content
stringlengths
5
1.05M
att.PrintName = "Squirt Gun" att.Icon = Material("snowysnowtime/2k/ico/arico/squirtgun.png", "smooth mips") att.Description = "A Squirt Gun alternative for the MA5B" att.Desc_Pros = { " ok but why" } att.Desc_Cons = { } att.Slot = "skin_hcear" att.Free = true att.ActivateElements = {"squirtgun"} att.AttachSound = "attch/snow/halo/h1/forward.wav" att.DetachSound = "attch/snow/halo/h1/back.wav"
local temp if data.raw.item["brass-alloy"] then temp = data.raw.recipe["brass-gear-wheel"] temp.energy_required = 1.5 temp.ingredients = { {type="item", name="brass-alloy", amount=5}, } end if data.raw.item["silicon-nitride"] then temp = data.raw.recipe["ceramic-bearing"] temp.energy_required = 1.5 temp.ingredients = { {type="item", name="silicon-nitride", amount=3}, {type="item", name="ceramic-bearing-ball", amount=42}, {type="fluid", name="lubricant", amount=3} } temp = data.raw.recipe["ceramic-bearing-ball"] temp.result_count = 8 end temp = data.raw.recipe["lithium-ion-battery"] temp.energy_required = 1.5 temp.ingredients = { {type="item", name="lithium-perchlorate", amount=4}, {type="item", name="lithium-cobalt-oxide", amount=2}, {type="item", name="carbon", amount=2}, {type="item", name="plastic-bar", amount=2}, } if data.raw.item["nitinol-alloy"] then temp = data.raw.recipe["nitinol-bearing"] temp.energy_required = 1.5 temp.ingredients = { {type="item", name="nitinol-alloy", amount=3}, {type="item", name="nitinol-bearing-ball", amount=42}, {type="fluid", name="lubricant", amount=2} } temp = data.raw.recipe["nitinol-bearing-ball"] temp.result_count = 8 temp = data.raw.recipe["nitinol-gear-wheel"] temp.energy_required = 1.5 temp.ingredients = { {type="item", name="nitinol-alloy", amount=5}, } end temp = data.raw.recipe["silver-zinc-battery"] temp.energy_required = 3 temp = data.raw.recipe["steel-bearing"] temp.energy_required = 1.5 temp.ingredients = { {type="item", name="steel-plate", amount=3}, {type="item", name="steel-bearing-ball", amount=42}, } temp = data.raw.recipe["steel-bearing-ball"] temp.result_count = 8 temp = data.raw.recipe["steel-gear-wheel"] temp.energy_required = 1.5 temp.ingredients = { {type="item", name="steel-plate", amount=5}, } if data.raw.item["titanium-plate"] then temp = data.raw.recipe["titanium-bearing"] temp.energy_required = 1.5 temp.ingredients = { {type="item", name="titanium-plate", amount=3}, {type="item", name="titanium-bearing-ball", amount=42}, {type="fluid", name="lubricant", amount=2} } temp = data.raw.recipe["titanium-bearing-ball"] temp.result_count = 8 temp = data.raw.recipe["titanium-gear-wheel"] temp.energy_required = 1.5 temp.ingredients = { {type="item", name="titanium-plate", amount=5}, } end if data.raw.item["tungsten-plate"] then temp = data.raw.recipe["tungsten-gear-wheel"] temp.energy_required = 1.5 temp.ingredients = { {type="item", name="tungsten-plate", amount=5}, } end
resource.AddFile("sound/gmodz/player/gasmask_wear.wav") resource.AddFile("gmodz/player/gasmask_inhale.wav") resource.AddFile("gmodz/player/gasmask_exhale.wav") resource.AddFile("materials/gmdz/gasmask.vmt") resource.AddFile("materials/gmdz/gasmask.vtf") resource.AddFile("materials/gmdz/gasmask_n.vtf") resource.AddFile("materials/gmdz/shtr.vmt") resource.AddFile("materials/gmdz/shtr.vtf") resource.AddFile("materials/gmdz/shtr_n.vtf") util.AddNetworkString("ixMskAdd") util.AddNetworkString("ixMaskOff") util.AddNetworkString("ixMaskOn") local PLUGIN = PLUGIN --- plugins\radiation\sv_plugin.lua -- local white = ColorAlpha(color_white, 150) -- function PLUGIN:PlayerTick(client) -- if (!IsValid(client) or !client:Alive()) then return end -- local faction = ix.faction.Get(client:Team()) -- if (faction and faction.noGas) then -- return -- end -- local area = ix.area.stored[client:GetArea()] -- if ((!client.gasTick or client.gasTick <= CurTime()) and client.ixInArea) then -- if (area and area["type"] == "gas") then -- local item = client:GetGasMask() -- local bool -- if (item and item.isGasMask) then -- if (item:GetHealth() <= 0) then -- bool = nil -- else -- if (item:GetFilter() <= 0) then -- bool = nil -- else -- bool = true -- end -- end -- else -- bool = nil -- end -- if (bool) then -- item:DamageFilter(ix.config.Get("gasmask_damage", 1)) -- else -- client:TakeDamage(ix.config.Get("gasDamage", 3)) -- client:ScreenFade(1, white, .5, 0) -- end -- if (bool) then -- client.gasTick = CurTime() + ix.config.Get("gasDelay", 2) -- else -- client.gasTick = CurTime() + ix.config.Get("gasDelayBad", 1.3) -- end -- end -- end -- end function PLUGIN:PlayerLoadedCharacter(client, curChar) if (curChar) then local inv = curChar:GetInventory() local gasItem for _, v in pairs(inv:GetItems()) do if (v.isGasMask and v:GetData("equip")) then gasItem = v break end end if (gasItem) then client.ixGasMaskItem = gasItem net.Start("ixMaskOn") net.WriteUInt(gasItem:GetID(), 32) net.WriteUInt(gasItem:GetHealth(), 16) net.Send(client) else client.ixGasMaskItem = nil net.Start("ixMaskOff") net.Send(client) end end end function PLUGIN:PlayerDeath(client) local item = client:GetGasMask() if (item and item.isGasMask and item:GetData("equip")) then item:Unequip(client) end end -- This hook simulates the damage of the Gas Mask. function PLUGIN:PostPlayerTakeDamage(client, dmgInfo) local item = client:GetGasMask() if (item and item.isGasMask) then local damage = dmgInfo:GetDamage() * .5 item:DamageHealth(damage) if (client:GetHealth() - damage <= 0) then return end local crackNums = math.Round((1 - item:GetHealth() / ix.config.Get("gasmask_health", 100)) * 6) if (item.curCracks and item.curCracks < crackNums) then net.Start("ixMskAdd") net.Send(client) end item.curCracks = crackNums end end
_G.ele_scoreboard = ele_scoreboard or {} ele_scoreboard.derma = ele_scoreboard.derma local teams = {} teams[TEAM_BLACK] = Material("element/ui/black.png") teams[TEAM_WHITE] = Material("element/ui/white.png") local playerList = function( panel ) players = team.GetPlayers(panel.team) panel.lastPlayers = panel.lastPlayers or {} panel.dermas = panel.dermas or {} if table.Count(players) == table.Count(panel.lastPlayers) then return end for k, derma in next, panel.dermas do derma:Remove() end local width = panel:GetWide() local height = panel:GetTall() local w, y, h = width * 0.8, 64, 64 local max = height / (h + 8) - 2 local x = width * 0.1 table.sort(players, function( a, b ) return a:Frags() > b:Frags() end) local counter = 1 for k, ply in next, players do local derma = TDLib("DPanel", panel) derma:SetPos(x,y) derma:SetSize(w,h) derma:ClearPaint() local class = TDLib("DImage", derma) class:SetMaterial(player_manager.RunClass(ply, "GetClassIcon")) class:SetSize( h, h ) --local color = GAMEMODE:GetEnemyTeamColor(ply) local color = team.GetColor(ply:Team()) local font = "fujimaru_small" local name = TDLib("DLabel", derma) local size = w * 0.8 name:SetText(ply:GetName()) name:SetFont(font) name:SetPos(h,0) name:SetAlpha(ply:Alive() and 255 or 100) name:SetSize(size, h) name:SetTextColor(color) local frags = TDLib("DLabel", derma) frags:SetText(ply:GetScore()) frags:SetFont(font) frags:SetPos(h + size,0) frags:SetSize(w-h, h) frags:SetTextColor(color) table.insert(panel.dermas, derma) y = y + h + 8 counter = counter + 1 if (counter > max) then break end end panel.lastPlayers = players end local smart_cast_guides = {} smart_cast_guides[Skill.TARGET.PLAYERLOCK] = "Target: Player - You have to hold the key until you see a glowing player" smart_cast_guides[Skill.TARGET.WORLD] = "Target: World - You have to hold the key until you see a glowing area" local hold_guide = "Cast will be up until the key was released" local function GenerateGuide( scrw, scrh, derma ) local size = 128 local offset = 32 local key_offsets = {} key_offsets[KEY_Q] = { x = 0, y = 0 } key_offsets[KEY_E] = { x = size + offset, y = -200 } key_offsets[KEY_LSHIFT] = { x = 2 * size + 2 * offset, y = 0 } key_offsets[MOUSE_LEFT] = { x = scrw - 96 - offset * 3 - size * 3, y = -200 } key_offsets[MOUSE_RIGHT] = { x = scrw - 96 - offset * 2 - size * 2, y = 0 } for key, skillname in next, LocalPlayer().skills do local skill = skill_manager.GetSkill(skillname) local x, y = key_offsets[key].x, key_offsets[key].y x = x + 96 y = y + scrh - 600 local h = 160 local text = skill:GetDescription() if skill:GetCleverCast() then text = text .. "\n\n" .. smart_cast_guides[skill:GetCleverTarget()] h = h + 64 end if skill:GetCastUntilRelease() then text = text .. "\n\n" .. hold_guide h = h + 32 end local guide = TDLib("DLabel", derma) guide:ClearPaint() guide:SetPos( x - offset, y ) guide:SetSize( 256, h ) guide:SetFont( "Trebuchet24" ) --"fujimaru_small") guide:SetWrap( true ) guide:SetTextColor(_COLOR.WHITEFADE) guide:SetText(text) local line = TDLib("DPanel", derma) line:ClearPaint() line:Background(_COLOR.WHITEFADE) line:SetPos( x + size * 0.5, y + h ) line:SetSize( 8, scrh - y - h - 256 ) end end function ele_scoreboard:Show() local derma = ele_scoreboard.derma if IsValid(derma) then derma:Remove() end local scrw, scrh = ScrW(), ScrH() local w, h = scrw * 0.4, scrh derma = TDLib("DPanel") derma:ClearPaint() derma:SetSize(scrw, scrh) local score = TDLib("DPanel", derma) score:ClearPaint() score:Blur() score:SetSize(w, h) score:SetPos(scrw * 0.5 - w * 0.5, 0) score:FadeIn(0.1) local black = TDLib("DPanel", score) black:ClearPaint() black:SetSize(w, h * 0.5) --black:Background(_COLOR.BLACK) black.team = TEAM_BLACK black.Think = playerList local white = TDLib("DPanel", score) white:ClearPaint() white:SetPos(0, h * 0.5) white:SetSize(w, h * 0.5) --white:Background(_COLOR.WHITE) white.team = TEAM_WHITE white.Think = playerList local size = 128 local wins = round_manager.GetWins() local offset = w * 0.9 / wins for teamID, material in next, teams do local points = team.GetScore(teamID) for j = 0, wins - 1 do local point = TDLib("DImage", score) point:SetPos(w * 0.05 + j * offset, h * 0.5 - size * 0.5) point:SetSize( size, size ) point:SetMaterial( material ) point:SetAlpha( points > j and 255 or 25 ) point.lastPaint = CurTime() point.ang = 0 function point:Paint() self.deltaTime = CurTime() - self.lastPaint self.lastPaint = CurTime() local ranomizer = math.max(math.abs(math.cos(CurTime())), 0.5) self.ang = self.ang - self.deltaTime * ranomizer * 100 local dw = self:GetWide() local dh = self:GetTall() surface.SetMaterial( self:GetMaterial() ) surface.SetDrawColor( _COLOR.FULL ) surface.DrawTexturedRectRotated( dw * 0.5, dh * 0.5, dw, dh, self.ang ) end end end GenerateGuide( scrw, scrh, derma ) ele_scoreboard.derma = derma end function ele_scoreboard:Hide() if IsValid(ele_scoreboard.derma) then ele_scoreboard.derma:Remove() end ele_scoreboard.derma = nil end function ele_scoreboard:Hidden() return ele_scoreboard.derma == nil end
object_mobile_space_comm_ep3_cpg_ace_04 = object_mobile_shared_space_comm_ep3_cpg_ace_04:new { } ObjectTemplates:addTemplate(object_mobile_space_comm_ep3_cpg_ace_04, "object/mobile/space_comm_ep3_cpg_ace_04.iff")
--[[ Gangi: aktualizacja danych dla czlonkow @author Jakub 'XJMLN' Starzak <[email protected] @package PSZMTA.psz-gangi @copyright Jakub 'XJMLN' Starzak <[email protected]> Nie mozesz uzywac tego skryptu bez mojej zgody. Napisz - byc moze sie zgodze na uzycie. ]]-- function updatePlayerCoData(pid) if (type(pid)=="number" or type(pid)=="string") then pid = tonumber(pid) for i,v in ipairs(getElementsByType("player")) do local c = getElementData(v, "character") local uid = getElementData(v,"auth:uid") if (c and uid and tonumber(uid) == pid) then -- cc = pg local query= string.format("SELECT pg.skin,pg.rank, g.id gang_id, g.nazwa gang_name,g.tag gang_tag, gr.name rank_name FROM psz_players_gangs pg JOIN psz_gangs_ranks gr ON gr.gang_id=pg.id_gang AND gr.rank_id=pg.rank JOIN psz_gangi g ON g.id=gr.gang_id WHERE pg.id_player=%d",pid) local dane= exports['psz-mysql']:pobierzWyniki(query) if (dane) then --c.gg_nazwa,c.gg_tag,c.gg_rank_name,c.gg_rank_id,c.gg_id -- gg_nazwa, gg_tag, gg_rank_name, gg_rank_id, gg_id c.gg_nazwa = dane.gang_name c.gg_tag = dane.gang_tag c.gg_rank_name = dane.rank_name c.gg_rank_id = dane.rank c.gg_id = dane.gang_id if (dane.skin and type(dane.skin)~="userdata") then setElementModel(v,dane.skin) else setElementModel(v, c.skin) end outputChatBox("Twoja przynależność do organizacji przestępczej została zaktualizowana.",v) else c.gg_nazwa = nil c.gg_tag = nil c.gg_rank_name = nil c.gg_rank_id = nil c.gg_id = nil setElementModel(v, c.skin) outputChatBox("Nie jestes juz czlonkiem organizacji przestepczej.",v) end setElementData(v,"character",c) return true end end end return false end function onDataUpgradesDownload(gid) if (not gid) then return end local upgrades_acctualy = exports['psz-mysql']:pobierzWyniki(string.format("SELECT id_upgrade FROM psz_gangi_owned_upgrades WHERE id_gang=%d",gid)) local upgrade = exports['psz-mysql']:pobierzTabeleWynikow(string.format("SELECT gu.id,gu.name,gu.tag,gu.cost,g.money_sejf FROM psz_gangi_upgrades gu JOIN psz_gangi g WHERE g.id=%d ORDER BY cost ASC;",gid)) if upgrades_acctualy and upgrades_acctualy.id_upgrade then triggerClientEvent(source,"doFillUpgradesData", resourceRoot, upgrade,upgrades_acctualy) else upgrades_acctualy = nil triggerClientEvent(source,"doFillUpgradesData", resourceRoot, upgrade,upgrades_acctualy) end end addEvent("onGangMemberEditNote",true) addEventHandler("onGangMemberEditNote",root, function(gid,note) if (not gid or not note) then return end tresc = tostring(note) local pid = getElementData(client,"auth:uid") local findString = string.find(note,"'") if (findString~=nil) then triggerClientEvent("onEditSendResult", resourceRoot, false, "Usuń znak ' z tekstu.") return end local query = string.format("UPDATE psz_gangi SET text_note='%s' WHERE id=%d", tresc, gid) exports['psz-mysql']:zapytanie(query) exports['psz-admin']:gameView_add("Gracz "..getPlayerName(client).."/"..pid.." edytuje notatke gangu ("..gid..")") triggerClientEvent("onEditSendResult", resourceRoot, true, "Notatka została edytowana.") end) addEvent("onPlayerRequestGangData",true) addEventHandler("onPlayerRequestGangData",root,function(gid) if (not gid) then return end local query --select c.id character_id,cc.rank rank_id,c.imie,c.nazwisko,cc.jointime lastduty,cc.skin,cr.name ranga from lss_character_co cc JOIN lss_characters c ON c.id=cc.character_id JOIN lss_co_ranks cr ON cr.co_id=cc.co_id AND cr.rank_id=cc.rank WHERE cc.co_id=%d query = string.format("SELECT p.userid player_id,g.text_note,pg.rank rank_id,pg.money wplacone_sejf,p.nick,pl.datetime_last lastduty,gr.name ranga FROM psz_players_gangs pg JOIN psz_gangi g ON g.id=pg.id_gang JOIN psz_postacie p ON p.userid=pg.id_player JOIN psz_players pl ON pl.id=p.userid JOIN psz_gangs_ranks gr ON gr.gang_id=pg.id_gang AND gr.rank_id=pg.rank WHERE pg.id_gang=%d",gid) local dane = exports['psz-mysql']:pobierzTabeleWynikow(query) -- ulepszenia query = string.format("SELECT g.money_sejf,g.logo,gs.skin FROM psz_gangi g JOIN psz_gangs_skins gs ON gs.gang_id=g.id WHERE g.id=%d",gid) local data = exports['psz-mysql']:pobierzTabeleWynikow(query) onDataUpgradesDownload(gid) local onlineMembers = gang_getOnlineMembers(gid) triggerClientEvent(source,'doFillGangData',resourceRoot,dane,data,onlineMembers) -- triggerClientEvent(source,"doFillUpgradesData", resourceRoot, upgrade) end) addEvent("onGangCharacterDetailsRequest",true) addEventHandler("onGangCharacterDetailsRequest", root, function(gid, pid) if (not gid or not pid) then return end local query query = string.format("SELECT rank_id, name FROM psz_gangs_ranks WHERE gang_id=%d ORDER BY rank_id ASC;",gid) local rangi = exports['psz-mysql']:pobierzTabeleWynikow(query) query = string.format("SELECT skin FROM psz_gangs_skins WHERE gang_id=%d ORDER BY skin ASC",gid) local skiny = exports['psz-mysql']:pobierzTabeleWynikow(query) query = string.format("SELECT p.userid, p.nick, pg.rank, pg.skin FROM psz_players_gangs pg JOIN psz_postacie p ON pg.id_player=p.userid WHERE pg.id_player=%d LIMIT 1", pid) local postac = exports['psz-mysql']:pobierzWyniki(query) local dane={ rangi=rangi, skiny=skiny, gracz=postac } triggerClientEvent(source, "doFillGangPlayerData", resourceRoot, dane) end) addEvent("onMemberGangSaveMoney",true) addEventHandler("onMemberGangSaveMoney", root, function(gid, pid, money) if (not gid or not pid or not money) then return end if (getPlayerMoney(client)<money) then triggerClientEvent(source,"onResultSaveMoney",resourceRoot, false, "Nie posiadasz przy sobie tylu pieniędzy.") return end takePlayerMoney(client,money) exports['psz-mysql']:zapytanie(string.format("UPDATE psz_players_gangs SET money=money+%d WHERE id_player=%d LIMIT 1",money, pid)) exports['psz-mysql']:zapytanie(string.format("UPDATE psz_gangi SET money_sejf=money_sejf+%d WHERE id=%d LIMIT 1",money,gid)) exports['psz-admin']:gameView_add("Gracz "..getPlayerName(client).." wplaca $"..money..", do sejfu gangu ("..gid..")") triggerClientEvent(source,"onResultSaveMoney", resourceRoot, true) outputChatBox("Wpłaciłeś "..money.."$, do sejfu gangu.",client,255,0,0) end) addEvent("onGangEdycjaPostaci", true) addEventHandler("onGangEdycjaPostaci", root, function(pid, ranga, skin) if (not pid or not ranga ) then return end if ranga == 4 then outputChatBox("Nie możesz nadać tej rangi nikomu.",client) return end skin = skin and tostring(skin) or "NULL" local query = string.format("UPDATE psz_players_gangs SET skin=%s, rank=%d WHERE id_player=%d LIMIT 1", skin, ranga, pid) exports['psz-mysql']:zapytanie(query) triggerClientEvent(source, "onGangEdycjaComplete", resourceRoot, true) exports['psz-admin']:gameView_add("Gracz "..getPlayerName(client).." aktualizuje gracza ("..pid.."), rank: "..ranga..", skin: "..skin) updatePlayerCoData(pid) end) addEvent('onGangInviteRequest',true) addEventHandler('onGangInviteRequest', root, function(gid, nick) if (not gid or not nick) then return end nick = tostring(nick) nick = string.gsub(nick,"#%x%x%x%x%x%x","") local query= string.format("SELECT userid FROM psz_postacie WHERE nick='%s' LIMIT 1", nick) local dane=exports['psz-mysql']:pobierzWyniki(query) if (dane and dane.userid) then query = string.format("SELECT 1 FROM psz_players_gangs WHERE id_player=%d LIMIT 1", dane.userid) if (exports['psz-mysql']:pobierzWyniki(query)) then triggerClientEvent(source,"onGangInviteReply", resourceRoot, false, "Ta osoba jest już w gangu.") return end local target = gang_getOnlinePlayer(dane.userid) if (target) then query = string.format("SELECT nazwa FROM psz_gangi WHERE id=%d LIMIT 1",gid) local g = exports['psz-mysql']:pobierzWyniki(query) outputChatBox("#BF5A02* Otrzymałeś zaproszenie do gangu #FFFFFF"..tostring(g.nazwa).."#BF5A02, aby zaakceptować wpisz /dolacz #FFFFFF"..tostring(g.nazwa).."#BF5A02.",target,255,255,255,true) setElementData(target,"ginv:ts",getTickCount()) setElementData(target,"ginv:name",g.nazwa) setElementData(target,"ginv:person",client) triggerClientEvent(source,'onGangInviteReply', resourceRoot, true) else triggerClientEvent(source, "onGangInviteReply", resourceRoot, false, "Podana osoba nie jest ONLINE.") return end else triggerClientEvent(source, "onGangInviteReply", resourceRoot, false, "Nie odnaleziono podanej osoby.") end end) addEvent("onGangWyrzucRequest",true) addEventHandler("onGangWyrzucRequest", root, function(gid,pid) if (not gid or not pid) then return end local query= string.format("DELETE FROM psz_players_gangs WHERE id_player=%d AND id_gang=%d LIMIT 1", pid, gid) exports['psz-mysql']:zapytanie(query) exports['psz-admin']:gameView_add("Gracz "..getPlayerName(client).." wyrzuca gracza ("..pid.."), z gangu ("..gid..")") triggerClientEvent(source,"onGangWyrzucComplete", resourceRoot) updatePlayerCoData(pid) end) addEvent("onGangUpgradeBuy", true) addEventHandler("onGangUpgradeBuy", root, function(gid, name) if (not gid or not name) then return end if name == 1 then outputChatBox("Funkcja w trakcie modyfikacji.",client) return -- outputChatBox("Aby dodać pojazd do gangu, wpisz komendę /edytor <id pojazdu/nazwa>.",client) --outputChatBox("Pamiętaj, nie możesz być w pojeździe lub innym interiorze.", client) --setElementData(client, "ge:have_access", true) elseif name == 3 then --local lvl = getElementData(client,"level") or 0 -- if (lvl and lvl~=3) then outputChatBox("W trakcie wdrażania.",client,255,0,0) return end gangs_upgradeGangZone(gid,client) else outputChatBox("Aktualnie możesz jedynie dodać nowe pojazdy do gangu, reszta będzie wkrótce.",client,255,0,0) return end end)
local M = {} function M.parse(arg) local cmd = torch.CmdLine() cmd:text() cmd:text('Object detection in torch') cmd:text() cmd:text('Options:') local curr_dir = paths.cwd() local defaultDataSetDir = paths.concat(curr_dir,'datasets') local defaultDataDir = paths.concat(defaultDataSetDir,'VOCdevkit/') local defaultROIDBDir = paths.concat(curr_dir,'data','selective_search_data/') cmd:text('Folder parameters') cmd:option('-cache',paths.concat(curr_dir,'cachedir'),'Cache dir') cmd:option('-datadir',defaultDataDir,'Path to dataset') cmd:option('-roidbdir',defaultROIDBDir,'Path to ROIDB') cmd:text() cmd:text('Model parameters') cmd:option('-algo','SPP','Detection framework. Options: RCNN | SPP') cmd:option('-netType','zeiler','Options: zeiler | vgg') cmd:option('-backend','cudnn','Options: nn | cudnn') cmd:text() cmd:text('Data parameters') cmd:option('-year',2007,'DataSet year (for Pascal)') cmd:option('-ipb',500,'iter per batch') cmd:option('-ntmd',10,'nTimesMoreData') cmd:option('-fg_frac',0.25,'fg_fraction') cmd:option('-classes','all','use all classes (all) or given class') cmd:text() cmd:text('Training parameters') cmd:option('-lr',1e-2,'learning rate') cmd:option('-num_iter',300,'number of iterations') cmd:option('-nsmooth',40,'number of iterations before reducing learning rate') cmd:option('-nred',4,'number of divisions by 2 before stopping learning') cmd:option('-nildfdx',false,'erase memory of gradients when reducing learning rate') cmd:text() cmd:text('Others') cmd:option('-gpu',1,'gpu device to use') cmd:option('-numthreads',6,'number of threads to use') cmd:option('-comment','','additional comment to the name') cmd:option('-seed',0,'random seed (0 = no fixed seed)') cmd:option('-retrain','none','modelpath for finetuning') cmd:text() local opt = cmd:parse(arg or {}) -- add commandline specified options opt.save = paths.concat(opt.cache, cmd:string(opt.netType, opt, {retrain=true, optimState=true, cache=true, data=true, gpu=true, numthread=true, netType=true})) -- add date/time opt.save_base = opt.save local date_time = os.date():gsub(' ','') opt.save = paths.concat(opt.save, date_time) return opt end return M
local Looper = require 'looping_signal' local KINDS = {'signal', 'word', 'listener'} local DEFAULT_DROPSPEED = 1 local LOOP_DELAY_FACTOR = 7 ---(Bubble):isAlive() -- @return boolean; whether the entity has outlasted its lifetime local isAlive = function(self) return self[6] > self[7] end ---(Bubble):isOn() -- @return boolean local isOn = function(self) if self[4] == KINDS[2] then return true end if self.elem.isOn then return self.elem:isOn() end return false end ---(Bubble):getLifeProgress() -- @return number >= 0; fraction of lifetime spent -- (0 at start, 1 at 'death'; can be > 1) local getLifeProgress = function(self) return self[7] / self[6] end ---(Bubble):getMessage() -- @return string; supplied message, if any (can be nil) local getMessage = function(self) return self[3] end ---(Bubble):getPosition() -- @return x,y position local getPosition = function(self) return self[1], self[2] end ---(Bubble):getType() -- @return string; enum of bubble kind (signal, word, &.) local getType = function(self) return self[4] end ---(Bubble):setPosition(x,y) -- @param x number (default 0) -- @param y number (default 0) local setPosition = function(self, x, y) self[1] = x or 0 self[2] = y or 0 end ---(Bubble):update(dt) -- @param dt 'delta time' (positive number) local update = function(self, dt) self[2] = self[2] + self[5] * dt self[7] = self[7] + dt if self.elem and self.elem.update then self.elem:update(dt) end end ---Bubble.new(msg, time_unit, speed, life) -- @param msg string; can cause errors if characters -- are not found in a dictionary elsewhere -- @param tums positive number; time unit of the signal/listener -- in milliseconds -- @param speed number; drop rate in pixels/second; < 0 rises (default 1) -- @param life positive number; lifespan in seconds (default +infinity) -- @return A new 'Bubble' object; -- msg,nil -> 'word' kind -- nil,ms -> 'listener' kind (NOT YET IMPLEMENTED) -- msg,ms -> 'signal' kind -- nil,nil -> error local function new(msg, tums, speed, life) speed = speed or 1 life = life or math.huge if msg then assert (type(msg) == 'string', 'msg must be a string') end assert (type(speed) == 'number', 'dropspeed must be a number') assert (type(life) == 'number', 'lifetime must be a number') assert (life > 0, 'lifetime must be greater than zero') local kind = KINDS[2] -- 'word' local elem if tums then assert (type(tums) == 'number', 'time unit must be a number') assert (tums > 0, 'time unit must be greater than zero') if msg then kind = KINDS[1] -- 'signal' elem = Looper.new(tums, msg) elem:setDelay(tums * LOOP_DELAY_FACTOR) elem:start() -- else -- kind = KINDS[3] -- 'listener' end else if not msg then error('must provide at least one of message or time unit') end -- else: default of word kind end return {[1] = 0, -- x coord [2] = 0, -- y coord [3] = msg, -- message [4] = kind, -- enum [5] = speed, -- drop rate [6] = life, -- fixed lifetime [7] = 0, -- time alive elem = elem, isAlive = isAlive, isOn = isOn, getLifeProgress = getLifeProgress, getMessage = getMessage, getPosition = getPosition, getType = getType, setPosition = setPosition, update = update, } end return {new = new}
local E, C, L, ET, _ = select(2, shCore()):unpack() if C.main.restyleUI ~= true then return end local _G = _G local GetPetHappiness = GetPetHappiness local HasPetUI = HasPetUI local UnitExists = UnitExists local function LoadSkin() local PetStableFrame = _G['PetStableFrame'] PetStableFrame:StripLayout() PetStableFrame:SetLayout() PetStableFrame.bg:SetAnchor('TOPLEFT', 10, -11) PetStableFrame.bg:SetAnchor('BOTTOMRIGHT', -32, 71) PetStableFrame:SetShadow() PetStableFrame.shadow:SetAnchor('TOPLEFT', 8, -9) PetStableFrame.shadow:SetAnchor('BOTTOMRIGHT', -28, 67) PetStableFramePortrait:dummy() ET:HandleButton(PetStablePurchaseButton) PetStableFrameCloseButton:CloseTemplate() ET:HandleRotateButton(PetStableModelRotateRightButton) ET:HandleRotateButton(PetStableModelRotateLeftButton) ET:HandleItemButton(_G['PetStableCurrentPet'], true) _G['PetStableCurrentPetIconTexture']:SetDrawLayer('OVERLAY') for i = 1, NUM_PET_STABLE_SLOTS do ET:HandleItemButton(_G['PetStableStabledPet'..i], true) _G['PetStableStabledPet'..i..'IconTexture']:SetDrawLayer('OVERLAY') end PetStablePetInfo:GetRegions():SetTexCoord(0.04, 0.15, 0.06, 0.30) PetStablePetInfo:SetFrameLevel(PetModelFrame:GetFrameLevel() +2) PetStablePetInfo:SetLayout() PetStablePetInfo:SetSize(24) hooksecurefunc('PetStable_Update', function() local happiness = GetPetHappiness() local hasPetUI, isHunterPet = HasPetUI() if UnitExists('pet') and hasPetUI and not isHunterPet then return end local texture = PetStablePetInfo:GetRegions() if happiness == 1 then texture:SetTexCoord(0.41, 0.53, 0.06, 0.30) elseif happiness == 2 then texture:SetTexCoord(0.22, 0.345, 0.06, 0.30) elseif happiness == 3 then texture:SetTexCoord(0.04, 0.15, 0.06, 0.30) end end) end table.insert(ET['SohighUI'], LoadSkin)
local config = { guildTalksEnabled = getBooleanFromString(getConfigValue('ingameGuildManagement')) } function onSay(cid, words, param, channel) local playerAccess, t = getPlayerAccess(cid), {} for i, talk in ipairs(getTalkActionList()) do if(not talk.hide and playerAccess >= talk.access) then local tmp = talk.words:sub(1, 1):trim() if((guildTalksEnabled or (talk.words ~= "!joinguild" and talk.words ~= "!createguild")) and (tmp == "!" or tmp == "/")) then table.insert(t, talk) end end end table.sort(t, function(a, b) return a.access > b.access end) local lastAccess, str = -1, "" for i, talk in ipairs(t) do local line = "" if(lastAccess ~= talk.access) then if(i ~= 1) then line = "\n" end lastAccess = talk.access end str = str .. line .. talk.words .. "\n" end doShowTextDialog(cid, 2160, str) return true end
test_run = require('test_run').new() REPLICASET_1 = { 'storage_1_a', 'storage_1_b' } REPLICASET_2 = { 'storage_2_a', 'storage_2_b' } test_run:create_cluster(REPLICASET_1, 'router') test_run:create_cluster(REPLICASET_2, 'router') util = require('util') util.wait_master(test_run, REPLICASET_1, 'storage_1_a') util.wait_master(test_run, REPLICASET_2, 'storage_2_a') test_run:cmd("create server router_1 with script='router/router_1.lua'") test_run:cmd("start server router_1") -- -- gh-77: garbage collection options and Lua garbage collection. -- test_run:switch('router_1') fiber = require('fiber') lua_gc = require('vshard.lua_gc') cfg.collect_lua_garbage = true vshard.router.cfg(cfg) lua_gc.internal.bg_fiber ~= nil -- Check that `collectgarbage()` was really called. a = setmetatable({}, {__mode = 'v'}) a.k = {b = 100} iterations = lua_gc.internal.iterations lua_gc.internal.bg_fiber:wakeup() while lua_gc.internal.iterations < iterations + 1 do fiber.sleep(0.01) end a.k lua_gc.internal.interval = 0.001 cfg.collect_lua_garbage = false vshard.router.cfg(cfg) lua_gc.internal.bg_fiber == nil iterations = lua_gc.internal.iterations fiber.sleep(0.01) iterations == lua_gc.internal.iterations test_run:switch("default") test_run:cmd("stop server router_1") test_run:cmd("cleanup server router_1") test_run:drop_cluster(REPLICASET_1) test_run:drop_cluster(REPLICASET_2)
remote = require('net.box') test_run = require('test_run').new() engine = test_run:get_cfg('engine') _ = box.space._session_settings:update('sql_default_engine', {{'=', 2, engine}}) box.execute('create table test (id int primary key, a NUMBER, b text)') space = box.space.TEST space:replace{1, 2, '3'} space:replace{4, 5, '6'} space:replace{7, 8.5, '9'} box.execute('select * from test') box.schema.user.grant('guest','read,write,execute', 'universe') box.schema.user.grant('guest', 'create', 'space') cn = remote.connect(box.cfg.listen) cn:ping() -- -- Static queries, with no parameters. -- -- Simple select. ret = cn:execute('select * from test') ret type(ret.rows[1]) -- Operation with row_count result. cn:execute('insert into test values (10, 11, NULL)') cn:execute('delete from test where a = 5') cn:execute('insert into test values (11, 12, NULL), (12, 12, NULL), (13, 12, NULL)') cn:execute('delete from test where a = 12') -- SQL errors. cn:execute('insert into not_existing_table values ("kek")') cn:execute('insert qwerty gjsdjq q qwd qmq;; q;qwd;') -- Empty result. cn:execute('select id as identifier from test where a = 5;') -- netbox API errors. cn:execute(100) cn:execute('select 1', nil, {dry_run = true}) -- Empty request. cn:execute('') cn:execute(' ;') -- -- gh-3467: allow only positive integers under limit clause. -- cn:execute('select * from test where id = ?', {1}) cn:execute('select * from test limit ?', {2}) cn:execute('select * from test limit ?', {-2}) cn:execute('select * from test limit ?', {2.7}) cn:execute('select * from test limit ?', {'Hello'}) cn:execute('select * from test limit 1 offset ?', {2}) cn:execute('select * from test limit 1 offset ?', {-2}) cn:execute('select * from test limit 1 offset ?', {2.7}) cn:execute('select * from test limit 1 offset ?', {'Hello'}) -- gh-2608 SQL iproto DDL cn:execute('create table test2(id int primary key, a int, b int, c int)') box.space.TEST2.name cn:execute('insert into test2 values (1, 1, 1, 1)') cn:execute('select * from test2') cn:execute('create index test2_a_b_index on test2(a, b)') #box.space.TEST2.index cn:execute('drop table test2') box.space.TEST2 -- gh-2617 DDL row_count either 0 or 1. -- Test CREATE [IF NOT EXISTS] TABLE. cn:execute('create table test3(id int primary key, a int, b int)') -- Rowcount = 1, although two tuples were created: -- for _space and for _index. cn:execute('insert into test3 values (1, 1, 1), (2, 2, 2), (3, 3, 3)') cn:execute('create table if not exists test3(id int primary key)') -- Test CREATE VIEW [IF NOT EXISTS] and -- DROP VIEW [IF EXISTS]. cn:execute('create view test3_view(id) as select id from test3') cn:execute('create view if not exists test3_view(id) as select id from test3') cn:execute('drop view test3_view') cn:execute('drop view if exists test3_view') -- Test CREATE INDEX [IF NOT EXISTS] and -- DROP INDEX [IF EXISTS]. cn:execute('create index test3_sec on test3(a, b)') cn:execute('create index if not exists test3_sec on test3(a, b)') cn:execute('drop index test3_sec on test3') cn:execute('drop index if exists test3_sec on test3') -- Test CREATE TRIGGER [IF NOT EXISTS] and -- DROP TRIGGER [IF EXISTS]. cn:execute('CREATE TRIGGER trig INSERT ON test3 FOR EACH ROW BEGIN SELECT * FROM test3; END;') cn:execute('CREATE TRIGGER if not exists trig INSERT ON test3 FOR EACH ROW BEGIN SELECT * FROM test3; END;') cn:execute('drop trigger trig') cn:execute('drop trigger if exists trig') -- Test DROP TABLE [IF EXISTS]. -- Create more indexes, triggers and _truncate tuple. cn:execute('create index idx1 on test3(a)') cn:execute('create index idx2 on test3(b)') box.space.TEST3:truncate() cn:execute('CREATE TRIGGER trig INSERT ON test3 FOR EACH ROW BEGIN SELECT * FROM test3; END;') cn:execute('insert into test3 values (1, 1, 1), (2, 2, 2), (3, 3, 3)') cn:execute('drop table test3') cn:execute('drop table if exists test3') -- -- gh-2948: sql: remove unnecessary templates for binding -- parameters. -- cn:execute('select ?1, ?2, ?3', {1, 2, 3}) cn:execute('select $name, $name2', {1, 2}) parameters = {} parameters[1] = 11 parameters[2] = 22 parameters[3] = 33 cn:execute('select $2, $1, $3', parameters) cn:execute('select * from test where id = :1', {1}) -- gh-2602 obuf_alloc breaks the tuple in different slabs _ = space:replace{1, 1, string.rep('a', 4 * 1024 * 1024)} res = cn:execute('select * from test') res.metadata box.execute('drop table test') cn:close() -- -- gh-3107: async netbox. -- cn = remote.connect(box.cfg.listen) cn:execute('create table test (id integer primary key, a integer, b integer)') future1 = cn:execute('insert into test values (1, 1, 1)', nil, nil, {is_async = true}) future2 = cn:execute('insert into test values (1, 2, 2)', nil, nil, {is_async = true}) future3 = cn:execute('insert into test values (2, 2, 2), (3, 3, 3)', nil, nil, {is_async = true}) future1:wait_result() future2:wait_result() future3:wait_result() future4 = cn:execute('select * from test', nil, nil, {is_async = true}) future4:wait_result() cn:close() box.execute('drop table test') -- gh-2618 Return generated columns after INSERT in IPROTO. -- Return all ids generated in current INSERT statement. box.execute('create table test (id integer primary key autoincrement, a integer)') cn = remote.connect(box.cfg.listen) cn:execute('insert into test values (1, 1)') cn:execute('insert into test values (null, 2)') cn:execute('update test set a = 11 where id == 1') cn:execute('insert into test values (100, 1), (null, 1), (120, 1), (null, 1)') cn:execute('insert into test values (null, 1), (null, 1), (null, 1), (null, 1), (null, 1)') cn:execute('select * from test') s = box.schema.create_space('test2', {engine = engine}) sq = box.schema.sequence.create('test2') pk = s:create_index('pk', {sequence = 'test2'}) function push_id() s:replace{box.NULL} s:replace{box.NULL} end _ = box.space.TEST:on_replace(push_id) cn:execute('insert into test values (null, 1)') box.execute('create table test3 (id int primary key autoincrement)') box.schema.sequence.alter('TEST3', {min=-10000, step=-10}) cn:execute('insert into TEST3 values (null), (null), (null), (null)') box.execute('drop table test') s:drop() sq:drop() box.execute('drop table test3') -- -- Ensure that FK inside CREATE TABLE does not affect row_count. -- cn:execute('create table test (id integer primary key, a integer)') cn:execute('create table test2 (id integer primary key, ref integer references test(id))') cn:execute('drop table test2') -- -- Ensure that REPLACE is accounted twice in row_count. As delete + -- insert. -- cn:execute('insert into test values(1, 1)') cn:execute('insert or replace into test values(1, 2)') cn:execute('drop table test') -- SELECT returns unpacked msgpack. format = {{name = 'id', type = 'integer'}, {name = 'x', type = 'any'}} s = box.schema.space.create('test', {format=format}) i1 = s:create_index('i1', {parts = {1, 'int'}}) s:insert({1, {1,2,3}}) s:insert({2, {a = 3}}) cn:execute('select * from "test"') s:drop() -- Too many autogenerated ids leads to SEGFAULT. cn = remote.connect(box.cfg.listen) box.execute('CREATE TABLE t1(id INTEGER PRIMARY KEY AUTOINCREMENT)') for i = 0, 1000 do cn:execute("INSERT INTO t1 VALUES (null)") end _ = cn:execute("INSERT INTO t1 SELECT NULL from t1") box.execute('DROP TABLE t1') cn:close() -- gh-3832: Some statements do not return column type box.execute('CREATE TABLE t1(id INTEGER PRIMARY KEY)') cn = remote.connect(box.cfg.listen) -- PRAGMA: res = cn:execute("PRAGMA table_info(t1)") res.metadata -- EXPLAIN res = cn:execute("EXPLAIN SELECT 1") res.metadata res = cn:execute("EXPLAIN QUERY PLAN SELECT COUNT(*) FROM t1") res.metadata -- Make sure that built-in functions have a right returning type. -- cn:execute("SELECT zeroblob(1);") -- randomblob() returns different results each time, so check only -- type in meta. -- res = cn:execute("SELECT randomblob(1);") res.metadata -- Type set during compilation stage, and since min/max are accept -- arguments of all scalar type, we can't say nothing more than -- SCALAR. -- cn:execute("SELECT LEAST(1, 2, 3);") cn:execute("SELECT GREATEST(1, 2, 3);") cn:close() box.execute('DROP TABLE t1') box.schema.user.revoke('guest', 'read,write,execute', 'universe') box.schema.user.revoke('guest', 'create', 'space') space = nil -- -- gh-4756: PREPARE and EXECUTE statistics should be present in box.stat() -- p = box.stat().PREPARE.total e = box.stat().EXECUTE.total s = box.prepare([[ SELECT ?; ]]) s:execute({42}) box.execute('SELECT 1;') res, err = box.unprepare(s) assert(box.stat().PREPARE.total == p + 1) assert(box.stat().EXECUTE.total == e + 2) -- Cleanup xlog box.snapshot()
local m = require 'lpeg' local contiguous_byte_ranges = require 'parse.char.utf8.data.contiguous_byte_ranges' local m_char = require 'parse.char.utf8' local two_chars = m.C(m_char) * m.C(m_char) * m.P(-1) local prefix_char = m.C(m_char) * m.Cp() local blob_tools = require 'parse.blob.tools' local next_blob = blob_tools.next local char_tools = require 'parse.char.utf8.tools' local next_char = char_tools.next local previous_char = char_tools.previous local char_range = char_tools.range local set_proto = {} local set_meta = {__index = set_proto} local function add_ranges(ranges, from_char, to_char) -- we don't need to do anything if from_char and to_char -- only differ by their final byte if #from_char ~= #to_char or (#from_char > 1 and from_char:sub(1, -2) ~= to_char:sub(1, -2)) then local min_char, max_char -- if this loop does not break/return, from_char is invalid for i, range_set in ipairs(contiguous_byte_ranges) do min_char = range_set.min max_char = range_set.max if from_char <= max_char then if to_char <= max_char then break end -- if lib.byte_sequence_ranges[i+1] is nil, to_char is invalid local next_min_char = contiguous_byte_ranges[i+1].min add_ranges(ranges, from_char, max_char) add_ranges(ranges, next_min_char, to_char) return end end -- this loop should always break/return for i = 1, #from_char-1 do local from_b = string.byte(from_char, i) local to_b = string.byte(to_char, i) if from_b ~= to_b then if string.sub(from_char, i+1) ~= string.sub(min_char, i+1) then add_ranges(ranges, from_char, string.sub(from_char, 1, i) .. string.sub(max_char, i + 1)) add_ranges(ranges, string.sub(from_char, 1, i - 1) .. string.char(from_b + 1) .. string.sub(min_char, i + 1), to_char) elseif string.sub(to_char, i+1) ~= string.sub(max_char, i+1) then add_ranges(ranges, from_char, string.sub(from_char, 1, i - 1) .. string.char(to_b - 1) .. string.sub(max_char, i + 1)) add_ranges(ranges, string.sub(from_char, 1, i - 1) .. string.char(from_b + 1) .. string.sub(min_char, i + 1), to_char) else break end return end end end ranges[#ranges+1] = {from_char, to_char} end local range_proto = {} local range_meta = {__index = range_proto} function range_proto:compile(min_pre_count) local p_initial = m.P(true) local count = #self if self[1] and self[1][1] then if min_pre_count and count >= min_pre_count then p_initial = m.P(false) for i = 1, count do p_initial = p_initial + self[i][1] end p_initial = #p_initial end if count >= 16 then local halfway_point = math.floor(count/2) local first_half = setmetatable({unpack(self,1,halfway_point)}, range_meta) local second_half = setmetatable({unpack(self,halfway_point+1)}, range_meta) local first_half_prefix_char = m.P(false) for i = 1, halfway_point do first_half_prefix_char = first_half_prefix_char + first_half[i][1] end return p_initial * ( #first_half_prefix_char * first_half:compile() + second_half:compile() ) end end local matcher = m.P(false) for i = count, 1, -1 do matcher = self[i][2] + matcher end return p_initial * matcher end local function aux_range_pattern(output, sorted_ranges, pos, prefix) local range = sorted_ranges[pos] if range == nil then return pos end if prefix ~= '' then if range[1]:sub(1, #prefix) ~= prefix or range[2]:sub(1, #prefix) ~= prefix then return pos end end local next_prefix_len = #prefix + 1 if next_prefix_len < #range[1] and string.byte(range[1], next_prefix_len) == string.byte(range[2], next_prefix_len) then local sub_output = setmetatable({}, range_meta) local next_prefix = string.sub(range[1], 1, next_prefix_len) local next_pos = aux_range_pattern(sub_output, sorted_ranges, pos, next_prefix) output[#output+1] = {m.P(next_prefix:sub(-1)), m.P(next_prefix:sub(-1)) * sub_output:compile(8)} return aux_range_pattern(output, sorted_ranges, next_pos, prefix) end local matcher = m.P(true) local match_prefix_char = false for i = next_prefix_len, #range[1] do local from_b = string.sub(range[1], i,i) local to_b = string.sub(range[2], i,i) local match_b if from_b == to_b then match_b = m.P(from_b) else match_b = m.R(from_b..to_b) end matcher = matcher * match_b if i == next_prefix_len and i < #range[1] then match_prefix_char = match_b end end output[#output+1] = {match_prefix_char, matcher} return aux_range_pattern(output, sorted_ranges, pos + 1, prefix) end function set_proto:compile() local ranges = {} local set = self.S if set ~= nil then local char local i = 1 while i <= #set do char, i = prefix_char:match(set, i) if char == nil then error('bad S value: invalid utf-8 sequence', 2) end add_ranges(ranges, char, char) end end local r = self.R if type(r) == 'string' then r = {r} end for _, pair in ipairs(r or {}) do local from_char, to_char = two_chars:match(pair) if from_char == nil then error('bad R value: expecting sequence of 2 utf-8 characters', 2) end add_ranges(ranges, from_char, to_char) end -- sort by the first character table.sort(ranges, function(a,b) return a[1] < b[1]; end) -- combine touching/overlapping ranges do local i = 1 local range = ranges[i] if range ~= nil then repeat i = i + 1 local next_range = ranges[i] while next_range ~= nil and (range[2] >= next_range[1] or next_blob(range[2]) == next_range[1]) do if range[2] < next_range[2] then range[2] = next_range[2] end table.remove(ranges, i) next_range = ranges[i] end range = next_range until range == nil end end local onebyte = m.P(false) while ranges[1] and #ranges[1][1] == 1 do local range = table.remove(ranges, 1) onebyte = onebyte + m.R(range[1] .. range[2]) end local alternatives = setmetatable({}, range_meta) aux_range_pattern(alternatives, ranges, 1, '') local ranges_pattern = alternatives:compile(2) return onebyte + ranges_pattern end function set_meta.__add(a, b) local R if type(a.R) == 'string' then R = {a.R} else R = {unpack(a.R or {})} end if type(b.R) == 'string' then R[#R+1] = b.R else for i,v in ipairs(b.R or {}) do R[#R+1] = v end end local S = (a.S or '') .. (b.S or '') return setmetatable({R=R, S=S}, set_meta) end local function each_char(v) local pos = 1 return function() if pos > #v then return nil end local char; char, pos = prefix_char:match(v, pos) if char == nil then error('invalid utf-8 sequence') end return char end end function set_meta.__sub(a, b) local S_set = {} do for c in each_char(a.S or '') do S_set[c] = true end end local R_list = {} do local R if type(a.R) == 'string' then R = {a.R} else R = a.R or {} end for i, pair in ipairs(R) do local from_char, to_char = two_chars:match(pair) if from_char == nil then error('invalid utf-8 sequence') end add_ranges(R_list, from_char, to_char) end table.sort(R_list, function(x, y) return x[1] < y[1] end) end local function remove_range(from_char, to_char) for c in char_range(from_char, to_char) do S_set[c] = nil end local i = 1 while true do local pair = R_list[i] if pair == nil or to_char < pair[1] then break end if from_char > pair[2] then i = i + 1 goto continue end if from_char <= pair[1] then if to_char >= pair[2] then table.remove(R_list, i) goto continue end pair[1] = next_char(to_char) i = i + 1 goto continue end if to_char >= pair[2] then pair[2] = previous_char(from_char) i = i + 1 goto continue end table.insert(R_list, i + 1, {next_char(to_char), pair[2]}) pair[2] = previous_char(from_char) i = i + 2 ::continue:: end end for c in each_char(b.S or '') do remove_range(c, c) end local remove_R = b.R if type(remove_R) == 'string' then remove_R = {remove_R} end for i, pair in ipairs(remove_R or {}) do local from_char, to_char = two_chars:match(pair) if from_char == nil then error('invalid utf-8 sequence') end remove_range(from_char, to_char) end local S_list = {} for c in pairs(S_set) do S_list[#S_list+1] = c end local S = table.concat(S_list) for i,pair in ipairs(R_list) do R_list[i] = pair[1] .. pair[2] end return setmetatable({R=R_list, S=S}, set_meta) end return function(def) return setmetatable(def or {R='\0\u{10ffff}'}, set_meta) end
---@class AceLocale-3.0 local AceLocale = {} ---@param application string Unique name of addon / module ---@param silent? boolean If true, the locale is optional, silently return nil if it's not found (defaults to false, optional) ---@return table -- The locale table for the current language. --- --- ---[Documentation](https://www.wowace.com/projects/ace3/pages/api/ace-locale-3-0#title-1) function AceLocale:GetLocale(application, silent) end ---@paramsig application, locale[, isDefault[, silent]] ---@param application string Unique name of addon / module ---@param locale GAME_LOCALE Name of the locale to register, e.g. "enUS", "deDE", etc. ---@param isDefault? boolean If this is the default locale being registered. Your addon is written in this language, generally enUS, set this to true (defaults to false) ---@param silent? boolean If true, the locale will not issue warnings for missing keys. Must be `true` on the first locale registered. If set to "raw", nils will be returned for unknown keys (no metatable used). ---@return table -- Locale Table to add localizations to, or nil if the current locale is not required. --- --- ---[Documentation](https://www.wowace.com/projects/ace3/pages/api/ace-locale-3-0#title-2) function AceLocale:NewLocale(application, locale, isDefault, silent) end ---@alias GAME_LOCALE ---| "frFR" French (France) ---| "deDE": German (Germany) ---| "enGB": English (Great Britain) if returned, can substitute 'enUS' for consistancy ---| "enUS": English (America) ---| "itIT": Italian (Italy) ---| "koKR": Korean (Korea) RTL - right-to-left ---| "zhCN": Chinese (China) (simplified) implemented LTR left-to-right in WoW ---| "zhTW": Chinese (Taiwan) (traditional) implemented LTR left-to-right in WoW ---| "ruRU": Russian (Russia) ---| "esES": Spanish (Spain) ---| "esMX": Spanish (Mexico) ---| "ptBR": Portuguese (Brazil)
local _G = getfenv(0) local AtlasLoot = _G.AtlasLoot -- lua local GetMapInfo = C_Map.GetMapInfo local rawget = rawget local _, tmp1 local months = { MONTH_JANUARY, MONTH_FEBRUARY, MONTH_MARCH, MONTH_APRIL, MONTH_MAY, MONTH_JUNE, MONTH_JULY, MONTH_AUGUST, MONTH_SEPTEMBER, MONTH_OCTOBER, MONTH_NOVEMBER, MONTH_DECEMBER, } local GetAchievementInfo, UnitSex, GetFactionInfoByID = _G.GetAchievementInfo, _G.UnitSex, _G.GetFactionInfoByID local function GetSpecNameById(id) _, tmp1 = GetSpecializationInfoByID(id) return tmp1 end local function GetAchievementName(id) _, tmp1 = GetAchievementInfo(id) return tmp1 end local function GetBuildingName(id) _, tmp1 = C_Garrison.GetBuildingInfo(id) return tmp1 end local function AtlasLoot_GetClassName(class) if (not LOCALIZED_CLASS_NAMES_MALE[class]) then return nil; end if (UnitSex("player") == "3") then return LOCALIZED_CLASS_NAMES_FEMALE[class]; else return LOCALIZED_CLASS_NAMES_MALE[class]; end end local IngameLocales = { -- ###################################################################### -- Factions -- ###################################################################### -- Legion ["Bizmo's Brawlpub"] = GetFactionInfoByID(2011), ["Brawl'gar Arena"] = GetFactionInfoByID(2010), -- Warlords of Draenor -- ["Bizmo's Brawlpub"] = GetFactionInfoByID(1691), -- ["Brawl'gar Arena"] = GetFactionInfoByID(1690), -- Mists of Pandaria ["Nat Pagle"] = GetFactionInfoByID(1358), ["Old Hillpaw"] = GetFactionInfoByID(1276), ["Sho"] = GetFactionInfoByID(1278), ["The August Celestials"] = GetFactionInfoByID(1341), -- ###################################################################### -- Months -- ###################################################################### ["January"] = months[1], ["February"] = months[2], ["March"] = months[3], ["April"] = months[4], ["May"] = months[5], ["June"] = months[6], ["July"] = months[7], ["August"] = months[8], ["September"] = months[9], ["October"] = months[10], ["November"] = months[11], ["December"] = months[12], -- ###################################################################### -- Class Specs -- ###################################################################### ["Balance"] = GetSpecNameById(102), ["Feral"] = GetSpecNameById(103), ["Guardian"] = GetSpecNameById(104), ["Restoration"] = GetSpecNameById(105), ["Blood"] = GetSpecNameById(250), ["Frost"] = GetSpecNameById(251), ["Unholy"] = GetSpecNameById(252), ["Brewmaster"] = GetSpecNameById(268), ["Mistweaver"] = GetSpecNameById(270), ["Windwalker"] = GetSpecNameById(269), ["Discipline"] = GetSpecNameById(256), ["Holy"] = GetSpecNameById(257), ["Shadow"] = GetSpecNameById(258), ["Protection"] = GetSpecNameById(66), ["Retribution"] = GetSpecNameById(70), ["Elemental"] = GetSpecNameById(262), ["Enhancement"] = GetSpecNameById(263), ["Arms"] = GetSpecNameById(71), ["Fury"] = GetSpecNameById(72), -- ###################################################################### -- Zones -- ###################################################################### -- Classic ["Ahn'Qiraj"] = GetMapInfo(319).name, ["Blackrock Depths"] = GetMapInfo(242).name, ["Blackwing Lair"] = GetMapInfo(287).name, ["Lower Blackrock Spire"] = GetAchievementName(643), ["Molten Core"] = GetMapInfo(232).name, ["Orgrimmar"] = GetMapInfo(85).name, ["Ruins of Ahn'Qiraj"] = GetMapInfo(247).name, ["Shadowfang Keep"] = GetMapInfo(310).name, ["Stormwind City"] = GetMapInfo(84).name, ["Upper Blackrock Spire"] = GetAchievementName(1307), -- Burning Crusade ["Black Temple"] = GetMapInfo(339).name, ["Gruul's Lair"] = GetMapInfo(330).name, ["Hyjal Summit"] = GetMapInfo(329).name, ["Karazhan"] = GetMapInfo(350).name, ["Magtheridon's Lair"] = GetMapInfo(331).name, ["Outland"] = GetMapInfo(101).name, ["Serpentshrine Cavern"] = GetMapInfo(332).name, ["Shattrath City"] = GetMapInfo(111).name, ["Sunwell Plateau"] = GetMapInfo(335).name, ["Tempest Keep"] = GetMapInfo(334).name, ["The Slave Pens"] = GetMapInfo(265).name, -- Wrath of the Lich King ["Dalaran"] = GetMapInfo(125).name, ["Icecrown"] = GetMapInfo(118).name, ["Icecrown Citadel"] = GetMapInfo(186).name, ["Naxxramas"] = GetMapInfo(162).name, ["Northrend"] = GetMapInfo(113).name, ["Onyxia's Lair"] = GetMapInfo(248).name, ["The Eye of Eternity"] = GetMapInfo(141).name, ["The Obsidian Sanctum"] = GetMapInfo(155).name, ["The Ruby Sanctum"] = GetMapInfo(200).name, ["Trial of the Crusader"] = GetMapInfo(172).name, ["Ulduar"] = GetMapInfo(147).name, ["Vault of Archavon"] = GetMapInfo(156).name, -- Cataclysm ["Molten Front"] = GetMapInfo(338).name, -- Mists of Pandaria ["Scarlet Monastery"] = GetMapInfo(435).name, ["Timeless Isle"] = GetMapInfo(554).name, -- ###################################################################### -- Garrison Buildings -- ###################################################################### ["DBWM"] = GetBuildingName(10), -- Client autoselection ["Enchanter's Study"] = GetBuildingName(126), ["Engineering Works"] = GetBuildingName(124), ["Fishing Shack"] = GetBuildingName(135), ["GGGW"] = GetBuildingName(164), -- Client autoselection ["LIFT"] = GetBuildingName(36), -- Client autoselection ["Salvage Yard"] = GetBuildingName(141), ["Stables"] = GetBuildingName(67), ["The Tannery"] = GetBuildingName(122), -- data from Core/ItemInfo.lua is generated after loading -- ###################################################################### -- Class -- ###################################################################### ["DEATHKNIGHT"] = AtlasLoot_GetClassName("DEATHKNIGHT"), ["DEMONHUNTER"] = AtlasLoot_GetClassName("DEMONHUNTER"), ["DRUID"] = AtlasLoot_GetClassName("DRUID"), ["HUNTER"] = AtlasLoot_GetClassName("HUNTER"), ["MAGE"] = AtlasLoot_GetClassName("MAGE"), ["MONK"] = AtlasLoot_GetClassName("MONK"), ["PALADIN"] = AtlasLoot_GetClassName("PALADIN"), ["PRIEST"] = AtlasLoot_GetClassName("PRIEST"), ["ROGUE"] = AtlasLoot_GetClassName("ROGUE"), ["SHAMAN"] = AtlasLoot_GetClassName("SHAMAN"), ["WARLOCK"] = AtlasLoot_GetClassName("WARLOCK"), ["WARRIOR"] = AtlasLoot_GetClassName("WARRIOR"), } AtlasLoot.IngameLocales = IngameLocales setmetatable(IngameLocales, { __index = function(tab, key) return rawget(tab, key) or key end } )
local name, _GatherLite = ...; local GFrame = LibStub("GatherLiteFrame"); local HBD = LibStub("HereBeDragons-2.0"); local worldmapOpen = false; local worldmapID = nil; local timeDiff = 0 local checkDiff = 0 GatherLiteTracker = {}; function GatherLiteTracker:OnLoad() GatherLite:On("worldmap:update", function() GatherLiteTracker:Worldmap(); end); end GatherLiteTracker.WorldmapFilter = function(node) if not GatherLite.db.char.worldmap.enabled then return false end -- check if were tracking the type of node if not GatherLite.db.char.tracking[node.type] then return false end -- check if were using the predefined database if node.predefined and not GatherLite.db.global.usePredefined then return false end -- check if the node type is should be ignored. if GatherLite:IsIgnored(node.object) then return false end return true; end GatherLiteTracker.MinimapFilter = function(node) if not GatherLite.db.char.minimap.enabled then return false end -- check if were tracking the type of node if not GatherLite.db.char.tracking[node.type] then return false end -- check if were using the predefined database --GatherLite:print(node.predefined) if node.predefined then if not GatherLite.db.global.usePredefined then return false end end -- check if the node type is should be ignored. if GatherLite:IsIgnored(node.object) then return false end return true; end function GatherLiteTracker:ClosestNodes(type, posX, posY, instanceID, maxDist, filter) local t = table.filter(_GatherLite.nodes[type], function(node) if node.instance ~= instanceID then return false end if not filter(node) then return false end local x, y, _ = HBD:GetWorldCoordinatesFromZone(node.posX, node.posY, node.mapID); local _, distance = HBD:GetWorldVector(instanceID, posX, posY, x, y) return distance and distance < maxDist; end) return t; end function GatherLiteTracker:WorldmapNodes(list, mapID, filter) return table.filter(list, function(node) return node.mapID == mapID and filter(node); end); end table.filter = function(t, filterIter) local out = {} for k, v in pairs(t) do if filterIter(v, k, t) then out[k] = v; end end return out end table.length = function(T) local count = 0 if T then for _ in pairs(T) do count = count + 1 end end return count end local function miningThread() local x, y, instanceID = HBD:GetPlayerWorldPosition() local t = GatherLiteTracker:ClosestNodes("mining", x, y, instanceID, GatherLite.db.char.minimap.range, GatherLiteTracker.MinimapFilter); for key, node in pairs(t) do if not _GatherLite.nodes["mining"][key].loaded then GatherLite:createMinimapNode(_GatherLite.nodes["mining"][key]) _GatherLite.nodes["mining"][key].loaded = true; end --print(key) coroutine.yield() end end local function herbalismThread() local x, y, instanceID = HBD:GetPlayerWorldPosition() local t = GatherLiteTracker:ClosestNodes("herbalism", x, y, instanceID, GatherLite.db.char.minimap.range, GatherLiteTracker.MinimapFilter); for key, node in pairs(t) do if not _GatherLite.nodes["herbalism"][key].loaded then GatherLite:createMinimapNode(_GatherLite.nodes["herbalism"][key]) _GatherLite.nodes["herbalism"][key].loaded = true; end coroutine.yield() end end local function containerThread() local x, y, instanceID = HBD:GetPlayerWorldPosition() local t = GatherLiteTracker:ClosestNodes("containers", x, y, instanceID, GatherLite.db.char.minimap.range, GatherLiteTracker.MinimapFilter); for key, node in pairs(t) do if not _GatherLite.nodes["containers"][key].loaded then GatherLite:createMinimapNode(_GatherLite.nodes["containers"][key]) _GatherLite.nodes["containers"][key].loaded = true; end coroutine.yield() end end local function fishingThread() local x, y, instanceID = HBD:GetPlayerWorldPosition() local t = GatherLiteTracker:ClosestNodes("fishing", x, y, instanceID, GatherLite.db.char.minimap.range, GatherLiteTracker.MinimapFilter); for key, node in pairs(t) do if not _GatherLite.nodes["fishing"][key].loaded then GatherLite:createMinimapNode(_GatherLite.nodes["fishing"][key]) _GatherLite.nodes["fishing"][key].loaded = true; end coroutine.yield() end end local function minimapIconThread() local x, y, instanceID = HBD:GetPlayerWorldPosition() for key, iframe in pairs(GFrame.usedFrames) do local frame = GFrame.usedFrames[key] if frame.type == "minimap" and frame.node.loaded then if IsInInstance() then frame.node.loaded = false; frame:Unload(); return end local x2, y2, _ = HBD:GetWorldCoordinatesFromZone(frame.node.posX, frame.node.posY, frame.node.mapID); local _, distance = HBD:GetWorldVector(instanceID, x, y, x2, y2) if not distance then frame.node.loaded = false; frame:Unload(); return end if distance >= GatherLite.db.char.minimap.range then frame.node.loaded = false; frame:Unload(); return end if not GatherLiteTracker.MinimapFilter(frame.node) then frame.node.loaded = false; frame:Unload(); return end if frame.node.type ~= "containers" and frame.node.type ~= "fishing" then if distance < GatherLite.db.char.minimap.distance and frame:IsVisible() then frame:FakeHide(); elseif distance >= GatherLite.db.char.minimap.distance and not frame:IsVisible() then frame:FakeShow(); end end elseif frame.type == "minimap" and not frame.node.loaded then frame.node.loaded = false; frame:Unload(); end coroutine.yield() end end local threadMining = coroutine.create(miningThread) local threadHerbalism = coroutine.create(herbalismThread) local threadContainer = coroutine.create(containerThread) local threadFishing = coroutine.create(fishingThread) local threadIcon = coroutine.create(minimapIconThread) function GatherLiteTracker:Minimap(timeDelta, force) local updateIcons = false local updateNodes = false if (force) then updateIcons = true updateNodes = true threadMining = coroutine.create(miningThread) threadHerbalism = coroutine.create(herbalismThread) threadContainer = coroutine.create(herbalismThread) threadFishing = coroutine.create(fishingThread) threadIcon = coroutine.create(minimapIconThread) else checkDiff = checkDiff + timeDelta timeDiff = timeDiff + timeDelta if (checkDiff > 5) then updateNodes = true checkDiff = 0 updateIcons = true timeDiff = 0 elseif (timeDiff > 0.5) then updateIcons = true timeDiff = 0 end end if (updateNodes) then if coroutine.status(threadMining) == "dead" then threadMining = coroutine.create(miningThread) end if coroutine.status(threadHerbalism) == "dead" then threadHerbalism = coroutine.create(herbalismThread) end if coroutine.status(threadContainer) == "dead" then threadContainer = coroutine.create(containerThread) end if coroutine.status(threadFishing) == "dead" then threadFishing = coroutine.create(fishingThread) end end if (updateIcons) then if coroutine.status(threadIcon) == "dead" then threadIcon = coroutine.create(minimapIconThread) end end coroutine.resume(threadMining) coroutine.resume(threadHerbalism) coroutine.resume(threadContainer) coroutine.resume(threadFishing) coroutine.resume(threadIcon) end function GatherLiteTracker:Worldmap() GatherLite:forEach(GFrame.usedFrames, function(frame) if frame.type == "worldmap" and frame.node.loadedWorldmap then frame.node.loadedWorldmap = false; frame:Unload() end end); if worldmapOpen and worldmapID then for key, node in pairs(GatherLiteTracker:WorldmapNodes(_GatherLite.nodes["mining"], worldmapID, GatherLiteTracker.WorldmapFilter)) do _GatherLite.nodes["mining"][key].loadedWorldmap = true GatherLite:createWorldmapNode(_GatherLite.nodes["mining"][key]) end for key, node in pairs(GatherLiteTracker:WorldmapNodes(_GatherLite.nodes["herbalism"], worldmapID, GatherLiteTracker.WorldmapFilter)) do _GatherLite.nodes["herbalism"][key].loadedWorldmap = true GatherLite:createWorldmapNode(_GatherLite.nodes["herbalism"][key]) end for key, node in pairs(GatherLiteTracker:WorldmapNodes(_GatherLite.nodes["containers"], worldmapID, GatherLiteTracker.WorldmapFilter)) do _GatherLite.nodes["containers"][key].loadedWorldmap = true GatherLite:createWorldmapNode(_GatherLite.nodes["containers"][key]) end for key, node in pairs(GatherLiteTracker:WorldmapNodes(_GatherLite.nodes["fishing"], worldmapID, GatherLiteTracker.WorldmapFilter)) do _GatherLite.nodes["fishing"][key].loadedWorldmap = true GatherLite:createWorldmapNode(_GatherLite.nodes["fishing"][key]) end end end function GatherLiteTracker:OnUpdate(timeDelta) if _GatherLite.WorldmapOpen and not worldmapOpen then worldmapOpen = true; elseif not _GatherLite.WorldmapOpen and worldmapOpen then worldmapOpen = false; worldmapID = nil; GatherLite:Trigger("worldmap:update") end if worldmapOpen then if worldmapID ~= WorldMapFrame.mapID then worldmapID = WorldMapFrame.mapID; GatherLite:Trigger("worldmap:update") end end GatherLiteTracker:Minimap(timeDelta) end
local Timing = Component.create("Timing") function Timing:initialize(time) self.timer = time end
return { namespaced_message = "This message is in another intl file." }
modifier_dummy = class({}) --Set the dummy out of the game function modifier_dummy:CheckState() local state = { [MODIFIER_STATE_OUT_OF_GAME] = true, [MODIFIER_STATE_INVULNERABLE] = true, [MODIFIER_STATE_NO_UNIT_COLLISION] = true, [MODIFIER_STATE_UNSELECTABLE] = true } return state end
table.insert(data.raw["technology"]["military"].effects, { type = "unlock-recipe", recipe = "alien-plate" }) table.insert(data.raw["technology"]["military"].effects, { type = "unlock-recipe", recipe = "alien-magazine" }) table.insert(data.raw["technology"]["military"].effects, { type = "unlock-recipe", recipe = "alien-fuel" }) if data.raw["item"]["alien-artifact"] then table.insert(data.raw["technology"]["automation"].effects, { type = "unlock-recipe", recipe = "alien-artifact-to-ore" }) end table.insert(data.raw["technology"]["automation"].effects, { type = "unlock-recipe", recipe = "alien-module-1" }) table.insert(data.raw["technology"]["automation"].effects, { type = "unlock-recipe", recipe = "alien-hyper-module-1" }) table.insert(data.raw["technology"]["electronics"].effects, { type = "unlock-recipe", recipe = "alien-module-2" }) table.insert(data.raw["technology"]["advanced-electronics"].effects, { type = "unlock-recipe", recipe = "alien-module-3" }) table.insert(data.raw["technology"]["advanced-electronics"].effects, { type = "unlock-recipe", recipe = "alien-module-4" }) table.insert(data.raw["technology"]["advanced-electronics"].effects, { type = "unlock-recipe", recipe = "alien-module-5" }) table.insert(data.raw["technology"]["solar-energy"].effects, { type = "unlock-recipe", recipe = "alien-solarpanel" }) table.insert(data.raw["technology"]["electric-energy-accumulators-1"].effects, { type = "unlock-recipe", recipe = "alien-accumulator" })
-- -- Created by IntelliJ IDEA. -- User: chen0 -- Date: 11/7/2017 -- Time: 8:28 AM -- To change this template use File | Settings | File Templates. -- local ConnectedComponents = {} ConnectedComponents.__index = ConnectedComponents function ConnectedComponents.create() local s = {} setmetatable(s, ConnectedComponents) s.marked = {} s.count = 0 s.id = {} return s end function ConnectedComponents:run(G) self.marked = {} self.id = {} for i = 0, G:vertexCount()-1 do local v = G:vertexAt(i) self.marked[v] = false self.id[v] = -1 end self.count = 0 for i = 0, G:vertexCount()-1 do local v = G:vertexAt(i) if self.marked[v] == false then self:dfs(G, v) self.count = self.count + 1 end end end function ConnectedComponents:dfs(G, v) self.marked[v] = true self.id[v] = self.count local adj_v = G:adj(v) for i = 0,adj_v:size()-1 do local e = adj_v:get(i) local w = e:other(v) if self.marked[w] == false then self:dfs(G, w) end end end function ConnectedComponents:component(v) return self.id[v] end return ConnectedComponents
---@class FrameworkMessageType EsoAddonFramework_Framework_MessageType = { ---Sent from framework the first time a player is activated after login or ui reload. InitialActivation = 1, ---Sent from framework to request controls that should be shown on the settings page. SettingsControlsRequest = 2, ---Send to framework to show settings page. ShowSettings = 3, ---Sent from framework when settings page is shown. SettingsShown = 4 }
-- important fields for Analyzer class require "lpeg" extensions = {"lua"} language = "Lua" full_grammar = "lua_grammar" other_grammars = {block = "lua_grammar"} paired = {"{", "}", "(", ")"} selectable = {"block", "chunk", "stat", "laststat", "function_name", "namelist", "varlist", "function_call", "expression", "unknown", } multi_text = {"line_comment", "multiline_comment"} floating = {"line_comment", "multiline_comment"} -- does language support multiline comments? multiline_support = "false" -- start & end tokens for comments; if language does not support multiline comments, define custom tokens line_tokens = {"--", ""} multiline_tokens = {"--[*[", "]*]"} local lpeg = require "lpeg"; local locale = lpeg.locale(); local P, S, V = lpeg.P, lpeg.S, lpeg.V; local C, Cb, Cc, Cg, Cs, Cmt, Ct = lpeg.C, lpeg.Cb, lpeg.Cc, lpeg.Cg, lpeg.Cs, lpeg.Cmt, lpeg.Ct; local shebang = P "#" * (P(1) - P "\n")^0 * P "\n"; local function K (k) -- keyword return Ct( Cc("keyword") * T(k)) * -(locale.alnum + P "_"); end function N(arg) -- nonterminal return Ct( Cc(arg) * V(arg) ) end function T(arg) -- terminal return Ct(C(arg)) end -- *** GRAMMAR **** local grammar = {"S", -- dummy symbol -- ENTRY POINTS lua_block = Ct(Cc("lua_program") * (shebang)^-1 * V "space" * N "chunk"^-1 * V "space" * N'unknown'^0 * -1); -- keywords keywords = K "and" + K "break" + K "do" + K "else" + K "elseif" + K "end" + K "false" + K "for" + K "function" + K "if" + K "in" + K "local" + K "nil" + K "not" + K "or" + K "repeat" + K "return" + K "then" + K "true" + K "until" + K "while"; -- longstrings -- longstring = P{ -- from Roberto Ierusalimschy's lpeg examples -- V "open" * C((P(1) - V "closeeq")^0) * -- V "close" / function (o, s) return s end; -- open = "[" * Cg((P "=")^0, "init") * P "[" * (P "\n")^-1; -- close = "]" * C((P "=")^0) * "]"; -- closeeq = Cmt(V "close" * Cb "init", function (s, i, a, b) return a == b end) -- }; longstring = T"[[" * (Cc(" ") * N"nl")^0 * N"longline"^0* T"]]"; longline = T((1-P"]]"-P"\n")^1) * N"nl"^0; -- comments & whitewhite space = (N'whites' + N'multiline_comment' + N'line_comment' + N'nl'^1)^0; line_comment = T "--" * V "longstring" + T(P"--" * (1 -S"\r\n")^0) * N'nl' ; multiline_comment = T(P"--[*[" * (1 - P"]*]")^0 * P"]*]"), whites = T((locale.space - S"\n\r")^1); nl = T(P"\r"^-1 * P"\n"); unknown = T((1 - S"\n\r")^1)* N'nl'^0, -- anything divided to lines -- unknown_word = N'whites'^-1 * T((1 - S" \t\r\n")^1), -- Types and Comments identifier = T((locale.alpha + P "_") * (locale.alnum + P "_")^0 - N "keywords"); number_constant = T((P "-")^-1 * V "space" * P "0x" * locale.xdigit^1 * -(locale.alnum + P "_") + (P "-")^-1 * V "space" * locale.digit^1 * (P "." * locale.digit^1)^-1 * (S "eE" * (P "-")^-1 * locale.digit^1)^-1 * -(locale.alnum + P "_") + (P "-")^-1 * V "space" * P "." * locale.digit^1 * (S "eE" * (P "-")^-1 * locale.digit^1)^-1 * -(locale.alnum + P "_")); string_constant = T( "\"" * (P "\\" * P(1) + (1 - P "\""))^0 * P "\"" + P "'" * (P "\\" * P(1) + (1 - P "'"))^0 * P "'"); -- Lua Complete Syntax chunk = (V "space" * N "laststat" * (V "space" * T ";")^-1) + -- laststat only (V "space" * N "stat" * (V "space" * T ";")^-1)^1 * -- stats (V "space" * N "laststat" * (V "space" * T ";")^-1)^-1; block = V"chunk"; stat = K "do" * V "space" * N "block" * V "space" * K "end" + K "while" * V "space" * N "expression" * V "space" * K "do" * V "space" * N "block" * V "space" * K "end" + K "repeat" * V "space" * N "block" * V "space" * K "until" * V "space" * N "expression" + K "if" * V "space" * N "expression" * V "space" * K "then" * V "space" * N "block" * V "space" * (K "elseif" * V "space" * N "expression" * V "space" * K "then" * V "space" * N "block" * V "space" )^0 * (K "else" * V "space" * N "block" * V "space")^-1 * K "end" + K "for" * V "space" * N "identifier" * V "space" * T "=" * V "space" * N "expression" * V "space" * T "," * V "space" * N "expression" * (V "space" * T "," * V "space" * N "expression")^-1 * V "space" * K "do" * V "space" * N "block" * V "space" * K "end" + K "for" * V "space" * N "namelist" * V "space" * K "in" * V "space" * N "explist" * V "space" * K "do" * V "space" * N "block" * V "space" * K "end" + K "function" * V "space" * N "function_name" * V "space" * V "function_body" + K "local" * V "space" * K "function" * V "space" * N "identifier" * V "space" * V "function_body" + K "local" * V "space" * N "namelist" * (V "space" * T "=" * V "space" * N "explist")^-1 + N "varlist" * V "space" * T "=" * V "space" * N "explist" + N "function_call"; laststat = K "return" * (V "space" * N "explist")^-1 + K "break"; function_name = N "identifier" * (V "space" * T "." * V "space" * N "identifier")^0 * (V "space" * T ":" * V "space" * N "identifier")^-1; namelist = N "identifier" * (V "space" * T "," * V "space" * N "identifier")^0; varlist = N "var" * (V "space" * T "," * V "space" * N "var")^0; -- Let's come up with a syntax that does not use left recursion -- (only listing changes to Lua 5.1 extended BNF syntax) -- value ::= nil | false | true | number_constant | string_constant | '...' | function | -- table_constructor | function_call | var | '(' expression ')' -- expression ::= unop expression | value [binop expression] -- prefix ::= '(' expression ')' | identifier -- index ::= '[' expression ']' | '.' identifier -- call ::= args | ':' identifier args -- suffix ::= call | index -- var ::= prefix {suffix} index | identifier -- function_call ::= prefix {suffix} call -- Something that represents a value (or many values) value = K "nil" + K "false" + K "true" + N "number_constant" + N "string_constant" + N "longstring" + T "..." + N "function" + N "table_constructor" + N "function_call" + N "var" + T "(" * V "space" * N "expression" * V "space" * T ")"; -- An expression operates on values to produce a new value or is a value expression = N "unop" * V "space" * N "expression" + N "value" * (V "space" * N "binop" * V "space" * N "expression")^-1; -- Index and Call index = T "[" * V "space" * N "expression" * V "space" * T "]" + T "." * V "space" * N "identifier"; call = N "args" + T ":" * V "space" * N "identifier" * V "space" * N "args"; -- A Prefix is a the leftmost side of a var(iable) or function_call prefix = T "(" * V "space" * N "expression" * V "space" * T ")" + N "identifier"; -- A Suffix is a Call or Index suffix = N "call" + N "index"; var = N "prefix" * (V "space" * N "suffix" * #(V "space" * N "suffix"))^0 * V "space" * N "index" + N "identifier"; function_call = N "prefix" * (V "space" * N "suffix" * #(V "space" * N "suffix"))^0 * V "space" * N "call"; explist = N "expression" * (V "space" * T "," * V "space" * N "expression")^0; args = T "(" * V "space" * (N "explist" * V "space")^-1 * T ")" + N "table_constructor" + N "string_constant"; ["function"] = K "function" * V "space" * V"function_body"; function_body = T "(" * V "space" * (N "parlist" * V "space")^-1 * T ")" * V "space" * N "block" * V "space" * K "end"; parlist = N "namelist" * (V "space" * T "," * V "space" * T "...")^-1 + T "..."; table_constructor = T "{" * V "space" * (N "field_list" * V "space")^-1 * T "}"; field_list = N "field" * (V "space" * N "fieldsep" * V "space" * N "field")^0 * (V "space" * N "fieldsep")^-1; field = T "[" * V "space" * N "expression" * V "space" * T "]" * V "space" * T "=" * V "space" * N "expression" + N "identifier" * V "space" * T "=" * V "space" * N "expression" + N "expression"; fieldsep = T "," + T ";"; binop = K "and" + -- match longest token sequences first K "or" + T ".." + T "<=" + T ">=" + T "==" + T "~=" + T "+" + T "-" + T "*" + T "/" + T "^" + T "%" + T "<" + T ">"; unop = T "-" + T "#" + K "not"; }; -- *** END OF GRAMMAR **** -- *** POSSIBLE GRAMMARS (ENTRY POINTS) **** grammar[1] = "lua_block" lua_grammar = P(grammar) --******************************************************************* -- TESTING - this script cannot be used by Analyzer.cpp when these lines are uncommented !!! -- dofile('default_grammar.lua') -- test("snippets.lua", lua_grammar)
local cjson = require "cjson" local helpers = require "spec.helpers" for _, strategy in helpers.each_strategy() do describe("URI encoding [#" .. strategy .. "]", function() local proxy_client setup(function() local bp = helpers.get_db_utils(strategy) bp.routes:insert { hosts = { "mock_upstream" }, } bp.routes:insert { hosts = { "mock_upstream" }, } bp.routes:insert { protocols = { "http" }, paths = { "/request" }, strip_path = false, } bp.routes:insert { protocols = { "http" }, paths = { "/stripped-path" }, strip_path = true, } assert(helpers.start_kong({ database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", })) proxy_client = helpers.proxy_client() end) teardown(function() helpers.stop_kong() end) it("issue #1975 does not double percent-encode proxied args", function() -- https://github.com/Kong/kong/pull/1975 local res = assert(proxy_client:send { method = "GET", path = "/get?limit=25&where=%7B%22or%22:%5B%7B%22name%22:%7B%22like%22:%22%25bac%25%22%7D%7D%5D%7D", headers = { ["Host"] = "mock_upstream", }, }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal("25", json.uri_args.limit) assert.equal([[{"or":[{"name":{"like":"%bac%"}}]}]], json.uri_args.where) end) it("issue #1480 does not percent-encode args unecessarily", function() -- behavior might not be correct, but we assert it anyways until -- a change is planned and documented. -- https://github.com/Mashape/kong/issues/1480 local res = assert(proxy_client:send { method = "GET", path = "/request?param=1.2.3", headers = { ["Host"] = "mock_upstream", }, }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal(helpers.mock_upstream_url .. "/request?param=1.2.3", json.url) end) it("issue #749 does not decode percent-encoded args", function() -- https://github.com/Mashape/kong/issues/749 local res = assert(proxy_client:send { method = "GET", path = "/request?param=abc%7Cdef", headers = { ["Host"] = "mock_upstream", }, }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal(helpers.mock_upstream_url .. "/request?param=abc%7Cdef", json.url) end) it("issue #688 does not percent-decode proxied URLs", function() -- https://github.com/Mashape/kong/issues/688 local res = assert(proxy_client:send { method = "GET", path = "/request/foo%2Fbar", headers = { ["Host"] = "mock_upstream", }, }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal(helpers.mock_upstream_url .. "/request/foo%2Fbar", json.url) end) it("issue #2512 does not double percent-encode upstream URLs", function() -- https://github.com/Mashape/kong/issues/2512 -- with `hosts` matching local res = assert(proxy_client:send { method = "GET", path = "/request/auth%7C123", headers = { ["Host"] = "mock_upstream", }, }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.matches("/request/auth%7C123", json.url, nil, true) -- with `uris` matching local res2 = assert(proxy_client:send { method = "GET", path = "/request/auth%7C123", }) local body2 = assert.res_status(200, res2) local json2 = cjson.decode(body2) assert.matches("/request/auth%7C123", json2.url, nil, true) -- with `uris` matching + `strip_uri` local res3 = assert(proxy_client:send { method = "GET", path = "/stripped-path/request/auth%7C123", }) local body3 = assert.res_status(200, res3) local json3 = cjson.decode(body3) assert.matches("/request/auth%7C123", json3.url, nil, true) end) end) end
-- This file is generated with ListStrings.ps1 local L = LibStub("AceLocale-3.0"):NewLocale("XKeyBinding", "ruRU") if not L then return end ---------- Total: 46 ---------- L["Command #"] = "Команда №" L["Invoked Macro by name: "] = "Вызван макрос с именем " L["Invoked Macro sequence "] = "Вызван код макроса " L["CVar not found or inaccessible: "] = "Переменная не найдена или недоступна" L["CVar |c20ff20ff%s|r was set to "] = "Переменная |c20ff20ff%s|r теперь " L["|cff00ff00On|r"] = "|cff00ff00Вкл.|r" L["|cffff1010Off|r"] = "|cffff1010Выкл.|r" L["Error while parsing code:\n"] = "Ошибка разбора:\n" L["Error while running code:\n"] = "Ошибка выполнения:\n" L["Lua code: "] = "Код Lua: " L["Lua code executed"] = "Код Lua выполнен" L[" (empty) "] = " (пусто) " L["(no name)"] = "(без имени)" L["Type"] = "Тип" L["Command type"] = "Тип команды" L["Name"] = "Имя" L["Command name"] = "Имя команды" L["On-screen notification"] = "Уведомление на экране" L["Show on-screen notification when command is invoked"] = "Отображать уведомление на экране при запуске команды" L["Chat notification"] = "Уведомление в чате" L["Show chat notification when command is invoked"] = "Отображать уведомление в чате при запуске команды" L["Command Text"] = "Текст команды" L["(not assigned)"] = "(не назначено)" L["Command Description"] = "Описание" L["Author"] = "Автор" L["Version"] = "Версия" L["Date"] = "Дата" L["Command List"] = "Список команд" L["Show numbers"] = "Отображать номера" L["Show numbers in command list"] = "Отображать порядковые номера команд в списке" L["Show icons"] = "Отображать значки" L["Show icons in command list"] = "Отображать значки типа команды в списке" L["Clear"] = "Очистить" L["Clear unused command entries"] = "Очистить неиспользуемые команды" L["Commands"] = "Команды" L["Profiles"] = "Профили" L["DISABLED.TYPENAME"] = "Отключена" L["DISABLED.TYPEZHELP"] = "|cffff0000Команда отключена|r" L["MACRO_NAME.TYPENAME"] = "Имя макроса" L["MACRO_NAME.TYPEZHELP"] = "|cffffff00Запуск макроса по имени|r\n\nВведите имя макроса в поле Имя команды" L["MACRO_TEXT.TYPENAME"] = "Текст макроса" L["MACRO_TEXT.TYPEZHELP"] = "|cffffff00Запуск макроса по содержимому|r\n\nВведите текст макроса в поле Имя команды" L["CVAR_TOGGLE.TYPENAME"] = "Переключение CVar" L["CVAR_TOGGLE.TYPEZHELP"] = "|cffffff00Переключает значение консольной переменной по очереди в одно из двух заданных зачений|r\n\nВведите название переменной, первое и второе значения в отдельные строки поля Текст команды" L["LUA_CODE.TYPENAME"] = "Код Lua" L["LUA_CODE.TYPEZHELP"] = "|cffff8000Выполняет код Lua|r\n\nВведите код в поле Текст команды"
if not modules then modules = { } end modules ['lpdf-mis'] = { version = 1.001, comment = "companion to lpdf-ini.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } -- Although we moved most pdf handling to the lua end, we didn't change -- the overall approach. For instance we share all resources i.e. we -- don't make subsets for each xform or page. The current approach is -- quite efficient. A big difference between MkII and MkIV is that we -- now use forward references. In this respect the MkII code shows that -- it evolved over a long period, when backends didn't provide forward -- referencing and references had to be tracked in multiple passes. Of -- course there are a couple of more changes. local next, tostring = next, tostring local format, gsub, formatters = string.format, string.gsub, string.formatters local texset, texget = tex.set, tex.get local backends, lpdf, nodes = backends, lpdf, nodes local nodeinjections = backends.pdf.nodeinjections local codeinjections = backends.pdf.codeinjections local registrations = backends.pdf.registrations local copy_node = node.copy local nodepool = nodes.pool local pdfliteral = nodepool.pdfliteral local register = nodepool.register local pdfdictionary = lpdf.dictionary local pdfarray = lpdf.array local pdfconstant = lpdf.constant local pdfreference = lpdf.reference local pdfunicode = lpdf.unicode local pdfverbose = lpdf.verbose local pdfstring = lpdf.string local pdfflushobject = lpdf.flushobject local pdfflushstreamobject = lpdf.flushstreamobject local pdfaction = lpdf.action local formattedtimestamp = lpdf.pdftimestamp local adddocumentextgstate = lpdf.adddocumentextgstate local addtocatalog = lpdf.addtocatalog local addtoinfo = lpdf.addtoinfo local addtopageattributes = lpdf.addtopageattributes local addtonames = lpdf.addtonames local variables = interfaces.variables local v_stop = variables.stop local positive = register(pdfliteral("/GSpositive gs")) local negative = register(pdfliteral("/GSnegative gs")) local overprint = register(pdfliteral("/GSoverprint gs")) local knockout = register(pdfliteral("/GSknockout gs")) local function initializenegative() local a = pdfarray { 0, 1 } local g = pdfconstant("ExtGState") local d = pdfdictionary { FunctionType = 4, Range = a, Domain = a, } local negative = pdfdictionary { Type = g, TR = pdfreference(pdfflushstreamobject("{ 1 exch sub }",d)) } local positive = pdfdictionary { Type = g, TR = pdfconstant("Identity") } adddocumentextgstate("GSnegative", pdfreference(pdfflushobject(negative))) adddocumentextgstate("GSpositive", pdfreference(pdfflushobject(positive))) initializenegative = nil end local function initializeoverprint() local g = pdfconstant("ExtGState") local knockout = pdfdictionary { Type = g, OP = false, OPM = 0 } local overprint = pdfdictionary { Type = g, OP = true, OPM = 1 } adddocumentextgstate("GSknockout", pdfreference(pdfflushobject(knockout))) adddocumentextgstate("GSoverprint", pdfreference(pdfflushobject(overprint))) initializeoverprint = nil end function nodeinjections.overprint() if initializeoverprint then initializeoverprint() end return copy_node(overprint) end function nodeinjections.knockout () if initializeoverprint then initializeoverprint() end return copy_node(knockout) end function nodeinjections.positive() if initializenegative then initializenegative() end return copy_node(positive) end function nodeinjections.negative() if initializenegative then initializenegative() end return copy_node(negative) end -- function codeinjections.addtransparencygroup() -- -- png: /CS /DeviceRGB /I true -- local d = pdfdictionary { -- S = pdfconstant("Transparency"), -- I = true, -- K = true, -- } -- lpdf.registerpagefinalizer(function() addtopageattributes("Group",d) end) -- hm -- end -- actions (todo: store and update when changed) local openpage, closepage, opendocument, closedocument function codeinjections.registerdocumentopenaction(open) opendocument = open end function codeinjections.registerdocumentcloseaction(close) closedocument = close end function codeinjections.registerpageopenaction(open) openpage = open end function codeinjections.registerpagecloseaction(close) closepage = close end local function flushdocumentactions() if opendocument then addtocatalog("OpenAction",pdfaction(opendocument)) end if closedocument then addtocatalog("CloseAction",pdfaction(closedocument)) end end local function flushpageactions() if openpage or closepage then local d = pdfdictionary() if openpage then d.O = pdfaction(openpage) end if closepage then d.C = pdfaction(closepage) end addtopageattributes("AA",d) end end lpdf.registerpagefinalizer (flushpageactions, "page actions") lpdf.registerdocumentfinalizer(flushdocumentactions,"document actions") --- info : this can change and move elsewhere local identity = { } function codeinjections.setupidentity(specification) for k, v in next, specification do if v ~= "" then identity[k] = v end end end local done = false -- using "setupidentity = function() end" fails as the meaning is frozen in register local function setupidentity() if not done then local title = identity.title if not title or title == "" then title = tex.jobname end addtoinfo("Title", pdfunicode(title), title) local subtitle = identity.subtitle or "" if subtitle ~= "" then addtoinfo("Subject", pdfunicode(subtitle), subtitle) end local author = identity.author or "" if author ~= "" then addtoinfo("Author", pdfunicode(author), author) -- '/Author' in /Info, 'Creator' in XMP end local creator = identity.creator or "" if creator ~= "" then addtoinfo("Creator", pdfunicode(creator), creator) -- '/Creator' in /Info, 'CreatorTool' in XMP end local currenttimestamp = lpdf.timestamp() addtoinfo("CreationDate", pdfstring(formattedtimestamp(currenttimestamp))) local date = identity.date or "" local pdfdate = formattedtimestamp(date) if pdfdate then addtoinfo("ModDate", pdfstring(pdfdate), date) else -- users should enter the date in 2010-01-19T23:27:50+01:00 format -- and if not provided that way we use the creation time instead addtoinfo("ModDate", pdfstring(formattedtimestamp(currenttimestamp)), currenttimestamp) end local keywords = identity.keywords or "" if keywords ~= "" then keywords = gsub(keywords, "[%s,]+", " ") addtoinfo("Keywords",pdfunicode(keywords), keywords) end local id = lpdf.id() addtoinfo("ID", pdfstring(id), id) -- needed for pdf/x -- addtoinfo("ConTeXt.Version", environment.version) addtoinfo("ConTeXt.Time", os.date("%Y-%m-%d %H:%M")) addtoinfo("ConTeXt.Jobname", environment.jobname or tex.jobname) addtoinfo("ConTeXt.Url", "www.pragma-ade.com") addtoinfo("ConTeXt.Support", "contextgarden.net") -- done = true else -- no need for a message end end lpdf.registerpagefinalizer(setupidentity,"identity") -- or when we want to be able to set things after pag e1: -- -- lpdf.registerdocumentfinalizer(setupidentity,1,"identity") local function flushjavascripts() local t = interactions.javascripts.flushpreambles() if #t > 0 then local a = pdfarray() local pdf_javascript = pdfconstant("JavaScript") for i=1,#t do local name, script = t[i][1], t[i][2] local j = pdfdictionary { S = pdf_javascript, JS = pdfreference(pdfflushstreamobject(script)), } a[#a+1] = pdfstring(name) a[#a+1] = pdfreference(pdfflushobject(j)) end addtonames("JavaScript",pdfreference(pdfflushobject(pdfdictionary{ Names = a }))) end end lpdf.registerdocumentfinalizer(flushjavascripts,"javascripts") -- -- -- local pagespecs = { [variables.max] = { mode = "FullScreen", layout = false, fit = false, fixed = false, duplex = false }, [variables.bookmark] = { mode = "UseOutlines", layout = false, fit = false, fixed = false, duplex = false }, [variables.fit] = { mode = "UseNone", layout = false, fit = true, fixed = false, duplex = false }, [variables.doublesided] = { mode = "UseNone", layout = "TwoColumnRight", fit = true, fixed = false, duplex = false }, [variables.singlesided] = { mode = "UseNone", layout = false, fit = false, fixed = false, duplex = false }, [variables.default] = { mode = "UseNone", layout = "auto", fit = false, fixed = false, duplex = false }, [variables.auto] = { mode = "UseNone", layout = "auto", fit = false, fixed = false, duplex = false }, [variables.none] = { mode = false, layout = false, fit = false, fixed = false, duplex = false }, -- new [variables.fixed] = { mode = "UseNone", layout = "auto", fit = false, fixed = true, duplex = false }, -- noscale [variables.landscape] = { mode = "UseNone", layout = "auto", fit = false, fixed = true, duplex = "DuplexFlipShortEdge" }, [variables.portrait] = { mode = "UseNone", layout = "auto", fit = false, fixed = true, duplex = "DuplexFlipLongEdge" }, [variables.page] = { mode = "UseNone", layout = "auto", fit = false, fixed = true, duplex = "Simplex" }, } local pagespec, topoffset, leftoffset, height, width, doublesided = "default", 0, 0, 0, 0, false local cropoffset, bleedoffset, trimoffset, artoffset = 0, 0, 0, 0 function codeinjections.setupcanvas(specification) local paperheight = specification.paperheight local paperwidth = specification.paperwidth local paperdouble = specification.doublesided if paperheight then texset('global','pageheight',paperheight) end if paperwidth then texset('global','pagewidth',paperwidth) end pagespec = specification.mode or pagespec topoffset = specification.topoffset or 0 leftoffset = specification.leftoffset or 0 height = specification.height or texget("pageheight") width = specification.width or texget("pagewidth") -- cropoffset = specification.cropoffset or 0 trimoffset = cropoffset - (specification.trimoffset or 0) bleedoffset = trimoffset - (specification.bleedoffset or 0) artoffset = bleedoffset - (specification.artoffset or 0) -- if paperdouble ~= nil then doublesided = paperdouble end end local function documentspecification() if not pagespec or pagespec == "" then pagespec = variables.default end -- local settings = utilities.parsers.settings_to_array(pagespec) -- local spec = pagespecs[variables.default] -- for i=1,#settings do -- local s = pagespecs[settings[i]] -- if s then -- for k, v in next, s do -- spec[k] = v -- end -- end -- end local spec = pagespecs[pagespec] or pagespecs[variables.default] if spec.layout == "auto" then if doublesided then local s = pagespecs[variables.doublesided] -- to be checked voor interfaces for k, v in next, s do spec[k] = v end else spec.layout = false end end local layout = spec.layout local mode = spec.mode local fit = spec.fit local fixed = spec.fixed local duplex = spec.duplex if layout then addtocatalog("PageLayout",pdfconstant(layout)) end if mode then addtocatalog("PageMode",pdfconstant(mode)) end if fit or fixed or duplex then addtocatalog("ViewerPreferences",pdfdictionary { FitWindow = fit and true or nil, PrintScaling = fixed and pdfconstant("None") or nil, Duplex = duplex and pdfconstant(duplex) or nil, }) end addtoinfo ("Trapped", pdfconstant("False")) -- '/Trapped' in /Info, 'Trapped' in XMP addtocatalog("Version", pdfconstant(format("1.%s",pdf.getminorversion()))) end -- temp hack: the mediabox is not under our control and has a precision of 4 digits local factor = number.dimenfactors.bp local f_value = formatters["%0.4F"] local function boxvalue(n) -- we could share them return pdfverbose(f_value(factor * n)) end local function pagespecification() local llx = leftoffset local lly = texget("pageheight") + topoffset - height local urx = width - leftoffset local ury = texget("pageheight") - topoffset -- boxes can be cached local function extrabox(WhatBox,offset,always) if offset ~= 0 or always then addtopageattributes(WhatBox, pdfarray { boxvalue(llx + offset), boxvalue(lly + offset), boxvalue(urx - offset), boxvalue(ury - offset), }) end end extrabox("CropBox",cropoffset,true) -- mandate for rendering extrabox("TrimBox",trimoffset,true) -- mandate for pdf/x extrabox("BleedBox",bleedoffset) -- optional -- extrabox("ArtBox",artoffset) -- optional .. unclear what this is meant to do end lpdf.registerpagefinalizer(pagespecification,"page specification") lpdf.registerdocumentfinalizer(documentspecification,"document specification") -- Page Label support ... -- -- In principle we can also support /P (prefix) as we can just use the verbose form -- and we can then forget about the /St (start) as we don't care about those few -- extra bytes due to lack of collapsing. Anyhow, for that we need a stupid prefix -- variant and that's not on the agenda now. local map = { numbers = "D", Romannumerals = "R", romannumerals = "r", Characters = "A", characters = "a", } -- local function featurecreep() -- local pages, lastconversion, list = structures.pages.tobesaved, nil, pdfarray() -- local getstructureset = structures.sets.get -- for i=1,#pages do -- local p = pages[i] -- if not p then -- return -- fatal error -- else -- local numberdata = p.numberdata -- if numberdata then -- local conversionset = numberdata.conversionset -- if conversionset then -- local conversion = getstructureset("structure:conversions",p.block,conversionset,1,"numbers") -- if conversion ~= lastconversion then -- lastconversion = conversion -- list[#list+1] = i - 1 -- pdf starts numbering at 0 -- list[#list+1] = pdfdictionary { S = pdfconstant(map[conversion] or map.numbers) } -- end -- end -- end -- if not lastconversion then -- lastconversion = "numbers" -- list[#list+1] = i - 1 -- pdf starts numbering at 0 -- list[#list+1] = pdfdictionary { S = pdfconstant(map.numbers) } -- end -- end -- end -- addtocatalog("PageLabels", pdfdictionary { Nums = list }) -- end local function featurecreep() local pages = structures.pages.tobesaved local list = pdfarray() local getset = structures.sets.get local stopped = false local oldlabel = nil local olconversion = nil for i=1,#pages do local p = pages[i] if not p then return -- fatal error end local label = p.viewerprefix or "" if p.status == v_stop then if not stopped then list[#list+1] = i - 1 -- pdf starts numbering at 0 list[#list+1] = pdfdictionary { P = pdfunicode(label), } stopped = true end oldlabel = nil oldconversion = nil stopped = false else local numberdata = p.numberdata local conversion = nil local number = p.number if numberdata then local conversionset = numberdata.conversionset if conversionset then conversion = getset("structure:conversions",p.block,conversionset,1,"numbers") end end conversion = conversion and map[conversion] or map.numbers if number == 1 or oldlabel ~= label or oldconversion ~= conversion then list[#list+1] = i - 1 -- pdf starts numbering at 0 list[#list+1] = pdfdictionary { S = pdfconstant(conversion), St = number, P = label ~= "" and pdfunicode(label) or nil, } end oldlabel = label oldconversion = conversion stopped = false end end addtocatalog("PageLabels", pdfdictionary { Nums = list }) end lpdf.registerdocumentfinalizer(featurecreep,"featurecreep")
splash:go(args.url) splash:wait(1.0) result = {} result.lowest_price = 10000 result.bag_weight = "20kg" result.bag_price = "20" result.html = splash:html()
--local _button = "Small" local id_number = 0 local debug = false local names = { "Kyle", "Preston", "Pedro", "Jean", "Willis", "Eric", "Alan", "Jeremiah", "Troy", "Warner", "Guadalupe", "Emanuel", "Parker", "Willie", "Mauricio", "Tommie", "Buck", "Marlon", "Deshawn", "Fritz", "Sam", "Chung", "Chungus", "Jim", "Whitney", "Barton", "Alec", "Antione", "Micah", "Rhett", "Clint", "Raphael", "Sammy", "Dale", "Pat", "Lazarus", "Milton", "Vaughn", "Walton", "Lorenzo", "Robby", "Stanley", "Marvin", "Arnold", "Chester", "Wilmer", "Zane", "Cornelius", "Ivan", "Javier", "Jesse", "Rhea", "Karla", "Maybelle", "Salley", "Temple", "Ronna", "Lilli", "Stella", "Lorine", "Denna", "Bernice", "Lorina", "Rhona", "Kasie", "Earline", "Felisha", "Jeni", "Stormy", "Akiko", "Beverlee", "Chia", "Ethelene", "Lakisha", "Hsiu", "Dawna", "Demetra", "Junita", "June", "Lyndia", "Otelia", "Joanie", "Jenell", "Johana", "Corina", "Hannelore", "Deandra", "Florida", "Matilde", "Maragret", "Luana", "Neva", "Rachal", "Rona", "Shirl", "Maudie", "Rosalyn", "Rosaura", "Jesusita", "Adela", "Lashon" } local _side = "enemy" local _states = { ["player"] = {color = {0, 0, 0.545098}, state = 1}, ["enemy"] = {color = {0.517647, 0, 0.098039}, state = 2}, ["ally"] = {color = {0.039216, 0.368627, 0.211765}, state = 3}, ["neutral"] = {color = {0.764706, 0.560784, 0}, state = 4} } local _initiative_pos = {117.97, 4, -29.30} --local _initiative_pos = {45.06, 3, -18.70} local _initiative_bag = "de97c2" local _pawn_pos = {x = 121.44, y = 3.2, z = 27.69} --_pawn_pos = {x = 78.08, y = 3, z = 28.09} local _pawn_bag = "e1e28a" local _hand_pos = {141.53, 17.80, -1.09} local _boss_bag = "627199" --local _tracker_pos = {x = 42.83, y = 1.5, z = -2.77} ----local _tracker_pos = {x = 42.83, y = 1.5, z = -2.77} --local _tracker_bag = "d2f618" --local _tracker_zone = "84f009" --local _bag_pos = {x = 17.50, y = 2.00, z = 6.12} local _processing = false local _global_calc = 0 local _objects = {} function onLoad() local inputs = { -- name { input_function = "none", function_owner = self, label = "Name", position = {6.2, 0.7, 7.6}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 2000, height = 350, font_size = 320, tab = 2, value = debug and "/" or "", tooltip = "Name (/ for random)" }, -- initiative { input_function = "none", function_owner = self, label = "INI", position = {3.4, 0.7, 7.6}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 800, height = 350, font_size = 320, tab = 2, validation = 1, value = debug and "5" or "", tooltip = "Initiative Mod" }, -- hp { input_function = "hp", function_owner = self, label = "HP", position = {1.5, 0.7, 7.6}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 1000, height = 350, font_size = 320, tab = 2, value = debug and "r25-182" or "", tooltip = "Hit Points (rLW-UP)" }, -- ac { input_function = "none", function_owner = self, label = "AC", position = {-0.4, 0.7, 7.6}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 800, height = 350, font_size = 320, tab = 2, validation = 2, value = debug and "15" or "", tooltip = "Armor Class" }, -- attack { input_function = "none", function_owner = self, label = "ATK", position = {-2.1, 0.7, 7.6}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 800, height = 350, font_size = 320, tab = 2, validation = 2, value = debug and "7" or "", tooltip = "Attack Bonus" }, -- damage die { input_function = "d_die", function_owner = self, label = "DIE", position = {-3.8, 0.7, 7.6}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 800, height = 350, font_size = 200, value = debug and "2d8" or "", tooltip = "Damage Die" }, -- movement { input_function = "none", function_owner = self, label = "Movement", position = {-6.3, 0.7, 7.6}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 1600, height = 350, font_size = 280, tooltip = "Movement speed", value = debug and "10ft" or "" }, -- number { input_function = "none", function_owner = self, label = "Number", position = {6.57, 0.7, 6.7}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 1600, height = 350, font_size = 320, tooltip = "Number to Create", alignment = 3, value = "1", validation = 2 } } local buttons = { --{ -- click_function = "switch_size", -- function_owner = self, -- label = _button, -- position = {-6.4, 0.7, 7.6}, -- rotation = {0, 180, 0}, -- scale = {0.9, 1.2, 0.9}, -- width = 1600, height = 450, -- font_size = 320 --}, { click_function = "create_npc", function_owner = self, label = "Create", position = {0.2, 0.7, 6.7}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 1600, height = 380, font_size = 320, color = {0.7961, 0.2732, 0.2732, 1} }, { click_function = "switch_sides", function_owner = self, label = "Enemy", position = {3.4, 0.7, 6.7}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 1600, height = 380, font_size = 320, color = {0.517647, 0, 0.098039, 1} }, { click_function = "create_note", function_owner = self, label = "Note", position = {-2.5, 0.7, 6.7}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 1100, height = 380, font_size = 320, color = {0.192, 0.701, 0.168, 1}, tooltip = "Right click for named." }, { click_function = "update_checkbox", function_owner = self, label = " ", position = {-4.1, 0.7, 6.7}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 380, height = 380, font_size = 320, color = {0.856, 0.1, 0.094, 1}, tooltip = "false" }, { click_function = "switch_size", function_owner = self, label = "Medium", position = {-6.3, 0.7, 6.7}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 1600, height = 380, font_size = 320, color = {0.976471, 0.427451, 0.003922, 1}, tooltip = "Size" } } for i = 1, #inputs do self.createInput(inputs[i]) end for i = 1, #buttons do self.createButton(buttons[i]) end if debug then self.createButton( { click_function = "printme", function_owner = self, label = "Kek", position = {-7, 0.7, 6.7}, rotation = {0, 180, 0}, scale = {0.9, 1.2, 0.9}, width = 1600, height = 380, font_size = 320, color = {0, 0, 0, 1}, font_color = {1, 1, 1, 1} } ) end self.UI.setAttribute("calculateAll", "onClick", self.getGUID() .. "/UI_CalculateAll") self.UI.setAttribute("destroyAll", "onClick", self.getGUID() .. "/UI_DestroyAll") self.UI.setAttribute("calculateAllText", "onEndEdit", self.getGUID() .. "/UI_UpdateInput(value)") end function none() end function hp() --should be able to do random end function d_die() -- validate dies end function setNumber(number) self.editInput({index = 7, value = number}) end function getName() local inputs = self.getInputs()[1] local returner = inputs.value if string.sub(returner, 1, 1) == "/" then if #returner > 1 then returner = string.sub(returner, 2) .. names[math.random(1, #names)] else returner = names[math.random(1, #names)] end end if debug then returner = returner .. id_number end return returner end function getINI() local ini = self.getInputs()[2].value if string.sub(ini, 1, 1) == "r" then ini = string.gsub(ini, "r", "") local range = mysplit(ini, "-") ini = math.random(range[1], range[2]) elseif string.sub(ini, 1, 1) == "a" then ini = string.gsub(ini, "a", "") + 3 end return ini end function getHP() local hp = self.getInputs()[3].value if string.sub(hp, 1, 1) == "r" then hp = string.gsub(hp, "r", "") local range = mysplit(hp, "-") hp = math.random(range[1], range[2]) end return hp end function getAC() local inputs = self.getInputs()[4] return inputs.value end function getATK() local inputs = self.getInputs()[5] return inputs.value end function getDMG() local inputs = self.getInputs()[6] return inputs.value end function getMovement() local inputs = self.getInputs()[7] return inputs.value end function getNumber() local inputs = self.getInputs()[8] return inputs.value end function getSize(getData) local buttons = self.getButtons()[5] if not getData then return buttons.label else if not getBossCheckbox() then local scale = {} scale["Small"] = 0.17 scale["Medium"] = 0.30 scale["Large"] = 0.55 scale["Huge"] = 0.90 scale["Gargantuan"] = 1.20 return scale[buttons.label] else local scale = {} scale["Small"] = 0.53 scale["Medium"] = 0.78 scale["Large"] = 1.45 scale["Huge"] = 2.40 scale["Gargantuan"] = 3.30 return scale[buttons.label] end end end function setName(params) self.editInput({index = 0, value = params.input}) end function setINI(params) self.editInput({index = 1, value = params.input}) end function setHP(params) self.editInput({index = 2, value = params.input}) end function setAC(params) self.editInput({index = 3, value = params.input}) end function setATK(params) self.editInput({index = 4, value = params.input}) end function setDMG(params) self.editInput({index = 5, value = params.input}) end function setMovement(params) self.editInput({index = 6, value = params.input}) end function setSize(params) self.editButton({index=4, label=params.input}) end function create_note(obj, color, alt_click) local card_pos = {107.95, 3.1, 18.37} local card_bag = getObjectFromGUID("15a6b7") if not card_bag then print("Where's the card bag?") return end if color == "Black" then local inputs = self.getInputs() local entityName = "" local data = {} for i = 1, #inputs do if inputs[i].label ~= "Number" then local val = "" if inputs[i].label == "Name" then entityName = inputs[i].value val = getBossCheckbox() and entityName or "/" else val = inputs[i].value end table.insert(data, val) if data[i] == "" then print("Error in data") return nil end end end table.insert(data, getSize()) -- create the note with the name as "/" local str = "" for i = 1, #data do if data[i] ~= data[#data] then str = str .. data[i] .. "|" else str = str .. data[i] end end if getBossCheckbox() then local desc = self.getDescription() if desc ~= "" then str = str .. "\n" .. desc end end takeParams = { position = card_pos, rotation = {0, 270, 0}, callback_function = function(spawned) local waiter = function() return spawned.resting end local waited = function() spawned.setName(entityName) spawned.setDescription(str) end Wait.condition(waited, waiter) end } card_bag.takeObject(takeParams) end end function switch_size(obj, player_clicker_color, alt_click) local sizes = {} sizes[1] = "Small" sizes[2] = "Medium" sizes[3] = "Large" sizes[4] = "Huge" sizes[5] = "Gargantuan" local currentSize = getSize() local c = 1 for i = 1, #sizes do if sizes[i] == currentSize then c = alt_click and i - 1 or i + 1 end end if c > #sizes then c = 1 elseif c <= 0 then c = #sizes end self.editButton( { index = 4, label = sizes[c] } ) end function create_npc(owner, color, alt_click) id_number = id_number + 1 local object = { id = id_number, name = getName(), initiative = getINI(), hp = getHP(), ac = getAC(), atk = getATK(), dmg = getDMG(), dice = nil, size = getSize(true), pawn = nil, ini_tracker = nil, movement = getMovement(), side = _side } object.maxhp = object.hp table.insert(_objects, object) local bagToUse = _pawn_bag if getBossCheckbox() == true then bagToUse = _boss_bag end _pawn_pos.z = 28.09 + math.random(-4.66, 4.66) takeParams = { position = _pawn_pos, rotation = {0, 0, 0}, callback_function = function(obj) if not getBossCheckbox() then take_pawn(obj, object.name, object.id, tonumber(getNumber()) > 1 and true) else take_boss(obj, object.name, object.id, tonumber(getNumber()) > 1 and true) end end } getObjectFromGUID(bagToUse).takeObject(takeParams) local waiter = function() return object.pawn ~= nil end local waited = function() takeParams = { position = _initiative_pos, rotation = {0.00, 90.00, 0.00}, callback_function = function(obj) take_initiative(obj, object.name, object.id) end } getObjectFromGUID(_initiative_bag).takeObject(takeParams) end Wait.condition(waited, waiter) --takeParams = { -- position = _tracker_pos, -- rotation = {0, 90, 0}, -- callback_function = function(obj) -- take_tracker(obj, object) -- end --} --getObjectFromGUID(_tracker_bag).takeObject(takeParams) local waiter = function() local i = object.ini_tracker ~= nil local p = object.pawn ~= nil return i and p end local waited = function() addToCommander(object) if tonumber(getNumber()) > 1 then _processing = true end checkLoop(id_number + 1) end Wait.condition(waited, waiter) --Wait.time( -- function() -- -- end, -- 1.5 --) end function getBossCheckbox() local btn = self.getButtons()[4] return btn.tooltip == "true" end function update_checkbox() --broadcastToColor("Disabled for now, sorry", "Black", {r = 1, g = 1, b = 1}) --if debug then local btn = self.getButtons()[4] --printTable(btn) local isBoss = btn.tooltip == "true" local color = { red = {0.856, 0.1, 0.094, 1}, green = {0.4418, 0.8101, 0.4248, 1} } if not isBoss then --print("it is boss") --btn.color = color.green --btn.tooltip = "true" self.editButton({index = 3, color = color.green}) self.editButton({index = 3, tooltip = "true"}) else --print("it is not boss") --btn.color = color.red --btn.tooltip = "false" self.editButton({index = 3, color = color.red}) self.editButton({index = 3, tooltip = "false"}) end --end end function toggleIsBoss(params) local btn = self.getButtons()[4] local color = { red = {0.856, 0.1, 0.094, 1}, green = {0.4418, 0.8101, 0.4248, 1} } if params.input then self.editButton({index = 3, color = color.green}) self.editButton({index = 3, tooltip = "true"}) else self.editButton({index = 3, color = color.red}) self.editButton({index = 3, tooltip = "false"}) end end function checkLoop(id) local number = tonumber(getNumber()) if number > 1 then number = number - 1 setNumber(number) create_npc() end if number == 1 and _processing then --print(id) if id then local waiter = function() local object = getObjectByID(id) --print(id) --printTable(object) if object then object = object.obj local i = object.ini_tracker ~= nil local p = object.pawn ~= nil return i and p else return false end end local waited = function() --print("waited") _processing = false for i = 0, 5 do self.editInput({index = i, value = ""}) end end Wait.condition(waited, waiter, 5) else Wait.time( function() _processing = false for i = 0, 5 do self.editInput({index = i, value = ""}) end end, 3 ) end end end function addToCommander(payload) -- <HorizontalLayout> -- <Text class="name" text="Zwerg"></Text> -- <Text text="+2"></Text> -- <Text class="hp">10 <textcolor color="#FFFFFF">|</textcolor>10</Text> -- <Text text="13"></Text> -- <Text text="+4"></Text> -- <Text text="2d6"></Text> -- <Button>-</Button> -- <Button id="omegalul" onClick="UI_ButtonClick(omegalul)">+</Button> -- <Button class="destroy">X</Button> if tonumber(payload.initiative) > 0 then payload.initiative = "+" .. payload.initiative end local xmlTable = self.UI.getXmlTable() if not xmlTable[4].children[1].children then xmlTable[4].children[1].children = {} end local toAdd = { tag = "HorizontalLayout", attributes = { id = payload.id, color = (payload.id % 2 ~= 0) and "#00000080" or "#00000000" }, children = { -- name { tag = "Text", attributes = { class = "name", text = payload.name, id = "name-" .. payload.id } }, -- initiative { tag = "Text", attributes = { text = payload.initiative, id = "initiative-" .. payload.id } }, -- hp { tag = "Text", attributes = { class = "hp", text = payload.hp .. " | " .. payload.maxhp, id = "hp-" .. payload.id } }, -- ac { tag = "Text", attributes = { text = payload.ac, id = "ac-" .. payload.id } }, -- dmg { tag = "Text", attributes = { text = payload.dmg, id = "dmg-" .. payload.id } }, -- atk { tag = "Text", attributes = { text = payload.atk, id = "atk-" .. payload.id } }, -- calculate { tag = "InputField", attributes = { id = "calcText-" .. payload.id, class = "calculate", onEndEdit = self.getGUID() .. "/UI_InputEdit(value)" } }, -- calculateButton { tag = "Button", attributes = { id = "calcButton-" .. payload.id, onClick = self.getGUID() .. "/UI_Calculate(" .. payload.id .. ")" }, value = "C" }, -- destroy { tag = "Button", attributes = { class = "destroy", id = "destroy-" .. payload.id, onClick = self.getGUID() .. "/UI_Destroy(" .. payload.id .. ")" }, value = "X" } } } table.insert(xmlTable[4].children[1].children, toAdd) updateTable(xmlTable) end function destroy(caller) local object = nil if caller.pawn then object = getObjectByPawn(caller.pawn) elseif caller.object then object = caller.object end if object then object.obj.ini_tracker.destruct() --object.obj.full_tracker.destruct() --printTable(self.UI.getValue(object.obj.id)) --table.remove(_objects, object.index) --printTable(self.UI.getXmlTable()) if not caller.skipUpdate then local xmlTable = self.UI.getXmlTable() local rows = xmlTable[4].children[1].children local i = 1 local done = false while (i <= #rows and not done) do local id = tonumber(rows[i].attributes.id) if id == object.obj.id then table.remove(xmlTable[4].children[1].children, i) done = true end i = i + 1 end updateTable(xmlTable) end table.remove(_objects, object.index) end end function take_boss(spawned, name, id, moveIt) local waiter = function() return spawned.resting end local waited = function() local object = getObjectByID(id).obj local image = self.getDescription() local gid = spawned.getGUID() --spawned.editInput({index = 0, value = name}) spawned.call("_starter", {image = image}) Wait.time( function() spawned = getObjectFromGUID(gid) spawned.call( "_init", { master = self, obj = object } ) object.pawn = spawned spawned.editInput({index = 0, value = name}) spawned.use_hands = true --spawned.deal(1, "Black", 7) spawned.setPositionSmooth(_hand_pos, false, false) spawned.setRotationSmooth({0, 270, 0}, false, true) end, 0.5 ) --object.pawn = spawned --print("-----") --print(spawned.getGUID()) --local desc = self.getDescription() --spawned.setCustomObject( -- { -- image = desc, -- image_secondary = desc -- } --) --broadcastToColor("Remember to reimport the image now.", "Black", {r = 1, g = 1, b = 1}) if debug then object.pawn__id = spawned.getGUID() end end Wait.condition(waited, waiter) end function take_pawn(spawned, name, id, moveIt) local waiter = function() return spawned.resting end local waited = function() local object = getObjectByID(id).obj spawned.editInput({index = 0, value = name}) spawned.call( "_init", { master = self, obj = object } ) --attributeTable = { -- value = "kek" -- fontSize = 300, -- color = "#000000" --} --spawned.UI.setAttribute("exampleText", attributeTable) --spawned.setPositionSmooth(_bag_pos, false, false) spawned.use_hands = true spawned.setPositionSmooth(_hand_pos, false, false) spawned.setRotationSmooth({0, 270, 0}, false, true) --spawned.deal(1, "Black", 7) object.pawn = spawned if debug then object.pawn__id = spawned.getGUID() end end Wait.condition(waited, waiter) end function take_initiative(spawned, name, id) --PrintTable(spawned.getStates()) local initiative = nil --initiative = spawned.call("setSide", {side = _side}) local waiter = function() return spawned.resting end local waited = function() if not initiative then initiative = spawned end local i = getInitiative() initiative.call( "_init", {input = {name = name, i = i, pawn = getObjectByID(id).obj.pawn.getGUID(), side = _side}} ) --initiative.editInput({index = 0, value = name .. "\n" .. i.value}) --initiative.setDescription(i.value .. "\n" .. i.initiative .. "+" .. i.modifier) --if _side == "enemy" then -- initiative.call("setToken", {input = getObjectByID(id).obj.pawn.getGUID()}) --end getObjectByID(id).obj.ini_tracker = initiative if debug then getObjectByID(id).obj.ini_tracker__id = initiative.getGUID() end end Wait.condition(waited, waiter) end function take_tracker(spawned, object) local waiter = function() return spawned.resting end local waited = function() Wait.time( function() spawned.call("setName", {input = object.name}) spawned.call("setHP", {input = object.hp}) spawned.call("setAC", {input = object.ac}) spawned.call("setATK", {input = object.atk}) spawned.call("setDMG", {input = object.dmg}) spawned.call("setColor", {input = object.pawn.getColorTint()}) spawned.call("order", {input = _tracker_zone}) object.full_tracker = spawned if debug then object.full_tracker__id = spawned.getGUID() end end, 2 ) end Wait.condition(waited, waiter) end function switch_sides() if _side == "enemy" then _side = "ally" elseif _side == "ally" then _side = "neutral" elseif _side == "neutral" then _side = "enemy" end self.editButton({index = 1, color = _states[_side].color}) self.editButton({index = 1, label = _side:gsub("^%l", string.upper)}) end function refreshHP(params) --local obj = getObjectByID(params.id).obj --obj.full_tracker.call("setHP", {input = params.input}) end function getInitiative() local modifier = tonumber(getINI()) local initiative = math.random(1, 20) local v = initiative + modifier if v <= 0 then v = 1 end return {value = v, initiative = initiative, modifier = modifier} end function getObjectByID(id) for i = 1, #_objects do if _objects[i].id == tonumber(id) then return {obj = _objects[i], index = i} end end if debug then print("found no object with id " .. id) end return nil end function getObjectByPawn(pawn) for i = 1, #_objects do if _objects[i].pawn == pawn then return {obj = _objects[i], index = i} end end return nil end function printme() printTable(_objects) end function printTable(t) local printTable_cache = {} local function sub_printTable(t, indent) if (printTable_cache[tostring(t)]) then print(indent .. "*" .. tostring(t)) else printTable_cache[tostring(t)] = true if (type(t) == "table") then for pos, val in pairs(t) do if (type(val) == "table") then print(indent .. "[" .. pos .. "] => " .. tostring(t) .. " {") sub_printTable(val, indent .. string.rep(" ", string.len(pos) + 8)) print(indent .. string.rep(" ", string.len(pos) + 6) .. "}") elseif (type(val) == "string") then print(indent .. "[" .. pos .. '] => "' .. val .. '"') else print(indent .. "[" .. pos .. "] => " .. tostring(val)) end end else print(indent .. tostring(t)) end end end if (type(t) == "table") then print(tostring(t) .. " {") sub_printTable(t, " ") print("}") else sub_printTable(t, " ") end end function updateName(params) local object = getObjectByPawn(params.pawn).obj object.name = params.name local desc = object.ini_tracker.getDescription() local initiative = mysplit(desc, "\n")[1] object.ini_tracker.editInput({index = 0, value = params.name .. "\n" .. initiative}) local xmlTable = self.UI.getXmlTable() local row = getRowById(object.id, xmlTable) row.children[1].attributes.text = params.name updateTable(xmlTable) end function getRowById(payload, xmlTable) local rows = xmlTable[4].children[1].children for i = 1, #rows do local id = tonumber(rows[i].attributes.id) if id == payload then return rows[i] end end return nil end function updateTable(xmlTable) xmlTable[4].children[1].attributes.height = #_objects and 100 * #_objects or 100 self.UI.setXmlTable(xmlTable) end function UI_Destroy(player, payload, id) getObjectByID(tonumber(payload)).obj.pawn.call("destroy_all", nil) end function UI_DestroyAll() while (_objects[1]) do _objects[1].pawn.call("destroy_all_from_ui") end local xml = self.UI.getXmlTable() xml[4].children[1].children = {} updateTable(xml) end function UI_UpdateInput(player, value) _global_calc = value end function UI_InputEdit(player, v, id) id = tonumber(string.sub(id, -1)) local obj = getObjectByID(id).obj obj.calc = tonumber(v) end function UI_CalculateAll() for i = 1, #_objects do _objects[i].pawn.call("GlobalCalculate", {input = _global_calc}) end end function UI_Calculate(player, v) local obj = getObjectByID(tonumber(v)).obj obj.pawn.call("GlobalCalculate", {input = obj.calc}) end function mysplit(inputstr, sep) if sep == nil then sep = "%s" end local t = {} i = 1 for str in string.gmatch(inputstr, "([^" .. sep .. "]+)") do t[i] = str i = i + 1 end return t end function convertSize(input) if string.len(input) < 6 then return 320 else return 180 end end
SWEP.Base = "arccw_base" SWEP.Spawnable = true -- this obviously has to be set to true SWEP.Category = "ArcCW - COD Extras" -- edit this if you like SWEP.AdminOnly = false SWEP.PrintName = "Kuda AP9" SWEP.Trivia_Class = "Submachine Gun" SWEP.Trivia_Desc = "South African SMG." SWEP.Trivia_Manufacturer = "Kuda" SWEP.Trivia_Calibre = "9x19mm Parabellum" SWEP.Trivia_Mechanism = "Gas-Operated" SWEP.Trivia_Country = "South Africa" SWEP.Trivia_Year = 2050 SWEP.CanBash = false SWEP.Slot = 2 SWEP.UseHands = true SWEP.ViewModel = "models/weapons/arccw/c_bo3_kuda.mdl" SWEP.WorldModel = "models/weapons/arccw/c_bo3_kuda.mdl" SWEP.MirrorVMWM = true SWEP.WorldModelOffset = { scale = 1.125, pos = Vector(-9.1, 4, -3.7), ang = Angle(-10, -1, 180), bone = "ValveBiped.Bip01_R_Hand", } SWEP.ViewModelFOV = 60 SWEP.Damage = 28 SWEP.DamageMin = 19 -- damage done at maximum range SWEP.RangeMin = 25 SWEP.Range = 100 -- in METRES SWEP.Penetration = 4 SWEP.DamageType = DMG_BULLET SWEP.ShootEntity = nil -- entity to fire, if any SWEP.MuzzleVelocity = 700 -- projectile or phys bullet muzzle velocity -- IN M/S SWEP.TracerNum = 1 -- tracer every X SWEP.TracerCol = Color(255, 25, 25) SWEP.TracerWidth = 3 SWEP.ChamberSize = 0 -- how many rounds can be chambered. SWEP.Primary.ClipSize = 30 -- DefaultClip is automatically set. SWEP.ExtendedClipSize = 60 SWEP.Recoil = 0.25 SWEP.RecoilSide = 0.35 SWEP.RecoilRise = 0.25 SWEP.VisualRecoilMult = 1 SWEP.Delay = 60 / 722 -- 60 / RPM. SWEP.Num = 1 -- number of shots per trigger pull. SWEP.Firemodes = { { Mode = 2, }, { Mode = 1, }, { Mode = 0 } } SWEP.NPCWeaponType = { "weapon_smg1", } SWEP.NPCWeight = 100 SWEP.AccuracyMOA = 3 -- accuracy in Minutes of Angle. There are 60 MOA in a degree. SWEP.HipDispersion = 550 -- inaccuracy added by hip firing. SWEP.MoveDispersion = 150 SWEP.Primary.Ammo = "pistol" -- what ammo type the gun uses SWEP.MagID = "vector" -- the magazine pool this gun draws from SWEP.ShootVol = 115 -- volume of shoot sound SWEP.ShootPitch = 100 -- pitch of shoot sound SWEP.ShootSound = "ArcCW_BO2.Vector_Fire" SWEP.ShootSoundSilenced = "ArcCW_BO2.MSMC_Sil" SWEP.DistantShootSound = { "^weapons/arccw/bo2_generic_smg/dist1.wav", "^weapons/arccw/bo2_generic_smg/dist2.wav", "^weapons/arccw/bo2_generic_smg/dist3.wav" } SWEP.MuzzleEffect = "muzzleflash_smg" SWEP.ShellModel = "models/shells/shell_9mm.mdl" SWEP.ShellScale = 1.5 SWEP.ShellMaterial = "models/weapons/arcticcw/shell_556_steel" SWEP.MuzzleEffectAttachment = 1 -- which attachment to put the muzzle on SWEP.CaseEffectAttachment = 2 -- which attachment to put the case effect on SWEP.ProceduralViewBobAttachment = 1 SWEP.CamAttachment = 3 SWEP.SpeedMult = 0.95 SWEP.SightedSpeedMult = 0.5 SWEP.SightTime = 0.3 SWEP.BulletBones = { -- the bone that represents bullets in gun/mag -- [0] = "bulletchamber", -- [1] = "bullet1" } SWEP.ProceduralRegularFire = false SWEP.ProceduralIronFire = false SWEP.CaseBones = {} SWEP.IronSightStruct = { Pos = Vector(-3.35, 0, -0.6), Ang = Angle(0.4, 0.01, 0), Magnification = 1.1, CrosshairInSights = false, SwitchToSound = "", -- sound that plays when switching to this sight } SWEP.HoldtypeHolstered = "passive" SWEP.HoldtypeActive = "ar2" SWEP.HoldtypeSights = "ar2" SWEP.DefaultBodygroups = "0000000000" SWEP.AnimShoot = ACT_HL2MP_GESTURE_RANGE_ATTACK_AR2 SWEP.ActivePos = Vector(0, 0, -1) SWEP.ActiveAng = Angle(0, 0, 0) SWEP.SprintPos = Vector(0, 0, -1) SWEP.SprintAng = Angle(0, 0, 0) SWEP.CustomizePos = Vector(15, 1.5, 0) SWEP.CustomizeAng = Angle(15, 40, 35) SWEP.HolsterPos = Vector(3, 0, 0) SWEP.HolsterAng = Angle(-7.036, 30.016, 0) SWEP.BarrelOffsetSighted = Vector(0, 0, -1) SWEP.BarrelOffsetHip = Vector(2, 0, -2) SWEP.BarrelLength = 10 SWEP.ExtraSightDist = 5 SWEP.AttachmentElements = { ["mount"] = { VMBodygroups = { {ind = 3, bg = 1}, }, }, ["ammo_papunch"] = { NamePriority = 10, NameChange = "Crocuta", }, ["bo2_fastmag"] = { VMBodygroups = { {ind = 4, bg = 1}, }, }, ["bo1_extmag"] = { VMBodygroups = { {ind = 4, bg = 2}, }, }, ["bo1_rapidfire"] = { VMBodygroups = { {ind = 0, bg = 1}, {ind = 7, bg = 1}, }, }, ["bo1_fmj"] = { VMBodygroups = { {ind = 5, bg = 1}, }, }, ["bo3_longbarrel"] = { VMBodygroups = { {ind = 6, bg = 1}, }, AttPosMods = { [3] = { vpos = Vector(17, 0.21, 4.35) } } }, ["stock_m"] = { VMBodygroups = { {ind = 9, bg = 1}, }, }, } SWEP.RejectAttachments = { } SWEP.Attachments = { { --1 PrintName = "Optic", -- print name DefaultAttName = "Iron Sights", Slot = {"optic"}, -- what kind of attachments can fit here, can be string or table Bone = "tag_weapon", -- relevant bone any attachments will be mostly referring to Offset = { vpos = Vector(3, 0.21, 5), -- 4.6 offset that the attachment will be relative to the bone vang = Angle(0, 0, 0), }, InstalledEles = {"mount"}, CorrectivePos = Vector(0, 0, 0), CorrectiveAng = Angle(0, 0, 0), }, { --6 PrintName = "Barrel", Slot = {"bo3_longbarrel"}, DefaultAttName = "Standard Barrel", }, { --2 PrintName = "Muzzle", DefaultAttName = "Standard Muzzle", Slot = {"muzzle"}, Bone = "tag_weapon", Offset = { vpos = Vector(13, 0.21, 4.35), vang = Angle(0, 0, 0), }, }, { --3 PrintName = "Underbarrel", Slot = {"foregrip"}, Bone = "tag_weapon", Offset = { vpos = Vector(9, 0.21, 2), -- offset that the attachment will be relative to the bone vang = Angle(0, 0, 0), }, }, { --4 PrintName = "Tactical", Slot = {"bo1_tacprimary"}, VMScale = Vector(1, 1, 1), Bone = "tag_weapon", Offset = { vpos = Vector(9, 0.21, 4.85), -- offset that the attachment will be relative to the bone vang = Angle(0, 0, 180), }, }, { --6 PrintName = "Magazine", Slot = {"bo2_fastmag", "bo1_extmag"}, DefaultAttName = "Standard Magazine", }, { --7 PrintName = "Fire Group", Slot = {"bo1_fcg"} }, { --7 PrintName = "Stock", Slot = {"bo1_stock_m"}, DefaultAttName = "Default Stock" }, { --10 PrintName = "Charm", Slot = "charm", FreeSlot = true, Bone = "tag_weapon", Offset = { vpos = Vector(0, -0.5, 3), vang = Angle(0, 0, 0), }, }, } SWEP.Hook_SelectReloadAnimation = function(wep, curanim) local fastmag = wep:GetBuff_Override("BO1_FastMag") local ext = wep:GetBuff_Override("BO1_ExtMag") if ext then return curanim .. "_ext" end if fastmag then return curanim .. "_fast" end end SWEP.Animations = { ["idle"] = { Source = "idle", Time = 1 / 30, }, ["draw"] = { Source = "draw", Time = 0.83, LHIK = true, LHIKIn = 0.2, LHIKOut = 0.25, }, ["holster"] = { Source = "holster", Time = 0.5, LHIK = true, LHIKIn = 0.2, LHIKOut = 0.25, }, ["ready"] = { Source = "draw", Time = 0.83, LHIK = true, LHIKIn = 0.2, LHIKOut = 0.25, }, ["fire"] = { Source = {"fire"}, Time = 7 / 30, ShellEjectAt = 0, }, ["fire_iron"] = { Source = {"fire_ads"}, Time = 7 / 30, ShellEjectAt = 0, }, ["reload"] = { Source = "reload", Time = 2.166, TPAnim = ACT_HL2MP_GESTURE_RELOAD_SMG1, Framerate = 30, LHIK = true, LHIKIn = 0.5, LHIKOut = 0.5, SoundTable = { {s = "ArcCW_BO1.Kiparis_MagOut", t = 10 / 30}, {s = "ArcCW_BO1.Kiparis_MagIn", t = 36 / 30} }, }, ["reload_empty"] = { Source = "reload_empty", Time = 2.766, TPAnim = ACT_HL2MP_GESTURE_RELOAD_SMG1, Framerate = 30, LHIK = true, LHIKIn = 0.5, LHIKOut = 0.5, SoundTable = { {s = "ArcCW_BO1.Kiparis_MagOut", t = 10 / 30}, {s = "ArcCW_BO1.Kiparis_MagIn", t = 36 / 30}, {s = "ArcCW_BO1.MP5_BoltBack", t = 50 / 30}, {s = "ArcCW_BO1.MP5_BoltFwd", t = 60 / 30}, }, }, ["reload_fast"] = { Source = "fast", Time = 2.166, TPAnim = ACT_HL2MP_GESTURE_RELOAD_SMG1, Framerate = 30, LHIK = true, LHIKIn = 0.5, LHIKOut = 0.5, SoundTable = { {s = "ArcCW_BO1.Kiparis_MagOut", t = 10 / 30}, {s = "ArcCW_BO1.Kiparis_MagIn", t = 36 / 30} }, }, ["reload_empty_fast"] = { Source = "fast_empty", Time = 2.766, TPAnim = ACT_HL2MP_GESTURE_RELOAD_SMG1, Framerate = 30, LHIK = true, LHIKIn = 0.5, LHIKOut = 0.5, SoundTable = { {s = "ArcCW_BO1.Kiparis_MagOut", t = 10 / 30}, {s = "ArcCW_BO1.Kiparis_MagIn", t = 36 / 30}, {s = "ArcCW_BO1.M16_Button", t = 50 / 30}, }, }, ["reload_ext"] = { Source = "ext", Time = 2.166, TPAnim = ACT_HL2MP_GESTURE_RELOAD_SMG1, Framerate = 30, LHIK = true, LHIKIn = 0.5, LHIKOut = 0.5, SoundTable = { {s = "ArcCW_BO1.Kiparis_MagOut", t = 10 / 30}, {s = "ArcCW_BO1.Kiparis_MagIn", t = 36 / 30} }, }, ["reload_empty_ext"] = { Source = "ext_empty", Time = 2.766, TPAnim = ACT_HL2MP_GESTURE_RELOAD_SMG1, Framerate = 30, LHIK = true, LHIKIn = 0.5, LHIKOut = 0.5, SoundTable = { {s = "ArcCW_BO1.Kiparis_MagOut", t = 10 / 30}, {s = "ArcCW_BO1.Kiparis_MagIn", t = 36 / 30}, {s = "ArcCW_BO1.MP5_BoltBack", t = 50 / 30}, {s = "ArcCW_BO1.MP5_BoltFwd", t = 60 / 30}, }, }, ["enter_sprint"] = { Source = "sprint_in", Time = 10 / 30 }, ["idle_sprint"] = { Source = "sprint_loop", Time = 30 / 40 }, ["exit_sprint"] = { Source = "sprint_out", Time = 10 / 30 }, }
local path = (...):match('(.-)[^%./]+$') return { name = 'Quad', description = 'A quadrilateral (a polygon with four sides and four corners) with texture coordinate information.\n\nQuads can be used to select part of a texture to draw. In this way, one large texture atlas can be loaded, and then split up into sub-images.', constructors = { 'newQuad', }, supertypes = { 'Object', }, functions = { { name = 'getTextureDimensions', description = 'Gets reference texture dimensions initially specified in love.graphics.newQuad.', variants = { { returns = { { type = 'number', name = 'sw', description = 'The Texture width used by the Quad.', }, { type = 'number', name = 'sh', description = 'The Texture height used by the Quad.', }, }, }, }, }, { name = 'getViewport', description = 'Gets the current viewport of this Quad.', variants = { { returns = { { type = 'number', name = 'x', description = 'The top-left corner along the x-axis.', }, { type = 'number', name = 'y', description = 'The top-left corner along the y-axis.', }, { type = 'number', name = 'w', description = 'The width of the viewport.', }, { type = 'number', name = 'h', description = 'The height of the viewport.', }, }, }, }, }, { name = 'setViewport', description = 'Sets the texture coordinates according to a viewport.', variants = { { arguments = { { type = 'number', name = 'x', description = 'The top-left corner along the x-axis.', }, { type = 'number', name = 'y', description = 'The top-left corner along the y-axis.', }, { type = 'number', name = 'w', description = 'The width of the viewport.', }, { type = 'number', name = 'h', description = 'The height of the viewport.', }, { type = 'number', name = 'sw', description = 'The reference width, the width of the Image. (Must be greater than 0.)', }, { type = 'number', name = 'sh', description = 'The reference height, the height of the Image. (Must be greater than 0.)', }, }, }, }, }, }, }
local gears = require("gears") local awful = require("awful") require("widgets.main_menu") local desktop_mouse = gears.table.join( awful.button({}, 3, function() mymainmenu:toggle() end), awful.button({}, 4, awful.tag.viewnext), awful.button({}, 5, awful.tag.viewprev) ) return desktop_mouse
AddCSLuaFile() AddCSLuaFile("sh_sounds.lua") include("sh_sounds.lua") if CLIENT then SWEP.DrawCrosshair = true SWEP.PrintName = "Winchester 9422" SWEP.CSMuzzleFlashes = true SWEP.ViewModelMovementScale = 1.15 SWEP.IconLetter = "i" SWEP.MuzzleEffect = "muzzleflash_SR25" SWEP.MuzzleAttachmentName = "muzzle" SWEP.PosBasedMuz = true SWEP.SnapToGrip = true SWEP.ShellScale = 0.7 SWEP.ShellOffsetMul = 2 SWEP.ShellPosOffset = {x = 5, y = -200, z = 0} SWEP.ForeGripOffsetCycle_Draw = 0 SWEP.ForeGripOffsetCycle_Reload = 0.9 SWEP.ForeGripOffsetCycle_Reload_Empty = 0.8 SWEP.ShellDelay = 0.8 SWEP.FireMoveMod = 0.6 SWEP.IronsightPos = Vector(-3.221, 0, 1.639) SWEP.IronsightAng = Vector(-0.15, 0.02, 0) SWEP.EoTechPos = Vector(-3.24, -12, 0.22) SWEP.EoTechAng = Vector(-0.15, 0.02, 0) SWEP.AimpointPos = Vector(-3.23, -12, 0.34) SWEP.AimpointAng = Vector(-0.15, 0.02, 0) SWEP.MicroT1Pos = Vector(-3.24, 0, 0.47) SWEP.MicroT1Ang = Vector(-0.15, 0.02, 0) SWEP.ReflexPos = Vector(-3.22, -12, 0.6) SWEP.ReflexAng = Vector(-0.15, 0.02, 0) SWEP.CmorePos = Vector(-3.21, -12, 0.5) SWEP.CmoreAng = Vector(-0.15, 0.02, 0) SWEP.ShortDotPos = Vector(-3.22, -17, 0.435) SWEP.ShortDotAng = Vector(-0.15, 0.02, 0) SWEP.SchmidtShortDotAxisAlign = {right = 0, up = 0.02, forward = 0} SWEP.NXSPos = Vector(-3.25, -14, 0.325) SWEP.NXSAng = Vector(-0.15, 0.02, 0) SWEP.NXSAlign = {right = 0, up = 0.02, forward = 0} SWEP.SprintPos = Vector(3.029, -0.805, -2.201) SWEP.SprintAng = Vector(-4.926, 38.693, -18.292) SWEP.CustomizePos = Vector(5.519, 0, -1.601) SWEP.CustomizeAng = Vector(21.106, 25.326, 10.553) SWEP.SightWithRail = true //SWEP.DisableSprintViewSimulation = true SWEP.AttachmentModelsVM = { ["md_tundra9mm"] = {model = "models/cw2/attachments/9mmsuppressor.mdl", bone = "v_fa_1887", pos = Vector(-41, 0, 0.7), angle = Angle(0, 90, 0), size = Vector(1, 1, 1)}, ["md_schmidt_shortdot"] = { type = "Model", model = "models/cw2/attachments/schmidt.mdl", bone = "v_fa_1887", rel = "", pos = Vector(-2, -0.37, -2.953), angle = Angle(0, 180, 0), size = Vector(1, 1, 1), adjustment = {min = -8.2, max = -3, axis = "z", inverse = false, inverseOffsetCalc = true}}, ["md_aimpoint"] = { type = "Model", model = "models/wystan/attachments/aimpoint.mdl", bone = "v_fa_1887", rel = "", pos = Vector(-1, -0.3, -3.5), angle = Angle(-180, 90, 180), size = Vector(1.1, 1.1, 1.1), adjustment = {min = -9, max = -5, axis = "z", inverse = false, inverseOffsetCalc = true}}, ["md_eotech"] = { type = "Model", model = "models/wystan/attachments/2otech557sight.mdl", bone = "v_fa_1887", rel = "", pos = Vector(5, 0.3, -10.2), angle = Angle(0, 180, 0), size = Vector(1.2, 1.2, 1.2), adjustment = {min = -15.4, max = -12, axis = "z", inverse = false, inverseOffsetCalc = true}}, ["md_microt1"] = { type = "Model", model = "models/cw2/attachments/microt1.mdl", bone = "v_fa_1887", rel = "", pos = Vector(-9, 0, 2.9), angle = Angle(0, 90, 0), size = Vector(0.5, 0.5, 0.5), adjustment = {min = -2.8, max = 2.5, axis = "z", inverse = false, inverseOffsetCalc = true}}, ["md_rail"] = { type = "Model", model = "models/attachments/mosin/a_modkit_mosin.mdl", bone = "v_fa_1887", rel = "", pos = Vector(-12, 0, 1), angle = Angle(0, 180, 0), size = Vector(1, 1, 1)}, ["md_reflex"] = { type = "Model", model = "models/attachments/kascope.mdl", bone = "v_fa_1887", rel = "", pos = Vector(-11, -0.03, 2.95), angle = Angle(0, -90, 0), size = Vector(0.749, 0.749, 0.749), color = Color(255, 255, 255, 0)}, ["md_cmore"] = { type = "Model", model = "models/attachments/cmore.mdl", bone = "v_fa_1887", rel = "", pos = Vector(-9, 0, 2.7), angle = Angle(0, -90, 0), size = Vector(0.749, 0.749, 0.749), color = Color(255, 255, 255, 0)}, ["md_nightforce_nxs"] = {model = "models/cw2/attachments/l96_scope.mdl", bone = "v_fa_1887", pos = Vector(-8, -0.15, 4.05), angle = Angle(0, 180, 0), size = Vector(1.25, 1.25, 1.25)}, } SWEP.LuaVMRecoilAxisMod = {vert = 0.5, hor = 1, roll = 1, forward = 0.5, pitch = 0.5} SWEP.LaserPosAdjust = Vector(0, 0, 0) SWEP.LaserAngAdjust = Angle(0, 179.5, 0) SWEP.WS_PistolLaserPosAdjust = Vector(0, 0, 0) SWEP.WS_PistolLaserAngAdjust = Angle(0, 0, 0) end SWEP.LuaViewmodelRecoil = false SWEP.Attachments = { [1] = {header = "Sights", offset = {-100, -250}, atts = {"md_microt1", "md_eotech", "md_aimpoint", "md_reflex", "md_cmore", "md_schmidt_shortdot", "md_nightforce_nxs"}}, [2] = {header = "Barrel", offset = {-500, 150}, atts = {"md_tundra9mm"}}, ["+reload"] = {header = "Ammo", offset = {800, 150}, atts = {"am_hollowpoint", "am_armorpiercing"}} } SWEP.Animations = { fire = {"fire1"}, //base_fire_start reload_start = "reload_start", insert = "reload", reload_end = "reload_end", idle = "idle", //base_idle draw = "draw"} SWEP.Sounds = { reload_start = {[1] = {time = 0.5, sound = "CW_W9422_BOLTBACK"}}, reload = {[1] = {time = 0.4, sound = "CW_W9422_INSERT"}}, reload_end = {[1] = {time = 0.3, sound = "CW_W9422_BOLTFORWORD"}}, fire1 = { [1] = {time = 0.6, sound = "CW_W9422_BOLTBACK"}, [2] = {time = 0.8, sound = "CW_W9422_BOLTFORWORD"}}} SWEP.SpeedDec = 10 SWEP.ADSFireAnim = true SWEP.BipodFireAnim = true SWEP.UseHands = true SWEP.Slot = 3 SWEP.SlotPos = 0 SWEP.HoldType = "ar2" SWEP.NormalHoldType = "ar2" SWEP.RunHoldType = "crossbow" SWEP.FireModes = {"bolt"} SWEP.Base = "cw_base" SWEP.Category = "STALKER Weapons" SWEP.Author = "gumlefar & verne" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "" SWEP.WearDamage = 0.002 SWEP.WearEffect = 0.005 SWEP.ViewModelFOV = 70 SWEP.ViewModelFlip = false SWEP.ViewModel = "models/weapons/tfa_nmrih/v_fa_win1892.mdl" SWEP.WorldModel = "models/weapons/tfa_nmrih/w_fa_win1892.mdl" SWEP.DrawTraditionalWorldModel = false SWEP.WM = "models/weapons/tfa_nmrih/w_fa_win1892.mdl" SWEP.WMPos = Vector(-1, 4, 1.5) SWEP.WMAng = Vector(-9,1,180) SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.Primary.ClipSize = 15 SWEP.Primary.DefaultClip = 0 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = ".22LR" SWEP.FireDelay = 1.45 SWEP.FireSound = "CW_W9422_FIRE" SWEP.FireSoundSuppressed = "CW_WS_MOSIN_SUB" SWEP.Recoil = 1.1 SWEP.AimViewModelFOV = 50 SWEP.CustomizationMenuScale = 0.018 SWEP.ForceBackToHipAfterAimedShot = true SWEP.GlobalDelayOnShoot = 1.1 SWEP.HipSpread = 0.15 SWEP.AimSpread = 0.005 SWEP.VelocitySensitivity = 3 SWEP.MaxSpreadInc = 0.4 SWEP.SpreadPerShot = 0.007 SWEP.SpreadCooldown = 0.3 SWEP.Shots = 1 SWEP.Damage = 40 SWEP.DeployTime = 1 /* SWEP.ReloadSpeed = 1 SWEP.ReloadTime = 2.4 SWEP.ReloadTime_Empty = 3.8 SWEP.ReloadHalt = 2.7 SWEP.ReloadHalt_Empty = 4.1 */ SWEP.ReloadStartTime = 0.6 SWEP.InsertShellTime = 1 SWEP.ReloadFinishWait = 1 SWEP.ShotgunReload = true SWEP.Chamberable = false
-- Pandoc Filter to Generate FurAffinity Markup -- By anonusr, 2022 -- -- Based on 2bbcode (https://github.com/lilydjwg/2bbcode) -- Invoke with: pandoc -t to_furaffinity.lua [INPUTFILE] -- -- Note that Pandoc has no concept of text color or alignment, -- so these items will never be translated, even if FA supports them. -- Blocksep is used to separate block elements. function Blocksep() return "\n\n" end -- This function is called once for the whole document. Parameters: -- body, title, date are strings; authors is an array of strings; -- variables is a table. One could use some kind of templating -- system here; this just gives you a simple standalone HTML file. function Doc(body, title, authors, date, variables) return body .. '\n' end -- The functions that follow render corresponding pandoc elements. -- s is always a string, attr is always a table of attributes, and -- items is always an array of strings (the items in a list). -- Comments indicate the types of other variables. function Str(s) return s end function Space() return " " end function LineBreak() return "\n" end function Emph(s) return "[i]" .. s .. "[/i]" end function Strong(s) return "[b]" .. s .. "[/b]" end function Underline(s) return "[u]" .. s .. "[/u]" end function Subscript(s) return "[sub]" .. s .. "[/sub]" end function Superscript(s) return "[sup]" .. s .. "[/sup]" end function SmallCaps(s) error("SmallCaps isn't supported") end function Strikeout(s) return '[s]' .. s .. '[/s]' end function Link(s, src, tit) local ret = '[url' if s then ret = ret .. '=' .. src else s = src end ret = ret .. "]" .. s .. "[/url]" return ret end function Image(s, src, tit) error("Images aren't supported") end function Code(s, attr) error("Code isn't supported") end function InlineMath(s) error("InlineMath isn't supported") end function DisplayMath(s) error("DisplayMath isn't supported") end function Note(s) error("Note isn't supported") end function Plain(s) return s end function Para(s) return s end -- lev is an integer, the header level. function Header(lev, s, attr) return string.format("[h%d]%s[/h%d]",lev, s, lev) end function BlockQuote(s) return "[quote]\n" .. s .. "\n[/quote]" end function HorizontalRule() return "--------------------------------------------------------------------------------" end function Span(s, attr) return s end function Div(s, attr) return s .. '\n' end -- The following code will produce runtime warnings when you haven't defined -- all of the functions you need for the custom writer, so it's useful -- to include when you're working on a writer. local meta = {} meta.__index = function(_, key) io.stderr:write(string.format("WARNING: Undefined function '%s'\n",key)) return function() return "" end end setmetatable(_G, meta)
require 'torch' require 'nn' require 'optim' require 'image' require 'nninit' local model = require 'src/model' local dataproc = require 'src/dataproc' --Use FloatTensor for faster training local dtype = 'torch.FloatTensor' local useOpenCl = true; --If we are using opencl, we change the tensor dtype to "ClTensor" using :cl(); if (useOpenCl) then require 'cltorch' require 'clnn' dtype = torch.FloatTensor():cl():type() end --Create Loss Function local criterion = nn.MSECriterion():type(dtype) criterion.sizeAverage = false --Create VDSR conv neural network --http://cv.snu.ac.kr/research/VDSR/VDSR_CVPR2016.pdf vdsrcnn = model.create(8) --Set the network to the dtype vdsrcnn:type(dtype) --Create training data function TableToTensor(table) local tensorSize = table[1]:size() local tensorSizeTable = {-1} for i=1,tensorSize:size(1) do tensorSizeTable[i+1] = tensorSize[i] end merge=nn.Sequential() :add(nn.JoinTable(1)) :add(nn.View(unpack(tensorSizeTable))) return merge:forward(table) end local imagesn = 12 --Number of images in the folder ./train/ local batchsize = 10 --Reduce the batch size if you have memory problems (C++ Exception or Out of memory error) local minibatch = (imagesn*4)/batchsize --#Of iterations before going through entire batch local hr, lr = dataproc.getImages(imagesn) local timg = image.load("train/test.png", 3, "float") local thr = timg:type(dtype) local tlr = image.scale(image.scale(timg, "*1/2"), thr:size(3), thr:size(2), "bicubic"):type(dtype) local x; local y; function setBatch() ay, ax = dataproc.getBatch(hr, lr, n, w, h) x = TableToTensor(ax):type(dtype) y = TableToTensor(ay):type(dtype) end setBatch() --Initialise training variables params, gradParams = vdsrcnn:getParameters() local optimState = {learningRate = 0.05, weightDecay = 0.0001, momentum = 0.9} local cnorm = 0.001 * optimState.learningRate --Gradient Clipping (c * Initial_Learning_Rate) local showlossevery = 100; local loss = 1; --Training function function f(params) --vdsrcnn:zeroGradParameters(); gradParams:zero() local imagein = x:clone():csub(0.5) --Removing 0.5 to normalise the input images to [-0.5, 0.5] helps prevent gradient explosion --if the image has values of [0, 1], all the gradients initially will be positive at the same time --TODO: Better to substract with the mean of all images --Forward the image values local out = vdsrcnn:forward(imagein) local diff = y:clone():csub(x) --The loss is the difference between the output residual and the ground truth residual loss = criterion:forward(out, diff) --Compute the gradient local lrate = optimState.learningRate local grad_out = criterion:backward(out, diff) --Zero the previous gradient, and backpropagate the new gradient local grad_in = vdsrcnn:backward(imagein, grad_out):clamp(-cnorm/lrate, cnorm/lrate) gradParams:clamp(-cnorm/lrate, cnorm/lrate) --Clip the gradients --Return the loss and new gradient parameters to the optim.sgd() function return loss, gradParams end local decreaseRate = 0.1 --Saves a ground truth residual for testing local Truthdiff = thr:clone():csub(tlr) image.save("test/Truth.png", Truthdiff:add(0.5)) --image.save("test/TestInput.png", x[1]) --image.save("test/TestOutput.png", y[1]) local Truthdiff2 = y[1]:clone():csub(x[1]) image.save("test/TestGT1.png", Truthdiff2:add(0.5)) local epoch = 0; for iter = 1, 30000 do if (iter%10000 == 0) then optimState.learningRate = optimState.learningRate * decreaseRate print("Reducing learning rate by a factor of " .. decreaseRate .. ". New learning rate: " .. optimState.learningRate) end optim.sgd(f, params, optimState) if ((iter%showlossevery == 0) or (iter%20 == 0 and iter < 200) or (iter < 20)) then --Print the training loss and an example residual output to compare with ground truth print("Epoch " .. epoch .. " Iteration " .. iter .. " Training Loss " .. loss) local epochdiff = vdsrcnn:forward(tlr:clone():csub(0.5)) image.save("test/" .. iter .. "resid.png", epochdiff:add(0.5)) end if (iter%100 == 0) then --save model each 100 iterations vdsrcnn:clearState() vdsrcnn:float() torch.save("save/nn" .. iter .. ".cv", vdsrcnn) vdsrcnn:type(dtype) params, gradParams = vdsrcnn:getParameters() collectgarbage() end if (iter%minibatch == minibatch-1) then epoch = epoch+1 end setBatch() end
-------------------------------- -- @module BezierTo -- @extend BezierBy -- @parent_module cc -------------------------------- -- -- @function [parent=#BezierTo] startWithTarget -- @param self -- @param #cc.Node target -- @return BezierTo#BezierTo self (return value: cc.BezierTo) -------------------------------- -- -- @function [parent=#BezierTo] clone -- @param self -- @return BezierTo#BezierTo ret (return value: cc.BezierTo) -------------------------------- -- -- @function [parent=#BezierTo] reverse -- @param self -- @return BezierTo#BezierTo ret (return value: cc.BezierTo) return nil
for i=1,7 do soundblock.register({ filename = "horror_" .. i, key = "horror_" .. i, name = "Horror track " .. i }) end soundblock.register({ filename = "clock", key = "horror_clock", name = "Horror clock" }) soundblock.register({ filename = "clock_strikes_twelve", key = "clock_strikes_twelve", name = "Horror clock strikes twelve" }) soundblock.register({ filename = "Undersea_Garden", key = "Undersea_Garden", name = "Horror undersea garden" })
data:extend( { { type = "bool-setting", name = "enableinfiniteclownsore1", setting_type = "startup", default_value = true, order = "a", }, { type = "bool-setting", name = "enableinfiniteclownsore2", setting_type = "startup", default_value = true, order = "b", }, { type = "bool-setting", name = "enableinfiniteclownsore3", setting_type = "startup", default_value = true, order = "c", }, { type = "bool-setting", name = "enableinfiniteclownsore4", setting_type = "startup", default_value = true, order = "d", }, { type = "bool-setting", name = "enableinfiniteclownsore5", setting_type = "startup", default_value = true, order = "e", }, { type = "bool-setting", name = "enableinfiniteclownsore6", setting_type = "startup", default_value = true, order = "f", }, { type = "bool-setting", name = "enableinfiniteclownsore7", setting_type = "startup", default_value = true, order = "g", }, { type = "bool-setting", name = "enableinfiniteclownsore8", setting_type = "startup", default_value = true, order = "h", }, { type = "bool-setting", name = "enableinfiniteclownsore9", setting_type = "startup", default_value = true, order = "i", }, { type = "bool-setting", name = "enableinfiniteclownsresource1", setting_type = "startup", default_value = true, order = "l", }, { type = "bool-setting", name = "enableinfiniteclownsresource2", setting_type = "startup", default_value = true, order = "m", }, } )
vim.opt.path = ".,/usr/include,,,/home/max/.config/nvim,/home/max/Documents**" vim.opt.shiftwidth = 4 vim.opt.scrolloff = 10 vim.opt.number = true vim.opt.relativenumber = true vim.opt.wrap = false vim.opt.swapfile = false vim.opt.showmode = false vim.opt.laststatus = 3 vim.opt.guicursor = "" -- disable cursor-styling vim.cmd([[ syntax enable colorscheme catppuccin augroup vimrc-incsearch-highlight autocmd! autocmd CmdlineEnter /,\? :set hlsearch autocmd CmdlineLeave /,\? :set nohlsearch augroup END ]])
-- NMEA0183 sample setup for home tests, with UDP sockets instead of the real wired RS-422 network -- get the package NMEA = require( "NMEAcop" ) -- listener for incoming messages on backbone bblistener = NMEA.new() -- set up the filtering, override default discard action by forward to backbone output bblistener.default = NMEA.actions.enqueuebackbone -- this node produces TIROT, IIHDM, IIXDR and IIALR messages, so ignore them on input as they are only echoes bblistener.triggers.TIROT = NMEA.actions.discard bblistener.triggers.IIXDR = NMEA.actions.discard bblistener.triggers.IIHDM = NMEA.actions.discard bblistener.triggers.IIALR = NMEA.actions.discard -- *** IMPROVE ME one of these messages could be used to pet a backbone integrity watchdog -- -- the GPS is upstream on the MacBook and produces GPGSV,GPGGA,GPRMC -- send these on the local stub to the Lenovo running openCPN chartplotter -- no need to send them back out on the backbone that has only 2 nodes -- bblistener.triggers.GPRMC = NMEA.actions.enqueuedecodeandstubsingle -- feed the chartplotter and decode locally bblistener.triggers.GPGGA = NMEA.actions.enqueuedecodeandstubsingle bblistener.triggers.GPGSV = NMEA.actions.enqueuestub -- only for chartplotter -- listener for incoming messages on stub stublistener = NMEA.new() -- set up the filtering, default action is initially setup to discard, no need to repeat ... -- stublistener.default = NMEA.actions.discard -- this node produces TIROT, IIHDM, IIXDR messages, so ignore them on stub input as they are only echoes stublistener.triggers.TIROT = NMEA.actions.discard stublistener.triggers.IIXDR = NMEA.actions.discard stublistener.triggers.IIHDM = NMEA.actions.discard -- chartplotter output should be decoded and also sent down the backbone stublistener.triggers.ECRMB = NMEA.actions.enqueuedecodeandbackbonesingle stublistener.triggers.ECRMC = NMEA.actions.enqueuedecodeandbackbonesingle stublistener.triggers.ECAPB = NMEA.actions.enqueuedecodeandbackbonesingle stublistener.triggers.ECXTE = NMEA.actions.enqueuedecodeandbackbonesingle stublistener.triggers.ECRTE = NMEA.actions.enqueuedecodeandbackbone stublistener.triggers.ECWPL = NMEA.actions.enqueuedecodeandbackbone -- but these chartplotter outputs should be discarded if they come back on the backbone bblistener.triggers.ECRMB = NMEA.actions.discard bblistener.triggers.ECRMC = NMEA.actions.discard bblistener.triggers.ECAPB = NMEA.actions.discard bblistener.triggers.ECXTE = NMEA.actions.discard bblistener.triggers.ECRTE = NMEA.actions.discard bblistener.triggers.ECWPL = NMEA.actions.discard -- -- the main application will need to call the following functions (with a hardware talker function) to produce output -- NMEA.sendbackbone , NMEA.sendstub -- the main application will need to call the following function ( with a decoder) to process the messages received and queued for decoding -- NMEA.senddecode -- -- the main application must also tie the following functions to the listener callbacks to enqueue incoming messages -- bblistener:process , stublistener:process -- -- the data producers on this node need to call the appropriate function to prepare it for transmission -- NMEA.addchecksum and the various variants of NMEA.actions.enqueue<variant> --
function love.load() require "class" require "variables" require "essentials" require "tilelist" require "physics" require "game" require "spells" require "spellbook" require "end" require "menu" require "quoteunquotestory" require "player" require "quad" require "tile" require "laser" require "cube" require "diamonddog" require "damagenumber" require "texts" require "woodblock" require "screenboundary" require "stomper" require "failbox" require "shockwave" require "page" require "intro" gamefinished = true love.filesystem.setIdentity( "order_of_twilight" ) physicsdebug = false debugshapes = {} love.graphics.setLineWidth(1) soundextension = "ogg" soundlist = {"jump", "laser", "hurt", "dead", "arrow", "magic", "teleport", "cancelmagic", "playerdead", "superjump", "shockwave", "gamewin", "ascend", "runeget", "menumove", "menuselect", "menuback", "letter"} for i = 1, #soundlist do _G[soundlist[i] .. "sound"] = love.audio.newSource("sounds/" .. soundlist[i] .. "." .. soundextension, "static") end noiserepeatsound = love.audio.newSource("sounds/noiserepeat.ogg", "static");noiserepeatsound:setLooping(true);noiserepeatsound:setVolume(0.3) musicrev = love.audio.newSource("sounds/musicrev.ogg", "static");musicrev:setVolume(0.1);musicrev:setLooping(true) music = love.audio.newSource("sounds/music.ogg", "static");music:setVolume(0.1);music:setLooping(true) imagelist = {"hornglow", "hornglowbig", "cube", "diamonddog1", "diamonddog2", "numberfont", "font", "fontback", "smallfont", "noise", "lotsanoise", "woodblock", "image1", "image2", "image3", "image4", "image5", "image6", "image7", "image8", "image9", "image10", "image11", "image12", "image13", "background1", "background2", "background3", "background4", "magic", "screengradient", "stomper", "spellbook", "spellbookbook", "bookarrowright", "bookarrowleft", "shockwave", "page", "letter", "title", "background1noise", "background2noise", "background3noise", "background4noise", "rainbowdash", "applejack", "pinkiepie", "fluttershy", "rarity"} thumb = {} for i = 1, 12 do thumb[i] = love.graphics.newImage("maps/thumb" .. i .. ".png") end love.graphics.setDefaultFilter("nearest", "nearest") for i = 1, #imagelist do _G[imagelist[i] .. "img"] = love.graphics.newImage("graphics/" .. imagelist[i] .. ".png") end playeranimation = {} playeranimation.idle = love.graphics.newImage("graphics/twilightidle.png") playeranimation.jump = love.graphics.newImage("graphics/twilightjump.png") playeranimation.dead = love.graphics.newImage("graphics/twilightdead.png") playeranimation.ascend = love.graphics.newImage("graphics/twilightascend.png") playeranimation.walk = {} for i = 1, 4 do playeranimation.walk[i] = love.graphics.newImage("graphics/twilightwalk" .. i .. ".png") end playeranimationinvis = {} playeranimationinvis.idle = love.graphics.newImage("graphics/twilightidleinvis.png") playeranimationinvis.jump = love.graphics.newImage("graphics/twilightjumpinvis.png") playeranimationinvis.walk = {} for i = 1, 4 do playeranimationinvis.walk[i] = love.graphics.newImage("graphics/twilightwalk" .. i .. "invis.png") end ponies = {rainbowdashimg, applejackimg, pinkiepieimg, fluttershyimg, rarityimg} hornoffsets = {} hornoffsets.walk = {{0, 0}, {0, -1}, {0, 0}, {0, -1}} arrow = {} arrow.back = love.graphics.newImage("graphics/arrowback.png") arrow.up = love.graphics.newImage("graphics/arrowup.png") arrow.right = love.graphics.newImage("graphics/arrowright.png") arrow.down = love.graphics.newImage("graphics/arrowdown.png") arrow.left = love.graphics.newImage("graphics/arrowleft.png") arrow.glow = love.graphics.newImage("graphics/arrowglow.png") numberfontquads = {} for i = 0, 9 do numberfontquads[i] = love.graphics.newQuad(i*4, 0, 4, 6, 40, 6) end fontglyphs = "abcdefghijklmnopqrstuvwxyz ^>V<?" fontquads = {} for i = 1, #fontglyphs do fontquads[string.sub(fontglyphs, i, i)] = love.graphics.newQuad((i-1)*8, 0, 8, 7, 256, 7) end fontbackquads = {} for i = 1, #fontglyphs do fontbackquads[string.sub(fontglyphs, i, i)] = love.graphics.newQuad((i-1)*10, 0, 10, 9, 320, 9) end smallfontglyphs = "abcdefghijklmnopqrstuvwxyz ^>V<?0123456789" smallfontquads = {} for i = 1, #smallfontglyphs do smallfontquads[string.sub(smallfontglyphs, i, i)] = love.graphics.newQuad((i-1)*6, 0, 6, 5, 252, 5) end magicquad = {} for i = 1, 5 do magicquad[i] = love.graphics.newQuad((i-1)*10, 0, 10, 10, 50, 10) end logo = love.graphics.newImage("graphics/logo.png") logoblood = love.graphics.newImage("graphics/logoblood.png") stabsound = love.audio.newSource("sounds/stab.ogg", "static") backgrounds = 4 width = 40 height = 20 noise = 0 maxrunecount = 8 levelcount = 10 menuselection = 1 twilighty = 1 currentchallenge = 1 targetoffset = 0 offset = 0 tilewidth = 6 scale = 4 if love.window.getMode() ~= width*tilewidth*scale then love.window.setMode(width*tilewidth*scale, height*tilewidth*scale, false, false, 0) end love.window.setIcon(love.image.newImageData("graphics/icon.png")) runesize = 14 runespacing = 2 storynoise = 0 loadtiles() goalspells = {1, 2, 6, 1, 1, 3, 3, 2, 2, 4, 4, 4} bestspells = {} loadhighscores() tiledb = {} --0 -> Free, 1-> Wall, 2-> Doesn't matter --Direction is clockwise starting top left. tiledb[2] = {1,1,1,1,1,1,1,1} tiledb[3] = {2,0,2,0,2,0,2,0} tiledb[4] = {0,1,0,1,0,1,0,1} tiledb[5] = {2,0,2,1,1,1,1,1} tiledb[6] = {2,1,1,1,1,1,2,0} tiledb[7] = {1,1,1,1,2,0,2,1} tiledb[8] = {1,1,2,0,2,1,1,1} tiledb[9] = {2,0,2,0,2,0,2,1} tiledb[10] = {2,1,2,0,2,0,2,0} tiledb[11] = {2,0,2,1,2,0,2,0} tiledb[12] = {2,0,2,0,2,1,2,0} tiledb[13] = {2,0,2,1,1,1,2,0} tiledb[14] = {2,0,2,0,2,1,1,1} tiledb[15] = {2,1,1,1,2,0,2,0} tiledb[16] = {1,1,2,0,2,0,2,1} tiledb[17] = {2,0,2,1,2,0,2,1} tiledb[18] = {2,1,2,0,2,1,2,0} tiledb[19] = {0,1,1,1,1,1,1,1} tiledb[20] = {1,1,0,1,1,1,1,1} tiledb[21] = {1,1,1,1,0,1,1,1} tiledb[22] = {1,1,1,1,1,1,0,1} tiledb[23] = {0,1,1,1,1,1,0,1} tiledb[24] = {0,1,0,1,1,1,1,1} tiledb[25] = {1,1,0,1,0,1,1,1} tiledb[26] = {1,1,1,1,0,1,0,1} tiledb[27] = {0,1,1,1,0,1,0,1} tiledb[28] = {0,1,0,1,1,1,0,1} tiledb[29] = {0,1,0,1,0,1,1,1} tiledb[30] = {1,1,0,1,0,1,0,1} tiledb[31] = {2,1,0,1,1,1,2,0} tiledb[32] = {2,1,0,1,0,1,2,0} tiledb[33] = {2,1,1,1,0,1,2,0} tiledb[34] = {2,0,2,1,1,1,0,1} tiledb[35] = {2,0,2,1,0,1,0,1} tiledb[36] = {2,0,2,1,0,1,1,1} tiledb[37] = {1,1,2,0,2,1,0,1} tiledb[38] = {0,1,2,0,2,1,1,1} tiledb[39] = {0,1,2,0,2,1,0,1} tiledb[40] = {0,1,1,1,2,0,2,1} tiledb[41] = {0,1,0,1,2,0,2,1} tiledb[42] = {1,1,0,1,2,0,2,1} tiledb[43] = {2,1,0,1,2,0,2,0} tiledb[44] = {0,1,2,0,2,0,2,1} tiledb[45] = {2,0,2,1,0,1,2,0} tiledb[46] = {2,0,2,0,2,1,0,1} tiledb[47] = {0,1,1,1,0,1,1,1} tiledb[48] = {1,1,0,1,1,1,0,1} spelldiscovered = {} changegamestate("intro") end function love.update(dt) --love.graphics.setCaption("FPS: " .. love.timer.getFPS()) dt = math.min(dt, 1/30) if skipupdate then skipupdate = false return end if _G[gamestate .. "_update"] then _G[gamestate .. "_update"](dt) end noiserepeatsound:setVolume(math.max(storynoise/2, noise)/100*0.6) end function love.draw() if _G[gamestate .. "_draw"] then _G[gamestate .. "_draw"]() end love.graphics.setColor(1, 1, 1, 0.01*noise) love.graphics.draw(lotsanoiseimg, -math.random()*240, -math.random()*120, 0, scale, scale) love.graphics.setColor(1, 1, 1) end function loadtiles() local tileimg = love.graphics.newImage("graphics/tiles.png") local tileimgdata = love.image.newImageData("graphics/tiles.png") local width = tileimgdata:getWidth() local height = tileimgdata:getHeight() tilequads = {} for y = 1, math.floor(height/(tilewidth+1)) do for x = 1, math.floor(width/(tilewidth+1)) do table.insert(tilequads, quad:new(tileimg, tileimgdata, x, y, width, height)) end end end function loadhighscores() if love.filesystem.getInfo("high") then local s = love.filesystem.read("high") local s1 = s:split(";") for i = 1, 12 do if tonumber(s1[i]) then bestspells[i] = tonumber(s1[i]) end end if #s1 == 13 then gamefinished = true end end end function savehighscores() local s = "" for i = 1, 12 do if bestspells[i] then s = s .. bestspells[i] end if i ~= 12 or gamefinished then s = s .. ";" end end love.filesystem.write("high", s) end function numberprint(s, x, y) local s = tostring(s) for j = 1, #s do local i = tonumber(string.sub(s, j, j)) if i then love.graphics.draw(numberfontimg, numberfontquads[i], math.floor((x+(j-1)*5)*scale), math.floor(y*scale), 0, scale, scale) end end end function properprint(s, x, y, background) for j = 1, #s do local i = string.sub(s, j, j) if background then local pos = x+(j-1)*8-1 if pos > -xscroll-4 and pos < xscroll+width*tilewidth+8 then love.graphics.draw(fontbackimg, fontbackquads[i], math.floor((pos)*scale), math.floor((y-1)*scale), 0, scale, scale) end else love.graphics.draw(fontimg, fontquads[i], math.floor((x+(j-1)*8)*scale), math.floor(y*scale), 0, scale, scale) end end end function properprintsmall(s, x, y) for j = 1, #s do local i = string.sub(s, j, j) love.graphics.draw(smallfontimg, smallfontquads[i], math.floor((x+(j-1)*6)*scale), math.floor(y*scale), 0, scale, scale) end end function changegamestate(s) gamestate = s if _G[gamestate .. "_load"] then _G[gamestate .. "_load"]() end end function playsound(s) love.audio.stop(s) love.audio.play(s) end function love.keypressed(key, unicode) if _G[gamestate .. "_keypressed"] then _G[gamestate .. "_keypressed"](key, unicode) end end function love.keyreleased(key, unicode) if _G[gamestate .. "_keyreleased"] then _G[gamestate .. "_keyreleased"](key, unicode) end end
ITEM.name = "Blown Capacitor" ITEM.model ="models/artefacts/empty.mdl" ITEM.description = "An electric artifact." ITEM.longdesc = "A physical impossibility. These two circular plates are held at a constant distance to one another, as if something invisible and intangible is keeping them apart. Scientists are still debating where in the lifetime of a Capacitor artifact this specimen is from. It could be a Capacitor that absorbed too much electrical energy and was destroyed by it, or it could be an early stage of it before something further transforms it into a true Capacitor." ITEM.width = 1 ITEM.height = 1 ITEM.price = 7200 ITEM.JumpPower = 300 ITEM.flag = "A" ITEM.rarity = 3 ITEM.baseweight = 1.500 ITEM.varweight = 0.550
describe("translate", function() local lib = require "resty.waf.translate" local t = lib.translate local chains, errs before_each(function() chains = {} errs = nil end) it("single valid rule with no errors", function() local raw = { [[SecRule ARGS "foo" "id:12345,phase:2,deny,msg:'dummy msg'"]] } assert.has.no_errors(function() chains, errs = t(raw, opts) end) assert.is_nil(errs) end) it("single invalid rule with errors", function() local raw = { [[SecRule DNE "foo" "id:12345,phase:2,deny,msg:'dummy msg'"]] } assert.has.no_errors(function() chains, errs = t(raw) end) assert.is_not_nil(errs) end) it("forces translation of a single valid rule with errors", function() local raw = { [[SecRule ARGS|DNE "foo" "id:12345,phase:2,deny,msg:'dummy msg'"]] } local opts = { force = true } assert.has.no_errors(function() chains, errs = t(raw, opts) end) assert.is_nil(errs) assert.is.same(#chains.access[1].vars, 1) end) it("single valid rule with invalid action", function() local raw = { [[SecRule ARGS "foo" "id:12345,phase:2,deny,msg:'dummy msg',foo"]] } assert.has.no_errors(function() chains, errs = t(raw) end) assert.is_not_nil(errs) end) it("loose single valid rule with invalid action", function() local raw = { [[SecRule ARGS "foo" "id:12345,phase:2,deny,msg:'dummy msg',foo"]] } local opts = { loose = true } assert.has.no_errors(function() chains, errs = t(raw, opts) end) assert.is_nil(errs) end) it("single valid rule with data file pattern", function() local raw = { [[SecRule REMOTE_ADDR "@ipMatchFromFile ips.txt" ]] .. [[ "id:12345,phase:2,deny,msg:'dummy msg'"]] } local opts = { path = require("lfs").currentdir() .. '/t/data' } assert.has.no_errors(function() chains, errs = t(raw, opts) end) assert.is_nil(errs) assert.is.same(chains.access[1].pattern, { '1.2.3.4', '5.6.7.8', '10.10.10.0/24' }) end) it("single invalid rule with data file pattern", function() local raw = { [[SecRule REMOTE_ADDR "@ipMatchFromFile ips.txt" ]] .. [[ "id:12345,phase:2,deny,msg:'dummy msg'"]] } local opts = { path = require("lfs").currentdir() .. '/t/dne' } assert.has.no_errors(function() chains, errs = t(raw, opts) end) assert.is_not_nil(errs) assert.is.same(#chains.access, 0) end) it("multiple rules in the same phase", function() local raw = { [[SecRule ARGS "foo" "id:12345,phase:2,deny,msg:'dummy msg'"]], [[SecRule ARGS "foo" "id:12346,phase:2,deny,msg:'dummy msg'"]] } local funcs = { 'clean_input', 'tokenize', 'parse_tokens', 'build_chains', 'translate_chains' } local s = {} for i = 1, #funcs do local func = funcs[i] s[func] = spy.on(lib, func) end assert.has.no_errors(function() chains, errs = t(raw, opts) end) assert.is_nil(errs) assert.is.same(#chains.access, 2) for i = 1, #funcs do local func = funcs[i] assert.spy(s[func]).was.called() end end) it("multiple rules in different phases", function() local raw = { [[SecRule ARGS "foo" "id:12345,phase:2,deny,msg:'dummy msg'"]], [[SecRule ARGS "foo" "id:12346,phase:3,deny,msg:'dummy msg'"]] } local funcs = { 'clean_input', 'tokenize', 'parse_tokens', 'build_chains', 'translate_chains' } local s = {} for i = 1, #funcs do local func = funcs[i] s[func] = spy.on(lib, func) end assert.has.no_errors(function() chains, errs = t(raw, opts) end) assert.is_nil(errs) assert.is.same(#chains.access, 1) assert.is.same(#chains.header_filter, 1) for i = 1, #funcs do local func = funcs[i] assert.spy(s[func]).was.called() end end) end)
local Translator = torch.class('Translator') local nnq = require ('nnquery') local options = { {'-model', '', [[Path to model .t7 file]], {valid=onmt.utils.ExtendedCmdLine.nonEmpty}}, {'-beam_size', 5, [[Beam size]]}, {'-batch_size', 30, [[Batch size]]}, {'-max_sent_length', 250, [[Maximum output sentence length.]]}, {'-replace_unk', false, [[Replace the generated UNK tokens with the source token that had the highest attention weight. If phrase_table is provided, it will lookup the identified source token and give the corresponding target token. If it is not provided (or the identified source token does not exist in the table) then it will copy the source token]]}, {'-phrase_table', '', [[Path to source-target dictionary to replace UNK tokens. See README.md for the format this file should be in]]}, {'-n_best', 1, [[If > 1, it will also output an n_best list of decoded sentences]]}, {'-max_num_unks', math.huge, [[All sequences with more unks than this will be ignored during beam search]]}, {'-pre_filter_factor', 1, [[Optional, set this only if filter is being used. Before applying filters, hypotheses with top `beamSize * preFilterFactor` scores will be considered. If the returned hypotheses voilate filters, then set this to a larger value to consider more.]]}, {'-gate', false, [[Using Gating Network.]]}, {'-concat', false, [[Using Concat Network.]]}, {'-gating_type', 'contextBiEncoder', [[Gating Network]], {enum={'contextBiEncoder', 'leave_one_out', 'conv', 'cbow'}}} } function Translator.declareOpts(cmd) cmd:setCmdLineOptions(options, 'Translator') end function Translator:__init(args) self.opt = args onmt.utils.Cuda.init(self.opt) _G.logger:info('Loading \'' .. self.opt.model .. '\'...') self.checkpoint = torch.load(self.opt.model) self.models = {} self.models.encoder = onmt.Factory.loadEncoder(self.checkpoint.models.encoder) self.models.decoder = onmt.Factory.loadDecoder(self.checkpoint.models.decoder) self.models.encoder:evaluate() self.models.decoder:evaluate() onmt.utils.Cuda.convert(self.models.encoder) onmt.utils.Cuda.convert(self.models.decoder) if self.opt.gate or self.opt.concat == true then self.models.gatingNetwork = onmt.Factory.loadGatingNetwork(self.checkpoint.models.gatingNetwork) self.models.gatingNetwork:evaluate() onmt.utils.Cuda.convert(self.models.gatingNetwork) end self.dicts = self.checkpoint.dicts if self.opt.phrase_table:len() > 0 then self.phraseTable = onmt.translate.PhraseTable.new(self.opt.phrase_table) end end function Translator:buildInput(tokens) local words, features = onmt.utils.Features.extract(tokens) local data = {} data.words = words if #features > 0 then data.features = features end return data end function Translator:buildOutput(data) return table.concat(onmt.utils.Features.annotate(data.words, data.features), ' ') end function Translator:buildData(src, gold) local srcData = {} srcData.words = {} srcData.features = {} local goldData if gold then goldData = {} goldData.words = {} goldData.features = {} end local ignored = {} local indexMap = {} local index = 1 for b = 1, #src do if #src[b].words == 0 then table.insert(ignored, b) else indexMap[index] = b index = index + 1 table.insert(srcData.words, self.dicts.src.words:convertToIdx(src[b].words, onmt.Constants.UNK_WORD)) if #self.dicts.src.features > 0 then table.insert(srcData.features, onmt.utils.Features.generateSource(self.dicts.src.features, src[b].features)) end if gold then table.insert(goldData.words, self.dicts.tgt.words:convertToIdx(gold[b].words, onmt.Constants.UNK_WORD, onmt.Constants.BOS_WORD, onmt.Constants.EOS_WORD)) if #self.dicts.tgt.features > 0 then table.insert(goldData.features, onmt.utils.Features.generateTarget(self.dicts.tgt.features, gold[b].features)) end end end end return onmt.data.Dataset.new(srcData, goldData), ignored, indexMap end function Translator:buildTargetWords(pred, src, attn) local tokens = self.dicts.tgt.words:convertToLabels(pred, onmt.Constants.EOS) if self.opt.replace_unk then for i = 1, #tokens do if tokens[i] == onmt.Constants.UNK_WORD then local _, maxIndex = attn[i]:max(1) local source = src[maxIndex[1]] if self.phraseTable and self.phraseTable:contains(source) then tokens[i] = self.phraseTable:lookup(source) else tokens[i] = source end end end end return tokens end function Translator:buildTargetFeatures(predFeats) local numFeatures = #predFeats[1] if numFeatures == 0 then return {} end local feats = {} for _ = 1, numFeatures do table.insert(feats, {}) end for i = 2, #predFeats do for j = 1, numFeatures do table.insert(feats[j], self.dicts.tgt.features[j]:lookup(predFeats[i][j])) end end return feats end function Translator:translateBatch(batch) local rnnSize = nil local gatingEncStates = nil local gatingContext = nil if self.opt.gate or self.opt.concat then self.models.gatingNetwork:maskPadding() rnnSize = self.models.gatingNetwork.args.rnnSize -- gatingContext: batch x rho x dim tensor if self.opt.gating_type == 'contextBiEncoder' then gatingEncStates, gatingContext = self.models.gatingNetwork:forward(batch) --print(gatingContext:size()) elseif self.opt.gating_type == 'leave_one_out' then gatingContext = {} for t = 1, batch.sourceLength do local gateInputBatch = onmt.utils.Tensor.deepClone(batch) gateInputBatch.sourceInput[t]:fill(onmt.Constants.DOL) local finalStates, context = self.models.gatingNetwork:forward(gateInputBatch) table.insert(gatingContext, finalStates[#finalStates]) -- gatingContext then becomes rho x batch x dim -> need to transpose later end gatingContext = torch.cat(gatingContext, 1):resize(batch.sourceLength, batch.size, self.models.gatingNetwork.args.rnnSize) gatingContext = gatingContext:transpose(1,2) -- swapping dim1 with dim2 -> batch x rho x dim elseif self.opt.gating_type == 'conv' then gatingContext = self.models.gatingNetwork:forward(batch) elseif self.opt.gating_type == 'cbow' then gatingVector = self.models.gatingNetwork:forward(batch) local replica = nn.Replicate(batch.sourceLength, 2) if #onmt.utils.Cuda.gpuIds > 0 then replica:cuda() end gatingContext = replica:forward(gatingVector) end batch:setGateTensor(gatingContext) --batch:setGateTensor(torch.Tensor(batch.size, batch.sourceLength, self.models.gatingNetwork.args.rnnSize):fill(1):cuda()) -- print(gatingContext) end self.models.encoder:maskPadding() self.models.decoder:maskPadding() local encStates, context = self.models.encoder:forward(batch) -- Compute gold score. local goldScore if batch.targetInput ~= nil then if batch.size > 1 then self.models.decoder:maskPadding(batch.sourceSize, batch.sourceLength) end goldScore = self.models.decoder:computeScore(batch, encStates, context) end -- Specify how to go one step forward. local advancer = onmt.translate.DecoderAdvancer.new(self.models.decoder, batch, context, self.opt.max_sent_length, self.opt.max_num_unks, encStates, self.dicts) -- Save memory by only keeping track of necessary elements in the states. -- Attentions are at index 4 in the states defined in onmt.translate.DecoderAdvancer. local attnIndex = 4 -- Features are at index 5 in the states defined in onmt.translate.DecoderAdvancer. local featsIndex = 5 advancer:setKeptStateIndexes({attnIndex, featsIndex}) -- Conduct beam search. local beamSearcher = onmt.translate.BeamSearcher.new(advancer) local results = beamSearcher:search(self.opt.beam_size, self.opt.n_best, self.opt.pre_filter_factor) local allHyp = {} local allFeats = {} local allAttn = {} local allScores = {} for b = 1, batch.size do local hypBatch = {} local featsBatch = {} local attnBatch = {} local scoresBatch = {} for n = 1, self.opt.n_best do local result = results[b][n] local tokens = result.tokens local score = result.score local states = result.states local attn = states[attnIndex] or {} local feats = states[featsIndex] or {} table.remove(tokens) -- Remove unnecessary values from the attention vectors. local size = batch.sourceSize[b] for j = 1, #attn do attn[j] = attn[j]:narrow(1, batch.sourceLength - size + 1, size) end table.insert(hypBatch, tokens) if #feats > 0 then table.insert(featsBatch, feats) end table.insert(attnBatch, attn) table.insert(scoresBatch, score) end table.insert(allHyp, hypBatch) table.insert(allFeats, featsBatch) table.insert(allAttn, attnBatch) table.insert(allScores, scoresBatch) end return allHyp, allFeats, allScores, allAttn, goldScore end --[[ Translate a batch of source sequences. Parameters: * `src` - a batch of tables containing: - `words`: the table of source words - `features`: the table of feaures sequences (`src.features[i][j]` is the value of the ith feature of the jth token) * `gold` - gold data to compute confidence score (same format as `src`) Returns: * `results` - a batch of tables containing: - `goldScore`: if `gold` was given, this is the confidence score - `preds`: an array of `opt.n_best` tables containing: - `words`: the table of target words - `features`: the table of target features sequences - `attention`: the attention vectors of each target word over the source words - `score`: the confidence score of the prediction ]] function Translator:translate(src, gold) local data, ignored, indexMap = self:buildData(src, gold) local results = {} if data:batchCount() > 0 then local batch = data:getBatch() local pred, predFeats, predScore, attn, goldScore = self:translateBatch(batch) for b = 1, batch.size do results[b] = {} results[b].preds = {} for n = 1, self.opt.n_best do results[b].preds[n] = {} results[b].preds[n].words = self:buildTargetWords(pred[b][n], src[indexMap[b]].words, attn[b][n]) results[b].preds[n].features = self:buildTargetFeatures(predFeats[b][n]) results[b].preds[n].attention = attn[b][n] results[b].preds[n].score = predScore[b][n] end if goldScore ~= nil then results[b].goldScore = goldScore[b] end end end for i = 1, #ignored do table.insert(results, ignored[i], {}) end return results end function Translator:extractWordEmbeddingBatch(batch) local rnnSize = nil local gatingEncStates = nil local gatingContext = nil if self.opt.gate or self.opt.concat then self.models.gatingNetwork:maskPadding() rnnSize = self.models.gatingNetwork.args.rnnSize -- gatingContext: batch x rho x dim tensor if self.opt.gating_type == 'contextBiEncoder' then gatingEncStates, gatingContext = self.models.gatingNetwork:forward(batch) elseif self.opt.gating_type == 'leave_one_out' then gatingContext = {} for t = 1, batch.sourceLength do local gateInputBatch = onmt.utils.Tensor.deepClone(batch) gateInputBatch.sourceInput[t]:fill(onmt.Constants.DOL) local finalStates, context = self.models.gatingNetwork:forward(gateInputBatch) table.insert(gatingContext, finalStates[#finalStates]) -- gatingContext then becomes rho x batch x dim -> need to transpose later end gatingContext = torch.cat(gatingContext, 1):resize(batch.sourceLength, batch.size, self.models.gatingNetwork.args.rnnSize) gatingContext = gatingContext:transpose(1,2) -- swapping dim1 with dim2 -> batch x rho x dim elseif self.opt.gating_type == 'conv' then gatingContext = self.models.gatingNetwork:forward(batch) elseif self.opt.gating_type == 'cbow' then gatingVector = self.models.gatingNetwork:forward(batch) local replica = nn.Replicate(batch.sourceLength, 2) if #onmt.utils.Cuda.gpuIds > 0 then replica:cuda() end gatingContext = replica:forward(gatingVector) end batch:setGateTensor(gatingContext) end self.models.encoder:maskPadding() self.models.decoder:maskPadding() local wordEmbedding = {} for t = 1, batch.sourceLength do if self.models.encoder.name == 'Encoder' then table.insert(wordEmbedding, nnq(self.models.encoder.modules[1]):descendants()[13]:val().data.module:forward(batch:getSourceInput(t)):clone()) -- append 1 x 500 to wordEmbedding else table.insert(wordEmbedding, nnq(self.models.encoder.modules[1].modules[1]):descendants()[13]:val().data.module:forward(batch:getSourceInput(t)):clone()) end end wordEmbedding = torch.cat(wordEmbedding, 1) -- table -> tensor return wordEmbedding:double() end function Translator:extractWordEmbedding(src) local data, ignored, indexMap = self:buildData(src, nil) local results = {} local batch = data:getBatch() assert(batch.size == 1) local embedding = self:extractWordEmbeddingBatch(batch) return embedding end return Translator
-- http://stackoverflow.com/questions/20284515/capitalize-first-letter-of-every-word-in-lua function string:to_http () return self:gsub ("_", "-"):gsub ("(%a)(%a*)", function (letter, r) return letter:upper() .. r:lower() end) end function string:to_identifier () return self:trim ():lower ():gsub ("-", "_") end -- Sequence: { [1] = text ... } -- Parameterized: { [1] = { token = ..., parameters = { ... } } -- MIME | Language: { [1] = { ..., parameters = { ... } } -- Tokens: { [token] = { parameters } } -- Token: { token = ..., parameters = { ... } } -- local dump = require "pl.pretty" . dump local Header = {} Header.__index = Header -- Header.Sequence = { name = "Sequence", } function Header.Sequence.request (header, context) local value = context.request.headers [header.as_identifier] local result = {} for token in value:gmatch "([^,%s]+)" do result [#result + 1] = { token = token } end context.request.headers [header.as_identifier] = result end function Header.Sequence.response (header, context) local value = context.response.headers [header.as_identifier] local result = {} for i, v in ipairs (value) do result [i] = v.token end context.response.headers [header.as_identifier] = table.concat (result, ",") end -- Header.Normalized = { name = "Normalized", } function Header.Normalized.request (header, context) local value = context.request.headers [header.as_identifier] for _, x in ipairs (value) do x.token = x.token:to_identifier () end end function Header.Normalized.response (header, context) local value = context.response.headers [header.as_identifier] for _, x in ipairs (value) do x.token = x.token:to_http () end end -- Header.Parameterized = { name = "Parameterized", token_pattern = "([^;%s]+)%s*;?(.*)", parameter_pattern = "([^=;%s]+)%s*[=]%s*([^;%s]+)", } function Header.Parameterized.request (header, context) local value = context.request.headers [header.as_identifier] for _, x in ipairs (value) do local _, remaining = x.token:match (Header.Parameterized.token_pattern) local parameters = {} for k, v in remaining:gmatch (Header.Parameterized.parameter_pattern) do parameters [k] = v end x.parameters = parameters end end function Header.Parameterized.response (header, context) local value = context.response.headers [header.as_identifier] for _, x in ipairs (value) do local result = x.token for k, v in pairs (x.parameters or {}) do result = result .. "; " .. k .. "=" .. v end x.token = result end end -- Header.MIME = { name = "MIME", pattern = "([^/%s]+)%s*/%s*(.*)", } function Header.MIME.request (header, context) local value = context.request.headers [header.as_identifier] for _, x in ipairs (value) do x.main, x.sub = x.token:match (Header.MIME.pattern) end end function Header.MIME.response (header, context) local value = context.response.headers [header.as_identifier] for _, x in ipairs (value) do x.token = x.main .. "/" .. x.sub end end -- Header.Language = { name = "Language", pattern = "(%a+)(-(%a+))?", } function Header.Language.request (header, context) local value = context.request.headers [header.as_identifier] for _, x in ipairs (value) do x.primary, _, x.sub = x.token:match (Header.Language.pattern) end end function Header.Language.response (header, context) local value = context.response.headers [header.as_identifier] for _, x in ipairs (value) do x.token = x.primary .. (x.sub and "-" .. x.sub or "") end end -- Header.Sorted = { name = "Sorted", } function Header.Sorted.request (header, context) local value = context.request.headers [header.as_identifier] table.sort (value, function (lhs, rhs) local l = (lhs.parameters or {}).q or 1 local r = (rhs.parameters or {}).q or 1 return l > r end) end function Header.Sorted.response () end -- Header.Tokenized = { name = "Tokenized", } function Header.Tokenized.request (header, context) local value = context.request.headers [header.as_identifier] local result = {} for _, x in ipairs (value) do result [x.token] = x.parameters or {} end context.request.headers [header.as_identifier] = result end function Header.Tokenized.response (header, context) local value = context.response.headers [header.as_identifier] local result = {} for k, v in pairs (value) do result [#result + 1] = { token = k, parameters = v, } end context.response.headers [header.as_identifier] = result end -- Header.First = { name = "First", } function Header.First.request (header, context) local value = context.request.headers [header.as_identifier] context.request.headers [header.as_identifier] = value [1] end function Header.First.response (header, context) local value = context.response.headers [header.as_identifier] context.response.headers [header.as_identifier] = { value } end -- Header.Integer = { name = "Integer", } function Header.Integer.request (header, context) local value = context.request.headers [header.as_identifier] context.request.headers [header.as_identifier] = tonumber (value.token) end function Header.Integer.response (header, context) local value = context.response.headers [header.as_identifier] context.response.headers [header.as_identifier] = { token = tostring (value), } end -- Header.depends = {} function Header.sort (headers) table.sort (headers, function (lhs, rhs) local lhs_id = lhs.as_identifier local rhs_id = rhs.as_identifier if not Header.depends [rhs_id] then local dependencies = {} for _, dep in ipairs (rhs.depends or {}) do dependencies [dep:to_identifier ()] = true end Header.depends [rhs_id] = dependencies end return Header.depends [rhs_id] [lhs_id] end) end function Header.__tostring (header) return header.as_http end function Header.class (attributes) attributes.as_identifier = attributes.name:to_identifier () attributes.as_http = attributes.name:to_http () return setmetatable (attributes, Header) end function Header.request (header, context) local value = context.request.headers [header.as_identifier] if not value then return end local filters = header.filters for i = 1, #filters do filters [i].request (header, context) end end function Header.response (header, context) local value = context.response.headers [header.as_identifier] if not value then return end local filters = header.filters for i = #filters, 1, -1 do filters [i].response (header, context) end end function Header.request_default () end function Header.response_default () end function Header.on_request () end function Header.on_response () end return Header
local t = My.Translator.translate My = My or {} My.SideMissions = My.SideMissions or {} My.SideMissions.TransportThing = function(from, to, player) local size = math.random() size = size * size + 0.2 -- ensures the size is at the lower border more oftenly local amount = math.ceil(size * player:getMaxStorageSpace()) local payment = My.SideMissions.paymentPerDistance(distance(from, to)) * 1.5 local timeLimit if math.random(0, 1) == 1 then local difficulty = math.random(1.0, 2.0) timeLimit = distance(from, to) / 120 * difficulty payment = payment * (1 + 1/difficulty * 0.2) end local possibleStories = {} if from:hasTag("residual") and to:hasTag("mining") then table.insert(possibleStories, "alcohol") end if from:hasTag("residual") or to:hasTag("residual") then table.insert(possibleStories, "letters") end if from:hasTag("mining") and to:hasTag("science") then table.insert(possibleStories, "minerals") end table.insert(possibleStories, "memory") local story = Util.random(possibleStories) if story == nil then return nil end local product = Product:new(t("side_mission_transport_thing_product_" .. story)) local description = t("side_mission_transport_thing_description_" .. story, to:getCallSign(), amount, payment) if not isNil(timeLimit) then description = description .. "\n\n" .. t("side_mission_transport_thing_time_limit", timeLimit / 60) end local mission mission = Missions:transportProduct(from, to, product, { amount = amount, acceptCondition = function(self, error) if error == "no_storage" then return t("side_mission_transport_thing_no_storage") elseif error == "small_storage" then return t("side_mission_transport_thing_small_storage", amount * product:getSize()) end return true end, onAccept = function(self) local hint = t("side_mission_transport_thing_accept_hint", from:getCallSign(), product:getName()) self:setHint(function() local text = hint if Mission:isTimeLimitMission(self) then text = text .. "\n" .. t("generic_mission_time_limit", self:getRemainingTime() / 60) end return text end) self:getPlayer():addToShipLog(hint, "255,127,0") end, onLoad = function(self) self:getPlayer():addToShipLog(t("side_mission_transport_thing_load_log", product:getName()), "255,127,0") local hint = t("side_mission_transport_thing_load_hint", to:getCallSign(), product:getName()) self:setHint(function() local text = hint if Mission:isTimeLimitMission(self) then text = text .. "\n" .. t("generic_mission_time_limit", self:getRemainingTime() / 60) end return text end) self:getPlayer():addToShipLog(hint, "255,127,0") end, onInsufficientStorage = function(self) mission:getPlayer():addToShipLog(t("side_mission_transport_thing_insufficient_storage", product:getName(), amount * product:getSize()), "255,127,0") end, onSuccess = function(self) to:sendCommsMessage(self:getPlayer(), t("side_mission_transport_thing_success", payment)) self:getPlayer():addReputationPoints(payment) end, onFailure = function(self) if self:getPlayer():isValid() and to:isValid() then to:sendCommsMessage(self:getPlayer(), t("side_mission_transport_thing_time_out")) end end, onEnd = function(self) if self:getPlayer():isValid() then self:getPlayer():modifyProductStorage(product, -999) -- make sure storage is not blocked end end, }) if not isNil(timeLimit) then Mission:withTimeLimit(mission, timeLimit) end Mission:withBroker(mission, t("side_mission_transport_thing", product:getName(), to:getCallSign()), { description = description, acceptMessage = nil, }) return mission end
local match = require "luassert.match" local spy = require "luassert.spy" local display = require "nvim-lsp-installer.core.ui.display" local Ui = require "nvim-lsp-installer.core.ui" local a = require "nvim-lsp-installer.core.async" describe("ui", function() it("produces a correct tree", function() local function renderer(state) return Ui.CascadingStyleNode({ "INDENT" }, { Ui.When(not state.is_active, function() return Ui.Text { "I'm not active", "Another line", } end), Ui.When(state.is_active, function() return Ui.Text { "I'm active", "Yet another line", } end), }) end assert.same({ children = { { type = "HL_TEXT", lines = { { { "I'm not active", "" } }, { { "Another line", "" } }, }, }, { type = "NODE", children = {}, }, }, styles = { "INDENT" }, type = "CASCADING_STYLE", }, renderer { is_active = false }) assert.same({ children = { { type = "NODE", children = {}, }, { type = "HL_TEXT", lines = { { { "I'm active", "" } }, { { "Yet another line", "" } }, }, }, }, styles = { "INDENT" }, type = "CASCADING_STYLE", }, renderer { is_active = true }) end) it("renders a tree correctly", function() local render_output = display._render_node( { win_width = 120, }, Ui.CascadingStyleNode({ "INDENT" }, { Ui.Keybind("i", "INSTALL_SERVER", { "sumneko_lua" }, true), Ui.HlTextNode { { { "Hello World!", "MyHighlightGroup" }, }, { { "Another Line", "Comment" }, }, }, Ui.HlTextNode { { { "Install something idk", "Stuff" }, }, }, Ui.Keybind("<CR>", "INSTALL_SERVER", { "tsserver" }, false), Ui.DiagnosticsNode { message = "yeah this one's outdated", severity = vim.diagnostic.severity.WARN, source = "trust me bro", }, Ui.Text { "I'm a text node" }, }) ) assert.same({ highlights = { { col_start = 2, col_end = 14, line = 0, hl_group = "MyHighlightGroup", }, { col_start = 2, col_end = 14, line = 1, hl_group = "Comment", }, { col_start = 2, col_end = 23, line = 2, hl_group = "Stuff", }, }, lines = { " Hello World!", " Another Line", " Install something idk", " I'm a text node" }, virt_texts = {}, keybinds = { { effect = "INSTALL_SERVER", key = "i", line = -1, payload = { "sumneko_lua" }, }, { effect = "INSTALL_SERVER", key = "<CR>", line = 3, payload = { "tsserver" }, }, }, diagnostics = { { line = 3, message = "yeah this one's outdated", source = "trust me bro", severity = vim.diagnostic.severity.WARN, }, }, }, render_output) end) end) describe("integration test", function() it( "calls vim APIs as expected during rendering", async_test(function() local window = display.new_view_only_win "test" window.view(function(state) return Ui.Node { Ui.Keybind("U", "EFFECT", nil, true), Ui.Text { "Line number 1!", state.text, }, Ui.Keybind("R", "R_EFFECT", { state.text }), Ui.HlTextNode { { { "My highlighted text", "MyHighlightGroup" }, }, }, } end) local mutate_state = window.init { text = "Initial state" } window.open { effects = { ["EFFECT"] = function() end, ["R_EFFECT"] = function() end, }, highlight_groups = { "hi def MyHighlight gui=bold", }, } local clear_namespace = spy.on(vim.api, "nvim_buf_clear_namespace") local buf_set_option = spy.on(vim.api, "nvim_buf_set_option") local win_set_option = spy.on(vim.api, "nvim_win_set_option") local set_lines = spy.on(vim.api, "nvim_buf_set_lines") local set_extmark = spy.on(vim.api, "nvim_buf_set_extmark") local add_highlight = spy.on(vim.api, "nvim_buf_add_highlight") local set_keymap = spy.on(vim.keymap, "set") -- Initial window and buffer creation + initial render a.scheduler() assert.spy(win_set_option).was_called(8) assert.spy(win_set_option).was_called_with(match.is_number(), "number", false) assert.spy(win_set_option).was_called_with(match.is_number(), "relativenumber", false) assert.spy(win_set_option).was_called_with(match.is_number(), "wrap", false) assert.spy(win_set_option).was_called_with(match.is_number(), "spell", false) assert.spy(win_set_option).was_called_with(match.is_number(), "foldenable", false) assert.spy(win_set_option).was_called_with(match.is_number(), "signcolumn", "no") assert.spy(win_set_option).was_called_with(match.is_number(), "colorcolumn", "") assert.spy(win_set_option).was_called_with(match.is_number(), "cursorline", true) assert.spy(buf_set_option).was_called(10) assert.spy(buf_set_option).was_called_with(match.is_number(), "modifiable", false) assert.spy(buf_set_option).was_called_with(match.is_number(), "swapfile", false) assert.spy(buf_set_option).was_called_with(match.is_number(), "textwidth", 0) assert.spy(buf_set_option).was_called_with(match.is_number(), "buftype", "nofile") assert.spy(buf_set_option).was_called_with(match.is_number(), "bufhidden", "wipe") assert.spy(buf_set_option).was_called_with(match.is_number(), "buflisted", false) assert.spy(buf_set_option).was_called_with(match.is_number(), "filetype", "lsp-installer") assert.spy(buf_set_option).was_called_with(match.is_number(), "undolevels", -1) assert.spy(set_lines).was_called(1) assert.spy(set_lines).was_called_with( match.is_number(), 0, -1, false, { "Line number 1!", "Initial state", "My highlighted text" } ) assert.spy(set_extmark).was_called(0) assert.spy(add_highlight).was_called(1) assert.spy(add_highlight).was_called_with( match.is_number(), match.is_number(), "MyHighlightGroup", 2, 0, 19 ) assert.spy(set_keymap).was_called(2) assert.spy(set_keymap).was_called_with( "n", "U", match.is_function(), match.tbl_containing { nowait = true, silent = true, buffer = match.is_number() } ) assert.spy(set_keymap).was_called_with( "n", "R", match.is_function(), match.tbl_containing { nowait = true, silent = true, buffer = match.is_number() } ) assert.spy(clear_namespace).was_called(1) assert.spy(clear_namespace).was_called_with(match.is_number(), match.is_number(), 0, -1) mutate_state(function(state) state.text = "New state" end) assert.spy(set_lines).was_called(1) a.scheduler() assert.spy(set_lines).was_called(2) assert.spy(set_lines).was_called_with( match.is_number(), 0, -1, false, { "Line number 1!", "New state", "My highlighted text" } ) end) ) end)
--- MaterialDesign local M = {} M.FontIconFileName = "MaterialIcons-Regular.ttf" M.IconMin = 0xe000 M.IconMax = 0xeb4c M.The3d_rotation = "\xee\xa1\x8d" M.Ac_unit = "\xee\xac\xbb" M.Access_alarm = "\xee\x86\x90" M.Access_alarms = "\xee\x86\x91" M.Access_time = "\xee\x86\x92" M.Accessibility = "\xee\xa1\x8e" M.Accessible = "\xee\xa4\x94" M.Account_balance = "\xee\xa1\x8f" M.Account_balance_wallet = "\xee\xa1\x90" M.Account_box = "\xee\xa1\x91" M.Account_circle = "\xee\xa1\x93" M.Adb = "\xee\x98\x8e" M.Add = "\xee\x85\x85" M.Add_a_photo = "\xee\x90\xb9" M.Add_alarm = "\xee\x86\x93" M.Add_alert = "\xee\x80\x83" M.Add_box = "\xee\x85\x86" M.Add_circle = "\xee\x85\x87" M.Add_circle_outline = "\xee\x85\x88" M.Add_location = "\xee\x95\xa7" M.Add_shopping_cart = "\xee\xa1\x94" M.Add_to_photos = "\xee\x8e\x9d" M.Add_to_queue = "\xee\x81\x9c" M.Adjust = "\xee\x8e\x9e" M.Airline_seat_flat = "\xee\x98\xb0" M.Airline_seat_flat_angled = "\xee\x98\xb1" M.Airline_seat_individual_suite = "\xee\x98\xb2" M.Airline_seat_legroom_extra = "\xee\x98\xb3" M.Airline_seat_legroom_normal = "\xee\x98\xb4" M.Airline_seat_legroom_reduced = "\xee\x98\xb5" M.Airline_seat_recline_extra = "\xee\x98\xb6" M.Airline_seat_recline_normal = "\xee\x98\xb7" M.Airplanemode_active = "\xee\x86\x95" M.Airplanemode_inactive = "\xee\x86\x94" M.Airplay = "\xee\x81\x95" M.Airport_shuttle = "\xee\xac\xbc" M.Alarm = "\xee\xa1\x95" M.Alarm_add = "\xee\xa1\x96" M.Alarm_off = "\xee\xa1\x97" M.Alarm_on = "\xee\xa1\x98" M.Album = "\xee\x80\x99" M.All_inclusive = "\xee\xac\xbd" M.All_out = "\xee\xa4\x8b" M.Android = "\xee\xa1\x99" M.Announcement = "\xee\xa1\x9a" M.Apps = "\xee\x97\x83" M.Archive = "\xee\x85\x89" M.Arrow_back = "\xee\x97\x84" M.Arrow_downward = "\xee\x97\x9b" M.Arrow_drop_down = "\xee\x97\x85" M.Arrow_drop_down_circle = "\xee\x97\x86" M.Arrow_drop_up = "\xee\x97\x87" M.Arrow_forward = "\xee\x97\x88" M.Arrow_upward = "\xee\x97\x98" M.Art_track = "\xee\x81\xa0" M.Aspect_ratio = "\xee\xa1\x9b" M.Assessment = "\xee\xa1\x9c" M.Assignment = "\xee\xa1\x9d" M.Assignment_ind = "\xee\xa1\x9e" M.Assignment_late = "\xee\xa1\x9f" M.Assignment_return = "\xee\xa1\xa0" M.Assignment_returned = "\xee\xa1\xa1" M.Assignment_turned_in = "\xee\xa1\xa2" M.Assistant = "\xee\x8e\x9f" M.Assistant_photo = "\xee\x8e\xa0" M.Attach_file = "\xee\x88\xa6" M.Attach_money = "\xee\x88\xa7" M.Attachment = "\xee\x8a\xbc" M.Audiotrack = "\xee\x8e\xa1" M.Autorenew = "\xee\xa1\xa3" M.Av_timer = "\xee\x80\x9b" M.Backspace = "\xee\x85\x8a" M.Backup = "\xee\xa1\xa4" M.Battery_alert = "\xee\x86\x9c" M.Battery_charging_full = "\xee\x86\xa3" M.Battery_full = "\xee\x86\xa4" M.Battery_std = "\xee\x86\xa5" M.Battery_unknown = "\xee\x86\xa6" M.Beach_access = "\xee\xac\xbe" M.Beenhere = "\xee\x94\xad" M.Block = "\xee\x85\x8b" M.Bluetooth = "\xee\x86\xa7" M.Bluetooth_audio = "\xee\x98\x8f" M.Bluetooth_connected = "\xee\x86\xa8" M.Bluetooth_disabled = "\xee\x86\xa9" M.Bluetooth_searching = "\xee\x86\xaa" M.Blur_circular = "\xee\x8e\xa2" M.Blur_linear = "\xee\x8e\xa3" M.Blur_off = "\xee\x8e\xa4" M.Blur_on = "\xee\x8e\xa5" M.Book = "\xee\xa1\xa5" M.Bookmark = "\xee\xa1\xa6" M.Bookmark_border = "\xee\xa1\xa7" M.Border_all = "\xee\x88\xa8" M.Border_bottom = "\xee\x88\xa9" M.Border_clear = "\xee\x88\xaa" M.Border_color = "\xee\x88\xab" M.Border_horizontal = "\xee\x88\xac" M.Border_inner = "\xee\x88\xad" M.Border_left = "\xee\x88\xae" M.Border_outer = "\xee\x88\xaf" M.Border_right = "\xee\x88\xb0" M.Border_style = "\xee\x88\xb1" M.Border_top = "\xee\x88\xb2" M.Border_vertical = "\xee\x88\xb3" M.Branding_watermark = "\xee\x81\xab" M.Brightness_1 = "\xee\x8e\xa6" M.Brightness_2 = "\xee\x8e\xa7" M.Brightness_3 = "\xee\x8e\xa8" M.Brightness_4 = "\xee\x8e\xa9" M.Brightness_5 = "\xee\x8e\xaa" M.Brightness_6 = "\xee\x8e\xab" M.Brightness_7 = "\xee\x8e\xac" M.Brightness_auto = "\xee\x86\xab" M.Brightness_high = "\xee\x86\xac" M.Brightness_low = "\xee\x86\xad" M.Brightness_medium = "\xee\x86\xae" M.Broken_image = "\xee\x8e\xad" M.Brush = "\xee\x8e\xae" M.Bubble_chart = "\xee\x9b\x9d" M.Bug_report = "\xee\xa1\xa8" M.Build = "\xee\xa1\xa9" M.Burst_mode = "\xee\x90\xbc" M.Business = "\xee\x82\xaf" M.Business_center = "\xee\xac\xbf" M.Cached = "\xee\xa1\xaa" M.Cake = "\xee\x9f\xa9" M.Call = "\xee\x82\xb0" M.Call_end = "\xee\x82\xb1" M.Call_made = "\xee\x82\xb2" M.Call_merge = "\xee\x82\xb3" M.Call_missed = "\xee\x82\xb4" M.Call_missed_outgoing = "\xee\x83\xa4" M.Call_received = "\xee\x82\xb5" M.Call_split = "\xee\x82\xb6" M.Call_to_action = "\xee\x81\xac" M.Camera = "\xee\x8e\xaf" M.Camera_alt = "\xee\x8e\xb0" M.Camera_enhance = "\xee\xa3\xbc" M.Camera_front = "\xee\x8e\xb1" M.Camera_rear = "\xee\x8e\xb2" M.Camera_roll = "\xee\x8e\xb3" M.Cancel = "\xee\x97\x89" M.Card_giftcard = "\xee\xa3\xb6" M.Card_membership = "\xee\xa3\xb7" M.Card_travel = "\xee\xa3\xb8" M.Casino = "\xee\xad\x80" M.Cast = "\xee\x8c\x87" M.Cast_connected = "\xee\x8c\x88" M.Center_focus_strong = "\xee\x8e\xb4" M.Center_focus_weak = "\xee\x8e\xb5" M.Change_history = "\xee\xa1\xab" M.Chat = "\xee\x82\xb7" M.Chat_bubble = "\xee\x83\x8a" M.Chat_bubble_outline = "\xee\x83\x8b" M.Check = "\xee\x97\x8a" M.Check_box = "\xee\xa0\xb4" M.Check_box_outline_blank = "\xee\xa0\xb5" M.Check_circle = "\xee\xa1\xac" M.Chevron_left = "\xee\x97\x8b" M.Chevron_right = "\xee\x97\x8c" M.Child_care = "\xee\xad\x81" M.Child_friendly = "\xee\xad\x82" M.Chrome_reader_mode = "\xee\xa1\xad" M.Class = "\xee\xa1\xae" M.Clear = "\xee\x85\x8c" M.Clear_all = "\xee\x82\xb8" M.Close = "\xee\x97\x8d" M.Closed_caption = "\xee\x80\x9c" M.Cloud = "\xee\x8a\xbd" M.Cloud_circle = "\xee\x8a\xbe" M.Cloud_done = "\xee\x8a\xbf" M.Cloud_download = "\xee\x8b\x80" M.Cloud_off = "\xee\x8b\x81" M.Cloud_queue = "\xee\x8b\x82" M.Cloud_upload = "\xee\x8b\x83" M.Code = "\xee\xa1\xaf" M.Collections = "\xee\x8e\xb6" M.Collections_bookmark = "\xee\x90\xb1" M.Color_lens = "\xee\x8e\xb7" M.Colorize = "\xee\x8e\xb8" M.Comment = "\xee\x82\xb9" M.Compare = "\xee\x8e\xb9" M.Compare_arrows = "\xee\xa4\x95" M.Computer = "\xee\x8c\x8a" M.Confirmation_number = "\xee\x98\xb8" M.Contact_mail = "\xee\x83\x90" M.Contact_phone = "\xee\x83\x8f" M.Contacts = "\xee\x82\xba" M.Content_copy = "\xee\x85\x8d" M.Content_cut = "\xee\x85\x8e" M.Content_paste = "\xee\x85\x8f" M.Control_point = "\xee\x8e\xba" M.Control_point_duplicate = "\xee\x8e\xbb" M.Copyright = "\xee\xa4\x8c" M.Create = "\xee\x85\x90" M.Create_new_folder = "\xee\x8b\x8c" M.Credit_card = "\xee\xa1\xb0" M.Crop = "\xee\x8e\xbe" M.Crop_16_9 = "\xee\x8e\xbc" M.Crop_3_2 = "\xee\x8e\xbd" M.Crop_5_4 = "\xee\x8e\xbf" M.Crop_7_5 = "\xee\x8f\x80" M.Crop_din = "\xee\x8f\x81" M.Crop_free = "\xee\x8f\x82" M.Crop_landscape = "\xee\x8f\x83" M.Crop_original = "\xee\x8f\x84" M.Crop_portrait = "\xee\x8f\x85" M.Crop_rotate = "\xee\x90\xb7" M.Crop_square = "\xee\x8f\x86" M.Dashboard = "\xee\xa1\xb1" M.Data_usage = "\xee\x86\xaf" M.Date_range = "\xee\xa4\x96" M.Dehaze = "\xee\x8f\x87" M.Delete = "\xee\xa1\xb2" M.Delete_forever = "\xee\xa4\xab" M.Delete_sweep = "\xee\x85\xac" M.Description = "\xee\xa1\xb3" M.Desktop_mac = "\xee\x8c\x8b" M.Desktop_windows = "\xee\x8c\x8c" M.Details = "\xee\x8f\x88" M.Developer_board = "\xee\x8c\x8d" M.Developer_mode = "\xee\x86\xb0" M.Device_hub = "\xee\x8c\xb5" M.Devices = "\xee\x86\xb1" M.Devices_other = "\xee\x8c\xb7" M.Dialer_sip = "\xee\x82\xbb" M.Dialpad = "\xee\x82\xbc" M.Directions = "\xee\x94\xae" M.Directions_bike = "\xee\x94\xaf" M.Directions_boat = "\xee\x94\xb2" M.Directions_bus = "\xee\x94\xb0" M.Directions_car = "\xee\x94\xb1" M.Directions_railway = "\xee\x94\xb4" M.Directions_run = "\xee\x95\xa6" M.Directions_subway = "\xee\x94\xb3" M.Directions_transit = "\xee\x94\xb5" M.Directions_walk = "\xee\x94\xb6" M.Disc_full = "\xee\x98\x90" M.Dns = "\xee\xa1\xb5" M.Do_not_disturb = "\xee\x98\x92" M.Do_not_disturb_alt = "\xee\x98\x91" M.Do_not_disturb_off = "\xee\x99\x83" M.Do_not_disturb_on = "\xee\x99\x84" M.Dock = "\xee\x8c\x8e" M.Domain = "\xee\x9f\xae" M.Done = "\xee\xa1\xb6" M.Done_all = "\xee\xa1\xb7" M.Donut_large = "\xee\xa4\x97" M.Donut_small = "\xee\xa4\x98" M.Drafts = "\xee\x85\x91" M.Drag_handle = "\xee\x89\x9d" M.Drive_eta = "\xee\x98\x93" M.Dvr = "\xee\x86\xb2" M.Edit = "\xee\x8f\x89" M.Edit_location = "\xee\x95\xa8" M.Eject = "\xee\xa3\xbb" M.Email = "\xee\x82\xbe" M.Enhanced_encryption = "\xee\x98\xbf" M.Equalizer = "\xee\x80\x9d" M.Error = "\xee\x80\x80" M.Error_outline = "\xee\x80\x81" M.Euro_symbol = "\xee\xa4\xa6" M.Ev_station = "\xee\x95\xad" M.Event = "\xee\xa1\xb8" M.Event_available = "\xee\x98\x94" M.Event_busy = "\xee\x98\x95" M.Event_note = "\xee\x98\x96" M.Event_seat = "\xee\xa4\x83" M.Exit_to_app = "\xee\xa1\xb9" M.Expand_less = "\xee\x97\x8e" M.Expand_more = "\xee\x97\x8f" M.Explicit = "\xee\x80\x9e" M.Explore = "\xee\xa1\xba" M.Exposure = "\xee\x8f\x8a" M.Exposure_neg_1 = "\xee\x8f\x8b" M.Exposure_neg_2 = "\xee\x8f\x8c" M.Exposure_plus_1 = "\xee\x8f\x8d" M.Exposure_plus_2 = "\xee\x8f\x8e" M.Exposure_zero = "\xee\x8f\x8f" M.Extension = "\xee\xa1\xbb" M.Face = "\xee\xa1\xbc" M.Fast_forward = "\xee\x80\x9f" M.Fast_rewind = "\xee\x80\xa0" M.Favorite = "\xee\xa1\xbd" M.Favorite_border = "\xee\xa1\xbe" M.Featured_play_list = "\xee\x81\xad" M.Featured_video = "\xee\x81\xae" M.Feedback = "\xee\xa1\xbf" M.Fiber_dvr = "\xee\x81\x9d" M.Fiber_manual_record = "\xee\x81\xa1" M.Fiber_new = "\xee\x81\x9e" M.Fiber_pin = "\xee\x81\xaa" M.Fiber_smart_record = "\xee\x81\xa2" M.File_download = "\xee\x8b\x84" M.File_upload = "\xee\x8b\x86" M.Filter = "\xee\x8f\x93" M.Filter_1 = "\xee\x8f\x90" M.Filter_2 = "\xee\x8f\x91" M.Filter_3 = "\xee\x8f\x92" M.Filter_4 = "\xee\x8f\x94" M.Filter_5 = "\xee\x8f\x95" M.Filter_6 = "\xee\x8f\x96" M.Filter_7 = "\xee\x8f\x97" M.Filter_8 = "\xee\x8f\x98" M.Filter_9 = "\xee\x8f\x99" M.Filter_9_plus = "\xee\x8f\x9a" M.Filter_b_and_w = "\xee\x8f\x9b" M.Filter_center_focus = "\xee\x8f\x9c" M.Filter_drama = "\xee\x8f\x9d" M.Filter_frames = "\xee\x8f\x9e" M.Filter_hdr = "\xee\x8f\x9f" M.Filter_list = "\xee\x85\x92" M.Filter_none = "\xee\x8f\xa0" M.Filter_tilt_shift = "\xee\x8f\xa2" M.Filter_vintage = "\xee\x8f\xa3" M.Find_in_page = "\xee\xa2\x80" M.Find_replace = "\xee\xa2\x81" M.Fingerprint = "\xee\xa4\x8d" M.First_page = "\xee\x97\x9c" M.Fitness_center = "\xee\xad\x83" M.Flag = "\xee\x85\x93" M.Flare = "\xee\x8f\xa4" M.Flash_auto = "\xee\x8f\xa5" M.Flash_off = "\xee\x8f\xa6" M.Flash_on = "\xee\x8f\xa7" M.Flight = "\xee\x94\xb9" M.Flight_land = "\xee\xa4\x84" M.Flight_takeoff = "\xee\xa4\x85" M.Flip = "\xee\x8f\xa8" M.Flip_to_back = "\xee\xa2\x82" M.Flip_to_front = "\xee\xa2\x83" M.Folder = "\xee\x8b\x87" M.Folder_open = "\xee\x8b\x88" M.Folder_shared = "\xee\x8b\x89" M.Folder_special = "\xee\x98\x97" M.Font_download = "\xee\x85\xa7" M.Format_align_center = "\xee\x88\xb4" M.Format_align_justify = "\xee\x88\xb5" M.Format_align_left = "\xee\x88\xb6" M.Format_align_right = "\xee\x88\xb7" M.Format_bold = "\xee\x88\xb8" M.Format_clear = "\xee\x88\xb9" M.Format_color_fill = "\xee\x88\xba" M.Format_color_reset = "\xee\x88\xbb" M.Format_color_text = "\xee\x88\xbc" M.Format_indent_decrease = "\xee\x88\xbd" M.Format_indent_increase = "\xee\x88\xbe" M.Format_italic = "\xee\x88\xbf" M.Format_line_spacing = "\xee\x89\x80" M.Format_list_bulleted = "\xee\x89\x81" M.Format_list_numbered = "\xee\x89\x82" M.Format_paint = "\xee\x89\x83" M.Format_quote = "\xee\x89\x84" M.Format_shapes = "\xee\x89\x9e" M.Format_size = "\xee\x89\x85" M.Format_strikethrough = "\xee\x89\x86" M.Format_textdirection_l_to_r = "\xee\x89\x87" M.Format_textdirection_r_to_l = "\xee\x89\x88" M.Format_underlined = "\xee\x89\x89" M.Forum = "\xee\x82\xbf" M.Forward = "\xee\x85\x94" M.Forward_10 = "\xee\x81\x96" M.Forward_30 = "\xee\x81\x97" M.Forward_5 = "\xee\x81\x98" M.Free_breakfast = "\xee\xad\x84" M.Fullscreen = "\xee\x97\x90" M.Fullscreen_exit = "\xee\x97\x91" M.Functions = "\xee\x89\x8a" M.G_translate = "\xee\xa4\xa7" M.Gamepad = "\xee\x8c\x8f" M.Games = "\xee\x80\xa1" M.Gavel = "\xee\xa4\x8e" M.Gesture = "\xee\x85\x95" M.Get_app = "\xee\xa2\x84" M.Gif = "\xee\xa4\x88" M.Golf_course = "\xee\xad\x85" M.Gps_fixed = "\xee\x86\xb3" M.Gps_not_fixed = "\xee\x86\xb4" M.Gps_off = "\xee\x86\xb5" M.Grade = "\xee\xa2\x85" M.Gradient = "\xee\x8f\xa9" M.Grain = "\xee\x8f\xaa" M.Graphic_eq = "\xee\x86\xb8" M.Grid_off = "\xee\x8f\xab" M.Grid_on = "\xee\x8f\xac" M.Group = "\xee\x9f\xaf" M.Group_add = "\xee\x9f\xb0" M.Group_work = "\xee\xa2\x86" M.Hd = "\xee\x81\x92" M.Hdr_off = "\xee\x8f\xad" M.Hdr_on = "\xee\x8f\xae" M.Hdr_strong = "\xee\x8f\xb1" M.Hdr_weak = "\xee\x8f\xb2" M.Headset = "\xee\x8c\x90" M.Headset_mic = "\xee\x8c\x91" M.Healing = "\xee\x8f\xb3" M.Hearing = "\xee\x80\xa3" M.Help = "\xee\xa2\x87" M.Help_outline = "\xee\xa3\xbd" M.High_quality = "\xee\x80\xa4" M.Highlight = "\xee\x89\x9f" M.Highlight_off = "\xee\xa2\x88" M.History = "\xee\xa2\x89" M.Home = "\xee\xa2\x8a" M.Hot_tub = "\xee\xad\x86" M.Hotel = "\xee\x94\xba" M.Hourglass_empty = "\xee\xa2\x8b" M.Hourglass_full = "\xee\xa2\x8c" M.Http = "\xee\xa4\x82" M.Https = "\xee\xa2\x8d" M.Image = "\xee\x8f\xb4" M.Image_aspect_ratio = "\xee\x8f\xb5" M.Import_contacts = "\xee\x83\xa0" M.Import_export = "\xee\x83\x83" M.Important_devices = "\xee\xa4\x92" M.Inbox = "\xee\x85\x96" M.Indeterminate_check_box = "\xee\xa4\x89" M.Info = "\xee\xa2\x8e" M.Info_outline = "\xee\xa2\x8f" M.Input = "\xee\xa2\x90" M.Insert_chart = "\xee\x89\x8b" M.Insert_comment = "\xee\x89\x8c" M.Insert_drive_file = "\xee\x89\x8d" M.Insert_emoticon = "\xee\x89\x8e" M.Insert_invitation = "\xee\x89\x8f" M.Insert_link = "\xee\x89\x90" M.Insert_photo = "\xee\x89\x91" M.Invert_colors = "\xee\xa2\x91" M.Invert_colors_off = "\xee\x83\x84" M.Iso = "\xee\x8f\xb6" M.Keyboard = "\xee\x8c\x92" M.Keyboard_arrow_down = "\xee\x8c\x93" M.Keyboard_arrow_left = "\xee\x8c\x94" M.Keyboard_arrow_right = "\xee\x8c\x95" M.Keyboard_arrow_up = "\xee\x8c\x96" M.Keyboard_backspace = "\xee\x8c\x97" M.Keyboard_capslock = "\xee\x8c\x98" M.Keyboard_hide = "\xee\x8c\x9a" M.Keyboard_return = "\xee\x8c\x9b" M.Keyboard_tab = "\xee\x8c\x9c" M.Keyboard_voice = "\xee\x8c\x9d" M.Kitchen = "\xee\xad\x87" M.Label = "\xee\xa2\x92" M.Label_outline = "\xee\xa2\x93" M.Landscape = "\xee\x8f\xb7" M.Language = "\xee\xa2\x94" M.Laptop = "\xee\x8c\x9e" M.Laptop_chromebook = "\xee\x8c\x9f" M.Laptop_mac = "\xee\x8c\xa0" M.Laptop_windows = "\xee\x8c\xa1" M.Last_page = "\xee\x97\x9d" M.Launch = "\xee\xa2\x95" M.Layers = "\xee\x94\xbb" M.Layers_clear = "\xee\x94\xbc" M.Leak_add = "\xee\x8f\xb8" M.Leak_remove = "\xee\x8f\xb9" M.Lens = "\xee\x8f\xba" M.Library_add = "\xee\x80\xae" M.Library_books = "\xee\x80\xaf" M.Library_music = "\xee\x80\xb0" M.Lightbulb_outline = "\xee\xa4\x8f" M.Line_style = "\xee\xa4\x99" M.Line_weight = "\xee\xa4\x9a" M.Linear_scale = "\xee\x89\xa0" M.Link = "\xee\x85\x97" M.Linked_camera = "\xee\x90\xb8" M.List = "\xee\xa2\x96" M.Live_help = "\xee\x83\x86" M.Live_tv = "\xee\x98\xb9" M.Local_activity = "\xee\x94\xbf" M.Local_airport = "\xee\x94\xbd" M.Local_atm = "\xee\x94\xbe" M.Local_bar = "\xee\x95\x80" M.Local_cafe = "\xee\x95\x81" M.Local_car_wash = "\xee\x95\x82" M.Local_convenience_store = "\xee\x95\x83" M.Local_dining = "\xee\x95\x96" M.Local_drink = "\xee\x95\x84" M.Local_florist = "\xee\x95\x85" M.Local_gas_station = "\xee\x95\x86" M.Local_grocery_store = "\xee\x95\x87" M.Local_hospital = "\xee\x95\x88" M.Local_hotel = "\xee\x95\x89" M.Local_laundry_service = "\xee\x95\x8a" M.Local_library = "\xee\x95\x8b" M.Local_mall = "\xee\x95\x8c" M.Local_movies = "\xee\x95\x8d" M.Local_offer = "\xee\x95\x8e" M.Local_parking = "\xee\x95\x8f" M.Local_pharmacy = "\xee\x95\x90" M.Local_phone = "\xee\x95\x91" M.Local_pizza = "\xee\x95\x92" M.Local_play = "\xee\x95\x93" M.Local_post_office = "\xee\x95\x94" M.Local_printshop = "\xee\x95\x95" M.Local_see = "\xee\x95\x97" M.Local_shipping = "\xee\x95\x98" M.Local_taxi = "\xee\x95\x99" M.Location_city = "\xee\x9f\xb1" M.Location_disabled = "\xee\x86\xb6" M.Location_off = "\xee\x83\x87" M.Location_on = "\xee\x83\x88" M.Location_searching = "\xee\x86\xb7" M.Lock = "\xee\xa2\x97" M.Lock_open = "\xee\xa2\x98" M.Lock_outline = "\xee\xa2\x99" M.Looks = "\xee\x8f\xbc" M.Looks_3 = "\xee\x8f\xbb" M.Looks_4 = "\xee\x8f\xbd" M.Looks_5 = "\xee\x8f\xbe" M.Looks_6 = "\xee\x8f\xbf" M.Looks_one = "\xee\x90\x80" M.Looks_two = "\xee\x90\x81" M.Loop = "\xee\x80\xa8" M.Loupe = "\xee\x90\x82" M.Low_priority = "\xee\x85\xad" M.Loyalty = "\xee\xa2\x9a" M.Mail = "\xee\x85\x98" M.Mail_outline = "\xee\x83\xa1" M.Map = "\xee\x95\x9b" M.Markunread = "\xee\x85\x99" M.Markunread_mailbox = "\xee\xa2\x9b" M.Memory = "\xee\x8c\xa2" M.Menu = "\xee\x97\x92" M.Merge_type = "\xee\x89\x92" M.Message = "\xee\x83\x89" M.Mic = "\xee\x80\xa9" M.Mic_none = "\xee\x80\xaa" M.Mic_off = "\xee\x80\xab" M.Mms = "\xee\x98\x98" M.Mode_comment = "\xee\x89\x93" M.Mode_edit = "\xee\x89\x94" M.Monetization_on = "\xee\x89\xa3" M.Money_off = "\xee\x89\x9c" M.Monochrome_photos = "\xee\x90\x83" M.Mood = "\xee\x9f\xb2" M.Mood_bad = "\xee\x9f\xb3" M.More = "\xee\x98\x99" M.More_horiz = "\xee\x97\x93" M.More_vert = "\xee\x97\x94" M.Motorcycle = "\xee\xa4\x9b" M.Mouse = "\xee\x8c\xa3" M.Move_to_inbox = "\xee\x85\xa8" M.Movie = "\xee\x80\xac" M.Movie_creation = "\xee\x90\x84" M.Movie_filter = "\xee\x90\xba" M.Multiline_chart = "\xee\x9b\x9f" M.Music_note = "\xee\x90\x85" M.Music_video = "\xee\x81\xa3" M.My_location = "\xee\x95\x9c" M.Nature = "\xee\x90\x86" M.Nature_people = "\xee\x90\x87" M.Navigate_before = "\xee\x90\x88" M.Navigate_next = "\xee\x90\x89" M.Navigation = "\xee\x95\x9d" M.Near_me = "\xee\x95\xa9" M.Network_cell = "\xee\x86\xb9" M.Network_check = "\xee\x99\x80" M.Network_locked = "\xee\x98\x9a" M.Network_wifi = "\xee\x86\xba" M.New_releases = "\xee\x80\xb1" M.Next_week = "\xee\x85\xaa" M.Nfc = "\xee\x86\xbb" M.No_encryption = "\xee\x99\x81" M.No_sim = "\xee\x83\x8c" M.Not_interested = "\xee\x80\xb3" M.Note = "\xee\x81\xaf" M.Note_add = "\xee\xa2\x9c" M.Notifications = "\xee\x9f\xb4" M.Notifications_active = "\xee\x9f\xb7" M.Notifications_none = "\xee\x9f\xb5" M.Notifications_off = "\xee\x9f\xb6" M.Notifications_paused = "\xee\x9f\xb8" M.Offline_pin = "\xee\xa4\x8a" M.Ondemand_video = "\xee\x98\xba" M.Opacity = "\xee\xa4\x9c" M.Open_in_browser = "\xee\xa2\x9d" M.Open_in_new = "\xee\xa2\x9e" M.Open_with = "\xee\xa2\x9f" M.Pages = "\xee\x9f\xb9" M.Pageview = "\xee\xa2\xa0" M.Palette = "\xee\x90\x8a" M.Pan_tool = "\xee\xa4\xa5" M.Panorama = "\xee\x90\x8b" M.Panorama_fish_eye = "\xee\x90\x8c" M.Panorama_horizontal = "\xee\x90\x8d" M.Panorama_vertical = "\xee\x90\x8e" M.Panorama_wide_angle = "\xee\x90\x8f" M.Party_mode = "\xee\x9f\xba" M.Pause = "\xee\x80\xb4" M.Pause_circle_filled = "\xee\x80\xb5" M.Pause_circle_outline = "\xee\x80\xb6" M.Payment = "\xee\xa2\xa1" M.People = "\xee\x9f\xbb" M.People_outline = "\xee\x9f\xbc" M.Perm_camera_mic = "\xee\xa2\xa2" M.Perm_contact_calendar = "\xee\xa2\xa3" M.Perm_data_setting = "\xee\xa2\xa4" M.Perm_device_information = "\xee\xa2\xa5" M.Perm_identity = "\xee\xa2\xa6" M.Perm_media = "\xee\xa2\xa7" M.Perm_phone_msg = "\xee\xa2\xa8" M.Perm_scan_wifi = "\xee\xa2\xa9" M.Person = "\xee\x9f\xbd" M.Person_add = "\xee\x9f\xbe" M.Person_outline = "\xee\x9f\xbf" M.Person_pin = "\xee\x95\x9a" M.Person_pin_circle = "\xee\x95\xaa" M.Personal_video = "\xee\x98\xbb" M.Pets = "\xee\xa4\x9d" M.Phone = "\xee\x83\x8d" M.Phone_android = "\xee\x8c\xa4" M.Phone_bluetooth_speaker = "\xee\x98\x9b" M.Phone_forwarded = "\xee\x98\x9c" M.Phone_in_talk = "\xee\x98\x9d" M.Phone_iphone = "\xee\x8c\xa5" M.Phone_locked = "\xee\x98\x9e" M.Phone_missed = "\xee\x98\x9f" M.Phone_paused = "\xee\x98\xa0" M.Phonelink = "\xee\x8c\xa6" M.Phonelink_erase = "\xee\x83\x9b" M.Phonelink_lock = "\xee\x83\x9c" M.Phonelink_off = "\xee\x8c\xa7" M.Phonelink_ring = "\xee\x83\x9d" M.Phonelink_setup = "\xee\x83\x9e" M.Photo = "\xee\x90\x90" M.Photo_album = "\xee\x90\x91" M.Photo_camera = "\xee\x90\x92" M.Photo_filter = "\xee\x90\xbb" M.Photo_library = "\xee\x90\x93" M.Photo_size_select_actual = "\xee\x90\xb2" M.Photo_size_select_large = "\xee\x90\xb3" M.Photo_size_select_small = "\xee\x90\xb4" M.Picture_as_pdf = "\xee\x90\x95" M.Picture_in_picture = "\xee\xa2\xaa" M.Picture_in_picture_alt = "\xee\xa4\x91" M.Pie_chart = "\xee\x9b\x84" M.Pie_chart_outlined = "\xee\x9b\x85" M.Pin_drop = "\xee\x95\x9e" M.Place = "\xee\x95\x9f" M.Play_arrow = "\xee\x80\xb7" M.Play_circle_filled = "\xee\x80\xb8" M.Play_circle_outline = "\xee\x80\xb9" M.Play_for_work = "\xee\xa4\x86" M.Playlist_add = "\xee\x80\xbb" M.Playlist_add_check = "\xee\x81\xa5" M.Playlist_play = "\xee\x81\x9f" M.Plus_one = "\xee\xa0\x80" M.Poll = "\xee\xa0\x81" M.Polymer = "\xee\xa2\xab" M.Pool = "\xee\xad\x88" M.Portable_wifi_off = "\xee\x83\x8e" M.Portrait = "\xee\x90\x96" M.Power = "\xee\x98\xbc" M.Power_input = "\xee\x8c\xb6" M.Power_settings_new = "\xee\xa2\xac" M.Pregnant_woman = "\xee\xa4\x9e" M.Present_to_all = "\xee\x83\x9f" M.Print = "\xee\xa2\xad" M.Priority_high = "\xee\x99\x85" M.Public = "\xee\xa0\x8b" M.Publish = "\xee\x89\x95" M.Query_builder = "\xee\xa2\xae" M.Question_answer = "\xee\xa2\xaf" M.Queue = "\xee\x80\xbc" M.Queue_music = "\xee\x80\xbd" M.Queue_play_next = "\xee\x81\xa6" M.Radio = "\xee\x80\xbe" M.Radio_button_checked = "\xee\xa0\xb7" M.Radio_button_unchecked = "\xee\xa0\xb6" M.Rate_review = "\xee\x95\xa0" M.Receipt = "\xee\xa2\xb0" M.Recent_actors = "\xee\x80\xbf" M.Record_voice_over = "\xee\xa4\x9f" M.Redeem = "\xee\xa2\xb1" M.Redo = "\xee\x85\x9a" M.Refresh = "\xee\x97\x95" M.Remove = "\xee\x85\x9b" M.Remove_circle = "\xee\x85\x9c" M.Remove_circle_outline = "\xee\x85\x9d" M.Remove_from_queue = "\xee\x81\xa7" M.Remove_red_eye = "\xee\x90\x97" M.Remove_shopping_cart = "\xee\xa4\xa8" M.Reorder = "\xee\xa3\xbe" M.Repeat = "\xee\x81\x80" M.Repeat_one = "\xee\x81\x81" M.Replay = "\xee\x81\x82" M.Replay_10 = "\xee\x81\x99" M.Replay_30 = "\xee\x81\x9a" M.Replay_5 = "\xee\x81\x9b" M.Reply = "\xee\x85\x9e" M.Reply_all = "\xee\x85\x9f" M.Report = "\xee\x85\xa0" M.Report_problem = "\xee\xa2\xb2" M.Restaurant = "\xee\x95\xac" M.Restaurant_menu = "\xee\x95\xa1" M.Restore = "\xee\xa2\xb3" M.Restore_page = "\xee\xa4\xa9" M.Ring_volume = "\xee\x83\x91" M.Room = "\xee\xa2\xb4" M.Room_service = "\xee\xad\x89" M.Rotate_90_degrees_ccw = "\xee\x90\x98" M.Rotate_left = "\xee\x90\x99" M.Rotate_right = "\xee\x90\x9a" M.Rounded_corner = "\xee\xa4\xa0" M.Router = "\xee\x8c\xa8" M.Rowing = "\xee\xa4\xa1" M.Rss_feed = "\xee\x83\xa5" M.Rv_hookup = "\xee\x99\x82" M.Satellite = "\xee\x95\xa2" M.Save = "\xee\x85\xa1" M.Scanner = "\xee\x8c\xa9" M.Schedule = "\xee\xa2\xb5" M.School = "\xee\xa0\x8c" M.Screen_lock_landscape = "\xee\x86\xbe" M.Screen_lock_portrait = "\xee\x86\xbf" M.Screen_lock_rotation = "\xee\x87\x80" M.Screen_rotation = "\xee\x87\x81" M.Screen_share = "\xee\x83\xa2" M.Sd_card = "\xee\x98\xa3" M.Sd_storage = "\xee\x87\x82" M.Search = "\xee\xa2\xb6" M.Security = "\xee\x8c\xaa" M.Select_all = "\xee\x85\xa2" M.Send = "\xee\x85\xa3" M.Sentiment_dissatisfied = "\xee\xa0\x91" M.Sentiment_neutral = "\xee\xa0\x92" M.Sentiment_satisfied = "\xee\xa0\x93" M.Sentiment_very_dissatisfied = "\xee\xa0\x94" M.Sentiment_very_satisfied = "\xee\xa0\x95" M.Settings = "\xee\xa2\xb8" M.Settings_applications = "\xee\xa2\xb9" M.Settings_backup_restore = "\xee\xa2\xba" M.Settings_bluetooth = "\xee\xa2\xbb" M.Settings_brightness = "\xee\xa2\xbd" M.Settings_cell = "\xee\xa2\xbc" M.Settings_ethernet = "\xee\xa2\xbe" M.Settings_input_antenna = "\xee\xa2\xbf" M.Settings_input_component = "\xee\xa3\x80" M.Settings_input_composite = "\xee\xa3\x81" M.Settings_input_hdmi = "\xee\xa3\x82" M.Settings_input_svideo = "\xee\xa3\x83" M.Settings_overscan = "\xee\xa3\x84" M.Settings_phone = "\xee\xa3\x85" M.Settings_power = "\xee\xa3\x86" M.Settings_remote = "\xee\xa3\x87" M.Settings_system_daydream = "\xee\x87\x83" M.Settings_voice = "\xee\xa3\x88" M.Share = "\xee\xa0\x8d" M.Shop = "\xee\xa3\x89" M.Shop_two = "\xee\xa3\x8a" M.Shopping_basket = "\xee\xa3\x8b" M.Shopping_cart = "\xee\xa3\x8c" M.Short_text = "\xee\x89\xa1" M.Show_chart = "\xee\x9b\xa1" M.Shuffle = "\xee\x81\x83" M.Signal_cellular_4_bar = "\xee\x87\x88" M.Signal_cellular_connected_no_internet_4_bar = "\xee\x87\x8d" M.Signal_cellular_no_sim = "\xee\x87\x8e" M.Signal_cellular_null = "\xee\x87\x8f" M.Signal_cellular_off = "\xee\x87\x90" M.Signal_wifi_4_bar = "\xee\x87\x98" M.Signal_wifi_4_bar_lock = "\xee\x87\x99" M.Signal_wifi_off = "\xee\x87\x9a" M.Sim_card = "\xee\x8c\xab" M.Sim_card_alert = "\xee\x98\xa4" M.Skip_next = "\xee\x81\x84" M.Skip_previous = "\xee\x81\x85" M.Slideshow = "\xee\x90\x9b" M.Slow_motion_video = "\xee\x81\xa8" M.Smartphone = "\xee\x8c\xac" M.Smoke_free = "\xee\xad\x8a" M.Smoking_rooms = "\xee\xad\x8b" M.Sms = "\xee\x98\xa5" M.Sms_failed = "\xee\x98\xa6" M.Snooze = "\xee\x81\x86" M.Sort = "\xee\x85\xa4" M.Sort_by_alpha = "\xee\x81\x93" M.Spa = "\xee\xad\x8c" M.Space_bar = "\xee\x89\x96" M.Speaker = "\xee\x8c\xad" M.Speaker_group = "\xee\x8c\xae" M.Speaker_notes = "\xee\xa3\x8d" M.Speaker_notes_off = "\xee\xa4\xaa" M.Speaker_phone = "\xee\x83\x92" M.Spellcheck = "\xee\xa3\x8e" M.Star = "\xee\xa0\xb8" M.Star_border = "\xee\xa0\xba" M.Star_half = "\xee\xa0\xb9" M.Stars = "\xee\xa3\x90" M.Stay_current_landscape = "\xee\x83\x93" M.Stay_current_portrait = "\xee\x83\x94" M.Stay_primary_landscape = "\xee\x83\x95" M.Stay_primary_portrait = "\xee\x83\x96" M.Stop = "\xee\x81\x87" M.Stop_screen_share = "\xee\x83\xa3" M.Storage = "\xee\x87\x9b" M.Store = "\xee\xa3\x91" M.Store_mall_directory = "\xee\x95\xa3" M.Straighten = "\xee\x90\x9c" M.Streetview = "\xee\x95\xae" M.Strikethrough_s = "\xee\x89\x97" M.Style = "\xee\x90\x9d" M.Subdirectory_arrow_left = "\xee\x97\x99" M.Subdirectory_arrow_right = "\xee\x97\x9a" M.Subject = "\xee\xa3\x92" M.Subscriptions = "\xee\x81\xa4" M.Subtitles = "\xee\x81\x88" M.Subway = "\xee\x95\xaf" M.Supervisor_account = "\xee\xa3\x93" M.Surround_sound = "\xee\x81\x89" M.Swap_calls = "\xee\x83\x97" M.Swap_horiz = "\xee\xa3\x94" M.Swap_vert = "\xee\xa3\x95" M.Swap_vertical_circle = "\xee\xa3\x96" M.Switch_camera = "\xee\x90\x9e" M.Switch_video = "\xee\x90\x9f" M.Sync = "\xee\x98\xa7" M.Sync_disabled = "\xee\x98\xa8" M.Sync_problem = "\xee\x98\xa9" M.System_update = "\xee\x98\xaa" M.System_update_alt = "\xee\xa3\x97" M.Tab = "\xee\xa3\x98" M.Tab_unselected = "\xee\xa3\x99" M.Tablet = "\xee\x8c\xaf" M.Tablet_android = "\xee\x8c\xb0" M.Tablet_mac = "\xee\x8c\xb1" M.Tag_faces = "\xee\x90\xa0" M.Tap_and_play = "\xee\x98\xab" M.Terrain = "\xee\x95\xa4" M.Text_fields = "\xee\x89\xa2" M.Text_format = "\xee\x85\xa5" M.Textsms = "\xee\x83\x98" M.Texture = "\xee\x90\xa1" M.Theaters = "\xee\xa3\x9a" M.Thumb_down = "\xee\xa3\x9b" M.Thumb_up = "\xee\xa3\x9c" M.Thumbs_up_down = "\xee\xa3\x9d" M.Time_to_leave = "\xee\x98\xac" M.Timelapse = "\xee\x90\xa2" M.Timeline = "\xee\xa4\xa2" M.Timer = "\xee\x90\xa5" M.Timer_10 = "\xee\x90\xa3" M.Timer_3 = "\xee\x90\xa4" M.Timer_off = "\xee\x90\xa6" M.Title = "\xee\x89\xa4" M.Toc = "\xee\xa3\x9e" M.Today = "\xee\xa3\x9f" M.Toll = "\xee\xa3\xa0" M.Tonality = "\xee\x90\xa7" M.Touch_app = "\xee\xa4\x93" M.Toys = "\xee\x8c\xb2" M.Track_changes = "\xee\xa3\xa1" M.Traffic = "\xee\x95\xa5" M.Train = "\xee\x95\xb0" M.Tram = "\xee\x95\xb1" M.Transfer_within_a_station = "\xee\x95\xb2" M.Transform = "\xee\x90\xa8" M.Translate = "\xee\xa3\xa2" M.Trending_down = "\xee\xa3\xa3" M.Trending_flat = "\xee\xa3\xa4" M.Trending_up = "\xee\xa3\xa5" M.Tune = "\xee\x90\xa9" M.Turned_in = "\xee\xa3\xa6" M.Turned_in_not = "\xee\xa3\xa7" M.Tv = "\xee\x8c\xb3" M.Unarchive = "\xee\x85\xa9" M.Undo = "\xee\x85\xa6" M.Unfold_less = "\xee\x97\x96" M.Unfold_more = "\xee\x97\x97" M.Update = "\xee\xa4\xa3" M.Usb = "\xee\x87\xa0" M.Verified_user = "\xee\xa3\xa8" M.Vertical_align_bottom = "\xee\x89\x98" M.Vertical_align_center = "\xee\x89\x99" M.Vertical_align_top = "\xee\x89\x9a" M.Vibration = "\xee\x98\xad" M.Video_call = "\xee\x81\xb0" M.Video_label = "\xee\x81\xb1" M.Video_library = "\xee\x81\x8a" M.Videocam = "\xee\x81\x8b" M.Videocam_off = "\xee\x81\x8c" M.Videogame_asset = "\xee\x8c\xb8" M.View_agenda = "\xee\xa3\xa9" M.View_array = "\xee\xa3\xaa" M.View_carousel = "\xee\xa3\xab" M.View_column = "\xee\xa3\xac" M.View_comfy = "\xee\x90\xaa" M.View_compact = "\xee\x90\xab" M.View_day = "\xee\xa3\xad" M.View_headline = "\xee\xa3\xae" M.View_list = "\xee\xa3\xaf" M.View_module = "\xee\xa3\xb0" M.View_quilt = "\xee\xa3\xb1" M.View_stream = "\xee\xa3\xb2" M.View_week = "\xee\xa3\xb3" M.Vignette = "\xee\x90\xb5" M.Visibility = "\xee\xa3\xb4" M.Visibility_off = "\xee\xa3\xb5" M.Voice_chat = "\xee\x98\xae" M.Voicemail = "\xee\x83\x99" M.Volume_down = "\xee\x81\x8d" M.Volume_mute = "\xee\x81\x8e" M.Volume_off = "\xee\x81\x8f" M.Volume_up = "\xee\x81\x90" M.Vpn_key = "\xee\x83\x9a" M.Vpn_lock = "\xee\x98\xaf" M.Wallpaper = "\xee\x86\xbc" M.Warning = "\xee\x80\x82" M.Watch = "\xee\x8c\xb4" M.Watch_later = "\xee\xa4\xa4" M.Wb_auto = "\xee\x90\xac" M.Wb_cloudy = "\xee\x90\xad" M.Wb_incandescent = "\xee\x90\xae" M.Wb_iridescent = "\xee\x90\xb6" M.Wb_sunny = "\xee\x90\xb0" M.Wc = "\xee\x98\xbd" M.Web = "\xee\x81\x91" M.Web_asset = "\xee\x81\xa9" M.Weekend = "\xee\x85\xab" M.Whatshot = "\xee\xa0\x8e" M.Widgets = "\xee\x86\xbd" M.Wifi = "\xee\x98\xbe" M.Wifi_lock = "\xee\x87\xa1" M.Wifi_tethering = "\xee\x87\xa2" M.Work = "\xee\xa3\xb9" M.Wrap_text = "\xee\x89\x9b" M.Youtube_searched_for = "\xee\xa3\xba" M.Zoom_in = "\xee\xa3\xbf" M.Zoom_out = "\xee\xa4\x80" M.Zoom_out_map = "\xee\x95\xab" return M
local class = require("pl.class") local ChannelAudience = require("core.ChannelAudience"); local tablex = require("pl.tablex") ---@class WorldAudience : ChannelAudience local M = class(ChannelAudience) function M:getBroadcastTargets() return tablex.filter(tablex.values(self.state.PlayerManager.players), function(player, _) return player ~= self.sender end) -- return this.state.PlayerManager.filter(player => player !== this.sender); end return M
local m = require "luadiff" assert(m.diff("", "") == 0, "Empty strings should have diff equal to zero") assert(m.diff(" ", " ") == 0, "Characters should have diff equal to zero") assert(m.diff("algo", "algo") == 0, "Strings without spaces should have diff equal to zero") assert(m.diff("algo assim", "algo assim") == 0, "Strings with spaces should have diff equal to zero") assert(m.diff("a", "") ~= 0, "Characters and empty strings should have diff different from zero") assert(m.diff("a", " ") ~= 0, "Different characters should have diff different from zero") assert(m.diff("abc", "abd") ~= 0, "Different strings should have diff different from zero") assert(m.diff("space", "s p a c e") ~= 0, "Additional spaces should not make diff different from zero") assert(m.diff("lspace", " lspace") ~= 0, "Left space should not make diff different from zero") assert(m.diff("rspace", "rspace ") ~= 0, "Right space should not make diff different from zero") assert(m.diff("case-sensitive", "CaSe-SeNsitIvE") ~= 0, "Diff should be case-sensitive")
WeaponTypes.addType("SpreadFire", "Spreadfire Cannon", armed)
_G.GhostMode = _G.GhostMode or {} GhostMode._path = ModPath GhostMode._data_path = SavePath .. "ghost_mode_data.json" GhostMode._data = {} --[[ Menu logics ]] function GhostMode:Save() local file = io.open(self._data_path, "w+") if file then file:write(json.encode(self._data)) file:close() end end function GhostMode:Load() local file = io.open(self._data_path, "r") if file then self._data = json.decode(file:read("*all")) file:close() end end function isGMEnabled() if GhostMode._data.enable_value == nil then GhostMode:Load() end return GhostMode._data.enable_value end Hooks:Add("LocalizationManagerPostInit", "LocalizationManagerPostInit_GhostMode", function(loc) loc:load_localization_file(GhostMode._path .. "loc/en.json") end) Hooks:Add("MenuManagerInitialize", "MenuManagerInitialize_GhostMode", function(menu_manager) MenuCallbackHandler.ghost_mode_callback_enable_toggle = function(self, item) GhostMode._data.enable_value = (item:value() == "on" and true or false) GhostMode:Save() log("Toggle is: " .. item:value()) end GhostMode:Load() MenuHelper:LoadFromJsonFile(GhostMode._path .. "menu.json", GhostMode, GhostMode._data) end) --[[ Mod logics ]] if isGMEnabled() == true then function GroupAIStateBase:_clbk_switch_enemies_to_not_cool() end function PlayerMovement:on_suspicion(observer_unit, status) end function GroupAIStateBase:on_criminal_suspicion_progress(u_suspect, u_observer, status) end function GroupAIStateBase:criminal_spotted(unit) end function GroupAIStateBase:report_aggression(unit) end function PlayerMovement:on_uncovered(enemy_unit) end function SecurityCamera:_upd_suspicion(t) end function SecurityCamera:_sound_the_alarm(detected_unit) end function SecurityCamera:_set_suspicion_sound(suspicion_level) end function SecurityCamera:clbk_call_the_police() end function CopMovement:anim_clbk_police_called(unit) end function CopLogicArrest._upd_enemy_detection(data) end function CopLogicArrest._call_the_police(data, my_data, paniced) end function CopLogicIdle.on_alert(data, alert_data) end function CopLogicBase._get_logic_state_from_reaction(data, reaction) return "idle" end function GroupAIStateBase:sync_event(event_id, blame_id) end function GroupAIStateBase:on_police_called(called_reason) end function GroupAIStateBase:on_police_weapons_hot(called_reason) end function GroupAIStateBase:on_gangster_weapons_hot(called_reason) end function GroupAIStateBase:on_enemy_weapons_hot(is_delayed_callback) end function GroupAIStateBase:_clbk_switch_enemies_to_not_cool() end end
--------------------------------------------------------------------------- -- A layout with widgets added at specific positions. -- -- Use cases include desktop icons, complex custom composed widgets, a floating -- client layout and fine grained control over the output. -- -- -- @author Emmanuel Lepage Vallee -- @copyright 2016 Emmanuel Lepage Vallee -- @classmod wibox.layout.manual --------------------------------------------------------------------------- local gtable = require("gears.table") local base = require("wibox.widget.base") local unpack = unpack or table.unpack -- luacheck: globals unpack (compatibility with Lua 5.1) local manual_layout = {} --- Add some widgets to the given stack layout -- @param layout The layout you are modifying. -- @tparam widget ... Widgets that should be added -- @name add -- @class function --- Remove a widget from the layout -- @tparam index The widget index to remove -- @treturn boolean index If the operation is successful -- @name remove -- @class function --- Insert a new widget in the layout at position `index` -- @tparam number index The position -- @param widget The widget -- @treturn boolean If the operation is successful -- @name insert -- @class function function manual_layout:insert(index, widget) table.insert(self._private.widgets, index, widget) -- Add the point if widget.point then table.insert(self._private.pos, index, widget.point) end self:emit_signal("widget::layout_changed") end --- Remove one or more widgets from the layout -- The last parameter can be a boolean, forcing a recursive seach of the -- widget(s) to remove. -- @param widget ... Widgets that should be removed (must at least be one) -- @treturn boolean If the operation is successful -- @name remove_widgets -- @class function function manual_layout:fit(_, width, height) return width, height end local function geometry(self, new) self._new_geo = new return self._new_geo or self end function manual_layout:layout(context, width, height) local res = {} for k, v in ipairs(self._private.widgets) do local pt = self._private.pos[k] or {x=0,y=0} local w, h = base.fit_widget(self, context, v, width, height) -- Make sure the signature is compatible with `awful.placement`. `Wibox`, -- doesn't depend on `awful`, but it is still nice not to have to code -- geometry functions again and again. if type(pt) == "function" or (getmetatable(pt) or {}).__call then local geo = { x = 0, y = 0, width = w, height = h, geometry = geometry, } pt = pt(geo, { parent = { x=0, y=0, width = width, height = height, geometry = geometry } }) -- Trick to ensure compatibility with `awful.placement` gtable.crush(pt, geo._new_geo or {}) end assert(pt.x) assert(pt.y) table.insert(res, base.place_widget_at( v, pt.x, pt.y, pt.width or w, pt.height or h )) end return res end function manual_layout:add(...) local wdgs = {...} local old_count = #self._private.widgets gtable.merge(self._private.widgets, {...}) -- Add the points for k, v in ipairs(wdgs) do if v.point then self._private.pos[old_count+k] = v.point end end self:emit_signal("widget::layout_changed") end --- Add a widget at a specific point. -- -- The point can either be a function or a table. The table follow the generic -- geometry format used elsewhere in Awesome. -- -- * *x*: The horizontal position. -- * *y*: The vertical position. -- * *width*: The width. -- * *height*: The height. -- -- If a function is used, it follows the same prototype as `awful.placement` -- functions. -- -- * *geo*: -- * *x*: The horizontal position (always 0). -- * *y*: The vertical position (always 0). -- * *width*: The width. -- * *height*: The height. -- * *geometry*: A function to get or set the geometry (for compatibility). -- The function is compatible with the `awful.placement` prototype. -- * *args*: -- * *parent* The layout own geometry -- * *x*: The horizontal position (always 0). -- * *y*: The vertical position (always 0). -- * *width*: The width. -- * *height*: The height. -- * *geometry*: A function to get or set the geometry (for compatibility) -- The function is compatible with the `awful.placement` prototype. -- -- -- @tparam widget widget The widget. -- @tparam table|function point Either an `{x=x,y=y}` table or a function -- returning the new geometry. function manual_layout:add_at(widget, point) assert(not widget.point, "2 points are specified, only one is supported") -- Check is the point function is valid if type(point) == "function" or (getmetatable(point) or {}).__call then local fake_geo = {x=0,y=0,width=1,height=1,geometry=geometry} local pt = point(fake_geo, { parent = { x=0, y=0, width = 10, height = 10, geometry = geometry } }) assert(pt and pt.x and pt.y, "The point function doesn't seem to be valid") end self._private.pos[#self._private.widgets+1] = point self:add(widget) end --- Move a widget (by index). -- @tparam number index The widget index. -- @tparam table|function point A new point value. -- @see add_at function manual_layout:move(index, point) assert(self._private.pos[index]) self._private.pos[index] = point self:emit_signal( "widget::layout_changed" ) end --- Move a widget. -- -- -- @tparam widget widget The widget. -- @tparam table|function point A new point value. -- @see add_at function manual_layout:move_widget(widget, point) local idx, l = self:index(widget, false) if idx then l:move(idx, point) end end function manual_layout:get_children() return self._private.widgets end function manual_layout:set_children(children) self:reset() self:add(unpack(children)) end function manual_layout:reset() self._private.widgets = {} self._private.pos = {} self:emit_signal( "widget::layout_changed" ) end --- Create a manual layout. -- @tparam table ... Widgets to add to the layout. local function new_manual(...) local ret = base.make_widget(nil, nil, {enable_properties = true}) gtable.crush(ret, manual_layout, true) ret._private.widgets = {} ret._private.pos = {} ret:add(...) return ret end -- -- return setmetatable(manual_layout, {__call=function(_,...) return new_manual(...) end})
T = require't' Pack = require( "t.Pack" ) Test = require( "t.Test" ) Buffer = require( "t.Buffer" ) Oht = require( "t.OrderedHashTable" ) pprint = require( "t.Table" ).pprint equals = require( "t" ).equals prxIdx = require( "t" ).proxyTableIndex utl = T.require('t_pck_utl') -- 0 1 2 3 4 5 6 7 -- 0000 0001 0010 0011 0100 0101 0110 0111 -- 8 9 A B C D E F -- 1000 1001 1010 1011 1100 1101 1110 1111 -- idx: 1 2 3 4 5 6 7 8 9 10 111213141516 17 -- dec: -7 85 -4 -3 -2 -1 0 1 2 3 -3692 t f 0 1 0 -1 -- bin: 1001 1010101 100 101 110 111 000 001 010 011 111000110010100 1 0 0 1 0 1 -- bin: 10011010 10110010 11101110 00001010 01111100 01100101 00100101 -- val = Oht( { threeUInt = 6373987 } , { twoIntegs = 25924 } , { twoBytes = Oht( { signedByte = -61 } , { unsignByte = 188 } ) } , { bits = { -7, 85 , {-4, -3, -2, -1, 0, 1, 2, 3} , -3692, true, false, 0, 1, 0, -1 } } , { fiveSInt = 311004130124 } , { fourSInt = 1349471853 } , { signShort = -18749 } ) v = { threeUInt = 6373987 , twoIntegs = 25924 , twoBytes = { signedByte = -61 , unsignByte = 188 } , bits = { -7, 85 , {-4, -3, -2, -1, 0, 1, 2, 3} , -3692, true, false, 0, 1, 0, -1 } , fiveSInt = 311004130124 , fourSInt = 1349471853 , signShort = -18749 } p = Pack( { threeUInt = '>I3' } , { twoIntegs = '<i2' } , { twoBytes = Pack( { signedByte = 'b' } , { unsignByte = 'B' } ) } , { bits = Pack( 'r4','R7',Pack( 'r3', 8 ),'r15','v','v','R1','R1','r1','r1' ) } , { fiveSInt = '>I5' } , { fourSInt = '<I4' } , { signShort = 'h' } ) b = Buffer( 'aBcDeü' .. string.char( 0x9A, 0xB2, 0xEE, 0x0A, 0x7C, 0x65, 0x25 ) .. 'HiJkLmNoPö' ) utl.get(p,b) b1 = Buffer( #b ) -- create empty buffer of #b length print( b1:toHex(), '', '', #b1 ) -- expecting all zeros utl.set(p,b1,v) print( b1:toHex(), '', '', #b1, b1:read() ) -- expecting same as buffer b x=p(b1) print('-----------------') pprint(x) print('-----------------') pprint(val[prxIdx]) print('-----------------') assert( x == val, "The input and output shall be identical" )
-- event.lua local M = {} local manager = { events = {} } M.notify = function(event, data) if not manager.events[event] then return end for _,callback in ipairs(manager.events[event]) do callback(data) end end M.subscribe = function(event, callback) if not manager.events[event] then manager.events[event] = {} end table.insert(manager.events[event], callback) end return M
local qcfg = require 'Q/UTILS/lua/qcfg' local qconsts = require 'Q/UTILS/lua/qconsts' local incdir = "../gen_inc/" local srcdir = "../gen_src/" local plpath = require 'pl.path' if ( not plpath.isdir(srcdir) ) then plpath.mkdir(srcdir) end if ( not plpath.isdir(incdir) ) then plpath.mkdir(incdir) end local gen_code = require 'Q/UTILS/lua/gen_code' --OLD local tmpl = qconsts.Q_SRC_ROOT .. '/OPERATORS/IDX_SORT/lua/idx_qsort.tmpl' local tmpl = qcfg.q_src_root .. '/OPERATORS/IDX_SORT/lua/idx_qsort.tmpl' ordrs = { 'asc', 'dsc' } val_qtypes = { "I1", "I2", "I4", "I8", "F4", "F8" } idx_qtypes = { "I1", "I2", "I4", "I8" } for i, ordr in ipairs(ordrs) do for j, val_qtype in ipairs(val_qtypes) do for k, idx_qtype in ipairs(idx_qtypes) do local subs = {} subs.srcdir = "OPERATORS/IDX_SORT/gen_src/" subs.incdir = "OPERATORS/IDX_SORT/gen_inc/" subs.fn = qsort_ subs.srt_ordr = ordr subs.val_qtype = val_qtype subs.val_ctype = qconsts.qtypes[val_qtype].ctype subs.idx_qtype = idx_qtype subs.idx_ctype = qconsts.qtypes[idx_qtype].ctype subs.fn = "qsort_" .. subs.srt_ordr .. "_val_" .. subs.val_qtype .. "_idx_" .. subs.idx_qtype -- TODO Check below is correct order/comparator combo if ordr == "asc" then c = "<" end if ordr == "dsc" then c = ">" end subs.comparator = c subs.tmpl = tmpl --====================== gen_code.doth(subs, subs.incdir) gen_code.dotc(subs, subs.srcdir) end end end print("Succesfully completed " .. arg[0])
local success, config = pcall(function() return json.fromString(remodel.readFile("deployment.json")) end) if not success then error("Could not read deployment.json: " .. config) end local branchName = io.popen("git rev-parse --abbrev-ref HEAD"):read("*l") local commitSHA = io.popen("git rev-parse HEAD"):read("*l") local assetId do local targetType = type(config.target) if targetType == "string" then assetId = config.target elseif targetType == "table" then assetId = config.target[branchName] if not assetId then error("Could not find asset ID for branch ".. branchName) end elseif targetType ~= "nil" then error("Invalid targetType: ".. targetType) end end local paths = config.files do local pathsType = type(paths) if pathsType ~= "table" then error("Invalid pathsType: ".. pathsType) end end return { Branch = branchName, Commit = commitSHA, AssetId = assetId, IncludeMetadata = config.includeMetadata, Paths = config.files, }
-- test luacheck -- if there is a error, luacheck does NOT show warnings local foo = true local function bar() end
module("luci.controller.vlmcsd", package.seeall) function index() if not nixio.fs.access("/etc/config/vlmcsd") then return end entry({"admin", "services", "vlmcsd"}, cbi("vlmcsd"), _("KMS Server"), 100).dependent = true entry({"admin", "services", "vlmcsd", "status"}, call("act_status")).leaf = true end function act_status() local e={} e.running=luci.sys.call("pgrep vlmcsd >/dev/null")==0 luci.http.prepare_content("application/json") luci.http.write_json(e) end
local ngx_agent = ngx.var.http_user_agent local ngx_host = ngx.var.host local ngx_status = ngx.var.status local ngx_request_time = tonumber(ngx.var.request_time) local ngx_scheme = ngx.var.scheme local ngx_ssl_session_reused = ngx.var.ssl_session_reused local ngx_xlocation = "" if ngx.var.xlocation ~= nil and ngx.var.xlocation ~= "" then ngx_xlocation = ngx.var.xlocation end ---- 请求次数统计(域名维度) metric_requests:inc(1, {ngx_host, ngx_xlocation}) ---- 状态码统计 metric_requests_status:inc(1, {ngx_host, ngx_status, ngx_xlocation}) ---- bytes_sent local ngx_bytes_sent = tonumber(ngx.var.bytes_sent) if ngx_bytes_sent then -- 如果获取不到值,则直接跳过 metric_bytes_send:inc(ngx_bytes_sent, {ngx_host, ngx_xlocation}) end ---- bytes receive local ngx_bytes_receive = tonumber(ngx.var.request_length) if ngx_bytes_receive then ngx_bytes_receive:inc(ngx_bytes_receive, {ngx_host, ngx_xlocation}) end ---- request_time统计 metric_requests_time:observe(ngx_request_time, {ngx_host, ngx_xlocation}) ---- upstream_time统计 local ngx_upstream_time = tonumber(ngx.var.upstream_response_time) if ngx_upstream_time then -- 如果获取不到值,则直接跳过 metric_request_upstream_time:observe(ngx_upstream_time, {ngx_host, ngx_xlocation}) end ---- https session复用率 if ngx_scheme == "https" then metric_tls_query_counter:inc(1, {ngx_host}) if ngx_ssl_session_reused == "r" then metric_tls_session_reuse_counter:inc(1, {ngx_host}) end end
--------------------------------------------------------------------------- -- NUI CALLBACKS --------------------------------------------------------------------------- RegisterNUICallback("bub-notify::closeSettings", function(data, callback) SetNuiFocus(false, false) callback("ok") end)
AddCSLuaFile() ENT.Type = "anim" ENT.Base = "base_anim" ENT.PrintName = "Flame" ENT.Author = "FiLzO" ENT.Purpose = "Can you feel Air Exchange?" ENT.Category = "Combine Units +PLUS+" ENT.Spawnable = false ENT.AdminOnly = false local COLLISION_RADIUS = 3 local LIFE_TIME = 0.35 local sndEngulf = Sound( "Fire.Engulf" ) if SERVER then function ENT:Initialize() self:SetModel( "models/Combine_Helicopter/helicopter_bomb01.mdl" ) self:SetNoDraw( true ) self:DrawShadow( false ) self:PhysicsInitSphere( COLLISION_RADIUS ) self:SetCollisionBounds( Vector( -COLLISION_RADIUS, -COLLISION_RADIUS, -COLLISION_RADIUS ), Vector( COLLISION_RADIUS, COLLISION_RADIUS, COLLISION_RADIUS ) ) self:SetNotSolid( true ) self:SetTrigger( true ) self:SetMoveType( MOVETYPE_FLY ) self:SetMoveCollide( MOVECOLLIDE_FLY_SLIDE ) self.Owner = self:GetOwner() or self if not self.Owner:IsValid() then self.Owner = self end self.Weapon = self.Owner:GetActiveWeapon() if not self.Weapon:IsValid() then self.Weapon = self end self.DamageModifier = 1 self.BaseDamage = 1 self.NextTouch = CurTime() self:Fire( "kill", "", LIFE_TIME ) self.KillTime = CurTime() + LIFE_TIME end function ENT:SetDamage( mindmg, maxdmg ) self.DamageModifier = ( maxdmg - mindmg ) / LIFE_TIME self.BaseDamage = mindmg end function ENT:Touch( ent ) -- ent == self.Owner or ent:IsWorld() then return end --if ent:GetClass()=="cup_fuel_tank" and ent:GetClass()=="npc_stalker" or ent:GetClass()=="npc_combine_s" or ent:GetClass()=="npc_metropolice" or ent:GetClass()=="npc_cscanner" or ent:GetClass()=="npc_manhack" or ent:GetClass()=="npc_strider" or ent:GetClass()=="npc_hunter" or ent:GetClass()=="npc_rollermine" or ent:GetClass()=="npc_clawscanner" or ent:GetClass()=="npc_turret_floor" or ent:GetClass()=="npc_turret_ceiling" or ent:GetClass()=="npc_combine_camera" or ent:GetClass()=="npc_combinedropship" or ent:GetClass()=="npc_combinegunship" or ent:GetClass()=="npc_helicopter" or ent:GetClass()=="npc_turret_ground" or ent:GetClass()=="npc_apcdriver" then return end if ent.wearsuit == true then return end if self.NextTouch > CurTime() then return end self.NextTouch = CurTime() + 0.05 -- Die under water --if self:WaterLevel() >= 1 then -- self:Remove() -- return --end -- Stop moving since we hit something self:SetMoveType( MOVETYPE_NONE ) -- Make sure the owner and weapon are still around, otherwise we would error out if not self.Owner:IsValid() then self.Owner = self end if not self.Weapon:IsValid() then self.Weapon = self end -- Apply damage based on how long the projectile has been alive local dmg = ( self.KillTime - CurTime() ) * self.DamageModifier + self.BaseDamage if dmg < 0 then dmg = 0 end ent:TakeDamage( dmg, self.Owner, self.Weapon ) -- Play that cool igniting sound if this entity is being ignited for the first time if not ent:IsOnFire() then ent:EmitSound( sndEngulf ) end -- Ignite the entity --if ent:IsPlayer() then ent:Ignite( math.random( 5, 6 ), 0 ) -- Go easier on players --else -- ent:Fire( "IgniteLifeTime", math.random( 10, 12 ), 0 ) -- garry done broke ent:Ignite(), so we have to use this --end end end
local Native = require('lib.native.native') local Player = require('lib.oop.player') local Widget = require('lib.oop.widget') local Destructable = require('lib.oop.destructable') local Item = require('lib.oop.item') local Unit = require('lib.oop.unit') local Ability = require('lib.oop.ability') local Timer = require('lib.oop.timer') local Trigger = require('lib.oop.trigger') local TriggerCondition = require('lib.oop.triggercondition') local Event = require('lib.oop.event') local Force = require('lib.oop.force') local Group = require('lib.oop.group') local Location = require('lib.oop.location') local Rect = require('lib.oop.rect') local BoolExpr = require('lib.oop.boolexpr') local Sound = require('lib.oop.sound') local Effect = require('lib.oop.effect') local UnitPool = require('lib.oop.unitpool') local ItemPool = require('lib.oop.itempool') local Quest = require('lib.oop.quest') local QuestItem = require('lib.oop.questitem') local DefeatCondition = require('lib.oop.defeatcondition') local TimerDialog = require('lib.oop.timerdialog') local LeaderBoard = require('lib.oop.leaderboard') local MultiBoard = require('lib.oop.multiboard') local MultiBoardItem = require('lib.oop.multiboarditem') local Trackable = require('lib.oop.trackable') local Dialog = require('lib.oop.dialog') local Button = require('lib.oop.button') local TextTag = require('lib.oop.texttag') local Lightning = require('lib.oop.lightning') local Image = require('lib.oop.image') local Ubersplat = require('lib.oop.ubersplat') local Region = require('lib.oop.region') local FogModifier = require('lib.oop.fogmodifier') local Frame = require('lib.oop.frame') ---@class Hashtable : Agent local Hashtable = class('Hashtable', assert(require('lib.oop.agent'))) ---<static> create ---@return Hashtable function Hashtable:create() return Hashtable:fromUd(Native.InitHashtable()) end ---saveInteger ---@param parentKey integer ---@param childKey integer ---@param value integer ---@return void function Hashtable:saveInteger(parentKey, childKey, value) return Native.SaveInteger(getUd(self), parentKey, childKey, value) end ---saveReal ---@param parentKey integer ---@param childKey integer ---@param value float ---@return void function Hashtable:saveReal(parentKey, childKey, value) return Native.SaveReal(getUd(self), parentKey, childKey, value) end ---saveBoolean ---@param parentKey integer ---@param childKey integer ---@param value boolean ---@return void function Hashtable:saveBoolean(parentKey, childKey, value) return Native.SaveBoolean(getUd(self), parentKey, childKey, value) end ---saveStr ---@param parentKey integer ---@param childKey integer ---@param value string ---@return boolean function Hashtable:saveStr(parentKey, childKey, value) return Native.SaveStr(getUd(self), parentKey, childKey, value) end ---savePlayerHandle ---@param parentKey integer ---@param childKey integer ---@param player Player ---@return boolean function Hashtable:savePlayerHandle(parentKey, childKey, player) return Native.SavePlayerHandle(getUd(self), parentKey, childKey, getUd(player)) end ---saveWidgetHandle ---@param parentKey integer ---@param childKey integer ---@param widget Widget ---@return boolean function Hashtable:saveWidgetHandle(parentKey, childKey, widget) return Native.SaveWidgetHandle(getUd(self), parentKey, childKey, getUd(widget)) end ---saveDestructableHandle ---@param parentKey integer ---@param childKey integer ---@param destructable Destructable ---@return boolean function Hashtable:saveDestructableHandle(parentKey, childKey, destructable) return Native.SaveDestructableHandle(getUd(self), parentKey, childKey, getUd(destructable)) end ---saveItemHandle ---@param parentKey integer ---@param childKey integer ---@param item Item ---@return boolean function Hashtable:saveItemHandle(parentKey, childKey, item) return Native.SaveItemHandle(getUd(self), parentKey, childKey, getUd(item)) end ---saveUnitHandle ---@param parentKey integer ---@param childKey integer ---@param unit Unit ---@return boolean function Hashtable:saveUnitHandle(parentKey, childKey, unit) return Native.SaveUnitHandle(getUd(self), parentKey, childKey, getUd(unit)) end ---saveAbilityHandle ---@param parentKey integer ---@param childKey integer ---@param ability Ability ---@return boolean function Hashtable:saveAbilityHandle(parentKey, childKey, ability) return Native.SaveAbilityHandle(getUd(self), parentKey, childKey, getUd(ability)) end ---saveTimerHandle ---@param parentKey integer ---@param childKey integer ---@param timer Timer ---@return boolean function Hashtable:saveTimerHandle(parentKey, childKey, timer) return Native.SaveTimerHandle(getUd(self), parentKey, childKey, getUd(timer)) end ---saveTriggerHandle ---@param parentKey integer ---@param childKey integer ---@param trigger Trigger ---@return boolean function Hashtable:saveTriggerHandle(parentKey, childKey, trigger) return Native.SaveTriggerHandle(getUd(self), parentKey, childKey, getUd(trigger)) end ---saveTriggerConditionHandle ---@param parentKey integer ---@param childKey integer ---@param triggercondition TriggerCondition ---@return boolean function Hashtable:saveTriggerConditionHandle(parentKey, childKey, triggercondition) return Native.SaveTriggerConditionHandle(getUd(self), parentKey, childKey, getUd(triggercondition)) end ---saveTriggerActionHandle ---@param parentKey integer ---@param childKey integer ---@param triggeraction TriggerAction ---@return boolean function Hashtable:saveTriggerActionHandle(parentKey, childKey, triggeraction) return Native.SaveTriggerActionHandle(getUd(self), parentKey, childKey, triggeraction) end ---saveTriggerEventHandle ---@param parentKey integer ---@param childKey integer ---@param event Event ---@return boolean function Hashtable:saveTriggerEventHandle(parentKey, childKey, event) return Native.SaveTriggerEventHandle(getUd(self), parentKey, childKey, getUd(event)) end ---saveForceHandle ---@param parentKey integer ---@param childKey integer ---@param force Force ---@return boolean function Hashtable:saveForceHandle(parentKey, childKey, force) return Native.SaveForceHandle(getUd(self), parentKey, childKey, getUd(force)) end ---saveGroupHandle ---@param parentKey integer ---@param childKey integer ---@param group Group ---@return boolean function Hashtable:saveGroupHandle(parentKey, childKey, group) return Native.SaveGroupHandle(getUd(self), parentKey, childKey, getUd(group)) end ---saveLocationHandle ---@param parentKey integer ---@param childKey integer ---@param loc Location ---@return boolean function Hashtable:saveLocationHandle(parentKey, childKey, loc) return Native.SaveLocationHandle(getUd(self), parentKey, childKey, getUd(loc)) end ---saveRectHandle ---@param parentKey integer ---@param childKey integer ---@param rect Rect ---@return boolean function Hashtable:saveRectHandle(parentKey, childKey, rect) return Native.SaveRectHandle(getUd(self), parentKey, childKey, getUd(rect)) end ---saveBooleanExprHandle ---@param parentKey integer ---@param childKey integer ---@param boolexpr BoolExpr ---@return boolean function Hashtable:saveBooleanExprHandle(parentKey, childKey, boolexpr) return Native.SaveBooleanExprHandle(getUd(self), parentKey, childKey, getUd(boolexpr)) end ---saveSoundHandle ---@param parentKey integer ---@param childKey integer ---@param sound Sound ---@return boolean function Hashtable:saveSoundHandle(parentKey, childKey, sound) return Native.SaveSoundHandle(getUd(self), parentKey, childKey, getUd(sound)) end ---saveEffectHandle ---@param parentKey integer ---@param childKey integer ---@param effect Effect ---@return boolean function Hashtable:saveEffectHandle(parentKey, childKey, effect) return Native.SaveEffectHandle(getUd(self), parentKey, childKey, getUd(effect)) end ---saveUnitPoolHandle ---@param parentKey integer ---@param childKey integer ---@param unitpool UnitPool ---@return boolean function Hashtable:saveUnitPoolHandle(parentKey, childKey, unitpool) return Native.SaveUnitPoolHandle(getUd(self), parentKey, childKey, getUd(unitpool)) end ---saveItemPoolHandle ---@param parentKey integer ---@param childKey integer ---@param itempool ItemPool ---@return boolean function Hashtable:saveItemPoolHandle(parentKey, childKey, itempool) return Native.SaveItemPoolHandle(getUd(self), parentKey, childKey, getUd(itempool)) end ---saveQuestHandle ---@param parentKey integer ---@param childKey integer ---@param quest Quest ---@return boolean function Hashtable:saveQuestHandle(parentKey, childKey, quest) return Native.SaveQuestHandle(getUd(self), parentKey, childKey, getUd(quest)) end ---saveQuestItemHandle ---@param parentKey integer ---@param childKey integer ---@param questitem QuestItem ---@return boolean function Hashtable:saveQuestItemHandle(parentKey, childKey, questitem) return Native.SaveQuestItemHandle(getUd(self), parentKey, childKey, getUd(questitem)) end ---saveDefeatConditionHandle ---@param parentKey integer ---@param childKey integer ---@param defeatcondition DefeatCondition ---@return boolean function Hashtable:saveDefeatConditionHandle(parentKey, childKey, defeatcondition) return Native.SaveDefeatConditionHandle(getUd(self), parentKey, childKey, getUd(defeatcondition)) end ---saveTimerDialogHandle ---@param parentKey integer ---@param childKey integer ---@param timerdialog TimerDialog ---@return boolean function Hashtable:saveTimerDialogHandle(parentKey, childKey, timerdialog) return Native.SaveTimerDialogHandle(getUd(self), parentKey, childKey, getUd(timerdialog)) end ---saveLeaderboardHandle ---@param parentKey integer ---@param childKey integer ---@param leaderboard LeaderBoard ---@return boolean function Hashtable:saveLeaderboardHandle(parentKey, childKey, leaderboard) return Native.SaveLeaderboardHandle(getUd(self), parentKey, childKey, getUd(leaderboard)) end ---saveMultiboardHandle ---@param parentKey integer ---@param childKey integer ---@param multiboard MultiBoard ---@return boolean function Hashtable:saveMultiboardHandle(parentKey, childKey, multiboard) return Native.SaveMultiboardHandle(getUd(self), parentKey, childKey, getUd(multiboard)) end ---saveMultiboardItemHandle ---@param parentKey integer ---@param childKey integer ---@param multiboarditem MultiBoardItem ---@return boolean function Hashtable:saveMultiboardItemHandle(parentKey, childKey, multiboarditem) return Native.SaveMultiboardItemHandle(getUd(self), parentKey, childKey, getUd(multiboarditem)) end ---saveTrackableHandle ---@param parentKey integer ---@param childKey integer ---@param trackable Trackable ---@return boolean function Hashtable:saveTrackableHandle(parentKey, childKey, trackable) return Native.SaveTrackableHandle(getUd(self), parentKey, childKey, getUd(trackable)) end ---saveDialogHandle ---@param parentKey integer ---@param childKey integer ---@param dialog Dialog ---@return boolean function Hashtable:saveDialogHandle(parentKey, childKey, dialog) return Native.SaveDialogHandle(getUd(self), parentKey, childKey, getUd(dialog)) end ---saveButtonHandle ---@param parentKey integer ---@param childKey integer ---@param button Button ---@return boolean function Hashtable:saveButtonHandle(parentKey, childKey, button) return Native.SaveButtonHandle(getUd(self), parentKey, childKey, getUd(button)) end ---saveTextTagHandle ---@param parentKey integer ---@param childKey integer ---@param texttag TextTag ---@return boolean function Hashtable:saveTextTagHandle(parentKey, childKey, texttag) return Native.SaveTextTagHandle(getUd(self), parentKey, childKey, getUd(texttag)) end ---saveLightningHandle ---@param parentKey integer ---@param childKey integer ---@param lightning Lightning ---@return boolean function Hashtable:saveLightningHandle(parentKey, childKey, lightning) return Native.SaveLightningHandle(getUd(self), parentKey, childKey, getUd(lightning)) end ---saveImageHandle ---@param parentKey integer ---@param childKey integer ---@param image Image ---@return boolean function Hashtable:saveImageHandle(parentKey, childKey, image) return Native.SaveImageHandle(getUd(self), parentKey, childKey, getUd(image)) end ---saveUbersplatHandle ---@param parentKey integer ---@param childKey integer ---@param ubersplat Ubersplat ---@return boolean function Hashtable:saveUbersplatHandle(parentKey, childKey, ubersplat) return Native.SaveUbersplatHandle(getUd(self), parentKey, childKey, getUd(ubersplat)) end ---saveRegionHandle ---@param parentKey integer ---@param childKey integer ---@param region Region ---@return boolean function Hashtable:saveRegionHandle(parentKey, childKey, region) return Native.SaveRegionHandle(getUd(self), parentKey, childKey, getUd(region)) end ---saveFogStateHandle ---@param parentKey integer ---@param childKey integer ---@param fogState FogState ---@return boolean function Hashtable:saveFogStateHandle(parentKey, childKey, fogState) return Native.SaveFogStateHandle(getUd(self), parentKey, childKey, fogState) end ---saveFogModifierHandle ---@param parentKey integer ---@param childKey integer ---@param fogModifier FogModifier ---@return boolean function Hashtable:saveFogModifierHandle(parentKey, childKey, fogModifier) return Native.SaveFogModifierHandle(getUd(self), parentKey, childKey, getUd(fogModifier)) end ---saveAgentHandle ---@param parentKey integer ---@param childKey integer ---@param agent Agent ---@return boolean function Hashtable:saveAgentHandle(parentKey, childKey, agent) return Native.SaveAgentHandle(getUd(self), parentKey, childKey, getUd(agent)) end ---saveHashtableHandle ---@param parentKey integer ---@param childKey integer ---@param hashtable Hashtable ---@return boolean function Hashtable:saveHashtableHandle(parentKey, childKey, hashtable) return Native.SaveHashtableHandle(getUd(self), parentKey, childKey, getUd(hashtable)) end ---saveFrameHandle ---@param parentKey integer ---@param childKey integer ---@param frameHandle Frame ---@return boolean function Hashtable:saveFrameHandle(parentKey, childKey, frameHandle) return Native.SaveFrameHandle(getUd(self), parentKey, childKey, getUd(frameHandle)) end ---loadInteger ---@param parentKey integer ---@param childKey integer ---@return integer function Hashtable:loadInteger(parentKey, childKey) return Native.LoadInteger(getUd(self), parentKey, childKey) end ---loadReal ---@param parentKey integer ---@param childKey integer ---@return float function Hashtable:loadReal(parentKey, childKey) return Native.LoadReal(getUd(self), parentKey, childKey) end ---loadBoolean ---@param parentKey integer ---@param childKey integer ---@return boolean function Hashtable:loadBoolean(parentKey, childKey) return Native.LoadBoolean(getUd(self), parentKey, childKey) end ---loadStr ---@param parentKey integer ---@param childKey integer ---@return string function Hashtable:loadStr(parentKey, childKey) return Native.LoadStr(getUd(self), parentKey, childKey) end ---loadPlayerHandle ---@param parentKey integer ---@param childKey integer ---@return Player function Hashtable:loadPlayerHandle(parentKey, childKey) return Player:fromUd(Native.LoadPlayerHandle(getUd(self), parentKey, childKey)) end ---loadWidgetHandle ---@param parentKey integer ---@param childKey integer ---@return Widget function Hashtable:loadWidgetHandle(parentKey, childKey) return Widget:fromUd(Native.LoadWidgetHandle(getUd(self), parentKey, childKey)) end ---loadDestructableHandle ---@param parentKey integer ---@param childKey integer ---@return Destructable function Hashtable:loadDestructableHandle(parentKey, childKey) return Destructable:fromUd(Native.LoadDestructableHandle(getUd(self), parentKey, childKey)) end ---loadItemHandle ---@param parentKey integer ---@param childKey integer ---@return Item function Hashtable:loadItemHandle(parentKey, childKey) return Item:fromUd(Native.LoadItemHandle(getUd(self), parentKey, childKey)) end ---loadUnitHandle ---@param parentKey integer ---@param childKey integer ---@return Unit function Hashtable:loadUnitHandle(parentKey, childKey) return Unit:fromUd(Native.LoadUnitHandle(getUd(self), parentKey, childKey)) end ---loadAbilityHandle ---@param parentKey integer ---@param childKey integer ---@return Ability function Hashtable:loadAbilityHandle(parentKey, childKey) return Ability:fromUd(Native.LoadAbilityHandle(getUd(self), parentKey, childKey)) end ---loadTimerHandle ---@param parentKey integer ---@param childKey integer ---@return Timer function Hashtable:loadTimerHandle(parentKey, childKey) return Timer:fromUd(Native.LoadTimerHandle(getUd(self), parentKey, childKey)) end ---loadTriggerHandle ---@param parentKey integer ---@param childKey integer ---@return Trigger function Hashtable:loadTriggerHandle(parentKey, childKey) return Trigger:fromUd(Native.LoadTriggerHandle(getUd(self), parentKey, childKey)) end ---loadTriggerConditionHandle ---@param parentKey integer ---@param childKey integer ---@return TriggerCondition function Hashtable:loadTriggerConditionHandle(parentKey, childKey) return TriggerCondition:fromUd(Native.LoadTriggerConditionHandle(getUd(self), parentKey, childKey)) end ---loadTriggerActionHandle ---@param parentKey integer ---@param childKey integer ---@return TriggerAction function Hashtable:loadTriggerActionHandle(parentKey, childKey) return Native.LoadTriggerActionHandle(getUd(self), parentKey, childKey) end ---loadTriggerEventHandle ---@param parentKey integer ---@param childKey integer ---@return Event function Hashtable:loadTriggerEventHandle(parentKey, childKey) return Event:fromUd(Native.LoadTriggerEventHandle(getUd(self), parentKey, childKey)) end ---loadForceHandle ---@param parentKey integer ---@param childKey integer ---@return Force function Hashtable:loadForceHandle(parentKey, childKey) return Force:fromUd(Native.LoadForceHandle(getUd(self), parentKey, childKey)) end ---loadGroupHandle ---@param parentKey integer ---@param childKey integer ---@return Group function Hashtable:loadGroupHandle(parentKey, childKey) return Group:fromUd(Native.LoadGroupHandle(getUd(self), parentKey, childKey)) end ---loadLocationHandle ---@param parentKey integer ---@param childKey integer ---@return Location function Hashtable:loadLocationHandle(parentKey, childKey) return Location:fromUd(Native.LoadLocationHandle(getUd(self), parentKey, childKey)) end ---loadRectHandle ---@param parentKey integer ---@param childKey integer ---@return Rect function Hashtable:loadRectHandle(parentKey, childKey) return Rect:fromUd(Native.LoadRectHandle(getUd(self), parentKey, childKey)) end ---loadBooleanExprHandle ---@param parentKey integer ---@param childKey integer ---@return BoolExpr function Hashtable:loadBooleanExprHandle(parentKey, childKey) return BoolExpr:fromUd(Native.LoadBooleanExprHandle(getUd(self), parentKey, childKey)) end ---loadSoundHandle ---@param parentKey integer ---@param childKey integer ---@return Sound function Hashtable:loadSoundHandle(parentKey, childKey) return Sound:fromUd(Native.LoadSoundHandle(getUd(self), parentKey, childKey)) end ---loadEffectHandle ---@param parentKey integer ---@param childKey integer ---@return Effect function Hashtable:loadEffectHandle(parentKey, childKey) return Effect:fromUd(Native.LoadEffectHandle(getUd(self), parentKey, childKey)) end ---loadUnitPoolHandle ---@param parentKey integer ---@param childKey integer ---@return UnitPool function Hashtable:loadUnitPoolHandle(parentKey, childKey) return UnitPool:fromUd(Native.LoadUnitPoolHandle(getUd(self), parentKey, childKey)) end ---loadItemPoolHandle ---@param parentKey integer ---@param childKey integer ---@return ItemPool function Hashtable:loadItemPoolHandle(parentKey, childKey) return ItemPool:fromUd(Native.LoadItemPoolHandle(getUd(self), parentKey, childKey)) end ---loadQuestHandle ---@param parentKey integer ---@param childKey integer ---@return Quest function Hashtable:loadQuestHandle(parentKey, childKey) return Quest:fromUd(Native.LoadQuestHandle(getUd(self), parentKey, childKey)) end ---loadQuestItemHandle ---@param parentKey integer ---@param childKey integer ---@return QuestItem function Hashtable:loadQuestItemHandle(parentKey, childKey) return QuestItem:fromUd(Native.LoadQuestItemHandle(getUd(self), parentKey, childKey)) end ---loadDefeatConditionHandle ---@param parentKey integer ---@param childKey integer ---@return DefeatCondition function Hashtable:loadDefeatConditionHandle(parentKey, childKey) return DefeatCondition:fromUd(Native.LoadDefeatConditionHandle(getUd(self), parentKey, childKey)) end ---loadTimerDialogHandle ---@param parentKey integer ---@param childKey integer ---@return TimerDialog function Hashtable:loadTimerDialogHandle(parentKey, childKey) return TimerDialog:fromUd(Native.LoadTimerDialogHandle(getUd(self), parentKey, childKey)) end ---loadLeaderboardHandle ---@param parentKey integer ---@param childKey integer ---@return LeaderBoard function Hashtable:loadLeaderboardHandle(parentKey, childKey) return LeaderBoard:fromUd(Native.LoadLeaderboardHandle(getUd(self), parentKey, childKey)) end ---loadMultiboardHandle ---@param parentKey integer ---@param childKey integer ---@return MultiBoard function Hashtable:loadMultiboardHandle(parentKey, childKey) return MultiBoard:fromUd(Native.LoadMultiboardHandle(getUd(self), parentKey, childKey)) end ---loadMultiboardItemHandle ---@param parentKey integer ---@param childKey integer ---@return MultiBoardItem function Hashtable:loadMultiboardItemHandle(parentKey, childKey) return MultiBoardItem:fromUd(Native.LoadMultiboardItemHandle(getUd(self), parentKey, childKey)) end ---loadTrackableHandle ---@param parentKey integer ---@param childKey integer ---@return Trackable function Hashtable:loadTrackableHandle(parentKey, childKey) return Trackable:fromUd(Native.LoadTrackableHandle(getUd(self), parentKey, childKey)) end ---loadDialogHandle ---@param parentKey integer ---@param childKey integer ---@return Dialog function Hashtable:loadDialogHandle(parentKey, childKey) return Dialog:fromUd(Native.LoadDialogHandle(getUd(self), parentKey, childKey)) end ---loadButtonHandle ---@param parentKey integer ---@param childKey integer ---@return Button function Hashtable:loadButtonHandle(parentKey, childKey) return Button:fromUd(Native.LoadButtonHandle(getUd(self), parentKey, childKey)) end ---loadTextTagHandle ---@param parentKey integer ---@param childKey integer ---@return TextTag function Hashtable:loadTextTagHandle(parentKey, childKey) return TextTag:fromUd(Native.LoadTextTagHandle(getUd(self), parentKey, childKey)) end ---loadLightningHandle ---@param parentKey integer ---@param childKey integer ---@return Lightning function Hashtable:loadLightningHandle(parentKey, childKey) return Lightning:fromUd(Native.LoadLightningHandle(getUd(self), parentKey, childKey)) end ---loadImageHandle ---@param parentKey integer ---@param childKey integer ---@return Image function Hashtable:loadImageHandle(parentKey, childKey) return Image:fromUd(Native.LoadImageHandle(getUd(self), parentKey, childKey)) end ---loadUbersplatHandle ---@param parentKey integer ---@param childKey integer ---@return Ubersplat function Hashtable:loadUbersplatHandle(parentKey, childKey) return Ubersplat:fromUd(Native.LoadUbersplatHandle(getUd(self), parentKey, childKey)) end ---loadRegionHandle ---@param parentKey integer ---@param childKey integer ---@return Region function Hashtable:loadRegionHandle(parentKey, childKey) return Region:fromUd(Native.LoadRegionHandle(getUd(self), parentKey, childKey)) end ---loadFogStateHandle ---@param parentKey integer ---@param childKey integer ---@return FogState function Hashtable:loadFogStateHandle(parentKey, childKey) return Native.LoadFogStateHandle(getUd(self), parentKey, childKey) end ---loadFogModifierHandle ---@param parentKey integer ---@param childKey integer ---@return FogModifier function Hashtable:loadFogModifierHandle(parentKey, childKey) return FogModifier:fromUd(Native.LoadFogModifierHandle(getUd(self), parentKey, childKey)) end ---loadHandle ---@param parentKey integer ---@param childKey integer ---@return Hashtable function Hashtable:loadHandle(parentKey, childKey) return Hashtable:fromUd(Native.LoadHashtableHandle(getUd(self), parentKey, childKey)) end ---loadFrameHandle ---@param parentKey integer ---@param childKey integer ---@return Frame function Hashtable:loadFrameHandle(parentKey, childKey) return Frame:fromUd(Native.LoadFrameHandle(getUd(self), parentKey, childKey)) end ---haveSavedInteger ---@param parentKey integer ---@param childKey integer ---@return boolean function Hashtable:haveSavedInteger(parentKey, childKey) return Native.HaveSavedInteger(getUd(self), parentKey, childKey) end ---haveSavedReal ---@param parentKey integer ---@param childKey integer ---@return boolean function Hashtable:haveSavedReal(parentKey, childKey) return Native.HaveSavedReal(getUd(self), parentKey, childKey) end ---haveSavedBoolean ---@param parentKey integer ---@param childKey integer ---@return boolean function Hashtable:haveSavedBoolean(parentKey, childKey) return Native.HaveSavedBoolean(getUd(self), parentKey, childKey) end ---haveSavedString ---@param parentKey integer ---@param childKey integer ---@return boolean function Hashtable:haveSavedString(parentKey, childKey) return Native.HaveSavedString(getUd(self), parentKey, childKey) end ---haveSavedHandle ---@param parentKey integer ---@param childKey integer ---@return boolean function Hashtable:haveSavedHandle(parentKey, childKey) return Native.HaveSavedHandle(getUd(self), parentKey, childKey) end ---removeSavedInteger ---@param parentKey integer ---@param childKey integer ---@return void function Hashtable:removeSavedInteger(parentKey, childKey) return Native.RemoveSavedInteger(getUd(self), parentKey, childKey) end ---removeSavedReal ---@param parentKey integer ---@param childKey integer ---@return void function Hashtable:removeSavedReal(parentKey, childKey) return Native.RemoveSavedReal(getUd(self), parentKey, childKey) end ---removeSavedBoolean ---@param parentKey integer ---@param childKey integer ---@return void function Hashtable:removeSavedBoolean(parentKey, childKey) return Native.RemoveSavedBoolean(getUd(self), parentKey, childKey) end ---removeSavedString ---@param parentKey integer ---@param childKey integer ---@return void function Hashtable:removeSavedString(parentKey, childKey) return Native.RemoveSavedString(getUd(self), parentKey, childKey) end ---removeSavedHandle ---@param parentKey integer ---@param childKey integer ---@return void function Hashtable:removeSavedHandle(parentKey, childKey) return Native.RemoveSavedHandle(getUd(self), parentKey, childKey) end ---flushParent ---@return void function Hashtable:flushParent() return Native.FlushParentHashtable(getUd(self)) end ---flushChild ---@param parentKey integer ---@return void function Hashtable:flushChild(parentKey) return Native.FlushChildHashtable(getUd(self), parentKey) end return Hashtable
object_building_kashyyyk_poi_kash_rryatt_lvl1_near_canopy_a3 = object_building_kashyyyk_shared_poi_kash_rryatt_lvl1_near_canopy_a3:new { } ObjectTemplates:addTemplate(object_building_kashyyyk_poi_kash_rryatt_lvl1_near_canopy_a3, "object/building/kashyyyk/poi_kash_rryatt_lvl1_near_canopy_a3.iff")
wincent.g.command_callbacks = {} -- TODO: garbage-collect overwritten command callbacks -- Wrapper for simple :command use cases. `repl` (replacement) may be a string -- or a Lua function. -- -- Slight departure from Vim default behavior: `force = true` is the default -- (ie. `:command!` instead of `:command`), seeing as I am using that at -- literally every call-site. -- local command = function (name, repl, opts) opts = opts or {} local repl_type = type(repl) if repl_type == 'function' then local key = wincent.util.get_key_for_fn(repl, wincent.g.command_callbacks) wincent.g.command_callbacks[key] = repl repl = 'lua wincent.g.command_callbacks.' .. key .. '()' elseif repl_type ~= 'string' then error('command(): unsupported repl type: ' .. repl_type) end local prefix = opts.force == false and 'command' or 'command!' if opts.bang then prefix = prefix .. ' -bang' end if opts.complete then prefix = prefix .. ' -complete=' .. opts.complete end if opts.nargs then prefix = prefix .. ' -nargs=' .. opts.nargs end if opts.range then prefix = prefix .. ' -range' end vim.cmd(prefix .. ' ' .. name .. ' ' .. repl) end return command
----------------------------------- -- Ability: Evoker's Roll -- Gradually restores MP for party members within area of effect -- Optimal Job: Summoner -- Lucky Number: 5 -- Unlucky Number: 9 -- Level: 40 -- -- Die Roll |No SMN |With SMN -- -------- ------- ----------- -- 1 |+1 |+2 -- 2 |+1 |+2 -- 3 |+1 |+2 -- 4 |+1 |+2 -- 5 |+3 |+4 -- 6 |+2 |+3 -- 7 |+2 |+3 -- 8 |+2 |+3 -- 9 |+1 |+2 -- 10 |+3 |+4 -- 11 |+4 |+5 -- Bust |-1 |-1 ----------------------------------- require("scripts/globals/ability") require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------- function onAbilityCheck(player,target,ability) ability:setRange(ability:getRange() + player:getMod(tpz.mod.ROLL_RANGE)) if player:hasStatusEffect(tpz.effect.EVOKERS_ROLL) then return tpz.msg.basic.ROLL_ALREADY_ACTIVE,0 elseif atMaxCorsairBusts(player) then return tpz.msg.basic.CANNOT_PERFORM,0 else return 0,0 end end function onUseAbility(caster,target,ability,action) if caster:getID() == target:getID() then corsairSetup(caster, ability, action, tpz.effect.EVOKERS_ROLL, tpz.job.SMN) end local total = caster:getLocalVar("corsairRollTotal") return applyRoll(caster,target,ability,action,total) end function applyRoll(caster,target,ability,action,total) local duration = 300 + caster:getMerit(tpz.merit.WINNING_STREAK) + caster:getMod(tpz.mod.PHANTOM_DURATION) local effectpowers = {1, 1, 1, 1, 3, 2, 2, 2, 1, 3, 4, 1} local effectpower = effectpowers[total] if caster:getLocalVar("corsairRollBonus") == 1 and total < 12 then effectpower = effectpower + 1 end -- Check if COR Main or Sub if caster:getMainJob() == tpz.job.COR and caster:getMainLvl() < target:getMainLvl() then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()) elseif caster:getSubJob() == tpz.job.COR and caster:getSubLvl() < target:getMainLvl() then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()) end if not target:addCorsairRoll(caster:getMainJob(), caster:getMerit(tpz.merit.BUST_DURATION), tpz.effect.EVOKERS_ROLL, effectpower, 0, duration, caster:getID(), total, tpz.mod.REFRESH) then ability:setMsg(tpz.msg.basic.ROLL_MAIN_FAIL) elseif total > 11 then ability:setMsg(tpz.msg.basic.DOUBLEUP_BUST) end return total end
-- private utility module for `cp.rx`. local util = {} local defaultScheduler = nil util.pack = table.pack or function(...) return { n = select('#', ...), ... } end util.unpack = table.unpack or _G.unpack util.eq = function(x, y) return x == y end util.noop = function() end util.identity = function(x) return x end util.constant = function(x) return function() return x end end util.isa = function(object, class) if type(object) == 'table' then local mt = getmetatable(object) return mt ~= nil and rawequal(mt.__index, class) or not rawequal(mt, object) and util.isa(mt, class) end return false end util.tryWithObserver = function(observer, fn, ...) local args = util.pack(...) local success, result = xpcall(function() fn(util.unpack(args)) end, function(message) return debug.traceback(message, 2) end) if not success then observer:onError(result) end return success, result end util.defaultScheduler = function(newScheduler) if newScheduler and type(newScheduler.schedule) == "function" then defaultScheduler = newScheduler end return defaultScheduler end util.tableId = function(value) local __tostring local mt = getmetatable(value) if mt then __tostring = mt.__tostring mt.__tostring = nil end local id = tostring(value) if mt then mt.__tostring = __tostring end return id end return util
local testCasesForRAI = {} require('atf.util') local commonPreconditions = require ('user_modules/shared_testcases/commonPreconditions') local events = require("events") local path_config = commonPreconditions:GetPathToSDL() --[[@InitHMI_onReady_without_UI_GetCapabilities: replace original InitHMIOnReady from connecttest --! without expect UI.GetCapabilites --! @parameters: NO --]] function testCasesForRAI.InitHMI_onReady_without_UI_GetCapabilities(self) local function ExpectRequest(name, mandatory, params) local event = events.Event() event.level = 2 event.matches = function(_, data) return data.method == name end return EXPECT_HMIEVENT(event, name) :Times(mandatory and 1 or AnyNumber()) :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", params) end) end ExpectRequest("BasicCommunication.MixingAudioSupported", true, { attenuatedSupported = true }) ExpectRequest("BasicCommunication.GetSystemInfo", false, { ccpu_version = "ccpu_version", language = "EN-US", wersCountryCode = "wersCountryCode" }) ExpectRequest("UI.GetLanguage", true, { language = "EN-US" }) ExpectRequest("VR.GetLanguage", true, { language = "EN-US" }) ExpectRequest("TTS.GetLanguage", true, { language = "EN-US" }) ExpectRequest("UI.ChangeRegistration", false, { }):Pin() ExpectRequest("TTS.SetGlobalProperties", false, { }):Pin() ExpectRequest("BasicCommunication.UpdateDeviceList", false, { }):Pin() ExpectRequest("VR.ChangeRegistration", false, { }):Pin() ExpectRequest("TTS.ChangeRegistration", false, { }):Pin() ExpectRequest("VR.GetSupportedLanguages", true, { languages = { "EN-US","ES-MX","FR-CA","DE-DE","ES-ES","EN-GB","RU-RU", "TR-TR","PL-PL","FR-FR","IT-IT","SV-SE","PT-PT","NL-NL", "ZH-TW","JA-JP","AR-SA","KO-KR","PT-BR","CS-CZ","DA-DK", "NO-NO","NL-BE","EL-GR","HU-HU","FI-FI","SK-SK" } }) ExpectRequest("TTS.GetSupportedLanguages", true, { languages = { "EN-US","ES-MX","FR-CA","DE-DE","ES-ES","EN-GB","RU-RU", "TR-TR","PL-PL","FR-FR","IT-IT","SV-SE","PT-PT","NL-NL", "ZH-TW","JA-JP","AR-SA","KO-KR","PT-BR","CS-CZ","DA-DK", "NO-NO","NL-BE","EL-GR","HU-HU","FI-FI","SK-SK" } }) ExpectRequest("UI.GetSupportedLanguages", true, { languages = { "EN-US","ES-MX","FR-CA","DE-DE","ES-ES","EN-GB","RU-RU", "TR-TR","PL-PL","FR-FR","IT-IT","SV-SE","PT-PT","NL-NL", "ZH-TW","JA-JP","AR-SA","KO-KR","PT-BR","CS-CZ","DA-DK", "NO-NO","NL-BE","EL-GR","HU-HU","FI-FI","SK-SK" } }) ExpectRequest("VehicleInfo.GetVehicleType", true, { vehicleType = { make = "Ford", model = "Fiesta", modelYear = "2013", trim = "SE" } }) ExpectRequest("VehicleInfo.GetVehicleData", true, { vin = "52-452-52-752" }) local function button_capability(name, shortPressAvailable, longPressAvailable, upDownAvailable) return { name = name, shortPressAvailable = shortPressAvailable == nil and true or shortPressAvailable, longPressAvailable = longPressAvailable == nil and true or longPressAvailable, upDownAvailable = upDownAvailable == nil and true or upDownAvailable } end local buttons_capabilities = { capabilities = { button_capability("PRESET_0"), button_capability("PRESET_1"), button_capability("PRESET_2"), button_capability("PRESET_3"), button_capability("PRESET_4"), button_capability("PRESET_5"), button_capability("PRESET_6"), button_capability("PRESET_7"), button_capability("PRESET_8"), button_capability("PRESET_9"), button_capability("OK", true, false, true), button_capability("SEEKLEFT"), button_capability("SEEKRIGHT"), button_capability("TUNEUP"), button_capability("TUNEDOWN") }, presetBankCapabilities = { onScreenPresetsAvailable = true } } ExpectRequest("Buttons.GetCapabilities", true, buttons_capabilities) ExpectRequest("VR.GetCapabilities", true, { vrCapabilities = { "TEXT" } }) ExpectRequest("TTS.GetCapabilities", true, { speechCapabilities = { "TEXT", "PRE_RECORDED" }, prerecordedSpeechCapabilities = { "HELP_JINGLE", "INITIAL_JINGLE", "LISTEN_JINGLE", "POSITIVE_JINGLE", "NEGATIVE_JINGLE" } }) ExpectRequest("VR.IsReady", true, { available = true }) ExpectRequest("TTS.IsReady", true, { available = true }) ExpectRequest("UI.IsReady", true, { available = true }) ExpectRequest("Navigation.IsReady", true, { available = true }) ExpectRequest("VehicleInfo.IsReady", true, { available = true }) self.applications = { } ExpectRequest("BasicCommunication.UpdateAppList", false, { }) :Pin() :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", { }) self.applications = { } for _, app in pairs(data.params.applications) do self.applications[app.appName] = app.appID end end) self.hmiConnection:SendNotification("BasicCommunication.OnReady") end --[[@InitHMI_onReady_without_UI_IsReady_available_false: replace original InitHMIOnReady from connecttest --! without expect UI.GetCapabilites --! without expect UI.IsReady --! @parameters: exp_occur - times to wait UI.<<RPC>> --! in case UI.IsReady(available = false), exp_occur = 0, else exp_occur = 1 --]] function testCasesForRAI.InitHMI_onReady_without_UI_IsReady_GetCapabilities(self, exp_occur) if(exp_occur == nil) then exp_occur = 0 end local function ExpectRequest(name, mandatory, params) local event = events.Event() event.level = 2 event.matches = function(_, data) return data.method == name end return EXPECT_HMIEVENT(event, name) :Times(mandatory and 1 or AnyNumber()) :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", params) end) end ExpectRequest("BasicCommunication.MixingAudioSupported", true, { attenuatedSupported = true }) ExpectRequest("BasicCommunication.GetSystemInfo", false, { ccpu_version = "ccpu_version", language = "EN-US", wersCountryCode = "wersCountryCode" }) ExpectRequest("UI.GetLanguage", true, { language = "EN-US" }):Times(exp_occur) ExpectRequest("VR.GetLanguage", true, { language = "EN-US" }) ExpectRequest("TTS.GetLanguage", true, { language = "EN-US" }) ExpectRequest("UI.ChangeRegistration", false, { }):Pin():Times(exp_occur) ExpectRequest("TTS.SetGlobalProperties", false, { }):Pin() ExpectRequest("BasicCommunication.UpdateDeviceList", false, { }):Pin() ExpectRequest("VR.ChangeRegistration", false, { }):Pin() ExpectRequest("TTS.ChangeRegistration", false, { }):Pin() ExpectRequest("VR.GetSupportedLanguages", true, { languages = { "EN-US","ES-MX","FR-CA","DE-DE","ES-ES","EN-GB","RU-RU", "TR-TR","PL-PL","FR-FR","IT-IT","SV-SE","PT-PT","NL-NL", "ZH-TW","JA-JP","AR-SA","KO-KR","PT-BR","CS-CZ","DA-DK", "NO-NO","NL-BE","EL-GR","HU-HU","FI-FI","SK-SK" } }) ExpectRequest("TTS.GetSupportedLanguages", true, { languages = { "EN-US","ES-MX","FR-CA","DE-DE","ES-ES","EN-GB","RU-RU", "TR-TR","PL-PL","FR-FR","IT-IT","SV-SE","PT-PT","NL-NL", "ZH-TW","JA-JP","AR-SA","KO-KR","PT-BR","CS-CZ","DA-DK", "NO-NO","NL-BE","EL-GR","HU-HU","FI-FI","SK-SK" } }) ExpectRequest("UI.GetSupportedLanguages", true, { languages = { "EN-US","ES-MX","FR-CA","DE-DE","ES-ES","EN-GB","RU-RU", "TR-TR","PL-PL","FR-FR","IT-IT","SV-SE","PT-PT","NL-NL", "ZH-TW","JA-JP","AR-SA","KO-KR","PT-BR","CS-CZ","DA-DK", "NO-NO","NL-BE","EL-GR","HU-HU","FI-FI","SK-SK" } }):Times(exp_occur) ExpectRequest("VehicleInfo.GetVehicleType", true, { vehicleType = { make = "Ford", model = "Fiesta", modelYear = "2013", trim = "SE" } }) ExpectRequest("VehicleInfo.GetVehicleData", true, { vin = "52-452-52-752" }) local function button_capability(name, shortPressAvailable, longPressAvailable, upDownAvailable) return { name = name, shortPressAvailable = shortPressAvailable == nil and true or shortPressAvailable, longPressAvailable = longPressAvailable == nil and true or longPressAvailable, upDownAvailable = upDownAvailable == nil and true or upDownAvailable } end local buttons_capabilities = { capabilities = { button_capability("PRESET_0"), button_capability("PRESET_1"), button_capability("PRESET_2"), button_capability("PRESET_3"), button_capability("PRESET_4"), button_capability("PRESET_5"), button_capability("PRESET_6"), button_capability("PRESET_7"), button_capability("PRESET_8"), button_capability("PRESET_9"), button_capability("OK", true, false, true), button_capability("SEEKLEFT"), button_capability("SEEKRIGHT"), button_capability("TUNEUP"), button_capability("TUNEDOWN") }, presetBankCapabilities = { onScreenPresetsAvailable = true } } ExpectRequest("Buttons.GetCapabilities", true, buttons_capabilities) ExpectRequest("VR.GetCapabilities", true, { vrCapabilities = { "TEXT" } }) ExpectRequest("TTS.GetCapabilities", true, { speechCapabilities = { "TEXT", "PRE_RECORDED" }, prerecordedSpeechCapabilities = { "HELP_JINGLE", "INITIAL_JINGLE", "LISTEN_JINGLE", "POSITIVE_JINGLE", "NEGATIVE_JINGLE" } }) ExpectRequest("VR.IsReady", true, { available = true }) ExpectRequest("TTS.IsReady", true, { available = true }) ExpectRequest("Navigation.IsReady", true, { available = true }) ExpectRequest("VehicleInfo.IsReady", true, { available = true }) self.applications = { } ExpectRequest("BasicCommunication.UpdateAppList", false, { }) :Pin() :Do(function(_, data) self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", { }) self.applications = { } for _, app in pairs(data.params.applications) do self.applications[app.appName] = app.appID end end) self.hmiConnection:SendNotification("BasicCommunication.OnReady") end --[[@get_data_steeringWheelLocation: read hmi_capabilities parameters: --! steeringWheelLocation, navigation, phoneCall --! @parameters: NO --]] function testCasesForRAI.get_data_steeringWheelLocation() local path_to_file = path_config .. 'hmi_capabilities.json' local file = io.open(path_to_file, "r") local json_data = file:read("*all") file:close() local json = require("modules/json") local data = json.decode(json_data) return data.UI.hmiCapabilities.steeringWheelLocation, data.UI.hmiCapabilities.navigation, data.UI.hmiCapabilities.phoneCall end --[[@write_data_steeringWheelLocation: write value to hmi_capabilities --! in hmi_capabilities.json --! @parameters: value --! @value - new value for steeringWheelLocation --]] function testCasesForRAI.write_data_steeringWheelLocation(steeringWheelLocation, navigation, phoneCall) local path_to_file = path_config .. 'hmi_capabilities.json' local file = io.open(path_to_file, "r") local json_data = file:read("*all") file:close() local json = require("modules/json") local data = json.decode(json_data) if(steeringWheelLocation ~= nil) then data.UI.hmiCapabilities.steeringWheelLocation = steeringWheelLocation end if(navigation ~= nil) then data.UI.hmiCapabilities.navigation = navigation end if(phoneCall ~= nil) then data.UI.hmiCapabilities.phoneCall = phoneCall end data = json.encode(data) file = io.open(path_to_file, "w") file:write(data) file:close() end return testCasesForRAI
local core = require "sys.core" local master = require "cluster.master" core.start(function() local addr = assert(core.envget("master"), "master") local monitor = assert(core.envget("monitor"), "monitor") local capacity = { ['auth'] = 1, ['gate'] = 2, ['role'] = 2, } local ok, err = master.start { monitor = monitor, listen = addr, capacity = capacity } core.log("[main] start success") end)
local thismod = minetest.get_current_modname() local modpath = minetest.get_modpath(thismod) -- Global leash = {} leash.leashes = {} leash.leashed_entities = {} leash.leashed_playernames = {} -- Leash object prototype leash.proto = {} local proto = leash.proto proto.entity_ref = "" proto.origin = {x = 0, y = 100, z = 0} proto.limits = {} proto.buffer_distance = 0.01 proto.show_effect = true proto.effect = {} proto.hud_def = { hud_elem_type = "image", position = {x = 0, y = 0}, name = "leash_hud", scale = {x = 2, y = 2}, number = 1, z_index = -302, size = {x = 100, y = 100}, text = "lens.png" } function proto:new(def) -- Creates new leash object and places reference in global leash table def = def or {} setmetatable(def, proto) proto.__index = self local num = #leash.leashes def.id = num leash.leashes[num+1] = def end function proto:get_entity() local ref = self.entity_ref if(type(ref) == "string")then return minetest.get_player_by_name(ref) elseif(type(ref) == "table")then return ref:get_pos() and ref or nil end end function proto:check_pos() local ent = self:get_entity() return ent and ent:get_pos() end function proto:is_trespassing() local pos = self:check_pos() local origin = self.origin local limit = self.limits local magsort = function(n,n2) local sorted = {n > n2 and n or n2} sorted[2] = n == sorted[1] and n2 or n -- First entry always higher, second entry always lower return sorted end local dist = {} for k,v in pairs(limit) do local origin_axis_value = origin[k] local position_axis_value = pos[k] if(origin_axis_value and position_axis_value)then local oav, pav = origin_axis_value, position_axis_value local vals = magsort(oav,pav) local axis_dist = vals[1] - vals[2] if(axis_dist > math.abs(limit[k]))then return k end end end end function proto:restrain(axis) local ent = self:get_entity() local ori = self.origin[axis] local pos = self:check_pos() local lim = self.limits[axis] local pt = pos[axis] local dist = math.abs(pt)-math.abs(lim) local is_pos = pt > lim local offset = lim-self.buffer_distance pos[axis] = is_pos and ori + offset or ori - offset ent:set_pos(pos) end -- HUD STUFF dofile(modpath .. "/hud.lua") minetest.register_on_joinplayer(function(ObjectRef, last_login) local name = ObjectRef:get_player_name() local g = {} g.entity_ref = name g.limits = {x = 50, y = 50, z = 50} proto:new(g) end) leash.process_leashes = function() local leashes = leash.leashes for n = 1, #leashes do local leash = leashes[n] local is_trespassing = leash:is_trespassing() if(is_trespassing)then leash:restrain(is_trespassing) end leash:say_diff() leash:hud_update() end end minetest.register_globalstep(function(dtime) leash.process_leashes() end)
local registerAsserts = require 'registerAsserts' local SparkSession = require 'stuart-sql.SparkSession' registerAsserts(assert) describe('DataFrameReader.parquet()', function() local filename = 'model2-data-part-00003.parquet' describe(filename, function() it('centroids load', function() local session = SparkSession.builder():getOrCreate() local centroidsDataFrame = session.read:parquet('spec-fixtures/' .. filename) local centroids = centroidsDataFrame:rdd():collect() assert.not_nil(centroids) assert.equal(1, #centroids) assert.equal(0, centroids[1][1]) assert.same({3,4,5}, centroids[1][2]) end) end) end)
function Client_PresentSettingsUI(rootParent) UI.CreateLabel(rootParent) .SetText('Cost per neutral army = ' .. Mod.Settings.CostPerNeutralArmy); end
--------------------------------- --! @file SystemLogger.lua --! @brief ロガー管理クラス定義 --! SILENT ログ出力無し --! 出力する場合は以下の8段階 --! FATAL、ERROR、WARN、INFO、DEBUG、TRACE、VERBOSE、PARANOID --! 現状、loggingライブラリの都合で以下の5段階になっている --! FATAL、ERROR、WARN、INFO、DEBUG --! DEBUG、TRACE、VERBOSE、PARANOIDはDEBUGの出力になる --------------------------------- --[[ Copyright (c) 2017 Nobuhiko Miyamoto ]] local Logger= {} --_G["openrtm.SystemLogger"] = SystemLogger Logger.LogStream = {} local NO_LOGGER = true Logger.SILENT = 0 Logger.FATAL = 1 Logger.ERROR = 2 Logger.WARN = 3 Logger.INFO = 4 Logger.DEBUG = 5 Logger.TRACE = 6 Logger.VERBOSE = 7 Logger.PARANOID = 8 -- 文字列をログレベルに変換 -- @oaram lv 文字列 -- @return ログレベル Logger.strToLogLevel = function(lv) if lv == "SILENT" then return Logger.SILENT elseif lv == "FATAL" then return Logger.FATAL elseif lv == "ERROR" then return Logger.ERROR elseif lv == "WARN" then return Logger.WARN elseif lv == "INFO" then return Logger.INFO elseif lv == "DEBUG" then return Logger.DEBUG elseif lv == "TRACE" then return Logger.TRACE elseif lv == "VERBOSE" then return Logger.VERBOSE elseif lv == "PARANOID" then return Logger.PARANOID else return Logger.INFO end end Logger.printf = function(fmt) return fmt end -- ロガーストリーム初期化 -- @return ロガーストリーム Logger.LogStream.new = function() local obj = {} obj._LogLock = false obj._logger_name = "" obj._loggerObj = {} obj._log_enable = true -- ロガーストリーム終了処理 function obj:shutdown() for k,v in pairs(self._loggerObj) do v:shutdown() end self._loggerObj = {} end -- ロガー追加 -- @param loggerObj ロガー function obj:addLogger(loggerObj) table.insert(self._loggerObj, loggerObj) end -- ログレベル設定 -- @param level ログレベル(文字列) function obj:setLogLevel(level) local lvl = Logger.strToLogLevel(level) for k,v in pairs(self._loggerObj) do v:setLogLevel(lvl) end end function obj:setLogLock(lock) if lock == 1 then self._LogLock = true elseif lock == 0 then self._LogLock = false end end function obj:enableLogLock() self._LogLock = true end function obj:disableLogLock() self._LogLock = false end -- ログ出力 -- @param LV ログレベル -- @param msg 出力フォーマット -- @param ... 値 function obj:RTC_LOG(LV, msg, ...) if self._log_enable then --self.acquire() msg = tostring(msg) for k,v in pairs(self._loggerObj) do v:log(msg:format(...), LV, self._logger_name) end end --self.release() end -- ログ出力(FATAL) -- @param msg 出力フォーマット -- @param ... 値 function obj:RTC_FATAL(msg, ...) --self.acquire() if self._log_enable then msg = tostring(msg) for k,v in pairs(self._loggerObj) do v:log(msg:format(...), Logger.FATAL, self._logger_name) end end --self.release() end -- ログ出力(ERROR) -- @param msg 出力フォーマット -- @param ... 値 function obj:RTC_ERROR(msg, ...) --self.acquire() if self._log_enable then msg = tostring(msg) for k,v in pairs(self._loggerObj) do v:log(msg:format(...), Logger.ERROR, self._logger_name) end end --self.release() end -- ログ出力(WARN) -- @param msg 出力フォーマット -- @param ... 値 function obj:RTC_WARN(msg, ...) --self.acquire() if self._log_enable then msg = tostring(msg) for k,v in pairs(self._loggerObj) do v:log(msg:format(...), Logger.WARN, self._logger_name) end end --self.release() end -- ログ出力(INFO) -- @param msg 出力フォーマット -- @param ... 値 function obj:RTC_INFO(msg, ...) --self.acquire() if self._log_enable then msg = tostring(msg) for k,v in pairs(self._loggerObj) do v:log(msg:format(...), Logger.INFO, self._logger_name) end end --self.release() end -- ログ出力(DEBUG) -- @param msg 出力フォーマット -- @param ... 値 function obj:RTC_DEBUG(msg, ...) --self.acquire() if self._log_enable then msg = tostring(msg) for k,v in pairs(self._loggerObj) do v:log(msg:format(...), Logger.DEBUG, self._logger_name) end end --self.release() end -- ログ出力(TRACE) -- @param msg 出力フォーマット -- @param ... 値 function obj:RTC_TRACE(msg, ...) --self.acquire() if self._log_enable then msg = tostring(msg) for k,v in pairs(self._loggerObj) do v:log(msg:format(...), Logger.TRACE, self._logger_name) end end --self.release() end -- ログ出力(VERBOSE) -- @param msg 出力フォーマット -- @param ... 値 function obj:RTC_VERBOSE(msg, ...) --self.acquire() if self._log_enable then msg = tostring(msg) for k,v in pairs(self._loggerObj) do v:log(msg:format(...), Logger.VERBOSE, self._logger_name) end end --self.release() end -- ログ出力(PARANOID) -- @param msg 出力フォーマット -- @param ... 値 function obj:RTC_PARANOID(msg, ...) --self.acquire() if self._log_enable then msg = tostring(msg) for k,v in pairs(self._loggerObj) do v:log(msg:format(...), Logger.PARANOID, self._logger_name) end end --self.release() end -- 指定名のロガー取得 -- @param name ロガー名 -- @return ロガー function obj:getLogger(name) local syslogger = {} for k,v in pairs(self) do syslogger[k] = v end syslogger._logger_name = name return syslogger end return obj end return Logger
mhf = require("schema_processor") unistd = require("posix.unistd"); local xml_string = [=[<?xml version="1.0" encoding="UTF-8"?> <ns1:array_struct xmlns:ns1="http://test_example.com"> <author>123</author> <author>456</author> <author>789</author> <author>012</author> <author>234</author> <title>1</title> <title>2</title> <title>3</title> <genre>as</genre> <genre>bs</genre> <ns1:basic_string_simple_content attr2="CHA" attr1="123">SRIRAM</ns1:basic_string_simple_content> <ns1:basic_string_simple_content attr2="CHA" attr1="123">GOWRI</ns1:basic_string_simple_content> </ns1:array_struct>]=] mhf = require("schema_processor") array_struct = mhf:get_message_handler("array_struct", "http://test_example.com"); local content, msg = array_struct:from_xml(xml_string) if (type(content) == 'table') then require 'pl.pretty'.dump(content); else print(content, msg) end if (nil ~= content) then print(array_struct:to_json(content)); end if (nil ~= content) then print(array_struct:to_xml(content)); end if (content ~= nil) then os.exit(true); else os.exit(false); end
local players = {} local function tick(name) if players[name] == nil then return end if not minetest.get_player_by_name(name) or minetest.check_player_privs(name, {interact=true}) == true then players[name] = nil return end if minetest.check_player_privs(name, {shout=true}) then minetest.chat_send_player(name, "Hey " .. name .. " ! Pour pouvoir construire et intéragir sur ce serveur, tu dois lire les règles du serveur et les accepter. Tape /rules.") minetest.chat_send_player(name, "Hey " .. name .. " ! To build and interact on this server, you have to read the rules of our server and agree them. Type /rules.") end minetest.after(20, tick, name) end minetest.register_on_joinplayer(function(player) local name = player:get_player_name() if not minetest.check_player_privs(name, {interact=true}) and players[name] == nil then minetest.after(7, tick, name) players[name] = true end end) minetest.register_on_leaveplayer(function(player) local name = player:get_player_name() if not name then return end players[name] = nil end)
function class(base, init) local c = {} -- a new class instance if not init and type(base) == 'function' then init = base base = nil elseif type(base) == 'table' then -- our new class is a shallow copy of the base class! for i,v in pairs(base) do c[i] = v end c._base = base end -- the class will be the metatable for all its objects, -- and they will look up their methods in it. c.__index = c -- expose a constructor which can be called by <classname>(<args>) local mt = {} mt.__call = function(class_tbl, ...) local obj = {} setmetatable(obj,c) if class_tbl.init then class_tbl.init(obj,...) --if init then -- init(obj,...) else -- make sure that any stuff from the base class is initialized! if base and base.init then base.init(obj, ...) end end return obj end c.init = init c.is_a = function(self, klass) local m = getmetatable(self) while m do if m == klass then return true end m = m._base end return false end setmetatable(c, mt) return c end A = class() function A:init(x) self.x = x end function A:test() print(self.x) end B = class(A) function B:init(x,y) A.init(self,x) self.y = y end
require("Examples.08_Container.Container") require("Examples.08_Container.Child") require("Framework.event.Event") ---@class Examples.08_Container.logic_08 ---@field ui Examples.08_Container.Container logic_08 = class("Examples.08_Container.logic_08") function logic_08:ctor() self.ui = Container.New() local child = Child.New() self.ui:AddChild(child) self.ui:AddEventListener("click", self, self.onClickUI) child.m_Button.EventClick:Add(self, self.onClickBtn) child:AddEventListener("click", self, self.onClickChild) end ---onClickUI ---@param evt Framework.event.Event function logic_08:onClickUI(evt) LogUtil.LogError("onClickUI target:%s curTarget:%s", evt.target.name, evt.currentTarget.name) end ---onClickChild ---@param evt Framework.event.Event function logic_08:onClickChild(evt) LogUtil.LogError("onClickChild target:%s curTarget:%s", evt.target.name, evt.currentTarget.name) evt:StopBubble() end ---onClickBtn ---@param evt Framework.event.Event function logic_08:onClickBtn(evt) LogUtil.LogError("onClickBtn target:%s curTarget:%s", evt.target.name, evt.currentTarget.name) end return logic_08
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf/protobuf" module('FlowerRecord_pb') FLOWERRECORD = protobuf.Descriptor(); local FLOWERRECORD_ROLEID_FIELD = protobuf.FieldDescriptor(); local FLOWERRECORD_COUNT_FIELD = protobuf.FieldDescriptor(); local FLOWERRECORD_UPDATEDAY_FIELD = protobuf.FieldDescriptor(); local FLOWERRECORD_GETRANKREWARD_FIELD = protobuf.FieldDescriptor(); local FLOWERRECORD_GETFLOWERTIME_FIELD = protobuf.FieldDescriptor(); local FLOWERRECORD_GETFLOWERNUM_FIELD = protobuf.FieldDescriptor(); FLOWERRECORD_ROLEID_FIELD.name = "roleid" FLOWERRECORD_ROLEID_FIELD.full_name = ".KKSG.FlowerRecord.roleid" FLOWERRECORD_ROLEID_FIELD.number = 1 FLOWERRECORD_ROLEID_FIELD.index = 0 FLOWERRECORD_ROLEID_FIELD.label = 3 FLOWERRECORD_ROLEID_FIELD.has_default_value = false FLOWERRECORD_ROLEID_FIELD.default_value = {} FLOWERRECORD_ROLEID_FIELD.type = 4 FLOWERRECORD_ROLEID_FIELD.cpp_type = 4 FLOWERRECORD_COUNT_FIELD.name = "count" FLOWERRECORD_COUNT_FIELD.full_name = ".KKSG.FlowerRecord.count" FLOWERRECORD_COUNT_FIELD.number = 2 FLOWERRECORD_COUNT_FIELD.index = 1 FLOWERRECORD_COUNT_FIELD.label = 3 FLOWERRECORD_COUNT_FIELD.has_default_value = false FLOWERRECORD_COUNT_FIELD.default_value = {} FLOWERRECORD_COUNT_FIELD.type = 13 FLOWERRECORD_COUNT_FIELD.cpp_type = 3 FLOWERRECORD_UPDATEDAY_FIELD.name = "updateday" FLOWERRECORD_UPDATEDAY_FIELD.full_name = ".KKSG.FlowerRecord.updateday" FLOWERRECORD_UPDATEDAY_FIELD.number = 3 FLOWERRECORD_UPDATEDAY_FIELD.index = 2 FLOWERRECORD_UPDATEDAY_FIELD.label = 1 FLOWERRECORD_UPDATEDAY_FIELD.has_default_value = false FLOWERRECORD_UPDATEDAY_FIELD.default_value = 0 FLOWERRECORD_UPDATEDAY_FIELD.type = 13 FLOWERRECORD_UPDATEDAY_FIELD.cpp_type = 3 FLOWERRECORD_GETRANKREWARD_FIELD.name = "getRankReward" FLOWERRECORD_GETRANKREWARD_FIELD.full_name = ".KKSG.FlowerRecord.getRankReward" FLOWERRECORD_GETRANKREWARD_FIELD.number = 4 FLOWERRECORD_GETRANKREWARD_FIELD.index = 3 FLOWERRECORD_GETRANKREWARD_FIELD.label = 1 FLOWERRECORD_GETRANKREWARD_FIELD.has_default_value = false FLOWERRECORD_GETRANKREWARD_FIELD.default_value = false FLOWERRECORD_GETRANKREWARD_FIELD.type = 8 FLOWERRECORD_GETRANKREWARD_FIELD.cpp_type = 7 FLOWERRECORD_GETFLOWERTIME_FIELD.name = "getFlowerTime" FLOWERRECORD_GETFLOWERTIME_FIELD.full_name = ".KKSG.FlowerRecord.getFlowerTime" FLOWERRECORD_GETFLOWERTIME_FIELD.number = 5 FLOWERRECORD_GETFLOWERTIME_FIELD.index = 4 FLOWERRECORD_GETFLOWERTIME_FIELD.label = 1 FLOWERRECORD_GETFLOWERTIME_FIELD.has_default_value = false FLOWERRECORD_GETFLOWERTIME_FIELD.default_value = 0 FLOWERRECORD_GETFLOWERTIME_FIELD.type = 13 FLOWERRECORD_GETFLOWERTIME_FIELD.cpp_type = 3 FLOWERRECORD_GETFLOWERNUM_FIELD.name = "getFlowerNum" FLOWERRECORD_GETFLOWERNUM_FIELD.full_name = ".KKSG.FlowerRecord.getFlowerNum" FLOWERRECORD_GETFLOWERNUM_FIELD.number = 6 FLOWERRECORD_GETFLOWERNUM_FIELD.index = 5 FLOWERRECORD_GETFLOWERNUM_FIELD.label = 1 FLOWERRECORD_GETFLOWERNUM_FIELD.has_default_value = false FLOWERRECORD_GETFLOWERNUM_FIELD.default_value = 0 FLOWERRECORD_GETFLOWERNUM_FIELD.type = 13 FLOWERRECORD_GETFLOWERNUM_FIELD.cpp_type = 3 FLOWERRECORD.name = "FlowerRecord" FLOWERRECORD.full_name = ".KKSG.FlowerRecord" FLOWERRECORD.nested_types = {} FLOWERRECORD.enum_types = {} FLOWERRECORD.fields = {FLOWERRECORD_ROLEID_FIELD, FLOWERRECORD_COUNT_FIELD, FLOWERRECORD_UPDATEDAY_FIELD, FLOWERRECORD_GETRANKREWARD_FIELD, FLOWERRECORD_GETFLOWERTIME_FIELD, FLOWERRECORD_GETFLOWERNUM_FIELD} FLOWERRECORD.is_extendable = false FLOWERRECORD.extensions = {} FlowerRecord = protobuf.Message(FLOWERRECORD)
require "xlog" require "xclass" local log = xlog("xclients") xclients = xclass { __create = function (self) self.clients = {} return self end, get_clients_count = function (self) local count = 0 for _ in pairs(self.clients) do count = count + 1 end return count end, check_client = function (self, client_id) if self.clients[client_id] then return true end log("debug", "client not found: %d", client_id) return false end, broadcast = function (self, package) package:dump_head() local buffer = package:get() for _, client in pairs(self.clients) do client.socket:send(buffer) end return package end, dispatch = function (self, package) if package.id_to == 0 then return self:broadcast(package) end if self:check_client(package.id_to) then package:transmit(self.clients[package.id_to]) end return package end, }
local http = require "socket.http" local ltn12 = require "ltn12" local baseurl = "http://api.projecthawkthorne.com" local glove = require 'vendor/glove' local channel = glove.thread.getChannel("mixpanel") while true do local payload = channel:demand() http.request { method = "POST", url = baseurl .. "/metrics", headers = { ["content-type"] = "application/json", ["content-length"] = tostring(payload:len()) }, source = ltn12.source.string(payload), } end
openIn:whatever( 4, false )
local function god(ply, args) if (!ply:hasPerm("God")) then return am.broadcast(ply, "You aren't staff! You can't do this!"); end local user = am.finduser(args[1]); if (!user) then return am.broadcast(ply, "User not found!"); end if (!user:Alive()) then return am.broadcast(ply, "User is not alive!"); end if (!user:IsValid()) then return am.broadcast(ply, "User is invalid?"); end user:GodEnable(); am.broadcast(Color(25, 255, 25), ply:Nick(), Color(255, 255, 255), " has enabled god mode on ", Color(25, 255, 25), user:Nick()); end AddChatCommand("!god", god); local function ungod(ply, args) if (!ply:hasPerm("UnGod")) then return am.broadcast(ply, "You aren't staff! You can't do this!"); end local user = am.finduser(args[1]); if (!user) then return am.broadcast(ply, "User not found!"); end if (!user:Alive()) then return am.broadcast(ply, "User is not alive!"); end if (!user:IsValid()) then return am.broadcast(ply, "User is invalid?"); end user:GodDisable(); am.broadcast(Color(25, 255, 25), ply:Nick(), Color(255, 255, 255), " has disabled god mode on ", Color(25, 255, 25), user:Nick()); end AddChatCommand("!ungod", ungod);
local Clockwork = Clockwork; local PLUGIN = PLUGIN; -- A function to load the fields. function PLUGIN:LoadFields() local fields = Clockwork.kernel:RestoreSchemaData("plugins/ff/"..game.GetMap()); for k, v in pairs(fields) do local entity = ents.Create("cw_forcefield"); entity:SetAngles(v.angles); entity:SetPos(v.position); entity:Spawn(); entity:Activate(); local physicsObject = entity:GetPhysicsObject(); if ( IsValid(physicsObject) ) then physicsObject:EnableMotion(false); end; end; end; -- A function to save the fields. function PLUGIN:SaveFields() local fields = {}; for k, v in pairs(ents.FindByClass("cw_forcefield")) do local position = v:GetPos(); local angles = v:GetAngles(); fields[#fields + 1] = { position = position, angles = angles, }; end; Clockwork.kernel:SaveSchemaData("plugins/ff/"..game.GetMap(), fields); end;
local view = require'nvim-tree.view' local M = {} function M.compute_lines() local help_lines = {'HELP'} local help_hl = {{'NvimTreeRootFolder', 0, 0, #help_lines[1]}} local mappings = vim.tbl_filter(function(v) return v.cb ~= nil and v.cb ~= "" end, view.View.mappings) local processed = {} for _, b in pairs(mappings) do local cb = b.cb local key = b.key local name if cb:sub(1,35) == view.nvim_tree_callback('test'):sub(1,35) then name = cb:match("'[^']+'[^']*$") name = name:match("'[^']+'") table.insert(processed, {key, name, true}) else name = (b.name ~= nil) and b.name or cb name = '"' .. name .. '"' table.insert(processed, {key, name, false}) end end table.sort(processed, function(a,b) return (a[3] == b[3] and (a[2] < b[2] or (a[2] == b[2] and #a[1] < #b[1]))) or (a[3] and not b[3]) end) local num = 0 for _, val in pairs(processed) do local keys = type(val[1]) == "string" and {val[1]} or val[1] local map_name = val[2] local builtin = val[3] for _, key in pairs(keys) do num = num + 1 local bind_string = string.format("%6s : %s", key, map_name) table.insert(help_lines, bind_string) local hl_len = math.max(6, string.len(key)) + 2 table.insert(help_hl, {'NvimTreeFolderName', num, 0, hl_len}) if not builtin then table.insert(help_hl, {'NvimTreeFileRenamed', num, hl_len, -1}) end end end return help_lines, help_hl end return M
--TODO: Depends - wood, gear, steel, stick, stone --TODO: Steel requires forgin of head --TODO: Tiles crafting.register_type('tools') workbench.register('toolbench:lvl1', 'tools', 1, { description = 'Tool workbench', tiles = { "workbench_top.png^level1.png", "workbench_bottom.png^level1.png", {name = "workbench_side.png^level1.png^default_tool_woodpick.png", tileable_vertical = false} }, }) workbench.register('toolbench:lvl2', 'tools', 2, { description = 'Tool workbench', tiles = { "workbench_top.png^level2.png", "workbench_bottom.png^level2.png", {name = "workbench_side.png^level2.png^default_tool_stonepick.png", tileable_vertical = false} }, inventory = { x = 8, y = 3 }, }) workbench.register('toolbench:lvl3', 'tools', 3, { description = 'Tool workbench', tiles = { "workbench_top.png^level3.png", "workbench_bottom.png^level3.png", {name = "workbench_side.png^level3.png^default_tool_steelpick.png", tileable_vertical = false} }, inventory = { x = 8, y = 4 }, }) --[[ -- Awards -------------------------------------- awards.register_award("toolbench:lvl1", { description = "Creating tools", -- Optional: --requires = { "amod:an_award" }, --background = "background_image.png", trigger = { type = "craft", item = "toolbench:lvl1" }, on_unlock = function(name, award_def) end, }) awards.register_award("toolbench:lvl2", { description = "Upgrading the toolbench", requires = { "toolbench:level1" }, --background = "background_image.png", trigger = { type = "craft", item = "toolbench:lvl2" }, on_unlock = function(name, award_def) end, }) ]] -- -- Crafts --------------------------------------- dofile(minetest.get_modpath("toolbench").."/crafts.lua")
local UTILS = {} -- # trilateration formulas to return the (x,y) intersection point of three circles local function trilateration(x1,y1,r1,x2,y2,r2,x3,y3,r3) local A = 2*x2 - 2*x1 local B = 2*y2 - 2*y1 local C = math.pow(r1, 2) - math.pow(r2, 2) - math.pow(x1, 2) + math.pow(x2, 2) - math.pow(y1, 2) + math.pow(y2, 2) local D = 2*x3 - 2*x2 local E = 2*y3 - 2*y2 local F = math.pow(r2, 2) - math.pow(r3, 2) - math.pow(x2,2) + math.pow(x3,2) - math.pow(y2,2) + math.pow(y3,2) local x = (C*E - F*B) / (E*A - B*D) local y = (C*D - A*F) / (B*D - A*E) return x, y end -- ###################### -- ToA - Time Of Arrival -- --  Distance = Velocity * Travel Time --  Travel Time = Receiving Timestamp - Sending Timestamp --  The problem becomes how to validate the timestamp -- • Synchronization -- ###################### -- Wave velocity difference based: --  Two waves of different velocity are sent from the sender -- • Can be an electromagnetic wave + a sound wave --  Record the timestamp in receiver only -- • Arrival timestamp of electromagnetic wave tr -- • Arrival timestamp of sound wave ts local function time_of_arrival_wave_velocity(vr, vs, ts, tr) return (vr * vs * (ts - tr)) / (vr - vs) end --  Two waves of different velocity are sent from the sender -- • Can be an electromagnetic wave + a sound wave --  Record the timestamp in receiver only -- • Arrival timestamp of electromagnetic wave tr -- • Arrival timestamp of sound wave ts local function time_of_arrival_return_time(v, t, t0, t_delay) return (v * (t - t0 - t_delay)) / 2 end -- ###################### -- Time Difference of Arrival --  Difference of Distance based --  Improvement: does not require the receiver to be synchronized --  Limitation: still require all the senders' clocks to be synchronized -- ###################### -- Principle --  Distance Difference = Velocity * (Travel Time 1 - Travel Time 2) --  The target sends out the signal, two receivers are used --  The position of the target/sender (x,y) is determined by -- • The positions of receiver 1 (xi,yi) and receiver 2 (xj,yj) -- • The calculated distance difference Δdij --  2 groups of data/differences are needed to solve the equation -- -- Limitations for both ToA and TDoA --  Require customised sender and receiver --  Additional device --  Additional cost local function time_difference_of_arrival(x1, y1, x2, y2, x3, y3) return math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2)) - math.sqrt(math.pow(x1 - x3, 2) + math.pow(y1, y3)) end -- ################# -- WIFI BASED LOCALIZATION -- Steps: --  Scan the available APs --  Get the RSSI for each reference --  Filter the RSSI of outliers --  Calculate the position -- • Formula required -- • RSSI = – (10*n*log10d + R) -- • R is the RSSI when distance is 1 unit, d is the distance, n is the factor -- (RSSI) Received Signal Strength Indication -- R is the RSSI when distance is 1 unit, d is the distance, n is the factor -- Prior setup: --  Measure the initial RSSI --  Potisions of APs should be stable local function received_signal_strength_indication(n, d, R) return -(10 * n * math.log(d, 10) + R) end UTILS.trilateration = trilateration UTILS.time_of_arrival_wave_velocity = time_of_arrival_wave_velocity UTILS.time_of_arrival_return_time = time_of_arrival_return_time UTILS.time_difference_of_arrival = time_difference_of_arrival UTILS.received_signal_strength_indication = received_signal_strength_indication return UTILS
script.Parent = nil text = "hours:mins:secs" main = Vector3.new(-10,1.7,40) sec = nil min = nil ho = nil mod = nil function makeclock() for _,v in pairs(workspace:children()) do if v.Name == "xSclock" then v:remove() end end local m = Instance.new("Model",workspace) m.Name = "xSclock" local o = 5 local humbug = 5 for i=0,354,6 do local p = Instance.new("Part",m) p.formFactor = "Custom" p.TopSurface = "Smooth" Instance.new("BlockMesh",p) if o >= 5 then p.Size = Vector3.new(0.9,1,2.6) p.BrickColor = BrickColor.new("Institutional white") o = 0 else p.Size = Vector3.new(0.5,0.8,0.8) end if humbug == 5 then p.Size = Vector3.new(1,1,4.5) p.BrickColor = BrickColor.new("New Yeller") local bil = Instance.new("BillboardGui",p) bil.Adornee = p bil.Size = UDim2.new(0,200,0,200) local tx = Instance.new("TextLabel",bil) tx.BackgroundTransparency = 1 tx.Size = bil.Size tx.Position = UDim2.new(0,0,0,-80) tx.TextWrap = true tx.TextColor3 = Color3.new(1,1,0) tx.FontSize = "Size24" coroutine.resume(coroutine.create(function() while m.Parent ~= nil do wait(0.1) local tim = time() local hours = math.floor((tim/60)/60 % 24) local mins = math.floor(tim/60 % 60) local secs = math.floor(tim % 60) if hours < 10 then hours = "0"..hours end if mins < 10 then mins = "0"..mins end if secs < 10 then secs = "0"..secs end local t = text:gsub("hours", hours) local te = t:gsub("mins", mins) local tex = te:gsub("secs", secs) tx.Text = tex end end)) humbug = 0 end p.Anchored = true p.CFrame = CFrame.new(main) * CFrame.Angles(0,math.rad(i),0) * CFrame.new(0,0,-15) o = o + 1 end local se = Instance.new("Part",m) se.formFactor = "Custom" se.Size = Vector3.new(0.8,0.8,14) se.Anchored = true se.BrickColor = BrickColor.new("Bright red") se.CFrame = CFrame.new(main) * CFrame.new(0,0,-se.Size.Z/2) Instance.new("BlockMesh",se) local mi = Instance.new("Part",m) mi.formFactor = "Custom" mi.Size = Vector3.new(0.8,0.8,15) mi.BrickColor = BrickColor.new("Dark green") mi.Anchored = true mi.CFrame = CFrame.new(main) * CFrame.new(0,0,-mi.Size.Z/2) Instance.new("BlockMesh",mi) local h = Instance.new("Part",m) h.formFactor = "Custom" h.Size = Vector3.new(0.6,0.6,11) h.BrickColor = BrickColor.new("White") h.Anchored = true h.CFrame = CFrame.new(main) * CFrame.new(0,0,-h.Size.Z/2) Instance.new("BlockMesh",h) sec = se min = mi ho = h mod = m local huh = Instance.new("Part",m) huh.Size = Vector3.new(34,1,34) huh.Anchored = true huh.CFrame = CFrame.new(main) * CFrame.new(0,-0.4,0) huh.BrickColor = BrickColor.new("Black") Instance.new("CylinderMesh",huh) local mmm = huh:clone() mmm.Parent = m mmm.Size = Vector3.new(2,1,2) mmm.CFrame = CFrame.new(main) mmm.BrickColor = BrickColor.new("Really black") local able = true local function change(pr) if pr == "Parent" and able then able = false for _,v in pairs(workspace:children()) do if v.Name == "xSclock" then v:remove() end end makeclock() end end for _,v in pairs(mod:children()) do v.Changed:connect(change) end mod.Changed:connect(change) end makeclock() while true do pcall(function() local ti = time() local angs = CFrame.Angles(0,math.rad(-ti*6),0) local angm = CFrame.Angles(0,math.rad(-(ti*6)/60),0) local angh = CFrame.Angles(0,math.rad(-((ti*6)/60))/12,0) sec.CFrame = CFrame.new(main) * angs * CFrame.new(0,0,-sec.Size.Z/2) min.CFrame = CFrame.new(main) * angm * CFrame.new(0,0,-min.Size.Z/2) ho.CFrame = CFrame.new(main) * angh * CFrame.new(0,0,-ho.Size.Z/2) end) wait(0.1) end
print("Solving 2015, day 1") local directions = nil for line in io.lines("Day01.txt") do directions = line end local floor = 0 local basement = 0 for i = 1, #directions do -- print(string.byte(directions,i)) -- open: 40 -- closed: 41 local isOpenParenthesis = string.byte(directions,i) == 40 if isOpenParenthesis then floor = floor + 1 else floor = floor - 1 end if floor == -1 and basement == 0 then basement = i end end print(floor) print(basement)
--- TDLib client. -- @classmod Client local ffi = require("ffi") local cjson = require("cjson") local class = require("middleclass") local Client = class("luajit-tdlib.Client") function Client:initialize(clib) --- The internal loaded FFI object of tdlib (clib). -- @local self._clib = clib --- The internal void* pointer to the tdlib client (ctype). -- @local self._client = self._clib.td_json_client_create() -- Set the finalizer. local client = self._client ffi.gc(self._client, function() clib.td_json_client_destroy(client) end) end --- Sends a request to the TDLib client. -- May be called from any thread. -- @tparam table request The request content (JSON-serialized internally). -- @raise Error on json encoding failure, or if the client was destroyed. function Client:send(request) if not self._client then return error("The client is destroyed!") end request = cjson.encode(request) self._clib.td_json_client_send(self._client, request) end --- Receives incoming updates and request responses from the TDLib client. -- May be called from any thread, but shouldn't be called simultaneously from two different threads. -- @tparam number timeout The maximum number of seconds allowed for this function to wait for new data. -- @treturn ?table The request response, may be `nil` if the timeout expires. -- @raise Error on json decoding failure, or if the client was destroyed. function Client:receive(timeout) if not self._client then return error("The client is destroyed!") end local response = self._clib.td_json_client_receive(self._client, timeout) if response == ffi.NULL then return end response = ffi.string(response) response = cjson.decode(response) return response end --- Synchronously executes TDLib request. -- May be called from any thread. -- -- Only a few requests can be executed synchronously. -- @tparam table request The request content (JSON-serialized internally). -- @treturn table The request response. -- @raise Error on json en/decoding failure, or if the client was destroyed. function Client:execute(request) if not self._client then return error("The client is destroyed!") end request = cjson.encode(request) local response = self._clib.td_json_client_execute(self._client, request) response = ffi.string(response) response = cjson.decode(response) return response end --- Check if the tdlib client was destroyed or not. -- @treturn boolean Whether the client was destroyed or not. function Client:isDestoyed() return not self._client end --- Destroy the tdlib client, automatically happens in garbage collection. -- @raise Error if the client was already destroyed. function Client:destroy() if not self._client then return error("The client was already destroyed!") end self._client = nil end return Client
local player = require 'lib.ent.player' local enemy = require 'lib.ent.enemy' local bullet = require 'lib.ent.bullet' local missle = require 'lib.ent.missle' local planet = require 'lib.ent.planet' local radio = require 'lib.ent.radio' local smoke = require 'lib.ent.smoke' local ecs = {} function ecs.new(model, x, y ,vx, vy, rot) local self = {} self.model = model self.isDead = false if model == "player" then self = player.inherit(x, y) elseif model == "enemy" then self = enemy.inherit(x, y) elseif model == "bullet" then self = bullet.inherit(x, y, vx, vy, rot) elseif model == "missle" then self = missle.inherit(x, y, vx, vy, rot) elseif model == "planet" then self = planet.inherit(x, y) elseif model == "radio" then self = radio.inherit(x, y) elseif model == "smoke" then self = smoke.inherit(x, y) end return self end return ecs
dofile ("raylib_premake5.lua") dofile ("examples_premake5.lua") workspace "raylib" configurations { "Debug","Debug.DLL", "Release", "Release.DLL" } platforms { "x64" } filter "configurations:Debug" defines { "DEBUG" } symbols "On" filter "configurations:Debug.DLL" defines { "DEBUG" } symbols "On" filter "configurations:Release" defines { "NDEBUG" } optimize "On" filter "configurations:Release.DLL" defines { "NDEBUG" } optimize "On" filter { "platforms:x64" } architecture "x86_64" targetdir "bin/%{cfg.buildcfg}/" raylib() examples()
--- -- @author wesen -- @copyright 2020 wesen <[email protected]> -- @release 0.1 -- @license MIT -- local luaunit = require "luaunit" local mach = require "mach" local Object = require "classic" local TestFunctionWrapper = Object:extend() function TestFunctionWrapper:setUp() package.loaded["ArgumentListWrapper.ArgumentListWrapper"] = nil local ArgumentListWrapper = require "ArgumentListWrapper.ArgumentListWrapper" self.argumentListWrapperDependency = ArgumentListWrapper self.argumentListWrapperDependencyMock = mach.mock_object(ArgumentListWrapper, "ArgumentListWrapperDependencyMock") setmetatable(self.argumentListWrapperDependencyMock, { __call = function(...) return self.argumentListWrapperDependencyMock.__call(...) end }) package.loaded["ArgumentListWrapper.ArgumentListWrapper"] = self.argumentListWrapperDependencyMock package.loaded["FunctionWrapper"] = nil self.functionWrapperClass = require "FunctionWrapper" end function TestFunctionWrapper:tearDown() package.loaded["ArgumentListWrapper.ArgumentListWrapper"] = self.argumentListWrapperDependency end function TestFunctionWrapper:testCanWrapFunction() local wrappedFunctionMock = mach.mock_function("wrappedFunctionMock") local argumentListWrapperMock = mach.mock_object(self.argumentListWrapperDependency, "ArgumentListWrapperMock") local functionWrapper self.argumentListWrapperDependencyMock.__call :should_be_called() :and_will_return(argumentListWrapperMock) :when( function() functionWrapper = self.functionWrapperClass(wrappedFunctionMock) end ) local returnValueA, returnValueB, returnValueC, returnValueD, returnValueE argumentListWrapperMock.getFilteredArguments :should_be_called_with("hallo", 1, 6, 4, 1, "welt") :and_will_return(6, 4, "welt") :and_then( wrappedFunctionMock:should_be_called_with(6, 4, "welt") :and_will_return("here", "are", "your", "return", "values") ) :when( function() returnValueA, returnValueB, returnValueC, returnValueD, returnValueE = functionWrapper("hallo", 1, 6, 4, 1, "welt") end ) luaunit.assertEquals(returnValueA, "here") luaunit.assertEquals(returnValueB, "are") luaunit.assertEquals(returnValueC, "your") luaunit.assertEquals(returnValueD, "return") luaunit.assertEquals(returnValueE, "values") end return TestFunctionWrapper
local Log = require("uic/log"); local Util = require("uic/util"); local Components = require("uic/components"); local Text = {} --# assume Text: TEXT --v function(name: string, parent: CA_UIC | COMPONENT_TYPE, textType: TEXT_TYPE, textToDisplay: string) --> TEXT function Text.new(name, parent, textType, textToDisplay) local parentComponent = Components.getUiContentComponent(parent); local text = nil --: CA_UIC if textType == "NORMAL" then text = Util.createComponent(name, parentComponent, "ui/uimf/text_black_12_parchment"); elseif textType == "HEADER" then text = Util.createComponent(name, parentComponent, "ui/uimf/text_black_14_parchment_header"); elseif textType == "WRAPPED" then text = Util.createComponent( name, parentComponent, "ui/campaign ui/mission_details", "mission_details_child", "description_background", "description_view", "dy_description" ); elseif textType == "TITLE" then text = Util.createComponent( name, parentComponent, "ui/campaign ui/objectives_screen", "panel_title", "tx_objectives" ); else Log.write("Invalid text type:" .. textType); end text:DestroyChildren(); text:SetStateText(textToDisplay); local self = {}; setmetatable(self, { __index = Text }) --# assume self: TEXT self.uic = text --: const self.name = name --: const self.textType = textType --: const Util.registerComponent(name, self); return self; end -- Component functions --v function(self: TEXT, xPos: number, yPos: number) function Text.MoveTo(self, xPos, yPos) self.uic:MoveTo(xPos, yPos); end --v function(self: TEXT, xMove: number, yMove: number) function Text.Move(self, xMove, yMove) Components.move(self.uic, xMove, yMove); end --v function(self: TEXT, component: CA_UIC | COMPONENT_TYPE, xDiff: number, yDiff: number) function Text.PositionRelativeTo(self, component, xDiff, yDiff) Components.positionRelativeTo(self.uic, component, xDiff, yDiff); end --v function(self: TEXT) --> (number, number) function Text.Position(self) return self.uic:Position(); end --v function(self: TEXT) --> (number, number) function Text.Bounds(self) return self.uic:Bounds(); end --v function(self: TEXT) --> number function Text.XPos(self) local xPos, yPos = self:Position(); return xPos; end --v function(self: TEXT) --> number function Text.YPos(self) local xPos, yPos = self:Position(); return yPos; end --v function(self: TEXT) --> number function Text.Width(self) local width, height = self:Bounds(); return width; end --v function(self: TEXT) --> number function Text.Height(self) local width, height = self:Bounds(); return height; end --v function(self: TEXT, visible: boolean) function Text.SetVisible(self, visible) return self.uic:SetVisible(visible); end --v function(self: TEXT) --> boolean function Text.Visible(self) return self.uic:Visible(); end --v function(self: TEXT) --> CA_UIC function Text.GetContentComponent(self) return self.uic; end --v function(self: TEXT) --> CA_UIC function Text.GetPositioningComponent(self) return self.uic; end --v function(self: TEXT) function Text.Delete(self) Util.delete(self.uic); Util.unregisterComponent(self.name); end -- Custom functions --v function(self: TEXT, text: string) function Text.SetText(self, text) local xPos, yPos = self.uic:Position(); self.uic:SetStateText(text); self.uic:MoveTo(xPos, yPos); end --v function(self: TEXT) --> string function Text.GetText(self) return self.uic:GetStateText(); end --v function(self: TEXT, factor: number) function Text.Scale(self, factor) local width, height = self:Bounds(); self.uic:SetCanResizeHeight(true); self.uic:SetCanResizeWidth(true); self.uic:ResizeTextResizingComponentToInitialSize(width * factor, height * factor); self:SetText(self:GetText()); self.uic:SetCanResizeHeight(false); self.uic:SetCanResizeWidth(false); end --v function(self: TEXT, width: number, height: number) function Text.Resize(self, width, height) self.uic:SetCanResizeHeight(true); self.uic:SetCanResizeWidth(true); self.uic:ResizeTextResizingComponentToInitialSize(width, height); self:SetText(self:GetText()); self.uic:SetCanResizeHeight(false); self.uic:SetCanResizeWidth(false); end return { new = Text.new; }
local PANEL = {} function PANEL:Init() self:SetSize(500, 150) local sw, sh = ScrW(), ScrH() local ww, wh = self:GetSize() self:SetPos(sw/2 - ww/2, sh - wh - 100) self:SetTitle("Vote (F2 to activate)") local seconds = 10 self.setTime = CurTime() + seconds self.id = 0 self.name = self:Add("DLabel") self.name:DockMargin(2, 2, 2, 2) self.name:Dock(TOP) local x, y = self.name:GetSize() self.name:SetSize(x, y + 20) self.name:SetFont("nutChatFont") self.name:SetTextColor(color_white) self.name:SetContentAlignment(5) self.name:SetText("Starting Vote.") self.name:SetExpensiveShadow(1, Color(0, 0, 0, 150)) self.buttons = self:Add("DPanel") self.buttons:DockMargin(2, 2, 2, 2) self.buttons:Dock(FILL) self.buttons.Paint = function() local w, h = self.buttons:GetSize() local p = (self.setTime - CurTime()) / seconds draw.RoundedBox(0, 0, h-2, w*p, 2, color_white) if (p < 0) then self:Close() end end self.a = self.buttons:Add("DButton") self.a:DockMargin(22, 12, 2, 20) self.a:Dock(LEFT) self.a:SetSize(120,0) self.a:SetTextColor(color_white) self.a:SetText(L"yes") self.a.DoClick = function() self:sendResult(1) end self.b = self.buttons:Add("DButton") self.b:DockMargin(22, 12, 22, 20) self.b:Dock(RIGHT) self.b:SetSize(120,0) self.b:SetTextColor(color_white) self.b:SetText(L"no") self.b.DoClick = function() self:sendResult(0) end if (nut.vote) then local voteID = self.id nut.vote.list[voteID] = self end end function PANEL:OnClose() local voteID = self.id if (nut.vote.list[voteID]) then nut.vote.list[voteID] = nil end end function PANEL:OnRemove() local voteID = self.id if (nut.vote.list[voteID]) then nut.vote.list[voteID] = nil end end function PANEL:sendResult(yes) netstream.Start("nutVote", self.id, yes) self:Remove() end vgui.Register("voteRequired", PANEL, "DFrame") netstream.Hook("voteRequired", function(id, title) local voteWindow = vgui.Create("voteRequired") voteWindow.id = id voteWindow.name:SetText(L(title)) end)
-- This file is required by Luarocks, but I think putting source files in the -- project root is dumb, so it is not used.
package("imath") set_homepage("https://github.com/AcademySoftwareFoundation/Imath/") set_description("Imath is a C++ and python library of 2D and 3D vector, matrix, and math operations for computer graphics") set_license("BSD-3-Clause") add_urls("https://github.com/AcademySoftwareFoundation/Imath/archive/refs/tags/$(version).tar.gz", "https://github.com/AcademySoftwareFoundation/Imath.git") add_versions("v3.1.0", "211c907ab26d10bd01e446da42f073ee7381e1913d8fa48084444bc4e1b4ef87") on_load(function (package) if not package.is_built or package:is_built() then package:add("deps", "cmake") end end) on_install("windows", "macosx", "linux", function (package) local configs = {"-DBUILD_TESTING=OFF"} table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release")) table.insert(configs, "-DBUILD_SHARED_LIBS=" .. (package:config("shared") and "ON" or "OFF")) import("package.tools.cmake").install(package, configs) end) on_test(function (package) assert(package:check_cxxsnippets({test = [[ void test() { Imath::V3f a(0, 0, 0); Imath::V3f b(1, 1, 1); Imath::V3f c(2, 9, 2); Imath::Box3f box(a); box.extendBy(c); } ]]}, {configs = {languages = "c++11"}, includes = "Imath/ImathBox.h"})) end)
----------------------------------------------------------------- ----------------------------------------------------------------- -- MASS EFFECT: UNIFICATION Low Health IFS Script by Nedarb7 -- Build 20404/06 -- Screen Names: Nedarb7 -- E-Mail: -- Apr 04, 2015 -- Copyright (c) 2015 Nedarb7 -- -- About: -- The purpose of script is to work with MEU's low health function and display a red vignette when the player has low health. -- -- -- Legal: -- This script is licensed under the BSD 3-Clause License. A copy of this license (as LICENSE.md) should have been included -- with this script. If it wasn't, it can also be found here: https://www.w3.org/Consortium/Legal/2008/03-bsd-license.html -- -- THIS SCRIPT IS NOT MADE, DISTRIBUTED, OR SUPPORTED BY LUCASARTS, A DIVISION OF LUCASFILM ENTERTAINMENT COMPANY LTD. ----------------------------------------------------------------- ----------------------------------------------------------------- ifs_lowhealth_vignette = NewIFShellScreen { Timer = nil, -- This is our timer variable. It is useless unless used by the update function. TimerMngr = nil, -- Manages the amount of frames displayed and prepares the timer for rewinding TimerType = nil, -- This will only be used for reversing the vision effects bNohelptext_back = 1, -- Remove the default "back" button bNohelptext_backPC = 1, -- To be safe, use PC variable as well bNohelptext_accept = 1, -- Remove the default "accept" button bg_texture = nil, -- Background texture, leave it at nil since the update function manages that movieBackground = nil, -- We don't have a movie background movieIntro = nil, -- We don't have a movie intro Enter = function(this, bFwd) -- Function runs on entering the screen gIFShellScreenTemplate_fnEnter(this, bFwd) -- call base class -- Make sure these variables are only set on entering forward to the screen, not backing in if(bFwd) and this.TimerType ~= false then -- Further, prevent spawn screen bugs this.Timer = 10 -- By setting the timer to 10, we have initiated the fake timer this.TimerMngr = 0 -- We will also keep track of frames this.TimerType = nil -- Reset the reversal if on entering screen to prevent bugs end -- Disable mouse ScriptCB_EnableCursor(nil) end, Update = function(this, fDt) gIFShellScreenTemplate_fnUpdate(this, fDt) -- Load defaults -- Keep the mouse invisible (bug fix) ScriptCB_EnableCursor(nil) -- Exit this function as soon as possible if the timer is nil if this.Timer == nil then return end -- Safety reasons, we don't want to jump frames if fDt < 0.5 then -- Subtract the function delay time from our timer variable this.Timer = this.Timer - ( fDt * 100 ) -- Timer time if this.Timer <= 0 then -- Make sure we haven't passed ten frames if this.TimerMngr < 10 and this.TimerType == nil then -- Count the frame this.TimerMngr = this.TimerMngr + 1 -- Change the texture using TimerMngr as our frame number IFImage_fnSetTexture(ifs_lowhealth_vignette["lowhealth_vignette_textures"], "meu_lowhealth_threshold_" .. this.TimerMngr) Timer = nil -- End the timer elseif this.TimerType == true then -- If it is a reversed process, undo the effects -- Count the frame this.TimerMngr = this.TimerMngr - 1 -- Change the texture using TimerMngr as our frame number IFImage_fnSetTexture(ifs_lowhealth_vignette["lowhealth_vignette_textures"], "meu_lowhealth_threshold_" .. this.TimerMngr) if this.TimerMngr <= 0 then -- Exit the screen when no frames are left ScriptCB_PopScreen() end end end end end, Exit = function(this, bFwd) end, Input_Accept = function(this) end, Input_Back = function(this) end, Input_GeneralUp = function(this) end, Input_GeneralRight = function(this) end, Input_GeneralDown = function(this) end, Input_GeneralLeft = function(this) end, Input_GeneralUp2 = function(this) end, Input_GeneralRight2 = function(this) end, Input_GeneralDown2 = function(this) end, Input_GeneralLeft2 = function(this) end, } -- This function will create our texture table function ifs_LowHealth_TextureTable(this) local w,h = ScriptCB_GetScreenInfo() ifs_lowhealth_vignette["lowhealth_vignette_textures"] = NewIFImage { ZPos = 255, -- or ZOrder ScreenRelativeX = 0.5, ScreenRelativeY = 0.5, texture = "single_player_campaign", localpos_l = -w / 2, -- localpos_(x) is how far the image stretches in a direction from the position localpos_t = -h / 2, localpos_r = w / 2, localpos_b = h / 2, } -- Make the texture invisible IFImage_fnSetTexture(ifs_lowhealth_vignette["lowhealth_vignette_textures"], nil) end -- Call our texture making function ifs_LowHealth_TextureTable(ifs_lowhealth_vignette) ifs_LowHealth_TextureTable = nil -- Make the screen AddIFScreen(ifs_lowhealth_vignette,"ifs_lowhealth_vignette")
--[[ Copyright (C) 2013-2018 Draios Inc dba Sysdig. This file is part of sysdig. 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. --]] view_info = { id = "spectro_all", name = "Spectrogram-All", description = "System call latency spectrogram.", view_type = "spectrogram", applies_to = {"evt.type"}, filter = "evt.dir=<", use_defaults = false, columns = { { name = "NA", field = "evt.latency.quantized", is_key = true }, { name = "LATENCY", description = "system call latency.", field = "evt.latency.quantized", }, { name = "COUNT", description = "XXX.", field = "evt.count", aggregation = "SUM", colsize = 8, } } }
--[[--ldoc desc @Module Chip.lua @Author JasonLiu Date: 2018-10-24 14:25:57 Last Modified by: JasonLiu Last Modified time: 2018-10-25 11:52:07 ]] local Chip = class("Chip", cc.load("boyaa").mvc.BoyaaView); local BehaviorExtend = cc.load("boyaa").behavior.BehaviorExtend; BehaviorExtend(Chip); function Chip:ctor(type, color, value, fontSize) self:initView(type, color, value, fontSize) end --[[ @function initView 初始化View @param #type int 筹码的类型 大:0 小 1 @param #color int 筹码的颜色 @param #value string 筹码的值 @param #fontSize int 筹码的字体大小 ]] function Chip:initView(type, color, value, fontSize) self._data = { type = type or 0, color = color or 1, value = value or "5K", fontSize = fontSize or 10 } if self._data.type == 0 then self:addBigChip(self._data.color, self._data.value, self._data.fontSize) else self:addSmallChip(self._data.color) end end --[[ @function addSmallChip 添加一个小筹码 @param #color int 筹码的颜色 ]] function Chip:addSmallChip(color) local chipTexture = cc.SpriteBatchNode:create("Images/koprokdice/koprok_chip_pin.png"):getTexture() self.chipView = cc.Sprite:createWithTexture(chipTexture, cc.rect(5 + (4 - color) * (33 + 9), 5, 33, 33)):setContentSize(cc.size(10,10)) self:addChild(self.chipView) end --[[ @function addSmallChip 添加一个大筹码 @param #color int 筹码的颜色 @param #value string 筹码的值 @param #fontSize int 筹码的字体大小 ]] function Chip:addBigChip(color, value, fontSize) self.chipLight = cc.Sprite:create("Images/koprokdice/chip_btn_light.png"):setContentSize(cc.size(50, 50)):setVisible(false) self.chipView = ccui.ImageView:create("Images/koprokdice/chip_btn" .. color .. ".png"):ignoreContentAdaptWithSize(false):setContentSize(cc.size(40, 40)):move(0.5, -1) self.chipNum = cc.Label:createWithTTF(value, "fonts/Marker Felt.ttf", fontSize, cc.size(0, 0), cc.TEXT_ALIGNMENT_CENTER, cc.VERTICAL_TEXT_ALIGNMENT_CENTER):move(0, -1) self.chipView:setTouchEnabled(true) :addTouchEventListener(function(sender, eventType) if eventType == 0 then self:setScale(0.9) elseif eventType == 2 then self:setScale(1) self:setLight(true) if self.clickListener then self.clickListener() end elseif eventType == 3 then self:setScale(1) end end) self:addChild(self.chipLight) self:addChild(self.chipView) self:addChild(self.chipNum) end --[[ @function getContentSize 获取内容大小 @return size_table#size_table ret (return value: size_table) ]] function Chip:getContentSize() return self.chipView:getContentSize() end --[[ @function setLight 设置是否点亮 ]] function Chip:setLight(visible) if self.chipLight then self.chipLight:setVisible(visible) end end --[[ @function addClickListener 添加点击事件 @param #callback function 回调方法 ]] function Chip:addClickListener(callback) self.clickListener = callback end return Chip
-- Copyright (c) 2015-2017 Lymia Alusyia <[email protected]> -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. if _mpPatch_activateFrontEnd then _mpPatch.setBIsModding() Matchmaking = _mpPatch.hookTable(Matchmaking, {LaunchMultiplayerGame = function(...) _mpPatch.overrideModsFromPreGame() return Matchmaking._super.LaunchMultiplayerGame(...) end}) -- Protocol for ensuring non-host players will override the mod list. local gameLaunchSet = false local gameLaunchCountdown = -1 local function setGameLaunch() gameLaunchSet = true gameLaunchCountdown = 3 end _mpPatch.event.reset.registerHandler(function() gameLaunchSet = false end) _mpPatch.net.startLaunchCountdown.registerHandler(function(_, id) if id == m_HostID and not Matchmaking.IsHost() then _mpPatch.overrideModsFromPreGame() end end) local HandleExitRequestOld = HandleExitRequest function HandleExitRequest(...) if gameLaunchSet then return end _mpPatch.event.reset() return HandleExitRequestOld(...) end local LaunchGameOld = LaunchGame _mpPatch.event.update.registerHandler(function(timeDiff) if not ContextPtr:IsHidden() and gameLaunchSet then gameLaunchCountdown = gameLaunchCountdown - timeDiff if gameLaunchCountdown <= 0 then _mpPatch.event.kickAllUnpatched("Game starting") LaunchGameOld() _mpPatch.event.reset() end return true end end, -1) function LaunchGame(...) if PreGame.IsHotSeatGame() then return LaunchGameOld(...) else _mpPatch.net.startLaunchCountdown() setGameLaunch() end end Controls.LaunchButton:RegisterCallback(Mouse.eLClick, LaunchGame) -- Ensure the NetPatch hook doesn't end up escaping the UI. local DequeuePopup = UIManager.DequeuePopup _mpPatch.patch.globals.rawset(UIManager, "DequeuePopup", function(this, ...) local context = ... if context == ContextPtr then _mpPatch.event.reset() end return DequeuePopup(this, ...) end) end
-- **Big thing that contains all sorts of fun stuff related to ms based scoring and adapting existing systems to it** -- probably need to reorganize large parts of this -- global here ms = {} -- *Values and stuff* -- Make the distinction between ms timed and non-timed judgments -- Radar values people on earth actually care about ms.RelevantRadarsShort = { THEME:GetString("RadarCategoryShort", "Notes")..":", THEME:GetString("RadarCategoryShort", "Jumps")..":", THEME:GetString("RadarCategoryShort", "Hands")..":", THEME:GetString("RadarCategoryShort", "Holds")..":", THEME:GetString("RadarCategoryShort", "Mines")..":", THEME:GetString("RadarCategoryShort", "TotalTaps")..":", THEME:GetString("RadarCategoryShort", "Rolls")..":", THEME:GetString("RadarCategoryShort", "Lifts")..":", THEME:GetString("RadarCategoryShort", "Fakes")..":" } ms.RelevantRadars = { "RadarCategory_Notes", "RadarCategory_Jumps", "RadarCategory_Hands", "RadarCategory_Holds", "RadarCategory_Mines", "RadarCategory_TapsAndHolds", "RadarCategory_Rolls", "RadarCategory_Lifts", "RadarCategory_Fakes" } -- lists just for displayed judgment counts ms.JudgeCount = { "TapNoteScore_W1", "TapNoteScore_W2", "TapNoteScore_W3", "TapNoteScore_W4", "TapNoteScore_W5", "TapNoteScore_Miss", "HoldNoteScore_Held", "HoldNoteScore_LetGo" } ms.JudgeCountInverse = { TapNoteScore_W1 = 1, TapNoteScore_W2 = 2, TapNoteScore_W3 = 3, TapNoteScore_W4 = 4, TapNoteScore_W5 = 5, TapNoteScore_Miss = 6, HoldNoteScore_Held = 7, HoldNoteScore_LetGo = 8 } ms.SkillSets = { "Overall", "Stream", "Jumpstream", "Handstream", "Stamina", "JackSpeed", "Chordjack", "Technical" } ms.SkillSetsShort = { "Overall", "Stream", "JS", "HS", "Stam", "Jack Speed", "Chordjack", "Tech" } ms.SkillSetsTranslatedByName = { Overall = THEME:GetString("Skillsets", "Overall"), Stream = THEME:GetString("Skillsets", "Stream"), Jumpstream = THEME:GetString("Skillsets", "Jumpstream"), Handstream = THEME:GetString("Skillsets", "Handstream"), Stamina = THEME:GetString("Skillsets", "Stamina"), JackSpeed = THEME:GetString("Skillsets", "JackSpeed"), Chordjack = THEME:GetString("Skillsets", "Chordjack"), Technical = THEME:GetString("Skillsets", "Technical"), } ms.SkillSetsTranslated = { THEME:GetString("Skillsets", "Overall"), THEME:GetString("Skillsets", "Stream"), THEME:GetString("Skillsets", "Jumpstream"), THEME:GetString("Skillsets", "Handstream"), THEME:GetString("Skillsets", "Stamina"), THEME:GetString("Skillsets", "JackSpeed"), THEME:GetString("Skillsets", "Chordjack"), THEME:GetString("Skillsets", "Technical"), } ms.JudgeScalers = {1.50, 1.33, 1.16, 1.00, 0.84, 0.66, 0.50, 0.33, 0.20} local musicstr = THEME:GetString("GeneralInfo", "RateMusicString") -- **Functions** function ms.ok(m) if not m then SCREENMAN:SystemMessage("nahbro") else SCREENMAN:SystemMessage(m) end end --[[ Print a thing to the error console (F3+F6+8 to enable, F3+F6+9 to make it persist) str: anything that can be used with tostring() ]] function ms.p(str) MESSAGEMAN:Broadcast("ScriptError", {message = tostring(str)}) end --[[ This runs the LuaJIT profiler. Shows the approximate line of section of Lua that are being used the most. This will cause a minor fps drop. ]] function ms.startjitprofiler() local profile = require("jit.profile") local tH = {} local tHS = {} profile.start( "li1", function(th, samples, vmmode) local f = require("jit.profile").dumpstack(th, "pl", 1) tH[f] = 1 + (tH[f] or 0) if not tHS[f] then tHS[f] = {} end tHS[f][vmmode] = (tHS[f][vmmode] or 0) + 1 end ) local function dump(o) if type(o) == "table" then local s = "{ " for k, v in pairs(o) do if type(k) ~= "number" then k = '"' .. k .. '"' end s = s .. "[" .. k .. "] = " .. dump(v) .. ",\n" end return s .. "} " else return tostring(o) end end SCREENMAN:GetTopScreen():setInterval( function() local tmp = {} local n = 0 for k, v in pairs(tH) do tmp[n + 1] = {k, v} n = n + 1 end table.sort( tmp, function(a, b) return a[2] > b[2] end ) local str = "" for _, v in ipairs(tmp) do str = str .. dump(v[1]) .. " =" .. tostring(v[2]) .. "\n" end SCREENMAN:SystemMessage(str) end, 1 ) end --[[ Stop the LuaJIT profiler only if it has already been started. ]] function ms.stopjitprofiler() local profile = require("jit.profile") profile.stop() end function ms.type(m) SCREENMAN:SystemMessage(type(m)) end --- Table sum designed for ms tables (optional starting position, default to 0, and absolute value flag) function ms.tableSum(t, n, abs) local o = 0 for i = n or 0, #t do if abs then o = o + math.abs(t[i]) else o = o + t[i] end end return o end function wifeMean(t) local c = #t local m = 0 if c == 0 then return 0 end local o = 0 for i = 1, c do if t[i] ~= 1000 and t[i] ~= -1100 then o = o + t[i] else m = m + 1 end end return o / (c - m) end function wifeAbsMean(t) local c = #t local m = 0 if c == 0 then return 0 end local o = 0 for i = 1, c do if t[i] ~= 1000 and t[i] ~= -1100 then o = o + math.abs(t[i]) else m = m + 1 end end return o / (c - m) end function wifeSd(t) local u = wifeMean(t) local u2 = 0 local m = 0 for i = 1, #t do if t[i] ~= 1000 and t[i] ~= -1100 then u2 = u2 + (t[i] - u) ^ 2 else m = m + 1 end end return math.sqrt(u2 / (#t - 1 - m)) end function wifeRange(t) local x, y = 10000, 0 for i = 1, #t do if t[i] ~= 1000 then if math.abs(t[i]) < math.abs(x) then x = t[i] end if math.abs(t[i]) > math.abs(y) then y = t[i] end end end return x, y end function IndexOf(t, x) for k, v in pairs(t) do if v == x then return k end end return nil end -- **Very slight efficiency rewrites** notShit = {} function notShit.floor(x, y) y = 10 ^ (y or 0) return math.floor(x * y) / y end function notShit.ceil(x, y) y = 10 ^ (y or 0) return math.ceil(x * y) / y end -- seriously what is math and how does it work function notShit.round(x, y) y = 10 ^ (y or 0) return math.floor(x * y + 0.5) / y end -- Grabs the currently selected rate as a string in the form of "r.rrx" while dropping trailing 0s function getCurRateString() return getRateString(getCurRateValue()) end function getRateString(x) return string.format("%.2f", x):gsub("%.?0+$", "") .. "x" end function getCurRateDisplayString() return getRateDisplayString(getCurRateString()) end function getRateDisplayString(x) if x == "1x" then x = "1.0x" elseif x == "2x" then x = "2.0x" end return x .. musicstr end function getCurRateValue() return notShit.round(GAMESTATE:GetSongOptionsObject("ModsLevel_Current"):MusicRate(), 3) end function getCurKey() return GAMESTATE:GetCurrentSteps(PLAYER_1):GetChartKey() end -- returns a string of keys for a table function showKeys(t) local o = {} for k, v in pairs(t) do o[#o + 1] = k end return table.concat(o, ",") -- apparently theres an alias for this in this game who knew end -- same but returns a table (array) function tableKeys(t) local o = {} for k, v in pairs(t) do o[#o + 1] = k end return o end function formLink(x, y) x[y] = x[y] or {} return x[y] end function GetPlayableTime() local td = GAMESTATE:GetCurrentSteps(PLAYER_1):GetTimingData() local song = GAMESTATE:GetCurrentSong() return (td:GetElapsedTimeFromBeat(song:GetLastBeat()) - td:GetElapsedTimeFromBeat(song:GetFirstBeat())) / getCurRateValue() end function ChangeMusicRate(rate, params) if params.Name == "PrevScore" and rate < 2.95 and (getTabIndex() == 0 or getTabIndex() == 1) then GAMESTATE:GetSongOptionsObject("ModsLevel_Preferred"):MusicRate(rate + 0.1) GAMESTATE:GetSongOptionsObject("ModsLevel_Song"):MusicRate(rate + 0.1) GAMESTATE:GetSongOptionsObject("ModsLevel_Current"):MusicRate(rate + 0.1) MESSAGEMAN:Broadcast("CurrentRateChanged") elseif params.Name == "NextScore" and rate > 0.55 and (getTabIndex() == 0 or getTabIndex() == 1) then GAMESTATE:GetSongOptionsObject("ModsLevel_Preferred"):MusicRate(rate - 0.1) GAMESTATE:GetSongOptionsObject("ModsLevel_Song"):MusicRate(rate - 0.1) GAMESTATE:GetSongOptionsObject("ModsLevel_Current"):MusicRate(rate - 0.1) MESSAGEMAN:Broadcast("CurrentRateChanged") end if params.Name == "PrevRate" and rate < 3 and (getTabIndex() == 0 or getTabIndex() == 1) then GAMESTATE:GetSongOptionsObject("ModsLevel_Preferred"):MusicRate(rate + 0.05) GAMESTATE:GetSongOptionsObject("ModsLevel_Song"):MusicRate(rate + 0.05) GAMESTATE:GetSongOptionsObject("ModsLevel_Current"):MusicRate(rate + 0.05) MESSAGEMAN:Broadcast("CurrentRateChanged") elseif params.Name == "NextRate" and rate > 0.5 and (getTabIndex() == 0 or getTabIndex() == 1) then GAMESTATE:GetSongOptionsObject("ModsLevel_Preferred"):MusicRate(rate - 0.05) GAMESTATE:GetSongOptionsObject("ModsLevel_Song"):MusicRate(rate - 0.05) GAMESTATE:GetSongOptionsObject("ModsLevel_Current"):MusicRate(rate - 0.05) MESSAGEMAN:Broadcast("CurrentRateChanged") end end