content
stringlengths
5
1.05M
-- -- src/project/oven.lua -- Premake next-generation configuration "baking" API. -- Copyright (c) 2011-2012 Jason Perkins and the Premake project -- premake5.oven = premake5.oven or { } local oven = premake5.oven -- -- These configuration fields are used to support the baking process, and -- should not be included in any generated configuration objects. -- local nomerge = { blocks = true, keywords = true, project = true, removes = true, solution = true, } -- -- The main entry point: walks through all of the configuration data -- present in the project and "bakes" it into a single object, filtered -- by the provided set of terms. -- -- @param container -- The solution or project to query. -- @param basis -- A "parent" object containing an initial configuration. For example, -- if baking a project, this would be the containing solution. -- @param filterterms -- An optional list of filter terms. Only configuration blocks which -- match all of the terms in the list will be included in the result. -- @param filterfield -- An optional configuration field name. If set, that specific field, -- and only that field, will be baked and returned. -- @return -- A configuration object. -- function oven.bake(container, basis, filterTerms, filterField) local cfg = {} filterTerms = filterTerms or {} -- keyword/term tests are case-insensitive; convert all terms to lowercase local casedTerms = {} for key, value in pairs(filterTerms) do casedTerms[key] = value:lower() end -- If there is a basis object, start with that if basis then cfg = oven.bake(basis, nil, filterTerms, filterField) end -- Walk the blocks available in this container, and merge their values -- into my configuration-in-progress, if they pass the keyword filter container.blocks = container.blocks or {} for _, block in ipairs(container.blocks) do if oven.filter(block, casedTerms) then oven.merge(cfg, block, filterField) end end -- Store the filter terms in the configuration (i.e. buildcfg, platform) cfg.terms = casedTerms for key, value in pairs(filterTerms) do if type(key) ~= 'number' then cfg[key] = value end end return cfg end -- -- Retrieve the settings for a specific file within a configuration. Files -- have special rules: they only return those values from blocks that -- explicitly match the filename. -- -- @param cfg -- The base configuration to query. -- @param filename -- The name of the file to query. -- @return -- A file configuration object, which may be empty. -- function oven.bakefile(cfg, filename) local fcfg = { solution = cfg.solution, project = cfg.project, buildcfg = cfg.buildcfg, platform = iif(cfg.platform ~= '', cfg.platform, nil), } filename = { filename:lower() } for _, block in ipairs(cfg.solution.blocks) do if oven.filter(block, cfg.terms, filename) then oven.mergefile(fcfg, cfg, block) end end for _, block in ipairs(cfg.project.blocks) do if oven.filter(block, cfg.terms, filename) then oven.mergefile(fcfg, cfg, block) end end return fcfg end -- -- Scan an object for expandable tokens, and expand them, in place. -- -- @param cfg -- A configuration object. If the filecfg parameter is nil, the tokens in this -- object will be expanded; else this will be used as the cfg context object. -- @param scope -- The scope of fields which should be expanded, one of "project" or "config". -- @param filecfg -- A file configuration object, optional. If set, the tokens in this object -- will be expanded, and the cfg parameter will be used as a context variable. -- @param fieldname -- Optional; if set, only this field will be expanded. -- function oven.expandtokens(cfg, scope, filecfg, fieldname, delayedExpand) local tmr=timer.start('oven.expandTokens') -- File this under "too clever by half": I want path tokens (targetdir, etc.) -- to expand to relative paths, but it is easier to work with absolute paths -- everywhere else. So create a proxy object with an attached metatable that -- will translate any path fields from absolute to relative on the fly. local _cfg = cfg local context = _cfg._expandTokensContext if not context then local cfgproxy = {} setmetatable(cfgproxy, { __index = function(cfg, key) -- pass through access to non-Premake fields local field = premake.fields[key] if field and field.kind:contains("path") then return premake5.project.getrelative(_cfg.project, _cfg[key]) end return _cfg[key] end }) -- build a context for the tokens to use context = { sln = cfg.solution, prj = cfg.project, cfg = cfgproxy, file = filecfg, cache = {}, } _cfg._expandTokensContext = context end local function expand(target, field) local value = target[field] if not value then target[field] = nil elseif type(value) == "string" then target[field] = oven.expandvalue(value, context) else -- delayed expand, only expand if you need it. -- Makes a small perf increase, remove if it causes problems, eg. because you're unable to call ipairs(t) if false and delayedExpand then local proxyTable = {} local mt = {} mt.__index = function(self, key) expand(value, key) self[key] = value[key] return value[key] end setmetatable(proxyTable, mt) target[field] = proxyTable else for k,_ in pairs(value) do expand(value, k) end end end end local target = filecfg or cfg if fieldname then if target[fieldname] then expand(target, fieldname) end else for key, value in pairs(target) do -- to avoid unexpected errors or recursions, I only process -- Premake's own API fields, and only those marked for it local field = premake.fields[key] if field ~= nil and field.expandtokens and field.scope == scope then expand(target, key) end end end timer.stop(tmr) end function oven.expandvalue(value, context) -- early out makes the function 40% faster if not value:find('%{',1,true) then return value end local tmr=timer.start('oven.expandvalue') -- function to do the work of replacing a single token local expander = function(token) if context.cache[token] then return context.cache[token] end -- convert the token into a function to execute local func, err = loadstring("return " .. token) if not func then return nil, err end -- give the function access to the project objects setfenv(func, context) setmetatable(context, {__index = _G}) -- run it and return the result local err, result = pcall(func) if not err or not result then return nil, "Invalid token '" .. token .. "'" end if type(result) == 'table' then result = table.concat(result, ' ') end context.cache[token] = result return result end -- keep expanding tokens until they are all handled repeat value, count = string.gsub(value, "%%{(.-)}", function(token) local result, err = expander(token) if not result then local location = (context.sln.name or '') ..'/'..(context.prj.name or '')..'/'..(context.cfg.shortname or '') error(err .. ' in ' .. value..' at '..location, 0) end return result end) until count == 0 timer.stop(tmr) return value end -- -- -- Compare a list of block keywords against a set of filter terms. Keywords -- are Lua patterns applied to the block when it is specified in the script -- using the configuration() function. Filter terms include things such -- the current build configuration, target platform, or operating system. -- If all of the keywords on the block can be matched to a filter term, -- then the function returns true. If any keywords can NOT be matched, then -- the function returns false. -- -- @param block -- The block whose keywords are to be tested. -- @param anyOfThese -- If any of these values match the block keywords, the block is included. -- @param allOfThese -- Optional. If present, all terms present much exist in the block keywords -- for it to be returned in the results. Primarily used for filtering for -- file configurations, where only the file-specific values are desired. -- @returns -- True if the keywords and filter terms match, false otherwise. -- function oven.filter(block, anyOfThese, allOfThese) allOfThese = allOfThese or {} -- All of these terms must match at least one block keyword; -- negative matches (i.e. "not X") do not count for _, term in ipairs(allOfThese) do local matched = false for _, keyword in ipairs(block.keywords) do if oven.testkeyword(keyword, { term }, true) then matched = true break end end if not matched then return false end end -- All block keywords must match at least one term for _, keyword in ipairs(block.keywords) do if not oven.testkeyword(keyword, anyOfThese) and not oven.testkeyword(keyword, allOfThese) then return false end end return true end -- -- Compares a single keyword (Lua pattern) against a list of filter terms. -- The keyword must match at least one term to pass. -- -- @param keyword -- The keyword to test. -- @param terms -- The list of terms to filter against. -- @param skipNots -- Boolean flag indicating whether negative matches (i.e. "not X") -- should be considered (they are not for filename searches). -- @returns -- True if the keyword matches at least one filter term. -- function oven.testkeyword(keyword, terms, skipNots) if keyword:startswith("not ") then if skipNots then return false else return not oven.testkeyword(keyword:sub(5), terms) end end for _, pattern in ipairs(keyword:explode(" or ")) do for _, term in pairs(terms) do if term:match(pattern) == term then return true end end end return false end -- -- Merge from an individual block into the configuration object. -- -- @param cfg -- The configuration currently being built; will contain the new values. -- @param block -- The block containing the values to merge. -- @param filterField -- An optional configuration field name. If present, only this specific -- field will be merged. -- @return -- The configuration object, which is also modified in place. -- function oven.merge(cfg, block, filterField) if block.removes then oven.remove(cfg, block.removes, filterField) end if filterField then if block[filterField] then oven.mergefield(cfg, filterField, block[filterField]) end else local tmr = timer.start('oven.merge') for key, value in pairs(block) do if not nomerge[key] then oven.mergefield(cfg, key, value) end end -- remember the container object (solution, project, etc.) ptypeSet(cfg, ptype(block)) timer.stop(tmr) end return cfg end -- -- Merge from an individual block into a file configuration object, using the -- provided configuration as a basis. -- -- @param fcfg -- The file configuration being built; will contain the new values. -- @param cfg -- The base configuration. -- @param block -- The block containing the values to merge. -- function oven.mergefile(fcfg, cfg, block) for key, value in pairs(block) do -- if this is the first appearance of this field, start by -- copying over the basis values from the configuration if not fcfg[key] then oven.merge(fcfg, cfg, key) end -- then merge the file specific values over that oven.merge(fcfg, block, key) end end -- -- Merges a single field from a configuration block into a baked -- configuration object. -- @param cfg -- The configuration currently being built; will contain the new values. -- @param name -- The name of the field being merged. -- @param value -- The value of the field being merged. -- function oven.mergefield(cfg, name, value) if not value then return end local tmr = timer.start('oven.mergefield') local field = premake.fields[name] -- if this isn't a Premake field, then just copy if not field then cfg[name] = value else if field.isKeyedTable then oven.mergekeyvalue(cfg, name, field, value) else oven.mergevalue(cfg, name, field, value) end end timer.stop(tmr) end -- -- Merge a collection of key-values into an baked configuration. -- @param target -- The object receiving the values. -- @param fieldname -- The name of the field being set. -- @param fieldkind -- The data type of the field. -- @param values -- The object containing the key-value pairs. -- function oven.mergekeyvalue(target, fieldname, field, values) -- make sure I've got an object to hold the key-value pairs target[fieldname] = target[fieldname] or {} -- merge in the values for key, value in pairs(values) do oven.mergevalue(target[fieldname], key, field, value) end end -- -- Copy, and optionally merge, a value into a baked configuration. -- @param target -- The object receiving the values. -- @param fieldname -- The name of the field being set. -- @param fieldkind -- The data type of the field. -- @param values -- The object containing the key-value pairs. -- function oven.mergevalue(target, fieldname, field, value) -- list values get merged, others overwrite; note that if the -- values contain tokens they will be modified in the token -- expansion phase, so important to make copies of objects if field.kind == 'flaglist' or field.kind == 'usesconfig' then target[fieldname] = oven.mergekeyedtables(target[fieldname] or {}, value) elseif field.isList then target[fieldname] = oven.mergetables(target[fieldname] or {}, value) else target[fieldname] = table.deepcopy(value) end end -- -- Merge keyed tables -- function oven.mergekeyedtables(t, additions) for k,v in pairs(additions) do if type(k) == 'number' then table.insert(t, v) else t[k] = v end end return t end -- -- Merge a collection of key-values into an baked configuration. -- @param target -- The original value of the table being merged into. -- @param additions -- The new values to add to the table. -- @returns -- A table containing the merged results. -- function oven.mergetables(original, additions) if type(additions) == 'string' then additions = {additions} end for _, item in ipairs(additions) do -- if the item is already in the list, remove it. This allows a -- later configuration block (i.e. a project) to override the -- ordering of values from an earlier block (i.e. a solution). -- Could be a performance hit; have to wait and see. --[[if original[item] then local i = table.indexof(original, item) table.remove(original, i) end original[item] = item table.insert(original, item) ]] if not original[item] then original[item] = item table.insert(original, item) end end return original end -- -- Removes a set of values from a configuration. -- -- @param cfg -- The configuration from which to remove. -- @param removes -- The set of values to remove. Specified by a key-value -- list in the form: -- removes[key] = { list of values to remove } -- @param filterField -- An optional configuration field name. If present, only this specific -- field will be merged. -- function oven.remove(cfg, removes, filterField) if filterField then oven.removefromfield(cfg[filterField], removes[filterField]) else for fieldname, values in pairs(removes) do oven.removefromfield(cfg[fieldname], values) end end end function oven.removefromfield(field, removes) local tmr = timer.start('oven.removefromfield') if field and removes then for key, pattern in ipairs(removes) do local wpattern = path.wildcards(pattern) local found = true if pattern == wpattern then -- Quick check for the entry before searching for it found = field[pattern] end if found then wpattern = wpattern:lower() local i = 1 while i <= #field do local value = field[i]:lower() if value:match(wpattern) == value then field[ field[i] ] = nil table.remove(field, i) else i = i + 1 end end end end end timer.stop(tmr) end
--[[ usage example, keep components to 3 or less buildM.updater.bldg_from_components({bldg="assembling-machine-1", components={"iron-plate", "stone"}}) --]] --[[ All recipe changes are indexed and the current data.raw.recipe list is checked against it Any mods not loaded will not cause nil references this way --]] require("prototypes/recipes/mods-precomposites/base") require("prototypes/recipes/mods-components/base") require("prototypes/recipes/mods-buildings/base") require("prototypes/recipes/mods-precomposites/bobs") require("prototypes/recipes/mods-components/bobs") require("prototypes/recipes/mods-buildings/bobs") require("prototypes/recipes/mods-precomposites/angels") require("prototypes/recipes/mods-components/angels") require("prototypes/recipes/mods-buildings/angels") require("prototypes/recipes/mods-precomposites/omni") require("prototypes/recipes/mods-components/omni") require("prototypes/recipes/mods-buildings/omni") require("prototypes/recipes/mods-components/others") require("prototypes/recipes/mods-buildings/bio-industries") require("prototypes/recipes/mods-buildings/npbees") require("prototypes/recipes/mods-buildings/others")
-- Data lineDefs = { {"ESC", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "SYSRQ", "SCROLLLOCK", "PAUSE"}, {"GRAVE", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "MINUS", "EQUAL", "BACKSPACE", "INSERT", "HOME", "PAGEUP", "NUMLOCK", "KPSLASH", "KPASTERISK", "KPMINUS"}, {"TAB", "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "LBRACE", "RBRACE", "BACKSLASH", "DELETE", "END", "PAGEDOWN", "KP7", "KP8", "KP9", "KPPLUS"}, {"CAPSLOCK", "A", "S", "D", "F", "G", "H", "J", "K", "L", "SEMICOLON", "APOSTROPHE", "ENTER", 0, 0, 0, "KP4", "KP5", "KP6", "KPPLUS"}, {"LSHIFT", "102ND", "Z", "X", "C", "V", "B", "N", "M", "COMMA", "DOT", "SLASH", "RSHIFT", 0, "UP", 0, "KP1", "KP2", "KP3", "KPENTER"}, {"LCTRL", "LMETA", "LALT", "SPACE", "RALT", "RMETA", "FN", "COMPOSE", "RCTRL", "LEFT", "DOWN", "RIGHT", "KP0", "KPDOT", "KPENTER"} } color = tocolor(keyleds.config.color) or tocolor('white') transparent = tocolor(color.red, color.green, color.blue, 0) speed = tonumber(keyleds.config.speed) or 0.02 fadeTime = tonumber(keyleds.config.fadeTime) or 0.5 -- Lookup all names into key entries, eliminating unavailable ones function initLines() lines = {} for i, lineDef in ipairs(lineDefs) do local line = {} for j, def in ipairs(lineDef) do if def == 0 then line[#line + 1] = 0 else local key = keyleds.db:findName(def) if key then line[#line + 1] = key end end end lines[#lines + 1] = line end end -- Return (line, index) of given key within lines table function findKey(which) for i, line in ipairs(lines) do for j, key in ipairs(line) do if key == which then return line, j end end end return nil end -- Play animation for given key function react(kb, key) local line, idx = findKey(key) if not line then print("Key ", key, " not found") return end kb[line[idx]] = fade(fadeTime, color, transparent) for i = 1, math.max(idx - 1, #line - idx) do wait(speed) if idx - i > 0 and line[idx - i] ~= 0 then kb[line[idx - i]] = fade(fadeTime, color, transparent) end if idx + i <= #line and line[idx + i] ~= 0 then kb[line[idx + i]] = fade(fadeTime, color, transparent) end end end -- Weak table of active animations and their buffer, used for rendering buffers = {} setmetatable(buffers, { __mode = 'kv' }) -- Invoked whenever a key is pressed or release; trigger the animation function onKeyEvent(key, isPress) if not isPress then return end buffer = RenderTarget:new() local thread = thread(react, buffer, key) buffers[thread] = buffer end -- Blend all ongoing animations into the target function render(ms, target) for thread, buffer in pairs(buffers) do target:blend(buffer) end end -- Don't forget running init code initLines()
p.test=function() -- ts(res.kexiezhaoxin) -- first(); -- chenjiong.first(); return ; end
local StateType = require 'State.Type' local state = {} --[[ When called, tells the engine that it should go back the previous state. If the current state is the last state, it will exit. This all depends on how the State stack is built. This function is only available if `cfg.console.enabled` is true @class function ]] function state.prev() console:log("Returning to previous state") currentEvent:sendStateChange(StateType.Quit) currentEvent:stopPropgation() end --[[ When called, tells the engine that it should go reload the current state. This means that it will unload everything in the current state before creating it a new again. This function is only available if `cfg.console.enabled` is true @class function ]] function state.reload() console:log("Reloading current state") currentEvent:sendStateChange(StateType.Refresh) currentEvent:stopPropgation() end --[[ When called, tells the engine that it should do a full reload of the entire Window, GL context and current state. This means that the engine will basically be recreated. This function is only available if `cfg.console.enabled` is true @class function ]] function state.windowRefresh() console:log("Reloading window") currentEvent:sendStateChange(StateType.WinRefresh) currentEvent:stopPropgation() end function state.load(statetoLoad) console:log("Loading State") currentEvent:sendStateChange(statetoLoad) currentEvent:stopPropgation() end --[[ Reloads the Lua Engine by sending a state change to the Engine. If variables are defined by using the console and not stored in a file, they will be erased. This function is only available if `cfg.console.enabled` is true @class function ]] function state.luaReload() console:log("Reloading LUA engine and files") currentEvent:sendStateChange(StateType.LuaReload) currentEvent:stopPropgation() end return state
function backhome() local outTime = os.time() while (os.time()-outTime <= 60 ) do if active(app,10)then elseif UI('在地图中','在地图界面')then click(11,370) elseif UI_pic('回城','回城展开')then delay(2) UI_pic('回城','回城展开_技能',true) elseif UI_pic('回城','弹窗回城',true)then delay(1) click(983,499) delay(10) return true else click(20,20) end delay(1) end end function ad() local out_time = os.time() local doing = 0 local 发送ad = false while (os.time()-out_time < 60*3) do if active(app,10)then elseif UI('聊天','聊天界面')or UI('聊天','聊天界面2')then if UI_pic('聊天','聊天界面_世界频道',true)then elseif UI('聊天','聊天界面_世界频道_界面')then if UI_pic('聊天','聊天界面_世界频道_界面_发送',true)then delay(30) return true elseif UI_pic('聊天','聊天界面_世界频道_界面_发言位置')then click(x+200,y) input(values.ad) click(675,712) end end elseif UI('在地图中','在地图界面')then log("准备发广告") UI_pic('换服','聊天按钮',true) else if UI('返回','返回图标',true,1)then else other() end end mSleep(1000) end end if t == nil then t = {} end t['主界面']={ 0x9a5300, "-903|639|0x3f5cae,-1033|643|0x917444,-1148|649|0xd8ff22", 90, 0, 0, 1333, 749} t['主界面_对话框']={ 0xdcdc94, "18|27|0xb4bcb7,25|-15|0xbaba6f,-33|6|0x164850", 90, 126, 156, 230, 256} t['消息界面_竖']={ 0xe4d38a, "-2|-677|0xe4d38a,1201|-700|0x14494d,1220|3|0x14494d", 90, 6, 1, 1329, 746 } --多点找色 t['消息详情界面_竖']={ 0xe4d38a, "-8|-675|0x14494d,-11|-684|0xe4d38a,1199|-677|0x14494d", 90, 38, 8, 1320, 744 } --多点找色 t['消息详情界面_竖_反击']={ 0x453941, "-4|-26|0xdf5c05,6|-33|0x810d0d,-46|1|0x810d0d", 90, 148, 98, 1210, 644 } --多点找色 t['消息界面']={ 0xe4d38a, "9|-1|0x14494d,-12|701|0x14494d,8|702|0x14494d", 90, 4, 5, 492, 743 } --多点找色 t['消息界面ios11']={ 0xe4d38a, "9|0|0x14494d,-16|700|0x14494d,-3|701|0x14494d", 90, 1, 8, 573, 742 } --多点找色 t['消息详情界面']={ 0xe4d38a, "10|-2|0x14494d,1245|-4|0x14494d,1245|-12|0xe4d38a", 90, 0, 2, 1326, 99 } --多点找色 t['消息详情界面_反击']={ 0x453941, "-6|-9|0xeae2e9,-29|4|0xdf5c05,25|-4|0xdf5c05", 90,0, 0, 1333, 749} t['弹窗_前往']={ 0xe1993c, "-327|8|0x37bdbd,134|-450|0x861400", 90, 0, 0, 1333, 749 } --多点找色} t['弹窗_开战']={0x52d13f, "-335|-7|0x25a1bd,19|-127|0xf35150", 90, 337, 206, 1003, 520} t['弹窗_体力']={ 0x91f244, "-375|-24|0x29a9bd,-42|-27|0x49c744", 90, 344, 450, 995, 553 } --多点找色 t['返回箭头']={0xe6e189, "2|-11|0x326c7a,20|10|0xb1c8ca,3|20|0x389371", 90, 5, 1, 99, 69} t['返回箭头_世界地图']={ 0x154a51, "12|-10|0xf4f492,14|0|0x11444c", 90, 1237, 667, 1319, 743} t['返回箭头_世界地图_前往']={ 0x64de3d, "-7|17|0x97f346,-70|-20|0x45ad58,-3|-42|0x36a657,59|-16|0x28a942", 90, 276, 107, 1110, 689} t['返回箭头_世界地图_城市内']={ 0xeee9d4, "7|6|0xa88d50,-341|-1|0xeee9d4,-340|5|0x95732b", 90, 414, 4, 905, 100} t['返回箭头_世界地图_城市内_提示']={ 0xd9d8d1, "-21|-8|0xf9f3b9,16|-8|0xfbf4ba,0|10|0xd9d7d0", 90, 0, 0, 1333, 749 } --多点找色 t['返回箭头_世界地图_城市内_攻击']={ 0xf8f8f8, "33|-6|0x5d2320,-67|0|0x7e3f35,19|16|0xd48d2f", 90, 604, 397, 1026, 748} t['攻城界面'] ={ 0xe6e58d, "-10|6|0x28756f,-18|8|0xf1ed93,-35|10|0x2b7b73", 90, 4, 2, 100, 66} t['弹窗_公会_攻击']={ 0xdb7b40, "99|-32|0x9b1651,9|36|0xede03d,-78|-33|0xdc605e", 90, 0, 0, 1333, 749 } --多点找色 t['弹窗_公会_攻击_']={ 0xe7bf39, "-330|-1|0x39bfbd,-131|-400|0xc72906", 90, 241, 124, 1148, 690 } --多点找色 function attck() local TimeLine = os.time() local usedTime = 60*3 while (os.time()-TimeLine < usedTime) do if active(app,5)then elseif 在地图界面(false,clickMun,stayTime)then click(1170,699) --点击对话框 elseif d('消息界面_竖')then click(210,86) elseif d('消息详情界面_竖')then d('消息详情界面_竖_反击',true) elseif d('消息界面') or d('消息界面ios11')then click(483,124)--置顶对话 elseif d('消息详情界面')then if d('消息详情界面_反击',true)then --反击 moveTo(500,500,500,200,10) delay(1) end elseif d('返回箭头')then if d('返回箭头_世界地图')then if d('返回箭头_世界地图_前往',true)then delay(5) elseif d('返回箭头_世界地图_城市内')then delay(1) if d('返回箭头_世界地图_城市内_提示')then click(x,y+80) elseif d('返回箭头_世界地图_城市内_攻击',true)then click(868,471) -- 攻击的确认按钮 delay(3) else d('返回箭头',true) end end else d('返回箭头',true) end elseif d('攻城界面')then click(1142,66) --展开 预设位置={ {1045,162,0x0a0c04}, {1220,166,0x0d0e08}, {1041,257,0x060c07}, {1220,252,0xffffff}, {1048,350,0xdbdbdb}, {1227,348,0x090c08}, {1044,442,0x0d0f05}, {1222,443,0x111609}, {1044,536,0x0d0f05}, {1222,536,0x0d0f05}, } --多点比色 if values.yiji_arm == '10' then for i = 1,20 do click(1076-math.random(0,3)*117,662) d('弹窗_体力',true) end else click(预设位置[tonumber(values.yiji_arm)+1][1],预设位置[tonumber(values.yiji_arm)+1][2]) delay(3) end click(1212,661) --开始 战斗力位置 else if d('弹窗_前往',true,1)then delay(2) elseif d('弹窗_公会_攻击',true,1)then elseif d('弹窗_公会_攻击_',true,1)then elseif d('弹窗_开战',true,1)then delay(3) return true else if other() then click(97,33) end end end delay(1) end end t['在地图_技能']={ 0x6c6a49, "14|-19|0xf6f694,207|-3|0x22a695", 90, 1, 110, 263, 658 } --多点找色 t['弹窗_技能选择框']={ 0xfaf9ed, "-97|-4|0x051419,-92|-4|0xffffff,-179|-1|0xeae2b9", 90, 249, 95, 1099, 170 } --多点找色 t['弹窗_技能选择框_城门修复']={ 0x85f3f1, "29|-30|0x68ccd1,-9|3|0xe9fffa,-41|-31|0x68c9ce,-35|27|0x66d6dd,-31|23|0x2297c8", 90, 216, 168, 1106, 588 } --多点找色 t['弹窗_技能选择框_使用']={ 0x124d5d, "-75|26|0x3095c0,69|4|0x1470a6", 90, 845, 362, 1113, 591 } --多点找色 function fixWall() local TimeLine = os.time() local usedTime = 35*1 while (os.time()-TimeLine < usedTime) do if active(app,5)then elseif 在地图界面(false,clickMun,stayTime)then click(12,371) --点击左三角 elseif d('在地图_技能',true)then elseif d('弹窗_技能选择框')then if d('弹窗_技能选择框_使用',true)then delay(15) return '修复成功' elseif d('弹窗_技能选择框_城门修复',true)then else return '没有技能' end elseif d('返回箭头',true)then else click(20,20) other() end end return '修复超时or不要修复' end --[[ function change() out_time = os.time() doing = 0 while (os.time()-out_time < 90) do if active(app,10)then elseif UI('换服','在地图上')then if UI_pic('地图','王国',true)then elseif UI('地图','侧边',true,1)then end elseif UI('返回','返回图标',false,1)then -- if UI('返回','纯白之帆利萨姆')then if UI('返回','银翼之国桑多瑞')then if UI_pic('地图','移民按钮',true)then else return true end elseif UI('返回','转国界面')then click(1236,39) --纯白之帆利萨姆 click(1174,115) click(1184,446) else UI('返回','返回图标',true,1) end elseif UI('other','移民按钮',true,1)then doing = doing + 1 if doing == 2 then return true end else other() end mSleep(1000) end end --]] t['宝箱_军队']={ 0xebe78d, "-17|0|0x859365,16|0|0x828d60,51|6|0xffffff", 90, 5, 191, 213, 256 } --多点找色 t['返回_军队界面']={ 0xf8d72f, "-245|-2|0x3e4162,-482|-10|0xb4925a", 90, 536, 9, 1311, 97 } --多点找色 t['返回_军队界面_清空']={ 0x102036, "77|-2|0x112136,36|39|0x112137,-1|84|0x102037", 90, 132, 163, 234, 269 } --多点找色 t['返回_兵种详情']={ 0x29abbd, "837|-585|0x34a47f,-243|-469|0x98bcbd", 90, 60, 68, 1284, 743 } --遣散 t['返回_兵种详情2']={ 0x29adbe, "-16|27|0x4ccdb4,233|0|0x57d63c,235|22|0x9ff54b", 90, 115, 607, 555, 713 } --多点找色 t['弹窗_确定遣散']={ 0x41c6b6, "-414|-24|0x299dbe,104|-61|0x0a6a9d", 90, 279, 163, 1079, 555 } --多点找色 function dismiss() local TimeLine = os.time() local usedTime = 60*5 while (os.time()-TimeLine < usedTime) do if active(app,3)then elseif 在地图界面(false,clickMun,stayTime)then UI_pic('宝箱','未展开',true) elseif UI_pic('宝箱','展开',false)then d('宝箱_军队',true) elseif UI('返回','返回图标',false,1)then if d('返回_军队界面',false,1)then if d('返回_军队界面_清空')then return '清空军队' else click(180,275) end elseif d('返回_兵种详情',true)then elseif d('返回_兵种详情2',true)then else UI('返回','返回图标',true,1) end elseif d('弹窗_确定遣散')then moveTo(366,288,951,288,20) delay(0.5) d('弹窗_确定遣散',true) else if other()then click(20,20) end end mSleep(500) end return '解散超时' end t['城堡内_万神殿_指引']={ 0x7aff81, "-20|3|0x03f04a,13|14|0x204c57", 90, 473, 430, 558, 507 } t['返回_万神殿界面']={ 0xece8d4, "355|1|0xece8d4,710|-1|0xffffff,783|-14|0xf2f294", 90, 391, 3, 1317, 89 } t['返回_万神殿界面_激活']={ 0x2e6425, "7|17|0xcbe52a,68|-6|0x229b67", 90, 136, 683, 1197, 743 } t['返回_万神殿界面_向上']={ 0xffffff, "-3|25|0xf7f0bb,23|-31|0xd12f1e", 90, 1235, 265, 1331, 548 } --多点找色 t['返回_万神殿界面_神象']={ 0xb27f0c, "55|-31|0xd2311c", 90, 91, 91, 1229, 206 } t['返回_万神殿界面_向下']={ 0xffffff, "23|31|0xd3311d", 90, 1249, 444, 1330, 555 } t['返回_万神象']={ 0xffffff, "-13|-1|0x889cd4,7|-81|0x3c9a72", 90, 1130, 3, 1331, 160 } --多点找色 t['返回_万神象_可填']={ 0x239348, "-20|2|0x178957,-1|-23|0x9bcfcc,19|1|0x249448,3|22|0x82c437", 65, 234, 158, 1328, 545 } t['激活神象_确定']={ 0x72e73e, "-3|8|0x8df043,-125|-14|0xe7e2eb,6|-47|0x2b9c52", 90, 734, 597, 1020, 676 } --多点找色 t['弹窗_神石宝库']={ 0xdfffe5, "-320|41|0xffffff,-505|0|0x82a8a7", 90, 166, 61, 1174, 164 } --多点找色 t['弹窗_神石宝库_选择']={ 0x3bc2bb, "-76|11|0x299ece,74|-59|0x096ca4", 90, 205, 93, 1120, 645 } --多点找色 function Pantheon() local 计时 = os.time() local 超时 = 60*15 if setting[6] then while (os.time()-计时< 超时) do if active(app,3)then elseif UI('在地图中','在地图界面',true,2)then elseif UI('返回','返回图标',false,1)then if d('返回_城堡中') and d('返回_城堡中_右下角对话按钮')then if d('城堡内_万神殿_指引',true)then else return "神殿OK" end elseif d('返回_万神殿界面')then if d('返回_万神殿界面_激活',true)then elseif d('返回_万神殿界面_向上',true)then elseif d('返回_万神殿界面_神象',true)then elseif d('返回_万神殿界面_向下',true)then else UI('返回','返回图标',true,1) end elseif d('返回_万神象')then local LineTTTTime = os.time() local break_key = true while (os.time()-LineTTTTime<6) do if d('返回_万神象_可填',true)then break_key = false break end end if break_key then UI('返回','返回图标',true,1) end else UI('返回','返回图标',true,1) end elseif d('激活神象_确定',true)then elseif d('弹窗_神石宝库')then if d('弹窗_神石宝库_选择',true)then else click(278,217) end else if other()then click(20,20) end end mSleep(500) end return "神殿超时" end end
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by Administrator. --- DateTime: 2018/11/20 15:26 --- --- @class StageAbout --- @field world World --- @field area Area StageAbout = Object:extend() function StageAbout:new() self.area = Area(self) self.font = font self.main_canvas = love.graphics.newCanvas(gw,gh) gooi.newButton({group = "StageAbout",text = "返回菜单", x = gw*sw - 80,y = gh*sh - 40}) :center() :bg({1,1,1,0.1}) :onRelease( function() gotoRoom("StageMain","StageMain") gooi.setGroupEnabled("StageAbout",false) gooi.setGroupVisible("StageAbout",false) gooi.setGroupEnabled("StageMain",true) gooi.setGroupVisible("StageMain",true) end ) end function StageAbout:update(dt) if self.area then self.area:update(dt) end end function StageAbout:draw() love.graphics.setCanvas(self.main_canvas) love.graphics.clear() camera:attach(0,0,sw*gw,sh*gh) if self.area then self.area:draw() end camera:detach() --love.graphics.print("你挂了~~",gw/2,gh/2 - 50,0,sw,sh,math.floor(self.font:getWidth("打飞机")/2)) --local t0 = "得分:"..score[#score] --love.graphics.print(t0,gw/2,gh/2 - 100,0,sw,sh,math.floor(self.font:getWidth(t0)/2)) --local t1 = "按“空格”重新开始" --love.graphics.print(t1,gw/2,gh/2 + 40,0,sw,sh,math.floor(self.font:getWidth(t1)/2)) --local t2 = "左右箭头控制方向\n上下箭头控制速度" --love.graphics.print(t2,gw/2,gh/2 + 60,0,sw,sh,math.floor(self.font:getWidth(t2)/2)) --love.graphics.setFont(font,32) love.graphics.setCanvas() love.graphics.setColor(1,1,1,1) love.graphics.setBlendMode('alpha','premultiplied') love.graphics.draw(self.main_canvas,0,0,0,sw,sh) love.graphics.setBlendMode('alpha') gooi.draw("StageAbout") end function StageAbout:destroy() --if self.area then -- self.area:destroy() -- --self.area = nil --end end function StageAbout:finished() end return StageAbout
AddCSLuaFile() if CLIENT then SWEP.Author = "DarkRP Developers" SWEP.PrintName = "Glock" SWEP.Instructions = "Shoot with it" SWEP.Slot = 1 SWEP.SlotPos = 0 SWEP.IconLetter = "c" killicon.AddFont("weapon_glock2", "CSKillIcons", SWEP.IconLetter, Color(255, 80, 0, 255)) end SWEP.Base = "weapon_cs_base2" SWEP.Spawnable = true SWEP.AdminOnly = false SWEP.Category = "DarkRP (Weapon)" SWEP.ViewModel = "models/weapons/cstrike/c_pist_glock18.mdl" SWEP.WorldModel = "models/weapons/w_pist_glock18.mdl" SWEP.HoldType = "pistol" SWEP.Weight = 5 SWEP.AutoSwitchTo = false SWEP.AutoSwitchFrom = false SWEP.Primary.Sound = Sound("Weapon_Glock.Single") SWEP.Primary.Recoil = 2 SWEP.Primary.Unrecoil = 6 SWEP.Primary.Damage = 10 SWEP.Primary.NumShots = 1 SWEP.Primary.Cone = 0.05 SWEP.Primary.ClipSize = 20 SWEP.Primary.Delay = 0.06 SWEP.Primary.DefaultClip = 20 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "pistol" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" --Start of Firemode configuration SWEP.IronSightsPos = Vector(-5.77, -6.6, 2.7) SWEP.IronSightsAng = Vector(0.9, 0, 0)
return {function() -- wrap the function in a table to avoid detection by the TestRunnerPlugin local modules = game.ServerStorage.TestRunnerPlugin local NewTry = require(modules.Utils.NewTry) local progress = "startup" spawn(function() wait(); wait() if not progress then print("NewTry tests successful") elseif progress ~= -1 then error("NewTry tests got stuck at progress " .. tostring(progress)) end end) local function assertEquals(name, a, b) if a ~= b then progress = -1 error(("%s: %s ~= %s"):format(name, tostring(a), tostring(b)), 2) end end local function assertTableEquals(name, a, b) if a ~= b then for k, v in pairs(a) do if b[k] ~= v then progress = -1 error(("%s: key '%s': %s ~= %s"):format(name, tostring(k), tostring(v), tostring(b[k])), 2) end end for k, v in pairs(b) do if a[k] ~= v then progress = -1 error(("%s: key '%s': %s ~= %s"):format(name, tostring(k), tostring(a[k]), tostring(v)), 2) end end end end progress = 1 --[[try has this api: onSuccess(f) -- f will be called with whatever 'func' returned, if it succeeds within any timeout specified onError(f) -- will be called with the error msg; can use debug.traceback() since 'f' becomes the error handler in xpcall onTimeout(t, f) -- if 't' seconds go by, f() will be called onAsyncStartEnd(onStart, onEnd) -- onStart(co:coroutine) called if 'func' yields; onEnd(co:coroutine) called when the try completes/dies (before onSuccess/onTimeout trigger) finally(f) -- f() will be called after the try completes This will not run if any of the onSuccess/onTimeout/etc functions error or yield forever ]] local function return1() return 1 end local function no(try, ...) for _, name in ipairs({...}) do (try["on" .. name] or error("no try function on" .. name))(try, function() error("on" .. name .. " does not get called") end) end return try end local onSuccessCalled NewTry(function(try) no(try, "Error", "AsyncStartEnd") :onSuccess(function(a, b) onSuccessCalled = true assertEquals("onSuccess returns what the function returns", a, 1) assertEquals("onSuccess does not return more args", b, nil) end) :finally(function() assertEquals("finally called after onSuccess", onSuccessCalled, true) end) end, function() return 1 end) local onErrorCalled NewTry(function(try) no(try, "Success", "AsyncStartEnd") :onError(function(msg) onErrorCalled = true if not msg:find("HI") then progress = -1 print("onError did not receive error. msg:", msg) end end) :finally(function() assertEquals("finally called after onError", onErrorCalled, true) end) end, function() error("HI") end) assertEquals("onErrorCalled immediately", onErrorCalled, true) local test2 local p = 1 local function r(n, msg) assertEquals(msg, p, n) p += 1 if p == 7 and progress ~= -1 then progress = 2 test2() end end NewTry(function(try) no(try, "Error") :onAsyncStartEnd(function() r(1, "NewTry must call onAsyncStart") end, function() r(4, "onAsyncEnd called next") end) :onSuccess(function(a) r(5, "onSuccess after onAsyncEnd") assertEquals("onSuccess returns what the function returns", a, 1) end) :finally(function() r(6, "finally after onSuccess") assertEquals("finally called after onSuccess", onSuccessCalled, true) end) end, function() wait() r(3, "NewTry must return without yielding") return 1 end) r(2, "NewTry must return after onAsyncStart") function test2() local hitTimeout NewTry(function(try) no(try, "Error", "Success") :onTimeout(0.001, function() hitTimeout = true end) :finally(function() assertEquals("hit timeout before finally", hitTimeout, true) progress = nil end) end, wait, 1) end end}
local ffi = require("ffi"); local ffi_cdef = ffi.cdef local ffi_load = ffi.load local ffi_new = ffi.new local wirefilter = ffi_load "wirefilter"; ffi_cdef [[ typedef struct wirefilter_scheme wirefilter_scheme_t; typedef struct wirefilter_execution_context wirefilter_execution_context_t; typedef struct wirefilter_filter_ast wirefilter_filter_ast_t; typedef struct wirefilter_filter wirefilter_filter_t; typedef struct { const char *data; size_t length; } wirefilter_rust_allocated_str_t; typedef struct { const char *data; size_t length; } wirefilter_static_rust_allocated_str_t; typedef struct { const char *data; size_t length; } wirefilter_externally_allocated_str_t; typedef struct { const unsigned char *data; size_t length; } wirefilter_externally_allocated_byte_arr_t; typedef union { uint8_t success; struct { uint8_t _res1; wirefilter_rust_allocated_str_t msg; } err; struct { uint8_t _res2; wirefilter_filter_ast_t *ast; } ok; } wirefilter_parsing_result_t; typedef enum { WIREFILTER_TYPE_IP, WIREFILTER_TYPE_BYTES, WIREFILTER_TYPE_INT, WIREFILTER_TYPE_BOOL, } wirefilter_type_t; wirefilter_scheme_t *wirefilter_create_scheme(); void wirefilter_free_scheme(wirefilter_scheme_t *scheme); void wirefilter_add_type_field_to_scheme( wirefilter_scheme_t *scheme, wirefilter_externally_allocated_str_t name, wirefilter_type_t type ); wirefilter_parsing_result_t wirefilter_parse_filter( const wirefilter_scheme_t *scheme, wirefilter_externally_allocated_str_t input ); void wirefilter_free_parsing_result(wirefilter_parsing_result_t result); wirefilter_filter_t *wirefilter_compile_filter(wirefilter_filter_ast_t *ast); void wirefilter_free_compiled_filter(wirefilter_filter_t *filter); wirefilter_execution_context_t *wirefilter_create_execution_context( const wirefilter_scheme_t *scheme ); void wirefilter_free_execution_context( wirefilter_execution_context_t *exec_ctx ); void wirefilter_add_int_value_to_execution_context( wirefilter_execution_context_t *exec_ctx, wirefilter_externally_allocated_str_t name, int32_t value ); void wirefilter_add_bytes_value_to_execution_context( wirefilter_execution_context_t *exec_ctx, wirefilter_externally_allocated_str_t name, wirefilter_externally_allocated_byte_arr_t value ); void wirefilter_add_ipv6_value_to_execution_context( wirefilter_execution_context_t *exec_ctx, wirefilter_externally_allocated_str_t name, uint8_t value[16] ); void wirefilter_add_ipv4_value_to_execution_context( wirefilter_execution_context_t *exec_ctx, wirefilter_externally_allocated_str_t name, uint8_t value[4] ); void wirefilter_add_bool_value_to_execution_context( wirefilter_execution_context_t *exec_ctx, wirefilter_externally_allocated_str_t name, bool value ); bool wirefilter_match( const wirefilter_filter_t *filter, const wirefilter_execution_context_t *exec_ctx ); bool wirefilter_filter_uses( const wirefilter_filter_ast_t *ast, wirefilter_externally_allocated_str_t field_name ); uint64_t wirefilter_get_filter_hash(const wirefilter_filter_ast_t *ast); wirefilter_rust_allocated_str_t wirefilter_serialize_filter_to_json( const wirefilter_filter_ast_t *ast ); void wirefilter_free_string(wirefilter_rust_allocated_str_t str); wirefilter_static_rust_allocated_str_t wirefilter_get_version(); ]] local _M = { _VERSION = '1.0.0', types = { BYTES = ffi.C.WIREFILTER_TYPE_BYTES, IP = ffi.C.WIREFILTER_TYPE_IP, BOOL = ffi.C.WIREFILTER_TYPE_BOOL, INT = ffi.C.WIREFILTER_TYPE_INT } } local mt = { __index = _M } function _M:new(args) local args = args or {} local fields = args.fields or {} local filter = args.filter or "" local fields_map = {} local scheme, err = self:init_scheme(fields, fields_map) if (scheme == nil) then return nil, err end local filter, err = self:create_filter(scheme, args.filter) if (filter == nil) then return nil, err end local self = { scheme = scheme, filter = filter, fields_map = fields_map } return setmetatable(self, mt) end function _M:create_execution_context(scheme) local context = ffi_new("wirefilter_execution_context_t*") local context = wirefilter.wirefilter_create_execution_context(scheme) if (context == nil) then return nil, "could not create execution context" end return context end function _M:match(filter, context) local match_result = wirefilter.wirefilter_match(filter, context) return match_result end function _M:free_execution_context(context) wirefilter.wirefilter_free_execution_context(context) end function _M:exec(values) local context, err = self:create_execution_context(self.scheme) if (context == nil) then return nil, err end for name, value in pairs(values) do local result, err = self:add_value_to_execution_context(context, { name = name, value = value }) if not result then return nil, err end end local match_result = self:match(self.filter, context) self:free_execution_context(context) return match_result end function _M:get_field(value) local field = self.fields_map[value.name] if (field == nil) then return nil, "field does not exist" end return field end function _M:add_value_to_execution_context(context, value) local field, err = self:get_field(value) if (field == nil) then return false, err end if (field == self.types.BYTES) then wirefilter.wirefilter_add_bytes_value_to_execution_context(context, self:wirefilter_string(value.name), self:wirefilter_byte(value.value)) elseif (field == self.types.BOOL) then wirefilter.wirefilter_add_bool_value_to_execution_context(context, self:wirefilter_string(value.name), value.value) elseif (field == self.types.INT) then local int_value, err = self:wirefilter_int(value.value) if (int_value == nil) then return false, err end wirefilter.wirefilter_add_int_value_to_execution_context(context, self:wirefilter_string(value.name), int_value) elseif (field == self.types.IP) then local ip_value, err = self:wirefilter_ip(value.value) if (ip_value == nil) then return false, err end wirefilter.wirefilter_add_ipv4_value_to_execution_context(context, self:wirefilter_string(value.name), ip_value) end return true end function _M:clear(filter, scheme) self:free_compiled_filter(filter) self:free_scheme(scheme) end function _M:free_compiled_filter(filter) wirefilter.wirefilter_free_compiled_filter(filter); end function _M:free_scheme(scheme) wirefilter.wirefilter_free_scheme(scheme); end function _M:create_filter(scheme, filter_string) local result = ffi_new("wirefilter_parsing_result_t") local result = wirefilter.wirefilter_parse_filter(scheme, self:wirefilter_string(filter_string)) if (result.success ~= 1) then return nil, "could not parse filter" end if (result.ok.ast == nil) then return nil, "could not parse filter" end local filter = ffi_new("wirefilter_filter_t*") local filter = wirefilter.wirefilter_compile_filter(result.ok.ast) if (filter == nil) then return nil, "could not compile filter" end return filter end function _M:init_scheme(fields, fields_map) local scheme, err = self:create_scheme() if (scheme == nil) then return nil, err end for name, type in pairs(fields) do self:add_type_field_to_scheme(scheme, fields_map, name, type) end return scheme end function _M:create_scheme() local scheme = ffi_new("wirefilter_scheme_t*") local scheme = wirefilter.wirefilter_create_scheme() if (scheme == nil) then return nil, "could not create scheme" end return scheme end function _M:add_type_field_to_scheme(scheme, fields_map, name, type) wirefilter.wirefilter_add_type_field_to_scheme(scheme, self:wirefilter_string(name), type) fields_map[name] = type end function _M:wirefilter_int(value) local value = tonumber(value) if (value == nil) then return nil, "number is not valid" end return value end function _M:wirefilter_string(value) local value = tostring(value) local str = ffi_new("wirefilter_externally_allocated_str_t", { data = value, length = string.len(value) }) return str end function _M:wirefilter_byte(value) local value = tostring(value) local bytes = ffi_new("wirefilter_externally_allocated_byte_arr_t", { data = value, length = string.len(value) }) return bytes end function _M:wirefilter_ip(value) local ip_tab = {} for s in string.gmatch(value, "[^.]+") do local ip_seg = tonumber(s) if (ip_seg ~= nil and ip_seg >= 0 and ip_seg <= 255) then table.insert(ip_tab, ip_seg) end end if (#ip_tab ~= 4) then return nil, "invalid ipv4 address" end local ip = ffi_new("uint8_t[4]", ip_tab) return ip end return _M
-- Crimson premake file group "ex" include "ex/tinyxml2" include "ex/glfw" include "ex/physfs" include "ex/glad" include "ex/imgui" include "ex/angelscript" group "" crimsonSystemDeps = {} if os.host() == "linux" then crimsonSystemDeps = { "pthread", "dl", "X11", "GL", } elseif os.host() == "windows" then crimsonSystemDeps = { "opengl32" } end crimsonExternalDeps = { crimsonSystemDeps, "glad", "physfs", "glfw", "tinyxml2", "glad", "imgui", "angelscript" } project "crimson" kind "StaticLib" staticruntime "on" language "C++" cppdialect "C++11" targetdir "../bin" includedirs { "src", "ex/glfw/include", "ex/glad/include", "ex/imgui/include", "ex/physfs/src", "ex/tinyxml2/src", "ex/angelscript/angelscript/include", "ex/angelscript/angelscript/add_on", } links { crimsonExternalDeps, } files { "include/**.h", "src/**.h", "src/**.cpp", "src/**.c" } defines { "GLFW_INCLUDE_NONE", "CR_STATIC" } filter "system:windows" defines { "CR_LIBRARY_EXPORT" } filter "configurations:debug" defines { "DEBUG" } symbols "on" filter "configurations:release" defines { "RELEASE" } optimize "on"
--[[ Copyright (c) 2013 David Young dayoung@goliathdesigns.com This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ]] require "AgentCommunications" require "AgentUtilities" require "AnimationStateMachine" Soldier = {}; -- Height in meters. Soldier.Height = {}; Soldier.Height.Crouch = 1.3; Soldier.Height.Stand = 1.6; -- Speed in meters per second. Soldier.Speed = {}; Soldier.Speed.Crouch = 1; Soldier.Speed.Stand = 3; -- All possible soldier animation state machine states. Soldier.SoldierStates = { CROUCH_DEAD = "crouch_dead", CROUCH_FIRE = "crouch_fire", CROUCH_FORWARD = "crouch_forward", CROUCH_IDLE_AIM = "crouch_idle_aim", STAND_DEAD = "dead", STAND_DEAD_HEADSHOT = "dead_headshot", STAND_FALL_DEAD = "fall_dead", STAND_FALL_IDLE = "fall_idle", STAND_FIRE = "fire", STAND_IDLE_AIM = "idle_aim", STAND_JUMP_LAND = "jump_land", STAND_JUMP_UP = "jump_up", STAND_MELEE = "melee", STAND_RELOAD = "reload", STAND_RUN_BACKWARD = "run_backward", STAND_RUN_FORWARD = "run_forward", STAND_SMG_TRANSFORM = "smg_transform", STAND_SNIPER_TRANSFORM = "sniper_transform" }; -- All possible weapon animation state machine states. Soldier.WeaponStates = { SMG_IDLE = "smg_idle", SMG_TRANSFORM = "smg_transform", SNIPER_IDLE = "sniper_idle", SNIPER_RELOAD = "sniper_reload", SNIPER_TRANSFORM = "sniper_transform" }; -- Accumulates acceleration to smooth out jerks in movement. local _agentAccumulators = {}; -- Handles the removal of particles. local _impactParticles = {}; local function _SendImpactEvent(sandbox, hitPosition) local event = { position = hitPosition }; AgentCommunications_SendMessage( sandbox, AgentCommunications.EventType.BulletImpact, event); end local function _SendShootEvent(sandbox, shootPosition) local event = { position = shootPosition }; AgentCommunications_SendMessage( sandbox, AgentCommunications.EventType.BulletShot, event); end local function _ParticleImpact(sandbox, collision) Sandbox.RemoveObject(sandbox, collision.objectA); local particleImpact = Core.CreateParticle(sandbox, "BulletImpact"); Core.SetPosition(particleImpact, collision.pointA); Core.SetParticleDirection(particleImpact, collision.normalOnB); table.insert(_impactParticles, { particle = particleImpact, ttl = 2.0 } ); if (Agent.IsAgent(collision.objectB)) then Agent.SetHealth(collision.objectB, Agent.GetHealth(collision.objectB) - 5); end _SendImpactEvent(sandbox, collision.pointA); end local function _ShootBullet(sandbox, position, rotation) local forward = Vector.Rotate(Vector.new(1, 0, 0), rotation); local up = Vector.Rotate(Vector.new(0, 1, 0), rotation); local left = Vector.Rotate(Vector.new(0, 0, -1), rotation); local bullet = Sandbox.CreatePhysicsCapsule(sandbox, 0.3, 0.01); Core.SetMass(bullet, 0.1); Core.SetPosition(bullet, position + forward * 0.2); Core.SetAxis(bullet, left, -forward, up); Core.SetGravity(bullet, Vector.new(0, -0.01, 0)); local bulletParticle = Core.CreateParticle(bullet, "Bullet"); Core.SetRotation(bulletParticle, Vector.new(-90, 0, 0)); Core.ApplyImpulse(bullet, forward * 750); Sandbox.AddCollisionCallback(sandbox, bullet, _ParticleImpact); _SendShootEvent(sandbox, position); end function Soldier_ApplySteering(agent, steeringForces, deltaTimeInSeconds) local agentId = agent:GetId(); if (_agentAccumulators[agentId] == nil) then _agentAccumulators[agentId] = Vector.new(); end AgentUtilities_ApplySteeringForce2( agent, steeringForces, _agentAccumulators[agentId], deltaTimeInSeconds); AgentUtilities_ClampHorizontalSpeed(agent); end function Soldier_AttachWeapon(soldier, weapon) Animation.AttachToBone( soldier, "b_RightHand", weapon, Vector.new(0.04, 0.05, -0.01), Vector.new(98.0, 97.0, 0)); end function Soldier_CalculateSlowSteering(agent, deltaTimeInSeconds) local avoidForce = agent:ForceToAvoidAgents(0.5); local avoidObjectForce = agent:ForceToAvoidObjects(0.5); local followForce = agent:ForceToFollowPath(0.5); local stayForce = agent:ForceToStayOnPath(0.5); local totalForces = Vector.Normalize(followForce) + Vector.Normalize(stayForce) * 0.2 + avoidForce * 1 + avoidObjectForce * 1; local targetSpeed = agent:GetMaxSpeed(); if (agent:GetSpeed() < targetSpeed) then local speedForce = agent:ForceToTargetSpeed(targetSpeed); totalForces = totalForces + speedForce * 5; end return totalForces; end function Soldier_CalculateSteering(agent, deltaTimeInSeconds) local avoidForce = agent:ForceToAvoidAgents(0.5); local avoidObjectForce = agent:ForceToAvoidObjects(0.5); local followForce = agent:ForceToFollowPath(0.5); local stayForce = agent:ForceToStayOnPath(0.5); local totalForces = followForce * 1.5 + stayForce * 0.4 + avoidForce * 1 + avoidObjectForce * 2; totalForces.y = 0; local targetSpeed = agent:GetMaxSpeed(); if (agent:GetSpeed() < targetSpeed) then local speedForce = agent:ForceToTargetSpeed(targetSpeed); totalForces = totalForces + speedForce * 7; end return totalForces; end function Soldier_CreateLightSoldier(agent) local soldier = Core.CreateMesh( agent, "models/futuristic_soldier/futuristic_soldier_anim.mesh"); -- Offset the soldier mesh since the origin of the mesh is at the feet -- while the origin of the agent is at the center. local height = agent:GetHeight(); Core.SetPosition(soldier, Vector.new(0, -height * 0.5, 0)); return soldier; end function Soldier_CreateSoldier(agent) local soldier = Core.CreateMesh( agent, "models/futuristic_soldier/futuristic_soldier_dark_anim.mesh"); -- Offset the soldier mesh since the origin of the mesh is at the feet -- while the origin of the agent is at the center. local height = agent:GetHeight(); Core.SetPosition(soldier, Vector.new(0, -height * 0.5, 0)); return soldier; end function Soldier_CreateSoldierStateMachine(soldier) local soldierAsm = AnimationStateMachine.new(); local crouchIdleAim = Animation.GetAnimation(soldier, "crouch_idle_aim"); local crouchIdleAimLength = Animation.GetLength(crouchIdleAim); local crouchForward = Animation.GetAnimation(soldier, "crouch_forward_aim"); local crouchForwardLength = Animation.GetLength(crouchForward); local idleAim = Animation.GetAnimation(soldier, "stand_idle_aim"); local idleAimLength = Animation.GetLength(idleAim); local runForward = Animation.GetAnimation(soldier, "stand_run_forward_aim"); local runForwardLength = Animation.GetLength(runForward); soldierAsm:AddState("idle_aim", Animation.GetAnimation(soldier, "stand_idle_aim"), true); soldierAsm:AddState("crouch_idle_aim", Animation.GetAnimation(soldier, "crouch_idle_aim"), true); soldierAsm:AddState("crouch_dead", Animation.GetAnimation(soldier, "stand_dead_2"), nil, 0.8); soldierAsm:AddState("crouch_fire", Animation.GetAnimation(soldier, "crouch_fire_one_shot"), true); soldierAsm:AddState("crouch_forward", Animation.GetAnimation(soldier, "crouch_forward_aim"), true); soldierAsm:AddState("dead", Animation.GetAnimation(soldier, "stand_dead_2")); soldierAsm:AddState("dead_headshot", Animation.GetAnimation(soldier, "stand_dead_headshot")); soldierAsm:AddState("fall_dead", Animation.GetAnimation(soldier, "stand_dead_2")); soldierAsm:AddState("fall_idle", Animation.GetAnimation(soldier, "stand_idle_aim"), true); soldierAsm:AddState("fire", Animation.GetAnimation(soldier, "stand_fire_one_shot"), true); soldierAsm:AddState("jump_land", Animation.GetAnimation(soldier, "stand_jump_land")); soldierAsm:AddState("jump_up", Animation.GetAnimation(soldier, "stand_jump_up")); soldierAsm:AddState("melee", Animation.GetAnimation(soldier, "stand_melee_1_with_weapon")); soldierAsm:AddState("reload", Animation.GetAnimation(soldier, "stand_reload")); soldierAsm:AddState("run_backward", Animation.GetAnimation(soldier, "stand_run_backward_aim"), true); soldierAsm:AddState("run_forward", Animation.GetAnimation(soldier, "stand_run_forward_aim"), true); soldierAsm:AddState("smg_transform", Animation.GetAnimation(soldier, "stand_smg_transform")); soldierAsm:AddState("sniper_transform", Animation.GetAnimation(soldier, "stand_sniper_transform")); soldierAsm:AddTransition("idle_aim", "crouch_idle_aim", idleAimLength, 0.3); soldierAsm:AddTransition("idle_aim", "dead", idleAimLength, 0.1); soldierAsm:AddTransition("idle_aim", "fall_dead", idleAimLength, 0.15, 1.0); soldierAsm:AddTransition("idle_aim", "dead_headshot", idleAimLength, 0.2); soldierAsm:AddTransition("idle_aim", "fire", idleAimLength, 0.1); soldierAsm:AddTransition("idle_aim", "melee", idleAimLength, 0.2); soldierAsm:AddTransition("idle_aim", "reload", idleAimLength, 0.2); soldierAsm:AddTransition("idle_aim", "run_backward", idleAimLength, 0.2); soldierAsm:AddTransition("idle_aim", "run_forward", idleAimLength, 0.5); soldierAsm:AddTransition("idle_aim", "smg_transform", idleAimLength, 0.2); soldierAsm:AddTransition("idle_aim", "sniper_transform", idleAimLength, 0.2); soldierAsm:AddTransition("crouch_idle_aim", "idle_aim", crouchIdleAimLength, 0.3); soldierAsm:AddTransition("crouch_idle_aim", "crouch_dead", crouchIdleAimLength, 0.2, 0.5); soldierAsm:AddTransition("crouch_idle_aim", "crouch_fire", crouchIdleAimLength, 0.1); soldierAsm:AddTransition("crouch_idle_aim", "crouch_forward", crouchIdleAimLength, 0.5); soldierAsm:AddTransition("crouch_idle_aim", "fire", crouchIdleAimLength, 0.5); soldierAsm:AddTransition("crouch_idle_aim", "reload", crouchIdleAimLength, 0.3); soldierAsm:AddTransition("crouch_idle_aim", "run_forward", crouchIdleAimLength, 0.5); soldierAsm:AddTransition("crouch_fire", "crouch_dead", 0.2, 0.2, 0.5); soldierAsm:AddTransition("crouch_fire", "crouch_forward", 0.5, 0.5); soldierAsm:AddTransition("crouch_fire", "crouch_idle_aim", 0.1, 0.1); soldierAsm:AddTransition("crouch_fire", "fire", 0.3, 0.3); soldierAsm:AddTransition("crouch_fire", "idle_aim", 0.3, 0.3); soldierAsm:AddTransition("crouch_fire", "reload", 0.3, 0.3); soldierAsm:AddTransition("crouch_fire", "run_forward", 0.5, 0.5); soldierAsm:AddTransition("crouch_forward", "crouch_dead", crouchForwardLength, 0.2, 0.5); soldierAsm:AddTransition("crouch_forward", "crouch_fire", crouchForwardLength, 0.2); soldierAsm:AddTransition("crouch_forward", "crouch_idle_aim", crouchForwardLength, 0.2); soldierAsm:AddTransition("crouch_forward", "fall_idle", crouchForwardLength, 0.2); soldierAsm:AddTransition("crouch_forward", "fire", crouchForwardLength, 0.5); soldierAsm:AddTransition("crouch_forward", "idle_aim", crouchForwardLength, 0.5); soldierAsm:AddTransition("crouch_forward", "reload", crouchForwardLength, 0.5); soldierAsm:AddTransition("crouch_forward", "run_forward", crouchForwardLength, 0.4); soldierAsm:AddTransition("run_forward", "crouch_fire", runForwardLength, 0.5); soldierAsm:AddTransition("run_forward", "crouch_forward", runForwardLength, 0.2); soldierAsm:AddTransition("run_forward", "crouch_idle_aim", runForwardLength, 0.5); soldierAsm:AddTransition("run_forward", "dead", runForwardLength, 0.2); soldierAsm:AddTransition("run_forward", "fall_idle", runForwardLength, 0.1); soldierAsm:AddTransition("run_forward", "fire", runForwardLength, 0.5); soldierAsm:AddTransition("run_forward", "idle_aim", runForwardLength, 0.5); soldierAsm:AddTransition("run_forward", "reload", runForwardLength, 0.5); soldierAsm:AddTransition("fall_idle", "fall_dead", idleAimLength, 0.15, 1.0); soldierAsm:AddTransition("fire", "idle_aim", 0.1, 0.1); soldierAsm:AddTransition("fire", "reload", 0.1, 0.1); soldierAsm:AddTransition("fire", "run_forward", 0.5, 0.5); soldierAsm:AddTransition("fire", "run_backward", 0.5, 0.5); soldierAsm:AddTransition("fire", "crouch_idle_aim", 0.5, 0.5); soldierAsm:AddTransition("fire", "crouch_fire", 0.3, 0.3); soldierAsm:AddTransition("fire", "crouch_forward", 0.5, 0.5); soldierAsm:AddTransition("melee", "idle_aim", 0.2, 0.2); soldierAsm:AddTransition("reload", "idle_aim", 0.2, 0.2); soldierAsm:AddTransition("run_backward", "idle_aim", 0.2, 0.2); soldierAsm:AddTransition("smg_transform", "idle_aim", 0.2, 0.2); soldierAsm:AddTransition("sniper_transform", "idle_aim", 0.2, 0.2); soldierAsm:RequestState("idle_aim"); return soldierAsm; end function Soldier_CreateWeapon(agent) local weapon = Core.CreateMesh( agent, "models/futuristic_soldier/soldier_weapon.mesh"); return weapon; end function Soldier_CreateWeaponStateMachine(weapon) local weaponAsm = AnimationStateMachine.new(); local sniperIdle = Animation.GetAnimation(weapon, "sniper_idle"); local smgIdle = Animation.GetAnimation(weapon, "smg_idle"); weaponAsm:AddState("smg_idle", Animation.GetAnimation(weapon, "smg_idle"), true); weaponAsm:AddState("smg_transform", Animation.GetAnimation(weapon, "smg_transform")); weaponAsm:AddState("sniper_idle", sniperIdle, true); weaponAsm:AddState("sniper_reload", Animation.GetAnimation(weapon, "sniper_reload")); weaponAsm:AddState("sniper_transform", Animation.GetAnimation(weapon, "sniper_transform")); weaponAsm:AddTransition("sniper_idle", "sniper_reload", Animation.GetLength(sniperIdle), 0.2); weaponAsm:AddTransition("sniper_idle", "sniper_transform", Animation.GetLength(sniperIdle), 0.2); weaponAsm:AddTransition("sniper_reload", "sniper_idle", 0.2, 0.2); weaponAsm:AddTransition("sniper_transform", "sniper_idle", 0.2, 0.2); weaponAsm:AddTransition("smg_idle", "smg_transform", Animation.GetLength(smgIdle), 0.2); weaponAsm:AddTransition("smg_transform", "smg_idle", 0.2, 0.2); weaponAsm:RequestState("sniper_idle"); return weaponAsm; end function Soldier_PathToRandomPoint(agent) local sandbox = agent:GetSandbox(); local endPoint = Sandbox.RandomPoint(sandbox, "default"); local path = Sandbox.FindPath(sandbox, "default", agent:GetPosition(), endPoint); while #path == 0 do endPoint = Sandbox.RandomPoint(sandbox, "default"); path = Sandbox.FindPath(sandbox, "default", agent:GetPosition(), endPoint); end return path; end function Soldier_IsFalling(agent) -- Agents must fall for at least half a second to be considered falling. return (agent:GetVelocity().y < (-9.8 * 0.5)); end function Soldier_IsMoving(agent) return Vector.LengthSquared(agent:GetVelocity()) > 2; end function Soldier_OnGround(agent) return (agent:GetVelocity().y > (-9.8 * 0.1)); end function Soldier_SetHeight(agent, soldierMesh, newHeight) assert(type(agent) == "userdata"); assert(type(soldierMesh) == "userdata"); assert(type(newHeight) == "number"); local height = agent:GetHeight(); Core.SetPosition(soldierMesh, Vector.new(0, -newHeight/2, 0)); agent:SetPosition( agent:GetPosition() - Vector.new(0, (height - newHeight)/2, 0)); agent:SetHeight(newHeight); end function Soldier_SetPath(agent, path, cyclic) agent:SetPath(path, cyclic); -- Find a future position on the path based on the closest point on the path. local nearest = Agent.GetNearestPointOnPath(agent, agent:GetPosition()); local distance = Agent.GetDistanceAlongPath(agent, nearest); local pointOnPath = Agent.GetPointOnPath(agent, distance + 2); local forward = pointOnPath - agent:GetPosition(); forward.y = 0; -- Orient the soldier directly toward the path if the beginning -- of the path is great than 90 degrees from the soldier's current -- forward vector. -- Typically you would want to play a turn animation here so soldiers won't -- steer off the environment to their death. Since the soldier doesn't -- have turn animations we directly set the agent's forward. if ( Vector.DotProduct(forward, agent:GetForward()) < 0 ) then agent:SetVelocity(forward * agent:GetSpeed()); agent:SetForward(forward); end end function Soldier_SlowMovement(agent, deltaTimeInMillis, rate) rate = rate or 1; local horizontalVelocity = agent:GetVelocity(); local yMovement = horizontalVelocity.y; horizontalVelocity.y = 0; horizontalVelocity = horizontalVelocity * 0.91 * (1 / rate); horizontalVelocity.y = yMovement; agent:SetVelocity(horizontalVelocity); end function Soldier_Shoot(stateName, callbackData) assert(callbackData.agent); assert(callbackData.soldier); local agent = callbackData.agent; local sandbox = agent:GetSandbox(); local soldier = callbackData.soldier; local position = Animation.GetBonePosition(soldier, "b_muzzle"); local rotation = Animation.GetBoneRotation(soldier, "b_muzzle"); _ShootBullet(sandbox, position, rotation); end function Soldier_Update(agent, deltaTimeInMillis) -- Clean up particles after their Time to Live has passed if (_impactParticles and #_impactParticles > 0) then local index = 1; while (index <= #_impactParticles) do local impactParticle = _impactParticles[index]; impactParticle.ttl = impactParticle.ttl - deltaTimeInMillis / 1000; if (impactParticle.ttl <= 0) then table.remove(_impactParticles, index); Core.Remove(impactParticle.particle); else index = index + 1; end end end end
myyydrilreturnScreenPlay = ScreenPlay:new { numberOfActs = 1, } registerScreenPlay("myyydrilreturnScreenPlay", true) function myyydrilreturnScreenPlay:start() if (isZoneEnabled("kashyyyk")) then self:spawnMobiles() self:spawnSceneObjects() end end function myyydrilreturnScreenPlay:spawnSceneObjects() end function myyydrilreturnScreenPlay:spawnMobiles() local pCollector1 = spawnMobile("kashyyyk", "teleporter", 120, -100.1, -57.8, 31, -113, 6296409) local collector1 = LuaCreatureObject(pCollector1) collector1:setOptionsBitmask(264) collector1:setCustomObjectName("\\#FF0000Return to Cave Entrance") createObserver(OBJECTRADIALUSED, "myyydrilreturnScreenPlay", "returnmyyydril", pCollector1) if (pCollecter1~= nil) then return end end function myyydrilreturnScreenPlay:returnmyyydril(pCollector, pPlayer)--current local player = LuaSceneObject(pPlayer) player:switchZone("kashyyyk", -1742, 51.4, 1824.5, 0) return 0 end
object_static_worldbuilding_camping_eqp_camping_chair_s3 = object_static_worldbuilding_camping_shared_eqp_camping_chair_s3:new { } ObjectTemplates:addTemplate(object_static_worldbuilding_camping_eqp_camping_chair_s3, "object/static/worldbuilding/camping/eqp_camping_chair_s3.iff")
local AL = _G.AtlasLoot.GetLocales("esES") if not AL then return end -- These localization strings are translated on WoWAce: https://www.wowace.com/projects/atlasloot-enhanced/localization -- Options AL["A window with possible loot is shown if a Bonus Roll is started."] = "Si se inicia una tirada de dados, se muestra una ventana con el posible botín." AL["Always show item comparison."] = "Mostrar siempre la comparativa de objetos." AL["Always show quick preview."] = "Mostrar siempre la previsualización rápida." AL["AtlasLoot Options"] = "Opciones del AtlasLoot" AL["Auto select current instance's loot tables."] = "Seleccionar automáticamente las tablas de botín para la instancia actual." AL["Background"] = "Fondo" AL["Background color/alpha"] = "Color/transparencia del fondo" AL["Content"] = "Contenido" AL["Content bottom bar"] = "Barra inferior de contenido" AL["Content top bar"] = "Barra superior de contenido" AL["Content top/bottom bar"] = "Barra superior/inferior de contenido" AL["Font"] = "Fuente" AL["Font color/alpha"] = "Color/transparencia de la fuente" AL["Font size"] = "Tamaño de fuente" AL["Lock minimap button around minimap."] = "Bloquear el botón del minimapa alrededor del minimapa." AL["Lock minimap button."] = "Bloquear botón del minimapa." AL["Main Window"] = "Ventana principal" AL["Minimap Button"] = "Botón del minimapa" AL["Model"] = "Modelo" AL["Preview"] = "Vista previa" AL["Quick Loot"] = "Botín rápido" AL["Reset frame position"] = "Reiniciar posición del marco" AL["Reset position of minimap button"] = "Reiniciar posición del botón del minimapa" AL["Reset position of the |cff33ff99\"%s\"|r window."] = "Reiniciar posición de la ventana |cff33ff99\"%s\"|r" AL["Reset position of the |cff33ff99\"Minimap button\"|r."] = "Reiniciar posición del |cff33ff99\"Minimap button\"|r." AL["Scale"] = "Tamaño" AL["Set View"] = "Establecer visualización" AL["Show AtlasLoot button on WorldMap."] = "Mostrar botón de AtlasLoot en el mapa del mundo." AL["Show AtlasLoot button on WorldMap's title bar."] = "Mostrar el botón de AtlasLoot en la barra de títulos del mapa del mundo" AL["Show background image if available."] = "Mostrar imagen de fondo si es posible." AL["Show minimap button."] = "Mostrar botón del minimapa." AL["Subtitle"] = "Subtítulo" AL["Title"] = "Título" AL["Use content color if available."] = "Usar color de contenido si está disponible." AL["Use GameTooltip"] = "Usar descripción emergente" AL["Use the standard GameTooltip instead of the custom AtlasLoot tooltip"] = "Usar la descripción emergente del juego en vez de la descripción emergente de AtlasLoot" AL["Windows"] = "Ventanas"
modifier_ramza_mystic_mystic_arts_disbelief = class({}) function modifier_ramza_mystic_mystic_arts_disbelief:IsPurgable() return false end function modifier_ramza_mystic_mystic_arts_disbelief:GetStatusEffectName() return "particles/status_fx/status_effect_avatar.vpcf" end function modifier_ramza_mystic_mystic_arts_disbelief:GetEffectName() return "particles/items_fx/black_king_bar_avatar.vpcf" end function modifier_ramza_mystic_mystic_arts_disbelief:GetEffectAttachType() return PATTACH_ABSORIGIN_FOLLOW end function modifier_ramza_mystic_mystic_arts_disbelief:GetTexture() return "elder_titan_natural_order" end function modifier_ramza_mystic_mystic_arts_disbelief:CheckState() return { [MODIFIER_STATE_MAGIC_IMMUNE] = true } end function modifier_ramza_mystic_mystic_arts_disbelief:OnCreated() if IsClient() then return end local hParent = self:GetParent() self.fMana = hParent:GetMana() hParent:SetMana(0) self:StartIntervalThink(0.1) end function modifier_ramza_mystic_mystic_arts_disbelief:OnIntervalThink() if IsClient() then return end local hParent = self:GetParent() self.fMana = self.fMana+hParent:GetMana() hParent:SetMana(0) end function modifier_ramza_mystic_mystic_arts_disbelief:OnDestroy() if IsClient() then return end local hParent = self:GetParent() hParent:SetMana(self.fMana) end modifier_ramza_mystic_defense_boost = class({}) function modifier_ramza_mystic_defense_boost:IsHidden() return true end function modifier_ramza_mystic_defense_boost:RemoveOnDeath() return false end function modifier_ramza_mystic_defense_boost:IsPurgable() return false end function modifier_ramza_mystic_defense_boost:OnCreated() if IsClient() then return end self.iBonusArmor = self:GetAbility():GetSpecialValueFor("bonus_armor") self.fDuration = self:GetAbility():GetSpecialValueFor("duration") end function modifier_ramza_mystic_defense_boost:DeclareFunctions() return {MODIFIER_EVENT_ON_ATTACKED} end function modifier_ramza_mystic_defense_boost:OnAttacked(keys) if keys.target ~= self:GetParent() then return end if keys.target:PassivesDisabled() then return end keys.target:AddNewModifier(keys.target, nil, "modifier_ramza_mystic_defense_boost_armor", {Duration = self.fDuration}):SetStackCount(self.iBonusArmor) end modifier_ramza_mystic_defense_boost_armor = class({}) function modifier_ramza_mystic_defense_boost_armor:IsPurgable() return true end function modifier_ramza_mystic_defense_boost_armor:GetTexture() return "ramza_mystic_defense_boost" end function modifier_ramza_mystic_defense_boost_armor:DeclareFunctions() return {MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS} end function modifier_ramza_mystic_defense_boost_armor:GetModifierPhysicalArmorBonus() return self:GetStackCount() end function modifier_ramza_mystic_defense_boost_armor:OnCreated() if IsClient() then return end self.iParticle = ParticleManager:CreateParticle("particles/econ/items/treant_protector/ti7_shoulder/treant_ti7_crimson_livingarmor.vpcf", PATTACH_ABSORIGIN_FOLLOW, self:GetParent()) ParticleManager:SetParticleControlEnt(self.iParticle, 1, self:GetParent(), PATTACH_POINT, "follow_origin", self:GetParent():GetAbsOrigin(), true) end function modifier_ramza_mystic_defense_boost_armor:OnDestroy() if IsClient() then return end ParticleManager:DestroyParticle(self.iParticle, true) end modifier_ramza_mystic_manafont = class({}) function modifier_ramza_mystic_manafont:IsHidden() return true end function modifier_ramza_mystic_manafont:RemoveOnDeath() return false end function modifier_ramza_mystic_manafont:IsPurgable() return false end function modifier_ramza_mystic_manafont:OnCreated() if IsClient() then return end self.iPercentageDistanceMP = self:GetAbility():GetSpecialValueFor("percentage_distance_mp") self.vPreviousPosition = self:GetParent():GetOrigin() self:StartIntervalThink(0.25) end function modifier_ramza_mystic_manafont:OnIntervalThink() if IsClient() then return end local hParent = self:GetParent() local fDistance = self.vPreviousPosition.Length(hParent:GetOrigin() - self.vPreviousPosition) if not hParent:PassivesDisabled() then hParent:GiveMana(fDistance*self.iPercentageDistanceMP/100) end self.vPreviousPosition = hParent:GetOrigin() end modifier_ramza_mystic_absorb_mp = class({}) function modifier_ramza_mystic_absorb_mp:IsHidden() return true end function modifier_ramza_mystic_absorb_mp:RemoveOnDeath() return false end function modifier_ramza_mystic_absorb_mp:IsPurgable() return false end function modifier_ramza_mystic_absorb_mp:DeclareFunctions() return {MODIFIER_PROPERTY_ABSORB_SPELL} end function modifier_ramza_mystic_absorb_mp:GetAbsorbSpell(keys) local hParent = self:GetParent() if hParent:PassivesDisabled() then return end local fMana = keys.ability:GetManaCost(keys.ability:GetLevel()-1) hParent:GiveMana(fMana) ParticleManager:CreateParticle("particles/units/heroes/hero_obsidian_destroyer/obsidian_destroyer_essence_effect.vpcf", PATTACH_ABSORIGIN_FOLLOW, hParent) hParent:EmitSound("Hero_ObsidianDestroyer.EssenceAura") local iParticle2 = ParticleManager:CreateParticle("particles/msg_fx/msg_mana_add.vpcf", PATTACH_POINT_FOLLOW, hParent) ParticleManager:SetParticleControl(iParticle2, 1, Vector(0, math.floor(fMana), 0)) ParticleManager:SetParticleControl(iParticle2, 2, Vector(1, 2+math.floor(math.log10(fMana)), 500)) ParticleManager:SetParticleControl(iParticle2, 3, Vector(20, 20, 100)) return false end
return {'meander','meanderen','meao','meander','mea','meadow','meanders','meanderde','meanderend','meanderende','meandert','meas','meadows'}
--[[ PlayState = Class:extend() PlayState:implement(State) function PlayState:new(name) self:init_state(name) self.timer = Timer() self.main = Group() self.persistent_draw = false self.persistent_update = false end function PlayState:on_enter(from end function PlayState:update(dt) self.main:update(dt) camera:update(dt) if self.timer then self.timer:update(dt) end end function PlayState:draw() camera:attach() self.map:drawLayer(self.map.layers["Camada de Tiles 1"]) self.main:draw() camera:detach() end ]] --[[ Object = Class:extend() Object:implement(Physics) function Object:new(group, x, y) -- game object self.class = 'Object' self.id = utils.UUID() self.x = x or 0 self.y = y or 0 self.group = group self.group:add(self) self.scene = main.current.main return self end function Object:update(dt) end function Object:draw() end ]]
return {'eemien','eemnes','eems','eemshaven','eemsmond','eem'}
----------------------------- 以下为 UI代码 不可修改 ----------------------------------- ---@type Framework.UI.Prefab local super = require("Framework.UI.Prefab") ---@class Examples.12_DragAndDrop.UI_12:Framework.UI.Prefab ---@field Image Framework.UI.Image ---@field Image_1 Framework.UI.Image UI_12 = class("Examples.12_DragAndDrop.UI_12", super) function UI_12:ctor(autoBind) super.ctor(self) self.Image = Image.New() self:InsertChild(self.Image) self.Image_1 = Image.New() self:InsertChild(self.Image_1) if autoBind ~= false then self:bindExtend() end end function UI_12:GetAssetPath() return "Assets/UI/Prefab/Example/UI_12.prefab" end ----------------------------- 以下为 逻辑代码 可以修改 ----------------------------------- return UI_12
-- -- created with TexturePacker - https://www.codeandweb.com/texturepacker -- -- $TexturePacker:SmartUpdate:cadcfe307a1eb19417de4d4c0dcda166:1e2a9027e60fc70d48b2e90cb500a164:1784b3470aad1b82bb9f03684bcf642d$ -- -- local sheetInfo = require("mysheet") -- local myImageSheet = graphics.newImageSheet( "mysheet.png", sheetInfo:getSheet() ) -- local sprite = display.newSprite( myImageSheet , {frames={sheetInfo:getFrameIndex("sprite")}} ) -- local SheetInfo = {} SheetInfo.sheet = { frames = { { -- bg-clouds x=0, y=512, width=640, height=240, }, { -- bg-separator x=0, y=180, width=640, height=134, }, { -- cannon x=120, y=58, width=34, height=66, }, { -- continue x=340, y=0, width=322, height=44, }, { -- crown x=664, y=0, width=80, height=52, }, { -- earth x=642, y=330, width=180, height=180, }, { -- finger x=592, y=58, width=100, height=100, }, { -- leaderboard x=58, y=58, width=60, height=60, }, { -- leaf x=156, y=58, width=72, height=76, }, { -- logo-text x=0, y=330, width=640, height=172, }, { -- meteor x=402, y=58, width=86, height=92, }, { -- ozone x=230, y=58, width=84, height=84, }, { -- play x=694, y=58, width=120, height=120, }, { -- rate x=0, y=58, width=56, height=56, }, { -- remove-ads x=746, y=0, width=56, height=56, }, { -- rocket x=642, y=512, width=126, height=248, }, { -- satellite1 x=0, y=0, width=168, height=40, }, { -- satellite2 x=170, y=0, width=168, height=40, }, { -- ship x=642, y=180, width=94, height=148, }, { -- star x=316, y=58, width=84, height=84, }, { -- ufo x=490, y=58, width=100, height=98, }, }, sheetContentWidth = 822, sheetContentHeight = 760 } SheetInfo.frameIndex = { ["bg-clouds"] = 1, ["bg-separator"] = 2, ["cannon"] = 3, ["continue"] = 4, ["crown"] = 5, ["earth"] = 6, ["finger"] = 7, ["leaderboard"] = 8, ["leaf"] = 9, ["logo-text"] = 10, ["meteor"] = 11, ["ozone"] = 12, ["play"] = 13, ["rate"] = 14, ["remove-ads"] = 15, ["rocket"] = 16, ["satellite1"] = 17, ["satellite2"] = 18, ["ship"] = 19, ["star"] = 20, ["ufo"] = 21, } function SheetInfo:getSheet() return self.sheet; end function SheetInfo:getFrameIndex(name) return self.frameIndex[name]; end return SheetInfo
--[[Author: Pizzalol Date: 04.03.2015. Kills the target and applies a modifier with a duration according to the remaining hp of the target Checks if the target is in the allowed table for taking abilities If it is then get the abilities of the target and give them to the caster]] function Devour( keys ) local caster = keys.caster local target = keys.target local ability = keys.ability local ability_level = ability:GetLevel() - 1 -- Ability variables local target_hp = target:GetHealth() local health_per_second = ability:GetLevelSpecialValueFor("health_per_second", ability_level) local modifier = keys.modifier local modifier_duration = target_hp/health_per_second -- Apply the modifier and kill the target ability:ApplyDataDrivenModifier(caster, caster, modifier, {duration = modifier_duration}) target:Kill(ability, caster) -- Setting up the table for allowed devour targets local devour_table = {} local doom_empty1 = keys.doom_empty1 local doom_empty2 = keys.doom_empty2 -- Insert the names of the units that you want to be valid targets for ability stealing table.insert(devour_table, "npc_dota_neutral_polar_furbolg_ursa_warrior") -- Red Hellbear table.insert(devour_table, "npc_dota_neutral_giant_wolf") -- Small wolf table.insert(devour_table, "npc_dota_neutral_centaur_khan") -- Big centaur -- Checks if the killed unit is in the table for allowed targets for _,v in ipairs(devour_table) do if target:GetUnitName() == v then -- Get the first two abilities local ability1 = target:GetAbilityByIndex(0) local ability2 = target:GetAbilityByIndex(1) -- If we already devoured a target and stole an ability from before then clear it if caster.devour_ability1 then caster:SwapAbilities(doom_empty1, caster.devour_ability1, true, false) caster:RemoveAbility(caster.devour_ability1) end if caster.devour_ability2 then caster:SwapAbilities(doom_empty2, caster.devour_ability2, true, false) caster:RemoveAbility(caster.devour_ability2) end -- Checks if the ability actually exist on the target if ability1 then -- Get the name and add it to the caster local ability1_name = ability1:GetAbilityName() caster:AddAbility(ability1_name) -- Make the stolen ability active, level it up and save it in the caster handle for later checks caster:SwapAbilities(doom_empty1, ability1_name, false, true) caster.devour_ability1 = ability1_name caster:FindAbilityByName(ability1_name):SetLevel(ability1:GetLevel()) end -- Checks if the ability actually exist on the target if ability2 then -- Get the name and add it to the caster local ability2_name = ability2:GetAbilityName() caster:AddAbility(ability2_name) -- Make the stolen ability active, level it up and save it in the caster handle for later checks caster:SwapAbilities(doom_empty2, ability2_name, false, true) caster.devour_ability2 = ability2_name caster:FindAbilityByName(ability2_name):SetLevel(ability2:GetLevel()) end end end end --[[Author: Pizzalol Date: 04.03.2015. Awards the bonus gold to the modifier owner only if the modifier owner is alive]] function DevourGold( keys ) local target = keys.target local ability = keys.ability local ability_level = ability:GetLevel() - 1 local bonus_gold = ability:GetLevelSpecialValueFor("bonus_gold", ability_level) -- Give the gold only if the target is alive if target:IsAlive() then target:ModifyGold(bonus_gold, false, 0) end end --[[Author: igo95862, Noya Used by: Pizzalol Date: 27.01.2016. Disallows eating another unit while Devour is in progress]] function DevourCheck( keys ) local caster = keys.caster local modifier = keys.modifier local player = caster:GetPlayerOwner() local pID = caster:GetPlayerOwnerID() if caster:HasModifier(modifier) then caster:Interrupt() -- Play Error Sound EmitSoundOnClient("General.CastFail_InvalidTarget_Hero", player) end end
local PlayerChoice = { Name = "PlayerChoice", Type = "System", Namespace = "C_PlayerChoice", Functions = { { Name = "GetPlayerChoiceInfo", Type = "Function", Returns = { { Name = "choiceInfo", Type = "PlayerChoiceInfo", Nilable = false }, }, }, { Name = "GetPlayerChoiceOptionInfo", Type = "Function", Arguments = { { Name = "optionIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "info", Type = "PlayerChoiceOptionInfo", Nilable = false }, }, }, { Name = "GetPlayerChoiceRewardInfo", Type = "Function", Arguments = { { Name = "rewardIndex", Type = "number", Nilable = false }, }, Returns = { { Name = "rewardInfo", Type = "PlayerChoiceRewardInfo", Nilable = false }, }, }, { Name = "IsWaitingForPlayerChoiceResponse", Type = "Function", Returns = { { Name = "isWaitingForResponse", Type = "bool", Nilable = false }, }, }, }, Events = { { Name = "PlayerChoiceClose", Type = "Event", LiteralName = "PLAYER_CHOICE_CLOSE", }, { Name = "PlayerChoiceUpdate", Type = "Event", LiteralName = "PLAYER_CHOICE_UPDATE", }, }, Tables = { { Name = "PlayerChoiceRarity", Type = "Enumeration", NumValues = 4, MinValue = 0, MaxValue = 3, Fields = { { Name = "Common", Type = "PlayerChoiceRarity", EnumValue = 0 }, { Name = "Uncommon", Type = "PlayerChoiceRarity", EnumValue = 1 }, { Name = "Rare", Type = "PlayerChoiceRarity", EnumValue = 2 }, { Name = "Epic", Type = "PlayerChoiceRarity", EnumValue = 3 }, }, }, { Name = "PlayerChoiceInfo", Type = "Structure", Fields = { { Name = "choiceID", Type = "number", Nilable = false }, { Name = "questionText", Type = "string", Nilable = false }, { Name = "numOptions", Type = "number", Nilable = false }, { Name = "uiTextureKit", Type = "string", Nilable = false }, { Name = "soundKitID", Type = "number", Nilable = true }, { Name = "hideWarboardHeader", Type = "bool", Nilable = false }, { Name = "keepOpenAfterChoice", Type = "bool", Nilable = false }, }, }, { Name = "PlayerChoiceOptionInfo", Type = "Structure", Fields = { { Name = "id", Type = "number", Nilable = false }, { Name = "responseIdentifier", Type = "number", Nilable = false }, { Name = "buttonText", Type = "string", Nilable = false }, { Name = "description", Type = "string", Nilable = false }, { Name = "header", Type = "string", Nilable = false }, { Name = "choiceArtID", Type = "number", Nilable = false }, { Name = "confirmation", Type = "string", Nilable = true }, { Name = "widgetSetID", Type = "number", Nilable = true }, { Name = "disabledButton", Type = "bool", Nilable = false }, { Name = "desaturatedArt", Type = "bool", Nilable = false }, { Name = "disabledOption", Type = "bool", Nilable = false }, { Name = "groupID", Type = "number", Nilable = true }, { Name = "headerIconAtlasElement", Type = "string", Nilable = true }, { Name = "subHeader", Type = "string", Nilable = true }, { Name = "buttonTooltip", Type = "string", Nilable = true }, { Name = "rewardQuestID", Type = "number", Nilable = true }, { Name = "soundKitID", Type = "number", Nilable = true }, { Name = "hasRewards", Type = "bool", Nilable = false }, { Name = "rarity", Type = "PlayerChoiceRarity", Nilable = false }, { Name = "rarityColor", Type = "table", Mixin = "ColorMixin", Nilable = true }, { Name = "typeArtID", Type = "number", Nilable = true }, { Name = "uiTextureKit", Type = "string", Nilable = true }, { Name = "spellID", Type = "number", Nilable = true }, { Name = "maxStacks", Type = "number", Nilable = false }, }, }, { Name = "PlayerChoiceRewardCurrencyInfo", Type = "Structure", Fields = { { Name = "currencyId", Type = "number", Nilable = false }, { Name = "currencyTexture", Type = "number", Nilable = false }, { Name = "quantity", Type = "number", Nilable = false }, }, }, { Name = "PlayerChoiceRewardInfo", Type = "Structure", Fields = { { Name = "money", Type = "number", Nilable = true }, { Name = "xp", Type = "number", Nilable = true }, { Name = "itemRewards", Type = "table", InnerType = "PlayerChoiceRewardItemInfo", Nilable = false }, { Name = "currencyRewards", Type = "table", InnerType = "PlayerChoiceRewardCurrencyInfo", Nilable = false }, { Name = "repRewards", Type = "table", InnerType = "PlayerChoiceRewardReputationInfo", Nilable = false }, }, }, { Name = "PlayerChoiceRewardItemInfo", Type = "Structure", Fields = { { Name = "itemId", Type = "number", Nilable = false }, { Name = "name", Type = "string", Nilable = false }, { Name = "quality", Type = "number", Nilable = false }, { Name = "textureFileId", Type = "number", Nilable = false }, { Name = "quantity", Type = "number", Nilable = false }, { Name = "itemLink", Type = "string", Nilable = false }, }, }, { Name = "PlayerChoiceRewardReputationInfo", Type = "Structure", Fields = { { Name = "factionId", Type = "number", Nilable = false }, { Name = "quantity", Type = "number", Nilable = false }, }, }, }, }; APIDocumentation:AddDocumentationTable(PlayerChoice);
buffer = {} -- buffer namespace currentBuffer = { -- currently opened file buffer lines = { -- content of the file "Welcome to lua nano!", "to start using lua nano do one of the following:", "1: Erase this then use ^o to save the file with a new name", "2: Use ^X to close this file and open lua nano with a file", "3: Goto github.com/BEN1JEN/lua-nano and read the readme.md" }, name="welcome.txt" -- name of the file } function buffer.open(file) -- function for loading a file currentBuffer.name = file -- set current buffer file name currentBuffer.lines = {} -- reset buffer content lines = currentBuffer.lines -- set the lines variable to point to the current buffer content os.execute("touch " .. file) -- make sure the file exists local f = io.open(file) -- use lua stdio open the file line = true -- hack to start the for loop off, could be replaced with a do while loop while line do line = f:read("*line") -- set line to the current file line if line then -- if the line exists, replace hard tabs with soft ones =O line = string.gsub(line, "\t", " ") end lines[#lines+1] = line -- add the line to the current buffer content end if #lines < 1 then -- I don't know what this is doing lines[1] = "" end status.set("Opened File " .. file) -- set the status message end function buffer.getName() -- get the current buffer file name return currentBuffer.name end function buffer.setName(name) -- set the current buffer file name currentBuffer.name = name end function buffer.getLines(start, amount) -- get amount lines from start in the current buffer content if not amount then -- default amount value if not start then amount = #currentBuffer.lines -- if no start value was givin, return every line else amount = 1 -- otherwise only read one line end end if not start then -- default start value start = 1 end local returnLines = {} -- create a new table for output for i = start, start+amount do -- go through the current buffer content and add lines to the output table returnLines[#returnLines + 1] = currentBuffer["lines"][i] end return returnLines -- return the output table end function buffer.writeString(write, y, x, insert) -- write a string to the current buffer content on line y, starting at x local lines = currentBuffer.lines -- set the lines variable to point to the current buffer content if not y then y = 1 end -- default to the first line if not x then -- overwrite the entire line if no x was specified x = 1 lines[y] = "" end if insert then lines[y] = string.sub(lines[y], 1, x-1) .. write .. string.sub(lines[y], x+string.len(write), string.len(lines[y])) -- insert the string else lines[y] = string.sub(lines[y], 1, x-1) .. write .. string.sub(lines[y], x, string.len(lines[y])) -- overwrite with the string end end function buffer.erase(len, y) -- erase from the cursur position if not len then -- default length len = 1 end if not y then -- default y y = cursor.y end local lines = currentBuffer.lines -- set the lines variable to point to the current buffer content lines[y] = string.sub(lines[y], 1, cursor.x-len-1) .. string.sub(lines[y], cursor.x, string.len(lines[y])) -- preform the erasion end function buffer.eraseLine() -- erase the line the cursur is on local lines = currentBuffer.lines -- set the lines variable to point to the current buffer content lines[cursor.y-1] = lines[cursor.y-1] .. table.remove(lines, cursor.y) -- preform the erasion end function buffer.write() -- write the current buffer to a file -- convert the current buffer content to a string local stringBuffer = "" for n, l in ipairs(currentBuffer.lines) do stringBuffer = stringBuffer .. l .. "\n" end -- I don't know what this does local tmp = io.output() local f = io.open(currentBuffer.name, "w+") io.output(f) local stringBuffer = string.gsub(stringBuffer, " ", "\t") -- fix soft tabs to hard tabs! XD io.write(stringBuffer) io.output(tmp) f:close() status.set("Saved As " .. currentBuffer.name) -- set the status message end function buffer.newLine() -- insert a new line like a text editor would local lines = currentBuffer.lines -- set the lines variable to point to the current buffer content local newLine = string.sub(lines[cursor.y], cursor.x, string.len(lines[cursor.y])) -- set this variable to whatever is in between the cursor and the end of the line lines[cursor.y] = string.sub(lines[cursor.y], 1, cursor.x-1) -- erase whatevers between the cursor and the end of the line table.insert(lines, cursor.y+1, newLine) -- insert the above variable on a new line end return buffer -- return the namespace
--! @file pcap-test.lua --! @brief This is a simple test for MoonGen's pcap import and export functionality local mg = require "dpdk" local memory = require "memory" local device = require "device" local log = require "log" local ts = require "timestamping" local pcap = require "pcap" function master(source, sink) source = source or "-" sink = sink or "test-sink.pcap" if source == '--help' then return log:info([[ Usage: [source pcap] [sink pcap] Reads UDP packets from the source pcap to the sink pcap. if source is set to '-', some random UDP packets are generated and written to sink. The default value for source is '-'. The default value for sink is test-sink.pcap. ]]) end source = source or "-" sink = sink or "test-sink.pcap" -- test demonstration without usage of network interfaces simplePcapStoreAndLoadTestSlave(source, sink) mg.waitForSlaves() end --! @brief most simpliest test; just store a packet from buffer to pcap file, and read it again function simplePcapStoreAndLoadTestSlave(source, sink) -- allocate mempool with generator for udp packets with random src port local mem = memory.createMemPool(function(buf) buf:getUdpPacket():fill({udpSrc=math.floor(math.random()*65535)}) end) local bufs = mem:bufArray(12) bufs:alloc(124) local rx = 0 -- read packets from a pcap if the user provided one if source ~= '-' then local pcapReader = pcapReader:newPcapReader(source) rx = pcapReader:readPkt(bufs) for i = 1,rx do print(i..' Read UDP packet with src port '..bufs[i]:getUdpPacket().udp:getSrcPortString()) end pcapReader:close() -- log randomly generated packets instead else print("Simple test: Generating random packets, writing to "..sink.." and reading back from "..sink) for i = 1,#bufs do print(i..' Generated UDP packet with src port '..bufs[i]:getUdpPacket().udp:getSrcPortString()) end end -- write the packets print("Writing packets to "..sink) local pcapWriter = pcapWriter:newPcapWriter(sink) pcapWriter:write(bufs) pcapWriter:close() -- read back local pcapReader = pcapReader:newPcapReader(sink) -- yes, open sink, not source local pktidx = 1 while not pcapReader.done do rx = pcapReader:readPkt(bufs) for i = 1,rx do print(pktidx..' Read back UDP packet with src port '..bufs[i]:getUdpPacket().udp:getSrcPortString()) pktidx = pktidx +1 end end end
function get_filtered_amount(amount) -- spawn deep core ore chunks depending on the ore patch removed amount -- 10 000 = 3% -- 300% = 1 000 000 -- Set to 10% of amount by removing ore patch and max 1 000 chunks (stacks to 100, so 10 stacks to be transportable) -- eg : Yields 100 per refine, so total = 1 000 000 local amountospawn = 0.1 * amount -- prevent too much spawning if amount is over the top (ie creative mod / cheating, etc). if amountospawn > 1000 then amountospawn = 1000 elseif amountospawn < 10 then amountospawn = 10 end return amountospawn end function get_patchable_ores() local patchableOres = { ["iron-ore"] = "iron-ore", ["copper-ore"] = "copper-ore", ["coal"] = "coal", ["stone"] = "stone", ["uranium-ore"] = "uranium-ore", } -- SimpleSilicon's ore support if game.active_mods["SimpleSilicon"] then patchableOres = table.merge(patchableOres, {["SiSi-quartz-ore"] = "SiSi-quartz"}) end -- Angel's ore support if game.active_mods["angelsrefining"] then local angelsores = { ["angels-ore1"] = "angels-ore1", ["angels-ore2"] = "angels-ore2", ["angels-ore3"] = "angels-ore3", ["angels-ore4"] = "angels-ore4", ["angels-ore5"] = "angels-ore5", ["angels-ore6"] = "angels-ore6", } patchableOres = table.merge(patchableOres, angelsores) end -- Clowns Extended Minerals ore support if game.active_mods["Clowns-Extended-Minerals"] then local clownssores = { ["clowns-ore1"] = "clowns-ore1", ["clowns-ore2"] = "clowns-ore2", ["clowns-ore3"] = "clowns-ore3", ["clowns-ore4"] = "clowns-ore4", ["clowns-ore5"] = "clowns-ore5", ["clowns-ore6"] = "clowns-ore6", ["clowns-ore7"] = "clowns-ore7", } patchableOres = table.merge(patchableOres, clownssores) end -- Bob's ore support if game.active_mods["bobores"] and not game.active_mods["angelsrefining"] then local bobores = { ["tin-ore"] = "tin-ore", ["lead-ore"] = "lead-ore", ["quartz"] = "quartz", ["silver-ore"] = "silver-ore", ["zinc-ore"] = "zinc-ore", ["gold-ore"] = "gold-ore", ["bauxite-ore"] = "bauxite-ore", ["rutile-ore"] = "rutile-ore", ["tungsten-ore"] = "tungsten-ore", ["thorium-ore"] = "thorium-ore", ["nickel-ore"] = "nickel-ore", ["cobalt-ore"] = "cobalt-ore", ["sulfur"] = "sulfur", ["gem-ore"] = "gem-ore", } patchableOres = table.merge(patchableOres, bobores) end -- Krastorio2's ore support if game.active_mods["Krastorio2"] then patchableOres = table.merge(patchableOres, {["rare-metals"] = "raw-rare-metals"}) end -- Leighzer's Morphite support if game.active_mods["leighzermorphite"] then local leighzermorphite = { ["morphite-ore"] = "morphite-ore", } patchableOres = table.merge(patchableOres, leighzermorphite) end -- Pyanodons Raw Ores support if game.active_mods["pyrawores"] then local pyrawores = { ["ore-tin"] = "ore-tin", ["ore-quartz"] = "ore-quartz", ["ore-aluminium"] = "ore-aluminium", ["ore-chromium"] = "ore-chromium", ["ore-lead"] = "ore-lead", ["ore-nickel"] = "ore-nickel", ["raw-coal"] = "raw-coal", ["ore-titanium"] = "ore-titanium", ["ore-zinc"] = "ore-zinc", } patchableOres = table.merge(patchableOres, pyrawores) end -- Pyanodons Coal Processing support if game.active_mods["pycoalprocessing"] then local pycoalprocessing = { ["borax"] = "raw-borax", ["niobium"] = "niobium-ore", } patchableOres = table.merge(patchableOres, pycoalprocessing) end return patchableOres end function spawn_ore_patch_on_depleted_ore(event) local ore = event.entity local surface = ore.surface local areaToScan = Position.expand_to_area(ore.position, 10) local minspawnrange = settings.global["vtk-deep-core-mining-spawn-radius-from-start"].value local minrichness = settings.global["vtk-deep-core-mining-patch-min-richness"].value local maxrichness = settings.global["vtk-deep-core-mining-patch-max-richness"].value local patchableOres = get_patchable_ores() -- since it is a user setting, it is possible to break things up, making sure this won't if minrichness > maxrichness then minrichness = maxrichness end -- Add support for Dirty Mining of supported ore patches if game.active_mods["DirtyMining"] then local dirtyores = {} for orename, oreresult in pairs(patchableOres) do local dirtyorename = 'dirty-ore-'..orename if game.entity_prototypes[dirtyorename] then dirtyores = table.merge(dirtyores, {[dirtyorename] = oreresult}) end end patchableOres = table.merge(patchableOres, dirtyores) end -- When Prospector is installed, only generate patches after the last deposit is exhausted -- Prospector is currently not really compatible to DirtyMining, so only enable this feature when DirtyMining is absent if game.active_mods["Prospector"] and not game.active_mods["DirtyMining"] then local patchableOresNew = {} for key, name in pairs(patchableOres) do local key_seam = key.."-seam" if game.entity_prototypes[key_seam] ~= nil then patchableOresNew = table.merge(patchableOresNew, {[key_seam] = name}) else patchableOresNew = table.merge(patchableOresNew, {[key] = name}) end end patchableOres = patchableOresNew end -- logic : -- - if depleted ore has an equivalent patch entity -- - 10% chance to spawn an ore patch on depletion -- - check if there isn't a nearby ore patch already -- - then spawn it on the location the ore was depleted -- debug -- local player = game.players[1] -- player.print("VTK-DEEP-CORE-MINING_DEBUG") -- player.print("mined ore : "..serpent.block(ore)) -- player.print(serpent.block(player)) local validOre = false local orePatchToSpawn = nil for patchableOre, oreresult in pairs(patchableOres) do if patchableOre == ore.name then if settings.global["vtk-deep-core-mining-spawn-"..oreresult.."-patch"] and settings.global["vtk-deep-core-mining-spawn-"..oreresult.."-patch"].value then validOre = true orePatchToSpawn = oreresult.."-patch" break end end end if validOre and not Area.inside(Position.expand_to_area({0,0}, minspawnrange), ore.position) then local number = math.random(1, 10) entitiesCount = surface.count_entities_filtered{area = areaToScan, name = orePatchToSpawn} if number == 1 and entitiesCount == 0 then oreamount = math.random(minrichness, maxrichness) local newOreEntity = surface.create_entity({name = orePatchToSpawn, amount = oreamount, position = ore.position, force = game.forces.neutral, raise_built = true}) end end end function place_deep_core_cracks(area, surface) if not settings.global["vtk-deep-core-mining-spawn-cracks"].value then return end local minspawnrange = settings.global["vtk-deep-core-mining-spawn-radius-from-start"].value local crackrichness = settings.global["vtk-deep-core-mining-crack-richness"].value -- debug -- local player = game.players[1] -- player.print("VTK-DEEP-CORE-MINING_DEBUG") -- only spawn deep core mining cracks in nauvis -- supports New Game Plus mod's "Nauvis plus" worlds if surface.name ~= "nauvis" and not string.contains(surface.name, "Nauvis plus") then return end -- lucky day ? (1 / 500) local luck = math.random(1, 500) -- debug player.print(serpent.block(luck)) if luck ~= 250 then return end -- check if there's already an entity present here (shouldn't but just in case) entitiesCount = surface.count_entities_filtered{area = area, name = "vtk-deepcore-mining-crack"} -- debug player.print(serpent.block(entitiesCount)) if entitiesCount ~= 0 then return end local x1 = area.left_top.x local y1 = area.left_top.y local x2 = area.right_bottom.x local y2 = area.right_bottom.y -- minimum distance from spawn where deepcore mining cracks appear (default 1) -- debug -- player.print("setting value "..minspawnrange) -- player.print("position x "..x1.." y "..y1) if Area.inside(Position.expand_to_area({0,0}, minspawnrange), {x1, y1}) then return end local attempts = 0 -- try 10 times to find a valid position to spawn a crack otherwise abandon while attempts < 10 do local x = math.random(x1, x2) local y = math.random(y1, y2) local tile = surface.get_tile(x, y) -- debug player.print(serpent.block(tile.name)) if tile.valid and surface.can_place_entity{name = "vtk-deepcore-mining-crack", position = tile.position} then local oreamount = crackrichness local createdentity = surface.create_entity({name = "vtk-deepcore-mining-crack", amount = oreamount, position = tile.position, force = game.forces.neutral}) -- cleanup decoratives around the newly spawned crack local cleanupzone = Area.construct(createdentity.position.x, createdentity.position.y, createdentity.position.x, createdentity.position.y) cleanupzone = Area.expand(cleanupzone, 2) surface.destroy_decoratives({area=cleanupzone}) -- debug -- player.print("vtk-deepcore-mining-crack placed successfully") -- player.print(serpent.block(tile.position)) -- player.print(serpent.block(cleanupzone)) return end attempts = attempts + 1 end end function remove_ore_patch(player, surface, area, entities) local patchescount = 0 local sulfuricpatchescount = 0 local chlorinepatchescount = 0 local dronescount = player.get_item_count("vtk-deepcore-mining-drone") local patches = {} local sulfuricpatches = {} local todo = true local sulfuricacidbarrel = "sulfuric-acid-barrel" if game.active_mods["angelspetrochem"] then sulfuricacidbarrel = "liquid-sulfuric-acid-barrel" end local sulfuricacidbarrelcount = player.get_item_count(sulfuricacidbarrel) local chlorinebarrelcount = 0 if game.active_mods["Krastorio2"] then local chlorinebarrelcount = player.get_item_count("chlorine-barrel") end -- debug -- player.print("inventory : "..serpent.line(player.get_inventory(defines.inventory.player_main).get_contents())) for _,entity in pairs(entities) do -- player.print("entity : "..serpent.line(entity)) -- player.print("entity : "..serpent.block(entity)) -- player.print("name : "..entity.name) -- player.print("type : "..entity.type) -- player.print("entity proto : "..serpent.block(entity.prototype)) -- player.print("proto : "..serpent.line(game.entity_prototypes[entity.name].name)) -- player.print("cat : "..game.entity_prototypes[entity.name].resource_category) -- player.print("entity proto name : "..serpent.block(entity.prototype.name)) -- player.print("entity proto cat : "..serpent.block(entity.prototype.resource_category)) if entity.type == "resource" and (entity.prototype.resource_category == "vtk-deepcore-mining-ore-patch" or entity.prototype.resource_category == "vtk-deepcore-mining-crack") then table.insert(patches, entity) patchescount = patchescount + 1 if entity.name == "uranium-ore-patch" or entity.name == "vtk-deepcore-mining-crack" then sulfuricpatchescount = sulfuricpatchescount + 1 end if entity.name == "rare-metals" then chlorinepatchescount = chlorinepatchescount + 1 end end end -- nothing todo ? if patchescount <= 0 then todo = false end -- display all requirements if not enough in inventory if dronescount < patchescount then player.print("Not enough Deep Core mining drones. "..patchescount.." needed only "..dronescount.." in inventory.") todo = false end if sulfuricacidbarrelcount < sulfuricpatchescount then player.print("Not enough sulfuric acid barrel. "..sulfuricpatchescount.." needed only "..sulfuricacidbarrelcount.." in inventory.") todo = false end if chlorinepatchescount < chlorinebarrelcount then player.print("Not enough chlorine acid barrel. "..chlorinepatchescount.." needed only "..chlorinebarrelcount.." in inventory.") todo = false end if not todo then return end -- removing ! for _,entity in pairs(patches) do local amountospawn = get_filtered_amount(entity.amount) -- debug -- player.print("VTK-DEEP-CORE-MINING_DEBUG") -- player.print("Found "..patchescount.." patches to remove and "..sulfuricpatchescount.." sulfuric patches to remove") -- player.print(serpent.block(entity.name)) -- player.print(serpent.block(entity.amount)) -- player.print(serpent.block(amountospawn)) if entity.name == "vtk-deepcore-mining-crack" then surface.spill_item_stack(entity.position, {name="vtk-deepcore-mining-ore-chunk", count = amountospawn}, true) elseif (entity.prototype.resource_category == "vtk-deepcore-mining-ore-patch") then local chunk = string.sub(entity.name, 1, -7) -- "iron-ore-patch" surface.spill_item_stack(entity.position, {name="vtk-deepcore-mining-"..chunk.."-chunk", count = amountospawn}, true) end entity.destroy({raise_destroy = true}) end player.remove_item{name="vtk-deepcore-mining-drone", count = patchescount} if sulfuricpatchescount > 0 then player.remove_item{name=sulfuricacidbarrel, count = sulfuricpatchescount} end if chlorinepatchescount > 0 then player.remove_item{name="chlorine-barrel", count = chlorinepatchescount} end end
-- ############################### -- ## Project: MTA:Speedrace ## -- ## Name: CVehicle.lua ## -- ## Author: Noneatme ## -- ## Version: 1.0 ## -- ## License: See top Folder ## -- ############################### -- FUNCTIONS / METHODS -- local cFunc = {}; -- Local Functions local cSetting = {}; -- Local Settings Vehicle = {}; Vehicle.__index = Vehicle; -- /////////////////////////////// -- ///// GETTERS & SETTERS ////// -- /////////////////////////////// -- /////////////////////////////// -- ///// GETTERS & SETTERS ////// -- /////////////////////////////// -- /////////////////////////////// -- ///// GetDriver ////// -- /////////////////////////////// function Vehicle:GetDriver() return getVehicleOccupant(self); end -- /////////////////////////////// -- ///// GetPassengers ////// -- /////////////////////////////// function Vehicle:GetPassengers() return getVehicleOccupants(self); end -- /////////////////////////////// -- ///// GetColor ////// -- /////////////////////////////// function Vehicle:GetColor() return getVehicleColor(self); end -- /////////////////////////////// -- ///// GetPrice ////// -- /////////////////////////////// function Vehicle:GetPrice() local priceString = vehicleCosts.vehicleCosts[self:GetModel()]; if(priceString) then local money, tokens = gettok(priceString, 1, ","), gettok(priceString, 2, ","); return tonumber(money), tonumber(tokens); end return 0, 0 end -- /////////////////////////////// -- ///// SetColor ////// -- /////////////////////////////// function Vehicle:SetColor(...) return setVehicleColor(self, ...); end -- /////////////////////////////// -- ///// GetType ////// -- /////////////////////////////// function Vehicle:GetType() return getVehicleType(self); end -- /////////////////////////////// -- ///// GetName ////// -- /////////////////////////////// function Vehicle:GetName() return getVehicleName(self); end -- /////////////////////////////// -- ///// GetHandling ////// -- /////////////////////////////// function Vehicle:GetHandling() return getVehicleHandling(self); end -- /////////////////////////////// -- ///// SetHandling ////// -- /////////////////////////////// function Vehicle:SetHandling(...) return setVehicleHandling(self, ...); end -- /////////////////////////////// -- ///// GetOriginalHandling////// -- /////////////////////////////// function Vehicle:GetOriginalHandling() return getOriginalHandling(self); end -- /////////////////////////////// -- ///// SetDamageProof ////// -- /////////////////////////////// function Vehicle:SetDamageProof(bool) return setVehicleDamageProof(self, bool); end -- /////////////////////////////// -- ///// SetEngineState ////// -- /////////////////////////////// function Vehicle:SetEngineState(bool) return setVehicleEngineState(self, bool); end -- /////////////////////////////// -- ///// IsOnGround ////// -- /////////////////////////////// function Vehicle:IsOnGround() return isVehicleOnGround(self); end -- /////////////////////////////// -- ///// getPos ////// -- /////////////////////////////// function Vehicle:GetPos() return getElementPosition(self); end -- /////////////////////////////// -- ///// setPos ////// -- /////////////////////////////// function Vehicle:SetPos(...) return setElementPosition(self, ...); end -- /////////////////////////////// -- ///// setInt ////// -- /////////////////////////////// function Vehicle:SetInt(...) return setElementInterior(self, ...); end -- /////////////////////////////// -- ///// getInt ////// -- /////////////////////////////// function Vehicle:GetInt() return getElementInterior(self); end -- /////////////////////////////// -- ///// setDim ////// -- /////////////////////////////// function Vehicle:SetDim(...) return setElementDimension(self, ...); end -- /////////////////////////////// -- ///// getDim ////// -- /////////////////////////////// function Vehicle:GetDim() return getElementDimension(self); end -- /////////////////////////////// -- ///// FUNKTIONEN ////// -- /////////////////////////////// -- /////////////////////////////// -- ///// FUNKTIONEN ////// -- /////////////////////////////// -- /////////////////////////////// -- ///// reset ////// -- /////////////////////////////// function Vehicle:Reset() local x, y, z = getElementPosition(self); setElementPosition(self, x, y, z-50); setElementVelocity(self, 0, 0, -50); self:ToggleGhostmode(5000); end -- /////////////////////////////// -- ///// toggleGhostmode ////// -- /////////////////////////////// function Vehicle:ToggleGhostmode(seconds) triggerClientEvent(getRootElement(), "Vehicle:ToggleGhostmode", self, seconds); end -- /////////////////////////////// -- ///// respawn ////// -- /////////////////////////////// function Vehicle:Respawn() return respawmVehicle(self); end -- /////////////////////////////// -- ///// fix ////// -- /////////////////////////////// function Vehicle:Fix() return fixVehicle(self); end -- /////////////////////////////// -- ///// blow ////// -- /////////////////////////////// function Vehicle:Blow() return blowVehicle(self); end -- /////////////////////////////// -- ///// addUpgrade ////// -- /////////////////////////////// function Vehicle:AddUpgrade(...) return addVehicleUpgrade(self, ...); end -- /////////////////////////////// -- ///// removeUpgrade ////// -- /////////////////////////////// function Vehicle:RemoveUpgrade(...) return removeVehicleUpgrade(self, ...); end -- /////////////////////////////// -- ///// GetID ////// -- /////////////////////////////// function Vehicle:GetID() return tonumber(self:GetData(nil, "ID")); end -- /////////////////////////////// -- ///// ElementTree ////// -- /////////////////////////////// function Vehicle:NewElementTree() if(self["ElementTree"]) then for index, data in pairs(self["ElementTree"]) do setElementData(self, index, nil); end end self["ElementTree"] = {}; logger:OutputInfo("Element Tree for vehicle: "..self:GetName().." deleted"); end -- /////////////////////////////// -- ///// SaveData ////// -- /////////////////////////////// function Vehicle:SaveData(typ, index, key) if(typ == "account") then connectionManager:Query("UPDATE tblCarData SET "..index.." = '"..key.."' WHERE ID = '"..self:GetID().."';", true) end end -- /////////////////////////////// -- ///// SetData ////// -- /////////////////////////////// function Vehicle:SetData(typ, index, key, doNotSave) assert(self["ElementTree"] ~= nil); if(typ) then typ = string.lower(typ); if not(self["ElementTree"][typ]) then self["ElementTree"][typ] = {}; end self["ElementTree"][typ][index] = key; setElementData(self, typ..":"..index, key); if(doNotSave ~= true) then self:SaveData(typ, index, key); end else self["ElementTree"][index] = key; setElementData(self, index, key); end end -- /////////////////////////////// -- ///// GetData ////// -- /////////////////////////////// function Vehicle:GetData(typ, index) if not(self["ElementTree"]) then return false; end if(typ) then typ = string.lower(typ); if not(self["ElementTree"][typ]) then self["ElementTree"][typ] = {}; end return self["ElementTree"][typ][index]; else return self["ElementTree"][index]; end end -- /////////////////////////////// -- ///// Constructor ////// -- /////////////////////////////// function Vehicle:constructor(...) self["ElementTree"] = {}; self:SetHandling("mass", tonumber(self:GetHandling()["mass"])); self:SetHandling("turnMass", tonumber(self:GetHandling()["turnMass"])); self.resetVehicleFunc = function() self:Reset() end; addEvent("Vehicle:Reset", true) addEventHandler("Vehicle:Reset", self, self.resetVehicleFunc); --logger:OutputInfo("[CALLING] Vehicle: Constructor"); end registerElementClass("vehicle", Vehicle); -- EVENT HANDLER --
local Map = game.GetMap() or "" if Map:find("gm_mus_loop") then Metrostroi.PlatformMap = "loop" Metrostroi.CurrentMap = "gm_loop" else return end Metrostroi.Skins["717_schemes"]["p"] = { adv = "metrostroi_skins/81-717_schemes/int_loop_spb_adv", clean = "metrostroi_skins/81-717_schemes/int_loop_spb_clean", } Metrostroi.Skins["717_schemes"]["m"] = { adv = "metrostroi_skins/81-717_schemes/int_loop_msk_adv", clean = "metrostroi_skins/81-717_schemes/int_loop_msk_clean", } --[НОМЕР] = {НАЗВАНИЕ,ПРАВАЯ СТОРОНА,ВЕЖЛИВОСТЬ,ВЕЩИ,ПРИСЛНОЯТЬСЯ К ДВЕРЯМ,ИМЕЕТ В НАЗВАНИИ "СТАНЦИЯ",СТАНЦИЯ ПЕРЕХОДА,СТАНЦИЯ РАЗДЕЛЕНИЯ,НЕ КОНЕЧНАЯ(развернуть информатор)} Metrostroi.AnnouncerData = { [651] = {"First april", false,true ,0 ,false,false,0}, [652] = {"Park", false,false,false,true ,false,{799,235,799}}, [653] = {"Metrostroiteley", false,false,1 ,false,false,{699,236,699}}, [654] = {"Marine", false,true ,false,true ,false,0 }, [654] = {}, [655] = {"Glorious country",false,false,0 ,false,false,{799,235,799}}, [656] = {"Pionerskaya", false,false,false,false,false,{699,236,699}}, loop = true, } Metrostroi.AnnouncerTranslate = { [651] = "Первоапрельская", [652] = "Парк", [653] = "Метростроителей", --[654] = "Морская", [655] = "Славная страна", [656] = "Пионерская", } ---[=[ НЕ ТРОГАТЬ, информатор не готов! Metrostroi.WorkingStations = { {651,652,653--[[,654]],655,656}, {656,655--[[,654]],653,652,651}, } Metrostroi.EndStations = { --{652,654,656}, {652,653,656}, {656,655,652,651}, } if Metrostroi.WorkingStations then for k, v in pairs(Metrostroi.WorkingStations) do for k1, v1 in pairs(v) do Metrostroi.WorkingStations[k][v1] = k1 end end end if Metrostroi.EndStations then for k, v in pairs(Metrostroi.EndStations) do for k1, v1 in pairs(v) do Metrostroi.EndStations[k][v1] = k1 end end end -- ]=]
local has_notify, notify = pcall(require, "notify") local a = vim.api local uv = vim.loop local M = {} M.is_windows = vim.fn.has "win32" == 1 or vim.fn.has "win32unix" == 1 function M.Notify(msg) vim.schedule(function() vim.notify(msg) end) end function M.GetInputChar(prompt) vim.api.nvim_command("redraw") print(prompt) local _, resp = pcall(vim.fn.getcharstr) resp = resp or "" vim.api.nvim_command("normal! :") return resp end function M.Input(opts, callback) vim.api.nvim_command("redraw") vim.ui.input(opts, callback) vim.api.nvim_command("normal! :") end function M.path_to_matching_str(path) return path:gsub("(%-)", "(%%-)"):gsub("(%.)", "(%%.)"):gsub("(%_)", "(%%_)") end function M.warn(msg) vim.schedule(function() if has_notify then notify(msg, vim.log.levels.WARN, { title = "FTree" }) else vim.notify("[FTree] " .. msg, vim.log.levels.WARN) end end) end function M.str_find(haystack, needle) return vim.fn.stridx(haystack, needle) ~= -1 end function M.read_file(path) local fd = uv.fs_open(path, "r", 438) if not fd then return "" end local stat = uv.fs_fstat(fd) if not stat then return "" end local data = uv.fs_read(fd, stat.size, 0) uv.fs_close(fd) return data or "" end local path_separator = package.config:sub(1, 1) function M.path_join(paths) return table.concat(vim.tbl_map(M.path_remove_trailing, paths), path_separator) end function M.path_split(path) return path:gmatch("[^" .. path_separator .. "]+" .. path_separator .. "?") end ---Get the basename of the given path. ---@param path string ---@return string function M.path_basename(path) path = M.path_remove_trailing(path) local i = path:match("^.*()" .. path_separator) if not i then return path end return path:sub(i + 1, #path) end ---Get a path relative to another path. ---@param path string ---@param relative_to string ---@return string function M.path_relative(path, relative_to) local p, _ = path:gsub("^" .. M.path_to_matching_str(M.path_add_trailing(relative_to)), "") return p end function M.path_add_trailing(path) if path:sub(-1) == path_separator then return path end return path .. path_separator end function M.path_remove_trailing(path) local p, _ = path:gsub(path_separator .. "$", "") return p end M.path_separator = path_separator function M.clear_prompt() vim.api.nvim_command "normal! :" end function M.get_user_input_char() local c = vim.fn.getchar() while type(c) ~= "number" do c = vim.fn.getchar() end return vim.fn.nr2char(c) end ---Matching executable files in Windows. ---@param ext string ---@return boolean local PATHEXT = vim.env.PATHEXT or "" local wexe = vim.split(PATHEXT:gsub("%.", ""), ";") local pathexts = {} for _, v in pairs(wexe) do pathexts[v] = true end function M.is_windows_exe(ext) return pathexts[ext:upper()] end function M.rename_loaded_buffers(old_path, new_path) for _, buf in pairs(a.nvim_list_bufs()) do if a.nvim_buf_is_loaded(buf) then local buf_name = a.nvim_buf_get_name(buf) local exact_match = buf_name == old_path local child_match = ( buf_name:sub(1, #old_path) == old_path and buf_name:sub(#old_path + 1, #old_path + 1) == path_separator ) if exact_match or child_match then a.nvim_buf_set_name(buf, new_path .. buf_name:sub(#old_path + 1)) -- to avoid the 'overwrite existing file' error message on write for -- normal files if a.nvim_buf_get_option(buf, "buftype") == "" then a.nvim_buf_call(buf, function() vim.cmd "silent! write!" end) end end end end end --- @param path string path to file or directory --- @return boolean function M.file_exists(path) local _, error = vim.loop.fs_stat(path) return error == nil end --- @param path string --- @return string function M.canonical_path(path) if M.is_windows and path:match "^%a:" then return path:sub(1, 1):upper() .. path:sub(2) end return path end -- Create empty sub-tables if not present -- @param tbl to create empty inside of -- @param sub dot separated string of sub-tables -- @return deepest sub-table function M.table_create_missing(tbl, sub) if tbl == nil then return nil end local t = tbl for s in string.gmatch(sub, "([^%.]+)%.*") do if t[s] == nil then t[s] = {} end t = t[s] end return t end function M.format_bytes(bytes) local units = { "B", "K", "M", "G", "T" } bytes = math.max(bytes, 0) local pow = math.floor((bytes and math.log(bytes) or 0) / math.log(1024)) pow = math.min(pow, #units) local value = bytes / (1024 ^ pow) value = math.floor((value * 10) + 0.5) / 10 pow = pow + 1 return (units[pow] == nil) and (bytes .. "B") or (value .. units[pow]) end function M.key_by(tbl, key) local keyed = {} for _, val in ipairs(tbl) do keyed[val[key]] = val end return keyed end return M
require( "config" ) function new_size( oldvalue, offset, factor ) if oldvalue == nil then oldvalue = 1 end local v = offset + oldvalue * factor if v > oldvalue then return( v ) else return oldvalue end end if my_inventory_size then data.raw.player.player.inventory_size = my_inventory_size end if my_running_speed_factor and my_running_speed_factor ~= 1 and data.raw.player.player.running_speed == 0.15 then data.raw.player.player.running_speed = 0.15 * my_running_speed_factor end for _,dat in pairs(data.raw) do for _,item in pairs(dat) do if item.stack_size and item.stack_size > 1 then item.stack_size = new_size( item.stack_size, my_stack_offset, my_stack_factor ) end if item.default_request_amount then if my_default_req_amount then item.default_request_amount = my_default_req_amount end end if item.ingredients then item.ingredients = {} end if item.unit then item.unit.ingredients = {} item.unit.count = 1 item.unit.time = 0.5 end if item.range then item.range = item.range * 2 end if item.mining_speed then item.mining_speed = item.mining_speed * 5 end if item.energy_usage then item.energy_usage = '100W' end if item.energy_required then item.energy_required = 0.5 end end end for _, ammo in pairs(data.raw.ammo) do -- ammo.stack_size = new_size( ammo.stack_size, my_stack_offset, my_stack_factor ) ammo.magazine_size = new_size( ammo.magazine_size, my_mag_offset, my_mag_factor ) if my_default_req_amount then ammo.default_request_amount = my_default_req_amount end end for _, modu in pairs(data.raw["module"]) do modu.stack_size = new_size( modu.stack_size, my_stack_offset, my_stack_factor ) end for _, caps in pairs(data.raw["capsule"]) do caps.stack_size = new_size( caps.stack_size, my_stack_offset, my_stack_factor ) end -- make resources endless for k, v in pairs(data.raw.resource) do data.raw.resource[k].infinite = true data.raw.resource[k].minimum = 175 data.raw.resource[k].normal = 350 end
<div id="content"> <div class="panel"> <% if topics and #topics > 0 then %> <div class="inner no-padding"> <%- partial('item', {collection = topics, as = 'topic'}) %> </div> <% else %> <div class="inner"> <p>无话题</p> </div> <% end %> </div> <%- markdown([[ ## 快速使用 推荐在centos7系统运行 目前适配的系统:centos7,ubuntu。其他系统尚未适配过。 centos7安装git工具 ``` sudo yum install -y git ``` ubuntu安装git工具 ``` sudo apt-get install -y git ``` ### 1. 下载源代码,或者使用git克隆 ``` git clone https://github.com/skynetlua/meiru-skynet.git ``` ### 2. 配置工程 ``` cd yourfolder/meiru-skynet ./meiru/bin/meiru setup ``` meiru setup会自动下载安装gcc,autoconf,readline,openssl等。 ### 3. 编译工程 ``` ./meiru/bin/meiru build ``` 该命令会自动进行编译。编译后,生成skynet程序,就可以在其他主机运行,而无需要再次编译。 如果要清理编译文件,可执行 ``` ./meiru/bin/meiru clean ``` ### 4. 创建工程 以创建test项目为例,在终端,cd到meiru-skynet目录下。执行 ``` ./meiru/bin/meiru create test ``` 可以把meiru-skynet/meiru/bin添加到系统环境变量 ``` meiru create test ``` ### 5. 启动工程 ``` ./meiru/bin/meiru start test ``` 浏览器打开127.0.0.1:8080/index。既可以看到结果 ### 6. 停止服务 ``` ./meiru/bin/meiru stop test ``` test项目的结构如下 ``` assets //存放资源 config //项目的启动配置文件 lualib //存放lua脚本库文件 ``` ]]) %> </div>
package.path = package.path .. ";../?.lua" local TLBE = { Camera = require("scripts.camera"), Main = require("scripts.main"), Config = require("scripts.config") } local lu = require("luaunit") local tileSize = 32 TestNewCamera = {} function TestNewCamera.TestUniqueName() local camera1 = TLBE.Camera.newCamera({postion = {0, 0}}, {}) lu.assertEquals(camera1.name, "new camera", "with empty list no index is needed") local camera2 = TLBE.Camera.newCamera({postion = {0, 0}}, {camera1}) lu.assertEquals(camera2.name, "new camera-2", "with camera 'new camera' already in the list, add '-2' to the name") local camera3 = TLBE.Camera.newCamera({postion = {0, 0}}, {camera1, camera2}) lu.assertEquals( camera3.name, "new camera-3", "with camera 'new camera' and 'new camera-2' already in the list, add '-3' to the name" ) end TestCamera = {} local function nextTick() TLBE.Main.tick() game.tick = game.tick + 1 end function TestCamera:SetUp() -- mock Factorio provided globals global = {} game = { tick = 0, surfaces = {{name = "nauvis"}}, take_screenshot = function() end } -- mock TLBE tables global.playerSettings = { TLBE.Config.newPlayerSettings({position = {x = 0, y = 0}}), TLBE.Config.newPlayerSettings({position = {x = 0, y = 0}}) } game.players = { {index = 1, surface = game.surfaces[1]}, {index = 2, surface = game.surfaces[1]} } -- Enable player1 camera global.playerSettings[1].cameras[1].enabled = true -- Make cameras easier to test self.testCameraPlayer1 = global.playerSettings[1].cameras[1] self.testCameraPlayer2 = global.playerSettings[2].cameras[1] for _, playerSettings in pairs(global.playerSettings) do for _, camera in pairs(playerSettings.cameras) do for k, v in pairs( { width = 20 * tileSize, height = 15 * tileSize, screenshotInterval = 1, -- do not skip any ticks for these tests realtimeInterval = 1, -- do not skip any ticks for these tests zoomTicks = 1, -- zoom immediately for these tests zoomTicksRealtime = 1 -- zoom immediately for these tests } ) do camera[k] = v end end end end function TestCamera:TestTransitionFromPlayerToBaseTracker() game.players[1].position = {x = 5, y = 4} nextTick() lu.assertEquals(self.testCameraPlayer1.centerPos.x, 5, "expected to be at player position") lu.assertEquals(self.testCameraPlayer1.centerPos.y, 4, "expected to be at player position") lu.assertEquals(self.testCameraPlayer1.zoom, 1, "expected that zoom at max_zoom") -- Move player and build entity game.players[1].position = {x = 2, y = 2} TLBE.Main.entity_built( { created_entity = { surface = game.surfaces[1], bounding_box = { left_top = {x = 1, y = 3}, right_bottom = {x = 3, y = 4} } } } ) nextTick() lu.assertEquals(self.testCameraPlayer1.centerPos.x, 2, "expected to be at entity center") lu.assertEquals(self.testCameraPlayer1.centerPos.y, 3.5, "expected to be at entity center") lu.assertEquals(self.testCameraPlayer1.zoom, 1, "expected that zoom at max_zoom") lu.assertEquals(self.testCameraPlayer2.centerPos.x, 0, "expected disabled camera to be unchanged") lu.assertEquals(self.testCameraPlayer2.centerPos.y, 0, "expected disabled camera to be unchanged") end function TestCamera:TestRocketLaunch() -- center camera at 0,0 self.testCameraPlayer1.centerPos = {x = 0, y = 0} self.testCameraPlayer1.zoom = 1 -- Initialize base tracker TLBE.Main.entity_built( { created_entity = { surface = game.surfaces[1], bounding_box = { left_top = {x = -1, y = -1}, right_bottom = {x = 1, y = 1} } } } ) nextTick() lu.assertEquals(self.testCameraPlayer1.centerPos.x, 0, "expected to be at entity center") lu.assertEquals(self.testCameraPlayer1.centerPos.y, 0, "expected to be at entity center") lu.assertEquals(self.testCameraPlayer1.zoom, 1, "expected that zoom at max_zoom") -- Launch rocket TLBE.Main.rocket_launch({rocket_silo = {surface = game.surfaces[1], position = {x = 10, y = 10}}}) nextTick() lu.assertEquals(self.testCameraPlayer1.centerPos.x, 10, "expected to be at rocket_silo position") lu.assertEquals(self.testCameraPlayer1.centerPos.y, 10, "expected to be at rocket_silo position") lu.assertEquals(self.testCameraPlayer1.zoom, 1, "expected that zoom at max_zoom") -- Rocket launched (return back to base) TLBE.Main.rocket_launched({rocket_silo = {surface = game.surfaces[1]}}) nextTick() lu.assertEquals(self.testCameraPlayer1.centerPos.x, 0, "expected to be back at entity center") lu.assertEquals(self.testCameraPlayer1.centerPos.y, 0, "expected to be back at entity center") lu.assertEquals(self.testCameraPlayer1.zoom, 1, "expected that zoom at max_zoom") end function TestCamera:TestResolutionChange() -- Only keep base tracker (so it is the active tacker) self.testCameraPlayer1.trackers = {self.testCameraPlayer1.trackers[3]} local baseTracker = self.testCameraPlayer1.trackers[1]; TLBE.Main.entity_built( { created_entity = { surface = game.surfaces[1], bounding_box = { left_top = {x = -20, y = -20}, right_bottom = {x = 20, y = 20} } } } ) -- force set camera position and zoom TLBE.Camera.followTracker(nil, nil, self.testCameraPlayer1, baseTracker, true) local oldZoom = self.testCameraPlayer1.zoom; local oldCenterPos = self.testCameraPlayer1.centerPos; TLBE.Camera.setWidth(self.testCameraPlayer1, self.testCameraPlayer1.width*2) TLBE.Camera.setHeight(self.testCameraPlayer1, self.testCameraPlayer1.height*2) lu.assertEquals(self.testCameraPlayer1.centerPos.x, oldCenterPos.x, "expected centerpos to be the same") lu.assertEquals(self.testCameraPlayer1.centerPos.y, oldCenterPos.y, "expected centerpos to be the same") lu.assertNotEquals(self.testCameraPlayer1.zoom, oldZoom, "expected that zoom has been changed") lu.assertEquals(self.testCameraPlayer1.zoom, oldZoom * 2, "expected that zoom has doubled as resolution has been doubled") end
AddCSLuaFile("shared.lua") AddCSLuaFile("cl_init.lua") include("shared.lua") util.AddNetworkString("fw.updateTurretStatus") util.AddNetworkString("fw.upgradeTurret") util.AddNetworkString("fw.toggleMenu") util.AddNetworkString("fw.buyAmmo") --setup initial conditions :v --wow that's a lot of network variables function ENT:Initialize() self:SetModel("models/combine_turrets/ground_turret.mdl") self:PhysicsInit(SOLID_NONE) self:SetMoveType(MOVETYPE_NONE) self:SetSolid(SOLID_VPHYSICS) self:SetPos(self:GetPos() + Vector(0, 0, 20)) self:DropToFloor() local ang = self:GetAngles() self:SetAngles(Angle(0, ang.y, 0)) --self:SetTrigger(true) self:SetUseType(SIMPLE_USE) self:SetUpgradeStatus(0) self:SetOwner(self) self:SetRemaining(self.clip) self:SetTargeting(false) self:SetTargetingDistance(0) self:SetStatus(false) self:SetMaxClip(self.clip) self:SetCanControl(false) self:SetMenuOpen(true) self:SetTHealth(self.health) self:SetTMaxHealth(self.health) self:SetCooldown(0) self:SetDamage(self.damage) self:SetRadius(self.radius) self:SetFireOffset(self.fire_offset) self:SetAmmoCost(self.ammo_cost) self.origin_ang = self:GetAngles() self:SetDefaultAngle(self:GetAngles()) self.last_fire = CurTime() self.shoot_positions = { Vector(0, 0, 0) } self.angle_offset = 180 end --opens the menu on entity use function ENT:Use(act, caller) if (not IsValid(caller) or self:GetMenuOpen()) then return end self:SetMenuOpen(not self:GetMenuOpen()) end --handles upgrades function ENT:Upgrade(tbl) self:SetUpgradeStatus(tbl.upgrade_id) --1 to whatever self:SetRemaining(tbl.clipsize or self:GetMaxClip()) --if no clip upgrade just reset it self:SetMaxClip(tbl.clipsize or self:GetMaxClip()) self:SetDamage(tbl.damage or self:GetDamage()) self:SetRadius(tbl.radius or self:GetRadius()) self:SetFireOffset(tbl.fire_offset or self:GetFireOffset()) self:SetModel(tbl.model or self:GetModel()) self:SetAmmoCost(tbl.ammo_cost or self:GetAmmoCost()) self:SetTHealth(tbl.health or self:GetTMaxHealth()) self:SetTMaxHealth(tbl.health or self:GetTMaxHealth()) self:DropToFloor() self.shoot_positions = tbl.shoot_positions or self.shoot_positions --for multiple turret holes! self:SetCanControl(tbl.can_control or false) self:SetCooldown(0) end --handles entity health function ENT:OnTakeDamage(dmg) local damage = dmg:GetDamage() if (self:GetTHealth() - damage < 0) then local effect = EffectData() effect:SetOrigin(self:GetPos()) util.Effect("Explosion", effect) self:Remove() return end self:SetTHealth(self:GetTHealth() - damage) end --determines whether an entity is abled to be targeted function ENT:ShouldTarget(target) if (not target:IsPlayer()) then return false end if (not target:inFaction()) then return false end if (IsValid(self:FWGetOwner()) and IsValid(target) and target:getFaction() == self:FWGetOwner():getFaction()) then return false end if (self:FWGetOwner() == target) then return false end return true end --finds the closest targetable entity function ENT:FindNearest() local near = nil local range = self:GetRadius() * self:GetRadius() local entlist = ents.GetAll() if (#entlist == 0) then return end for _,ent in pairs(entlist) do if (not ent:IsPlayer() and not self:ShouldTarget(ent)) then continue end local dis = self:GetPos():DistToSqr(ent:GetPos()) if (dis <= range) then near = ent range = dis end end return near, range end --resets the targeting state function ENT:ResetData() self:SetTargeting(false) self:SetTargetingDistance(0) end --determines if the weapon has the ability to shoot function ENT:ShouldFire() local bullets = self:GetRemaining() if (not self.last_fire) then return true end --hasn't fire yet if (bullets - 1 < 0) then return false end return true end --fires bullets function ENT:FireThisShit() self:SetRemaining(self:GetRemaining() - #self.shoot_positions)-- - 1) self.last_fire = CurTime() for k,v in pairs(self.shoot_positions) do local targ_pos = self.target:GetPos() + Vector(0, 0, 50) local tr = util.TraceLine({ start = v, endpos = targ_pos }) if (not tr.Hit or not tr.Entity) then continue end if (tr.Entity != self.target) then continue end local fire_tbl = { Damage = self:GetDamage(), Distance = self:GetRadius(), Dir = targ_pos, Src = v } self:FireBullets(fire_tbl) end end --handles entity positions and finding / shooting of targets local ang = 0 local floater_angle = Angle(0, 0, 0) local shouldChange = true local offset = 1 function ENT:Think() if (not self:GetStatus()) then self:ResetData() return end if (IsValid(self)) then --blah blah fancy rotating gun code :D if (not self:GetTargeting() and self:GetStatus()) then if (shouldChange) then ang = ang - offset if (ang == -180) then shouldChange = false end elseif (not shouldChange) then ang = ang + offset if (ang == 180) then shouldChange = true end end self:SetAngles(self.origin_ang + Angle(0, ang, 0)) end end --make sure we find an entity local nearest, distance = self:FindNearest() if (not nearest) then self:ResetData() return end if (not IsValid(nearest)) then self:ResetData() return end if (not self:ShouldFire()) then --this is an error state function self:ResetData() self:SetStatus(false) return end if (not self:ShouldTarget(nearest)) then self:ResetData() return end self.target = nearest self:SetTargeting(true) self:PointAtEntity(nearest) self.targeting_angle = self:GetAngles() self:SetAngles(Angle(0, self.targeting_angle.y, 0)) self:SetTargetingDistance(math.sqrt(distance)) if (CurTime() < self.last_fire + self:GetFireOffset()) then self:SetCooldown(CurTime() - self.last_fire + 1) return end self:FireThisShit() end --toggles the turret on or off net.Receive("fw.updateTurretStatus", function(l, caller) local ent = net.ReadEntity() local bool = net.ReadBool() if (not IsValid(ent) or not ent:ShouldFire()) then return end local dis = caller:GetPos():DistToSqr(ent:GetPos()) if (dis > 140 * 140) then return end ent:SetStatus(bool) end) --handles the player trying to upgrade the turret net.Receive("fw.upgradeTurret", function(l, caller) local ent = net.ReadEntity() if (not IsValid(ent)) then return end local dis = caller:GetPos():DistToSqr(ent:GetPos()) if (dis > 140 * 140) then return end local upgrade_status = ent:GetUpgradeStatus() local target_upgrade = ent.upgrades[upgrade_status + 1] if (not target_upgrade) then return end local mon = caller:getMoney() if (mon - target_upgrade.cost < 0) then return end caller:addMoney(-target_upgrade.cost) target_upgrade.upgrade_id = ent:GetUpgradeStatus() + 1 ent:Upgrade(target_upgrade) end) --turns the menu off net.Receive("fw.toggleMenu", function(l, caller) local ent = net.ReadEntity() if (not IsValid(ent)) then return end local dis = caller:GetPos():DistToSqr(ent:GetPos()) if (dis > 140 * 140) then return end ent:SetMenuOpen(not ent:GetMenuOpen()) end) --handles the player trying to buy ammo net.Receive("fw.buyAmmo", function(l, caller) local ent = net.ReadEntity() if (not IsValid(ent)) then return end local dis = caller:GetPos():DistToSqr(ent:GetPos()) if (dis > 140 * 140) then return end --only charge for the ammo needed local ammo_cost = (ent:GetRemaining() / ent:GetMaxClip()) * ent:GetAmmoCost() ammo_cost = math.Round(ent:GetAmmoCost() - ammo_cost) if (caller:getMoney() - ammo_cost < 0) then return end if (tonumber(ent:GetRemaining()) != tonumber(ent:GetMaxClip())) then caller:addMoney(-ammo_cost) ent:SetRemaining(ent:GetMaxClip()) end end)
-- I have no idea what im doing. - TheEndBoss_101 -- NOTE: I started on roblox, wasent my best idea. -- you're doing some cool stuff - Xalalau C_GM13B_GUI_Panel = {} function C_GM13B_GUI_Panel:CreateWindow() --print("Hello, World") math.randomseed(os.time()) -- Random local DermaFrame = vgui.Create("DFrame") DermaFrame:SetPos(50, 50) DermaFrame:SetSize(ScrW() / 3, ScrH() / 2) DermaFrame:SetTitle("gm_construct 13 beta - Gui") DermaFrame:SetVisible(true) DermaFrame:SetDraggable(true) DermaFrame:ShowCloseButton(true) DermaFrame:SetBackgroundBlur(false) DermaFrame:SetDeleteOnClose(true) DermaFrame:SetMouseInputEnabled(true) DermaFrame:SetKeyboardInputEnabled(true) DermaFrame:MakePopup() DermaFrame:Center() -- Tabs local PropertySheet = vgui.Create("DPropertySheet") PropertySheet:SetParent(DermaFrame) PropertySheet:Dock(FILL) local About_Tab = vgui.Create("DPanel") About_Tab:SetBackgroundColor(Color(51, 51, 51)) local GM13B_Tab = vgui.Create("DPanel") GM13B_Tab:SetBackgroundColor(Color(51, 51, 51)) local ARC_Tab = vgui.Create("DPanel") ARC_Tab:SetBackgroundColor(Color(51, 51, 51)) C_GM13B_GUI_Panel:Fill_About_Tab(About_Tab) C_GM13B_GUI_Panel:Fill_GM13B_Tab(GM13B_Tab) C_GM13B_GUI_Panel:Fill_ARC_Tab(ARC_Tab) PropertySheet:AddSheet("About", About_Tab, "icon16/information.png", false, false, "Information") PropertySheet:AddSheet("gm13b", GM13B_Tab, "icon16/application.png", false, false, "gm_construct 13 beta") -- if file.Exists("addons/Anomaly-Research-Center-ARC", "GAME" ) then PropertySheet:AddSheet("A.R.C.", ARC_Tab, "icon16/application_add.png", false, false, "Anomaly Research Center") -- end end -- bind "n" "echo "C_GM13B_GUI_Panel.CreateWindow";cgm13d_vgui" concommand.Add("cgm13d_vgui", C_GM13B_GUI_Panel.CreateWindow)
SecurityCamConfig = {} SecurityCamConfig.DebugMode = false SecurityCamConfig.HideRadar = true SecurityCamConfig.Locations = { { camBox = {label = "Hackerspace", x = 1072.02, y = -202.10, z = 71.30}, cameras = { {label = "Camera Praça", x = 141.06698608398, y = -1032.443359375, z = 39.122398376465, r = {x = 0.0, y = 0.0, z = -20.0}, canRotate = true}, {label = "Camera Garagem", x = 248.07768249512, y = -793.23187255859, z = 38.394092559814, r = {x = 0.0, y = 0.0, z = 80.0}, canRotate = true}, {label = "Camera DP", x = 388.52795410156, y = -980.82495117188, z = 42.424461364746, r = {x = -20.0, y = 0.0, z = -70.0}, canRotate = true}, {label = "Camera Central", x = 179.50575256348, y = 180.42587280273, z = 117.59791564941, r = {x = -20.0, y = 0.0, z = -70.0}, canRotate = true}, {label = "Camera Prisão", x = 1679.2337646484, y = 2531.7316894531, z = 56.681903839111, r = {x = -20.0, y = 0.0, z = -170.0}, canRotate = true}, }, allowedModels = {} } }
dofile('common.lua') local hack_symbols = read_asm_sym_file('src/m2-hack.sym') local includes_symbols = read_asm_sym_file('working/m12-includes.sym') local asm_symbols = {} for k,v in ipairs(hack_symbols) do if v.IsGlobal then table.insert(asm_symbols,v) end end for k,v in ipairs(includes_symbols) do if v.IsGlobal then table.insert(asm_symbols,v) end end local asm_symbols_names = {} for k,v in ipairs(asm_symbols) do table.insert(asm_symbols_names,v.name) end local ext_symbols = read_sym_file('src/c/undefine_obj.sym') local ext_symbols_names = {} for k,v in ipairs(ext_symbols) do if v.IsGlobal and v.IsFunction then table.insert(ext_symbols_names,v.name) end end for k,v in ipairs(ext_symbols_names) do if not is_include(v, asm_symbols_names) then print(string.format("Error: Undefined external symbol %s\n",v)) end end local nfile = io.open ("src/c/link.ld","w") nfile:write("SECTIONS { .text 0x83755B8 : { *(.text .data .rodata*) } }\n") for k,v in ipairs(asm_symbols) do --table.insert(asm_symbols_names,v.name) nfile:write(string.format("%s = 0x%X;\n",v.name, v.value)) end nfile:close()
local Class = require "hump.class" local Vector = require "hump.vector" local BaseObject = require "toys/baseObject" ExplodingPlatform = Class{__includes = BaseObject} function ExplodingPlatform:init(world, mapObject) self.mapObject = mapObject -- Save all our map object values for re-spawn self.width, self.height = mapObject.width, mapObject.height self.xSpawn, self.ySpawn = mapObject.x + (self.width / 2), mapObject.y + (self.height / 2) self.bodyType = self:checkStaticBool(mapObject.properties.static) self.rotation = mapObject.rotation self:resetPhysicsObject(world, mapObject) if mapObject.properties.texturePath then self.image = love.graphics.newImage(mapObject.properties.texturePath) end -- check if we're important to the camera self.cameraDistance = mapObject.properties.cameraDistance self.cameraFocus = mapObject.properties.cameraFocus -- start timer (seconds) self.timer = 3 + love.math.random(9) self.state = "exists" -- Becomes more red as we get closer to exploding self.color = {1, 1, 1, 1} -- keep track of to gradually get more difficult self.timesExploded = 0 end function ExplodingPlatform:resetPhysicsObject(world) -- [re]-create based on saved values self.body = love.physics.newBody(world, self.xSpawn, self.ySpawn, self.bodyType) self.body:setUserData({ type = "explodingPlatform", collisionSfxFolder = self.mapObject.properties.collisionSfxFolder or "generic" }) self.shape = love.physics.newRectangleShape(0, 0, self.width, self.height) self.fixture = love.physics.newFixture(self.body, self.shape); self.fixture:setFriction(0.9) -- if no texture self.color = {1, 0.2, 0.7} local centre = Vector(self.body:getPosition()) -- get the rotation point (top left corner) local rotationPoint = Vector(centre.x - self.width/2, centre.y - self.height/2) -- move to be around rotation point centre = centre - rotationPoint -- rotate local new = centre:rotated(math.rad(self.rotation)) -- move point back centre = new + rotationPoint self.body:setPosition(centre:unpack()) self.body:setAngle(math.rad(self.rotation)) end function ExplodingPlatform:getPosition() if self.body and not self.body:isDestroyed() then return self.body:getPosition() end -- if body doesn't exist, return where it's about to be return self.xSpawn, self.ySpawn end function ExplodingPlatform:getColor() return self.color[1], self.color[2], self.color[3], self.color[4] end function ExplodingPlatform:update(dt, world) self.timer=self.timer-dt if self.timer < 3 then -- normalize (kinda (not really lol)) timer from 3 - 0 to 1 - 0.3 local newGB = (self.timer/3) + 0.3 self.color = {1, newGB, newGB, 1} end if self.timer < 0 then if self.state=="exists" then -- blow up love.audio.play("assets/sounds/sfx/box-disappear.wav", "static") self.state = "recovering" self.timer = 1.5 self.timesExploded = self.timesExploded + 1 self.body:destroy() elseif self.state=="recovering" then -- respawn love.audio.play("assets/sounds/sfx/box-reappear.wav", "static") self.state = "exists" -- timer has a shorter potental maximum each time. Goes down to a mimimum of 3 seconds, which probably isn't survivable. -- GOOD. They're not supposed to survive. muahahaha. Should just survive long enough to find it funny, then move onto the next level. -- Might be annoying if it's unfair though? But only if people care about getting a 'high score'. -- and the game doesn't even track score. So, I dunno. Hmm. This game's all about the ride, mmaann -- and if we want to use this exploding object somewhere else should make fuse shortening a tiled attribute... -- ... Should chat to Rory about it. self.timer = (3 + love.math.random(9)) - (self.timesExploded * 0.5) if self.timer < 3 then self.timer = 3 end self:resetPhysicsObject(world) self.color = {1, 1, 1, 1} end end end function ExplodingPlatform:draw() love.graphics.setColor(self:getColor()) if self.body and not self.body:isDestroyed() then self:drawRectangleObject(self) end love.graphics.setColor(1, 1, 1, 1) end return ExplodingPlatform
local status_ok, _ = pcall(require, "nvim-lsp-installer") if not status_ok then return end -- automatically install -- https://github.com/neovim/nvim-lspconfig/wiki/Installing-language-servers#automatically local servers = { "sumneko_lua", "rust_analyzer" } require("nvim-lsp-installer").setup({ ensure_installed = servers, -- ensure these servers are always installed automatic_installation = true, -- automatically detect which servers to install (based on which servers are set up via lspconfig) ui = { icons = { server_installed = "✓", server_pending = "➜", server_uninstalled = "✗" } } }) -- Setup lspconfig. for _, server in ipairs(servers) do local opts = { on_attach = require("rc/lsp/handlers").on_attach, capabilities = require("rc/lsp/handlers").capabilities } local has_custom_opts, server_custom_opts = pcall(require, "rc/lsp/settings." .. server) if has_custom_opts then opts = vim.tbl_deep_extend("force", opts, server_custom_opts) end require('lspconfig')[server].setup(opts) end
MATCH_STATES = { WARM_UP = 1, PREPARING = 2, IN_PROGRESS = 3, POST_TIME = 4, } GAME_MODE = { DEATHMATCH = 1, GUNGAME = 2 }
local utils = require("lib.utils") local cjson = require "cjson" local Assignment = require "assignment" local Experiment = {} function Experiment:new(inputs) return utils._new_(self, {}):init(inputs) end function Experiment:init(inputs) self.inputs = inputs self.exposureLogged = false self.salt = nil self._inExperiment = true self.name = self:getDefaultExperimentName() self.autoExposureLogging = true self:setup() self.assignment = Assignment:new(self:getSalt()) self.assigned = false return self end function Experiment:getDefaultExperimentName() return "GenericExperiment" end function Experiment:getDefaultParamNames() if self.__defaultParams == nil then local Capture = {} local me = self function Capture:set(key, val) table.insert(me.__defaultParams, key) end self.__defaultParams = {} local res, err = pcall(function() me.assign({}, Capture, {}) end) end return self.__defaultParams end function Experiment:requireAssignment() if not self.assigned then self:_assign() end end function Experiment:requireExposureLogging(paramName) if self:shouldLogExposure(paramName) then self:logExposure() end end function Experiment:_assign() self:configureLogger() local assigneVal = self:assign(self.assignment, self.inputs) self._inExperiment = assigneVal == nil or assigneVal ~= false self.assigned = true end function Experiment:setup() return end function Experiment:inExperiment() return self._inExperiment end function Experiment:addOverride(key, value) self.assignment:addOverride(key, value) end function Experiment:setOverrides(values) self.assignment:setOverrides(values) local obj = self.assignment:getOverrides() for k, v in pairs(obj) do self.inputs[k] = v end ----------------------------- end function Experiment:getSalt() return self.salt or self.name end function Experiment:setSalt(value) self.salt = value if self.assignment ~= nil then self.assignment.experimentSalt = value end end function Experiment:getName() return self.name end function Experiment:assign(param, args) error "Not implemented" end function Experiment:getParamNames() error "Not implemented" end function Experiment:shouldFetchExperimentParameter(name) local experimentalParams = self:getParamNames() return table.indexOf(experimentalParams, name) > 0 end function Experiment:setName(name) name = string.gsub(name, " ", "-") self.name = name if self.assignment ~= nil then self.assignment.experimentSalt = self:getSalt() end end function Experiment:__asBlob(extras) extras = extras or {} return table.merge(extras, { name = self:getName(), time = os.clock(), salt = self:getSalt(), inputs = self.inputs, params = self.assignment:getParams() }) end function Experiment:setAutoExposureLogging(value) self.autoExposureLogging = value end function Experiment:getParams() self:requireAssignment() self:requireExposureLogging() return self.assignment:getParams() end function Experiment:get(name, def) self:requireAssignment() self:requireExposureLogging(name) return self.assignment:get(name, def) end function Experiment:toString() self:requireAssignment() self:requireExposureLogging() return cjson.encode(self:__asBlob()) end function Experiment:logExposure(extras) if not self:inExperiment() then return end self.exposureLogged = true self:logEvent('exposure', extras) end function Experiment:shouldLogExposure(paramName) if paramName ~= nil and not self:shouldFetchExperimentParameter(paramName) then return false end return self.autoExposureLogging and not (self:previouslyLogged() ~= nil) end function Experiment:logEvent(eventType, extras) if not self:inExperiment() then return end local extraPayload = { event = eventType, extras_data = utils.shallowcopy(extras) } self:log(self:__asBlob(extraPayload)) end function Experiment:configureLogger() error "Not implemented" end function Experiment:log(data) error "Not implemented" end function Experiment:previouslyLogged() error "Not implemented" end return Experiment
-- customize how ever you like shared.stop = true wait(5) shared.stop = false local str = shared.scr or "qw[er]ty" local FinishTime = shared.ftime or 10 print("Finishing in",FinishTime/60,"minutes") local vs = game:GetService("VirtualUser") local nstr = string.gsub(str,"[[\]\n]","") local delay = shared.delay or FinishTime / (string.len(nstr) / 1.05) local queue = "" local rem = true for i=1, #str do if shared.stop == true then return end local c = str:sub(i,i) if c == "[" then rem = false continue elseif c == "]" then rem = true if string.find(queue," ") then for ii=1, #queue do local cc = queue:sub(ii,ii) vs:SetKeyDown(cc) wait(delay/2) vs:SetKeyUp(cc) end else for ii=1, #queue do local cc = queue:sub(ii,ii) vs:SetKeyDown(cc) wait() end wait() for ii=1, #queue do local cc = queue:sub(ii,ii) vs:SetKeyUp(cc) wait() end end queue = "" continue elseif c == " " then wait(delay) continue elseif c == "|" then wait(delay*2) continue end if not rem then queue=queue..c continue end vs:SetKeyDown(c) wait() vs:SetKeyUp(c) wait(delay) end
net.Receive("XYZ911:StartCall", function() local caller = net.ReadEntity() local callID = net.ReadUInt(32) local reason = net.ReadString() XYZ911.UI.Popup(caller, callID, reason) end) function XYZ911.UI.Popup(caller, callID, reason) local frame = XYZUI.Frame("911 Call #"..tostring(callID), XYZ911.Config.Color, nil, nil, true) frame:SetSize(400, 165) frame:SetPos((ScrW()*0.5) - (frame:GetWide()*0.5), ScrH() - (frame:GetTall()) - 5) local name = XYZUI.PanelText(frame, caller:Name() or "Unknown", 30, TEXT_ALIGN_CENTER) local reasonText = XYZUI.PanelText(frame, reason or "Unknown", 20, TEXT_ALIGN_CENTER) local button = XYZUI.ButtonInput(frame, "Take Call", function() net.Start("XYZ911:Respond") net.WriteUInt(callID, 32) net.SendToServer() frame:Close() end) button:Dock(BOTTOM) timer.Simple(XYZ911.Config.ClaimTime, function() if not IsValid(frame) then return end frame:Close() end) end
-- Mean to be a module dedicated to debugging create mode? local toolsController = require("tevgit:create/controllers/tool.lua") local uiController = require("tevgit:create/controllers/ui.lua") local uiTabController = require("tevgit:create/controllers/uiTabController.lua") uiController.devTab = uiController.createFrame(uiController.workshop.interface, { name = "devTab", size = guiCoord(1, 0, 0, 60), position = guiCoord(0,0,0,23) }, "mainTopBar") uiTabController.createTab(uiController.tabs, "Dev [ignore this]", uiController.devTab) toolsController.registerMenu("devTab", uiController.devTab) local reloadButton = toolsController.createButton("devTab", "fa:s-sync", "Reload all") reloadButton:mouseLeftReleased(function () engine.input.cursorTexture = "fa:s-mouse-pointer" uiController.workshop:reloadCreate() end) local gcWindow = uiController.createWindow(uiController.workshop.interface, guiCoord(0.5, -150, 0, 300), guiCoord(0, 300, 0, 93), "GC", true) --undockable window gcWindow.visible = false gcWindow.zIndex = 2000 local gcText = uiController.create("guiTextBox", gcWindow.content, { size = guiCoord(1,-20,1,-40), position = guiCoord(0,10,0,10), wrap = true }, "mainText") local gcnow = uiController.create("guiButton", gcWindow.content, { size = guiCoord(1,-20,0,20), position= guiCoord(0,10,1,-25), text = "collectgarbage()" }, "main") gcnow:mouseLeftReleased(function () collectgarbage() end) local garbageButton = toolsController.createButton("devTab", "fa:s-trash-alt", "GC") garbageButton:mouseLeftReleased(function () gcWindow.visible = not gcWindow.visible spawnThread(function () while gcWindow.visible do gcText.text = string.format("Memory Usage %.3f MB", collectgarbage( "count" ) / 1024) wait(.1) end end) end)
-- copy all globals into locals, some locals are prefixed with a G to reduce name clashes local coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,Gload,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require=coroutine,package,string,table,math,io,os,debug,assert,dofile,error,_G,getfenv,getmetatable,ipairs,load,loadfile,loadstring,next,pairs,pcall,print,rawequal,rawget,rawset,select,setfenv,setmetatable,tonumber,tostring,type,unpack,_VERSION,xpcall,module,require require("apps").default_paths() -- default search paths so things can easily be found local apps=require("apps") local lfs=require("lfs") local wstr=require("wetgenes.string") arg={...} lfs.chdir(apps.dir) if arg[1] then local m=require("cmd."..arg[1]) return m.cmd(unpack(arg)) else print("Available test commands are") print() for fname in lfs.dir("./lua/cmd") do if fname:sub(-4)==".lua" then print("./cmd "..fname:sub(1,-5)) end end print() end
local cassowary = require("cassowary") describe('cassowary.SimplexSolver', function () it('should be constructable without args', function () assert.is.truthy(cassowary.SimplexSolver()) end) end) describe("addEditVar", function () it("works with required strength", function () local solver = cassowary.SimplexSolver() local a = cassowary.Variable({name = "a"}) solver:addConstraint(cassowary.StayConstraint(a, cassowary.Strength.strong, 0)) solver:resolve() assert.equal(0, a.value) solver:addEditVar(a, cassowary.Strength.required) :beginEdit() :suggestValue(a, 2) :resolve() assert.is.equal(2, a.value) end) it("works with required strength after many suggestions", function () local solver = cassowary.SimplexSolver() local a = cassowary.Variable({name = "a"}) local b = cassowary.Variable({name = "b"}) solver:addConstraint(cassowary.StayConstraint(a, cassowary.Strength.strong, 0)) :addConstraint(cassowary.Equation(a,b,cassowary.Strength.required)) :resolve() assert.equal(0, b.value) assert.equal(0, a.value) solver:addEditVar(a, cassowary.Strength.required) :beginEdit() :suggestValue(a, 2) :resolve() assert.equal(2, a.value) assert.equal(2, b.value) solver:suggestValue(a, 10):resolve() assert.equal(10, a.value) assert.equal(10, b.value) end) it('works with weight', function () local x = cassowary.Variable({ name= 'x' }) local y = cassowary.Variable({ name= 'y' }) local solver = cassowary.SimplexSolver() solver:addStay(x):addStay(y):addConstraint(cassowary.Equation(x, y, cassowary.Strength.required)):addEditVar(x,cassowary.Strength.medium,1) solver:addEditVar(y, cassowary.Strength.medium,10):beginEdit() solver:suggestValue(x, 10):suggestValue(y, 20) solver:resolve() assert.is.truthy(cassowary.approx(x.value, 20)) assert.is.truthy(cassowary.approx(y.value, 20)) end) end)
local Label, Timer, AttackProperties, Damage, AttackRange, BulletProperties = Component.load({"Label", "Timer", "AttackProperties", "Damage", "AttackRange", "BulletProperties"}) DefaultAttackConstructors = {} function createPlayerAttack(parent) local entity = Entity(parent) local stats = parent:get("Stats") entity:add(Label("RangedAttack")) entity:add(Timer(stats:getShotDelay())) entity:add(AttackProperties(25)) entity:add(Damage(1)) entity:add(AttackRange(stats:getShotRange())) return entity end function DefaultAttackConstructors.BasicMeleeAttack(parent) local entity = Entity(parent) local level = parent:get("Level").level entity:add(Label("BasicMeleeAttack")) entity:add(Timer(1 - 0.25 * (level - 1))) entity:add(AttackProperties(0)) entity:add(Damage(level + 1)) entity:add(AttackRange(2)) Enemy.setSpeed(parent, level * 70 + 100) Enemy.addBonusHitpoints(parent,level * 10) return entity end function DefaultAttackConstructors.LightMeleeAttack(parent) local entity = Entity(parent) local level = parent:get("Level").level entity:add(Label("LightMeleeAttack")) entity:add(Timer(1 - 0.25 * (level - 1))) entity:add(AttackProperties(0)) entity:add(Damage(level)) entity:add(AttackRange(2)) Enemy.setSpeed(parent, level * 75 + 125) Enemy.addBonusHitpoints(parent,level * 5) return entity end function DefaultAttackConstructors.BasicRangedAttack(parent) local entity = Entity(parent) local level = parent:get("Level").level entity:add(Label("BasicRangedAttack")) entity:add(Timer(2 - 0.25 * (level - 1))) entity:add(AttackProperties(25)) entity:add(Damage(level)) entity:add(AttackRange(150 + level * 75)) entity:add(BulletProperties(level * 100 + 300, 7 + level)) Enemy.setSpeed(parent, level * 50 + 100) Enemy.addBonusHitpoints(parent, level * 5) return entity end function DefaultAttackConstructors.FastRangedAttack(parent) local entity = Entity(parent) local level = parent:get("Level").level entity:add(Label("FastRangedAttack")) entity:add(Timer(0.5 - 0.1 * (level - 1))) entity:add(AttackProperties(25)) entity:add(Damage(level)) entity:add(AttackRange(100 + level * 50)) entity:add(BulletProperties(level * 100 + 200, 5 + level)) Enemy.setSpeed(parent, level * 25 + 150) Enemy.addBonusHitpoints(parent, level * 5) return entity end function DefaultAttackConstructors.SniperRangedAttack(parent) local entity = Entity(parent) local level = parent:get("Level").level entity:add(Label("SniperRangedAttack")) entity:add(Timer(3 - 0.5 * (level - 1))) entity:add(AttackProperties(25)) entity:add(Damage(level + 2)) entity:add(AttackRange(500 + level * 100)) entity:add(BulletProperties(300 + level * 125, 7 + (2 *level))) Enemy.setSpeed(parent, level * 75) Enemy.addBonusHitpoints(parent, level * 5) return entity end function DefaultAttackConstructors.BigRangedAttack(parent) local entity = Entity(parent) local level = parent:get("Level").level entity:add(Label("BigRangedAttack")) entity:add(Timer(2 - 0.25 * (level - 1))) entity:add(AttackProperties(25)) entity:add(Damage(level * 2 + 1)) entity:add(AttackRange(400 + 100 * level)) entity:add(BulletProperties(200 + 75 * level, 10 + (5 * level))) Enemy.setSpeed(parent, level * 50 + 125) Enemy.addBonusHitpoints(parent, level * 7) return entity end function DefaultAttackConstructors.BasicDashAttack(parent) local entity = Entity(parent) local level = parent:get("Level").level entity:add(Label("BasicDashAttack")) entity:add(Timer(4 - 0.75 * (level - 1))) entity:add(AttackProperties(8)) entity:add(Damage(2 * level + 2)) entity:add(AttackRange(75 + 75 * level)) Enemy.setSpeed(parent, level * 50 + 125) Enemy.addBonusHitpoints(parent, level * 10) return entity end function DefaultAttackConstructors.SlowBigDashAttack(parent) local entity = Entity(parent) local level = parent:get("Level").level entity:add(Label("SlowBigDashAttack")) entity:add(AttackProperties(8)) entity:add(Timer(4.5 - level * 0.5)) entity:add(Damage(2 * level + 2)) entity:add(AttackRange(level * 200 + 250)) Enemy.setSpeed(parent, 20 + level * 10) Enemy.addBonusHitpoints(parent, level * 10) return entity end function DefaultAttackConstructors.SetTrap(parent) local entity = Entity(parent) local level = parent:get("Level").level entity:add(Label("SetTrap")) entity:add(Timer(6 - level * 1)) entity:add(Damage(level * 4 + 1)) Enemy.setSpeed(parent, level * 50 + 100) Enemy.addBonusHitpoints(parent, level * 15) return entity end
-- @namespace yatm.wrench local Directions = assert(foundation.com.Directions) local table_copy = assert(foundation.com.table_copy) yatm.wrench = {} yatm.wrench.ROTATE_FACE = 'face' yatm.wrench.ROTATE_AXIS = 'axis' -- Contains a table of all the supported paramtype2 that can be rotated yatm.wrench.type_handler = {} yatm.wrench.type_handler.flowingliquid = false yatm.wrench.type_handler.leveled = false -- debatable, but only used by plantlike and mesh yatm.wrench.type_handler.degrotate = false yatm.wrench.type_handler.meshoptions = false yatm.wrench.type_handler.color = false yatm.wrench.type_handler.glasslikeliquidlevel = false yatm.wrench.type_handler.colordegrotate = false yatm.wrench.type_handler.none = false local function rotate_facedir(rotate_type, facedir, reversed) if rotate_type == yatm.wrench.ROTATE_FACE then if reversed then facedir = Directions.rotate_facedir_face_anticlockwise(facedir) else facedir = Directions.rotate_facedir_face_clockwise(facedir) end elseif rotate_type == yatm.wrench.ROTATE_AXIS then if reversed then facedir = Directions.rotate_facedir_axis_anticlockwise(facedir) else facedir = Directions.rotate_facedir_axis_clockwise(facedir) end end return facedir end -- @mutative -- @spec type_handler.wallmounted(RotationType, Node, reversed: Boolean): Node function yatm.wrench.type_handler.wallmounted(rotate_type, node, reversed) -- TODO return node end -- @mutative -- @spec type_handler.facedir(RotationType, Node, reversed: Boolean): Node function yatm.wrench.type_handler.facedir(rotate_type, node, reversed) -- the original facedir value local facedir = rotate_facedir(rotate_type, node.param2, reversed) node.param2 = facedir return node end -- @mutative -- @spec type_handler.colorfacedir(RotationType, Node, reversed: Boolean): Node function yatm.wrench.type_handler.colorfacedir(rotate_type, node, reversed) -- the original facedir value local facedir = node.param2 % 32 local rest = node.param2 - 32 facedir = rotate_facedir(rotate_type, facedir, reversed) node.param2 = facedir + rest return node end -- @mutative -- @spec type_handler.colorwallmounted(RotationType, Node, reversed: Boolean): Node function yatm.wrench.type_handler.colorwallmounted(rotate_type, node, reversed) -- TODO return node end -- Triggered when a wrench or something wants to rotate the node, this function -- should return the updated node if any rotations should apply, -- or nil otherwise -- -- @mutative -- @spec calc_rotate_node(rotate_type: ROTATE_AXIS | ROTATE_FACE, pos: Vector3, node: Node, reverse: Boolean): Node | nil function yatm.wrench.calc_rotate_node(rotate_type, pos, node, reversed) local nodedef = minetest.registered_nodes[node.name] if nodedef.calc_rotate_node == false then return nil elseif type(nodedef.calc_rotate_node) == "function" then return nodedef.calc_rotate_node(rotate_type, pos, node, reversed) else local handler = yatm.wrench.type_handler[nodedef.paramtype2] if handler then return handler(rotate_type, node, reversed) end end return nil end -- Called when the wrench or caller is now going to commit to rotating the node -- the updated node is provided as new_node, while the original node is provided -- as old_node. -- -- Returns true if the node was successfully rotated, returns false otherwise. -- -- @spec rotate_node(pos: Vector3, new_node: Node, old_node: Node): Boolean function yatm.wrench.do_rotate_node(pos, new_node, old_node) local nodedef = minetest.registered_nodes[old_node.name] local do_rotate_node = nodedef.do_rotate_node if do_rotate_node == false then return false elseif type(do_rotate_node) == "function" then return do_rotate_node(pos, new_node, old_node) else minetest.swap_node(pos, new_node) return true end return false end function yatm.wrench.after_rotate_node(pos, node) local nodedef = minetest.registered_nodes[node.name] local after_rotate_node = nodedef.after_rotate_node if type(after_rotate_node) == "function" then return after_rotate_node(pos, node) end end function yatm.wrench.rotate_node(rotate_type, pos, node, reversed) local new_node = yatm.wrench.calc_rotate_node(rotate_type, pos, table_copy(node), reversed) if new_node then if yatm.wrench.do_rotate_node(pos, new_node, node) then yatm.wrench.after_rotate_node(pos, new_node) return true end end return false end function yatm.wrench.rotate_node_at_pos(rotate_type, pos, reversed) local node = minetest.get_node_or_nil(pos) if node then return yatm.wrench.rotate_node(rotate_type, pos, node, reversed) end return false end function yatm.wrench.user_rotate_node_at_pos(user, rotate_type, pos, reversed) local player_name if user then player_name = user:get_player_name() end if minetest.is_protected(pos, player_name) then minetest.record_protection_violation(pos, player_name) return false end return yatm.wrench.rotate_node_at_pos(rotate_type, pos, reversed) end
local PART = {} PART.ClassName = "light" PART.Group = 'effects' PART.Icon = 'icon16/lightbulb.png' pac.StartStorableVars() pac.GetSet(PART, "Brightness", 1) pac.GetSet(PART, "Size", 5, {editor_sensitivity = 0.25}) pac.GetSet(PART, "Style", 0, {editor_clamp = {0, 16}}) pac.GetSet(PART, "Color", Vector(255, 255, 255), {editor_panel = "color"}) pac.EndStorableVars() function PART:GetNiceName() local hue = pac.ColorToNames(self:GetColor()) return hue .. " light" end local DynamicLight = DynamicLight function PART:OnDraw(owner, pos, ang) local light = self.light or DynamicLight(tonumber(self.UniqueID)) light.Pos = pos light.MinLight = self.Brightness light.Size = self.Size light.Style = self.Style light.r = self.Color.r light.g = self.Color.g light.b = self.Color.b -- 100000000 constant is better than calling pac.RealTime light.DieTime = 1000000000000 -- pac.RealTime self.light = light end function PART:OnHide() local light = self.light if light then light.DieTime = 0 light.Size = 0 light.MinLight = 0 light.Pos = Vector() end end pac.RegisterPart(PART)
-- TODO: implement in-place version of functions require 'randomkit' require 'cephes' require 'torch' if not distributions.gamma then distributions.gamma = {} end function distributions.gamma.entropy(params) assert(params.shape) assert(params.scale or params.rate) if params.scale then local k = params.shape local t = params.scale return k + math.log(t) + cephes.lgam(k) + (1-k)*cephes.digamma(k) elseif params.rate then local a = params.shape local b = params.rate return a - math.log(b) + cephes.lgam(a) + (1-a)*cephes.digamma(a) end end function distributions.gamma.kl(q,p) if q.scale then if p.scale then return (q.shape - p.shape) * cephes.digamma(q.shape) - q.shape + q.shape * q.scale / p.scale + cephes.lgam(p.shape) - cephes.lgam(q.shape) + p.shape * math.log(p.scale) - p.shape * math.log(q.scale) elseif p.rate then return (q.shape - p.shape) * cephes.digamma(q.shape) - q.shape + q.shape * q.scale * p.rate + cephes.lgam(p.shape) - cephes.lgam(q.shape) - p.shape * math.log(p.rate) - p.shape * math.log(q.scale) end elseif q.rate then if p.scale then return (q.shape - p.shape) * cephes.digamma(q.shape) - q.shape + q.shape / q.rate / p.scale + cephes.lgam(p.shape) - cephes.lgam(q.shape) + p.shape * math.log(p.scale) + p.shape * math.log(q.rate) elseif p.rate then return (q.shape - p.shape) * cephes.digamma(q.shape) - q.shape + q.shape * p.rate / q.rate + cephes.lgam(p.shape) - cephes.lgam(q.shape) - p.shape * math.log(p.rate) + p.shape * math.log(q.rate) end end end
local granite = { {"granite", "Granite grigio"}, {"graniteR", "Granite ruggine"}, {"graniteA", "Granite avorio"}, {"graniteP", "Granite rosa"}, } local stairs_mod = minetest.get_modpath("stairs") local stairsplus_mod = minetest.get_modpath("moreblocks") and minetest.global_exists("stairsplus") for _, granite in pairs(granite) do if stairsplus_mod then stairsplus:register_all("summer", granite[1], "summer:" .. granite[1], { description = granite[2] .. " Summer", tiles = {granite[1] .. ".png"}, groups = {cracky = 3}, sounds = default.node_sound_stone_defaults(), }) stairsplus:register_alias_all("summer", granite[1], "summer", granite[1]) minetest.register_alias("stairs:slab_summer_".. granite[1], "summer:slab_baked_granite_" .. granite[1]) minetest.register_alias("stairs:stair_summer_".. granite[1], "summer:stair_baked_granite_" .. granite[1]) -- register all stair types for stairs redo elseif stairs_mod and stairs.mod then stairs.register_all("summer_" .. granite[1], "summer:" .. granite[1], {cracky = 3}, {granite[1] .. ".png"}, granite[2] .. " Summer", default.node_sound_stone_defaults()) -- register stair and slab using default stairs elseif stairs_mod then stairs.register_stair_and_slab("summer_".. granite[1], "summer:".. granite[1], {cracky = 3}, {granite[1] .. ".png"}, granite[2] .. " Summer Stair", granite[2] .. " Summer Slab", default.node_sound_stone_defaults()) end end
--[[ GetIndexOfValue =============== Super simple helper function to get the index of a value in a table. This is primarily used in conjunction with table.remove, as we will sometimes know the value of an item, but not its index. This allows us to pass in the value, get the index, and then remove that value from the table. Note that this only works on index-value tables (arrays), not key-value (dictionaries). Usage ----- local t = { "this", "table", "has", "a", "lot", "of", "values" } local index = getIndexOfValue("values", t) print(t[index] == "values") -- true table.remove(t, index) print(t[index] == nil) -- true --]] local function getIndexOfValue(value, list) for index, otherValue in ipairs(list) do if value == otherValue then return index end end end return getIndexOfValue
-------------------------------------------------------------------------------- --[[ Hose Demonstrates use of cycleAngle to wave back and forth. --]] -------------------------------------------------------------------------------- local CBE = require("CBE.CBE") local display_newImageRect = display.newImageRect local vent = CBE.newVent({ preset = "fountain", perEmit = 1, physics = { autoCalculateAngles = true, angles = {{60, 120}, {120, 60}}, -- Add angles in form of 60-120-60 cycleAngle = true } }) vent:start()
local core = require "sys.core" local ns = require "sys.netstream" local assert = assert --when luaVM destroyed, all process will be exit --so no need to clear socket connection local socket_pool = {} local socket = {} local EVENT = {} local type = type local assert = assert local function new_socket(fd) local s = { fd = fd, delim = false, co = false, closing = false, sbuffer = ns.new(fd), } assert(not socket_pool[fd]) socket_pool[fd] = s end local function del_socket(s) ns.free(s.sbuffer) socket_pool[s.fd] = nil end local function suspend(s) assert(not s.co) local co = core.running() s.co = co return core.wait(co) end local function wakeup(s, dat) local co = s.co s.co = false core.wakeup(co, dat) end function EVENT.accept(fd, _, portid, addr) local lc = socket_pool[portid]; new_socket(fd) local ok, err = core.pcall(lc.disp, fd, addr) if not ok then core.log(err) socket.close(fd) end end function EVENT.close(fd, _, errno) local s = socket_pool[fd] if s == nil then return end s.closing = true if s.co then wakeup(s, false) del_socket(s) end end function EVENT.data(fd, message) local s = socket_pool[fd] if not s then return end local sbuffer = s.sbuffer local size = ns.push(sbuffer, message) local delim = s.delim local typ = type(delim) if typ == "number" then if size >= delim then local dat = ns.read(sbuffer, delim) s.delim = false wakeup(s, dat) end else if typ == "string" then local dat = ns.readline(sbuffer, delim) if dat then s.delim = false wakeup(s, dat) return end end end end local function socket_dispatch(typ, fd, message, ...) EVENT[typ](fd, message, ...) end function socket.listen(port, disp, backlog) assert(port) assert(disp) local portid = core.listen(port, socket_dispatch, backlog) if portid then socket_pool[portid] = { fd = portid, disp = disp, co = false } end return portid end function socket.connect(ip, bind) local fd = core.connect(ip, socket_dispatch, bind) if fd then assert(fd >= 0) new_socket(fd) end return fd end function socket.limit(fd, limit) local s = socket_pool[fd] if s == nil then return false end return ns.limit(s.sbuffer, limit) end function socket.close(fd) local s = socket_pool[fd] if s == nil then return false end if s.co then wakeup(s, false) end del_socket(s) core.close(fd) return true end function socket.read(fd, n) local s = socket_pool[fd] if not s then return false end local r = ns.read(s.sbuffer, n) if r then return r end if s.closing then del_socket(s) return false end s.delim = n return suspend(s) end function socket.readall(fd, max) local s = socket_pool[fd] if not s then return false end local r = ns.readall(s.sbuffer, max) if r == "" and s.closing then del_socket(s) return false end return r end function socket.readline(fd, delim) delim = delim or "\n" local s = socket_pool[fd] if not s then return false end local r = ns.readline(s.sbuffer, delim) if r then return r end if s.closing then del_socket(s) return false end s.delim = delim return suspend(s) end function socket.recvsize(fd) local s = socket_pool[fd] if not s then return 0 end return ns.size(s.sbuffer) end socket.write = core.write socket.sendsize = core.sendsize ---------udp local function new_udp(fd, callback) local s = { fd = fd, callback = callback, } socket_pool[fd] = s end --udp client can be closed(because it use connect) local function udp_dispatch(typ, fd, message, addr) local data local cb = socket_pool[fd].callback if typ == "udp" then data = ns.todata(message) cb(data, addr) elseif typ == "close" then cb() socket_pool[fd] = nil else assert(false, "type must be 'udp' or 'close'") end end function socket.bind(addr, callback) local fd = core.bind(addr, udp_dispatch) if fd then new_udp(fd, callback) end return fd end function socket.udp(addr, callback, bindip) local fd = core.udp(addr, udp_dispatch, bindip) if fd then new_udp(fd, callback) end return fd end socket.udpwrite = core.udpwrite return socket
---@type cocodec local cocodec = require "colibc.codec" return cocodec
#!/usr/bin/env lua --[[ This requires the restserver-xavante rock to run. run server (this file) th tools/rest_translation_server.lua -model ../Recipes/baseline-1M-enfr/exp/model-baseline-1M-enfr_epoch13_3.44.t7 -gpuid 1 query the server: curl -v -H "Content-Type: application/json" -X POST -d '[{ "src" : "international migration" }]' http://127.0.0.1:7784/translator/translate ]] require('onmt.init') local tokenizer = require('tools.utils.tokenizer') local BPE = require ('tools.utils.BPE') local restserver = require("tools.restserver.restserver") local cmd = onmt.utils.ExtendedCmdLine.new('rest_translation_server.lua') local options = { { '-host', '127.0.0.1', [[Host to run the server on.]] }, { '-port', '7784', [[Port to run the server on.]] }, { '-withAttn', false, [[If set returns by default attn vector.]] } } cmd:setCmdLineOptions(options, 'Server') onmt.translate.Translator.declareOpts(cmd) onmt.utils.Cuda.declareOpts(cmd) onmt.utils.Logger.declareOpts(cmd) tokenizer.declareOpts(cmd) onmt.utils.HookManager.updateOpt(arg, cmd) onmt.utils.HookManager.declareOpts(cmd) cmd:text("") cmd:text("Other options") cmd:text("") cmd:option('-batch_size', 64, [[Size of each parallel batch - you should not change except if low memory.]]) local opt = cmd:parse(arg) local function translateMessage(translator, lines) local bpe local res local err _G.logger:debug("Start Tokenization") if opt.bpe_model ~= '' then bpe = BPE.new(opt) end local i = 1 local translations = {} while i <= #lines do local batch = {} while i <= #lines and #batch < opt.batch_size do local srcTokens = {} local srcTokenized = {} local tokens res, err = pcall(function() local preprocessed = _G.hookManager:call("mpreprocess", opt, lines[i].src) or lines[i].src tokens = tokenizer.tokenize(opt, preprocessed, bpe) end) -- it can generate an exception if there are utf-8 issues in the text if not res then if string.find(err, "interrupted") then error("interrupted") else error("unicode error in line " .. err) end end -- Add custom source features if they are provided in the request. This is usually used for domain control. if lines[i].feats then for j = 1, #tokens do for _, feat in ipairs(lines[i].feats) do if feat ~= '' then tokens[j] = tokens[j] .. '│' .. feat end end end end table.insert(srcTokenized, table.concat(tokens, ' ')) -- Extract from the line. for word in srcTokenized[1]:gmatch'([^%s]+)' do table.insert(srcTokens, word) end -- Currently just a single batch. table.insert(batch, translator:buildInput(srcTokens)) i = i + 1 end -- Translate _G.logger:debug("Start Translation") local results = translator:translate(batch) _G.logger:debug("End Translation") -- Return the nbest translations for each in the batch. for b = 1, #batch do local ret = {} for bi = 1, translator.args.n_best do local srcSent = translator:buildOutput(batch[b]) local predSent res, err = pcall(function() predSent = tokenizer.detokenize(opt, results[b].preds[bi].words, results[b].preds[bi].features) end) if not res then if string.find(err,"interrupted") then error("interrupted") else error("unicode error in line ".. err) end end local lineres = { tgt = predSent, src = srcSent, n_best = bi, pred_score = results[b].preds[bi].score } if opt.withAttn or lines[b].withAttn then local attnTable = {} for j = 1, #results[b].preds[bi].attention do table.insert(attnTable, results[b].preds[bi].attention[j]:totable()) end lineres.attn = attnTable end table.insert(ret, lineres) end table.insert(translations, ret) end end return translations end local function init_server(host, port, translator) local server = restserver:new():host(host):port(port) server:add_resource("translator", { { method = "POST", path = "/translate", consumes = "application/json", produces = "application/json", handler = function(req) _G.logger:debug("receiving request") local translate = translateMessage(translator, req) _G.logger:debug("sending response") return restserver.response():status(200):entity(translate) end, } }) return server end local function main() -- load logger _G.logger = onmt.utils.Logger.new(opt.log_file, opt.disable_logs, opt.log_level, opt.log_tag) onmt.utils.Cuda.init(opt) _G.hookManager = onmt.utils.HookManager.new(opt) -- disable profiling _G.profiler = onmt.utils.Profiler.new(false) _G.logger:info("Loading model") local translator = onmt.translate.Translator.new(opt) _G.logger:info("Launch server") local server = init_server(opt.host, opt.port, translator) -- This loads the restserver.xavante plugin server:enable("restserver.xavante"):start() end main()
local branch_prob = 190 local n2 = { name = "default:ladder_wood", param2 = 4, force_place=true } local n6 = { name = "stairs:stair_inner_junglewood", param2 = 3, force_place=true } local n7 = { name = "stairs:stair_junglewood", param2 = 2, force_place=true } local n8 = { name = "stairs:stair_inner_junglewood", param2 = 2, force_place=true } local n9 = { name = "default:fence_junglewood", force_place=true } local n10 = { name = "default:fence_rail_junglewood", force_place=true } local n11 = { name = "stairs:stair_outer_junglewood", param2 = 22, force_place=true } local n12 = { name = "stairs:slab_junglewood", param2 = 21, force_place=true } local n13 = { name = "stairs:stair_junglewood", param2 = 22, force_place=true } local n14 = { name = "stairs:stair_outer_junglewood", param2 = 23, force_place=true } local n17 = { name = "default:jungletree", force_place=true } local n19 = { name = "stairs:stair_junglewood", param2 = 3, force_place=true } local n20 = { name = "stairs:slab_junglewood", param2 = 1, force_place=true } local n21 = { name = "doors:trapdoor", force_place=true } local n22 = { name = "stairs:stair_junglewood", param2 = 1, force_place=true } local n26 = { name = "default:torch_wall", param2 = 2, force_place=true } local n27 = { name = "stairs:stair_junglewood", param2 = 21, force_place=true } local n29 = { name = "default:junglewood", force_place=true } local n30 = { name = "beds:bed_bottom", param2 = 1, force_place=true } local n31 = { name = "beds:bed_top", param2 = 1, force_place=true } local n32 = { name = "stairs:stair_inner_junglewood", force_place=true } local n33 = { name = "stairs:stair_junglewood", force_place=true } local n34 = { name = "stairs:stair_inner_junglewood", param2 = 1, force_place=true } local n35 = { name = "stairs:stair_outer_junglewood", param2 = 21, force_place=true } local n36 = { name = "stairs:stair_junglewood", param2 = 20, force_place=true } local n37 = { name = "stairs:stair_outer_junglewood", param2 = 20, force_place=true } local n23 = { name = "air", force_place=true } local n3 = { name = "default:jungleleaves", prob=222 } local n15 = { name = "default:jungleleaves", prob=190 } local n24 = { name = "default:jungletree", prob=126, force_place=true } -- non-force-place local n5 = { name = "default:jungleleaves" } local n16 = { name = "default:jungletree" } local n1 = { name = "air", prob=0 } return { yslice_prob = { {ypos=0}, {ypos=1}, {ypos=2}, {ypos=3}, {ypos=4}, {ypos=5}, {ypos=6, prob=branch_prob}, {ypos=7, prob=branch_prob}, {ypos=8, prob=branch_prob}, {ypos=9, prob=branch_prob}, {ypos=10, prob=branch_prob}, {ypos=11}, {ypos=12}, {ypos=13}, {ypos=14}, {ypos=15}, {ypos=16}, }, size = {x = 5, y = 17, z = 5}, data = { -- z=0, y=0 n1, n1, n1, n1, n1, -- z=0, y=1 n1, n1, n2, n1, n1, -- z=0, y=2 n1, n1, n1, n1, n1, -- z=0, y=3 n1, n1, n1, n1, n1, -- z=0, y=4 n1, n1, n1, n1, n1, -- z=0, y=5 n1, n1, n1, n1, n1, -- z=0, y=6 n3, n5, n3, n1, n1, -- z=0, y=7 n1, n1, n3, n5, n3, -- z=0, y=8 n1, n1, n1, n1, n1, -- z=0, y=9 n1, n1, n1, n1, n1, -- z=0, y=10 n3, n5, n3, n1, n1, -- z=0, y=11 n6, n7, n7, n7, n8, -- z=0, y=12 n9, n10, n9, n10, n9, -- z=0, y=13 n11, n12, n13, n12, n14, -- z=0, y=14 n15, n3, n3, n3, n15, -- z=0, y=15 n15, n3, n3, n3, n15, -- z=0, y=16 n1, n1, n1, n1, n1, -- z=1, y=0 n1, n1, n16, n1, n1, -- z=1, y=1 n1, n1, n17, n1, n1, -- z=1, y=2 n1, n1, n2, n1, n1, -- z=1, y=3 n1, n1, n2, n1, n1, -- z=1, y=4 n1, n1, n2, n1, n1, -- z=1, y=5 n1, n1, n2, n1, n1, -- z=1, y=6 n5, n17, n2, n1, n1, -- z=1, y=7 n1, n1, n2, n17, n5, -- z=1, y=8 n1, n1, n2, n1, n1, -- z=1, y=9 n1, n1, n2, n1, n1, -- z=1, y=10 n5, n17, n2, n1, n1, -- z=1, y=11 n19, n20, n21, n20, n22, -- z=1, y=12 n10, n23, n23, n23, n10, -- z=1, y=13 n12, n12, n12, n12, n12, -- z=1, y=14 n3, n17, n5, n17, n3, -- z=1, y=15 n3, n5, n5, n5, n3, -- z=1, y=16 n1, n3, n3, n3, n1, -- z=2, y=0 n1, n16, n16, n16, n1, -- z=2, y=1 n1, n17, n17, n17, n1, -- z=2, y=2 n1, n24, n17, n24, n1, -- z=2, y=3 n1, n1, n17, n1, n1, -- z=2, y=4 n1, n1, n17, n1, n1, -- z=2, y=5 n1, n1, n17, n1, n1, -- z=2, y=6 n3, n5, n17, n1, n1, -- z=2, y=7 n1, n1, n17, n5, n3, -- z=2, y=8 n1, n1, n17, n5, n3, -- z=2, y=9 n3, n5, n17, n1, n1, -- z=2, y=10 n3, n5, n17, n1, n1, -- z=2, y=11 n19, n20, n17, n20, n22, -- z=2, y=12 n9, n26, n17, n23, n9, -- z=2, y=13 n27, n12, n17, n12, n27, -- z=2, y=14 n3, n5, n5, n5, n3, -- z=2, y=15 n3, n5, n5, n5, n3, -- z=2, y=16 n1, n3, n5, n3, n1, -- z=3, y=0 n1, n1, n16, n1, n1, -- z=3, y=1 n1, n1, n17, n1, n1, -- z=3, y=2 n1, n1, n24, n1, n1, -- z=3, y=3 n1, n1, n1, n1, n1, -- z=3, y=4 n1, n1, n1, n1, n1, -- z=3, y=5 n1, n1, n1, n1, n1, -- z=3, y=6 n1, n1, n1, n1, n1, -- z=3, y=7 n1, n1, n1, n1, n1, -- z=3, y=8 n1, n1, n5, n17, n5, -- z=3, y=9 n5, n17, n5, n1, n1, -- z=3, y=10 n1, n1, n1, n1, n1, -- z=3, y=11 n19, n20, n29, n29, n22, -- z=3, y=12 n10, n23, n30, n31, n10, -- z=3, y=13 n12, n12, n12, n12, n12, -- z=3, y=14 n3, n17, n5, n17, n3, -- z=3, y=15 n3, n5, n5, n5, n3, -- z=3, y=16 n1, n3, n3, n3, n1, -- z=4, y=0 n1, n1, n1, n1, n1, -- z=4, y=1 n1, n1, n1, n1, n1, -- z=4, y=2 n1, n1, n1, n1, n1, -- z=4, y=3 n1, n1, n1, n1, n1, -- z=4, y=4 n1, n1, n1, n1, n1, -- z=4, y=5 n1, n1, n1, n1, n1, -- z=4, y=6 n1, n1, n1, n1, n1, -- z=4, y=7 n1, n1, n1, n1, n1, -- z=4, y=8 n1, n1, n3, n5, n3, -- z=4, y=9 n3, n5, n3, n1, n1, -- z=4, y=10 n1, n1, n1, n1, n1, -- z=4, y=11 n32, n33, n33, n33, n34, -- z=4, y=12 n9, n10, n9, n10, n9, -- z=4, y=13 n35, n12, n36, n12, n37, -- z=4, y=14 n15, n3, n3, n3, n15, -- z=4, y=15 n15, n3, n3, n3, n15, -- z=4, y=16 n1, n1, n1, n1, n1, } }
Config = {} Config.Font = 'Montserrat' -- ฟ้อนท์ข้อความ Config.PositionX = 0.850 -- ตำแหน่งข้อความ X Config.PositionY = 0.530 -- ตำแหน่งข้อความ Y Config.ShowNotifyInSafeZone = "<b style='color:#1E90FF'>Bạn đã vào Đảo Khỉ" -- แจ้งเตือนเวลาเข้าเซฟโซน Config.ShowNotifyOutSafeZone = "<b style='color:red'>Bạn đã rời khỏi Đảo Khỉ" -- แจ้งเตือนเวลาออกเซฟโซน Config.Blips = { ["Đảo Khỉ"] = { x = 5128.4658203125, y = -4924.3676757813, z = 15.700043678284, --5128.4658203125, y = -4924.3676757813, z = 15.700043678284 Size = 1300.0, Color = 51, Alpha = 180, notifIn = false, notifOut = false, revive = true, allowWeapon = "Được Phép Sử Dụng Súng" } } Config.TargetZone = { ["Điểm 1"] = { x = 5007.9545898438, y = -4543.2392578125, z = 8.9128198623657, Size = 10.0, Color = 51, Alpha = 180, notifIn = false, notifOut = false, revive = true, allowWeapon = "Được Phép Sử Dụng Súng" } } Config.WeaponGroup = { ['Cận Chiến'] = { [GetHashKey("WEAPON_DAGGER")] = true, [GetHashKey("WEAPON_BAT")] = true, [GetHashKey("WEAPON_BOTTLE")] = true, [GetHashKey("WEAPON_CROWBAR")] = true, [GetHashKey("WEAPON_UNARMED")] = true, [GetHashKey("WEAPON_FLASHLIGHT")] = true, [GetHashKey("WEAPON_GOLFCLUB")] = true, [GetHashKey("WEAPON_HAMMER")] = true, [GetHashKey("WEAPON_HATCHET")] = true, [GetHashKey("WEAPON_KNUCKLE")] = true, [GetHashKey("WEAPON_KNIFE")] = true, [GetHashKey("WEAPON_MACHETE")] = true, [GetHashKey("WEAPON_SWITCHBLADE")] = true, [GetHashKey("WEAPON_NIGHTSTICK")] = true, [GetHashKey("WEAPON_WRENCH")] = true, [GetHashKey("WEAPON_BATTLEAXE")] = true, [GetHashKey("WEAPON_POOLCUE")] = true, [GetHashKey("WEAPON_STONE_HATCHET")] = true, [GetHashKey("WEAPON_KATANA")] = true, }, ['Được Phép Sử Dụng Súng'] = { all = true } } conf = { safeZoneCoordMoveSpeed = 0.002, safeZoneRadiusMoveSpeed = 0.002, color = {r = 255, g = 0, b = 0, a = 200} } Config.WeaponNames = { [tostring(GetHashKey('WEAPON_UNARMED'))] = 'Unarmed', [tostring(GetHashKey('GADGET_PARACHUTE'))] = 'Parachute', [tostring(GetHashKey('WEAPON_KNIFE'))] = 'Knife', [tostring(GetHashKey('WEAPON_NIGHTSTICK'))] = 'Nightstick', [tostring(GetHashKey('WEAPON_HAMMER'))] = 'Hammer', [tostring(GetHashKey('WEAPON_BAT'))] = 'Baseball Bat', [tostring(GetHashKey('WEAPON_CROWBAR'))] = 'Crowbar', [tostring(GetHashKey('WEAPON_GOLFCLUB'))] = 'Golf Club', [tostring(GetHashKey('WEAPON_BOTTLE'))] = 'Bottle', [tostring(GetHashKey('WEAPON_DAGGER'))] = 'Antique Cavalry Dagger', [tostring(GetHashKey('WEAPON_HATCHET'))] = 'Hatchet', [tostring(GetHashKey('WEAPON_KNUCKLE'))] = 'Knuckle Duster', [tostring(GetHashKey('WEAPON_MACHETE'))] = 'Machete', [tostring(GetHashKey('WEAPON_FLASHLIGHT'))] = 'Flashlight', [tostring(GetHashKey('WEAPON_SWITCHBLADE'))] = 'Switchblade', [tostring(GetHashKey('WEAPON_BATTLEAXE'))] = 'Battleaxe', [tostring(GetHashKey('WEAPON_POOLCUE'))] = 'Poolcue', [tostring(GetHashKey('WEAPON_PIPEWRENCH'))] = 'Wrench', [tostring(GetHashKey('WEAPON_STONE_HATCHET'))] = 'Stone Hatchet', [tostring(GetHashKey('WEAPON_PISTOL'))] = 'Pistol', [tostring(GetHashKey('WEAPON_PISTOL_MK2'))] = 'Pistol Mk2', [tostring(GetHashKey('WEAPON_COMBATPISTOL'))] = 'Combat Pistol', [tostring(GetHashKey('WEAPON_PISTOL50'))] = 'Pistol .50 ', [tostring(GetHashKey('WEAPON_SNSPISTOL'))] = 'SNS Pistol', [tostring(GetHashKey('WEAPON_SNSPISTOL_MK2'))] = 'SNS Pistol Mk2', [tostring(GetHashKey('WEAPON_HEAVYPISTOL'))] = 'Heavy Pistol', [tostring(GetHashKey('WEAPON_VINTAGEPISTOL'))] = 'Vintage Pistol', [tostring(GetHashKey('WEAPON_MARKSMANPISTOL'))] = 'Marksman Pistol', [tostring(GetHashKey('WEAPON_REVOLVER'))] = 'Heavy Revolver', [tostring(GetHashKey('WEAPON_REVOLVER_MK2'))] = 'Heavy Revolver Mk2', [tostring(GetHashKey('WEAPON_DOUBLEACTION'))] = 'Double-Action Revolver', [tostring(GetHashKey('WEAPON_APPISTOL'))] = 'AP Pistol', [tostring(GetHashKey('WEAPON_STUNGUN'))] = 'Stun Gun', [tostring(GetHashKey('WEAPON_FLAREGUN'))] = 'Flare Gun', [tostring(GetHashKey('WEAPON_RAYPISTOL'))] = 'Up-n-Atomizer', [tostring(GetHashKey('WEAPON_MICROSMG'))] = 'Micro SMG', [tostring(GetHashKey('WEAPON_MACHINEPISTOL'))] = 'Machine Pistol', [tostring(GetHashKey('WEAPON_MINISMG'))] = 'Mini SMG', [tostring(GetHashKey('WEAPON_SMG'))] = 'SMG', [tostring(GetHashKey('WEAPON_SMG_MK2'))] = 'SMG Mk2 ', [tostring(GetHashKey('WEAPON_ASSAULTSMG'))] = 'Assault SMG', [tostring(GetHashKey('WEAPON_COMBATPDW'))] = 'Combat PDW', [tostring(GetHashKey('WEAPON_MG'))] = 'MG', [tostring(GetHashKey('WEAPON_COMBATMG'))] = 'Combat MG ', [tostring(GetHashKey('WEAPON_COMBATMG_MK2'))] = 'Combat MG Mk2', [tostring(GetHashKey('WEAPON_GUSENBERG'))] = 'Gusenberg Sweeper', [tostring(GetHashKey('WEAPON_RAYCARBINE'))] = 'Unholy Deathbringer', [tostring(GetHashKey('WEAPON_ASSAULTRIFLE'))] = 'Assault Rifle', [tostring(GetHashKey('WEAPON_ASSAULTRIFLE_MK2'))] = 'Assault Rifle Mk2', [tostring(GetHashKey('WEAPON_CARBINERIFLE'))] = 'Carbine Rifle', [tostring(GetHashKey('WEAPON_CARBINERIFLE_MK2'))] = 'Carbine Rifle Mk2', [tostring(GetHashKey('WEAPON_ADVANCEDRIFLE'))] = 'Advanced Rifle', [tostring(GetHashKey('WEAPON_SPECIALCARBINE'))] = 'Special Carbine', [tostring(GetHashKey('WEAPON_SPECIALCARBINE_MK2'))] = 'Special Carbine Mk2', [tostring(GetHashKey('WEAPON_BULLPUPRIFLE'))] = 'Bullpup Rifle', [tostring(GetHashKey('WEAPON_BULLPUPRIFLE_MK2'))] = 'Bullpup Rifle Mk2', [tostring(GetHashKey('WEAPON_COMPACTRIFLE'))] = 'Compact Rifle', [tostring(GetHashKey('WEAPON_SNIPERRIFLE'))] = 'Sniper Rifle', [tostring(GetHashKey('WEAPON_HEAVYSNIPER'))] = 'Heavy Sniper', [tostring(GetHashKey('WEAPON_HEAVYSNIPER_MK2'))] = 'Heavy Sniper Mk2', [tostring(GetHashKey('WEAPON_MARKSMANRIFLE'))] = 'Marksman Rifle', [tostring(GetHashKey('WEAPON_MARKSMANRIFLE_MK2'))] = 'Marksman Rifle Mk2', [tostring(GetHashKey('WEAPON_GRENADE'))] = 'Bom nổ', [tostring(GetHashKey('WEAPON_STICKYBOMB'))] = 'Sticky Bomb', [tostring(GetHashKey('WEAPON_PROXMINE'))] = 'Proximity Mine', [tostring(GetHashKey('WAPAON_PIPEBOMB'))] = 'Pipe Bomb', [tostring(GetHashKey('WEAPON_SMOKEGRENADE'))] = 'Tear Gas', [tostring(GetHashKey('WEAPON_BZGAS'))] = 'BZ Gas', [tostring(GetHashKey('WEAPON_MOLOTOV'))] = 'Molotov', [tostring(GetHashKey('WEAPON_FIREEXTINGUISHER'))] = 'Fire Extinguisher', [tostring(GetHashKey('WEAPON_PETROLCAN'))] = 'Jerry Can', [tostring(GetHashKey('WEAPON_BALL'))] = 'Ball', [tostring(GetHashKey('WEAPON_SNOWBALL'))] = 'Snowball', [tostring(GetHashKey('WEAPON_FLARE'))] = 'Flare', [tostring(GetHashKey('WEAPON_GRENADELAUNCHER'))] = 'Grenade Launcher', [tostring(GetHashKey('WEAPON_RPG'))] = 'RPG', [tostring(GetHashKey('WEAPON_MINIGUN'))] = 'Minigun', [tostring(GetHashKey('WEAPON_FIREWORK'))] = 'Firework Launcher', [tostring(GetHashKey('WEAPON_RAILGUN'))] = 'Railgun', [tostring(GetHashKey('WEAPON_HOMINGLAUNCHER'))] = 'Homing Launcher', [tostring(GetHashKey('WEAPON_COMPACTLAUNCHER'))] = 'Compact Grenade Launcher', [tostring(GetHashKey('WEAPON_RAYMINIGUN'))] = 'Widowmaker', [tostring(GetHashKey('WEAPON_PUMPSHOTGUN'))] = 'Pump Shotgun', [tostring(GetHashKey('WEAPON_PUMPSHOTGUN_MK2'))] = 'Pump Shotgun Mk2', [tostring(GetHashKey('WEAPON_SAWNOFFSHOTGUN'))] = 'Sawed-off Shotgun', [tostring(GetHashKey('WEAPON_BULLPUPSHOTGUN'))] = 'Bullpup Shotgun', [tostring(GetHashKey('WEAPON_ASSAULTSHOTGUN'))] = 'Assault Shotgun', [tostring(GetHashKey('WEAPON_MUSKET'))] = 'Musket', [tostring(GetHashKey('WEAPON_HEAVYSHOTGUN'))] = 'Heavy Shotgun', [tostring(GetHashKey('WEAPON_DBSHOTGUN'))] = 'Double Barrel Shotgun', [tostring(GetHashKey('WEAPON_SWEEPERSHOTGUN'))] = 'Sweeper Shotgun', [tostring(GetHashKey('WEAPON_REMOTESNIPER'))] = 'Remote Sniper', [tostring(GetHashKey('WEAPON_GRENADELAUNCHER_SMOKE'))] = 'Smoke Grenade Launcher', [tostring(GetHashKey('WEAPON_PASSENGER_ROCKET'))] = 'Passenger Rocket', [tostring(GetHashKey('WEAPON_AIRSTRIKE_ROCKET'))] = 'Airstrike Rocket', [tostring(GetHashKey('WEAPON_STINGER'))] = 'Stinger [Vehicle]', [tostring(GetHashKey('OBJECT'))] = 'Object', [tostring(GetHashKey('VEHICLE_WEAPON_TANK'))] = 'Tank Cannon', [tostring(GetHashKey('VEHICLE_WEAPON_SPACE_ROCKET'))] = 'Rockets', [tostring(GetHashKey('VEHICLE_WEAPON_PLAYER_LASER'))] = 'Laser', [tostring(GetHashKey('AMMO_RPG'))] = 'Rocket', [tostring(GetHashKey('AMMO_TANK'))] = 'Tank', [tostring(GetHashKey('AMMO_SPACE_ROCKET'))] = 'Rocket', [tostring(GetHashKey('AMMO_PLAYER_LASER'))] = 'Laser', [tostring(GetHashKey('AMMO_ENEMY_LASER'))] = 'Laser', [tostring(GetHashKey('WEAPON_RAMMED_BY_CAR'))] = 'Rammed by Car', [tostring(GetHashKey('WEAPON_FIRE'))] = 'Fire', [tostring(GetHashKey('WEAPON_HELI_CRASH'))] = 'Heli Crash', [tostring(GetHashKey('WEAPON_RUN_OVER_BY_CAR'))] = 'Run over by Car', [tostring(GetHashKey('WEAPON_HIT_BY_WATER_CANNON'))] = 'Hit by Water Cannon', [tostring(GetHashKey('WEAPON_EXHAUSTION'))] = 'Exhaustion', [tostring(GetHashKey('WEAPON_EXPLOSION'))] = 'Explosion', [tostring(GetHashKey('WEAPON_ELECTRIC_FENCE'))] = 'Electric Fence', [tostring(GetHashKey('WEAPON_BLEEDING'))] = 'Bleeding', [tostring(GetHashKey('WEAPON_DROWNING_IN_VEHICLE'))] = 'Drowning in Vehicle', [tostring(GetHashKey('WEAPON_DROWNING'))] = 'Drowning', [tostring(GetHashKey('WEAPON_BARBED_WIRE'))] = 'Barbed Wire', [tostring(GetHashKey('WEAPON_VEHICLE_ROCKET'))] = 'Vehicle Rocket', [tostring(GetHashKey('VEHICLE_WEAPON_ROTORS'))] = 'Rotors', [tostring(GetHashKey('WEAPON_AIR_DEFENCE_GUN'))] = 'Air Defence Gun', [tostring(GetHashKey('WEAPON_ANIMAL'))] = 'Animal', [tostring(GetHashKey('WEAPON_COUGAR'))] = 'Cougar' }
return { gok_ch = { acceleration = 0.288, brakerate = 0.9, buildcostenergy = 3285, buildcostmetal = 171, builddistance = 180, builder = true, buildpic = "gok_ch.dds", buildtime = 5000, canguard = true, canhover = true, canmove = true, canpatrol = true, canreclamate = 1, canstop = 1, category = "ALL MOBILE SMALL SURFACE", collisionvolumeoffsets = "0 0 0", collisionvolumescales = "31 31 31", collisionvolumetype = "CylZ", corpse = "dead", defaultmissiontype = "Standby", description = "Tech Level 1", energymake = 30, energystorage = 30, explodeas = "BIG_UNITEX", footprintx = 3, footprintz = 3, idleautoheal = 5, idletime = 1800, losemitheight = 25, maneuverleashlength = 640, mass = 171, maxdamage = 975, maxslope = 16, maxvelocity = 2.3, maxwaterdepth = 0, metalmake = 0.1, metalstorage = 10, mobilestandorders = 1, movementclass = "HOVER3", name = "Construction Gravitank", noautofire = false, objectname = "gok_ch", radaremitheight = 25, seismicsignature = 0, reclaimspeed = 50, repairspeed = 50, selfdestructas = "BIG_UNIT", shownanospray = false, sightdistance = 351, standingmoveorder = 1, steeringmode = 1, turninplace = 1, turninplaceanglelimit = 60, turninplacespeedlimit = 1.6698, turnrate = 425, unitname = "gok_ch", workertime = 100, buildoptions = { [1] = "gok_solar", [2] = "gok_advsolar", [3] = "gok_win", [4] = "gok_win1", [5] = "gok_geo", [6] = "gok_mstor", [7] = "gok_estor", [8] = "gok_mex", [9] = "gok_mex1", [10] = "gok_makr", [11] = "gok_makr1", [12] = "gok_lab", [13] = "gok_ap", --[14] = "", [15] = "gok_hp", [16] = "gok_ahp", [17] = "gok_nanotc", [18] = "gok_eyes", [19] = "gok_rad", [20] = "gok_jam", [21] = "gok_juno", [22] = "gok_gate2", [23] = "gok_drag", [24] = "gok_llt", --[25] = "", [26] = "gok_blackdawn", --[27] = "", [28] = "gok_rl", [29] = "gok_cir", [30] = "gok_tide", [31] = "gok_tide1", --[32] = "", [33] = "gok_fmkr", [34] = "gok_hpns", [35] = "gok_ahpns", [36] = "gok_sy", [37] = "gok_asy", [38] = "gok_fnanotc", [39] = "gok_frad", [40] = "gok_sonar", [41] = "gok_fdrag", [42] = "gok_tl", --[43] = "", [44] = "gok_frl", }, customparams = { buildpic = "gok_ch.dds", faction = "GOK", }, featuredefs = { dead = { blocking = false, collisionvolumeoffsets = "0.0 -1.56249816895 0.0184326171875", collisionvolumescales = "24.4295043945 10.1600036621 29.846862793", collisionvolumetype = "Box", damage = 1453, description = "Construction Hovercraft Wreckage", energy = 0, featuredead = "heap", footprintx = 3, footprintz = 3, metal = 108, object = "gok_ch_DEAD", reclaimable = true, }, heap = { blocking = false, damage = 1816, description = "Construction Hovercraft Debris", energy = 0, footprintx = 3, footprintz = 3, metal = 58, object = "3X3A", reclaimable = true, }, }, nanocolor = { [1] = 0.12, [2] = 0.52, [3] = 0.12, }, sfxtypes = { pieceexplosiongenerators = { [1] = "piecetrail0", [2] = "piecetrail1", [3] = "piecetrail2", [4] = "piecetrail3", [5] = "piecetrail4", [6] = "piecetrail6", }, }, sounds = { build = "nanlath1", canceldestruct = "cancel2", repair = "repair1", underattack = "warning1", working = "reclaim1", cant = { [1] = "cantdo4", }, count = { [1] = "count6", [2] = "count5", [3] = "count4", [4] = "count3", [5] = "count2", [6] = "count1", }, ok = { [1] = "hovmdok1", }, select = { [1] = "hovmdsl1", }, }, }, }
local core = require 'core' local parser = require 'parser' local function posToRange(lines, start, finish) local start_row, start_col = lines:rowcol(start) local finish_row, finish_col = lines:rowcol(finish) return { start = { line = start_row - 1, character = start_col - 1, }, ['end'] = { line = finish_row - 1, character = finish_col, }, } end local function fastCompletion(lsp, params, lines) local uri = params.textDocument.uri local text, oldText = lsp:getText(uri) -- lua是从1开始的,因此都要+1 local position = lines:positionAsChar(params.position.line + 1, params.position.character) local vm = lsp:getVM(uri) if not vm then vm = lsp:loadVM(uri) if not vm then return nil end end local items = core.completion(vm, text, position, oldText) if not items or #items == 0 then vm = lsp:loadVM(uri) if not vm then return nil end items = core.completion(vm, text, position) if not items or #items == 0 then return nil end end return items end local function finishCompletion(lsp, params, lines) local uri = params.textDocument.uri local text = lsp:getText(uri) -- lua是从1开始的,因此都要+1 local position = lines:positionAsChar(params.position.line + 1, params.position.character) local vm = lsp:loadVM(uri) if not vm then return nil end local items = core.completion(vm, text, position) if not items or #items == 0 then return nil end return items end return function (lsp, params) local uri = params.textDocument.uri local text, oldText = lsp:getText(uri) if not text then return nil end local lines = parser:lines(text, 'utf8') local items = fastCompletion(lsp, params, lines) --local items = finishCompletion(lsp, params, lines) if not items then return nil end for i, item in ipairs(items) do item.sortText = ('%04d'):format(i) item.insertTextFormat = 2 item.insertText = item.insertText or item.label if item.textEdit then item.textEdit.range = posToRange(lines, item.textEdit.start, item.textEdit.finish) item.textEdit.start = nil item.textEdit.finish = nil end if item.additionalTextEdits then for _, textEdit in ipairs(item.additionalTextEdits) do textEdit.range = posToRange(lines, textEdit.start, textEdit.finish) textEdit.start = nil textEdit.finish = nil end end end local response = { isIncomplete = true, items = items, } return response end
--*********************************************************** --** THE INDIE STONE ** --*********************************************************** require "ISUI/ISUIElement" ---@class ISVehicleGauge : ISUIElement ISVehicleGauge = ISUIElement:derive("ISVehicleGauge") function ISVehicleGauge:setNeedleWidth(width) self.javaObject:setNeedleWidth(width) end function ISVehicleGauge:setTexture(texture) self.javaObject:setTexture(texture) end function ISVehicleGauge:setValue(value) self.javaObject:setValue(value) end function ISVehicleGauge:instantiate() self.javaObject = VehicleGauge.new(self.texture, self.needleX, self.needleY, self.minAngle, self.maxAngle) self.javaObject:setTable(self) self.javaObject:setX(self.x) self.javaObject:setY(self.y) self.javaObject:setWidth(self.width) self.javaObject:setHeight(self.height) self.javaObject:setAnchorLeft(self.anchorLeft) self.javaObject:setAnchorRight(self.anchorRight) self.javaObject:setAnchorTop(self.anchorTop) self.javaObject:setAnchorBottom(self.anchorBottom) end function ISVehicleGauge:new(x, y, texture, needleX, needleY, minAngle, maxAngle) local o = ISUIElement:new(x, y, texture:getWidth(), texture:getHeight()) setmetatable(o, self) self.__index = self o.texture = texture o.needleX = needleX o.needleY = needleY o.minAngle = minAngle o.maxAngle = maxAngle return o end
local r = require "resources" local input = require "input" local Chat = require "chat" local HUD = require "hud" local Scenario = require "scenario" local Achievements = require "achievements" local readers = require "readers" local w = love.graphics.getWidth() local h = love.graphics.getHeight() local chatMargin = w * 0.05 local hudHeight = h * 0.1 local beep = r.sources.beep:clone() beep:setLooping(true) beep:setPitch(2.3) beep:setVolume(0.2) local Play = {} function Play:enteredState() love.graphics.setBackgroundColor(r.colors.background) self.morseReader = readers.MorseReader() self.multiReader = readers.MultiReader() if self.achievements then self.achievements:hide() else self.achievements = Achievements(h - hudHeight) end self.chat = Chat(chatMargin, chatMargin, w - chatMargin * 2, h - chatMargin * 2 - hudHeight) self.hud = HUD(self, hudHeight) self.scenario = Scenario(self) self.try = (self.try or 0) + 1 if self.try == 1 then self.hud:showMessage("[пробел] пищать") elseif self.try == 2 then self.hud:showMessage("[s] ускорить текст") end self.beeping = false end function Play:achieve(id) local ok, title = self.achievements:achieve(id) if ok then self.hud:showMessage(("Достижение: %s"):format(title)) end end function Play:exitedState() self.fast = false beep:stop() end function Play:pausedState() beep:stop() end function Play:endGame(final) self:gotoState("GameOver", final) end function Play:pauseGame() self:pushState("Pause") end function Play:focus(f) if not f then self:pauseGame() end end function Play:update(dt) self.fast = input.fast:isDown() if input.beep:pressed() then self.beeping = true end if not input.beep:isDown() or self.fast then self.beeping = false end if self.beeping then beep:play() else beep:stop() end if input.pause:pressed() then self:pauseGame() end self.chat:update(dt) self.hud:update(dt) self.scenario:update(self.fast and dt * 10 or dt) self.achievements:update(dt) end function Play:draw() self.chat:draw() self.hud:draw() self.achievements:draw() end return Play
target.stand_alone_mode = true
--[[ spoonacular API The spoonacular Nutrition, Recipe, and Food API allows you to access over 380,000 recipes, thousands of ingredients, 800,000 food products, and 100,000 menu items. Our food ontology and semantic recipe search engine makes it possible to search for recipes using natural language queries, such as \"gluten free brownies without sugar\" or \"low fat vegan cupcakes.\" You can automatically calculate the nutritional information for any recipe, analyze recipe costs, visualize ingredient lists, find recipes for what's in your fridge, find recipes based on special diets, nutritional requirements, or favorite ingredients, classify recipes into types and cuisines, convert ingredient amounts, or even compute an entire meal plan. With our powerful API, you can create many kinds of food and especially nutrition apps. Special diets/dietary requirements currently available include: vegan, vegetarian, pescetarian, gluten free, grain free, dairy free, high protein, whole 30, low sodium, low carb, Paleo, ketogenic, FODMAP, and Primal. The version of the OpenAPI document: 1.0 Contact: mail@spoonacular.com Generated by: https://openapi-generator.tech ]] -- inline_response_200_45 class local inline_response_200_45 = {} local inline_response_200_45_mt = { __name = "inline_response_200_45"; __index = inline_response_200_45; } local function cast_inline_response_200_45(t) return setmetatable(t, inline_response_200_45_mt) end local function new_inline_response_200_45(paired_wines, pairing_text, product_matches) return cast_inline_response_200_45({ ["pairedWines"] = paired_wines; ["pairingText"] = pairing_text; ["productMatches"] = product_matches; }) end return { cast = cast_inline_response_200_45; new = new_inline_response_200_45; }
Name = 'Text' OnUse = function(artboard, event, side, x, y) local layer = artboard:GetCurrentLayer() if layer.Layer.LayerType ~= 'Normal' then layer.Bedrock:DisplayAlertWindow('Tool Not Supported!', "You cannot use the text tool on non-normal layers.", {'Ok'}, function()end) elseif side == 1 then layer.CursorPos = {x, y} layer.Bedrock:SetActiveObject(layer) elseif side == 2 then local pixels = layer:GetEffectedPixels(x, y, artboard.BrushSize, artboard.BrushShape, artboard.CorrectPixelRatio) for i, pixel in ipairs(pixels) do layer:SetPixel(pixel[1], pixel[2], nil, artboard.BrushColour) end end end OnStopUse = function(artboard) local layer = artboard:GetCurrentLayer() layer.Bedrock:SetActiveObject() end
--[[ README: ]] script_name="C Smooth" script_description="Smooth v1.0" script_author="chaaaaang" script_version="1.0" include("karaskel.lua") require("lfs") function main(subtitle, selected, active) local meta,styles=karaskel.collect_head(subtitle,false) --count the size N local i = 0 for sa,la in ipairs(selected) do local line = subtitle[la] local ltext=(line.text:match("^{")==nil) and "{}"..line.text or line.text ltext=ltext:gsub("}{","") line.text = ltext subtitle[la] = line i = i + 1 end local N = i --end count the size N config_table = config_read() --GUI dialog_config={ {class="dropdown",name="tagtype",items={"posx","posy","fscx","fscy","frz"},value=config_table.tag,x=0,y=0}, {class="label",label="index",x=1,y=0}, {class="intedit",name="index",value=config_table.index,x=2,y=0}, --100 percent {class="label",label="lower threshold",x=0,y=1}, {class="floatedit",name="lower_threshold",value=config_table.L,x=1,y=1,hint="default: 180"}, {class="checkbox",name="keep_L",label="keep checking lower_threshold",value=config_table.keep_L,x=2,y=1,width=2}, {class="label",label="upper threshold",x=0,y=2}, {class="floatedit",name="upper_threshold",value=config_table.U,x=1,y=2,hint="default: 500"}, {class="checkbox",name="keep_U",label="keep checking upper_threshold",value=config_table.keep_U,x=2,y=2,width=2}, --force 0-100 {class="label",label="force",x=0,y=3}, {class="floatedit",name="force",value=config_table.F,x=1,y=3,hint="default: 30"}, {class="checkbox",name="remember",label="remember config",value=config_table.remember,x=2,y=3,width=2} } buttons={"Run","Quit"} pressed, result = aegisub.dialog.display(dialog_config,buttons) if (pressed=="Quit") then aegisub.cancel() end if (pressed=="Run") then if (result["remember"]==true) then config_write(result) end result["upper_threshold"] = result["upper_threshold"]/100 result["lower_threshold"] = result["lower_threshold"]/100 result["force"] = result["force"]/100 tag_table={} --get the tag information and write it to a table if (result["tagtype"]=="posx" or result["tagtype"]=="posy") then local i = 0 for si,li in ipairs(selected) do i = i + 1 local line = subtitle[li] if (result["tagtype"]=="posx") then local posx = tonumber(line.text:match("\\pos%(([%d%.%-]+)")) table.insert(tag_table,{index=i,value=posx,change=""}) else local posy = tonumber(line.text:match("\\pos%([%d%.%-]+,([%d%.%-]+)")) table.insert(tag_table,{index=i,value=posy,change=""}) end end elseif (result["tagtype"]=="fscx" or result["tagtype"]=="fscy" or result["tagtype"]=="frz") then local i = 0 for si,li in ipairs(selected) do i = i + 1 local line = subtitle[li] local tt_table={} for tg,tx in line.text:gmatch("({[^}]*})([^{]*)") do table.insert(tt_table,{tag=tg,text=tx}) end local count = 0 for _,tt in ipairs(tt_table) do tt.tag = tt.tag:gsub("\\"..result["tagtype"],"}\\"..result["tagtype"]) tt.tag = tt.tag.."\\"..result["tagtype"].."0" for p,q in tt.tag:gmatch("([^}]*)}\\"..result["tagtype"].."([%d%.%-]+)") do count = count + 1 if (count == result["index"]) then table.insert(tag_table,{index=i,value=q,change=""}) goto get_information end end count = count - 1 end :: get_information :: end end --analyze the table local sum_diff = 0 for i=1,N-1 do sum_diff = sum_diff + math.abs(tag_table[i+1].value - tag_table[i].value) end local average_diff = sum_diff / (N-1) + 0.001 --upper threshold local tag_table_upper={}--a copy of tag_table for i=2,N-1 do local diff_l = math.abs(tag_table[i].value - tag_table[i-1].value) local diff_r = math.abs(tag_table[i].value - tag_table[i+1].value) if (diff_l/average_diff>=result["upper_threshold"] and diff_r/average_diff>=result["upper_threshold"]) then local tag = tag_table[i] tag.value = (tag_table[i-1].value + tag_table[i+1].value) / 2 tag.change = "U" table.insert(tag_table_upper,tag) end end for si,upper in ipairs(tag_table_upper) do local tag = tag_table[upper.index] tag.value = upper.value tag.change = upper.change tag_table[upper.index] = tag end --get the average_diff again sum_diff = 0 for i=1,N-1 do sum_diff = sum_diff + math.abs(tag_table[i+1].value - tag_table[i].value) end average_diff = sum_diff / (N-1) + 0.001 --lower threshold local tag_table_lower={}--a copy of tag_table for i=2,N-1 do local diff_l = math.abs(tag_table[i].value - tag_table[i-1].value) local diff_r = math.abs(tag_table[i].value - tag_table[i+1].value) local diff_c = tag_table[i].value - (tag_table[i-1].value + tag_table[i+1].value)/2 if (diff_l/average_diff>=result["lower_threshold"] or diff_r/average_diff>=result["lower_threshold"]) then local tag = tag_table[i] tag.value = tag_table[i].value - diff_c * result["force"] tag.change = tag.change.."L" table.insert(tag_table_lower,tag) end end for si,lower in ipairs(tag_table_lower) do local tag = tag_table[lower.index] tag.value = lower.value tag.change = lower.change tag_table[lower.index] = tag end --analyze tag_table end --write back if (result["tagtype"]=="posx" or result["tagtype"]=="posy") then local i = 0 for si,li in ipairs(selected) do i = i + 1 local line = subtitle[li] local ltext = line.text if (result["tagtype"]=="posx") then ltext = ltext:gsub("\\pos%([%d%.%-]+",string.format("\\pos(%.3f",tag_table[i].value)) else ltext = ltext:gsub("(\\pos%([%d%.%-]+,)[%d%.%-]+",function(a) return string.format("%s%.3f",a,tag_table[i].value) end) end line.text = ltext line.actor = tag_table[i].change subtitle[li] = line end elseif (result["tagtype"]=="fscx" or result["tagtype"]=="fscy" or result["tagtype"]=="frz") then local i = 0 for si,li in ipairs(selected) do i = i + 1 local line = subtitle[li] local ltext = line.text local tt_table={} for tg,tx in ltext:gmatch("({[^}]*})([^{]*)") do table.insert(tt_table,{tag=tg,text=tx}) end local rebuild = "" local count = 0 for _,tt in ipairs(tt_table) do if (tt.tag:match("\\"..result["tagtype"])==nil) then rebuild = rebuild..tt.tag..tt.text else tt.tag = tt.tag:gsub("\\"..result["tagtype"],"}\\"..result["tagtype"]) tt.tag = tt.tag.."\\"..result["tagtype"].."0" local rebuild_tag = "" for p,q in tt.tag:gmatch("([^}]*)}\\"..result["tagtype"].."([%d%.%-]+)") do count = count + 1 if (count == result["index"]) then rebuild_tag = string.format("%s%s\\%s%.2f",rebuild_tag,p,result["tagtype"],tag_table[i].value) else rebuild_tag = rebuild_tag..p.."\\"..result["tagtype"]..q end end rebuild_tag = rebuild_tag:gsub("\\"..result["tagtype"].."[%d%.%-]+$","}") rebuild = rebuild..rebuild_tag..tt.text count = count - 1 end end ltext = rebuild line.text = ltext line.actor = tag_table[i].change subtitle[li] = line end end end aegisub.set_undo_point(script_name) return selected end function config_read () local path = "" local config_table = {tag="fscx",index=1,U=500,L=180,F=30,remember=false,keep_U=false,keep_L=false} for p in lfs.dir("C:\\Users") do if (p~="Public" and p:match("Default")==nil) then path = "C:\\Users\\"..p.."\\AppData\\Roaming\\Aegisub\\C Smooth.txt" end end if io.open(path,"r") then file = io.open(path,"r") io.input(file) for line in io.lines(path) do if line:match("tag") then config_table.tag=line:match(":(.*)") elseif line:match("index") then config_table.index=line:match(":(.*)") elseif line:match("upper_threshold") then config_table.U=line:match(":(.*)") elseif line:match("lower_threshold") then config_table.L=line:match(":(.*)") elseif line:match("force") then config_table.F=line:match(":(.*)") elseif line:match("keep_U") then config_table.keep_U=line:match(":(.*)")=="true" and true or false elseif line:match("keep_L") then config_table.keep_L=line:match(":(.*)")=="true" and true or false elseif line:match("remember") then config_table.remember=line:match(":(.*)")=="true" and true or false end end io.close(file) end return config_table end function config_write(result) local path = "" for p in lfs.dir("C:\\Users") do if (p~="Public" and p:match("Default")==nil) then path = "C:\\Users\\"..p.."\\AppData\\Roaming\\Aegisub\\C Smooth.txt" end end file = io.open(path,"w+") io.output(file) io.write("tag:"..result.tagtype.."\n") io.write("index:"..result.index.."\n") io.write("upper_threshold:"..result.upper_threshold.."\n") io.write("lower_threshold:"..result.lower_threshold.."\n") io.write("force:"..result.force.."\n") keep_U = result.keep_U and "true" or "false" keep_L = result.keep_L and "true" or "false" remember = result.remember and "true" or "false" io.write("keep_U:"..keep_U.."\n") io.write("keep_L:"..keep_L.."\n") io.write("remember:"..remember) io.close(file) end --This optional function lets you prevent the user from running the macro on bad input function macro_validation(subtitle, selected, active) --Check if the user has selected valid lines --If so, return true. Otherwise, return false return true end --This is what puts your automation in Aegisub's automation list aegisub.register_macro(script_name,script_description,main,macro_validation)
PLUGIN.englishTranslation = { pistol = "Pistol", ar2 = "Rifle", smg1 = "Sub Machine Gun", buckshot = "Shotgun", sniperround = "Sniper Rifle", ["357"] = "Magnum", -- These are for item description translation. att_rdot = "Red Dot Sight", attRDotDesc = "A Small Sight that displays a red dot in the center", att_holo = "Holographic Sight", attHoloDesc = "A Small sight that displays an aim-assisting image in the center", att_scope4 = "4x Scope", attScope4Desc = "A Scope that allows you to aim at mid-long distance targets", att_scope8 = "8x Scope", attScope8Desc = "A Scope that allows you to aim at long distance targets", att_muzsup = "Suppressor", attSupDesc = "A Suppressor that reduces the sound from the gun", att_exmag = "Extended Mag", attEMagDesc = "A Magazine that has more rounds capacity", att_foregrip = "Foregrip", attForeDesc = "A Grip that makes you to aim hip-fire more accurate.", att_laser = "Laser Sight", attLaserDesc = "A Laser that displays where you're aiming at", att_bipod = "Bipod", attBipodDesc = "A Bipod that assists your aim.", primary = "Primary Weapon", secondary = "Secondary Weapon", gunInfoDesc = "A Weapon that uses %s Ammunition", gunInfoStat = "Damage: %s\nWeapon Type: %s\nMagazine size: %s", gunInfoAttachments = "Current attachment: %s", attDetached = "Attachment has been detached.", detTarget = "You need to choose attachment to detach.", cantAttached = "This attachment does not fit for this Weapon.", alreadyAttached = "There is no slot for this attachment on this weapon.", notCW = "This weapon cannot be modded.", notAttachment = "This is not valid attachment.", noWeapon = "Can't find the target.", cwReloading = "Reloading %s%%", cwMagKappa = "%s / %s", cwGrenades = "%sx Grenade", cwEmptyM203 = "Reload M203", cwFilledM203 = "M203 Reloaded", cw40mm = "%sx Grenade", cwGrenType = "Type: %s", cwUse = "[USE]", cwStablize = "%s - Stabilize", cwAmmo_ar2 = "Rifle Ammo", cwAmmo_smg1 = "SMG Ammo", cwAmmo_pistol = "Pistol Ammo", cwAmmo_357 = "Magnum Ammo", cwAmmo_sniperround = "Sniper Rifle Ammo", cwAmmo_buckshot = "Buckshot Ammo", } PLUGIN.koreanTranslation = { ["Pistol Ammo"] = "권총 탄약", ["Magnum Ammo"] = "매그넘 탄약", ["Sub Machine Gun Ammo"] = "기관권총 탄약", ["Rifle Ammo"] = "소총 탄약", ["Shotgun Shells"] = "산탄총 탄약", ["Sniper Rounds"] = "저격소총 탄약", pistol = "권총", ar2 = "소총", smg1 = "기관권총", buckshot = "산탄총", sniperround = "저격소총", ["357"] = "매그넘", gunInfoDesc = "%s 를 사용하는 총기", gunInfoStat = "데미지: %s\n무기 종류: %s\n탄창 크기: %s발", gunInfoAttachments = "현재 부착물:%s", -- These are for item name translation. ["Red Dot Sight"] = "레드 닷 조준기", ["Holographic Sight"] = "홀로그래픽 조준기", ["4x Scope"] = "4배율 조준경", ["8x Scope"] = "8배율 조준경", ["Suppressor"] = "소음기", ["Extended Mag"] = "확장 탄알집", ["Foregrip"] = "수직 손잡이", ["Laser Sight"] = "레이저 조준기", ["Bipod"] = "양각대", -- These are for item description translation. att_rdot = "레드 닷 조준기", attRDotDesc = "조준을 도와주는 레드닷 조준기.", att_holo = "홀로그래픽 조준기", attHoloDesc = "조준을 도와주는 홀로그래픽 조준기", att_scope4 = "4배율 조준경", attScope4Desc = "멀리 있는 목표를 조준할 수 있게 해주는 4배율 조준경", att_scope8 = "8배율 조준경", attScope8Desc = "멀리 있는 목표를 조준할 수 있게 해주는 8배율 조준경", att_muzsup = "소음기", attSupDesc = "총기 소음을 줄여주는 소음기", att_exmag = "확장 탄알집", attEMagDesc = "총기의 탄약 장전양을 늘려주는 확장 탄알집", att_foregrip = "수직 손잡이", attForeDesc = "더 안정적이게 조준을 도와주는 수직 손잡이", att_laser = "레이저 조준기", attLaserDesc = "조준하는 곳을 가리켜주는 레이저 조준기", att_bipod = "양각대", attBipodDesc = "사격시 반동을 줄여주는 양각대", attDetached = "총기 부품을 떼냈습니다.", detTarget = "떼어낼 부품을 선택해 주세요.", cantAttached = "이 무기에는 해당 부품을 장착할 수 없습니다.", alreadyAttached = "무기에 빈자리가 없습니다.", notCW = "이 무기는 개조가능한 무기가 아닙니다.", notAttachment = "이건 올바른 총기 부품이 아닙니다.", noWeapon = "대상을 찾을수 없습니다.", cwReloading = "장전중 %s%%", cwMagKappa = "%s / %s", cwGrenades = "%sx 수류탄", cwEmptyM203 = "M203 장전필요", cwFilledM203 = "M203 장전 됨", cw40mm = "%sx 유탄", cwGrenType = "유탄종류: %s", cwUse = "[사용 키]", cwStablize = "%s - 안정화", cwAmmo_ar2 = "소총 탄", cwAmmo_smg1 = "SMG 탄", cwAmmo_pistol = "권총 탄", cwAmmo_357 = "매그넘 탄", cwAmmo_sniperround = "저격소총 탄", cwAmmo_buckshot = "산탄 쉘", }
require("test/bustedhelper_game") local character_info = require("content/character_info") describe('character_info', function () describe('init', function () it('should init a character_info with id, name, level, initial quote ids', function () local f_info = character_info(8, "employee") assert.are_same({8, "employee"}, {f_info.id, f_info.name}) end) end) describe('_tostring', function () it('character_info(8, "employee") => "character_info(8, "employee")"', function () local f_info = character_info(8, "employee") assert.are_equal("[character_info(8, \"employee\")]", f_info:_tostring()) end) end) end)
local function clean_path(p) -- todo: replace with dfhack.filesystem call? return p:gsub('\\', '/'):gsub('//', '/'):gsub('/$', '') end local fs = dfhack.filesystem local old_cwd = clean_path(fs.getcwd()) local function restore_cwd() fs.chdir(old_cwd) end function test.getDFPath() expect.eq(clean_path(dfhack.getDFPath()), old_cwd) end function test.getDFPath_chdir() dfhack.with_finalize(restore_cwd, function() fs.chdir('data') expect.eq(clean_path(dfhack.getDFPath()), old_cwd) expect.ne(clean_path(dfhack.getDFPath()), clean_path(fs.getcwd())) end) end function test.getHackPath() expect.eq(clean_path(dfhack.getHackPath()), clean_path(dfhack.getDFPath() .. '/hack/')) end function test.getHackPath_chdir() dfhack.with_finalize(restore_cwd, function() fs.chdir('hack') expect.eq(clean_path(dfhack.getHackPath()), clean_path(old_cwd .. '/hack/')) expect.eq(clean_path(dfhack.getHackPath()), clean_path(fs.getcwd())) end) end
--- Multishell allows multiple programs to be run at the same time. -- -- When multiple programs are running, it displays a tab bar at the top of the -- screen, which allows you to switch between programs. New programs can be -- launched using the `fg` or `bg` programs, or using the @{shell.openTab} and -- @{multishell.launch} functions. -- -- Each process is identified by its ID, which corresponds to its position in -- the tab list. As tabs may be opened and closed, this ID is _not_ constant -- over a program's run. As such, be careful not to use stale IDs. -- -- As with @{shell}, @{multishell} is not a "true" API. Instead, it is a -- standard program, which launches a shell and injects its API into the shell's -- environment. This API is not available in the global environment, and so is -- not available to @{os.loadAPI|APIs}. -- -- @module[module] multishell local expect = dofile("rom/modules/main/cc/expect.lua").expect -- Setup process switching local parentTerm = term.current() local w, h = parentTerm.getSize() local tProcesses = {} local nCurrentProcess = nil local nRunningProcess = nil local bShowMenu = false local bWindowsResized = false local nScrollPos = 1 local bScrollRight = false local function selectProcess(n) if nCurrentProcess ~= n then if nCurrentProcess then local tOldProcess = tProcesses[nCurrentProcess] tOldProcess.window.setVisible(false) end nCurrentProcess = n if nCurrentProcess then local tNewProcess = tProcesses[nCurrentProcess] tNewProcess.window.setVisible(true) tNewProcess.bInteracted = true end end end local function setProcessTitle(n, sTitle) tProcesses[n].sTitle = sTitle end local function resumeProcess(nProcess, sEvent, ...) local tProcess = tProcesses[nProcess] local sFilter = tProcess.sFilter if sFilter == nil or sFilter == sEvent or sEvent == "terminate" then local nPreviousProcess = nRunningProcess nRunningProcess = nProcess term.redirect(tProcess.terminal) local ok, result = coroutine.resume(tProcess.co, sEvent, ...) tProcess.terminal = term.current() if ok then tProcess.sFilter = result else printError(result) end nRunningProcess = nPreviousProcess end end local function launchProcess(bFocus, tProgramEnv, sProgramPath, ...) local tProgramArgs = table.pack(...) local nProcess = #tProcesses + 1 local tProcess = {} tProcess.sTitle = fs.getName(sProgramPath) if bShowMenu then tProcess.window = window.create(parentTerm, 1, 2, w, h - 1, false) else tProcess.window = window.create(parentTerm, 1, 1, w, h, false) end tProcess.co = coroutine.create(function() os.run(tProgramEnv, sProgramPath, table.unpack(tProgramArgs, 1, tProgramArgs.n)) if not tProcess.bInteracted then term.setCursorBlink(false) print("Press any key to continue") os.pullEvent("char") end end) tProcess.sFilter = nil tProcess.terminal = tProcess.window tProcess.bInteracted = false tProcesses[nProcess] = tProcess if bFocus then selectProcess(nProcess) end resumeProcess(nProcess) return nProcess end local function cullProcess(nProcess) local tProcess = tProcesses[nProcess] if coroutine.status(tProcess.co) == "dead" then if nCurrentProcess == nProcess then selectProcess(nil) end table.remove(tProcesses, nProcess) if nCurrentProcess == nil then if nProcess > 1 then selectProcess(nProcess - 1) elseif #tProcesses > 0 then selectProcess(1) end end if nScrollPos ~= 1 then nScrollPos = nScrollPos - 1 end return true end return false end local function cullProcesses() local culled = false for n = #tProcesses, 1, -1 do culled = culled or cullProcess(n) end return culled end -- Setup the main menu local menuMainTextColor, menuMainBgColor, menuOtherTextColor, menuOtherBgColor if parentTerm.isColor() then menuMainTextColor, menuMainBgColor = colors.yellow, colors.black menuOtherTextColor, menuOtherBgColor = colors.black, colors.gray else menuMainTextColor, menuMainBgColor = colors.white, colors.black menuOtherTextColor, menuOtherBgColor = colors.black, colors.gray end local function redrawMenu() if bShowMenu then -- Draw menu parentTerm.setCursorPos(1, 1) parentTerm.setBackgroundColor(menuOtherBgColor) parentTerm.clearLine() local nCharCount = 0 local nSize = parentTerm.getSize() if nScrollPos ~= 1 then parentTerm.setTextColor(menuOtherTextColor) parentTerm.setBackgroundColor(menuOtherBgColor) parentTerm.write("<") nCharCount = 1 end for n = nScrollPos, #tProcesses do if n == nCurrentProcess then parentTerm.setTextColor(menuMainTextColor) parentTerm.setBackgroundColor(menuMainBgColor) else parentTerm.setTextColor(menuOtherTextColor) parentTerm.setBackgroundColor(menuOtherBgColor) end parentTerm.write(" " .. tProcesses[n].sTitle .. " ") nCharCount = nCharCount + #tProcesses[n].sTitle + 2 end if nCharCount > nSize then parentTerm.setTextColor(menuOtherTextColor) parentTerm.setBackgroundColor(menuOtherBgColor) parentTerm.setCursorPos(nSize, 1) parentTerm.write(">") bScrollRight = true else bScrollRight = false end -- Put the cursor back where it should be local tProcess = tProcesses[nCurrentProcess] if tProcess then tProcess.window.restoreCursor() end end end local function resizeWindows() local windowY, windowHeight if bShowMenu then windowY = 2 windowHeight = h - 1 else windowY = 1 windowHeight = h end for n = 1, #tProcesses do local tProcess = tProcesses[n] local x, y = tProcess.window.getCursorPos() if y > windowHeight then tProcess.window.scroll(y - windowHeight) tProcess.window.setCursorPos(x, windowHeight) end tProcess.window.reposition(1, windowY, w, windowHeight) end bWindowsResized = true end local function setMenuVisible(bVis) if bShowMenu ~= bVis then bShowMenu = bVis resizeWindows() redrawMenu() end end local threading = {} --- @export --- Get the currently visible process. This will be the one selected on -- the tab bar. -- -- Note, this is different to @{getCurrent}, which returns the process which is -- currently executing. -- -- @treturn number The currently visible process's index. -- @see setFocus function threading.getFocus() return nCurrentProcess end --- Change the currently visible process. -- -- @tparam number n The process index to switch to. -- @treturn boolean If the process was changed successfully. This will -- return @{false} if there is no process with this id. -- @see getFocus function threading.setFocus(n) expect(1, n, "number") if n >= 1 and n <= #tProcesses then selectProcess(n) redrawMenu() return true end return false end --- Get the title of the given tab. -- -- This starts as the name of the program, but may be changed using -- @{multishell.setTitle}. -- @tparam number n The process index. -- @treturn string|nil The current process title, or @{nil} if the -- process doesn't exist. function threading.getTitle(n) expect(1, n, "number") if n >= 1 and n <= #tProcesses then return tProcesses[n].sTitle end return nil end --- Set the title of the given process. -- -- @tparam number n The process index. -- @tparam string title The new process title. -- @see getTitle -- @usage Change the title of the current process -- -- multishell.setTitle(multishell.getCurrent(), "Hello") function threading.setTitle(n, title) expect(1, n, "number") expect(2, title, "string") if n >= 1 and n <= #tProcesses then setProcessTitle(n, title) redrawMenu() end end --- Get the index of the currently running process. -- -- @treturn number The currently running process. function threading.getCurrent() return nRunningProcess end --- Start a new process, with the given environment, program and arguments. -- -- The returned process index is not constant over the program's run. It can be -- safely used immediately after launching (for instance, to update the title or -- switch to that tab). However, after your program has yielded, it may no -- longer be correct. -- -- @tparam table tProgramEnv The environment to load the path under. -- @tparam string sProgramPath The path to the program to run. -- @param ... Additional arguments to pass to the program. -- @treturn number The index of the created process. -- @see os.run -- @usage Run the "hello" program, and set its title to "Hello!" -- local id = multishell.launch({}, "/rom/programs/fun/hello.lua") -- multishell.setTitle(id, "Hello!") function threading.launch(tProgramEnv, sProgramPath, ...) expect(1, tProgramEnv, "table") expect(2, sProgramPath, "string") local previousTerm = term.current() setMenuVisible(#tProcesses + 1 >= 2) local nResult = launchProcess(false, tProgramEnv, sProgramPath, ...) redrawMenu() term.redirect(previousTerm) return nResult end --- Get the number of processes within this multishell. -- -- @treturn number The number of processes. function threading.getCount() return #tProcesses end -- Begin parentTerm.clear() setMenuVisible(false) launchProcess(true, { ["shell"] = shell, ["multishell"] = multishell, }, "/boot/.run") if not fs.exists("/services") then fs.makeDir("/services") end for _, sFile in ipairs(fs.list("/services")) do if string.sub(sFile, 1, 1) ~= "." then local sPath = "/services/" .. sFile launchProcess(false, { ["shell"] = shell, ["multishell"] = multishell, }, sPath) end end -- Run processes while #tProcesses > 0 do -- Get the event local tEventData = table.pack(os.pullEventRaw()) local sEvent = tEventData[1] if sEvent == "term_resize" then -- Resize event w, h = parentTerm.getSize() resizeWindows() redrawMenu() elseif sEvent == "char" or sEvent == "key" or sEvent == "key_up" or sEvent == "paste" or sEvent == "terminate" then -- Keyboard event -- Passthrough to current process resumeProcess(nCurrentProcess, table.unpack(tEventData, 1, tEventData.n)) if cullProcess(nCurrentProcess) then setMenuVisible(#tProcesses >= 2) redrawMenu() end elseif sEvent == "mouse_click" then -- Click event local button, x, y = tEventData[2], tEventData[3], tEventData[4] if bShowMenu and y == 1 then -- Switch process if x == 1 and nScrollPos ~= 1 then nScrollPos = nScrollPos - 1 redrawMenu() elseif bScrollRight and x == term.getSize() then nScrollPos = nScrollPos + 1 redrawMenu() else local tabStart = 1 if nScrollPos ~= 1 then tabStart = 2 end for n = nScrollPos, #tProcesses do local tabEnd = tabStart + #tProcesses[n].sTitle + 1 if x >= tabStart and x <= tabEnd then selectProcess(n) redrawMenu() break end tabStart = tabEnd + 1 end end else -- Passthrough to current process resumeProcess(nCurrentProcess, sEvent, button, x, bShowMenu and y - 1 or y) if cullProcess(nCurrentProcess) then setMenuVisible(#tProcesses >= 2) redrawMenu() end end elseif sEvent == "mouse_drag" or sEvent == "mouse_up" or sEvent == "mouse_scroll" then -- Other mouse event local p1, x, y = tEventData[2], tEventData[3], tEventData[4] if bShowMenu and sEvent == "mouse_scroll" and y == 1 then if p1 == -1 and nScrollPos ~= 1 then nScrollPos = nScrollPos - 1 redrawMenu() elseif bScrollRight and p1 == 1 then nScrollPos = nScrollPos + 1 redrawMenu() end elseif not (bShowMenu and y == 1) then -- Passthrough to current process resumeProcess(nCurrentProcess, sEvent, p1, x, bShowMenu and y - 1 or y) if cullProcess(nCurrentProcess) then setMenuVisible(#tProcesses >= 2) redrawMenu() end end else -- Other event -- Passthrough to all processes local nLimit = #tProcesses -- Storing this ensures any new things spawned don't get the event for n = 1, nLimit do resumeProcess(n, table.unpack(tEventData, 1, tEventData.n)) end if cullProcesses() then setMenuVisible(#tProcesses >= 2) redrawMenu() end end if bWindowsResized then -- Pass term_resize to all processes local nLimit = #tProcesses -- Storing this ensures any new things spawned don't get the event for n = 1, nLimit do resumeProcess(n, "term_resize") end bWindowsResized = false if cullProcesses() then setMenuVisible(#tProcesses >= 2) redrawMenu() end end end -- Shutdown term.redirect(parentTerm)
--[[ Copyright 2018 American Megatrends 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. --]] -- Import required libraries -- [See "redfish-handler.lua"](/redfish-handler.html) local RedfishHandler = require("redfish-handler") -- [See "constants.lua"](/constants.html) local CONSTANTS = require("constants") -- [See "utils.lua"](/utils.html) local utils = require("utils") -- [See "turbo library"](http://turbolua.org) local turbo = require("turbo") -- [See "underscore.lua"](https://mirven.github.io/underscore.lua/) local _ = require("underscore") local SystemVlanHandler = class("SystemVlanHandler", RedfishHandler) local yield = coroutine.yield -- Set the path names for system vlan OEM extensions local collection_oem_path = "system.system-vlan-collection" local instance_oem_path = "system.system-vlan-instance" SystemVlanHandler:set_all_oem_paths(collection_oem_path, instance_oem_path) --Handles GET requests for System VLANs collection and instance function SystemVlanHandler:get(id1, id2, id3) local response = {} if id3 == nil then --GET collection self:get_collection(response) else --GET instance self:get_instance(response) end self:set_response(response) self:output() end -- Handles GET System VLANs collection function SystemVlanHandler:get_collection(response) -- Before proceeding with the handler, we'll make sure the collection request is valid local collection_exists = self:parent_exists() self:assertTrue_404(collection_exists) local redis = self:get_db() local url_segments = self:get_url_segments(); local collection, instance, secondary_collection, secondary_instance, inner_collection = url_segments[1], url_segments[2], url_segments[3], url_segments[4], url_segments[5]; local prefix = "Redfish:" .. collection .. ":" .. instance .. ":" .. secondary_collection .. ":" .. secondary_instance .. ":VLANs" self:set_scope("Redfish:" .. table.concat(url_segments, ':')) -- Creating response response["Name"] = "VLAN Network Interface Collection" response["Description"] = "Collection of VLANs for this system" local odataIDs = utils.getODataIDArray(yield(redis:keys(prefix .. ":*:VLANId")), 1) response["Members@odata.count"] = #odataIDs response["Members"] = odataIDs response = self:oem_extend(response, "query." .. self:get_oem_collection_path()) self:set_context(CONSTANTS.VLAN_COLLECTION_CONTEXT) self:set_type(CONSTANTS.VLAN_COLLECTION_TYPE) -- GET requests must respond with the 'Allow' header specifying what methods are available for the given URL self:set_allow_header("GET") end -- Handles GET System VLANs instance function SystemVlanHandler:get_instance(response) local redis = self:get_db() local url_segments = self:get_url_segments(); local collection, instance, secondary_collection, secondary_instance, inner_collection, inner_instance = url_segments[1], url_segments[2], url_segments[3], url_segments[4], url_segments[5], url_segments[6]; local prefix = "Redfish:" .. collection .. ":" .. instance .. ":" .. secondary_collection .. ":" .. secondary_instance .. ":VLANs:" .. inner_instance self:set_scope("Redfish:"..table.concat(url_segments,':')) --Retrieving data from database local pl = redis:pipeline() pl:mget({ prefix .. ":Name", prefix .. ":Description", prefix .. ":VLANEnable", prefix .. ":VLANId" }) local db_result = yield(pl:run()) -- Check that data was found in Redis, if not we throw a 404 NOT FOUND self:assert_resource(db_result) local general = unpack(db_result) --Creating response using data from database response["Id"] = inner_instance response["Name"] = general[1] response["Description"] = general[2] response["VLANEnable"] = utils.bool(general[3]) response["VLANId"] = tonumber(general[4]) response = self:oem_extend(response, "query." .. self:get_oem_instance_path()) utils.remove_nils(response) local keys = _.keys(response) if #keys < 5 then local select_list = turbo.util.join(",", keys) self:set_context(CONSTANTS.VLAN_INSTANCE_CONTEXT.."(" .. select_list .. ")") else self:set_context(CONSTANTS.VLAN_INSTANCE_CONTEXT) end self:set_type(CONSTANTS.VLAN_TYPE) -- GET requests must respond with the 'Allow' header specifying what methods are available for the given URL self:set_allow_header("GET, PATCH") end --Handles PATCH request for System VLANs Interface function SystemVlanHandler:patch() local url_segments = self:get_url_segments() local collection, instance, secondary_collection, secondary_instance, inner_collection, inner_instance = url_segments[1], url_segments[2], url_segments[3], url_segments[4], url_segments[5], url_segments[6]; --Throwing error if request is to collection if inner_instance == nil then -- Allow an OEM patch handler for system vlan collections, if none exists, return with the normal 405 response self:set_header("Allow", "GET") self:set_status(405) response = self:oem_extend(response, "patch." .. self:get_oem_collection_path()) if self:get_status() == 405 then self:error_method_not_allowed() end else -- Allow the OEM patch handlers for system vlan instances to have the first chance to handle the request body response = self:oem_extend(response, "patch." .. self:get_oem_instance_path()) end --Making sure current user has permission to modify VLANs settings if self:can_user_do("ConfigureComponents") == true then local redis = self:get_db() local prefix = "Redfish:" .. collection .. ":" .. instance .. ":" .. secondary_collection .. ":" .. secondary_instance .. ":" .. inner_collection .. ":" .. inner_instance local response = {} local vlan_exists = yield(redis:exists(prefix .. ":VLANId")) if vlan_exists ~= 1 then self:error_resource_missing_at_uri() else local request_data = turbo.escape.json_decode(self:get_request().body) self:set_scope("Redfish:" .. table.concat(url_segments, ":")) local pl = redis:pipeline() local extended = {} local successful_sets = {} --Validating VLANEnable property and adding error if property is incorrect if request_data.VLANEnable ~= nil then if type(request_data.VLANEnable) ~= "boolean" then table.insert(extended, self:create_message("Base", "PropertyValueTypeError", {"#/VLANEnable"}, {request_data.VLANEnable, "VLANEnable"})) else --VLANEnable is valid and will be added to database pl:set(prefix .. ":VLANEnable", tostring(request_data.VLANEnable)) table.insert(successful_sets, "VLANEnable") end request_data.VLANEnable = nil end --Validating VLANId and adding property or adding error if property is incorrect if request_data.VLANId ~= nil then if tonumber(request_data.VLANId) == nil then table.insert(extended, self:create_message("Base", "PropertyValueTypeError", {"#/VLANId"}, {request_data.VLANId, "VLANId"})) elseif tonumber(request_data.VLANId) <= 0 or tonumber(request_data.VLANId) >= 4095 then table.insert(extended, self:create_message("Base", "PropertyValueFormatError", {"#/VLANId"}, {request_data.VLANId, "VLANId"})) else --VLANId is valid and will be added to database pl:set(prefix .. ":VLANId", request_data.VLANId) table.insert(successful_sets, "VLANId") end request_data.VLANId = nil end local result = yield(pl:run()) self:add_audit_log_entry(self:create_message("Security", "ResourceModified", nil, {turbo.util.join(", ", successful_sets), self:get_request().path})) local leftover_fields = utils.table_len(request_data) --Checking if there are any additional properties in the request and creating an error to show these properties if leftover_fields ~= 0 then local keys = _.keys(request_data) table.insert(extended, self:create_message("Base", "PropertyNotWritable", keys, turbo.util.join(",", keys))) end --Checking if there were errors and adding them to the response if there are if #extended ~= 0 then response["@Message.ExtendedInfo"] = extended end self:get_instance(response) end self:set_response(response) self:output() else --Throwing error if user is not authorized self:error_insufficient_privilege() end end return SystemVlanHandler
--[[ Get title for current song from external source ]]-- local settings = { radio_title_helper = "radio_title_helper", -- Path to Radio title helper interval = 10, -- Renew every 10 seconds (default) radios = {"fip", "franceculture", "francemusique", "tsfjazz", "franceinter", "rfimonde", "rfiafrique", "kexp"}, -- enable script for these radios (keyword must be in stream url) } require 'mp.options' read_options(settings, "radiotitle") local msg = require 'mp.msg' local utils = require 'mp.utils' local failures = 0 function get_song_name() local radio_url = mp.get_property('stream-open-filename') t = {} t.args = {settings.radio_title_helper, radio_url} res = utils.subprocess(t) if res.status == 0 then failures = 0 return res.stdout else failures = failures + 1 if failures == 3 then mp.msg.error("Could not retrieve title") end end end function change_title() local title = mp.get_property('media-title') local new_title = get_song_name() if new_title and title ~= new_title then mp.set_property("file-local-options/force-media-title", new_title) msg.info("Now playing "..new_title) end mp.add_timeout(settings.interval, change_title) end function enable_script() local radio_url = mp.get_property('stream-open-filename') for index, radio in ipairs(settings.radios) do if string.find(radio_url, radio) then change_title() end end end -- Wait 5s for mpv to open stream mp.add_timeout(5, enable_script)
package.path = '../../src/lua/?.lua;' .. package.path tools = require('tools') myTableHeaders, myTableRows = tools.csv('../../data/weather.csv') assert(#myTableHeaders == 6, 'wrong number of header columns') for i = 1, #myTableRows do assert(#myTableRows[i] == #myTableHeaders, string.format('row %d: %d number cols does not match header number cols %d', i, #myTableRows[i], #myTableHeaders)) end
io.write "Something\n" Point = {} Point.new = function(x, y) local self = {} x = x or 0 x = y or 0 self.getx = function() return x end self.gety = function() return y end self.write = function() io.write(string.format("(%d, %d)\n", x, y)) end return self end p = Point.new(2,5) p.write() function HelloWorld() io.write "Hello, World!\n" local test = true if test == true then io.write "it's true!\n" end end
--[[ Template script for Loading necessary packages and functions. This file is part of the CTSeg project. Stavros Tsogkas <stavros.tsogkas@centralesupelec.fr> Last update: October 2016 --]] -------------------------------------------------------------------------------- -- Load modules -------------------------------------------------------------------------------- require "torch" require "trepl" require "optim" require "image" require "nn" config = require "config" networks = require "networks" misc = require "misc" -------------------------------------------------------------------------------- -- Define training and testing functions -------------------------------------------------------------------------------- function computeErrorStats(prediction,labels) -- prediction: Bx1xDxHxW, labels: BxDxHxW local s = {} prediction = prediction:float() labels = labels:float() assert(prediction:nElement() == labels:nElement()) s.numExamples = labels:nElement() s.correct = prediction:eq(labels):sum() s.accuracy = s.correct/s.numExamples s.truePos = labels[prediction:eq(1)]:eq(1):sum() s.falsePos = labels[prediction:eq(1)]:eq(2):sum() s.trueNeg = labels[prediction:eq(2)]:eq(2):sum() s.falseNeg = labels[prediction:eq(2)]:eq(1):sum() s.numPos = labels:eq(1):sum() s.numNeg = labels:eq(2):sum() s.precision = s.truePos/math.max(1, s.truePos + s.falsePos) s.recall = s.truePos/math.max(1, s.truePos + s.falseNeg) s.specificity = s.trueNeg/math.max(1,s.trueNeg + s.falsePos) s.fmeasure = 2 * s.precision * s.recall / math.max(1, s.precision + s.recall) return s end -- Return mini-batch of scores from previously trained networks ---------------- function getBatch(data, inds) local images = data.images:index(1, inds) local labels = data.labels:index(1, inds) local sz = images:size() local containsPositives = util.any(images:view(sz[1],-1),2):sum():gt(0) -- Include at least one positive example in the batch if not containsPositives and posSlices then local inds = torch.randperm(data.images:size(1)) images[1]:copy(data.images[inds[1]]) end images = images:view(sz[1],1,sz[2],sz[3]) -- add a singleton dimension if cuda then images = images:cuda() labels = labels:cuda() else images = images:float() labels = labels:float() end return images, labels end -- Execute a single epoch of training (or validation) ------------------------- function processEpoch(epoch, mode, data) if not data then return end local train = mode == 'train' or mode == 'training' or mode == 'Train' or mode == 'TRAIN' local numExamples = data.images:size(1); local numBatches = math.ceil(numExamples/opts.batchSize) local lossTotal = 0 local inds = torch.randperm(numExamples):long() -- shuffle training examples if train then model:training() else model:evaluate() end -- Configure optimizer optimState = { learningRate = learningRate and learningRate[epoch] or opts.LR, learningRateDecay = learningRateDecay and learningRateDecay[epoch] or opts.LRDecay, weightDecay = weightDecay and weightDecay[epoch] or opts.weightDecay, momentum = momentum and momentum[epoch] or opts.momentum, dampening = 0 } print('\n--------------- ' .. mode .. ' epoch ' .. epoch .. '/' .. opts.numEpochs ..' [#examples = ' .. numExamples .. ', batchSize = ' .. opts.batchSize .. ', #batches: ' .. numBatches .. '] ----------------') if train then print('Optimization parameters:'); print(optimState) end -- Train using batches epochTimer = epochTimer or torch.Timer(); epochTimer:reset() for t = 1, numExamples, opts.batchSize do local imageBatch, labelBatch = getBatch(data, inds[{ {t,math.min(t+opts.batchSize-1, numExamples)} }]) -- Assertions assert(imageBatch:dim() == 4, 'Image batch should be a 5D array') assert(labelBatch:dim() == 3, 'Label batch should be a 4D array') -- closure to evaluate f(X) and df/dX (L and dL/dw) collectgarbage() local loss = 0 local outputBatch = model:forward(imageBatch) -- BxLxDxHxW local function feval(x) gradParameters:zero() local gradOutput loss, gradOutput = networks.spatialCrossEntropy(outputBatch,labelBatch,weights) model:backward(imageBatch,gradOutput) return loss, gradParameters end if train then -- optimize on current mini-batch optim.sgd(feval, parameters, optimState) end -- Print stats for current batch local maxScores,prediction = outputBatch:max(2) -- max score over labels (B1DHW) prediction, labelBatch = prediction:float():view(-1), labelBatch:float():view(-1) confusion:batchAdd(prediction,labelBatch) --print(confusion) local s, batch = computeErrorStats(prediction,labelBatch), math.ceil(t/opts.batchSize) lossTotal = lossTotal + loss printEpochMessage(lossTotal,epoch,batch,numBatches,mode,s,opts) if train then stats.train = s else stats.val = s end end -- for t = 1, numExamples, opts.batchSize -- print and reset confusion matrix and timings print(''); print(confusion); confusion:zero() print('') print('==> Time for epoch: ' .. misc.time2string(epochTimer:time().real) .. ', time per sample: ' .. misc.time2string(epochTimer:time().real/numExamples) ) end -- Print epoch message with loss and accuracy information ---------------------- function printEpochMessage(lossTotal,epoch,batch,numBatches,mode,s,opts) local batchInfo = string.format('%s %s Epoch %d/%d, Batch %d/%d || LOSS: %-6.4f', mode, opts.class, epoch, opts.numEpochs, batch, numBatches, lossTotal/batch) local accInfo if numClasses == 2 then accInfo = string.format(' PRE: %4.1f%% REC: %4.1f%% SPC: %4.1f%% FM: %.3f', s.precision*100,s.recall*100, s.specificity*100, s.fmeasure) elseif numClasses > 2 then confusion:updateValids() accInfo = '' for i=1,numClasses do -- print('') -- print(confusion.valids) -- print(confusion.valids[i]) accInfo = accInfo..string.format(' C%d: %.2f%%',i, confusion.valids[i]*100) end end print(batchInfo..accInfo) end -- Continue from checkpoint ---------------------------------------------------- function loadState(modelPath) local state = torch.load(modelPath) model = state.model optimState = state.optimState if cuda then -- copy to gpu before using for computations model:cuda() end parameters, gradParameters = model:getParameters() end -- Save progress --------------------------------------------------------------- function saveState(modelPath) -- Save batch normalization stats before clearing state (which deletes them) local batchNormStats = {} for i=1,model:size() do local layer = model:get(i) if layer.__typename == 'nn.VolumetricBatchNormalization' or layer.__typename == 'nn.SpatialBatchNormalization' then batchNormStats[i] = {layer.save_mean, layer.save_std} end end model:clearState() -- Clear intermediate variables -- Copy back bnorm mean and std for i=1,model:size() do local layer = model:get(i) if layer.__typename == 'nn.VolumetricBatchNormalization' or layer.__typename == 'nn.SpatialBatchNormalization' then layer.save_mean = batchNormStats[i].save_mean layer.save_std = batchNormStats[i].save_std end end -- Copy on CPU and save complete state local model = model:clone():float() local state = { model = model, optimState = optimState, stats = stats, opts = opts, confusion = confusion, paramRegimes = paramRegimes } torch.save(modelPath, state) end -- Training code --------------------------------------------------------------- function train(data) -- Display network information print('Loaded '..data.train.images:size(1)..' training examples (' .. misc.size2string(data.train.images)..')') local numInputChannels = nets and #nets*2 or 1 local dummyInput = torch.Tensor(opts.batchSize,numInputChannels,data.train.images:size(2),data.train.images:size(3)) if cuda then dummyInput = dummyInput:cuda() end print('Network architecture: ' .. opts.net) print('Weight initialization: ' .. opts.initMethod .. ' with parameters ' .. opts.initWeight .. '/' .. opts.initBias .. ' (if applicable)') networks.displayNetInfo(model,dummyInput) -- Set parameter regimes learningRate = torch.logspace(math.log10(opts.LR), math.log10(opts.LR/100), opts.numEpochs) confusion = optim.ConfusionMatrix(numClasses) stats = {} -- save stats in global variable paramRegimes = {} paramRegimes.learningRate = learningRate or opts.LR paramRegimes.learningRateDecay = learningRateDecay or opts.LRDecay paramRegimes.weightDecay = weightDecay or opts.weightDecay paramRegimes.momentum = momentum or opts.momentum -- WARNING: This command goes AFTER transfering the network to the GPU! -- Retrieve parameters and gradients: -- extracts and flattens all the trainable parameters of the model into a vector -- Parameters are references: when model:backward is called, these are changed parameters,gradParameters = model:getParameters() local trainTimer = torch.Timer() for epoch = 1, opts.numEpochs do local function epoch2modelPath(epoch) return paths.concat(opts.saveDir, 'model-epoch-' .. epoch .. '.t7') end if opts.load > 0 and paths.filep(epoch2modelPath(epoch)) then if not paths.filep(epoch2modelPath(epoch+1)) then print('\n==> Last checkpoint found: loading state from epoch ' .. epoch) loadState(epoch2modelPath(epoch)) end else processEpoch(epoch, 'train', data.train) processEpoch(epoch, 'val', data.val) if opts.save > 0 then print('\n==> Saving model (epoch ' .. epoch .. ')...') saveState(epoch2modelPath(epoch)) end end end print('Done training for ' .. opts.numEpochs .. ' epochs!') print('Total time for training: '..misc.time2string(trainTimer:time().real)) end -- Evaluation code ------------------------------------------------------------- function evaluate(data) -- Setup evaluation print(''); print('Setting up evaluation...') model:evaluate() confusion = optim.ConfusionMatrix(numClasses); confusion:zero() softmax = nn.SpatialSoftMax() stats = {} -- Move to gpu if cuda then softmax = softmax:cuda() end -- Test and compute stats for each volume local testTimer = torch.Timer() local volTimer = torch.Timer() local numTest = #data - opts.numTrain - opts.numVal print('Testing on '..numTest..' volumes...') for i=opts.numTrain+opts.numVal+1,#data do if data[i] then print('Testing on volume ' .. i - opts.numTrain - opts.numVal .. '/' .. numTest .. '...') local img, seg = data[i].img.data:float(), data[i].seg.data:float() -- DxHxW local scores = torch.FloatTensor(numClasses,img:size(1),img:size(2),img:size(3)) -- Remove extreme values and fix groundtruth seg. Our assumption is -- that 0 corresponds to examples that are ignored and numClasses+1 -- corresponds to background pixels. seg[seg:eq(0)] = numClasses if cuda then img = img:cuda() scores = scores:cuda() end -- Compute scores for each slice individually volTimer:reset() for j=1,img:size(1) do scores[{ {}, j, {}, {} }]:copy(model:forward(img[j]:view(1,1,img:size(2),img:size(3)))) end print('Time for '..img:size(2)..'x'..img:size(3)..'x'..img:size(1)..' volume:' ..misc.time2string(volTimer:time().real)) scores = softmax:forward(scores:view(scores:size(1),scores:size(2),-1)):float() assert(torch.all(scores:ge(0)) and torch.all(scores:le(1))) local maxScores, predictions = scores:max(1) assert(torch.all(predictions:ge(1)) and torch.all(predictions:le(numClasses))) assert(predictions:nElement() == seg:nElement()) -- Compute stats confusion:batchAdd(predictions:view(-1),seg:view(-1)) stats[#stats+1] = computeErrorStats(predictions, seg) print(confusion) print('') collectgarbage() else print('Skipping volume '..i..' (empty)') end end print('Total time for testing: '..misc.time2string(testTimer:time().real)) -- Save results on test data print('') print('===> Performance on the full test set:') print(confusion) torch.save(paths.concat(opts.saveDir, 'testSetPerformance.t7'), {stats = stats, confusion = confusion}) end
local cjson = require "cjson.safe" local http = require "resty.http" local hmac = require("crypto").hmac local ipairs = ipairs local pairs = pairs local ngx_http_time = ngx.http_time local ngx_re_gsub = ngx.re.gsub local ngx_time = ngx.time local setmetatable = setmetatable local string_byte = string.byte local string_format = string.format local string_upper = string.upper local table_concat = table.concat local table_insert = table.insert local table_sort = table.sort local _M = {} local mt = { __index = _M } local API_PREFIX = "/auth/v2/" local POST_ENDPOINTS = { enroll = true, enroll_status = true, preauth = true, auth = true, } local function url_encode_replace(c) return string_format("%%%02X", string_byte(c[1])) end local function url_encode(s) return ngx_re_gsub(s, [[([^\w\-\._~])]], url_encode_replace, "oj") end -- lexographically sort params and return as an ampersand-separated string local function canon_params(params) if not params then return "" end local p, pt = {}, {} for k, _ in pairs(params) do table_insert(pt, k) end table_sort(pt) for _, k in ipairs(pt) do table_insert(p, string_format("%s=%s", k, url_encode(params[k]))) end return table_concat(p, "&") end -- see https://duo.com/docs/authapi#authentication local function sign(method, host, path, params, ikey, skey) local date = ngx_http_time(ngx_time()) local sign_t = { date, method, host, path, params } local sig = string_upper(hmac.digest("sha1", table_concat(sign_t, "\n"), skey)) return date, ngx.encode_base64(string_format("%s:%s", ikey, sig)) end _M.sign = sign local function duo_request(self, endpoint, api_params) local is_post = POST_ENDPOINTS[endpoint] local method = is_post and "POST" or "GET" local params = canon_params(api_params) local path = string_format("https://%s%s%s", self.host, API_PREFIX, endpoint) local date, sig = sign(method, self.host, API_PREFIX .. endpoint, params, self.ikey, self.skey) local headers = { ["Date"] = date, ["Authorization"] = "Basic " .. sig, } local req_tab = { method = method, headers = headers, } if is_post then req_tab.headers["Content-Type"] = "application/x-www-form-urlencoded" req_tab.body = params else req_tab.query = params end return http.new():request_uri(path, req_tab) end _M.duo_request = duo_request local function read_duo_response(res, err) if not res then return nil, err end if res.status ~= 200 then return nil, res.body end local body, err = cjson.decode(res.body) if err then return nil, "Failed to decode Duo API response body" end if body.stat ~= "OK" then return nil, res.body end return body.response end function _M:enroll(username) return read_duo_response(duo_request(self, "enroll", { username = username, })) end function _M:preauth(username, ip) return read_duo_response(duo_request(self, "preauth", { username = username, ipaddr = ip, })) end function _M:auth(username, factor, opts) local params = { username = username, factor = factor, } for k, v in pairs(opts) do params[k] = v end return read_duo_response(duo_request(self, "auth", params)) end function _M.new(params) return setmetatable(params, mt) end return _M
-- lua/rs/UmbraMixin.lua Script.Load("lua/MapConnector.lua") MinimapConnectionMixin = CreateMixin( MinimapConnectionMixin ) MinimapConnectionMixin.type = "MinimapConnection" MinimapConnectionMixin.expectedMixins = { Team = "For team number." } MinimapConnectionMixin.expectedCallbacks = { GetConnectionStartPoint = "For map connector.", GetConnectionEndPoint = "For map connector." } local kUpdateRate = 0.5 function MinimapConnectionMixin:__initmixin() if Server then self:AddTimedCallback(MinimapConnectionMixin.OnTimedUpdate, kUpdateRate) end end if Server then function MinimapConnectionMixin:OnTimedUpdate(deltaTime) local endPoint = self:GetConnectionEndPoint() local startPoint = self:GetConnectionStartPoint() if (not endPoint or not startPoint) and self.connectorId then local connector = Shared.GetEntity(self.connectorId) if connector then DestroyEntity(connector) end self.connectorId = nil elseif endPoint and startPoint and not self.connectorId then self.connectorId = CreateEntity(MapConnector.kMapName, startPoint, self:GetTeamNumber()):GetId() end if endPoint and startPoint and self.connectorId then local connector = Shared.GetEntity(self.connectorId) assert(connector) connector:SetOrigin(startPoint) connector:SetEndPoint(endPoint) end return true end function MinimapConnectionMixin:OnDestroy() if self.connectorId then local connector = Shared.GetEntity(self.connectorId) if connector then DestroyEntity(connector) end self.connectorId = nil end end end
function ui.sectionHead ( arg1, arg2 ) local class = "sectionHead" local content if arg2 then class = class .. " " .. arg1 content = arg2 else content = arg1 end ui.container { attr = { class = class }, content = content } end
require "busted.runner" () local assert = require "luassert" describe ("c3 algorithm implementation", function () it ("can be required", function() assert.has.no.errors (function () require "c3" end) end) it ("can be instantiated", function () assert.has.no.error (function () local C3 = require "c3" C3 { superclass = function (x) return x end, } end) end) it ("detects non-callable superclass", function () assert.has.error (function () local C3 = require "c3" C3 { superclass = true, } end) end) it ("linearizes correctly a hierarchy", function () local C3 = require "c3" local c3 = C3 { superclass = function (x) return x end, } local o = {} local a = { o, } local b = { o, } local c = { o, } local d = { o, } local e = { o, } local k1 = { c, b, a, } local k2 = { e, b, d, } local k3 = { d, a, } local z = { k3, k2, k1, } assert.are.same (c3 (o ), { o, }) assert.are.same (c3 (a ), { o, a, }) assert.are.same (c3 (b ), { o, b, }) assert.are.same (c3 (c ), { o, c, }) assert.are.same (c3 (d ), { o, d, }) assert.are.same (c3 (e ), { o, e, }) assert.are.same (c3 (k1), { o, c, b, a, k1, }) assert.are.same (c3 (k2), { o, e, b, d, k2, }) assert.are.same (c3 (k3), { o, a, d, k3, }) assert.are.same (c3 (z ), { o, e, c, b, a, d, k3, k2, k1, z, }) end) it ("handles cycles", function () local C3 = require "c3" local c3 = C3 { superclass = function (x) return x end, } local a, b = {}, {} a [1] = b b [1] = a assert.are.same (c3 (a), { b, a, }) assert.are.same (c3 (b), { a, b, }) end) it ("reports an error when linearization is not possible", function () local C3 = require "c3" local c3 = C3 { superclass = function (x) return x end, } local a, b = {}, {} a [1] = b b [1] = a local c = { a, b, } local ok, err = pcall (c3, c) assert.is_falsy (ok) assert.is_truthy (type (err) == "table") end) it ("allows to clear the cache", function () assert.has.no.error (function () local C3 = require "c3" local c3 = C3 { superclass = function (x) return x end, } c3:clear () end) end) end)
package.loaded["libvenus"] = nil local venus = require("libvenus") local shell = require("shell") local filesystem = require("filesystem") local args, ops = shell.parse(...) if #args < 1 then io.stderr:write("Usage: venus <init|push>\n") return end local cmd = args[1] if cmd == "init" then local dir = args[2] or shin32.getenv("PWD_DRIVE") .. ":/" .. shin32.getenv("PWD") if args[2] then dir = shell.resolve(dir) end if dir == nil then io.stderr:write("Invalid directory or could not retrieve PWD\n") return end filesystem.makeDirectory(dir .. "/.venus") local master = venus.branch(venus.newKey(), "master") local readme = venus.file(venus.newKey(), "README.md", master, "# New Project") local s = io.open(dir .. "/README.md", "w") -- manually sync with directory s:write("# New Project") s:close() local commit = venus.commit(venus.newKey(), "Initial commit", {master, readme}) venus.writeObjects(dir .. "/.venus", {master, readme, commit}) end
-- Simple input handler for gui nodes. Register nodes and pass any call to -- on_input() to this module and it will automatically do picking and invoke -- a registered callback. Example: -- -- local input_gui = require "in.gui" -- -- function init(self) -- input_gui.acquire() -- -- input_gui.register(gui.get_node("blue"), function() -- print("blue") -- end) -- -- input_gui.register("green", function() -- print("green") -- local scale = math.random(1, 5) -- gui.set_scale(gui.get_node("blue"), vmath.vector3(scale, scale, 1)) -- end) -- end -- -- function final(self) -- input_gui.release() -- end -- -- function on_input(self, action_id, action) -- input_gui.on_input(action_id, action) -- end local M = {} M.TOUCH = hash("touch") local EMPTY_HASH = hash("") local registered_nodes = {} local index_count = 0 local function ensure_node(node_or_node_id) return type(node_or_node_id) == "string" and gui.get_node(node_or_node_id) or node_or_node_id end local function hash_to_hex(h) return h and _G.hash_to_hex(h) or "" end local function node_to_key(node) local url = msg.url() local id = gui.get_id(node) if id == EMPTY_HASH then id = hash("defold-input-button_" .. tostring(index_count)) gui.set_id(node, id) index_count = index_count + 1 end return hash_to_hex(url.socket) .. hash_to_hex(url.path) .. hash_to_hex(url.fragment) .. hash_to_hex(id) end --- Convenience function to acquire input focus function M.acquire() msg.post(".", "acquire_input_focus") end --- Convenience function to release input focus function M.release() msg.post(".", "release_input_focus") end --- Register a node and a callback to invoke when it is clicked function M.register(node_or_string, callback) assert(node_or_string, "You must provide a node") assert(callback, "You must provide a callback") local node = ensure_node(node_or_string) assert(node, "You must provide an existing node or node name") local key = node_to_key(node) registered_nodes[key] = { url = msg.url(), callback = callback, node = node, scale = gui.get_scale(node) } return node end --- Unregister a previously registered node or all nodes -- registered from the calling script -- @param node_or_string function M.unregister(node_or_string) if not node_or_string then local url = msg.url() for k,registered_node in pairs(registered_nodes) do if registered_node.url == url then registered_nodes[k] = nil end end else local node = ensure_node(node_or_string) assert(node, "You must provide an existing node or node name") local key = node_to_key(node) assert(registered_nodes[key], "You must provide the id of a registered node") registered_nodes[key] = nil end end function M.dump() local url = msg.url() for k,registered_node in pairs(registered_nodes) do if registered_node.url == url then print(k, registered_node.node) end end end local function shake(node, initial_scale) gui.cancel_animation(node, "scale.x") gui.cancel_animation(node, "scale.y") gui.set_scale(node, initial_scale) local scale = gui.get_scale(node) gui.set_scale(node, scale * 1.2) gui.animate(node, "scale.x", scale.x, gui.EASING_OUTELASTIC, 0.8) gui.animate(node, "scale.y", scale.y, gui.EASING_OUTELASTIC, 0.8, 0.05, function() gui.set_scale(node, initial_scale) end) end local function is_enabled(node) local enabled = gui.is_enabled(node) local parent = gui.get_parent(node) if not enabled or not parent then return enabled else return is_enabled(parent) end end local function find_registered_node(x, y) local url = msg.url() for _,registered_node in pairs(registered_nodes) do if registered_node.url == url then local node = registered_node.node if is_enabled(node) and gui.pick_node(node, x, y) then return registered_node end end end end --- Forward on_input calls to this function to detect input -- for registered nodes -- @param action_id, -- @param action -- @return true if input a registerd node received input function M.on_input(action_id, action) if action_id == M.TOUCH then if action.pressed then local registered_node = find_registered_node(action.x, action.y) if registered_node then registered_node.pressed = true return true end elseif action.released then local registered_node = find_registered_node(action.x, action.y) local pressed = registered_node and registered_node.pressed local url = msg.url() for _,registered_node in pairs(registered_nodes) do if registered_node.url == url then registered_node.pressed = false end end if pressed then shake(registered_node.node, registered_node.scale) registered_node.callback() end return pressed end end return false end return M
joystick = nil shootModes = { primarySecondary = 1, rotating = 2, } function love.joystickadded(j) joystick = j end function isReasonable(key) return key ~= "shift" and key ~= "lshift" and key ~= "rshift" and key ~= "up" and key ~= "down" and key ~= "left" and key ~= "right" end function handleJoystick(dt) if joystick ~= nil then if joystick:isGamepadDown("back") then byebye() end if joystick:isGamepadDown("dpleft") then move("left", dt) end if joystick:isGamepadDown("dpright") then move("right", dt) end if joystick:isGamepadDown("dpup") then move("up", dt) end if joystick:isGamepadDown("dpdown") then move("down", dt) end -- shooting if joystick:isGamepadDown("a", "b") then shoot() end end end function handleKeyboard(dt) if love.keyboard.isDown("escape") then switchToMenu() end if love.keyboard.isDown("left", "a") then move("left", dt) end if love.keyboard.isDown("right", "d") then move("right", dt) end if love.keyboard.isDown("up", "w") then move("up", dt) end if love.keyboard.isDown("down", "s") then move("down", dt) end -- shooting if love.keyboard.isDown("space") then shoot() end if love.keyboard.isDown("x", "z") then shoot(secondaryWeapon) end end function love.gamepadreleased(joystick, key) if gameState == gameStates.level then if not gameover then if key == "leftshoulder" or key == "rightshoulder" or key == "x" or key == "y" then switchWeapon(key == "leftshoulder" or key == "x") elseif key == "start" then paused = not paused elseif key == "back" then switchToMenu() end else if gameoverTimeout < 0 then gameover = false if key == "back" then byebye() else switchToMenu() end end end elseif gameState == "menu" and isMenuIdle() then if key == "back" then byebye() else gameState = gameStates.level resetLevelState() end end end function love.keyreleased(key) if gameState == gameStates.level then if not gameover then if key == "shift" or key == "lshift" or key == "rshift" then switchWeapon() elseif key == "p" then paused = not paused elseif key == "m" then mute = not mute elseif key == "q" then switchToMenu() end else if gameoverTimeout < 0 then gameover = false if key == "q" or key == "escape" then byebye() else switchToMenu() end end end elseif gameState == gameStates.menu and isMenuIdle() then if key == "q" or key == "escape" then byebye() elseif isReasonable(key) then gameState = gameStates.level resetLevelState() end end end
isFirstSpawn = true AddEventHandler("playerSpawned", function() -- Give the basic player model local model = GetHashKey("mp_m_freemode_01") RequestModel(model) while not HasModelLoaded(model) do RequestModel(model) Citizen.Wait(1) end SetPlayerModel(PlayerId(), model) SetModelAsNoLongerNeeded(model) SetPedDefaultComponentVariation(GetPlayerPed(PlayerId())) if isFirstSpawn == true then StartPlayerTeleport(PlayerId(), -220.98, -1080.87, 29.29, 77, true, true, true) --Display messages when player join the game for the first time displayJoinMessages() isFirstSpawn = false else -- Teleport to the nearest hospital StartPlayerTeleport(PlayerId(), 305.03, -1433.3, 29.8, 154.64, true, true, true) end end)
-- Stateless fromto with step parameter function fromto(n, m, s) function iter(state, ix) ix = ix + state.step if ix > state.max then return nil else return ix, state end end return iter, {max=m, step=s}, n - s end io.write('Give me a start number: ') local min = io.read('*number') io.write('Give me an end number: ') local max = io.read('*number') io.write('Give me a step: ') local step = io.read('*number') for ix in fromto(min, max, step) do print(ix) end
local function God(ply, cmd, args) if not FAdmin.Access.PlayerHasPrivilege(ply, "God") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end local targets = FAdmin.FindPlayer(args[1]) if not targets or #targets == 1 and not IsValid(targets[1]) then FAdmin.Messages.SendMessage(ply, 1, "Player not found") return false end for _, target in pairs(targets) do if IsValid(target) and not target:FAdmin_GetGlobal("FAdmin_godded") then target:FAdmin_SetGlobal("FAdmin_godded", true) target:GodEnable() end end FAdmin.Messages.FireNotification("god", ply, targets) return true, targets end local function Ungod(ply, cmd, args) if not FAdmin.Access.PlayerHasPrivilege(ply, "God") then FAdmin.Messages.SendMessage(ply, 5, "No access!") return false end local targets = FAdmin.FindPlayer(args[1]) if not targets or #targets == 1 and not IsValid(targets[1]) then FAdmin.Messages.SendMessage(ply, 1, "Player not found") return false end for _, target in pairs(targets) do if IsValid(target) and target:FAdmin_GetGlobal("FAdmin_godded") then target:FAdmin_SetGlobal("FAdmin_godded", false) target:GodDisable() end end FAdmin.Messages.FireNotification("ungod", ply, targets) return true, targets end FAdmin.StartHooks["God"] = function() FAdmin.Messages.RegisterNotification{ name = "god", hasTarget = true, message = {"instigator", " enabled godmode for ", "targets"}, receivers = "everyone", } FAdmin.Messages.RegisterNotification{ name = "ungod", hasTarget = true, message = {"instigator", " disabled godmode for ", "targets"}, receivers = "everyone", } FAdmin.Commands.AddCommand("God", God) FAdmin.Commands.AddCommand("Ungod", Ungod) FAdmin.Access.AddPrivilege("God", 2) end hook.Add("PlayerSpawn", "FAdmin_God", function() for _, ply in pairs(player.GetAll()) do if ply:FAdmin_GetGlobal("FAdmin_godded") then ply:GodEnable() end end end)
-- score vocalization assets can be downloaded at -- http://www.mediafire.com/file/mpsmto82d8diflr/Vocalize.zip -- ------------------------------------- -- Vocalization is a global table that will contain timing data -- for each digit of each available voice Vocalization = {} -- voice directories should be installed in ./Simply Love/Other/Vocalize/ -- but we can't assume that the theme directory will always be titled "Simply Love" -- maybe the path is ./Simply-Love-SM5-master/Other/Vocalize/ -- maybe the path is ./Stamina-House-Tokyo/Other/Vocalize/ -- maybe someone else has made a new theme and is using this code local vocalize_dir = THEME:GetCurrentThemeDirectory().."/Other/Vocalize/" -- what voice directories exist in ./Simply Love/Other/Vocalize/ ? local directories = FILEMAN:GetDirListing(vocalize_dir, true, false) if #directories > 0 then for i, voice_dir in ipairs(directories) do local path = vocalize_dir .. voice_dir .. "/default.lua" -- if a file exists at ./Simply Love/Other/Vocalize/[voice_dir]/default.lua if FILEMAN:DoesFileExist(path) then -- then we'll just hope that it contains nice, error-free code that will add -- digit timing data for this voice directly to the Vocalization table -- because that's the backwards-compatible corner we've backed ourselves into dofile(path) end end end -- ------------------------------------- -- a starry afternoon -- a sinking symphony -- and the polo champ -- who gave it all up -- for no reason -- whatsoever
-- SPDX-License-Identifier: MIT hexchat.register('SmartParts', '1', 'Intelligently hide parts, joins, modes, and nick changes') local TIME_THRESHOLD = 60 * 5 -- in seconds local function check_lasttalk (nick) local nick = hexchat.strip(nick) for user in hexchat.iterate('users') do if hexchat.nickcmp(nick, user.nick) == 0 then if os.time() - user.lasttalk > TIME_THRESHOLD then return hexchat.EAT_HEXCHAT else return hexchat.EAT_NONE end end end return hexchat.EAT_HEXCHAT end local function check_you (nick) return hexchat.nickcmp(hexchat.get_info('nick'), nick) == 0 end local function check_notify (nick) local nick = hexchat.strip(nick) for user in hexchat.iterate('notify') do if user.nick == nick then return true end end return false end hexchat.hook_print('Join', function (args) if check_notify (args[1]) then return hexchat.EAT_NONE else return hexchat.EAT_HEXCHAT end end, hexchat.PRI_LOW) hexchat.hook_print('Change Nick', function (args) if check_notify(args[1]) or check_notify(args[2]) then return hexchat.EAT_NONE end return check_lasttalk(args[1]) end, hexchat.PRI_LOW) hexchat.hook_print('Raw Modes', function (args) if check_you(args[1]) or check_notify(args[1]) then return hexchat.EAT_NONE end -- TODO: Parse targets return check_lasttalk(args[1]) end, hexchat.PRI_LOW) for _, event in pairs({'Quit', 'Part', 'Part with Reason'}) do hexchat.hook_print(event, function (args) if check_notify(args[1]) then return hexchat.EAT_NONE end return check_lasttalk(args[1]) end, hexchat.PRI_LOW) end for _, event in pairs({'Channel Operator', 'Channel Voices'}) do hexchat.hook_print(event, function (args) if check_you(args[1]) or check_you(args[2]) or check_notify(args[2]) then return hexchat.EAT_NONE end return check_lasttalk(args[2]) end, hexchat.PRI_LOW) end
-- handle searching finding local nav = {} nav.setup = function() local actions = require('telescope.actions') require('telescope').setup { defaults = { layout_config = { width = 0.75, prompt_position = "top", preview_cutoff = 120, horizontal = {mirror = false}, vertical = {mirror = false}, }, }, find_command = {'rg', '--no-heading', '--with-filename', '--line-number', '--column', '--smart-case'}, prompt_prefix = " ", selection_caret = " ", entry_prefix = " ", initial_mode = "insert", selection_strategy = "reset", sorting_strategy = "descending", layout_strategy = "horizontal", file_sorter = require'telescope.sorters'.get_fuzzy_file, file_ignore_patterns = {}, generic_sorter =require'telescope.sorters'.get_generic_fuzzy_sorter, path_display = {}, winblend = 0, border = {}, borderchars = {'─', '│', '─', '│', '╭', '╮', '╯', '╰'}, color_devicons = true, use_less = true, set_env = {['COLORTERM'] = 'truecolor'}, -- default = nil, file_previewer = require'telescope.previewers'.vim_buffer_cat.new, grep_previewer = require'telescope.previewers'.vim_buffer_vimgrep.new, qflist_previewer = require'telescope.previewers'.vim_buffer_qflist.new, buffer_previewer_maker = require'telescope.previewers'.buffer_previewer_maker, mappings = { i = { ["<C-j>"] = actions.move_selection_next, ["<C-k>"] = actions.move_selection_previous, ["<C-q>"] = actions.smart_send_to_qflist + actions.open_qflist, ["<esc>"] = actions.close, ["<CR>"] = actions.select_default + actions.center }, n = { ["<C-j>"] = actions.move_selection_next, ["<C-k>"] = actions.move_selection_previous, ["<C-q>"] = actions.smart_send_to_qflist + actions.open_qflist, } } } end return nav
local migration = {} function migration.global() end function migration.player_table(player_table) end function migration.subfactory(subfactory) if subfactory.icon and subfactory.icon.type == "virtual-signal" then subfactory.icon.type = "virtual" end end function migration.packed_subfactory(packed_subfactory) if packed_subfactory.icon and packed_subfactory.icon.type == "virtual-signal" then packed_subfactory.icon.type = "virtual" end end return migration
muellabfuhr = { ["Window"] = false, ["Label"] = {}, ["Button"] = {} } addEvent("onClientMuellabfuhrMarkerHit", true) addEventHandler("onClientMuellabfuhrMarkerHit", getRootElement(), function() muellabfuhr["Window"] = new(CDxWindow, "Muellabfuhr!", 200, 320, true, true, "Center|Middle") muellabfuhr["Label"][1] = new(CDxLabel, "Wilkommen bei der Muellabfuhr!\nHier haben Sie die Möglichkeit in kuerzester Zeit etwas Geld zu verdienen.\n\nLeeren sie die ausgewählte Muelltonne.", 5, 0, 190, 230, tocolor(255,255,255,255), 1, "default", "left", "center", muellabfuhr["Window"]) muellabfuhr["Button"][1] = new(CDxButton, "Starten", 5, 250, 190, 35, tocolor(255,255,255,255), muellabfuhr["Window"]) muellabfuhr["Button"][1]:addClickFunction( function() triggerServerEvent("onMuellabfuhrStart", getLocalPlayer()) muellabfuhr["Window"]:hide() delete(muellabfuhr["Window"]) muellabfuhr["Window"] = false setTimer(function() hud.hudObjects["radar"]:RefreshALShape() end, 1000,1) end ) muellabfuhr["Window"]:add(muellabfuhr["Label"][1]) muellabfuhr["Window"]:add(muellabfuhr["Button"][1]) muellabfuhr["Window"]:show() end )
--- The TestReport class encapsulates the result of a test set. -- @classmod lovecase.TestReport -- @author Fabian Staacke -- @copyright 2020 -- @license https://opensource.org/licenses/MIT local TestReport = {} TestReport.__index = TestReport TestReport.indentSpaces = 4 TestReport.failedPrefix = "FAILED: " TestReport.passedPrefix = "PASSED: " TestReport.resultLine = "\n\n%s of %s tests passing" --- Determine if the given value is an instance of the TestReport class. -- @param value The value -- @return True or false function TestReport.isInstance(value) return type(value) == "table" and getmetatable(value) == TestReport end --- Add a group to the report. -- @param groupName The group name -- @param groupFunc A function that provides the group closure function TestReport:addGroup(groupName, groupFunc) self:_writeLine(groupName) self._depth = self._depth + 1 groupFunc(self) self._depth = self._depth - 1 end --- Add a test result to the report. -- @param testName The name of the test -- @param failed True for a failed test, false otherwise -- @param[opt] reason The error message if the test failed function TestReport:addResult(testName, failed, reason) if failed then self:_writeLine(TestReport.failedPrefix .. testName) self:_writeLine(reason, self._depth + 1) self._failed = self._failed + 1 else self:_writeLine(TestReport.passedPrefix .. testName) self._passed = self._passed + 1 end end --- Get the test results formatted as string. -- @return Test results as string function TestReport:printResults() local report = table.concat(self._lines, "\n") local result = string.format( TestReport.resultLine, self._passed, self._passed + self._failed ) return report .. result end --- Get an iterator over the lines of the report. -- @return ipairs iterator -- @usage -- for i, line in report:lines() do -- print(i .. ". " .. line) -- end function TestReport:lines(callback) return ipairs(self._lines) end --- Get a (technical) string representation of the report. -- @treturn string function TestReport:__tostring() local mt = getmetatable(self) local rawString = tostring(setmetatable(self, nil)) setmetatable(self, mt) return string.format("<TestReport (%s)>", rawString) end --- Write a test line into the report. -- @param message The message to write -- @param[opt] depth The indentation depth (overrides default) function TestReport:_writeLine(message, depth) local indent = string.rep(" ", TestReport.indentSpaces * (depth or self._depth)) self._lines[#self._lines + 1] = indent .. message end return TestReport
SB.Include(Path.Join(SB_VIEW_DIR, "editor.lua")) MetalEditor = Editor:extends{} MetalEditor:Register({ name = "metalEditor", tab = "Map", caption = "Metal", tooltip = "Edit metal map", image = SB_IMG_DIR .. "minerals.png", order = 3, }) function MetalEditor:init() self:super("init") self:AddField(AssetField({ name = "patternTexture", title = "Pattern:", rootDir = "brush_patterns/terrain/", expand = true, itemWidth = 65, itemHeight = 65, Validate = function(obj, value) if value == nil then return true end if not AssetField.Validate(obj, value) then return false end local ext = Path.GetExt(value) or "" return table.ifind(SB_IMG_EXTS, ext), value end, Update = function(...) AssetField.Update(...) local texture = self.fields["patternTexture"].value SB.model.terrainManager:generateShape(texture) end })) self.btnSetMetal = TabbedPanelButton({ x = 0, y = 0, tooltip = "Left Click to set metal. Right click to remove it.", children = { TabbedPanelImage({ file = SB_IMG_DIR .. "metal-add.png" }), TabbedPanelLabel({ caption = "Set" }), }, OnClick = { function() SB.stateManager:SetState(MetalEditingState(self)) end }, }) self:AddDefaultKeybinding({ self.btnSetMetal }) self:AddControl("btn-show-metal", { Button:New { caption = "Show metal map", width = 200, height = 40, OnClick = { function() Spring.SendCommands('showmetalmap') end } }, }) self:AddField(NumericField({ name = "size", value = 100, minValue = 40, maxValue = 1000, title = "Size:", tooltip = "Size of the paint brush", })) self:AddField(NumericField({ name = "rotation", value = 0, minValue = -360, maxValue = 360, title = "Rotation:", tooltip = "Rotation of the shape", })) self:AddField(NumericField({ name = "amount", value = 5, minValue = 0, maxValue = 10, step = 0.01, title = "Amount:", tooltip = "Amount of metal", })) local children = { self.btnSetMetal, ScrollPanel:New { x = 0, y = 70, bottom = 30, right = 0, borderColor = {0,0,0,0}, horizontalScrollbar = false, children = { self.stackPanel }, }, } self:Finalize(children) end function MetalEditor:IsValidState(state) return state:is_A(MetalEditingState) end function MetalEditor:OnLeaveState(state) for _, btn in pairs({self.btnSetMetal}) do btn:SetPressedState(false) end end function MetalEditor:OnEnterState(state) self.btnSetMetal:SetPressedState(true) end
fx_version 'bodacious' game 'gta5' author 'bulva2' description 'Working bullet proof vest for LSPD' client_scripts { 'client/main.lua' } server_script 'server/main.lua' dependencies { 'es_extended' }
--[[ Main production interface ]]
local lunit, RUN = lunit do RUN = lunit and function()end or function () local res = lunit.run() if res.errors + res.failed > 0 then os.exit(-1) end return os.exit(0) end lunit = require "lunit" end local TEST_CASE = assert(lunit.TEST_CASE) local skip = lunit.skip or function() end local curl = require "lcurl" local scurl = require "lcurl.safe" local json = require "dkjson" local path = require "path" local upath = require "path".new('/') local utils = require "utils" -- local url = "http://127.0.0.1:7090/get" local fname = "./test.download" -- local GET_URL = "http://example.com" -- local POST_URL = "http://httpbin.org/post" local GET_URL = "http://127.0.0.1:7090/get" local POST_URL = "http://127.0.0.1:7090/post" -- print("------------------------------------") -- print("Lua version: " .. (_G.jit and _G.jit.version or _G._VERSION)) -- print("cURL version: " .. curl.version()) -- print("------------------------------------") -- print("") local weak_ptr, gc_collect, is_curl_ge, read_file, stream, Stream, dump_request = utils.import('weak_ptr', 'gc_collect', 'is_curl_ge', 'read_file', 'stream', 'Stream', 'dump_request') local null = curl.null local ENABLE = true local _ENV = TEST_CASE'curl error' if ENABLE then function test_eq_with_same_cat() local e1 = curl.error(curl.ERROR_EASY, curl.E_OK) local e2 = curl.error(curl.ERROR_EASY, curl.E_OK) assert_equal(e1, e2) end function test_eq_with_different_cat() local e1 = curl.error(curl.ERROR_EASY, curl.E_OK) local e2 = curl.error(curl.ERROR_FORM, curl.E_OK) assert_equal(e1:no(), e2:no()) assert_not_equal(e1, e2) end function test_ctor_cat() local e e = curl.error(curl.ERROR_EASY, curl.E_OK) assert_equal(e:category(), curl.ERROR_EASY) assert_equal(e:no(), curl.E_OK) e = curl.error(curl.ERROR_MULTI, curl.E_OK) assert_equal(e:category(), curl.ERROR_MULTI) assert_equal(e:no(), curl.E_OK) e = curl.error(curl.ERROR_SHARE, curl.E_OK) assert_equal(e:category(), curl.ERROR_SHARE) assert_equal(e:no(), curl.E_OK) e = curl.error(curl.ERROR_FORM, curl.E_OK) assert_equal(e:category(), curl.ERROR_FORM) assert_equal(e:no(), curl.E_OK) assert_error(function() curl.error(nil, curl.E_OK) end) assert_error(function() curl.error('UNKNOWN STRING', curl.E_OK) end) end end local _ENV = TEST_CASE'write_callback' if ENABLE then local c, f function teardown() if f then f:close() end os.remove(fname) if c then c:close() end f, c = nil end function test_write_to_file() f = assert(io.open(fname, "w+b")) c = assert(curl.easy{ url = GET_URL; writefunction = f; }) assert_equal(c, c:perform()) end function test_write_abort_01() c = assert(scurl.easy{ url = GET_URL; writefunction = function(str) return #str - 1 end; }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_WRITE_ERROR), e) end function test_write_abort_02() c = assert(scurl.easy{ url = GET_URL; writefunction = function(str) return false end; }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_WRITE_ERROR), e) end function test_write_abort_03() c = assert(scurl.easy{ url = GET_URL; writefunction = function(str) return nil, "WRITEERROR" end; }) local _, e = assert_nil(c:perform()) assert_equal("WRITEERROR", e) end function test_write_abort_04() c = assert(scurl.easy{ url = GET_URL; writefunction = function(str) return nil end; }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_WRITE_ERROR), e) end function test_reset_write_callback() f = assert(io.open(fname, "w+b")) c = assert(curl.easy{url = url}) assert_equal(c, c:setopt_writefunction(f)) assert_equal(c, c:setopt_writefunction(f.write, f)) assert_equal(c, c:setopt_writefunction(print)) assert_equal(c, c:setopt_writefunction(print, null)) assert_equal(c, c:setopt_writefunction(null)) assert_equal(c, c:setopt_writefunction(null, nil)) assert_equal(c, c:setopt_writefunction(null, null)) assert_error(function()c:setopt_writefunction()end) assert_error(function()c:setopt_writefunction(nil)end) assert_error(function()c:setopt_writefunction(nil, f)end) assert_error(function()c:setopt_writefunction(null, {})end) assert_error(function()c:setopt_writefunction(print, {}, nil)end) assert_error(function()c:setopt_writefunction(print, {}, null)end) end function test_write_pass_01() c = assert(curl.easy{ url = GET_URL; writefunction = function(s) return #s end }) assert_equal(c, c:perform()) end function test_write_pass_02() c = assert(curl.easy{ url = GET_URL; writefunction = function() return end }) assert_equal(c, c:perform()) end function test_write_pass_03() c = assert(curl.easy{ url = GET_URL; writefunction = function() return true end }) assert_equal(c, c:perform()) end function test_write_coro() local co1, co2 local called co1 = coroutine.create(function() c = assert(curl.easy{ url = GET_URL; writefunction = function() called = coroutine.running() return true end }) coroutine.yield() end) co2 = coroutine.create(function() assert_equal(c, c:perform()) end) coroutine.resume(co1) coroutine.resume(co2) assert_equal(co2, called) end function test_write_pass_null_context() c = assert(curl.easy{ url = GET_URL; }) local context assert_equal(c, c:setopt_writefunction(function(ctx) context = ctx return true end, null)) assert_equal(c, c:perform()) assert_equal(null, context) end function test_write_pass_nil_context() c = assert(curl.easy{ url = GET_URL; }) local context, called assert_equal(c, c:setopt_writefunction(function(ctx) context = ctx called = true return true end, nil)) assert_equal(c, c:perform()) assert_true(called) assert_nil(context) end end local _ENV = TEST_CASE'progress_callback' if ENABLE then local c local function pass() end function teardown() if f then f:close() end os.remove(fname) if c then c:close() end f, c = nil end function test_abort_01() c = assert(scurl.easy{ url = GET_URL, writefunction = pass, noprogress = false, progressfunction = function() return false end }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_02() c = assert(scurl.easy{ url = GET_URL, writefunction = pass, noprogress = false, progressfunction = function() return 0 end }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_03() c = assert(scurl.easy{ url = GET_URL, writefunction = pass, noprogress = false, progressfunction = function() return nil end }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_04() c = assert(scurl.easy{ url = GET_URL, writefunction = pass, noprogress = false, progressfunction = function() return nil, "PROGRESSERROR" end }) local _, e = assert_nil(c:perform()) assert_equal("PROGRESSERROR", e) end function test_abort_05() c = assert(scurl.easy{ url = GET_URL, writefunction = pass, noprogress = false, progressfunction = function() error( "PROGRESSERROR" )end }) assert_error_match("PROGRESSERROR", function() c:perform() end) end function test_pass_01() c = assert(scurl.easy{ url = GET_URL, writefunction = pass, noprogress = false, progressfunction = function() end }) assert_equal(c, c:perform()) end function test_pass_02() c = assert(scurl.easy{ url = GET_URL, writefunction = pass, noprogress = false, progressfunction = function() return true end }) assert_equal(c, c:perform()) end function test_pass_03() c = assert(scurl.easy{ url = GET_URL, writefunction = pass, noprogress = false, progressfunction = function() return 1 end }) assert_equal(c, c:perform()) end end local _ENV = TEST_CASE'header_callback' if ENABLE then local c, f local function dummy() end function teardown() if c then c:close() end f, c = nil end function test_header_abort_01() c = assert(scurl.easy{ url = GET_URL; writefunction = dummy, headerfunction = function(str) return #str - 1 end; }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_WRITE_ERROR), e) end function test_header_abort_02() c = assert(scurl.easy{ url = GET_URL; writefunction = dummy, headerfunction = function(str) return false end; }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_WRITE_ERROR), e) end function test_header_abort_03() c = assert(scurl.easy{ url = GET_URL; writefunction = dummy, headerfunction = function(str) return nil, "WRITEERROR" end; }) local _, e = assert_nil(c:perform()) assert_equal("WRITEERROR", e) end function test_header_abort_04() c = assert(scurl.easy{ url = GET_URL; writefunction = dummy, headerfunction = function(str) return nil end; }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_WRITE_ERROR), e) end function test_reset_header_callback() f = {header = function() end} c = assert(curl.easy{url = url}) assert_equal(c, c:setopt_headerfunction(f)) assert_equal(c, c:setopt_headerfunction(f.header, f)) assert_equal(c, c:setopt_headerfunction(print)) assert_equal(c, c:setopt_headerfunction(null)) assert_equal(c, c:setopt_headerfunction(null, nil)) assert_equal(c, c:setopt_headerfunction(null, null)) assert_error(function()c:setopt_headerfunction()end) assert_error(function()c:setopt_headerfunction(nil)end) assert_error(function()c:setopt_headerfunction(nil, f)end) assert_error(function()c:setopt_headerfunction(null, {})end) assert_error(function()c:setopt_headerfunction(print, {}, nil)end) end function test_header_pass_01() c = assert(curl.easy{ url = GET_URL; writefunction = dummy, headerfunction = function(s) return #s end }) assert_equal(c, c:perform()) end function test_header_pass_02() c = assert(curl.easy{ url = GET_URL; writefunction = dummy, headerfunction = function() return end }) assert_equal(c, c:perform()) end function test_header_pass_03() c = assert(curl.easy{ url = GET_URL; writefunction = dummy, headerfunction = function() return true end }) assert_equal(c, c:perform()) end end local _ENV = TEST_CASE'read_stream_callback' if ENABLE and is_curl_ge(7,30,0) then -- tested on WinXP(x32)/Win8(x64) libcurl/7.37.1 / libcurl/7.30.0 local url = POST_URL local m, c, f, t local function json_data() return json.decode(table.concat(t)) end function setup() t = {} f = assert(scurl.form()) c = assert(scurl.easy{ url = url, timeout = 60, }) assert_equal(c, c:setopt_writefunction(table.insert, t)) end function teardown() if f then f:free() end if c then c:close() end if m then m:close() end t, f, c, m = nil end function test() assert_equal(f, f:add_stream('SSSSS', stream('X', 128, 13))) assert_equal(c, c:setopt_httppost(f)) -- should be called only stream callback local read_called assert_equal(c, c:setopt_readfunction(function() read_called = true end)) assert_equal(c, c:perform()) assert_nil(read_called) assert_equal(200, c:getinfo_response_code()) local data = assert_table(json_data()) assert_table(data.form) assert_equal(('X'):rep(128), data.form.SSSSS) end function test_object() local s = Stream('X', 128, 13) assert_equal(f, f:add_stream('SSSSS', s:size(), s)) assert_equal(c, c:setopt_httppost(f)) assert_equal(c, c:perform()) assert_equal(s, s.called_ctx) assert_equal(200, c:getinfo_response_code()) local data = assert_table(json_data()) assert_table(data.form) assert_equal(('X'):rep(128), data.form.SSSSS) end function test_co_multi() local s = Stream('X', 128, 13) assert_equal(f, f:add_stream('SSSSS', s:size(), s)) assert_equal(c, c:setopt_httppost(f)) m = assert(scurl.multi()) assert_equal(m, m:add_handle(c)) co = coroutine.create(function() while 1== m:perform() do end end) coroutine.resume(co) assert_equal(co, s.called_co) assert_equal(200, c:getinfo_response_code()) local data = assert_table(json_data()) assert_table(data.form) assert_equal(('X'):rep(128), data.form.SSSSS) end function test_co() local s = Stream('X', 128, 13) assert_equal(f, f:add_stream('SSSSS', s:size(), s)) assert_equal(c, c:setopt_httppost(f)) co = coroutine.create(function() assert_equal(c, c:perform()) end) coroutine.resume(co) assert_equal(co, s.called_co) assert_equal(200, c:getinfo_response_code()) local data = assert_table(json_data()) assert_table(data.form) assert_equal(('X'):rep(128), data.form.SSSSS) end function test_abort_01() assert_equal(f, f:add_stream('SSSSS', 128 * 1024, function() end)) assert_equal(c, c:setopt_timeout(5)) assert_equal(c, c:setopt_httppost(f)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_OPERATION_TIMEDOUT), e) end function test_abort_02() assert_equal(f, f:add_stream('SSSSS', 128, function() return nil, "READERROR" end)) assert_equal(c, c:setopt_httppost(f)) local _, e = assert_nil(c:perform()) assert_equal("READERROR", e) end function test_abort_03() assert_equal(f, f:add_stream('SSSSS', 128, function() return 1 end)) assert_equal(c, c:setopt_httppost(f)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_04() assert_equal(f, f:add_stream('SSSSS', 128, function() return true end)) assert_equal(c, c:setopt_httppost(f)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_05() assert_equal(f, f:add_stream('SSSSS', 128, function() error("READERROR") end)) assert_equal(c, c:setopt_httppost(f)) assert_error_match("READERROR", function() c:perform() end) end function test_abort_06() assert_equal(f, f:add_stream('SSSSS', 128, function() return false end)) assert_equal(c, c:setopt_httppost(f)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_pass_01() assert_equal(c, c:setopt_timeout(10)) assert_equal(f, f:add_stream('SSSSS', 128, function() return nil end)) assert_equal(c, c:setopt_httppost(f)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_OPERATION_TIMEDOUT), e) end function test_pause() local counter = 0 assert_equal(f, f:add_stream('SSSSS', 128, function() if counter == 0 then counter = counter + 1 return curl.READFUNC_PAUSE end if counter == 1 then counter = counter + 1 return ('X'):rep(128) end return '' end)) assert_equal(c, c:setopt_progressfunction(function() if counter == 1 then c:pause(curl.PAUSE_CONT) end end)) assert_equal(c, c:setopt_noprogress(false)) assert_equal(c, c:setopt_httppost(f)) assert_equal(c, c:perform()) assert_equal(200, c:getinfo_response_code()) local data = assert_table(json_data()) assert_table(data.form) assert_equal(('X'):rep(128), data.form.SSSSS) end end local _ENV = TEST_CASE'read_callback' if ENABLE then local uname = upath:normalize(path.fullpath(fname)) local url = "FILE:///" .. uname local c function setup() c = assert(scurl.easy{ url = url, upload = true, }) end function teardown() os.remove(fname) if c then c:close() end c = nil end function test_abort_01() -- assert_equal(c, c:setopt_readfunction(function() end)) -- -- local _, e = assert_nil(c:perform()) -- assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_02() assert_equal(c, c:setopt_readfunction(function() return nil, "READERROR" end)) local _, e = assert_nil(c:perform()) assert_equal("READERROR", e) end function test_abort_03() assert_equal(c, c:setopt_readfunction(function() return 1 end)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_04() assert_equal(c, c:setopt_readfunction(function() return true end)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_05() assert_equal(c, c:setopt_readfunction(function() error("READERROR") end)) assert_error_match("READERROR", function() c:perform() end) end function test_abort_06() assert_equal(c, c:setopt_readfunction(function() return false end)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_pause() -- BUG? -- c:perform() returns curl.E_READ_ERROR after readfunction return curl.READFUNC_PAUSE -- -- OS version : Linux Mint 17 (x86_64) -- cURL version : libcurl/7.35.0 OpenSSL/1.0.1f zlib/1.2.8 libidn/1.28 librtmp/2.3 -- version_info("host"): x86_64-pc-linux-gnu -- -- OS version : Windows XP (x86_64) -- cURL version : libcurl/7.38.0 OpenSSL/1.0.1c zlib/1.2.7 WinIDN -- cURL version : libcurl/7.37.1 OpenSSL/1.0.1c zlib/1.2.7 WinIDN -- version_info("host"): i386-pc-win32 -- -- Works correctly on -- (same binary as with libcurl 7.38.0/7.37.1) -- -- OS version : Windows XP (x86_64) -- cURL version : libcurl/7.30.0 OpenSSL/0.9.8y zlib/1.2.7 -- version_info("host"): i386-pc-win32 -- local counter = 0 assert_equal(c, c:setopt_readfunction(function() if counter == 0 then counter = counter + 1 return curl.READFUNC_PAUSE end if counter == 1 then counter = counter + 1 return ('X'):rep(128) end return '' end)) assert_equal(c, c:setopt_progressfunction(function() if counter == 1 then c:pause(curl.PAUSE_CONT) end end)) assert_equal(c, c:setopt_noprogress(false)) local ok, err = c:perform() if (not ok) and err:name() == "READ_ERROR" then skip("TODO check pause on readfunction") end assert_equal(c, ok, err) assert_equal(0, c:getinfo_response_code()) end function test_readbuffer() local flag = false local N assert_equal(c, c:setopt_readfunction(function(n) if not flag then flag = true N = math.floor(n*2 + n/3) assert(N > n) return ("s"):rep(N) end return '' end)) assert_equal(c, c:perform()) c:close() local data = read_file(fname) assert_equal(N, #data) assert_equal(("s"):rep(N), data) end function test_pass_01() -- We need this to support file:read() method which returns nil as EOF assert_equal(c, c:setopt_readfunction(function() return nil end)) assert_equal(c, c:perform()) c:close() local data = read_file(fname) assert_equal(0, #data) end function test_pass_02() local counter = 10 assert_equal(c, c:setopt_readfunction(function() if counter > 0 then counter = counter - 1 return 'a' end end)) assert_equal(c, c:perform()) c:close() local data = read_file(fname) assert_equal(('a'):rep(10), data) end end local _ENV = TEST_CASE'escape' if ENABLE then local c function teardown() if c then c:close() end f, c = nil end function test() local e = "This%2Bis%2Ba%2Bsimple%2B%2526%2Bshort%2Btest." local d = "This+is+a+simple+%26+short+test." c = assert(curl.easy()) assert_equal(e, c:escape(d)) assert_equal(d, c:unescape(e)) end end local _ENV = TEST_CASE'setopt_form' if ENABLE then local c function teardown() if c then c:close() end c = nil end function test() local pfrom, e do local form = curl.form() e = curl.easy{httppost = form} pfrom = weak_ptr(form) end gc_collect() assert(pfrom.value) e:setopt_httppost(curl.form()) gc_collect() assert(not pfrom.value) end function test_unset() local pfrom, e do local form = curl.form() e = curl.easy{httppost = form} pfrom = weak_ptr(form) end gc_collect() assert(pfrom.value) assert_equal(e, e:unsetopt_httppost()) gc_collect() assert(not pfrom.value) end function test_reset() local pfrom, e do local form = curl.form() e = curl.easy{httppost = form} pfrom = weak_ptr(form) end gc_collect() assert(pfrom.value) assert_equal(e, e:reset()) gc_collect() assert(not pfrom.value) end end local _ENV = TEST_CASE'setopt_postfields' if ENABLE then local c function teardown() if c then c:close() end c = nil end function test() do local fields = {} for i = 1, 100 do fields[#fields + 1] = string.format('key%d=value%d', i, i) end fields = table.concat(fields, '&') c = assert(curl.easy{ url = POST_URL, postfields = fields, writefunction = function()end, }) end -- call gc to try clear `fields` string for i = 1, 4 do collectgarbage"collect" end c:perform() end function test_unset() local pfields do local fields = {} for i = 1, 100 do fields[#fields + 1] = string.format('key%d=value%d', i, i) end fields = table.concat(fields, '&') c = assert(curl.easy{ url = POST_URL, postfields = fields, writefunction = function()end, }) pfields = weak_ptr(fields) end -- call gc to try clear `fields` string for i = 1, 4 do collectgarbage"collect" end assert_string(pfields.value) assert_equal(c, c:unsetopt_postfields()) -- @todo check internal storage because gc really do not clear `weak` string -- for i = 1, 4 do collectgarbage"collect" end -- assert_nil(pfields.value) -- c:perform() end end local _ENV = TEST_CASE'setopt_user_data' if ENABLE then local c function teardown() if c then c:close() end c = nil end function test_data() c = assert(curl.easy()) assert_nil(c:getdata()) c:setdata("hello") assert_equal("hello", c:getdata()) end function test_cleanup() local ptr do local t = {} local e = curl.easy():setdata(t) ptr = weak_ptr(t) gc_collect() assert_equal(t, ptr.value) end gc_collect() assert_nil(ptr.value) end end local _ENV = TEST_CASE'multi_add_remove' if ENABLE then local m, c function setup() m = assert(scurl.multi()) end function teardown() if c then c:close() end if m then m:close() end m, c = nil end function test_remove_unknow_easy() c = assert(scurl.easy()) assert_equal(m, m:remove_handle(c)) end function test_double_remove_easy() c = assert(scurl.easy()) assert_equal(m, m:add_handle(c)) assert_equal(m, m:remove_handle(c)) assert_equal(m, m:remove_handle(c)) end function test_double_add_easy() c = assert(scurl.easy()) assert_equal(m, m:add_handle(c)) assert_nil(m:add_handle(c)) end end local _ENV = TEST_CASE'unset_callback_ctx' if ENABLE then local c function setup() c = assert(scurl.easy()) end function teardown() if c then c:close() end c = nil end local function test_cb(name) local set, unset = 'setopt_' .. name, 'unsetopt_' .. name set = assert_function(c[set], set) unset = assert_function(c[unset], unset) local pctx do local ctx = {} pctx = weak_ptr(ctx) assert(set(c, function() end, ctx)) end gc_collect() assert_table(pctx.value) unset(c) gc_collect() assert_nil(pctx.value) end function test_read() test_cb('readfunction') end function test_write() test_cb('writefunction') end function test_header() test_cb('headerfunction') end function test_progress() test_cb('progressfunction') end function test_seek() test_cb('seekfunction') end function test_debug() test_cb('debugfunction') end function test_fnmatch() test_cb('fnmatch_function') end function test_chunk_bgn() test_cb('chunk_bgn_function') end function test_chunk_end() test_cb('chunk_end_function') end end local _ENV = TEST_CASE'set_slist' if ENABLE then local c function teardown() if c then c:close() end c = nil end function test_set() c = curl.easy() c:setopt_httpheader({'X-Custom: value'}) local body, headers = assert_string(dump_request(c)) assert_match("X%-Custom:%s*value\r\n", headers) end function test_unset() c = curl.easy() c:setopt_httpheader({'X-Custom: value'}) c:unsetopt_httpheader() local body, headers = assert_string(dump_request(c)) assert_not_match("X%-Custom:%s*value\r\n", headers) end function test_set_empty_array() c = curl.easy() c:setopt_httpheader({'X-Custom: value'}) c:setopt_httpheader({}) local body, headers = assert_string(dump_request(c)) assert_not_match("X%-Custom:%s*value\r\n", headers) end end local _ENV = TEST_CASE'set_null' if ENABLE then local c, m function teardown() if c then c:close() end if m then m:close() end m, c = nil end function test_string() c = curl.easy() c:setopt_accept_encoding('gzip') local body, headers = assert_string(dump_request(c)) assert_match("Accept%-Encoding:%s*gzip", headers) c:setopt_accept_encoding(null) body, headers = assert_string(dump_request(c)) assert_not_match("Accept%-Encoding:%s*gzip", headers) end function test_string_via_table() c = curl.easy() c:setopt_accept_encoding('gzip') local body, headers = assert_string(dump_request(c)) assert_match("Accept%-Encoding:%s*gzip", headers) c:setopt{ accept_encoding = null } body, headers = assert_string(dump_request(c)) assert_not_match("Accept%-Encoding:%s*gzip", headers) end function test_slist() c = curl.easy() c:setopt_httpheader({'X-Custom: value'}) c:setopt_httpheader(null) local body, headers = assert_string(dump_request(c)) assert_not_match("X%-Custom:%s*value\r\n", headers) end function test_slist_via_table() c = curl.easy() c:setopt_httpheader({'X-Custom: value'}) c:setopt{httpheader = null} local body, headers = assert_string(dump_request(c)) assert_not_match("X%-Custom:%s*value\r\n", headers) end function test_multi_set_array() m = curl.multi() m:setopt_pipelining_site_bl{ '127.0.0.1' } assert_equal(m, m:setopt_pipelining_site_bl(null)) end end RUN()
Config = {} Config.Stables = { Valentine = { Pos = {x=-367.73, y=787.72, z=116.26}, Name = 'Lovarda', Heading = -30.65, SpawnPoint = { Pos = {x=-372.43, y=791.79, z=116.13}, CamPos = {x=1, y=-3, z=0}, Heading = 182.3 } }, BlackWater = { Pos = {x=-873.167, y=-1366.040, z=43.531}, Name = 'Lovarda', Heading = 266.84, SpawnPoint = { Pos = {x=-864.373, y=-1361.485, z=43.702}, CamPos = {x=-1.2, y=-3, z=0}, Heading = 181.91 } }, Saint_Denis = { Pos = {x=2503.153, y=-1442.725, z=46.312}, Name = 'Lovarda', Heading = 169.45, SpawnPoint = { Pos = {x=2508.822, y=-1449.949, z=46.402}, CamPos = {x=-3, y=3, z=0}, Heading = 93.13 } }, }
local RandomBatcher, Parent = torch.class('laia.RandomBatcher', 'laia.CachedBatcher') function RandomBatcher:__init(opt) Parent.__init(self, opt) end --[[ Use this method to shuffle the samples to serve following batches in a different order. This should be called at the beginning of each EPOCH to process the whole dataset in a different order. --]] function RandomBatcher:shuffle() for i=1,(self._num_samples-1) do -- DO NOT USE math.random(self._num_samples - i), rely only on torch -- random generators, instead. The state of torch RNG can be stored and -- recovered for greater replicability. --local j = math.random(self._num_samples - i) local j = 1 + math.floor(torch.uniform() * (self._num_samples - i)) self._samples[i], self._samples[j] = self._samples[j], self._samples[i] self._imglist[i], self._imglist[j] = self._imglist[j], self._imglist[i] end self._idx = 0 self:clearCache() end function RandomBatcher:epochReset(epoch_opt) self:shuffle() end return RandomBatcher
--remotes.lua -- Registers remote calls for other mods to use -- Register a Locomotive Type as an electric locomotive with the given dummy fuel item. -- This locomotive type will then be handled by RET. The registration is not persistent -- so it needs to be repeated whenever the map is loaded (i.e. during the evaluation of -- control.lua) -- The fuel item can be any item that can be used as fuel. There are three dummy items -- provided by RET: ret-dummy-fuel-1 (from the tier 1 electric locomotive), -- ret-dummy-fuel-2 (from the tier 2 electric locomotive) and "ret-dummy-fuel-modular". -- The latter enables modules being detected in the locomotive. function register_locomotive_type(loco_name, fuel_item) if (not game.entity_prototypes[loco_name]) or (fuel_item ~= nil and fuel_item ~= "ret-dummy-fuel-modular" and game.item_prototypes[fuel_item] == nil) then error("register_locomotive_type called with invalid arguments") end global.electric_loco_registry[loco_name] = fuel_item if remote.interfaces["FuelTrainStop"] then remote.call("FuelTrainStop", "exclude_from_fuel_schedule", loco_name) end end -- Returns the fuel item this locomotive type was registered with. function get_locomotive_fuel(loco_name) return global.electric_loco_registry[loco_name] end remote.add_interface("realistic_electric_trains", { ["register_locomotive_type"] = register_locomotive_type, ["get_locomotive_fuel"] = get_locomotive_fuel })
#!/usr/bin/luajit local magick = require("magick") image = magick.load_image(arg[1]) image:crop(image:get_width() - 200, image:get_height() - 200, 100, 100) -- this will use lanczos2 image:resize(image:get_width() * 0.9, image:get_height() * 0.9) -- gaussblur with radius 1 image:sharpen(1, 0) image:write(arg[2]); image:destroy()
local util = {} util.get_group = function(table, player_index, surface_index) for _, group in pairs(table) do if group.player.index == player_index and group.surface.index == surface_index then return group end end return nil end util.table_contains_value = function(table, value) for key, tableValue in pairs(table) do if key == value or tableValue == value then return key end end return false end util.create_exclude_list = function(defenceExcludeList) --reset list defenceExcludeList = {} for entry in string.gmatch(settings.global["defence-exclude-list"].value, "[^,]+") do defenceExcludeList[entry] = true end return defenceExcludeList end util.angle = function(pos1, pos2) local dx = (pos2[1] or pos2.x) - (pos1[1] or pos1.x) local dy = (pos2[2] or pos2.y) - (pos1[2] or pos1.y) return math.atan2(dy, dx) end util.rotate_vector = function(vector, orientation) local x = vector[1] or vector.x local y = vector[2] or vector.y local angle = (orientation) * math.pi * 2 return { x = (math.cos(angle) * x) - (math.sin(angle) * y), y = (math.sin(angle) * x) + (math.cos(angle) * y) } end util.get_offset = function(current_position, target_position, length, angle_adjustment) local angle = util.angle(current_position, target_position) angle = angle + (math.pi / 2) + (angle_adjustment or 0) local x1 = (length * math.sin(angle)) local y1 = (-length * math.cos(angle)) return {x1, y1} end util.get_distance = function(pos1, pos2) local pxpx = pos1.x - pos2.x local pypy = pos1.y - pos2.y return (pxpx * pxpx + pypy * pypy) ^ 0.5 end util.same_position = function(pos1, pos2) if pos1.x == pos2.x and pos1.y == pos2.y then return true else return false end end util.get_closest = function(pos, table) local x, y = pos.x, pos.y local closest = MAX_INT32 local entity for _, value in pairs(table) do if value.valid then local distance = util.get_distance(pos, value.position) if distance < closest then x, y = value.position.x, value.position.y1 closest = distance entity = value end end end return entity end return util
-- Copyright 2006-2011 Mitchell mitchell<att>caladbolg.net. See LICENSE. -- Light lexer theme for Scintillua. module('lexer', package.seeall) colors = { green = color('4D', '99', '4D'), blue = color('4D', '4D', '99'), red = color('99', '4C', '4C'), yellow = color('99', '99', '4D'), teal = color('4D', '99', '99'), white = color('EE', 'EE', 'EE'), black = color('33', '33', '33'), grey = color('AA', 'AA', 'AA'), purple = color('99', '4D', '99'), orange = color('C0', '80', '40'), lgreen = color('80', 'C0', '40'), lblue = color('40', '80', 'C0'), lred = color('C0', '40', '40'), lyellow = color('C0', 'C0', '40'), lteal = color('40', 'C0', 'C0'), lpurple = color('C0', '40', '80'), lorange = color('C0', '80', '40'), } style_nothing = style { } style_char = style { fore = colors.red, bold = true } style_class = style { fore = colors.black, underline = true } style_comment = style { fore = colors.lblue, bold = true } style_constant = style { fore = colors.teal, bold = true } style_definition = style { fore = colors.red, bold = true } style_error = style { fore = colors.lred } style_function = style { fore = colors.blue, bold = true } style_keyword = style { fore = colors.yellow, bold = true } style_number = style { fore = colors.teal } style_operator = style { fore = colors.black, bold = true } style_string = style { fore = colors.green, bold = true } style_preproc = style { fore = colors.red } style_tag = style { fore = colors.teal, bold = true } style_type = style { fore = colors.green } style_variable = style { fore = colors.red } style_embedded = style_tag..{ back = color('DD', 'DD', 'DD') } style_identifier = style_nothing -- Default styles. local font_face = '!Bitstream Vera Sans Mono' local font_size = 10 if WIN32 then font_face = not GTK and 'Courier New' or '!Courier New' elseif OSX then font_face = '!Monaco' font_size = 12 end style_default = style{ font = font_face, size = font_size, fore = colors.black, back = colors.white } style_line_number = style { fore = colors.black, back = colors.grey } style_bracelight = style { fore = color('66', '99', 'FF'), bold = true } style_bracebad = style { fore = color('FF', '66', '99'), bold = true } style_controlchar = style_nothing style_indentguide = style { fore = colors.grey, back = colors.white } style_calltip = style { fore = colors.black, back = color('DD', 'DD', 'DD') }