content
stringlengths 5
1.05M
|
|---|
local lastBpmChangeTime = 0;
local lastBpmChangeBeat = 0;
local prevBpm = 0;
local prevCrochet = 0;
function onCreate()
-- background shit
makeLuaSprite('sambg', 'nightstage/sambg', -600, -300);
setScrollFactor('sambg', 0.3, 0.3);
makeLuaSprite('eagle', 'nightstage/EAGLE', 970, 550);
makeAnimatedLuaSprite('wingFRONT', 'nightstage/wingFRONT', 1280, 7777777);
makeAnimatedLuaSprite('wingBACK', 'nightstage/wingBACK', 1170, 7777777); --Apparently the wave code is what sets the Y position. wtf ninja???
addAnimationByPrefix('wingFRONT', 'flap', 'WingFORE', 24, true);
addAnimationByPrefix('wingBACK', 'flapB', 'WingBACK', 24, true);
makeLuaSprite('cloudBACK', 'nightstage/BACKCLOUD', 0, 300);
makeLuaSprite('cloudBACK2', 'nightstage/BACKCLOUD', -520, 380);
setScrollFactor('cloudBACK', 0.4, 0.4);
setScrollFactor('cloudBACK2', 0.5, 0.5);
makeLuaSprite('cloudFRONT', 'nightstage/FRONTCLOUD', -500, 500);
makeLuaSprite('cloudFRONT2', 'nightstage/FRONTCLOUD', 600, 470);
setScrollFactor('cloudFRONT', 0.8, 0.8);
setScrollFactor('cloudFRONT2', 0.9, 0.9);
addLuaSprite('sambg', false);
addLuaSprite('cloudBACK2', false);
addLuaSprite('cloudBACK', false);
addLuaSprite('wingBACK', false);
addLuaSprite('eagle', false);
addLuaSprite('wingFRONT', true);
addLuaSprite('cloudFRONT', true);
addLuaSprite('cloudFRONT2', true);
end
function onUpdatePost(elapsed)
if not lowQuality then
local wave = math.sin((getSongPosition() - lastBpmChangeTime) / crochet * math.pi / 4);
setProperty('boyfriend.y', 20 * wave + 265); --bf-car y, idk why defaultBoyfriendY not work tbh -- I assume for the same reason its "boyfriend" in the json? idk but i think its funny this makes bf float on death too lol
setProperty('eagle.y', 20 * wave + 500);
setProperty('wingFRONT.y', 20 * wave + 293);
setProperty('wingBACK.y', 20 * wave + 293);
setProperty('gf.y', -50 * wave - 250); --lol??
end
end
function onSongStart()
lastBpmChangeTime = 0;
lastBpmChangeBeat = 0;
prevBpm = curBpm;
prevCrochet = crochet;
end
function onBeatHit() --changebpm stuff all called before this so should be good!
if curBpm ~= prevBpm then
lastBpmChangeTime = lastBpmChangeTime + (curBeat - lastBpmChangeBeat) * prevCrochet;
lastBpmChangeBeat = curBeat;
prevBpm = curBpm;
prevCrochet = crochet;
end
end
-- someone rly gotta add hooks for this shit on psych fr fr !!!!!
-- very easy just make lastChange from MusicBeatState.updateCurStep() a public variable outside the function scope so we can getPropertyFromClass shit
|
----------------------
-- Global variables --
----------------------
local g_LotteryFund = 0
local g_LotteryPlayers = {}
local g_FinishLotteryTimer = false
local g_BetsTimer = false -- GbAreBetsPlaced uses it
local SPIN_MAX_VAL = 36 -- also in cmd_s.lua
local SPIN_CASH_MULT = 40
local SPIN_CASH_LIMIT = 100000
local SPIN_COOLDOWN_MS = 30000
--------------------------------
-- Local function definitions --
--------------------------------
local function GbTryToFinishLottery()
g_FinishLotteryTimer = nil
if(not table.empty(g_LotteryPlayers)) then
GbFinishLottery()
end
end
local function GbRollTimer(player)
local n = math.random(1, 6)
local pdata = Player.fromEl(player)
if(n == 1) then
local cashsub = math.min(math.random(1000, 9000), pdata.accountData.cash)
pdata.accountData:add('cash', -cashsub)
privMsg(player, "You rolled %u, you just lost %s.", n, formatMoney(cashsub))
elseif(n == 2) then
local cashadd = math.random(1000, 5000)
pdata.accountData:add('cash', cashadd)
privMsg(player, "You rolled %u, %s added to your cash.", n, formatMoney(cashadd))
elseif(n == 3) then
privMsg(player, "You rolled %u, which is mute.", n, player)
if(pdata:mute(60, 'Roll')) then
outputMsg(g_Root, Styles.red, "%s has been muted after rolling a dice.", pdata:getName(true))
end
elseif(n == 4) then
local cashsub = math.min(math.random(1000, 4000), pdata.accountData.cash)
pdata.accountData:add('cash', -cashsub)
privMsg(player, "You rolled %u, you just lost %s.", n, formatMoney(cashsub))
elseif(n == 5) then
setSkyGradient(math.random(0,255), math.random(0,255), math.random(0,255), math.random(0,255), math.random(0,255), math.random(0,255))
privMsg(player, "You rolled %u, the sky color changes.", n)
elseif(n == 6) then
local cashadd = math.random (1000, 10000)
pdata.accountData:add('cash', cashadd)
privMsg(player, "You rolled %u, %s added to your cash.", n, formatMoney(cashadd))
end
end
local function GbSpinTimer(player, n, cash)
local n2 = math.random(0, SPIN_MAX_VAL)
if(n == n2) then
local pdata = Player.fromEl(player)
local cashAdd = cash * (SPIN_CASH_MULT+1)
pdata.accountData:add('cash', cashAdd)
privMsg(player, "You spinned %u and won %s.", n2, formatMoney(cashAdd))
else
privMsg(player, "You spinned %u and lost %s.", n2, formatMoney(cash))
end
end
local function GbLotteryFundInc()
local lotto_limit = Settings.lotto_limit
if(g_PlayersCount > 0 and g_LotteryFund < lotto_limit) then
local max_fund_inc = Settings.max_fund_inc
local n = math.random(1, max_fund_inc)
g_LotteryFund = g_LotteryFund + n
outputMsg(g_Root, Styles.gambling, "Lottery time! %s added to the fund!", formatMoney(n))
if(g_LotteryFund >= lotto_limit and not g_FinishLotteryTimer) then
g_FinishLotteryTimer = setTimer(GbTryToFinishLottery, 20000, 1)
end
end
end
---------------------------------
-- Global function definitions --
---------------------------------
function GbFinishLottery()
outputMsg(g_Root, Styles.gambling, "Lottery limit reached! Fund: %s.", formatMoney(g_LotteryFund))
local c = 0
for id, tickets in pairs(g_LotteryPlayers) do
c = c + tickets
end
if(c <= 0) then
return
end
local r = math.random(1, c)
for id, tickets in pairs(g_LotteryPlayers) do
r = r - tickets
if(r <= 0) then
local accountData = AccountData.create(id)
accountData:add('cash', g_LotteryFund)
outputMsg(g_Root, Styles.gambling, "%s won the lottery!", accountData:get('name'))
break
end
end
g_LotteryPlayers = {}
g_LotteryFund = 0
end
function GbCancelLottery()
for id, tickets in pairs(g_LotteryPlayers) do
AccountData.create(id):add('cash', tickets)
local player = Player.fromId(id)
if(player and player.sync) then
player:addNotify{icon = 'gambling/dices.png',
{"Lottery is cancelled! You get your money (%s) back.", formatMoney(tickets)}}
end
end
end
function GbGetLotteryFund()
return g_LotteryFund
end
function GbAddLotteryTickets(player, tickets_count)
local pdata = Player.fromEl(player)
if(not pdata.id) then
privMsg(player, "Guests cannot take part in lottery!")
return false
end
if(not g_LotteryPlayers[pdata.id]) then
g_LotteryPlayers[pdata.id] = 0
end
local max_tickets = Settings.max_tickets
if(g_LotteryPlayers[pdata.id] + tickets_count > max_tickets) then
privMsg(player, "You can buy only %u tickets more, because maximal number of tickets per player is %u!", max_tickets - g_LotteryPlayers[pdata.id], max_tickets)
return false
end
g_LotteryPlayers[pdata.id] = g_LotteryPlayers[pdata.id] + tickets_count
g_LotteryFund = g_LotteryFund + tickets_count
local lotto_limit = Settings.lotto_limit
if(not _lottery_time and g_LotteryFund >= lotto_limit) then
if(not g_FinishLotteryTimer) then
g_FinishLotteryTimer = setTimer(GbTryToFinishLottery, 1000, 1)
end
end
return true
end
function GbFinishBets(winner)
if(g_BetsTimer) then
killTimer(g_BetsTimer)
g_BetsTimer = false
end
local mult = 1 + math.log10(g_PlayersCount)
for player, pdata in pairs(g_Players) do
if(winner and pdata.bet == winner) then
local award = math.floor(pdata.betcash * mult)
pdata.accountData:add('cash', award)
pdata:addNotify{icon = 'gambling/dices.png',
{"You have won %s in your bet!", formatMoney(award)}}
end
pdata.bet = nil
end
end
function GbCancelBets()
for player, pdata in pairs(g_Players) do
if(pdata.bet) then
pdata.accountData:add('cash', pdata.betcash)
pdata:addNotify{icon = 'gambling/dices.png',
{"Your bet is cancelled! You get your money (%s) back.", formatMoney(pdata.betcash)}}
end
end
GbFinishBets()
end
local function GbRemoveBetsPlayer(player, return_cash)
for player2, pdata2 in pairs(g_Players) do
if(pdata2.bet == player) then
if(return_cash) then
pdata2.accountData:add('cash', pdata2.betcash)
pdata2:addNotify{icon = 'gambling/dices.png',
{"Your bet is cancelled! You get your money (%s) back.", formatMoney(pdata2.betcash)}}
end
pdata2.bet = nil
end
end
end
local function GbCleanup()
GbCancelBets()
GbCancelLottery()
end
local function GbOnPlayerQuit()
GbRemoveBetsPlayer(source, quitType ~= 'Quit') -- return cash to betters if he quits normally
end
local function GbOnMapStop()
if(g_BetsTimer) then
killTimer(g_BetsTimer)
g_BetsTimer = false
end
end
local function GbInit()
local fund_inc_interval = Settings.fund_inc_interval
if(fund_inc_interval > 0) then
setTimer(GbLotteryFundInc, fund_inc_interval * 1000, 0)
end
addEventHandler('onResourceStop', g_ResRoot, GbCleanup)
addEventHandler('onPlayerQuit', g_Root, GbOnPlayerQuit)
addEventHandler('onGamemodeMapStop', g_Root, GbOnMapStop)
end
function GbRoll(player)
local pdata = Player.fromEl(player)
if(not pdata.last_roll or (getTickCount() - pdata.last_roll) > 30000) then
pdata.last_roll = getTickCount()
setPlayerTimer(GbRollTimer, 5000, 1, player)
return true
end
return false
end
function GbSpin(player, number, cash)
local pdata = Player.fromEl(player)
local ticks = getTickCount()
if(pdata.last_spin and (ticks - pdata.last_spin) < SPIN_COOLDOWN_MS) then
privMsg(player, "You cannot spin so often!")
elseif(number < 0 or number > SPIN_MAX_VAL or cash <= 0 or cash > SPIN_CASH_LIMIT) then
privMsg(player, "Invalid number!")
elseif(pdata.accountData.cash < cash) then
privMsg(player, "You don't have enough cash!")
else
pdata.last_spin = ticks
pdata.accountData:add('cash', -cash)
-- Create timer
setPlayerTimer(GbSpinTimer, 5000, 1, player, number, cash)
return true
end
return false
end
function GbBet(player, player2, cash)
local pdata = Player.fromEl(player)
pdata.accountData:add('cash', -cash)
pdata.bet = player2
pdata.betcash = cash
return true
end
function GbUnbet(player)
local pdata = Player.fromEl(player)
if(not pdata.bet) then
return false
end
pdata.bet = nil
pdata.accountData:add('cash', pdata.betcash)
pdata.betcash = 0
return true
end
local function GbBetsPlacedTimer()
for el, player in pairs(g_Players) do
if(player.sync) then
player:addNotify{icon = 'gambling/dices.png', {"No More Bets."}}
end
end
g_BetsTimer = false
end
function GbStartBets()
local bet_time = Settings.bet_time
local bet_min_players = Settings.bet_min_players
if(bet_time > 0 and g_PlayersCount >= bet_min_players) then
g_BetsTimer = setTimer(GbBetsPlacedTimer, bet_time * 1000, 1)
for el, player in pairs(g_Players) do
if(player.sync) then
player:addNotify{icon = 'gambling/dices.png', {"Place Your Bets!"}}
end
end
end
end
function GbAreBetsPlaced()
if(g_BetsTimer) then
return false
end
return true
end
addInitFunc(GbInit)
|
cc = cc or {}
---EventListenerAssetsManagerEx object
---@class EventListenerAssetsManagerEx : EventListenerCustom
local EventListenerAssetsManagerEx = {}
cc.EventListenerAssetsManagerEx = EventListenerAssetsManagerEx
--------------------------------
--- Initializes event with type and callback function
---@param AssetsManagerEx
---@param callback function
---@return bool
function EventListenerAssetsManagerEx:init(AssetsManagerEx, callback) end
--------------------------------
--
---@return EventListenerAssetsManagerEx
function EventListenerAssetsManagerEx:clone() end
--------------------------------
---/ Overrides
---@return bool
function EventListenerAssetsManagerEx:checkAvailable() end
--------------------------------
--- Constructor
---@return EventListenerAssetsManagerEx
function EventListenerAssetsManagerEx:EventListenerAssetsManagerEx() end
return EventListenerAssetsManagerEx
|
-- The MIT License (MIT)
-- Copyright (c) 2015 Eugene Aksenov (e.aksenov@gmail.com)
--
-- 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.
-------------------------------------------------------------------------------
-- German translation
-------------------------------------------------------------------------------
MyBuild.DE = {}
MyBuild.DE.UI = {}
MyBuild.DE.UI_MainTitle = "ESO Mein Build"
MyBuild.DE.UI_ChampionTitle = "Champion Punkte"
MyBuild.DE.UI_StatsTitle = "Charakter"
MyBuild.DE.UI_DamageResistTitle = "Schaden und Widerstand"
MyBuild.DE.UI_AttributesTitle = "Attribute"
MyBuild.DE.UI_Stat_MagickaLabel = "Magicka"
MyBuild.DE.UI_Stat_StaminaLabel = "Ausdauer"
MyBuild.DE.UI_Stat_HealthLabel = "Leben"
MyBuild.DE.UI_Stat_Header_Attribute = "Attribut"
MyBuild.DE.UI_Stat_Header_Points = "Punkte"
MyBuild.DE.UI_Stat_Header_Maximum = "Maximum"
MyBuild.DE.UI_Stat_Header_Recovery = "Regen."
MyBuild.DE.UI_Stat_Label_Health = "Leben"
MyBuild.DE.UI_Stat_Label_Magicka = "Magicka"
MyBuild.DE.UI_Stat_Label_Stamina = "Asudauer"
MyBuild.DE.UI_Stat_Label_Weapon = "Waffe"
MyBuild.DE.UI_Stat_Label_Spell = "Zauber"
MyBuild.DE.UI_Stat_Label_Physical = "Physisch"
MyBuild.DE.UI_Stat_Label_Magical = "Magisch"
MyBuild.DE.Werewolf = "Werewolf"
MyBuild.DE.Vampire = "Vampir"
MyBuild.DE.UI_Equipment_Title = "Ausrüstung"
MyBuild.DE.UI_Header_Slot = "Slot"
MyBuild.DE.UI_Header_Rating = "Rüstung"
MyBuild.DE.UI_Header_Level = "Level"
MyBuild.DE.UI_Header_Trait = "Eigenschaft"
MyBuild.DE.UI_Header_Enchantment = "Verzauberung"
MyBuild.DE.UI_Header_Points = "Punkte"
MyBuild.DE.UI_Header_Max = "Max"
MyBuild.DE.UI_Header_Regen = "Regen."
MyBuild.DE.UI_Header_DamageType = "Schadensart"
MyBuild.DE.UI_Header_Damage = "Schaden"
MyBuild.DE.UI_Header_Crit = "Krit."
MyBuild.DE.UI_Header_CritPercent = "Krit. %"
MyBuild.DE.UI_Header_Resistance = "Widerstand"
MyBuild.DE.UI_Header_Penetration = "Durchdringung"
MyBuild.DE.UI_Mundus_Label = "Mundus Stein:"
MyBuild.DE.UI_Equipment_ArmorSubtitle = "Rüsrung"
MyBuild.DE.UI_Equipment_HeadLabel = "Helm: "
MyBuild.DE.UI_Equipment_ShouldersLabel = "Schultern: "
MyBuild.DE.UI_Equipment_ChestLabel = "Brust: "
MyBuild.DE.UI_Equipment_HandsLabel = "Hände: "
MyBuild.DE.UI_Equipment_WaistLabel = "Gürtel: "
MyBuild.DE.UI_Equipment_LegsLabel = "Beine: "
MyBuild.DE.UI_Equipment_FeetLabel = "Füße: "
MyBuild.DE.UI_Equipment_JewelrySubtitle = "Schmuck"
MyBuild.DE.UI_Equipment_Neck = "Kette: "
MyBuild.DE.UI_Equipment_Ring1 = "Ring 1: "
MyBuild.DE.UI_Equipment_Ring2 = "Ring 2: "
MyBuild.DE.UI_Equipment_WeaponSubtitle = "Waffe"
MyBuild.DE.UI_Equipment_WeaponMain1 = "Haupthand 1: "
MyBuild.DE.UI_Equipment_WeaponOff1 = "Nebenhand 1: "
MyBuild.DE.UI_Equipment_WeaponMain2 = "Haupthand 2: "
MyBuild.DE.UI_Equipment_WeaponOff2 = "Nebenhand 2: "
MyBuild.DE.Command_ShowHide = "Mein Build: anzeigen/verstecken"
MyBuild.DE.ESO = {}
MyBuild.DE.ESO.Quality = {}
MyBuild.DE.ESO.Quality[ITEM_QUALITY_ARCANE] = "Arkan"
MyBuild.DE.ESO.Quality[ITEM_QUALITY_ARTIFACT] = "Artefakt"
MyBuild.DE.ESO.Quality[ITEM_QUALITY_LEGENDARY] = "Legendär"
MyBuild.DE.ESO.Quality[ITEM_QUALITY_MAGIC] = "Magisch"
MyBuild.DE.ESO.Quality[ITEM_QUALITY_NORMAL] = "Normal"
MyBuild.DE.ESO.Quality[ITEM_QUALITY_TRASH] = "Trödel"
MyBuild.DE.ESO.Weapon = {}
MyBuild.DE.ESO.Weapon[WEAPONTYPE_AXE] = "Axt"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_BOW] = "Bogen"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_DAGGER] = "Dolch"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_FIRE_STAFF] = "Feuerstab"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_FROST_STAFF] = "Froststab"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_HAMMER] = "Keule"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_HEALING_STAFF] = "Heilungsstab"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_LIGHTNING_STAFF] = "Blitzstab"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_RUNE] = "Rune"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_SHIELD] = "Schild"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_SWORD] = "Schwert"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_TWO_HANDED_AXE] = "Zweihand Axt"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_TWO_HANDED_HAMMER] = "Zweihand Keule"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_TWO_HANDED_SWORD] = "Zweihand Schwert"
MyBuild.DE.ESO.Weapon[WEAPONTYPE_NONE] = ""
MyBuild.DE.ESO.Armor = {}
MyBuild.DE.ESO.Armor[ARMORTYPE_HEAVY] = "Schwer"
MyBuild.DE.ESO.Armor[ARMORTYPE_LIGHT] = "Leicht"
MyBuild.DE.ESO.Armor[ARMORTYPE_MEDIUM] = "Mittel"
MyBuild.DE.ESO.Armor[ARMORTYPE_NONE] = ""
MyBuild.DE.ESO.Trait = {}
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_ARMOR_DIVINES] = "Göttlich"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_ARMOR_EXPLORATION] = "Erforschend"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_ARMOR_IMPENETRABLE] = "Undurchdringlich"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_ARMOR_INFUSED] = "Erfüllt"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_ARMOR_INTRICATE] = "Komplex"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_ARMOR_NIRNHONED] = "Nirngeschliffen"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_ARMOR_ORNATE] = "Wertvoll"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_ARMOR_REINFORCED] = "Verstärkt"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_ARMOR_STURDY] = "Robust"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_ARMOR_TRAINING] = "Lehrend"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_ARMOR_WELL_FITTED] = "Passgenau"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_JEWELRY_ARCANE] = "Arkan"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_JEWELRY_HEALTHY] = "Gesund"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_JEWELRY_ORNATE] = "Wertvoll"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_JEWELRY_ROBUST] = "Robust"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_WEAPON_CHARGED] = "Geladen"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_WEAPON_DEFENDING] = "Verteidigend"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_WEAPON_INFUSED] = "Erfüllt"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_WEAPON_INTRICATE] = "Komplex"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_WEAPON_NIRNHONED] = "Nirngeschliffen"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_WEAPON_ORNATE] = "Wertvoll"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_WEAPON_POWERED] = "Gestärkt"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_WEAPON_PRECISE] = "Präzise"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_WEAPON_SHARPENED] = "Geschärft"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_WEAPON_TRAINING] = "Lehrend"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_WEAPON_WEIGHTED] = "Ausbalanciert"
MyBuild.DE.ESO.Trait[ITEM_TRAIT_TYPE_NONE] = ""
|
imageFont = { fontTable = {} }
-- /// Misc Func /// --
function imageFont.fileExists(file)
local f = io.open(file, "rb")
if f then
f:close()
end
return(f ~= nil)
end
function imageFont.linesFromFile(file)
if not imageFont.fileExists(file) then
return({})
end
local lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return(lines)
end
function string.split(t, b)
if t then
local cmd, match = {}, [[[^]]..b..[[]+]]
for word in string.gmatch(t, match) do
table.insert(cmd, word)
end
return(cmd)
else
return({nil})
end
end
-- /// Image Font Functions /// --
function imageFont.Load(file)
local lines = imageFont.linesFromFile(file)
local textSize = 0
for k,v in pairs(lines) do
if string.find(v, "textsize") then
textSize = tonumber(string.split(v,"=")[2])
if (textSize == nil) then
textSize = 13
end
if (imageFont.fontTable[textSize] == nil) then
imageFont.fontTable[textSize] = {}
end
else
local char = string.sub(v, 1, 1 )
local size = string.sub(v, 3)
imageFont.fontTable[textSize][char] = size
end
end
end
function charwidth(char, textSize)
if (textSize == nil) then
textSize = 13
end
if (imageFont.fontTable[textSize] ~= nil) then
if (imageFont.fontTable[textSize][char] ~= nil) then
return(imageFont.fontTable[textSize][char])
end
end
return(0)
end
function textwidth(text, textSize)
if (textSize == nil) then
textSize = 13
end
local len = 0
for i = 1, string.len(text) do
len = len + charwidth(string.sub(text, i, i), textSize)
end
return(len)
end
|
-- Every variable must start with this addon's unique ID, as each is a global.
local localization_strings = {
SI_ECHOEXP_MESSAGE = " c'est actif!",
------------------------------
}
------------------------------
--
--TODO use GetChatFontSize() to get size
--https://wiki.esoui.com/Text_Formatting
for stringId, stringValue in pairs(localization_strings) do
ZO_CreateStringId(stringId, stringValue)
SafeAddVersion(stringId, 1)
end
|
local playsession = {
{"Krono", {77770}},
{"littleminion007", {2030}},
{"wellczech", {1083}},
{"Discotek", {216846}},
{"supra90", {222008}},
{"Gerkiz", {110687}},
{"LeeFactor", {96158}},
{"TJ-orben", {1720}}
}
return playsession
|
local S = unified_inventory.gettext
function unified_inventory.canonical_item_spec_matcher(spec)
local specname = ItemStack(spec):get_name()
if specname:sub(1, 6) == "group:" then
local group_names = specname:sub(7):split(",")
return function (itemname)
local itemdef = minetest.registered_items[itemname]
for _, group_name in ipairs(group_names) do
if (itemdef.groups[group_name] or 0) == 0 then
return false
end
end
return true
end
else
return function (itemname) return itemname == specname end
end
end
function unified_inventory.item_matches_spec(item, spec)
local itemname = ItemStack(item):get_name()
return unified_inventory.canonical_item_spec_matcher(spec)(itemname)
end
function unified_inventory.extract_groupnames(groupname)
local specname = ItemStack(groupname):get_name()
if specname:sub(1, 6) == "group:" then
local group_names = specname:sub(7):split(",")
if #group_names == 1 then
return group_names[1], 1
end
local s = ""
for g=1,#group_names do
if g > 1 then
-- List connector
s = s .. S(" and ")
end
s = s .. group_names[g]
end
return s, #group_names
else
return nil, 0
end
end
unified_inventory.registered_group_items = {
mesecon_conductor_craftable = "mesecons:wire_00000000_off",
stone = "default:cobble",
wood = "default:wood",
book = "default:book",
sand = "default:sand",
leaves = "default:leaves",
tree = "default:tree",
vessel = "vessels:glass_bottle",
wool = "wool:white",
}
function unified_inventory.register_group_item(groupname, itemname)
unified_inventory.registered_group_items[groupname] = itemname
end
-- This is used when displaying craft recipes, where an ingredient is
-- specified by group rather than as a specific item. A single-item group
-- is represented by that item, with the single-item status signalled
-- in the "sole" field. If the group contains no items at all, the item
-- field will be nil.
--
-- Within a multiple-item group, we prefer to use an item that has the
-- same specific name as the group, and if there are more than one of
-- those items we prefer the one registered for the group by a mod.
-- Among equally-preferred items, we just pick the one with the
-- lexicographically earliest name.
--
-- The parameter to this function isn't just a single group name.
-- It may be a comma-separated list of group names. This is really a
-- "group:..." ingredient specification, minus the "group:" prefix.
local function compute_group_item(group_name_list)
local group_names = group_name_list:split(",")
local candidate_items = {}
for itemname, itemdef in pairs(minetest.registered_items) do
if (itemdef.groups.not_in_creative_inventory or 0) == 0 then
local all = true
for _, group_name in ipairs(group_names) do
if (itemdef.groups[group_name] or 0) == 0 then
all = false
end
end
if all then table.insert(candidate_items, itemname) end
end
end
local num_candidates = #candidate_items
if num_candidates == 0 then
return {sole = true}
elseif num_candidates == 1 then
return {item = candidate_items[1], sole = true}
end
local is_group = {}
local registered_rep = {}
for _, group_name in ipairs(group_names) do
is_group[group_name] = true
local rep = unified_inventory.registered_group_items[group_name]
if rep then registered_rep[rep] = true end
end
local bestitem = ""
local bestpref = 0
for _, item in ipairs(candidate_items) do
local pref
if registered_rep[item] then
pref = 4
elseif string.sub(item, 1, 8) == "default:" and is_group[string.sub(item, 9)] then
pref = 3
elseif is_group[item:gsub("^[^:]*:", "")] then
pref = 2
else
pref = 1
end
if pref > bestpref or (pref == bestpref and item < bestitem) then
bestitem = item
bestpref = pref
end
end
return {item = bestitem, sole = false}
end
local group_item_cache = {}
function unified_inventory.get_group_item(group_name)
if not group_item_cache[group_name] then
group_item_cache[group_name] = compute_group_item(group_name)
end
return group_item_cache[group_name]
end
|
---------------------------------------------------------------------------------------------------
-- User story: Smoke
-- Use case: OnDriverDistraction
-- Item: Happy path
--
-- Requirement summary:
-- [OnDriverDistraction] SUCCESS: getting SUCCESS:UI.OnDriverDistraction()
--
-- Description:
-- HMI sends OnDriverDistraction notification with valid parameters to SDL,
-- SDL resends notification to mobile application successful
-- Pre-conditions:
-- a. HMI and SDL are started
-- b. appID is registered and activated on SDL
-- c. appID is currently in Background, Full or Limited HMI level
-- Steps:
-- HMI sends OnDriverDistraction with valid parameters
-- Expected:
-- SDL receives notification and validates parameters
-- SDL checks if OnDriverDistraction is allowed by Policies
-- SDL checks if all parameters are allowed by Policies
-- SDL transfers notification with allowed parameters to mobile application
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local common = require('test_scripts/Smoke/commonSmoke')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Variables ]]
local OnDDValue = { "DD_ON", "DD_OFF" }
--[[ Local Functions ]]
local function onDriverDistraction(pOnDDValue)
local request = { state = pOnDDValue }
common.getHMIConnection():SendNotification("UI.OnDriverDistraction", request)
common.getMobileSession():ExpectNotification("OnDriverDistraction", request)
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Update Preloaded PT", common.updatePreloadedPT)
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("Register App", common.registerApp)
runner.Step("Activate App", common.activateApp)
runner.Title("Test")
for _, v in pairs(OnDDValue) do
runner.Step("OnDriverDistraction with state " .. v .. " Positive Case", onDriverDistraction, { v })
end
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
|
local base_ui = require"module/gui/component/base_ui"
local label = class("label",base_ui){
label = "Label",
style = {
font = nil,
font_color = nil,
bg = nil,
}
}
function label:__init(label,x,y,style)
base_ui.__init(self,x,y,0,0)
self:_load_style(style)
local font = self.style.font
self:set_box(font:getWidth(self.label),font:getHeight())
end
function label:_load_style(style)
style = style or {}
self.style.font = style.font or ling.font.default
self.style.font_color = style.font_color or {226,101,11,255}
self.style.bg = style.bg
end
function label:set_label(label)
self.label = label or self.label
local font = self.style.font
self:set_box(font:getWidth(self.label),font:getHeight())
return self
end
function label:get_label()
return self.label
end
function label:draw()
local x,y = self:get_pos()
local sf,df = self.style.font,ling.font.default
local is_set = (sf ~= df)
if self.style.bg then
self.style.bg:draw(x,y)
end
if is_set then
love.graphics.setFont(sf)
end
love.graphics.setColor(unpack(self.style.font_color))
love.graphics.print(self.label,x,y)
love.graphics.setColor(255,255,255,255)
if is_set then
love.graphics.setFont(ling.font.default)
end
end
return label
|
--------------------------------
-- @module SpriteBatchNode
-- @extend Node,TextureProtocol
-- @parent_module cc
--------------------------------
--
-- @function [parent=#SpriteBatchNode] appendChild
-- @param self
-- @param #cc.Sprite sprite
--------------------------------
--
-- @function [parent=#SpriteBatchNode] addSpriteWithoutQuad
-- @param self
-- @param #cc.Sprite child
-- @param #int z
-- @param #int aTag
-- @return SpriteBatchNode#SpriteBatchNode ret (return value: cc.SpriteBatchNode)
--------------------------------
--
-- @function [parent=#SpriteBatchNode] reorderBatch
-- @param self
-- @param #bool reorder
--------------------------------
--
-- @function [parent=#SpriteBatchNode] removeAllChildrenWithCleanup
-- @param self
-- @param #bool cleanup
--------------------------------
--
-- @function [parent=#SpriteBatchNode] lowestAtlasIndexInChild
-- @param self
-- @param #cc.Sprite sprite
-- @return long#long ret (return value: long)
--------------------------------
--
-- @function [parent=#SpriteBatchNode] atlasIndexForChild
-- @param self
-- @param #cc.Sprite sprite
-- @param #int z
-- @return long#long ret (return value: long)
--------------------------------
-- sets the TextureAtlas object
-- @function [parent=#SpriteBatchNode] setTextureAtlas
-- @param self
-- @param #cc.TextureAtlas textureAtlas
--------------------------------
--
-- @function [parent=#SpriteBatchNode] getTexture
-- @param self
-- @return Texture2D#Texture2D ret (return value: cc.Texture2D)
--------------------------------
--
-- @function [parent=#SpriteBatchNode] increaseAtlasCapacity
-- @param self
--------------------------------
-- returns the TextureAtlas object
-- @function [parent=#SpriteBatchNode] getTextureAtlas
-- @param self
-- @return TextureAtlas#TextureAtlas ret (return value: cc.TextureAtlas)
--------------------------------
-- Inserts a quad at a certain index into the texture atlas. The Sprite won't be added into the children array.<br>
-- This method should be called only when you are dealing with very big AtlasSrite and when most of the Sprite won't be updated.<br>
-- For example: a tile map (TMXMap) or a label with lots of characters (LabelBMFont)
-- @function [parent=#SpriteBatchNode] insertQuadFromSprite
-- @param self
-- @param #cc.Sprite sprite
-- @param #long index
--------------------------------
--
-- @function [parent=#SpriteBatchNode] setTexture
-- @param self
-- @param #cc.Texture2D texture
--------------------------------
--
-- @function [parent=#SpriteBatchNode] rebuildIndexInOrder
-- @param self
-- @param #cc.Sprite parent
-- @param #long index
-- @return long#long ret (return value: long)
--------------------------------
--
-- @function [parent=#SpriteBatchNode] highestAtlasIndexInChild
-- @param self
-- @param #cc.Sprite sprite
-- @return long#long ret (return value: long)
--------------------------------
-- removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter.<br>
-- warning Removing a child from a SpriteBatchNode is very slow
-- @function [parent=#SpriteBatchNode] removeChildAtIndex
-- @param self
-- @param #long index
-- @param #bool doCleanup
--------------------------------
--
-- @function [parent=#SpriteBatchNode] removeSpriteFromAtlas
-- @param self
-- @param #cc.Sprite sprite
--------------------------------
-- creates a SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and capacity of children.<br>
-- The capacity will be increased in 33% in runtime if it run out of space.<br>
-- The file will be loaded using the TextureMgr.
-- @function [parent=#SpriteBatchNode] create
-- @param self
-- @param #string fileImage
-- @param #long capacity
-- @return SpriteBatchNode#SpriteBatchNode ret (return value: cc.SpriteBatchNode)
--------------------------------
-- creates a SpriteBatchNode with a texture2d and capacity of children.<br>
-- The capacity will be increased in 33% in runtime if it run out of space.
-- @function [parent=#SpriteBatchNode] createWithTexture
-- @param self
-- @param #cc.Texture2D tex
-- @param #long capacity
-- @return SpriteBatchNode#SpriteBatchNode ret (return value: cc.SpriteBatchNode)
--------------------------------
-- @overload self, cc.Node, int, string
-- @overload self, cc.Node, int, int
-- @function [parent=#SpriteBatchNode] addChild
-- @param self
-- @param #cc.Node child
-- @param #int zOrder
-- @param #int tag
--------------------------------
--
-- @function [parent=#SpriteBatchNode] draw
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table transform
-- @param #unsigned int flags
--------------------------------
--
-- @function [parent=#SpriteBatchNode] getDescription
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#SpriteBatchNode] visit
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table parentTransform
-- @param #unsigned int parentFlags
--------------------------------
--
-- @function [parent=#SpriteBatchNode] sortAllChildren
-- @param self
--------------------------------
--
-- @function [parent=#SpriteBatchNode] removeChild
-- @param self
-- @param #cc.Node child
-- @param #bool cleanup
--------------------------------
--
-- @function [parent=#SpriteBatchNode] reorderChild
-- @param self
-- @param #cc.Node child
-- @param #int zOrder
return nil
|
--luacheck: ignore describe it
describe('rapidjson.decode()', function()
local rapidjson = require('rapidjson')
describe('should return value', function()
it('when decode values without array or object', function()
assert.are.equal('very funny', rapidjson.decode('"very funny"'))
assert.are.equal(1234, rapidjson.decode('1234'))
assert.are.equal(12.34, rapidjson.decode('12.34'))
assert.are.equal(rapidjson.null, rapidjson.decode('null'))
assert.are.equal(true, rapidjson.decode('true'))
assert.are.equal(false, rapidjson.decode('false'))
assert.are.equal(1E20, rapidjson.decode('100000000000000000000'))
if tostring(0x7fffffffffffffff) == '9223372036854775807' then -- check if Lua is compiled with 64 bit integer
assert.are.equal(9223372036854775807, rapidjson.decode('9223372036854775807'))
end
end)
it('when parse invalid json data', function()
local r, m, idx
r, _, m = rapidjson.decode('')
assert.are.equal(nil, r)
assert.are.equal('string', type(m))
idx = string.find(m, "The document is empty.", 1, true)
assert.are_not.equal(nil, idx)
-- kParseStopWhenDoneFlag: Supported in DKJson
-- r, _, m = rapidjson.decode('{}10')
-- assert.are.equal(nil, r)
-- assert.are.equal('string', type(m))
-- idx = string.find(m, "The document root must not be followed by other values.", 1, true)
-- assert.are_not.equal(nil, idx)
r, _, m = rapidjson.decode('{"a":b}')
assert.are.equal(nil, r)
assert.are.equal('string', type(m))
idx = string.find(m, "Invalid value.", 1, true)
assert.are_not.equal(nil, idx)
-- DKJson: Supported
r, _, m = rapidjson.decode('{12}')
assert.are.equal(nil, r)
assert.are.equal('string', type(m))
idx = string.find(m, "Missing a name for object member.", 1, true)
assert.are_not.equal(nil, idx)
-- DKJson: TrailingCommas Supported
r, _, m = rapidjson.decode('{"a",}')
assert.are.equal(nil, r)
assert.are.equal('string', type(m))
idx = string.find(m, "Missing a colon after a name of object member.", 1, true)
assert.are_not.equal(nil, idx)
r, _, m = rapidjson.decode('{"a":[] "b":[]}')
assert.are.equal(nil, r)
assert.are.equal('string', type(m))
idx = string.find(m, "Missing a comma or '}' after an object member.", 1, true)
assert.are_not.equal(nil, idx)
r, _, m = rapidjson.decode('[{}{}]')
assert.are.equal(nil, r)
assert.are.equal('string', type(m))
idx = string.find(m, "Missing a comma or ']' after an array element.", 1, true)
assert.are_not.equal(nil, idx)
r, _, m = rapidjson.decode('["\\uke"]')
assert.are.equal(nil, r)
assert.are.equal('string', type(m))
idx = string.find(m, "Incorrect hex digit after \\u escape in string.", 1, true)
assert.are_not.equal(nil, idx)
r, _, m = rapidjson.decode('["\\p"]')
assert.are.equal(nil, r)
assert.are.equal('string', type(m))
idx = string.find(m, "Invalid escape character in string.", 1, true)
assert.are_not.equal(nil, idx)
r, _, m = rapidjson.decode('["a]')
assert.are.equal(nil, r)
assert.are.equal('string', type(m))
idx = string.find(m, "Missing a closing quotation mark in string.", 1, true)
assert.are_not.equal(nil, idx)
r, _, m = rapidjson.decode('[999999999999999999e9999999999999999999]')
assert.are.equal(nil, r)
assert.are.equal('string', type(m))
idx = string.find(m, "Number too big to be stored in double.", 1, true)
assert.are_not.equal(nil, idx)
r, _, m = rapidjson.decode('[0.,]')
assert.are.equal(nil, r)
assert.are.equal('string', type(m))
idx = string.find(m, "Miss fraction part in number.", 1, true)
assert.are_not.equal(nil, idx)
r, _, m = rapidjson.decode('[1.2e,]')
assert.are.equal(nil, r)
assert.are.equal('string', type(m))
idx = string.find(m, "Miss exponent in number.", 1, true)
assert.are_not.equal(nil, idx)
--"The surrogate pair in string is invalid. ()", ''
--"Invalid encoding in string. ()",
end)
end)
describe('should raise error', function()
it('when arg type are neither string nor number', function()
assert.has_error(function() rapidjson.decode(true) end)
assert.has_error(function() rapidjson.decode(false) end)
assert.has_error(function() rapidjson.decode(function()end) end)
assert.has_error(function() rapidjson.decode({}) end)
assert.has_error(function() rapidjson.decode(io.input()) end)
end)
end)
describe('sould return empty table', function()
it('when decode empty array', function()
local a = rapidjson.decode('[]')
assert.are.same({}, a)
end)
it('when decode empty object', function()
local a = rapidjson.decode('{}')
assert.are.same({}, a)
end)
end)
describe('should return valid table', function()
it('when decode simple array', function()
local a = rapidjson.decode('[1, 2, "3", true]')
local e = {1, 2, '3', true}
assert.are.same(e, a)
end)
it('when decode simple object', function()
local a = rapidjson.decode('{"a":1, "b":2.1, "c":"", "d":false}')
local e = {a=1, b=2.1, c='', d=false}
assert.are.same(e, a)
end)
it('when decode nested objects', function()
local a = rapidjson.decode([[ {"a":[{"b":[1, 2, 3], "c":{}}, {}]} ]])
assert.are.same({a={{b={1,2,3}, c={}}, {}}}, a)
end)
end)
describe('valid json data formts', function()
it('should parse escaped characters', function()
local a = rapidjson.decode([[ ["\"", "\\", "\/", "\b", "\f", "\n", "\r", "\t", "\u0021"] ]])
local e = {[["]],[[\]], [[/]], '\b','\f','\n','\r','\t','!'}
assert.are.same(e, a)
end)
it('should parse all number formats', function()
local a = rapidjson.decode([[ [1000, -1000, 23.4, -23.4, 100e5, 1.99e3, -100E5, -100e-5, 100e+5, 1.99E3, 1.99E+3, -1.99e-3, -1.99e+3] ]])
local e = {1000, -1000, 23.4, -23.4, 100e5, 1.99e3, -100E5, -100e-5, 100e5, 1.99E3, 1.99E3, -1.99e-3, -1.99e3}
assert.are.same(e, a)
a = rapidjson.decode([[{"x": 23456789012E66}]])
e = {x= 23456789012E66}
assert.are.equal(tostring(e.x), tostring(a.x))
end)
it('shuld parse null', function()
local a = rapidjson.decode([[ [null] ]])
local e = {rapidjson.null}
assert.are.same(e, a)
end)
end)
end)
|
local GlobalVariablesScript = {}
function GlobalVariablesScript:PlaySuccessSound(player, hitresult, callingEntity)
callingEntity:PlaySound(GetWorld():Find("quizSuccessSound").sound)
end
return GlobalVariablesScript
|
-----------------------------------
-- Area: Labyrinth of Onzozo
-- Mob: Flying Manta
-- Note: PH for Lord of Onzozo and Peg Powler
-----------------------------------
local ID = require("scripts/zones/Labyrinth_of_Onzozo/IDs")
require("scripts/globals/regimes")
require("scripts/globals/mobs")
-----------------------------------
function onMobDeath(mob, player, isKiller)
tpz.regime.checkRegime(player, mob, 774, 1, tpz.regime.type.GROUNDS)
end
function onMobDespawn(mob)
tpz.mob.phOnDespawn(mob, ID.mob.LORD_OF_ONZOZO_PH, 4, math.random(75600, 86400)) -- 18 to 24 hours
tpz.mob.phOnDespawn(mob, ID.mob.PEG_POWLER_PH, 4, math.random(7200, 57600)) -- 2 to 16 hours
end
|
require("nvim-tmux-navigation").setup({
disable_when_zoomed = true, -- defaults to false
keybindings = {
left = "<C-h>",
down = "<C-j>",
up = "<C-k>",
right = "<C-l>",
last_active = "<C-\\>",
next = "<C-Space>",
},
})
|
--[[
PUC-Rio
INF1405 - Construção de Sistemas 2015.2
Professor Edmundo Torreão
Gabriel de Quadros Ligneul 1212560
Exploradores de Andrômeda
Pirate.lua
--]]
local Class = require "Class"
local LaserBeam = require "LaserBeam"
local Ship = require "Ship"
local Vector = require "Vector"
local Window = require "Window"
--- Class Pirate
local Pirate = Class(Ship)
--- Constants
Pirate.LIFE = 150
Pirate.SPEED_LIMIT = 150
Pirate.ACCELERATION = 150
Pirate.IMAGE_PATH = "data/pirate.png"
Pirate.SCORE = 500
Pirate.MIN_X = 700
Pirate.RELOAD_INTERVAL = 1.0
Pirate.SHOOT_INTERVAL = 2.0
Pirate.PROJECTILE_INTERVAL = 0.2
--- Creates a new Pirate
--- Parameters
--- shootCallback Function that will be called when the pirate shoot
--- player The player that the pirate will fight against
function Pirate.create(shootCallback, player)
local image = love.graphics.newImage(Pirate.IMAGE_PATH)
local image_w, image_h = image:getWidth(), image:getHeight()
local x = Window.WIDTH + image_w
local y = math.random(Window.HEIGHT - image_h)
local self = Pirate._create(x, y, nil, nil, 0, Window.HEIGHT - image_h,
Pirate.SPEED_LIMIT, Pirate.ACCELERATION, Pirate.LIFE, image)
self.player = player
self.shootCallback = shootCallback
self.shoot_coroutine = coroutine.create(Pirate.shoot)
self:setXForce(-1)
self:setYForce(-1)
return self
end
--- Defines the pirate moviment
function Pirate:moviment(dt)
local bbox = self:getBBox()
local player_bbox = self.player:getBBox()
-- Horizontal moviment
if bbox.x < Pirate.MIN_X then
self:setXForce(1)
elseif bbox.x > Window.WIDTH - 2 * self.image:getWidth() then
self:setXForce(-1)
end
-- Vertical moviment
if bbox.y < self.image:getHeight() then
self:setYForce(1)
elseif bbox.y > Window.HEIGHT - 2 * self.image:getHeight() then
self:setYForce(-1)
end
end
--- Creates a pirate's projectile
function Pirate:createProjectile()
local bbox = self:getBBox()
local x, y = bbox.x, bbox.y + bbox.h / 2
local dir_x = - bbox.x
local dir_y = math.random(Window.HEIGHT) - bbox.y
local direction = Vector.create(dir_x, dir_y):normalize()
return LaserBeam.create(x, y, direction, {255, 0, 0})
end
--- Shoots projectiles
function Pirate:shoot(dt)
while not self:isDestroyed() do
local reload_time = 0
while reload_time < Pirate.RELOAD_INTERVAL do
self, dt = coroutine.yield()
reload_time = reload_time + dt
end
local shoot_time = 0
while shoot_time < Pirate.SHOOT_INTERVAL do
local projectile_time = 0
while projectile_time < Pirate.PROJECTILE_INTERVAL do
self, dt = coroutine.yield()
shoot_time = shoot_time + dt
projectile_time = projectile_time + dt
end
local projectile = self:createProjectile()
self.shootCallback(projectile)
end
end
end
--- Returns the score earned after destroying the element
function Pirate:getScore()
return Pirate.SCORE
end
--- Updates the ship position
--- Parameters
--- dt Time elapsed in milliseconds
function Pirate:update(dt)
Ship.update(self, dt)
self:moviment(dt)
--coroutine.resume(self.shoot_coroutine, self, dt)
local status, err = coroutine.resume(self.shoot_coroutine, self, dt)
if not status then print(err) end
end
return Pirate
|
-- renumber test comments in ltcltest.lua
testno = false
for s in io.lines() do
m = string.match(s, '^-- (%d+)$')
if m then
if not testno then
testno = m * 1
else
testno = testno + 1
end
print("-- "..tostring(testno))
else
print(s)
end
end
|
-- by CapsAdmin
local flags = {
ad = {16, 11,0,0},
ae = {16, 11,16,0},
af = {16, 11,32, 0},
ag = {16, 11,48,0},
ai = {16, 11,64,0},
al = {16, 11,80,0},
am = {16, 11,96,0},
an = {16, 11,112,0},
ao = {16, 11,128,0},
ar = {16, 11,144,0},
as = {16, 11,160,0},
at = {16, 11,176,0},
au = {16, 11,192,0},
aw = {16, 11,0,11},
ax = {16, 11,16,11},
az = {16, 11,32,11},
ba = {16, 11,48,11},
bb = {16, 11,64,11},
bd = {16, 11,80,11},
be = {16, 11,96,11},
bf = {16, 11,112,11},
bg = {16, 11,128,11},
bh = {16, 11,144,11},
bi = {16, 11,160,11},
bj = {16, 11,176,11},
bm = {16, 11,192,11},
bn = {16, 11,0,22},
bo = {16, 11,16,22},
br = {16, 11,32,22},
bs = {16, 11,48,22},
bt = {16, 11,64,22},
bv = {16, 11,80,22},
bw = {16, 11,96,22},
by = {16, 11,112,22},
bz = {16, 11,128,22},
ca = {16, 11,144,22},
catalonia = {16, 11,160,22},
cc = {16, 11,176,22},
cd = {16, 11,192,22},
cf = {16, 11,0,33},
cg = {16, 11,16,33},
ch = {11, 11,32,33},
ci = {16, 11,43,33},
ck = {16, 11,59,33},
cl = {16, 11,75,33},
cm = {16, 11,91,33},
cn = {16, 11,107,33},
co = {16, 11,123,33},
cr = {16, 11,139,33},
cs = {16, 11,155,33},
cu = {16, 11,171,33},
cv = {16, 11,187,33},
cx = {16, 11,0,44},
cy = {16, 11,16,44},
cz = {16, 11,32,44},
de = {16, 11,48,44},
dj = {16, 11,64,44},
dk = {16, 11,80,44},
dm = {16, 11,96,44},
["do"] = {16, 11,112,44},
dz = {16, 11,128,44},
ec = {16, 11,144,44},
ee = {16, 11,160,44},
eg = {16, 11,176,44},
eh = {16, 11,192,44},
england = {16, 11,0,55},
er = {16, 11,16,55},
es = {16, 11,32,55},
et = {16, 11,48,55},
europeanunion = {16, 11,64,55},
fam = {16, 11,80,55},
fi = {16, 11,96,55},
fj = {16, 11,112,55},
fk = {16, 11,128,55},
fm = {16, 11,144,55},
fo = {16, 11,160,55},
fr = {16, 11,176,55},
ga = {16, 11,192,55},
gb = {16, 11,0,66},
gd = {16, 11,16,66},
ge = {16, 11,32,66},
gf = {16, 11,48,66},
gh = {16, 11,64,66},
gi = {16, 11,80,66},
gl = {16, 11,96,66},
gm = {16, 11,112,66},
gn = {16, 11,128,66},
gp = {16, 11,144,66},
gq = {16, 11,160,66},
gr = {16, 11,176,66},
gs = {16, 11,192,66},
gt = {16, 11,0,77},
gu = {16, 11,16,77},
gw = {16, 11,32,77},
gy = {16, 11,48,77},
hk = {16, 11,64,77},
hm = {16, 11,80,77},
hn = {16, 11,96,77},
hr = {16, 11,112,77},
ht = {16, 11,128,77},
hu = {16, 11,144,77},
id = {16, 11,160,77},
ie = {16, 11,176,77},
il = {16, 11,192,77},
["in"] = {16, 11,0,88},
io = {16, 11,16,88},
iq = {16, 11,32,88},
ir = {16, 11,48,88},
is = {16, 11,64,88},
it = {16, 11,80,88},
jm = {16, 11,96,88},
jo = {16, 11,112,88},
jp = {16, 11,128,88},
ke = {16, 11,144,88},
kg = {16, 11,160,88},
kh = {16, 11,176,88},
ki = {16, 11,192,88},
km = {16, 11,0,99},
kn = {16, 11,16,99},
kp = {16, 11,32,99},
kr = {16, 11,48,99},
kw = {16, 11,64,99},
ky = {16, 11,80,99},
kz = {16, 11,96,99},
la = {16, 11,112,99},
lb = {16, 11,128,99},
lc = {16, 11,144,99},
li = {16, 11,160,99},
lk = {16, 11,176,99},
lr = {16, 11,192,99},
ls = {16, 11,0,110},
lt = {16, 11,16,110},
lu = {16, 11,32,110},
lv = {16, 11,48,110},
ly = {16, 11,64,110},
ma = {16, 11,80,110},
mc = {16, 11,96,110},
md = {16, 11,112,110},
me = {16, 11,128,110},
mg = {16, 11,144,110},
mh = {16, 11,160,110},
mk = {16, 11,176,110},
ml = {16, 11,192,110},
mm = {16, 11,0,121},
mn = {16, 11,16,121},
mo = {16, 11,32,121},
mp = {16, 11,48,121},
mq = {16, 11,64,121},
mr = {16, 11,80,121},
ms = {16, 11,96,121},
mt = {16, 11,112,121},
mu = {16, 11,144,121},
mv = {16, 11,160,121},
mw = {16, 11,176,121},
mx = {16, 11,192,121},
my = {16, 11,0,132},
mz = {16, 11,16,132},
na = {16, 11,32,132},
nc = {16, 11,48,132},
ne = {16, 11,64,132},
nf = {16, 11,80,132},
ng = {16, 11,96,132},
ni = {16, 11,112,132},
nl = {16, 11,128,132},
no = {16, 11,144,132},
np = {9,11,160,132},
nr = {16, 11,169,132},
nu = {16, 11,185,132},
nz = {16, 11,0,143},
om = {16, 11,16,143},
pa = {16, 11,32,143},
pe = {16, 11,48,143},
pf = {16, 11,64,143},
pg = {16, 11,80,143},
ph = {16, 11,96,143},
pk = {16, 11,112,143},
pl = {16, 11,128,143},
pm = {16, 11,144,143},
pn = {16, 11,160,143},
pr = {16, 11,176,143},
ps = {16, 11,192,143},
pt = {16, 11,0,154},
pw = {16, 11,16,154},
py = {16, 11,32,154},
qa = {16, 11,48,154},
re = {16, 11,64,154},
ro = {16, 11,80,154},
rs = {16, 11,96,154},
ru = {16, 11,112,154},
rw = {16, 11,128,154},
sa = {16, 11,144,154},
sb = {16, 11,160,154},
sc = {16, 11,176,154},
scotland = {16, 11,192,154},
sd = {16, 11,0,165},
se = {16, 11,16,165},
sg = {16, 11,32,165},
sh = {16, 11,48,165},
si = {16, 11,64,165},
sj = {16, 11,80,165},
sk = {16, 11,96,165},
sl = {16, 11,112,165},
sm = {16, 11,128,165},
sn = {16, 11,144,165},
so = {16, 11,160,165},
sr = {16, 11,176,165},
st = {16, 11,192,165},
sv = {16, 11,0,176},
sy = {16, 11,16,176},
sz = {16, 11,32,176},
tc = {16, 11,48,176},
td = {16, 11,64,176},
tf = {16, 11,80,176},
tg = {16, 11,96,176},
th = {16, 11,112,176},
tj = {16, 11,128,176},
tk = {16, 11,144,176},
tl = {16, 11,160,176},
tm = {16, 11,176,176},
tn = {16, 11,192,176},
to = {16, 11,0,187},
tr = {16, 11,16,187},
tt = {16, 11,32,187},
tv = {16, 11,48,187},
tw = {16, 11,64,187},
tz = {16, 11,80,187},
ua = {16, 11,96,187},
ug = {16, 11,112,187},
um = {16, 11,128,187},
us = {16, 11,144,187},
uy = {16, 11,160,187},
uz = {16, 11,176,187},
va = {16, 11,192,187},
vc = {16, 11,0,198},
ve = {16, 11,16,198},
vg = {16, 11,32,198},
vi = {16, 11,48,198},
vn = {16, 11,64,198},
vu = {16, 11,80,198},
wales = {16, 11,96,198},
wf = {16, 11,112,198},
ws = {16, 11,128,198},
ye = {16, 11,144,198},
yt = {16, 11,160,198},
za = {16, 11,176,198},
zm = {16, 11,192,198},
zw = {16, 11,208,0},
} -- w,h, x,y, u1,u2,u3,u4
flags.eu = flags.eu or flags.europeanunion
local mat = Material("silk_icon_flags.png")
local W = 224
local H = 209
for _, info in next,flags do
local w, h = info[1], info[2]
local x, y = info[3], info[4]
info[5] = (x / W) + 0.0025
info[6] = (y / H) + 0.0025
info[7] = ((x + w) / W) - 0.0025
info[8] = ((y + h) / H) - 0.0025
end
--PrintTable(flags)
function surface.DrawFlag(country_code, x, y, w, h)
local info = flags[country_code]
if not info then return end
w = w or 16
h = h or 11
surface.SetMaterial(mat)
surface.SetDrawColor(255, 255, 255, 255)
surface.DrawTexturedRectUV(x,y, w,h, info[5],info[6],info[7],info[8])
return w,h
end
|
local AU = require( "adoc_cmd_ext.adoc_util" )
local U = require( "adoc_cmd_ext.util" )
describe( "adoc_util", function()
test( "tokenize_table", function()
local f = io.open( "test/xmpl01/pre.adoc" )
local str = f:read( "*a" )
local t = AU.tokenize_table( str )
assert.is.same( #t, 21 )
end )
test( "scan_parameter_value", function()
local v1 = AU.scan_parameter_value( "[ foobar ]" )
assert.is.same( "foobar", v1 )
local v2 = AU.scan_parameter_value( "[ foo bar ]" )
assert.is.same( "foo bar", v2 )
local v3 = AU.scan_parameter_value( "[]" )
assert.is.same( "", v3 )
local v4 = AU.scan_parameter_value( "[ ]" )
assert.is.same( "", v4 )
end )
test( "scan_command_instance", function()
local c1 = AU.scan_command_instance( "/:sub_def[ abc ][][ foo bar ]" )
assert.is.same( "sub_def", c1.name )
assert.is.same( "abc", c1.para[ 1 ] )
assert.is.same( "", c1.para[ 2 ] )
assert.is.same( "foo bar", c1.para[ 3 ] )
end )
end )
|
local ok, data = fa.pio( 0x06, 0x00 );
print [[
HTTP/1.1 200 OK
Content-Type: application/json
]]
print( '{"error":"","data":' .. data .. '}' );
|
local settings = {
-- Decomposer options
decomposer_power_requirement = 100000 / 2,
decomposer_item_requirement = 10,
enable_decomposer = true,
-- Colors, dyeing unit, paints
enable_colors_for_aluminium = true,
-- Saw
enable_saw_for_aluminium = true,
}
local modname = minetest.get_current_modname()
local prefix = modname.."_"
-- Scan settings
for name, value in pairs(settings) do
local setting_type = type(value)
if setting_type == "boolean" then
material_science[name] = minetest.settings:get_bool(prefix..name)
if material_science[name] == nil then
material_science[name] = value
end
else
material_science[name] = value
end
end
|
--Здесь должны быть квестовые итемы(не точно), итемы, которые не должны выпадать и еще какая-то поебота
PLUGIN.ignored = {
"psihelem",
"rpg7",
"gauska",
"buldog",
"fnp",
"scar",
"otboinik",
"aps",
"camelback",
"camelbackpack",
"ppsh",
"ammobox",
"tshirt_bez_bab",
"silence",
"scope_pso",
"dolg_bron",
"donate_exo",
"sh_donate_armor_aaa_dolg",
"cassette_bandits",
"cassette_barman",
"cassette_firelake",
"cassette_freedom",
"cassette_merc",
"cassette_standart",
"cassette_true",
"cassette_wickedrabbit",
"сhzo",
"docsbu",
"kowelek",
"vipkit"
}
|
-- This implements a lua parser of http://maxmind.github.io/MaxMind-DB/
local has_bit32, bit = pcall ( require , "bit32" )
bit = has_bit32 and bit or require ( "bit" )
local sunpack = string.unpack or require ( "struct" ).unpack
local mmdb_separator = "\171\205\239MaxMind.com"
local geodb_methods = { }
local geodb_mt = {
__index = geodb_methods ;
}
local file_contents_methods = { }
local file_contents_mt = {
__index = file_contents_methods ;
}
local data_types = { }
local getters = { }
function file_contents_methods:normalize_index ( i )
return math.max ( 1 , i >= 0 and i or self.size + i + 1 )
end
function file_contents_methods:sub ( i , j )
i , j = self:normalize_index ( i ) , math.min ( self.size , self:normalize_index ( j or -1 ) )
if j < i then return "" end
assert ( self.fd:seek ( "set" , i - 1 ) )
local sub = assert ( self.fd:read ( j - i + 1 ) )
assert ( #sub == j - i + 1 , "Could not read the requested chunk completely" )
return sub
end
function file_contents_methods:byte ( i , j )
return self:sub ( i , j or i ) :byte ( 1 , -1 )
end
local function open_db ( filename , read_once )
local fd = assert ( io.open ( filename , "rb" ) )
local size, contents
if read_once then
size = #contents
contents = assert ( fd:read ( "*a" ) )
else
size = assert ( fd:seek( "end" ) )
contents = setmetatable ( { fd = fd , size = size } , file_contents_mt )
end
local start_metadata do
-- Find data section seperator; at most it's 128kb from the end
local last_chunk_begin = math.max ( 1 , size - 128 * 1024 + 1 )
local last_chunk = contents:sub ( last_chunk_begin )
while true do
local s , e = last_chunk:find ( mmdb_separator , start_metadata or 1 , true )
if s == nil then break end
start_metadata = e + 1
end
if start_metadata == nil then
error ( "Invalid MaxMind Database" )
end
start_metadata = start_metadata + last_chunk_begin - 1
end
local self = setmetatable ( {
contents = contents ;
start_metadata = start_metadata ;
data = nil ;
left = nil ;
right = nil ;
ipv4_start = 0 ;
} , geodb_mt )
local offset , data = self:read_data ( start_metadata , 0 )
self.data = data
local getter = getters [ data.record_size ]
if getter == nil then
error ( "Unsupported record size: " .. data.record_size )
end
self.left , self.right , self.record_length = getter.left , getter.right , getter.record_length
self.start_data = self.record_length * self.data.node_count + 16 + 1
if self.data.ip_version == 6 then
self.ipv4_start = self:ipv6_find_ipv4_start ( )
end
return self
end
function geodb_methods:read_data ( base , offset )
local control_byte = self.contents:byte ( base + offset )
offset = offset + 1
-- The first three bits of the control byte tell you what type the field is.
local data_type = bit.rshift ( control_byte , 5 )
-- If these bits are all 0, then this is an "extended" type,
-- which means that the next byte contains the actual type.
if data_type == 0 then
data_type = self.contents:byte ( base + offset ) + 7
offset = offset + 1
end
local func = data_types [ data_type ]
if func == nil then
error ( "Unknown data section: " .. data_type )
end
-- The next five bits in the control byte tell you how long the data
-- field's payload is, except for maps and pointers.
local data_size = bit.band ( control_byte , 31 )
if data_type == 1 then
-- Ignore for pointers
elseif data_size == 29 then
-- If the value is 29, then the size is 29 + the next byte after the type specifying bytes as an unsigned integer.
data_size = 29 + self.contents:byte ( base + offset )
offset = offset + 1
elseif data_size == 30 then
-- If the value is 30, then the size is 285 + the next two bytes after the type specifying bytes as a single unsigned integer.
local hi , lo = self.contents:byte ( base + offset , base + offset+1 )
offset = offset + 2
data_size = 285 + bit.bor ( bit.lshift ( hi , 8 ) , lo )
elseif data_size == 31 then
-- If the value is 31, then the size is 65,821 + the next three bytes after the type specifying bytes as a single unsigned integer.
local o1 , o2 , o3 , o4 = self.contents:byte ( base + offset , base + offset+3 )
offset = offset + 4
data_size = 65821 + bit.bor (
bit.lshift ( o1 , 24 ) ,
bit.lshift ( o2 , 16 ) ,
bit.lshift ( o3 , 8 ) ,
o4 )
end
return func ( self , base , offset , data_size )
end
function geodb_methods:read_pointer ( base , offset , magic )
local size = bit.rshift ( magic , 3 )
local pointer
if size == 0 then
-- If the size is 0, the pointer is built by appending the next byte to the last three bits to produce an 11-bit value
local o1 = self.contents:byte ( base + offset )
offset = offset + 1
pointer = bit.bor (
bit.lshift ( bit.band ( magic , 7 ) , 8 ) ,
o1 )
elseif size == 1 then
-- If the size is 1, the pointer is built by appending the next two bytes to the last three bits to produce a 19-bit value + 2048.
local o1 , o2 = self.contents:byte ( base + offset , base + offset + 1 )
offset = offset + 2
pointer = bit.bor (
bit.lshift ( bit.band ( magic , 7 ) , 16 ) ,
bit.lshift ( o1 , 8 ) ,
o2 ) + 2048
elseif size == 2 then
-- If the size is 2, the pointer is built by appending the next three bytes to the last three bits to produce a 27-bit value + 526336.
local o1 , o2 , o3 = self.contents:byte ( base + offset , base + offset + 2 )
offset = offset + 3
pointer = bit.bor (
bit.lshift ( bit.band ( magic , 7 ) , 24 ) ,
bit.lshift ( o1 , 16 ) ,
bit.lshift ( o2 , 8 ) ,
o3 ) + 526336
elseif size == 3 then
-- Finally, if the size is 3, the pointer's value is contained in the next four bytes as a 32-bit value.
-- In this case, the last three bits of the control byte are ignored.
local o1 , o2 , o3 , o4 = self.contents:byte ( base + offset , base + offset+3 )
offset = offset + 4
pointer = bit.bor (
bit.lshift ( o1 , 24 ) ,
bit.lshift ( o2 , 16 ) ,
bit.lshift ( o3 , 8 ) ,
o4 )
end
local _ , val = self:read_data ( base , pointer )
return offset , val
end
data_types [ 1 ] = geodb_methods.read_pointer -- Pointer
function geodb_methods:read_string ( base , offset , length )
return offset + length , self.contents:sub ( base + offset , base + offset + length - 1 )
end
data_types [ 2 ] = geodb_methods.read_string -- UTF-8
data_types [ 4 ] = geodb_methods.read_string -- Binary
function geodb_methods:read_double ( base , offset , length )
assert ( length == 8 , "double of non-8 length" )
local src = self.contents:sub ( base + offset , base + offset + 8 - 1 )
return offset + 8 , sunpack ( ">d", src )
end
data_types [ 3 ] = geodb_methods.read_double -- Double
function geodb_methods:read_float ( base , offset , length )
assert ( length == 4 , "float of non-4 length" )
local src = self.contents:sub ( base + offset , base + offset + 4 - 1 )
return offset + 4 , sunpack ( ">f", src )
end
data_types [ 15 ] = geodb_methods.read_float -- Float
-- Integer types
-- The number of bytes used is determined by the length specifier in the control byte.
-- General function
function geodb_methods:read_unsigned ( base , offset , length )
if length == 0 then return offset , 0 end
local bytes = self.contents:sub ( base + offset , base + offset + length - 1 )
return offset + length , sunpack (">I" .. length, bytes)
end
function geodb_methods:read_signed ( base , offset , length )
if length == 0 then return offset , 0 end
local bytes = self.contents:sub ( base + offset , base + offset + length - 1 )
return offset + length , sunpack (">i" .. length, bytes)
end
data_types [ 5 ] = geodb_methods.read_unsigned -- unsigned 16-bit int
data_types [ 6 ] = geodb_methods.read_unsigned -- unsigned 32-bit int
data_types [ 8 ] = geodb_methods.read_signed -- signed 32-bit int
data_types [ 9 ] = geodb_methods.read_unsigned -- unsigned 64-bit int
data_types [ 10 ] = geodb_methods.read_unsigned -- unsigned 128-bit int
function geodb_methods:read_map ( base , offset , n_pairs ) -- Map
local map = { }
for i = 1 , n_pairs do
local key , val
offset , key = self:read_data ( base , offset )
assert ( type ( key ) == "string" )
offset , val = self:read_data ( base , offset )
map [ key ] = val
end
return offset , map
end
data_types [ 7 ] = geodb_methods.read_map
function geodb_methods:read_array ( base , offset , n_items ) -- Array
local array = { }
for i = 1 , n_items do
local val
offset , val = self:read_data ( base , offset )
array [ i ] = val
end
return offset , array
end
data_types [ 11 ] = geodb_methods.read_array
data_types [ 13 ] = function ( self , base , offset , zero ) -- End Marker
return nil
end
data_types [ 14 ] = function ( self , base , offset , length ) -- Boolean
return offset + length , length == 1
end
getters [ 24 ] = {
left = function ( self , offset )
local o1 , o2 , o3 = self.contents:byte ( offset , offset + 2 )
return bit.bor (
bit.lshift ( o1 , 16 ) ,
bit.lshift ( o2 , 8 ) ,
o3 )
end ;
right = function ( self , offset )
local o1 , o2 , o3 = self.contents:byte ( offset + 3 , offset + 5 )
return bit.bor (
bit.lshift ( o1 , 16 ) ,
bit.lshift ( o2 , 8 ) ,
o3 )
end ;
record_length = 6 ;
}
getters [ 28 ] = {
left = function ( self , offset )
local o1 , o2 , o3 , o4 = self.contents:byte ( offset , offset + 3 )
return bit.bor (
bit.lshift ( bit.band ( o4 , 0xf0 ) , 20 ) ,
bit.lshift ( o1 , 16 ) ,
bit.lshift ( o2 , 8 ) ,
o3 )
end ;
right = function ( self , offset )
local o1 , o2 , o3 , o4 = self.contents:byte ( offset + 3 , offset + 6 )
return bit.bor (
bit.lshift ( bit.band ( o1 , 0x0F ) , 24 ) ,
bit.lshift ( o2 , 16 ) ,
bit.lshift ( o3 , 8 ) ,
o4 )
end ;
record_length = 7 ;
}
getters [ 32 ] = {
left = function ( self , offset )
local o1 , o2 , o3 , o4 = self.contents:byte ( offset , offset + 3 )
return bit.bor (
bit.lshift ( o1 , 24 ) ,
bit.lshift ( o2 , 16 ) ,
bit.lshift ( o3 , 8 ) ,
o4 )
end ;
right = function ( self , offset )
local o1 , o2 , o3 , o4 = self.contents:byte ( offset + 4 , offset + 7 )
return bit.bor (
bit.lshift ( o1 , 24 ) ,
bit.lshift ( o2 , 16 ) ,
bit.lshift ( o3 , 8 ) ,
o4 )
end ;
record_length = 8 ;
}
function geodb_methods:search ( bits , node )
node = node or 0
local seen = { [node] = true }
for _ , bit in ipairs ( bits ) do
local offset = node * self.record_length + 1
local record_value
if bit then
record_value = self:right ( offset )
else
record_value = self:left ( offset )
end
if seen [ record_value ] then
error ( "Cyclical tree" )
end
seen [ record_value ] = true
if record_value == self.data.node_count then
-- If the record value is equal to the number of nodes, that means that
-- we do not have any data for the IP address, and the search ends here.
return nil
elseif record_value > self.data.node_count then
-- If the record value is greater than the number of nodes in the search tree,
-- then it is an actual pointer value pointing into the data section.
-- The value of the pointer is calculated from the start of the data section,
-- not from the start of the file.
local data_offset = record_value - self.data.node_count - 16
local _ , res = self:read_data ( self.start_data , data_offset )
return node , res
else
node = record_value
end
end
return node
end
function geodb_methods:ipv6_find_ipv4_start ( )
-- Use IPv4-mapped IPv6 addresses located at ::ffff:/80
local bits = { }
for i = 1 , 80 do
bits [ i ] = false
end
for i = 81 , 96 do
bits [ i ] = true
end
return self:search ( bits , 0 )
end
local function ipv4_to_bit_array ( str )
local bits = { }
local i = 0
for byte in str:gmatch ( "(%d%d?%d?)%.?" ) do
byte = tonumber ( byte )
for j = 1 , 8 do
bits[i*8+j] = bit.band ( 1 , bit.rshift ( byte , 8-j ) ) == 1
end
i = i + 1
end
return bits
end
function geodb_methods:search_ipv4 ( str )
return select ( 2 , self:search ( ipv4_to_bit_array ( str ) , self.ipv4_start ) )
end
local function ipv6_split ( str )
local components = { }
local n = 0
for u16 in str:gmatch ( "(%x%x?%x?%x?):?" ) do
n = n + 1
u16 = tonumber ( u16 , 16 )
assert ( u16 , "Invalid ipv6 address" )
components [ n ] = u16
end
return components , n
end
local function ipv6_to_bit_array ( str )
local a , b = str:match ( "^([%x:]-)::([%x:]*)$" )
local components , n = ipv6_split ( a or str )
if a ~= nil then
local end_components , m = ipv6_split ( b )
assert ( m+n <= 7 , "Invalid ipv6 address" )
for i = n+1 , 8-m do
components [ i ] = 0
end
for i = 8-m+1 , 8 do
components [ i ] = end_components [ i-8+m ]
end
else
assert ( n == 8 , "Invalid ipv6 address" )
end
-- Now components is an array of 16bit components
local bits = { }
for i = 1 , 8 do
local u16 = components [ i ]
for j = 1 , 16 do
bits[(i-1)*16+j] = bit.band ( 1 , bit.rshift ( u16 , 16-j ) ) == 1
end
end
return bits
end
function geodb_methods:search_ipv6 ( str )
return select ( 2 , self:search ( ipv6_to_bit_array ( str ) ) )
end
return {
open = open_db ;
}
|
--[[ Copyright (c) 2010 Edvin "Lego3" Linge
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. --]]
local pathsep = package.config:sub(1, 1)
--! Custom Game Window
class "UICustomGame" (UIMenuList)
function UICustomGame:UICustomGame(ui)
-- Supply the required list of items to UIMenuList
local path = debug.getinfo(1, "S").source:sub(2, -57)
path = path .. "Levels" .. pathsep
-- Create the actual list
local items = {}
for file in lfs.dir(path) do
if file:match"%.level$" then
local level_name, level_file, level_intro
for line in io.lines(path .. pathsep .. file) do
-- Get level name and name of the level file to load
if line:sub(1, 1) == "%" then
for text in line:gmatch("\".+\"") do
if line:find("Name") then
level_name = text
elseif line:find("LevelFile") then
level_file = text
elseif line:find("LevelBriefing") then
level_intro = text
end
end
end
end
if level_name and level_file then
items[#items + 1] = {
name = level_name,
tooltip = _S.tooltip.custom_game_window.start_game_with_name:format(level_file, level_intro),
level_file = level_file,
path = path .. file,
intro = level_intro,
}
end
end
end
self:UIMenuList(ui, "menu", _S.custom_game_window.caption, items, 10, 30)
-- Now add the free build button above the list.
if not pcall(function()
local palette = ui.app.gfx:loadPalette("QData", "DrugN01V.pal")
self.panel_sprites = ui.app.gfx:loadSpriteTable("QData", "DrugN02V", true, palette)
self.border_sprites = ui.app.gfx:loadSpriteTable("Bitmap", "aux_ui", true)
end) then
self:close()
return
end
self:addBevelPanel(20, 40, 200, 20, self.col_bg):setLabel(_S.custom_game_window.free_build).lowered = true
local button = self:addPanel(12, 230, 36):makeToggleButton(0, 0, 29, 29, 11, self.buttonFreebuild)
:setTooltip(_S.tooltip.custom_game_window.free_build)
if self.ui.app.config.free_build_mode then
button:toggle()
end
end
-- Overrides the function in the UIMenuList, choosing what should happen when the player
-- clicks a choice in the list.
function UICustomGame:buttonClicked(num)
local app = self.ui.app
local item = self.items[num + self.scrollbar.value - 1]
local level_name = item.name:sub(2, -2)
local level_file = item.level_file:sub(2, -2)
local level_intro = item.intro and item.intro:sub(2, -2)
local filename = item.path
-- First make sure the map file exists.
local _, errors = app:readLevelDataFile(level_file)
if errors then
self.ui:addWindow(UIInformation(self.ui, {errors}))
return
end
app:loadLevel(filename, nil, level_name, level_file, level_intro)
end
function UICustomGame:buttonFreebuild(checked)
self.ui.app.config.free_build_mode = checked
end
|
local lu = require('luaunit')
local File = require('jls.io.File')
local TEST_PATH = 'tests/full'
local TMP_PATH = TEST_PATH..'/tmp'
function Test_exists()
local f
f = File:new('does_not_exist')
lu.assertEquals(f:exists(), false)
f = File:new('.')
lu.assertEquals(f:exists(), true)
end
function Test_isFile()
local f
f = File:new('does_not_exist')
lu.assertEquals(f:isFile(), false)
f = File:new('.')
lu.assertEquals(f:isFile(), false)
f = File:new(TEST_PATH..'/File.lua')
lu.assertEquals(f:isFile(), true)
end
function Test_isDirectory()
local f
f = File:new('does_not_exist')
lu.assertEquals(f:isDirectory(), false)
f = File:new('.')
lu.assertEquals(f:isDirectory(), true)
end
local function getTmpDir()
local tmpDir = File:new(TMP_PATH)
if tmpDir:isDirectory() then
if not tmpDir:deleteRecursive() then
error('Cannot delete tmp dir')
end
end
return tmpDir
end
local function getEmptyTmpDir()
local tmpDir = File:new(TMP_PATH)
if tmpDir:isDirectory() then
if not tmpDir:deleteAll() then
error('Cannot delete tmp dir')
end
else
if not tmpDir:mkdir() then
error('Cannot create tmp dir')
end
end
return tmpDir
end
function Test_mkdirs()
local tmpDir = getEmptyTmpDir()
local f
f = File:new(tmpDir, 'a/b')
lu.assertEquals(f:isDirectory(), false)
lu.assertEquals(f:mkdirs(), true)
lu.assertEquals(f:isDirectory(), true)
end
function Test_z_mkdir()
local f = getTmpDir()
lu.assertEquals(f:isDirectory(), false)
lu.assertEquals(f:mkdir(), true)
lu.assertEquals(f:isDirectory(), true)
lu.assertEquals(f:delete(), true)
end
os.exit(lu.LuaUnit.run())
|
local K, C, L, _ = select(2, ...):unpack()
if C["ActionBar"].Enable ~= true then return end
local _G = _G
local CreateFrame = CreateFrame
-- Setup MultiBarBottomRight as bar #5 by Tukz
local bar = CreateFrame("Frame", "Bar5Holder", UIParent)
if C["ActionBar"].RightBars < 3 then
if C["ActionBar"].SplitBars == true then
bar:SetAllPoints(SplitBarLeft)
else
bar:SetAllPoints(ActionBarAnchor)
end
else
bar:SetAllPoints(RightActionBarAnchor)
end
MultiBarBottomRight:SetParent(bar)
for i = 1, 12 do
local b = _G["MultiBarBottomRightButton"..i]
local b2 = _G["MultiBarBottomRightButton"..i-1]
b:ClearAllPoints()
if C["ActionBar"].SplitBars == true and C["ActionBar"].RightBars < 3 then
if i == 1 then
b:SetPoint("TOPLEFT", SplitBarLeft, "TOPLEFT", 0, 0)
elseif i == 4 then
b:SetPoint("BOTTOMLEFT", SplitBarLeft, "BOTTOMLEFT", 0, 0)
elseif i == 7 then
b:SetPoint("TOPLEFT", SplitBarRight, "TOPLEFT", 0, 0)
elseif i == 10 then
b:SetPoint("BOTTOMLEFT", SplitBarRight, "BOTTOMLEFT", 0, 0)
else
b:SetPoint("LEFT", b2, "RIGHT", C["ActionBar"].Button_Space, 0)
end
else
if i == 1 then
if C["ActionBar"].RightBars < 3 then
b:SetPoint("TOPLEFT", Bar1Holder, 0, 0)
else
b:SetPoint("TOPLEFT", RightActionBarAnchor, "TOPLEFT", 0, 0)
end
else
if C["ActionBar"].RightBars < 3 then
b:SetPoint("LEFT", b2, "RIGHT", C["ActionBar"].Button_Space, 0)
else
b:SetPoint("TOP", b2, "BOTTOM", 0, -C["ActionBar"].Button_Space)
end
end
end
end
-- Hide bar
if C["ActionBar"].RightBars < 3 and C["ActionBar"].BottomBars < 3 then
bar:Hide()
end
|
local ros = require 'ros'
local function printf(...) return print(string.format(...)) end
ros.init('multi_array_demo')
local spinner = ros.AsyncSpinner()
spinner:start()
local nodehandle = ros.NodeHandle()
local publisher = nodehandle:advertise("float_tensor_source", 'std_msgs/Float64MultiArray', 10)
local subscriber = nodehandle:subscribe("float_tensor_source", 'std_msgs/Float64MultiArray', 10)
local specFloat64MultiArray = ros.MsgSpec('std_msgs/Float64MultiArray')
local function tensorToMsg(tensor)
local msg = ros.Message(specFloat64MultiArray)
msg.data = tensor:reshape(tensor:nElement())
for i=1,tensor:dim() do
local dim_desc = ros.Message('std_msgs/MultiArrayDimension')
dim_desc.size = tensor:size(i)
dim_desc.stride = tensor:stride(i)
table.insert(msg.layout.dim, dim_desc)
end
return msg
end
local function msgToTensor(msg)
-- TODO: add support non-continuous tensor (stride handling)
local layout = msg.layout
local dim_sizes = torch.LongStorage(#layout.dim)
for i=1,#layout.dim do
dim_sizes[i] = msg.layout.dim[i].size
end
return msg.data:reshape(dim_sizes)
end
local recv_seq = 1
subscriber:registerCallback(function(msg, header)
--print('Header:')
--print(header)
--print('Message:')
--print(msg)
local t = msgToTensor(msg)
--print("Tensor size:")
--print(t:size())
printf("[recv_seq: %d] Sum of all elements (received): %f", recv_seq, t:sum())
recv_seq = recv_seq + 1
end)
local send_seq = 1
while ros.ok() do
local source_data = torch.rand(4, 27, 13)
local msg = tensorToMsg(source_data)
--print("Sending message:")
--print(msg)
printf("[send_seq: %d] Sum of all elements (sent): %f", send_seq, source_data:sum())
send_seq = send_seq + 1
publisher:publish(msg)
ros.spinOnce()
sys.sleep(0.1)
end
ros.shutdown()
|
--- Telegram inline keyboard markup object.
-- This object represents an [inline keyboard](https://core.telegram.org/bots#inline-keyboards-and-on-the-fly-updating) that appears right next to the message it belongs to.
-- @classmod InlineKeyboardMarkup
local class = require("middleclass")
local InlineKeyboardMarkup = class("telegram.InlineKeyboardMarkup")
--- Create a new InlineKeyboardMarkup object.
-- @tparam {{InlineKeyboardButton}} keyboard Array of keyboard rows, each row is an array of InlineKeyboardButton.
-- @treturn InlineKeyboardMarkup The new created InlineKeyboardMarkup object.
-- @usage local InlineKeyboardMarkup = telegram.structures.InlineKeyboardMarkup(keyboard)
function InlineKeyboardMarkup:initialize(keyboard)
--- Array of button rows, each represented by an Array of `InlineKeyboardButton` objects.
self.inlineKeyboard = keyboard
end
--- Get the object's data in telegram's API format, to be sent using a method.
-- @treturn table The object's data in telegram's API format.
function InlineKeyboardMarkup:getData()
local keyboard = {}
for rid, row in pairs(self.inlineKeyboard) do
local clonedRow = {}
for bid, button in pairs(row) do
clonedRow[bid] = button:getData()
end
keyboard[rid] = clonedRow
end
return {
inline_keyboard = keyboard
}
end
return InlineKeyboardMarkup
|
local skynet = require "skynet"
local logger = require "logger"
local json = require "cjson"
local futil = require "futil"
local function boot()
skynet.newservice("logservice")
skynet.newservice("clustermgr")
local w = skynet.newservice("xwatchdog")
local ok = skynet.call(w, "lua", "start", {
port = 50600,
maxclient = 10000,
nodelay = true
})
logger.info('connector start : %s', ok)
end
skynet.start(function()
local ok, res = xpcall(boot, futil.handle_err)
if not ok then
skynet.error(string.format("boot fail::%s", tostring(res)))
else
skynet.error("boot success !")
end
end)
|
data.raw["logistic-robot"]["logistic-robot"].idle = {
filename = "__Robees__/graphics/bee.png",
priority = "high",
line_length = 16,
width = 41,
height = 42,
frame_count = 1,
shift = {0.015625, -0.09375},
direction_count = 16,
}
data.raw["logistic-robot"]["logistic-robot"].idle_with_cargo = {
filename = "__Robees__/graphics/bee.png",
priority = "high",
line_length = 16,
width = 41,
height = 42,
frame_count = 1,
shift = {0.015625, -0.09375},
direction_count = 16
}
data.raw["logistic-robot"]["logistic-robot"].in_motion = {
filename = "__Robees__/graphics/bee.png",
priority = "high",
line_length = 16,
width = 41,
height = 42,
frame_count = 1,
shift = {0.015625, -0.09375},
direction_count = 16,
y = 42
}
data.raw["logistic-robot"]["logistic-robot"].in_motion_with_cargo = {
filename = "__Robees__/graphics/bee.png",
priority = "high",
line_length = 16,
width = 41,
height = 42,
frame_count = 1,
shift = {0.015625, -0.09375},
direction_count = 16,
y = 42
}
data.raw["logistic-robot"]["logistic-robot"].working_sound = {
sound = {
{ filename = "__Robees__/sounds/bee.ogg", volume = 0.8 }
},
max_sounds_per_type = 3,
audible_distance_modifier = 0.5,
probability = 1 / (1 * 60) -- average pause between the sound is 1 seconds
}
data.raw["construction-robot"]["construction-robot"].idle = {
filename = "__Robees__/graphics/wasp.png",
priority = "high",
line_length = 16,
width = 32,
height = 36,
frame_count = 1,
shift = {0, -0.15625},
direction_count = 16
}
data.raw["construction-robot"]["construction-robot"].in_motion = {
filename = "__Robees__/graphics/wasp.png",
priority = "high",
line_length = 16,
width = 32,
height = 36,
frame_count = 1,
shift = {0, -0.15625},
direction_count = 16,
y = 36
}
data.raw["construction-robot"]["construction-robot"].working =
{
filename = "__Robees__/graphics/wasp_working.png",
priority = "high",
line_length = 2,
width = 28,
height = 36,
frame_count = 2,
shift = {0, -0.15625},
direction_count = 16,
animation_speed = 0.3,
}
data.raw["construction-robot"]["construction-robot"].working_sound = {
sound = {
{ filename = "__Robees__/sounds/bee.ogg", volume = 0.8 }
},
max_sounds_per_type = 3,
audible_distance_modifier = 0.5,
probability = 1 / (1 * 60) -- average pause between the sound is 1 seconds
}
data.raw["construction-robot"]["construction-robot"].sparks =
{
{
filename = "__Robees__/graphics/pollin_01.png",
width = 39,
height = 34,
frame_count = 19,
line_length = 19,
shift = {-0.109375, 0.3125},
tint = { r = 1.0, g = 0.9, b = 0.0, a = 1.0 },
animation_speed = 0.3,
},
{
filename = "__Robees__/graphics/pollin_02.png",
width = 36,
height = 32,
frame_count = 19,
line_length = 19,
shift = {0.03125, 0.125},
tint = { r = 1.0, g = 0.9, b = 0.0, a = 1.0 },
animation_speed = 0.3,
},
{
filename = "__Robees__/graphics/pollin_03.png",
width = 42,
height = 29,
frame_count = 19,
line_length = 19,
shift = {-0.0625, 0.203125},
tint = { r = 1.0, g = 0.9, b = 0.0, a = 1.0 },
animation_speed = 0.3,
},
{
filename = "__Robees__/graphics/pollin_04.png",
width = 40,
height = 35,
frame_count = 19,
line_length = 19,
shift = {-0.0625, 0.234375},
tint = { r = 1.0, g = 0.9, b = 0.0, a = 1.0 },
animation_speed = 0.3,
},
{
filename = "__Robees__/graphics/pollin_05.png",
width = 39,
height = 29,
frame_count = 19,
line_length = 19,
shift = {-0.109375, 0.171875},
tint = { r = 1.0, g = 0.9, b = 0.0, a = 1.0 },
animation_speed = 0.3,
},
{
filename = "__Robees__/graphics/pollin_06.png",
width = 44,
height = 36,
frame_count = 19,
line_length = 19,
shift = {0.03125, 0.3125},
tint = { r = 1.0, g = 0.9, b = 0.0, a = 1.0 },
animation_speed = 0.3,
},
}
data.raw["roboport"]["roboport"].recharging_animation = {
filename = "__Robees__/graphics/yellow_recharging.png",
priority = "high",
width = 37,
height = 35,
frame_count = 16,
scale = 1.5,
animation_speed = 0.5
}
data.raw["roboport-equipment"]["personal-roboport-equipment"].recharging_animation = {
filename = "__Robees__/graphics/yellow_recharging.png",
priority = "high",
width = 37,
height = 35,
frame_count = 16,
scale = 1.5,
animation_speed = 0.5
}
|
RUN_TESTS = false
if RUN_TESTS then
print('Running tests')
end
local utility = nil
local json = nil
LOCALIZATION = nil
STATE = {
PATHS = {
RESOURCES = nil
},
SCROLLBAR = {
START = nil,
MAX_HEIGHT = nil,
HEIGHT = nil,
STEP = nil
},
NUM_SLOTS = 5,
LOGGING = false,
STACK = false,
SCROLL_INDEX = nil,
PROPERTIES = nil,
FILTER_TYPE = nil,
ARGUMENTS = { },
NUM_GAMES_PATTERN = '',
BACK_BUTTON_TITLE = ''
}
local COMPONENTS = {
STATUS = nil,
SETTINGS = nil,
SLOTS = nil
}
local Property
do
local _class_0
local _base_0 = { }
_base_0.__index = _base_0
_class_0 = setmetatable({
__init = function(self, args)
self.title = args.title
self.value = args.value
self.enum = args.enum
self.arguments = args.arguments
self.properties = args.properties
self.action = args.action
self.update = args.update
end,
__base = _base_0,
__name = "Property"
}, {
__index = _base_0,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
Property = _class_0
end
local Slot
do
local _class_0
local _base_0 = {
populate = function(self, property)
self.property = property
return self:update()
end,
update = function(self)
if self.property then
if self.property.update ~= nil then
self.property.value = self.property:update()
end
SKIN:Bang(('[!SetOption "Slot%dTitle" "Text" "%s"]'):format(self.index, utility.replaceUnsupportedChars(self.property.title)))
SKIN:Bang(('[!SetOption "Slot%dValue" "Text" "%s"]'):format(self.index, utility.replaceUnsupportedChars(self.property.value)))
return
end
SKIN:Bang(('[!SetOption "Slot%dTitle" "Text" " "]'):format(self.index))
return SKIN:Bang(('[!SetOption "Slot%dValue" "Text" " "]'):format(self.index))
end,
hasAction = function(self)
return self.property ~= nil
end,
action = function(self)
if self.property.enum ~= nil then
STATE.FILTER_TYPE = self.property.enum
end
if self.property.arguments ~= nil then
for key, value in pairs(self.property.arguments) do
STATE.ARGUMENTS[key] = value
end
end
if self.property.properties ~= nil then
STATE.PROPERTIES = self.property.properties
return true
end
if self.property.action ~= nil then
self.property:action()
return true
end
local filter = STATE.FILTER_TYPE
local stack = tostring(STATE.STACK)
local arguments = json.encode(STATE.ARGUMENTS):gsub('"', '|')
SKIN:Bang(('[!CommandMeasure "Script" "Filter(%d, %s, \'%s\')" "#ROOTCONFIG#"]'):format(filter, stack, arguments))
return false
end
}
_base_0.__index = _base_0
_class_0 = setmetatable({
__init = function(self, index)
self.index = index
end,
__base = _base_0,
__name = "Slot"
}, {
__index = _base_0,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
Slot = _class_0
end
local Game = nil
log = function(...)
if STATE.LOGGING == true then
return print(...)
end
end
Initialize = function()
SKIN:Bang('[!Hide]')
STATE.PATHS.RESOURCES = SKIN:GetVariable('@')
dofile(('%s%s'):format(STATE.PATHS.RESOURCES, 'lib\\rainmeter_helpers.lua'))
COMPONENTS.STATUS = require('shared.status')()
local success, err = pcall(function()
log('Initializing Filter config')
require('shared.enums')
utility = require('shared.utility')
utility.createJSONHelpers()
json = require('lib.json')
COMPONENTS.SETTINGS = require('shared.settings')()
STATE.LOGGING = COMPONENTS.SETTINGS:getLogging()
LOCALIZATION = require('shared.localization')(COMPONENTS.SETTINGS)
STATE.NUM_GAMES_PATTERN = LOCALIZATION:get('game_number_of_games', '%d games')
STATE.BACK_BUTTON_TITLE = LOCALIZATION:get('filter_back_button_title', 'Back')
Game = require('main.game')
STATE.SCROLL_INDEX = 1
do
local _accum_0 = { }
local _len_0 = 1
for i = 1, STATE.NUM_SLOTS do
_accum_0[_len_0] = Slot(i)
_len_0 = _len_0 + 1
end
COMPONENTS.SLOTS = _accum_0
end
local scrollbar = SKIN:GetMeter('Scrollbar')
STATE.SCROLLBAR.START = scrollbar:GetY()
STATE.SCROLLBAR.MAX_HEIGHT = scrollbar:GetH()
SKIN:Bang(('[!SetOption "PageTitle" "Text" "%s"]'):format(LOCALIZATION:get('filter_window_all_title', 'Filter')))
SKIN:Bang('[!CommandMeasure "Script" "HandshakeFilter()" "#ROOTCONFIG#"]')
return COMPONENTS.STATUS:hide()
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
Update = function() end
local sortPropertiesByTitle
sortPropertiesByTitle = function(a, b)
if a.title:lower() < b.title:lower() then
return true
end
return false
end
local createPlatformProperties
createPlatformProperties = function(games, platforms)
local platformProperties = { }
for _index_0 = 1, #platforms do
local platform = platforms[_index_0]
local platformGames = 0
local platformID = platform:getPlatformID()
for _index_1 = 1, #games do
local game = games[_index_1]
if game:getPlatformID() == platformID and game:getPlatformOverride() == nil then
platformGames = platformGames + 1
end
end
if platformGames > 0 then
table.insert(platformProperties, Property({
title = platform:getName(),
value = STATE.NUM_GAMES_PATTERN:format(platformGames),
arguments = {
platformID = platformID
}
}))
end
end
local platformOverrides = { }
for _index_0 = 1, #games do
local game = games[_index_0]
local platformOverride = game:getPlatformOverride()
if platformOverride ~= nil then
if platformOverrides[platformOverride] == nil then
platformOverrides[platformOverride] = {
platformID = game:getPlatformID(),
numGames = 1
}
else
platformOverrides[platformOverride].numGames = platformOverrides[platformOverride].numGames + 1
end
end
end
for platformOverride, params in pairs(platformOverrides) do
if params.numGames > 0 then
table.insert(platformProperties, Property({
title = platformOverride .. '*',
value = STATE.NUM_GAMES_PATTERN:format(params.numGames),
arguments = {
platformID = params.platformID,
platformOverride = platformOverride
}
}))
end
end
table.sort(platformProperties, sortPropertiesByTitle)
return Property({
title = LOCALIZATION:get('filter_from_platform', 'Is on platform'),
value = STATE.NUM_GAMES_PATTERN:format(#games),
enum = ENUMS.FILTER_TYPES.PLATFORM,
properties = platformProperties
})
end
local createTagProperties
createTagProperties = function(games, filterStack)
local tags = { }
local gamesWithTags = 0
for _index_0 = 1, #games do
local game = games[_index_0]
local skinTags = game:getTags()
local platformTags = game:getPlatformTags()
if (#skinTags > 0 or #platformTags > 0) then
gamesWithTags = gamesWithTags + 1
end
local combinedTags = { }
for _index_1 = 1, #skinTags do
local tag = skinTags[_index_1]
combinedTags[tag] = true
end
for _index_1 = 1, #platformTags do
local tag = platformTags[_index_1]
combinedTags[tag] = true
end
for tag, _ in pairs(combinedTags) do
local _continue_0 = false
repeat
local skip = false
for _index_1 = 1, #filterStack do
local f = filterStack[_index_1]
if f.filter == ENUMS.FILTER_TYPES.TAG and f.args.tag == tag then
skip = true
break
end
end
if skip then
_continue_0 = true
break
end
if tags[tag] == nil then
tags[tag] = 0
end
tags[tag] = tags[tag] + 1
_continue_0 = true
until true
if not _continue_0 then
break
end
end
end
if gamesWithTags < 1 then
return nil, gamesWithTags
end
local tagProperties = { }
for tag, numGames in pairs(tags) do
if numGames > 0 then
table.insert(tagProperties, Property({
title = tag,
value = STATE.NUM_GAMES_PATTERN:format(numGames),
arguments = {
tag = tag
}
}))
end
end
if #tagProperties < 1 then
return nil, gamesWithTags
end
table.sort(tagProperties, sortPropertiesByTitle)
return Property({
title = LOCALIZATION:get('filter_has_tag', 'Has tag'),
value = STATE.NUM_GAMES_PATTERN:format(gamesWithTags),
enum = ENUMS.FILTER_TYPES.TAG,
properties = tagProperties
}), gamesWithTags
end
local createHasNoTagsProperty
createHasNoTagsProperty = function(numGames)
return Property({
title = LOCALIZATION:get('filter_has_no_tags', 'Has no tags'),
value = STATE.NUM_GAMES_PATTERN:format(numGames),
enum = ENUMS.FILTER_TYPES.NO_TAGS,
arguments = {
state = true
}
})
end
local createHiddenProperty
createHiddenProperty = function(numGames)
return Property({
title = LOCALIZATION:get('filter_is_hidden', 'Is hidden'),
value = STATE.NUM_GAMES_PATTERN:format(numGames),
enum = ENUMS.FILTER_TYPES.HIDDEN,
arguments = {
state = true
}
})
end
local createRandomProperty
createRandomProperty = function(numGames)
return Property({
title = LOCALIZATION:get('filter_random', 'Random game'),
value = STATE.NUM_GAMES_PATTERN:format(numGames),
enum = ENUMS.FILTER_TYPES.RANDOM_GAME,
arguments = {
state = true
}
})
end
local createNeverPlayedProperty
createNeverPlayedProperty = function(games)
local numGames = 0
for _index_0 = 1, #games do
local game = games[_index_0]
if game:getHoursPlayed() == 0 then
numGames = numGames + 1
end
end
if numGames < 1 then
return nil
end
return Property({
title = LOCALIZATION:get('filter_never_played', 'Has never been played'),
value = STATE.NUM_GAMES_PATTERN:format(numGames),
enum = ENUMS.FILTER_TYPES.NEVER_PLAYED,
arguments = {
state = true
}
})
end
local createHasNotesProperty
createHasNotesProperty = function(games)
local numGames = 0
for _index_0 = 1, #games do
local game = games[_index_0]
if game:getNotes() ~= nil then
numGames = numGames + 1
end
end
if numGames < 1 then
return nil
end
return Property({
title = LOCALIZATION:get('filter_has_notes', 'Has notes'),
value = STATE.NUM_GAMES_PATTERN:format(numGames),
enum = ENUMS.FILTER_TYPES.HAS_NOTES,
arguments = {
state = true
}
})
end
local createUninstalledProperty
createUninstalledProperty = function(numGames)
return Property({
title = LOCALIZATION:get('filter_is_uninstalled', 'Is not installed'),
value = STATE.NUM_GAMES_PATTERN:format(numGames),
enum = ENUMS.FILTER_TYPES.UNINSTALLED,
arguments = {
state = true
}
})
end
local createClearProperty
createClearProperty = function()
return Property({
title = LOCALIZATION:get('filter_clear_filters', 'Clear filters'),
value = ' ',
enum = ENUMS.FILTER_TYPES.NONE
})
end
local createCancelProperty
createCancelProperty = function()
return Property({
title = LOCALIZATION:get('button_label_cancel', 'Cancel'),
value = ' ',
action = function(self)
return SKIN:Bang('[!DeactivateConfig]')
end
})
end
local createProperties
createProperties = function(games, hiddenGames, uninstalledGames, platforms, stack, filterStack)
local properties = { }
if #hiddenGames > 0 then
table.insert(properties, createHiddenProperty(#hiddenGames))
end
if #uninstalledGames > 0 then
table.insert(properties, createUninstalledProperty(#uninstalledGames))
end
if #games > 0 then
local skipPlatforms = false
local skipTags = false
local skipNoTags = false
local skipRandom = false
local skipNeverPlayed = false
local skipHasNotes = false
for _index_0 = 1, #filterStack do
local f = filterStack[_index_0]
local _exp_0 = f.filter
if ENUMS.FILTER_TYPES.PLATFORM == _exp_0 then
skipPlatforms = true
elseif ENUMS.FILTER_TYPES.NO_TAGS == _exp_0 then
skipTags = true
elseif ENUMS.FILTER_TYPES.TAG == _exp_0 then
skipNoTags = true
elseif ENUMS.FILTER_TYPES.RANDOM_GAME == _exp_0 then
skipRandom = true
elseif ENUMS.FILTER_TYPES.NEVER_PLAYED == _exp_0 then
skipNeverPlayed = true
elseif ENUMS.FILTER_TYPES.HAS_NOTES == _exp_0 then
skipHasNotes = true
end
end
if not (skipPlatforms) then
local platformsProperty = createPlatformProperties(games, platforms)
if platformsProperty then
table.insert(platformsProperty.properties, Property({
title = STATE.BACK_BUTTON_TITLE,
value = ' ',
properties = properties
}))
table.insert(properties, platformsProperty)
end
end
local gamesWithTags = 0
if not (skipTags) then
local tagsProperty
tagsProperty, gamesWithTags = createTagProperties(games, filterStack)
if tagsProperty then
table.insert(tagsProperty.properties, Property({
title = STATE.BACK_BUTTON_TITLE,
value = ' ',
properties = properties
}))
table.insert(properties, tagsProperty)
end
end
if not (skipNoTags) then
local numGamesWithoutTags = #games - gamesWithTags
if numGamesWithoutTags > 0 then
table.insert(properties, createHasNoTagsProperty(numGamesWithoutTags))
end
end
if not skipRandom and #games > 1 then
table.insert(properties, createRandomProperty(#games))
end
if not (skipNeverPlayed) then
local neverPlayedProperty = createNeverPlayedProperty(games)
if neverPlayedProperty then
table.insert(properties, neverPlayedProperty)
end
end
if not (skipHasNotes) then
local hasNotesProperty = createHasNotesProperty(games)
if hasNotesProperty then
table.insert(properties, hasNotesProperty)
end
end
end
table.sort(properties, sortPropertiesByTitle)
if not (stack) then
table.insert(properties, createClearProperty())
end
table.insert(properties, createCancelProperty())
return properties
end
local updateScrollbar
updateScrollbar = function()
STATE.MAX_SCROLL_INDEX = #STATE.PROPERTIES - STATE.NUM_SLOTS + 1
if #STATE.PROPERTIES > STATE.NUM_SLOTS then
STATE.SCROLLBAR.HEIGHT = math.round(STATE.SCROLLBAR.MAX_HEIGHT / (#STATE.PROPERTIES - STATE.NUM_SLOTS + 1))
STATE.SCROLLBAR.STEP = (STATE.SCROLLBAR.MAX_HEIGHT - STATE.SCROLLBAR.HEIGHT) / (#STATE.PROPERTIES - STATE.NUM_SLOTS)
else
STATE.SCROLLBAR.HEIGHT = STATE.SCROLLBAR.MAX_HEIGHT
STATE.SCROLLBAR.STEP = 0
end
SKIN:Bang(('[!SetOption "Scrollbar" "H" "%d"]'):format(STATE.SCROLLBAR.HEIGHT))
local y = STATE.SCROLLBAR.START + (STATE.SCROLL_INDEX - 1) * STATE.SCROLLBAR.STEP
return SKIN:Bang(('[!SetOption "Scrollbar" "Y" "%d"]'):format(math.round(y)))
end
local updateSlots
updateSlots = function()
for i, slot in ipairs(COMPONENTS.SLOTS) do
slot:populate(STATE.PROPERTIES[i + STATE.SCROLL_INDEX - 1])
if i == STATE.HIGHLIGHTED_SLOT_INDEX then
MouseOver(i)
end
end
end
Handshake = function(stack, appliedFilters)
local success, err = pcall(function()
log('Accepting Filter handshake', stack)
STATE.STACK = stack
local platforms
do
local _accum_0 = { }
local _len_0 = 1
local _list_0 = require('main.platforms')
for _index_0 = 1, #_list_0 do
local Platform = _list_0[_index_0]
_accum_0[_len_0] = Platform(COMPONENTS.SETTINGS)
_len_0 = _len_0 + 1
end
platforms = _accum_0
end
local games = nil
local hiddenGames = { }
local uninstalledGames = { }
appliedFilters = appliedFilters:gsub('|', '"')
local filterStack = json.decode(appliedFilters)
if stack then
SKIN:Bang(('[!SetOption "PageTitle" "Text" "%s"]'):format(LOCALIZATION:get('filter_window_current_title', 'Filter (current games)')))
local library = require('shared.library')(COMPONENTS.SETTINGS, false)
local platformsEnabledStatus = { }
local temp = { }
for _index_0 = 1, #platforms do
local platform = platforms[_index_0]
local enabled = platform:isEnabled()
platformsEnabledStatus[platform:getPlatformID()] = enabled
if enabled then
table.insert(temp, platform)
end
end
platforms = temp
temp = nil
library:finalize(platformsEnabledStatus)
games = library:get()
local showHiddenGames = false
local showUninstalledGames = false
for _index_0 = 1, #filterStack do
local f = filterStack[_index_0]
if f.filter == ENUMS.FILTER_TYPES.HIDDEN and f.args.state == true then
showHiddenGames = true
elseif f.filter == ENUMS.FILTER_TYPES.UNINSTALLED and f.args.state == true then
showUninstalledGames = true
end
f.args.games = games
library:filter(f.filter, f.args)
games = library:get()
end
for i = #games, 1, -1 do
if not games[i]:isVisible() and not showHiddenGames then
table.insert(hiddenGames, table.remove(games, i))
elseif not games[i]:isInstalled() and not (showUninstalledGames or showHiddenGames) then
table.insert(uninstalledGames, table.remove(games, i))
end
end
else
do
local _accum_0 = { }
local _len_0 = 1
for _index_0 = 1, #platforms do
local platform = platforms[_index_0]
if platform:isEnabled() then
_accum_0[_len_0] = platform
_len_0 = _len_0 + 1
end
end
platforms = _accum_0
end
games = io.readJSON('games.json')
do
local _accum_0 = { }
local _len_0 = 1
local _list_0 = games.games
for _index_0 = 1, #_list_0 do
local args = _list_0[_index_0]
_accum_0[_len_0] = Game(args)
_len_0 = _len_0 + 1
end
games = _accum_0
end
for i = #games, 1, -1 do
if not games[i]:isVisible() then
table.insert(hiddenGames, table.remove(games, i))
elseif not games[i]:isInstalled() then
table.insert(uninstalledGames, table.remove(games, i))
end
end
end
STATE.PROPERTIES = createProperties(games, hiddenGames, uninstalledGames, platforms, stack, filterStack)
updateScrollbar()
updateSlots()
if COMPONENTS.SETTINGS:getCenterOnMonitor() then
local meter = SKIN:GetMeter('WindowShadow')
local skinWidth = meter:GetW()
local skinHeight = meter:GetH()
local mainConfig = utility.getConfig(SKIN:GetVariable('ROOTCONFIG'))
local monitorIndex = nil
if mainConfig ~= nil then
monitorIndex = utility.getConfigMonitor(mainConfig) or 1
else
monitorIndex = 1
end
local x, y = utility.centerOnMonitor(skinWidth, skinHeight, monitorIndex)
SKIN:Bang(('[!Move "%d" "%d"]'):format(x, y))
end
return SKIN:Bang('[!Show]')
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
Scroll = function(direction)
local success, err = pcall(function()
if not (COMPONENTS.SLOTS) then
return
end
local index = STATE.SCROLL_INDEX + direction
if index < 1 then
return
elseif index > STATE.MAX_SCROLL_INDEX then
return
end
STATE.SCROLL_INDEX = index
updateScrollbar()
return updateSlots()
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
MouseOver = function(index)
local success, err = pcall(function()
if index < 1 then
return
end
if not (COMPONENTS.SLOTS) then
return
end
if not (COMPONENTS.SLOTS[index]:hasAction()) then
return
end
STATE.HIGHLIGHTED_SLOT_INDEX = index
return SKIN:Bang(('[!SetOption "Slot%dButton" "SolidColor" "#ButtonHighlightedColor#"]'):format(index))
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
MouseLeave = function(index)
local success, err = pcall(function()
if index < 1 then
return
end
if not (COMPONENTS.SLOTS) then
return
end
if index == 0 then
STATE.HIGHLIGHTED_SLOT_INDEX = 0
for i = index, STATE.NUM_SLOTS do
SKIN:Bang(('[!SetOption "Slot%dButton" "SolidColor" "#ButtonBaseColor#"]'):format(i))
end
else
return SKIN:Bang(('[!SetOption "Slot%dButton" "SolidColor" "#ButtonBaseColor#"]'):format(index))
end
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
MouseLeftPress = function(index)
local success, err = pcall(function()
if index < 1 then
return
end
if not (COMPONENTS.SLOTS) then
return
end
if not (COMPONENTS.SLOTS[index]:hasAction()) then
return
end
return SKIN:Bang(('[!SetOption "Slot%dButton" "SolidColor" "#ButtonPressedColor#"]'):format(index))
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
ButtonAction = function(index)
local success, err = pcall(function()
if index < 1 then
return
end
if not (COMPONENTS.SLOTS) then
return
end
if not (COMPONENTS.SLOTS[index]:hasAction()) then
return
end
SKIN:Bang(('[!SetOption "Slot%dButton" "SolidColor" "#ButtonHighlightedColor#"]'):format(index))
if COMPONENTS.SLOTS[index]:action() then
STATE.SCROLL_INDEX = 1
updateScrollbar()
return updateSlots()
else
return SKIN:Bang('[!DeactivateConfig]')
end
end)
if not (success) then
return COMPONENTS.STATUS:show(err, true)
end
end
|
local ShowFlashyCombo = ThemePrefs.Get("FlashyCombo")
return Def.ActorFrame {
LoadActor("explosion") .. {
InitCommand=cmd(diffusealpha,0;blend,'BlendMode_Add';hide_if,not ShowFlashyCombo);
MilestoneCommand=cmd(rotationz,0;zoom,0.5;diffusealpha,0.6;linear,0.3;zoom,0.75;diffusealpha,0);
};
};
|
---LuaSocket API documentation
---LuaSocket <https://github.com/diegonehab/luasocket> is a Lua extension library that provides
---support for the TCP and UDP transport layers. Defold provides the "socket" namespace in
---runtime, which contain the core C functionality. Additional LuaSocket support modules for
---SMTP, HTTP, FTP etc are not part of the core included, but can be easily added to a project
---and used.
---Note the included helper module "socket.lua" in "builtins/scripts/socket.lua". Require this
---module to add some additional functions and shortcuts to the namespace:
---require "builtins.scripts.socket"
---
---
---
---LuaSocket is Copyright © 2004-2007 Diego Nehab. All rights reserved.
---LuaSocket is free software, released under the MIT license (same license as the Lua core).
---@class socket
socket = {}
---Closes the TCP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the close method) are allowed on a closed socket.
--- It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.
function client:close() end
---Check the read buffer status.
--- This is an internal method, any use is unlikely to be portable.
---@return boolean true if there is any data in the read buffer, false otherwise.
function client:dirty() end
---Returns the underlying socket descriptor or handle associated to the object.
--- This is an internal method, any use is unlikely to be portable.
---@return number the descriptor or handle. In case the object has been closed, the return will be -1.
function client:getfd() end
---Gets options for the TCP object. See client:setoption <> for description of the option names and values.
---@param option string the name of the option to get:
---@return any the option value, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function client:getoption(option) end
---Returns information about the remote side of a connected client object.
--- It makes no sense to call this method on server objects.
---@return string a string with the IP address of the peer, the port number that peer is using for the connection, and the family ("inet" or "inet6"). In case of error, the method returns nil.
function client:getpeername() end
---Returns the local address information associated to the object.
---@return string a string with local IP address, the local port number, and the family ("inet" or "inet6"). In case of error, the method returns nil.
function client:getsockname() end
---Returns accounting information on the socket, useful for throttling of bandwidth.
---@return string a string with the number of bytes received, the number of bytes sent, and the age of the socket object in seconds.
function client:getstats() end
---Reads data from a client object, according to the specified read pattern. Patterns follow the Lua file I/O format, and the difference in performance between patterns is negligible.
---@param pattern string|number the read pattern that can be any of the following:
---@param prefix string an optional string to be concatenated to the beginning of any received data before return.
---@return string the received pattern, or nil in case of error.
---@return string the error message, or nil if no error occurred. The error message can be the string "closed" in case the connection was closed before the transmission was completed or the string "timeout" in case there was a timeout during the operation.
---@return string a (possibly empty) string containing the partial that was received, or nil if no error occurred.
function client:receive(pattern, prefix) end
---Sends data through client object.
---The optional arguments i and j work exactly like the standard string.sub <> Lua function to allow the selection of a substring to be sent.
--- Output is not buffered. For small strings, it is always better to concatenate them in Lua (with the .. operator) and send the result in one call instead of calling the method several times.
---@param data string the string to be sent.
---@param i number optional starting index of the string.
---@param j number optional end index of string.
---@return number] the index of the last byte within [i, j that has been sent, or nil in case of error. Notice that, if i is 1 or absent, this is effectively the total number of bytes sent.
---@return string the error message, or nil if no error occurred. The error message can be "closed" in case the connection was closed before the transmission was completed or the string "timeout" in case there was a timeout during the operation.
---@return number] in case of error, the index of the last byte within [i, j that has been sent. You might want to try again from the byte following that. nil if no error occurred.
function client:send(data, i, j) end
---Sets the underling socket descriptor or handle associated to the object. The current one is simply replaced, not closed, and no other change to the object state is made
---@param handle number the descriptor or handle to set.
function client:setfd(handle) end
---Sets options for the TCP object. Options are only needed by low-level or time-critical applications. You should only modify an option if you are sure you need it.
---@param option string the name of the option to set. The value is provided in the value parameter:
---@param value any the value to set for the specified option.
---@return number the value 1, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function client:setoption(option, value) end
---Resets accounting information on the socket, useful for throttling of bandwidth.
---@param received number the new number of bytes received.
---@param sent number the new number of bytes sent.
---@param age number the new age in seconds.
---@return number the value 1 in case of success, or nil in case of error.
function client:setstats(received, sent, age) end
---Changes the timeout values for the object. By default, all I/O operations are blocking. That is, any call to the methods send, receive, and accept will block indefinitely, until the operation completes. The settimeout method defines a limit on the amount of time the I/O methods can block. When a timeout is set and the specified amount of time has elapsed, the affected methods give up and fail with an error code.
---There are two timeout modes and both can be used together for fine tuning.
--- Although timeout values have millisecond precision in LuaSocket, large blocks can cause I/O functions not to respect timeout values due to the time the library takes to transfer blocks to and from the OS and to and from the Lua interpreter. Also, function that accept host names and perform automatic name resolution might be blocked by the resolver for longer than the specified timeout value.
---@param value number the amount of time to wait, in seconds. The nil timeout value allows operations to block indefinitely. Negative timeout values have the same effect.
---@param mode string optional timeout mode to set:
function client:settimeout(value, mode) end
---Shuts down part of a full-duplex connection.
---@param mode string which way of the connection should be shut down:
---@return number the value 1.
function client:shutdown(mode) end
---Closes a UDP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the close method) are allowed on a closed socket.
--- It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.
function connected:close() end
---Gets an option value from the UDP object. See connected:setoption <> for description of the option names and values.
---@param option string the name of the option to get:
---@return any the option value, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function connected:getoption(option) end
---Retrieves information about the peer associated with a connected UDP object.
--- It makes no sense to call this method on unconnected objects.
---@return string a string with the IP address of the peer, the port number that peer is using for the connection, and the family ("inet" or "inet6"). In case of error, the method returns nil.
function connected:getpeername() end
---Returns the local address information associated to the object.
--- UDP sockets are not bound to any address until the setsockname or the sendto method is called for the first time (in which case it is bound to an ephemeral port and the wild-card address).
---@return string a string with local IP address, a number with the local port, and the family ("inet" or "inet6"). In case of error, the method returns nil.
function connected:getsockname() end
---Receives a datagram from the UDP object. If the UDP object is connected, only datagrams coming from the peer are accepted. Otherwise, the returned datagram can come from any host.
---@param size number optional maximum size of the datagram to be retrieved. If there are more than size bytes available in the datagram, the excess bytes are discarded. If there are less then size bytes available in the current datagram, the available bytes are returned. If size is omitted, the maximum datagram size is used (which is currently limited by the implementation to 8192 bytes).
---@return string the received datagram, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function connected:receive(size) end
---Sends a datagram to the UDP peer of a connected object.
--- In UDP, the send method never blocks and the only way it can fail is if the underlying transport layer refuses to send a message to the specified address (i.e. no interface accepts the address).
---@param datagram string a string with the datagram contents. The maximum datagram size for UDP is 64K minus IP layer overhead. However datagrams larger than the link layer packet size will be fragmented, which may deteriorate performance and/or reliability.
---@return number the value 1 on success, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function connected:send(datagram) end
---Sets options for the UDP object. Options are only needed by low-level or time-critical applications. You should only modify an option if you are sure you need it.
---@param option string the name of the option to set. The value is provided in the value parameter:
---@param value any the value to set for the specified option.
---@return number the value 1, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function connected:setoption(option, value) end
---Changes the peer of a UDP object. This method turns an unconnected UDP object into a connected UDP object or vice versa.
---For connected objects, outgoing datagrams will be sent to the specified peer, and datagrams received from other peers will be discarded by the OS. Connected UDP objects must use the send and receive methods instead of sendto and receivefrom.
--- Since the address of the peer does not have to be passed to and from the OS, the use of connected UDP objects is recommended when the same peer is used for several transmissions and can result in up to 30% performance gains.
---@param _ string if address is "*" and the object is connected, the peer association is removed and the object becomes an unconnected object again.
---@return number the value 1 on success, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function connected:setpeername(_) end
---Changes the timeout values for the object. By default, the receive and receivefrom operations are blocking. That is, any call to the methods will block indefinitely, until data arrives. The settimeout function defines a limit on the amount of time the functions can block. When a timeout is set and the specified amount of time has elapsed, the affected methods give up and fail with an error code.
--- In UDP, the send and sendto methods never block (the datagram is just passed to the OS and the call returns immediately). Therefore, the settimeout method has no effect on them.
---@param value number the amount of time to wait, in seconds. The nil timeout value allows operations to block indefinitely. Negative timeout values have the same effect.
function connected:settimeout(value) end
---Binds a master object to address and port on the local host.
---@param address string an IP address or a host name. If address is "*", the system binds to all local interfaces using the INADDR_ANY constant.
---@param port number the port to commect to, in the range [0..64K). If port is 0, the system automatically chooses an ephemeral port.
---@return number the value 1, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function master:bind(address, port) end
---Closes the TCP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the close method) are allowed on a closed socket.
--- It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.
function master:close() end
---Attempts to connect a master object to a remote host, transforming it into a client object. Client objects support methods send, receive, getsockname, getpeername, settimeout, and close.
---Note that the function socket.connect is available and is a shortcut for the creation of client sockets.
---@param address string an IP address or a host name. If address is "*", the system binds to all local interfaces using the INADDR_ANY constant.
---@param port number the port to commect to, in the range [0..64K). If port is 0, the system automatically chooses an ephemeral port.
---@return number the value 1, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function master:connect(address, port) end
---Check the read buffer status.
--- This is an internal method, any use is unlikely to be portable.
---@return boolean true if there is any data in the read buffer, false otherwise.
function master:dirty() end
---Returns the underlying socket descriptor or handle associated to the object.
--- This is an internal method, any use is unlikely to be portable.
---@return number the descriptor or handle. In case the object has been closed, the return will be -1.
function master:getfd() end
---Returns the local address information associated to the object.
---@return string a string with local IP address, the local port number, and the family ("inet" or "inet6"). In case of error, the method returns nil.
function master:getsockname() end
---Returns accounting information on the socket, useful for throttling of bandwidth.
---@return string a string with the number of bytes received, the number of bytes sent, and the age of the socket object in seconds.
function master:getstats() end
---Specifies the socket is willing to receive connections, transforming the object into a server object. Server objects support the accept, getsockname, setoption, settimeout, and close methods.
---@param backlog number the number of client connections that can be queued waiting for service. If the queue is full and another client attempts connection, the connection is refused.
---@return number the value 1, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function master:listen(backlog) end
---Sets the underling socket descriptor or handle associated to the object. The current one is simply replaced, not closed, and no other change to the object state is made
---@param handle number the descriptor or handle to set.
function master:setfd(handle) end
---Resets accounting information on the socket, useful for throttling of bandwidth.
---@param received number the new number of bytes received.
---@param sent number the new number of bytes sent.
---@param age number the new age in seconds.
---@return number the value 1 in case of success, or nil in case of error.
function master:setstats(received, sent, age) end
---Changes the timeout values for the object. By default, all I/O operations are blocking. That is, any call to the methods send, receive, and accept will block indefinitely, until the operation completes. The settimeout method defines a limit on the amount of time the I/O methods can block. When a timeout is set and the specified amount of time has elapsed, the affected methods give up and fail with an error code.
---There are two timeout modes and both can be used together for fine tuning.
--- Although timeout values have millisecond precision in LuaSocket, large blocks can cause I/O functions not to respect timeout values due to the time the library takes to transfer blocks to and from the OS and to and from the Lua interpreter. Also, function that accept host names and perform automatic name resolution might be blocked by the resolver for longer than the specified timeout value.
---@param value number the amount of time to wait, in seconds. The nil timeout value allows operations to block indefinitely. Negative timeout values have the same effect.
---@param mode string optional timeout mode to set:
function master:settimeout(value, mode) end
---Waits for a remote connection on the server object and returns a client object representing that connection.
--- Calling socket.select with a server object in the recvt parameter before a call to accept does not guarantee accept will return immediately. Use the settimeout method or accept might block until another client shows up.
---@return client if a connection is successfully initiated, a client object is returned, or nil in case of error.
---@return string the error message, or nil if no error occurred. The error is "timeout" if a timeout condition is met.
function server:accept() end
---Closes the TCP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the close method) are allowed on a closed socket.
--- It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.
function server:close() end
---Check the read buffer status.
--- This is an internal method, any use is unlikely to be portable.
---@return boolean true if there is any data in the read buffer, false otherwise.
function server:dirty() end
---Returns the underlying socket descriptor or handle associated to the object.
--- This is an internal method, any use is unlikely to be portable.
---@return number the descriptor or handle. In case the object has been closed, the return will be -1.
function server:getfd() end
---Gets options for the TCP object. See server:setoption <> for description of the option names and values.
---@param option string the name of the option to get:
---@return any the option value, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function server:getoption(option) end
---Returns the local address information associated to the object.
---@return string a string with local IP address, the local port number, and the family ("inet" or "inet6"). In case of error, the method returns nil.
function server:getsockname() end
---Returns accounting information on the socket, useful for throttling of bandwidth.
---@return string a string with the number of bytes received, the number of bytes sent, and the age of the socket object in seconds.
function server:getstats() end
---Sets the underling socket descriptor or handle associated to the object. The current one is simply replaced, not closed, and no other change to the object state is made
---@param handle number the descriptor or handle to set.
function server:setfd(handle) end
---Sets options for the TCP object. Options are only needed by low-level or time-critical applications. You should only modify an option if you are sure you need it.
---@param option string the name of the option to set. The value is provided in the value parameter:
---@param value any the value to set for the specified option.
---@return number the value 1, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function server:setoption(option, value) end
---Resets accounting information on the socket, useful for throttling of bandwidth.
---@param received number the new number of bytes received.
---@param sent number the new number of bytes sent.
---@param age number the new age in seconds.
---@return number the value 1 in case of success, or nil in case of error.
function server:setstats(received, sent, age) end
---Changes the timeout values for the object. By default, all I/O operations are blocking. That is, any call to the methods send, receive, and accept will block indefinitely, until the operation completes. The settimeout method defines a limit on the amount of time the I/O methods can block. When a timeout is set and the specified amount of time has elapsed, the affected methods give up and fail with an error code.
---There are two timeout modes and both can be used together for fine tuning.
--- Although timeout values have millisecond precision in LuaSocket, large blocks can cause I/O functions not to respect timeout values due to the time the library takes to transfer blocks to and from the OS and to and from the Lua interpreter. Also, function that accept host names and perform automatic name resolution might be blocked by the resolver for longer than the specified timeout value.
---@param value number the amount of time to wait, in seconds. The nil timeout value allows operations to block indefinitely. Negative timeout values have the same effect.
---@param mode string optional timeout mode to set:
function server:settimeout(value, mode) end
---max numbers of sockets the select function can handle
socket._SETSIZE = nil
---the current LuaSocket version
socket._VERSION = nil
---This function is a shortcut that creates and returns a TCP client object connected to a remote
---address at a given port. Optionally, the user can also specify the local address and port to
---bind (locaddr and locport), or restrict the socket family to "inet" or "inet6".
---Without specifying family to connect, whether a tcp or tcp6 connection is created depends on
---your system configuration.
---@param address string the address to connect to.
---@param port number the port to connect to.
---@param locaddr string optional local address to bind to.
---@param locport number optional local port to bind to.
---@param family string optional socket family to use, "inet" or "inet6".
---@return client a new IPv6 TCP client object, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function socket.connect(address, port, locaddr, locport, family) end
---This function converts a host name to IPv4 or IPv6 address.
---The supplied address can be an IPv4 or IPv6 address or host name.
---The function returns a table with all information returned by the resolver:
---{
--- [1] = {
--- family = family-name-1,
--- addr = address-1
--- },
--- ...
--- [n] = {
--- family = family-name-n,
--- addr = address-n
--- }
---}
---
---
---
---Here, family contains the string "inet" for IPv4 addresses, and "inet6" for IPv6 addresses.
---In case of error, the function returns nil followed by an error message.
---@param address string a hostname or an IPv4 or IPv6 address.
---@return table a table with all information returned by the resolver, or if an error occurs, nil.
---@return string the error message, or nil if no error occurred.
function socket.dns.getaddrinfo(address) end
---Returns the standard host name for the machine as a string.
---@return string the host name for the machine.
function socket.dns.gethostname() end
---This function converts an address to host name.
---The supplied address can be an IPv4 or IPv6 address or host name.
---The function returns a table with all information returned by the resolver:
---{
--- [1] = host-name-1,
--- ...
--- [n] = host-name-n,
---}
---@param address string a hostname or an IPv4 or IPv6 address.
---@return table a table with all information returned by the resolver, or if an error occurs, nil.
---@return string the error message, or nil if no error occurred.
function socket.dns.getnameinfo(address) end
---This function converts from an IPv4 address to host name.
---The address can be an IPv4 address or a host name.
---@param address string an IPv4 address or host name.
---@return string the canonic host name of the given address, or nil in case of an error.
---@return table|string a table with all information returned by the resolver, or if an error occurs, the error message string.
function socket.dns.tohostname(address) end
---This function converts a host name to IPv4 address.
---The address can be an IP address or a host name.
---@param address string a hostname or an IP address.
---@return string the first IP address found for the hostname, or nil in case of an error.
---@return table|string a table with all information returned by the resolver, or if an error occurs, the error message string.
function socket.dns.toip(address) end
---Returns the time in seconds, relative to the system epoch (Unix epoch time since January 1, 1970 (UTC) or Windows file time since January 1, 1601 (UTC)).
---You should use the values returned by this function for relative measurements only.
---@return number the number of seconds elapsed.
function socket.gettime() end
---This function creates and returns a clean try function that allows for cleanup before the exception is raised.
---The finalizer function will be called in protected mode (see protect <>).
---@param finalizer function() a function that will be called before the try throws the exception.
---@return function the customized try function.
function socket.newtry(finalizer) end
---Converts a function that throws exceptions into a safe function. This function only catches exceptions thrown by try functions. It does not catch normal Lua errors.
--- Beware that if your function performs some illegal operation that raises an error, the protected function will catch the error and return it as a string. This is because try functions uses errors as the mechanism to throw exceptions.
---@param func function a function that calls a try function (or assert, or error) to throw exceptions.
---@return function(function()) an equivalent function that instead of throwing exceptions, returns nil followed by an error message.
function socket.protect(func) end
---The function returns a list with the sockets ready for reading, a list with the sockets ready for writing and an error message. The error message is "timeout" if a timeout condition was met and nil otherwise. The returned tables are doubly keyed both by integers and also by the sockets themselves, to simplify the test if a specific socket has changed status.
---Recvt and sendt parameters can be empty tables or nil. Non-socket values (or values with non-numeric indices) in these arrays will be silently ignored.
---The returned tables are doubly keyed both by integers and also by the sockets themselves, to simplify the test if a specific socket has changed status.
--- This function can monitor a limited number of sockets, as defined by the constant socket._SETSIZE. This number may be as high as 1024 or as low as 64 by default, depending on the system. It is usually possible to change this at compile time. Invoking select with a larger number of sockets will raise an error.
--- A known bug in WinSock causes select to fail on non-blocking TCP sockets. The function may return a socket as writable even though the socket is not ready for sending.
--- Calling select with a server socket in the receive parameter before a call to accept does not guarantee accept will return immediately. Use the settimeout method or accept might block forever.
--- If you close a socket and pass it to select, it will be ignored.
---(Using select with non-socket objects: Any object that implements getfd and dirty can be used with select, allowing objects from other libraries to be used within a socket.select driven loop.)
---@param recvt table array with the sockets to test for characters available for reading.
---@param sendt table array with sockets that are watched to see if it is OK to immediately write on them.
---@param timeout number the maximum amount of time (in seconds) to wait for a change in status. Nil, negative or omitted timeout value allows the function to block indefinitely.
---@return table a list with the sockets ready for reading.
---@return table a list with the sockets ready for writing.
---@return string an error message. "timeout" if a timeout condition was met, otherwise nil.
function socket.select(recvt, sendt, timeout) end
---This function drops a number of arguments and returns the remaining.
---It is useful to avoid creation of dummy variables:
---D is the number of arguments to drop. Ret1 to retN are the arguments.
---The function returns retD+1 to retN.
---@param d number the number of arguments to drop.
---@param ret1 any argument 1.
---@param ret2 any argument 2.
---@param retN any argument N.
---@return any argument D+1.
---@return any argument D+2.
---@return any argument N.
function socket.skip(d, ret1, ret2, retN) end
---Freezes the program execution during a given amount of time.
---@param time number the number of seconds to sleep for.
function socket.sleep(time) end
---Creates and returns an IPv4 TCP master object. A master object can be transformed into a server object with the method listen (after a call to bind) or into a client object with the method connect. The only other method supported by a master object is the close method.
---@return master a new IPv4 TCP master object, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function socket.tcp() end
---Creates and returns an IPv6 TCP master object. A master object can be transformed into a server object with the method listen (after a call to bind) or into a client object with the method connect. The only other method supported by a master object is the close method.
---Note: The TCP object returned will have the option "ipv6-v6only" set to true.
---@return master a new IPv6 TCP master object, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function socket.tcp6() end
---Creates and returns an unconnected IPv4 UDP object. Unconnected objects support the sendto, receive, receivefrom, getoption, getsockname, setoption, settimeout, setpeername, setsockname, and close methods. The setpeername method is used to connect the object.
---@return unconnected a new unconnected IPv4 UDP object, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function socket.udp() end
---Creates and returns an unconnected IPv6 UDP object. Unconnected objects support the sendto, receive, receivefrom, getoption, getsockname, setoption, settimeout, setpeername, setsockname, and close methods. The setpeername method is used to connect the object.
---Note: The UDP object returned will have the option "ipv6-v6only" set to true.
---@return unconnected a new unconnected IPv6 UDP object, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function socket.udp6() end
---Closes a UDP object. The internal socket used by the object is closed and the local address to which the object was bound is made available to other applications. No further operations (except for further calls to the close method) are allowed on a closed socket.
--- It is important to close all used sockets once they are not needed, since, in many systems, each socket uses a file descriptor, which are limited system resources. Garbage-collected objects are automatically closed before destruction, though.
function unconnected:close() end
---Gets an option value from the UDP object. See unconnected:setoption <> for description of the option names and values.
---@param option string the name of the option to get:
---@return any the option value, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function unconnected:getoption(option) end
---Returns the local address information associated to the object.
--- UDP sockets are not bound to any address until the setsockname or the sendto method is called for the first time (in which case it is bound to an ephemeral port and the wild-card address).
---@return string a string with local IP address, a number with the local port, and the family ("inet" or "inet6"). In case of error, the method returns nil.
function unconnected:getsockname() end
---Receives a datagram from the UDP object. If the UDP object is connected, only datagrams coming from the peer are accepted. Otherwise, the returned datagram can come from any host.
---@param size number optional maximum size of the datagram to be retrieved. If there are more than size bytes available in the datagram, the excess bytes are discarded. If there are less then size bytes available in the current datagram, the available bytes are returned. If size is omitted, the maximum datagram size is used (which is currently limited by the implementation to 8192 bytes).
---@return string the received datagram, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function unconnected:receive(size) end
---Works exactly as the receive method, except it returns the IP address and port as extra return values (and is therefore slightly less efficient).
---@param size number optional maximum size of the datagram to be retrieved.
---@return string the received datagram, or nil in case of error.
---@return string the IP address, or the error message in case of error.
---@return number the port number, or nil in case of error.
function unconnected:receivefrom(size) end
---Sends a datagram to the specified IP address and port number.
--- In UDP, the send method never blocks and the only way it can fail is if the underlying transport layer refuses to send a message to the specified address (i.e. no interface accepts the address).
---@param datagram string a string with the datagram contents. The maximum datagram size for UDP is 64K minus IP layer overhead. However datagrams larger than the link layer packet size will be fragmented, which may deteriorate performance and/or reliability.
---@param ip string the IP address of the recipient. Host names are not allowed for performance reasons.
---@param port number the port number at the recipient.
---@return number the value 1 on success, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function unconnected:sendto(datagram, ip, port) end
---Sets options for the UDP object. Options are only needed by low-level or time-critical applications. You should only modify an option if you are sure you need it.
---@param option string the name of the option to set. The value is provided in the value parameter:
---@param value any the value to set for the specified option.
---@return number the value 1, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function unconnected:setoption(option, value) end
---Changes the peer of a UDP object. This method turns an unconnected UDP object into a connected UDP object or vice versa.
---For connected objects, outgoing datagrams will be sent to the specified peer, and datagrams received from other peers will be discarded by the OS. Connected UDP objects must use the send and receive methods instead of sendto and receivefrom.
--- Since the address of the peer does not have to be passed to and from the OS, the use of connected UDP objects is recommended when the same peer is used for several transmissions and can result in up to 30% performance gains.
---@param address string an IP address or a host name.
---@param port number the port number.
---@return number the value 1 on success, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function unconnected:setpeername(address, port) end
---Binds the UDP object to a local address.
--- This method can only be called before any datagram is sent through the UDP object, and only once. Otherwise, the system automatically binds the object to all local interfaces and chooses an ephemeral port as soon as the first datagram is sent. After the local address is set, either automatically by the system or explicitly by setsockname, it cannot be changed.
---@param address string an IP address or a host name. If address is "*" the system binds to all local interfaces using the constant INADDR_ANY.
---@param port number the port number. If port is 0, the system chooses an ephemeral port.
---@return number the value 1 on success, or nil in case of error.
---@return string the error message, or nil if no error occurred.
function unconnected:setsockname(address, port) end
---Changes the timeout values for the object. By default, the receive and receivefrom operations are blocking. That is, any call to the methods will block indefinitely, until data arrives. The settimeout function defines a limit on the amount of time the functions can block. When a timeout is set and the specified amount of time has elapsed, the affected methods give up and fail with an error code.
--- In UDP, the send and sendto methods never block (the datagram is just passed to the OS and the call returns immediately). Therefore, the settimeout method has no effect on them.
---@param value number the amount of time to wait, in seconds. The nil timeout value allows operations to block indefinitely. Negative timeout values have the same effect.
function unconnected:settimeout(value) end
return socket
|
--[[
╔═════════════════════════════════════╗
║ Settings for doums/lsp_spinner.nvim ║
╚═════════════════════════════════════╝
--]]
-- register an handler for `$/progress` method
-- options are optional
require("lsp_spinner").setup {
spinner = {'⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'},
interval = 80, -- spinner frame rate in ms
redraw_rate = 50, -- statusline refresh rate in ms
}
|
local Val = require("valerie")
local a = { value = 0 }
function love.keypressed(k)
a = Val.Transition({}, 0.5, Val.ease_in_out(a.value, a.value + 200))
end
function love.update(dt)
if a.update then
local out = a:update(dt)
if out then
a = { value = out }
end
end
end
function love.draw()
love.graphics.circle("fill", 400,a.value, 5)
end
|
Keyboard = class(Observer)
function Keyboard:init()
function love.keypressed(key, scancode, isrepeat)
self:notify(Message(MessageTypes.eventListener.keypressed, key))
if key == 'escape' then love.event.quit() end
end
function love.keyreleased(key)
self:notify(Message(MessageTypes.eventListener.keyreleased, key))
end
end
|
--------------------------------
-- @module EaseExponentialOut
-- @extend ActionEase
-- @parent_module cc
---@class cc.EaseExponentialOut:cc.ActionEase
local EaseExponentialOut = {}
cc.EaseExponentialOut = EaseExponentialOut
--------------------------------
---
---@param action cc.ActionInterval
---@return cc.EaseExponentialOut
function EaseExponentialOut:create(action)
end
--------------------------------
---
---@return cc.EaseExponentialOut
function EaseExponentialOut:clone()
end
--------------------------------
---
---@param time number
---@return cc.EaseExponentialOut
function EaseExponentialOut:update(time)
end
--------------------------------
---
---@return cc.ActionEase
function EaseExponentialOut:reverse()
end
--------------------------------
---
---@return cc.EaseExponentialOut
function EaseExponentialOut:EaseExponentialOut()
end
return nil
|
-- Dependencies
-- global debug flag
require 'resources/Debug'
-- Other Flags
require 'resources/Flags'
-- Utilities
require 'resources/Utilities'
-- DataTables
require 'resources/DataTables'
-- local debug flag
local thisDebug = false;
local isDebug = Debug.IsDebug() and thisDebug;
GameState = nil
-- Other local variables
-- the expectation for the building table is that we'll poll OnEntityKilled
-- for the building name, and if we find it, add this many points to the
-- team that killed it (well, not actually, since they could be denied.
-- The other team, anyway). As such, there is no need for these to be
-- named, we'll just iterate ipairs over the whole table in OnEntityKilled.
local radiantBuildings = dofile('resources/RadiantBuildings')
local direBuildings = dofile('resources/DireBuildings')
local RADIANT = 2
local DIRE = 3
-- For now we'll just calculate this internally and apply it in the bonus methods.
-- Later on we'll consider making it more granular.
-- Yes, I am getting lazier over time.
local throttle = 0
local botLead = 0
-- This determines when we want to start throttling the bots
-- (They are this far ahead)
local throttleThreshold = 10
-- throttle value is (Max - Lead) / (Max - Threshold)
local throttleMax = 20
-- Instantiate ourself
if GameState == nil then
GameState = {}
end
-- Updates the game state. This is to be called from OnEntityKilled(),
-- but it checks for IsTower and IsVictim, so we know we're getting a
-- building. Still, safe to check.
function GameState:Update(building)
-- Drop out if the other method was an idiot
if not building:IsTower() and not building:IsBuilding() then
return
end
-- get team
local team = building:GetTeam()
local name = building:GetName()
local msg = name..' destroyed: bot lead is '
-- Compare for the right team
if team == RADIANT then
for _, comparison in ipairs(radiantBuildings) do
if comparison.name == building:GetName() then
GameState:IncrementBotLead(comparison.value, team)
end
end
elseif team == DIRE then
for _, comparison in ipairs(direBuildings) do
if comparison.name == building:GetName() then
GameState:IncrementBotLead(comparison.value, team)
end
end
end
msg = msg..botLead
Debug:Print(msg)
end
-- Returns the current throttle value (making its global accessability moot!)
-- or nil if Throttle is <= 0
-- Also returns the team to which the throttle applies
function GameState:GetThrottle()
-- if not above threshold, return nil
if botLead <= throttleThreshold then return nil end
-- else return the throttle
throttle = (throttleMax - botLead) / (throttleMax - throttleThreshold)
-- sanity check!
if throttle < 0 then
throttle = 0
elseif throttle > 1 then
throttle = 1
end
return throttle, BotTeam
end
-- Increments the botLead variable based on points and the team that scored them
-- Note that the team here is the owner of the dead building, so logic is inverted
function GameState:IncrementBotLead(points, team)
if team ~= BotTeam then
botLead = botLead + points
else
botLead = botLead - points
end
end
|
local Player = ...;
local style = GAMESTATE:GetCurrentStyle();
local styleType = style:GetStyleType();
local bDoubles = (styleType == 'StyleType_OnePlayerTwoSides' or styleType == 'StyleType_TwoPlayersSharedSides');
local center1P = PREFSMAN:GetPreference("Center1Player")
-- initialize each stage at a HealthState of "alive"
local prevHealth = "HealthState_Alive";
local t = Def.ActorFrame{
Name="Danger" .. ToEnumShortString(Player);
HealthStateChangedMessageCommand=function(self, param)
if param.PlayerNumber == Player then
if param.HealthState == "HealthState_Danger" then
self:RunCommandsOnChildren(cmd(playcommand,"Danger"));
prevHealth = "HealthState_Danger"
elseif param.HealthState == "HealthState_Dead" then
self:RunCommandsOnChildren(cmd(playcommand,"Dead"));
else
if prevHealth == "HealthState_Danger" then
self:RunCommandsOnChildren(cmd(playcommand,"OutOfDanger"));
else
self:RunCommandsOnChildren(cmd(playcommand,"Hide"));
end
prevHealth = "HealthState_Alive";
end
end
end;
};
t[#t+1] = Def.Quad{
InitCommand=function(self)
self:diffusealpha(0);
if bDoubles then
self:stretchto(0,0,_screen.w,_screen.h);
elseif center1P and not (GAMESTATE:IsHumanPlayer(PLAYER_1) and GAMESTATE:IsHumanPlayer(PLAYER_2)) then
self:stretchto(0,0,_screen.w,_screen.h);
elseif not bDoubles and Player == PLAYER_1 then
self:faderight(0.1); self:stretchto(0,0,_screen.cx,_screen.h);
elseif not bDoubles and Player == PLAYER_2 then
self:fadeleft(0.1); self:stretchto(_screen.cx,0,_screen.w,_screen.h);
end
end;
DangerCommand=cmd(linear,0.3;diffusealpha,0.7;diffuseshift; effectcolor1,color("1,0,0.24,0.3"); effectcolor2,color("1,0,0,0.8"));
DeadCommand=cmd(diffusealpha,0; stopeffect; stoptweening; diffuse,color("1,0,0"); linear,0.3; diffusealpha,0.8; linear,0.3; diffusealpha,0);
OutOfDangerCommand=cmd(diffusealpha,0; stopeffect; stoptweening; diffuse,color("0,1,0"); linear,0.3; diffusealpha,0.8; linear,0.3; diffusealpha,0);
HideCommand=cmd(stopeffect; stoptweening; linear,0.3; diffusealpha,0);
};
t[#t+1] =Def.ActorFrame{
OnCommand=cmd(vibrate);
LoadFont("_8-bit madness 40px")..{
Text="Better!";
InitCommand=function(self)
self:diffusealpha(0);
if bDoubles then
self:Center();
elseif center1P then
self:Center();
elseif not bDoubles and Player == PLAYER_1 then
self:x(360-180); self:y(240);
elseif not bDoubles and Player == PLAYER_2 then
self:x(360+180); self:y(240);
end
end;
OnCommand=cmd(vibrate);
DangerCommand=cmd(linear,0.3;diffusealpha,0.7;diffuseshift; effectcolor1,color("1,0,0.24,0.3"); effectcolor2,color("1,0,0,0.8"));
DeadCommand=cmd(diffusealpha,0; stopeffect; stoptweening; diffuse,color("1,0,0"); linear,0.3; diffusealpha,0.8; linear,0.3; diffusealpha,0);
OutOfDangerCommand=cmd(diffusealpha,0; stopeffect; stoptweening; diffuse,color("0,1,0"); linear,0.3; diffusealpha,0.8; linear,0.3; diffusealpha,0);
HideCommand=cmd(stopeffect; stoptweening; linear,0.3; diffusealpha,0);
};
};
return t;
|
Loot {
resref = "pl_yotori",
[1] = {
Item("fab_barb_armor"),
Item("pl_yotori_hide")
},
}
|
local wibox = require('wibox')
local awful = require('awful')
local gears = require('gears')
local naughty = require('naughty')
local beautiful = require('beautiful')
local dpi = beautiful.xresources.apply_dpi
local config_dir = gears.filesystem.get_configuration_dir()
local widget_icon_dir = config_dir .. 'widget/weather/icons/'
local clickable_container = require('widget.clickable-container')
local json = require('library.json')
local config = require('configuration.config')
local secrets = {
key = config.widget.weather.key,
city_id = config.widget.weather.city_id,
units = config.widget.weather.units,
update_interval = config.widget.weather.update_interval
}
local weather_icon_widget = wibox.widget {
{
id = 'icon',
image = widget_icon_dir .. 'weather-error.svg',
resize = true,
forced_height = dpi(45),
forced_width = dpi(45),
widget = wibox.widget.imagebox,
},
layout = wibox.layout.fixed.horizontal
}
local sunrise_icon_widget = wibox.widget {
{
id = 'sunrise_icon',
image = widget_icon_dir .. 'sunrise.svg',
resize = true,
forced_height = dpi(18),
forced_width = dpi(18),
widget = wibox.widget.imagebox,
},
layout = wibox.layout.fixed.horizontal
}
local sunset_icon_widget = wibox.widget {
{
id = 'sunset_icon',
image = widget_icon_dir .. 'sunset.svg',
resize = true,
forced_height = dpi(18),
forced_width = dpi(18),
widget = wibox.widget.imagebox,
},
layout = wibox.layout.fixed.horizontal
}
local refresh_icon_widget = wibox.widget {
{
id = 'refresh_icon',
image = widget_icon_dir .. 'refresh.svg',
resize = true,
forced_height = dpi(18),
forced_width = dpi(18),
widget = wibox.widget.imagebox,
},
layout = wibox.layout.fixed.horizontal
}
local refresh_button = clickable_container(refresh_icon_widget)
refresh_button:buttons(
gears.table.join(
awful.button(
{},
1,
nil,
function()
awesome.emit_signal('widget::weather_fetch')
awesome.emit_signal('widget::forecast_fetch')
end
)
)
)
local refresh_widget = wibox.widget {
refresh_button,
bg = beautiful.transparent,
shape = gears.shape.circle,
widget = wibox.container.background
}
local weather_desc_temp = wibox.widget {
{
id = 'description',
markup = 'Dust and clouds, -1000°C',
font = 'Inter Regular 10',
align = 'left',
valign = 'center',
widget = wibox.widget.textbox
},
id = 'scroll_container',
max_size = 345,
speed = 75,
expand = true,
direction = 'h',
step_function = wibox.container.scroll
.step_functions.waiting_nonlinear_back_and_forth,
fps = 30,
layout = wibox.container.scroll.horizontal,
}
local weather_location = wibox.widget {
{
id = 'location',
markup = 'Earth, Milky Way',
font = 'Inter Regular 10',
align = 'left',
valign = 'center',
widget = wibox.widget.textbox
},
id = 'scroll_container',
max_size = 345,
speed = 75,
expand = true,
direction = 'h',
step_function = wibox.container.scroll
.step_functions.waiting_nonlinear_back_and_forth,
fps = 30,
layout = wibox.container.scroll.horizontal,
}
local weather_sunrise = wibox.widget {
markup = '00:00',
font = 'Inter Regular 10',
align = 'center',
valign = 'center',
widget = wibox.widget.textbox
}
local weather_sunset = wibox.widget {
markup = '00:00',
font = 'Inter Regular 10',
align = 'center',
valign = 'center',
widget = wibox.widget.textbox
}
local weather_data_time = wibox.widget {
markup = '00:00',
font = 'Inter Regular 10',
align = 'center',
valign = 'center',
widget = wibox.widget.textbox
}
local weather_forecast_tooltip = awful.tooltip {
text = 'Loading...',
objects = {weather_icon_widget},
mode = 'outside',
align = 'right',
preferred_positions = {'left', 'right', 'top', 'bottom'},
margin_leftright = dpi(8),
margin_topbottom = dpi(8)
}
local weather_report = wibox.widget {
{
{
layout = wibox.layout.fixed.horizontal,
spacing = dpi(10),
{
layout = wibox.layout.align.vertical,
expand = 'none',
nil,
weather_icon_widget,
nil
},
{
layout = wibox.layout.align.vertical,
expand = 'none',
nil,
{
layout = wibox.layout.fixed.vertical,
weather_location,
weather_desc_temp,
{
layout = wibox.layout.fixed.horizontal,
spacing = dpi(7),
{
layout = wibox.layout.fixed.horizontal,
spacing = dpi(3),
sunrise_icon_widget,
weather_sunrise
},
{
layout = wibox.layout.fixed.horizontal,
spacing = dpi(3),
sunset_icon_widget,
weather_sunset
},
{
layout = wibox.layout.fixed.horizontal,
spacing = dpi(3),
refresh_widget,
weather_data_time
}
}
},
nil
}
},
margins = dpi(10),
widget = wibox.container.margin
},
forced_height = dpi(92),
bg = beautiful.groups_bg,
shape = function(cr, width, height)
gears.shape.partially_rounded_rect(cr, width, height, true, true, true, true, beautiful.groups_radius)
end,
widget = wibox.container.background
}
-- Return weather symbol
local get_weather_symbol = function()
local symbol_tbl = {
['metric'] = '°C',
['imperial'] = '°F'
}
return symbol_tbl[secrets.units]
end
-- Create openweathermap script based on pass mode
-- Mode must be `forecast` or `weather`
local create_weather_script = function(mode)
local weather_script = [[
KEY="]] .. secrets.key .. [["
CITY="]] .. secrets.city_id .. [["
UNITS="]] .. secrets.units .. [["
weather=$(curl -sf "http://api.openweathermap.org/data/2.5/]] .. mode ..
[[?APPID="${KEY}"&id="${CITY}"&units="${UNITS}"")
if [ ! -z "$weather" ]; then
printf "${weather}"
else
printf "error"
fi
]]
return weather_script
end
awesome.connect_signal(
'widget::forecast_fetch',
function()
awful.spawn.easy_async_with_shell(
create_weather_script('forecast'),
function(stdout)
if stdout:match('error') then
weather_forecast_tooltip:set_markup('Can\'t retrieve data!')
else
local forecast_data = json.parse(stdout)
local forecast = ''
for i = 8, 40, 8 do
local day = os.date('%A @ %H:%M', forecast_data.list[i].dt)
local temp = math.floor(forecast_data.list[i].main.temp + 0.5)
local feels_like = math.floor(forecast_data.list[i].main.feels_like + 0.5)
local weather = forecast_data.list[i].weather[1].description
-- Capitalize weather description
weather = weather:sub(1, 1):upper() .. weather:sub(2)
forecast = forecast .. '<b>' .. day .. '</b>\n' ..
'Weather: ' .. weather .. '\n' ..
'Temperature: ' .. temp .. get_weather_symbol() .. '\n' ..
'Feels like: ' .. feels_like .. get_weather_symbol() .. '\n\n'
weather_forecast_tooltip:set_markup(forecast:sub(1, -2))
end
end
end
)
end
)
awesome.connect_signal(
'widget::weather_fetch',
function()
awful.spawn.easy_async_with_shell(
create_weather_script('weather'),
function(stdout)
if stdout:match('error') then
awesome.emit_signal(
'widget::weather_update',
'...',
'Dust and clouds, -1000°C',
'Earth, Milky Way',
'00:00',
'00:00',
'00:00'
)
else
-- Parse JSON string
local weather_data = json.parse(stdout)
-- Process weather data
local location = weather_data.name
local country = weather_data.sys.country
local sunrise = os.date('%H:%M', weather_data.sys.sunrise)
local sunset = os.date('%H:%M', weather_data.sys.sunset)
local refresh = os.date('%H:%M', weather_data.dt)
local temperature = math.floor(weather_data.main.temp + 0.5)
local weather = weather_data.weather[1].description
local weather_icon = weather_data.weather[1].icon
-- Capitalize weather description
local weather = weather:sub(1, 1):upper() .. weather:sub(2)
-- Contantenate weather description and symbol
local weather_description = weather .. ', ' .. temperature .. get_weather_symbol()
-- Contantenate city and country
local weather_location = location .. ', ' .. country
awesome.emit_signal(
'widget::weather_update',
weather_icon,
weather_description,
weather_location,
sunrise,
sunset,
refresh
)
end
end
)
end
)
local update_widget_timer = gears.timer {
timeout = secrets.update_interval,
autostart = true,
call_now = true,
single_shot = false,
callback = function()
awesome.emit_signal('widget::weather_fetch')
awesome.emit_signal('widget::forecast_fetch')
end
}
awesome.connect_signal(
'system::network_connected',
function()
awesome.emit_signal('widget::weather_fetch')
awesome.emit_signal('widget::forecast_fetch')
end
)
awesome.connect_signal(
'widget::weather_update',
function(code, desc, location, sunrise, sunset, data_receive)
local widget_icon_name = 'weather-error'
local icon_tbl = {
['01d'] = 'sun_icon.svg',
['01n'] = 'moon_icon.svg',
['02d'] = 'dfew_clouds.svg',
['02n'] = 'nfew_clouds.svg',
['03d'] = 'dscattered_clouds.svg',
['03n'] = 'nscattered_clouds.svg',
['04d'] = 'dbroken_clouds.svg',
['04n'] = 'nbroken_clouds.svg',
['09d'] = 'dshower_rain.svg',
['09n'] = 'nshower_rain.svg',
['10d'] = 'd_rain.svg',
['10n'] = 'n_rain.svg',
['11d'] = 'dthunderstorm.svg',
['11n'] = 'nthunderstorm.svg',
['13d'] = 'snow.svg',
['13n'] = 'snow.svg',
['50d'] = 'dmist.svg',
['50n'] = 'nmist.svg',
['...'] = 'weather-error.svg'
}
widget_icon_name = icon_tbl[code]
weather_icon_widget.icon:set_image(widget_icon_dir .. widget_icon_name)
weather_icon_widget.icon:emit_signal('widget::redraw_needed')
weather_desc_temp.description:set_markup(desc)
weather_location.location:set_markup(location)
weather_sunrise:set_markup(sunrise)
weather_sunset:set_markup(sunset)
weather_data_time:set_markup(data_receive)
end
)
return weather_report
|
local awful = require('awful')
local gears = require('gears')
-- local icons = require('theme.icons')
local apps = require('configuration.apps')
-- Configure Tag Properties
awful.screen.connect_for_each_screen(function(s)
-- Each screen has its own tag table.
awful.tag({ "1", "2", "3", "4", "5", "6", "7", "8", "9" }, s, awful.layout.layouts[1])
end)
-- }}}
-- Table of layouts to cover with awful.layout.inc, order matters.
awful.layout.layouts = {
awful.layout.suit.floating,
awful.layout.suit.tile,
-- awful.layout.suit.tile.left,
-- awful.layout.suit.tile.bottom,
-- awful.layout.suit.tile.top,
-- awful.layout.suit.fair,
-- awful.layout.suit.fair.horizontal,
-- awful.layout.suit.spiral,
-- awful.layout.suit.spiral.dwindle,
awful.layout.suit.max,
-- awful.layout.suit.max.fullscreen,
-- awful.layout.suit.magnifier,
-- awful.layout.suit.corner.nw,
-- awful.layout.suit.corner.ne,
-- awful.layout.suit.corner.sw,
-- awful.layout.suit.corner.se,
}
-- }}}
|
local PARSERS = require('esearch/shared/adapter/parse').PARSERS
local M = {}
function M.parse(data, parser)
local entries, lines_delta, errors = PARSERS[parser](data, vim.dict)
return vim.list(entries), lines_delta, errors
end
return M
|
-----------------------------------
-- Area: Upper Delkfutt's Tower
-- NPC: ???
-- Notes: Teleports you to the 10th floor.
-- !pos 261 19 20 158
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
player:startEvent(17)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
#!/usr/bin/env lua
--- Tests for antigravity unit.start.
package.path = package.path .. ";../du-mocks/?.lua" -- add du-mocks project
package.path = "../game-data-lua/?.lua;" .. package.path -- add link to Dual Universe/Game/data/lua/ directory
local lu = require("luaunit")
require("common.Utilities")
require("common.atlas")
require("common.planetref")
-- load file into a function for efficient calling
local unitStart = loadfile("./antigravity/ag.unit.start.lua")
local mockCoreUnit = require("dumocks.CoreUnit")
local mockScreenUnit = require("dumocks.ScreenUnit")
local mockAntiGravityGeneratorUnit = require("dumocks.AntiGravityGeneratorUnit")
local mockDatabankUnit = require("dumocks.DatabankUnit")
local mockControlUnit = require("dumocks.ControlUnit")
local TARGET_ALTITUDE_KEY = "AntigravTargetAltitude"
_G.TestAntigravityUnit = {}
function _G.TestAntigravityUnit:setup()
self.coreMock = mockCoreUnit:new(nil, 1, "dynamic core unit m")
self.core = self.coreMock:mockGetClosure()
self.screenMock = mockScreenUnit:new(nil, 2)
self.screen = self.screenMock:mockGetClosure()
self.agGeneratorMock = mockAntiGravityGeneratorUnit:new(nil, 3, "anti-gravity generator s")
self.agGenerator = self.agGeneratorMock:mockGetClosure()
self.databankMock = mockDatabankUnit:new(nil, 4)
self.databank = self.databankMock:mockGetClosure()
self.unitMock = mockControlUnit:new(nil, 5, "programming board")
-- link all mocks by default
self.unitMock.linkedElements["agScreen"] = self.screen
self.unitMock.linkedElements["agg"] = self.agGenerator
self.unitMock.linkedElements["core"] = self.core
self.unitMock.linkedElements["databank"] = self.databank
self.unit = self.unitMock:mockGetClosure()
self.printOutput = ""
_G.system = {
print = function(output)
self.printOutput = self.printOutput .. output .. "\n"
end
}
-- not testing screen, mock its functions
_G.agScreenController = {
needRefresh = false
}
function _G.agScreenController:init(_)
end
end
--- Unset all globals set/used by unit.start.
function _G.TestAntigravityUnit:teardown()
_G.agController = nil
_G.UPDATE_FREQUENCY = nil
_G.agScreen = nil
_G.agg = nil
_G.core = nil
_G.databank = nil
end
--- Verify slot loader maps all elements and reports correctly.
function _G.TestAntigravityUnit:testSlotMappingAuto()
_G.unit = self.unit
unitStart()
-- mappings are correct
lu.assertIs(_G.agController.slots.screen, self.screen)
lu.assertIs(_G.agController.slots.antigrav, self.agGenerator)
lu.assertIs(_G.agController.slots.core, self.core)
lu.assertIs(_G.agController.slots.databank, self.databank)
-- helper print text is correct
lu.assertStrContains(self.printOutput, "Slot agScreen mapped to antigrav screen.")
lu.assertStrContains(self.printOutput, "Slot agg mapped to antigrav antigrav.")
lu.assertStrContains(self.printOutput, "Slot core mapped to antigrav core.")
lu.assertStrContains(self.printOutput, "Slot databank mapped to antigrav databank.")
end
--- Verify slot loader verifies elements and reports correctly.
function _G.TestAntigravityUnit:testSlotMappingManual()
_G.unit = self.unit
-- manual mapping to named slots
_G.agScreen = self.screen
_G.agg = self.agGenerator
_G.core = self.core
_G.databank = self.databank
unitStart()
-- mappings are correct
lu.assertIs(_G.agController.slots.screen, self.screen)
lu.assertIs(_G.agController.slots.antigrav, self.agGenerator)
lu.assertIs(_G.agController.slots.core, self.core)
lu.assertIs(_G.agController.slots.databank, self.databank)
-- helper print text is correct - no output on valid manual mapping
lu.assertEquals(self.printOutput, "")
end
--- Verify underlying antigravity data is read properly when updating state.
function _G.TestAntigravityUnit:testUpdateStateAntiGravity()
_G.unit = self.unit
unitStart()
-- relevant mappings are correct
lu.assertIs(_G.agController.slots.antigrav, self.agGenerator)
lu.assertIs(_G.agController.slots.databank, self.databank)
-- update all values
local targetAltitude = 1750.5
local agState = true
local baseAltitude = 1277.0
local agField = 1.2000000178814
local agPower = 0.35299472945713
self.databankMock.data[TARGET_ALTITUDE_KEY] = targetAltitude
self.agGeneratorMock.state = agState
self.agGeneratorMock.baseAltitude = baseAltitude
self.agGeneratorMock.antiGravityField = agField
self.agGeneratorMock.antiGravityPower = agPower
_G.agScreenController.needRefresh = false
_G.agController:updateState()
lu.assertEquals(_G.agController.targetAltitude, targetAltitude)
lu.assertEquals(_G.agController.agState, agState)
lu.assertEquals(_G.agController.baseAltitude, baseAltitude)
lu.assertEquals(_G.agController.agField, agField)
lu.assertEquals(_G.agController.agPower, agPower)
lu.assertTrue(_G.agScreenController.needRefresh)
end
--- Verify altitude calculations under various flight conditions.
function _G.TestAntigravityUnit:testUpdateStateFlight()
_G.unit = self.unit
unitStart()
-- relevant mappings are correct
lu.assertIs(_G.agController.slots.core, self.core)
-- gValue is commented out because agg distorts it, but left in to show expected calculated result
-- underwater, parked
-- self.coreMock.gValue = 9.807479
self.coreMock.worldVelocity = {-0.012110, 0.010807, 0.000693}
self.coreMock.altitude = -20.920222
self.coreMock.worldVertical = {0.409438, 0.911008, -0.049251}
self.coreMock.constructWorldPos = {-1438971.755137, 486695.731718, -280968.612056}
_G.agController:updateState()
lu.assertAlmostEquals(_G.agController.verticalVelocity, 0, 0.1)
lu.assertAlmostEquals(_G.agController.currentAltitude, -20.92, 1)
-- underwater, moving straight up
-- self.coreMock.gValue = 9.807643
self.coreMock.worldVelocity = {-5.454992, -12.116544, 0.656135}
self.coreMock.altitude = -19.516626
self.coreMock.worldVertical = {0.409433, 0.911010, -0.049249}
self.coreMock.constructWorldPos = {-1438971.896043, 486694.249222, -280968.706895}
_G.agController:updateState()
lu.assertTrue(_G.agController.verticalVelocity > 0)
lu.assertAlmostEquals(_G.agController.currentAltitude, -19.52, 1)
-- atmo, moving up
-- self.coreMock.gValue = 9.397845
self.coreMock.worldVelocity = {109.752930, -147.477219, 37.130440}
self.coreMock.altitude = 1808.802935
self.coreMock.worldVertical = {0.371743, 0.926504, -0.058285}
self.coreMock.constructWorldPos = {-1436511.977069, 483709.645575, -280109.044122}
_G.agController:updateState()
lu.assertTrue(_G.agController.verticalVelocity > 0)
lu.assertAlmostEquals(_G.agController.currentAltitude, 1808.80, 1)
-- atmo, moving down
-- self.coreMock.gValue = 9.438065
self.coreMock.worldVelocity = {197.800613, 71.364143, 2.466721}
self.coreMock.altitude = 1628.717478
self.coreMock.worldVertical = {0.344287, 0.936704, -0.063651}
self.coreMock.constructWorldPos = {-1434110.053024, 483008.986417, -279663.074442}
_G.agController:updateState()
lu.assertTrue(_G.agController.verticalVelocity < 0)
lu.assertAlmostEquals(_G.agController.currentAltitude, 1628.71, 1)
-- near space (within planet influence), moving up
-- self.coreMock.gValue = 8.540230
self.coreMock.worldVelocity = {143.945374, 13.137656, 159.881790}
self.coreMock.altitude = 5985.715003
self.coreMock.worldVertical = {0.012509, 0.962592, -0.270667}
self.coreMock.constructWorldPos = {-1405952.891129, 476613.360567, -260881.213486}
_G.agController:updateState()
lu.assertTrue(_G.agController.verticalVelocity > 0)
lu.assertAlmostEquals(_G.agController.currentAltitude, 5985.72, 1)
-- middle space (hud stops showing altitude but core still gives it), moving up
-- self.coreMock.gValue = 2.896656
self.coreMock.worldVelocity = {664.247437, 1240.123413, 461.507721}
self.coreMock.altitude = 70094.493816
self.coreMock.worldVertical = {-0.648452, -0.278465, -0.708497}
self.coreMock.constructWorldPos = {-1305284.859003, 605398.637673, -176339.349603}
_G.agController:updateState()
lu.assertTrue(_G.agController.verticalVelocity > 0)
lu.assertAlmostEquals(_G.agController.currentAltitude, 70094.49, 1)
-- far space (g < 0.1), moving down
-- self.coreMock.gValue = 0.010681
self.coreMock.worldVelocity = {-87.481560, -39.660667, 33.877953}
self.coreMock.altitude = 0.000000
self.coreMock.worldVertical = {0.862569, 0.351494, -0.363905}
self.coreMock.constructWorldPos = {2260235.337751, -99279961.240220, -700690.506668}
_G.agController:updateState()
-- nan check, not equal to self
lu.assertTrue(_G.agController.verticalVelocity ~= _G.agController.verticalVelocity)
lu.assertTrue(_G.agController.currentAltitude ~= _G.agController.currentAltitude)
end
--- Verify setBaseAltitude rounds and respects minimum altitude.
function _G.TestAntigravityUnit:testSetBaseAltitude()
local DEFAULT_MIN_ALTITUDE = 1000
_G.unit = self.unit
unitStart()
-- relevant mappings are correct
lu.assertIs(_G.agController.slots.antigrav, self.agGenerator)
lu.assertIs(_G.agController.slots.databank, self.databank)
-- init to default of 2000 m
self.agGeneratorMock.targetAltitude = 2000
self.agGeneratorMock.baseAltitude = self.agGeneratorMock.targetAltitude
local expected
-- basic set
expected = 1500
_G.agController:setBaseAltitude(expected)
lu.assertEquals(_G.agController.targetAltitude, expected)
lu.assertEquals(self.agGeneratorMock.targetAltitude, expected)
lu.assertEquals(self.databankMock.data[TARGET_ALTITUDE_KEY], expected)
-- too low
expected = 1000
_G.agController:setBaseAltitude(500)
lu.assertEquals(_G.agController.targetAltitude, expected)
lu.assertEquals(self.agGeneratorMock.targetAltitude, expected)
lu.assertEquals(self.databankMock.data[TARGET_ALTITUDE_KEY], expected)
-- handles floats
expected = 2555.5
_G.agController:setBaseAltitude(2555.5)
lu.assertEquals(_G.agController.targetAltitude, expected)
lu.assertEquals(self.agGeneratorMock.targetAltitude, expected)
lu.assertEquals(self.databankMock.data[TARGET_ALTITUDE_KEY], expected)
end
--- Verify set base altitude works when no databank is mapped.
function _G.TestAntigravityUnit:testSetBaseAltitudeNoDatabank()
-- disable databank
self.unitMock = mockControlUnit:new(nil, 5, "programming board")
self.unitMock.linkedElements["agScreen"] = self.screen
self.unitMock.linkedElements["agg"] = self.agGenerator
self.unitMock.linkedElements["core"] = self.core
self.unit = self.unitMock:mockGetClosure()
_G.unit = self.unit
unitStart()
-- relevant mappings are correct
lu.assertIs(_G.agController.slots.antigrav, self.agGenerator)
lu.assertNil(_G.agController.slots.databank)
-- init to default of 2000 m
self.agGeneratorMock.targetAltitude = 2000
self.agGeneratorMock.baseAltitude = self.agGeneratorMock.targetAltitude
local expected
-- basic set, just making sure no nil error on databank
expected = 1500
_G.agController:setBaseAltitude(expected)
lu.assertEquals(_G.agController.targetAltitude, expected)
lu.assertEquals(self.agGeneratorMock.targetAltitude, expected)
end
--- Verify databank preference load works with no stored preferences.
function _G.TestAntigravityUnit:testDatabankEmptyPrefLoad()
_G.unit = self.unit
-- base and target non-default and different
local expected = 2500
self.agGeneratorMock.targetAltitude = 1500
self.agGeneratorMock.baseAltitude = expected
unitStart()
-- relevant mappings are correct
lu.assertIs(_G.agController.slots.antigrav, self.agGenerator)
lu.assertIs(_G.agController.slots.databank, self.databank)
-- defaults to current base altitude
lu.assertEquals(_G.agController.targetAltitude, expected)
lu.assertEquals(self.agGeneratorMock.targetAltitude, expected)
lu.assertEquals(self.databankMock.data[TARGET_ALTITUDE_KEY], expected)
end
--- Verify databank preference load works with stored preferences.
function _G.TestAntigravityUnit:testDatabankPopulatedPrefLoad()
_G.unit = self.unit
-- stored, base, and target non-default and different
local expected = 3000.5
self.databankMock.data[TARGET_ALTITUDE_KEY] = expected
self.agGeneratorMock.targetAltitude = 1500
self.agGeneratorMock.baseAltitude = 2500
unitStart()
-- relevant mappings are correct
lu.assertIs(_G.agController.slots.antigrav, self.agGenerator)
lu.assertIs(_G.agController.slots.databank, self.databank)
-- defaults to current base altitude
lu.assertEquals(_G.agController.targetAltitude, expected)
lu.assertEquals(self.agGeneratorMock.targetAltitude, expected)
lu.assertEquals(self.databankMock.data[TARGET_ALTITUDE_KEY], expected)
end
--- Verify non-databank preference default works.
function _G.TestAntigravityUnit:testDefaultPrefLoad()
-- disable databank
self.unitMock = mockControlUnit:new(nil, 5, "programming board")
self.unitMock.linkedElements["agScreen"] = self.screen
self.unitMock.linkedElements["agg"] = self.agGenerator
self.unitMock.linkedElements["core"] = self.core
self.unit = self.unitMock:mockGetClosure()
_G.unit = self.unit
-- base and target non-default and different
local expected = 2500
self.agGeneratorMock.targetAltitude = 1500
self.agGeneratorMock.baseAltitude = expected
unitStart()
-- relevant mappings are correct
lu.assertIs(_G.agController.slots.antigrav, self.agGenerator)
lu.assertNil(_G.agController.slots.databank)
-- defaults to current base altitude
lu.assertEquals(_G.agController.targetAltitude, expected)
lu.assertEquals(self.agGeneratorMock.targetAltitude, expected)
end
--- Verify setting state turns the agg on and off.
function _G.TestAntigravityUnit:testSetAgState()
_G.unit = self.unit
unitStart()
-- relevant mappings are correct
lu.assertIs(_G.agController.slots.antigrav, self.agGenerator)
-- start on
self.agGeneratorMock.state = true
-- no-op
_G.agController:setAgState(true)
lu.assertTrue(self.agGeneratorMock.state)
-- turn off
_G.agController:setAgState(false)
lu.assertFalse(self.agGeneratorMock.state)
-- no-op
_G.agController:setAgState(false)
lu.assertFalse(self.agGeneratorMock.state)
-- turn on
_G.agController:setAgState(true)
lu.assertTrue(self.agGeneratorMock.state)
end
os.exit(lu.LuaUnit.run())
|
local map = require'utils'.map
map(
"v",
"<Leader>re",
[[ <Esc><Cmd>lua require('refactoring').refactor('Extract Function')<CR>]],
{silent = true, expr = false}
)
map(
"v",
"<Leader>rf",
[[ <Esc><Cmd>lua require('refactoring').refactor('Extract Function To File')<CR>]],
{silent = true, expr = false}
)
map(
"v",
"<Leader>rv",
[[ <Esc><Cmd>lua require('refactoring').refactor('Extract Variable')<CR>]],
{silent = true, expr = false}
)
map(
"v",
"<Leader>ri",
[[ <Esc><Cmd>lua require('refactoring').refactor('Inline Variable')<CR>]],
{silent = true, expr = false}
)
|
local addonName = "KibsItemLevelContinued"
local addonNamespace = LibStub and LibStub(addonName .. "-1.0", true)
if not addonNamespace or addonNamespace.loaded.Tooltip then return end
addonNamespace.loaded.Tooltip = true
local Tooltip = {}
Tooltip.__index = Tooltip
addonNamespace.Tooltip = Tooltip
local TYPE_HYPERLINK = 1
local TYPE_TEXT = 2
local FIELD_TYPE = 1
local FIELD_CONTENT = 2
function Tooltip:new()
return setmetatable({
items = {},
link = nil,
}, self)
end
function Tooltip:AddHyperlink(link)
if link then
table.insert(self.items, {
TYPE_HYPERLINK,
link,
})
end
return self
end
function Tooltip:AddText(text)
table.insert(self.items, {
TYPE_TEXT,
text,
})
return self
end
local Tooltips = {}
function Tooltip:_HideTooltips()
for _, tooltip in pairs(Tooltips) do
tooltip:Hide()
end
end
function Tooltip:_ShowTooltips(parent, items)
self:_HideTooltips()
local i = 1
local maxSize = 0
self.link = nil
for _, item in pairs(items) do
if item then
if not Tooltips[i] then
Tooltips[i] = CreateFrame("GameTooltip", addonName .. "Tooltip" .. i, GameTooltip:GetParent(), "GameTooltipTemplate")
Tooltips[i]:SetScale(GameTooltip:GetScale())
end
if i == 1 then
Tooltips[i]:SetOwner(parent, "ANCHOR_RIGHT")
else
Tooltips[i]:SetOwner(Tooltips[i - 1], "ANCHOR_NONE")
Tooltips[i]:SetPoint("TOPLEFT", Tooltips[i - 1], "TOPRIGHT")
end
if item[FIELD_TYPE] == TYPE_HYPERLINK then
Tooltips[i]:SetHyperlink(item[FIELD_CONTENT])
self.link = item[FIELD_CONTENT]
elseif item[FIELD_TYPE] == TYPE_TEXT then
Tooltips[i]:SetText(item[FIELD_CONTENT])
end
maxSize = max(Tooltips[i]:GetHeight(), maxSize)
end
i = i + 1
end
-- for j = 1, i - 1 do
-- Tooltips[j]:SetHeight(maxSize)
-- end
end
function Tooltip:HasLink()
return not not self.link
end
function Tooltip:GetLink()
return self.link
end
function Tooltip:Show(parent)
self:_ShowTooltips(parent, self.items)
end
function Tooltip:Hide()
self:_HideTooltips()
end
|
-- https://github.com/ImagicTheCat/vRP
-- MIT license (see LICENSE or vrp/vRPShared.lua)
if not vRP.modules.transformer then return end
local lang = vRP.lang
-- this module define a generic system to transform (generate, process, convert) items/money/etc to items/money/etc in a specific area
-- each transformer can take things to generate other things, using a unit of work
-- units are generated periodically at a specific rate
-- reagents => products (ex: reagents can be nothing for an harvest transformer)
-- Transformer
local TransformerDef = class("TransformerDef")
-- id: identifier (string)
function TransformerDef:__construct(id, cfg)
self.id = id
self.cfg = cfg
self.units = 0
self.users = {} -- map of user => recipe name
end
function TransformerDef:unbindUser(user)
local recipe_name = self.users[user]
if recipe_name then
self.users[user] = nil
vRP.EXT.GUI.remote._removeProgressBar(user.source,"vRP:transformer:"..self.id)
-- onstop
if self.cfg.onstop then self.cfg.onstop(self, user, recipe_name) end
end
end
function TransformerDef:bindUser(user, recipe_name)
self:unbindUser(user)
self.users[user] = recipe_name
local r,g,b = table.unpack(self.cfg.color)
vRP.EXT.GUI.remote._setProgressBar(user.source,"vRP:transformer:"..self.id,"center",recipe_name.."...",r,g,b,0)
-- onstart
if self.cfg.onstart then self.cfg.onstart(self,user,recipe_name) end
end
function TransformerDef:unbindAll()
for user, recipe_name in pairs(self.users) do
self:unbindUser(user)
end
end
-- do transformer tick
function TransformerDef:tick()
local processors = vRP.EXT.Transformer.processors
for user, recipe_name in pairs(self.users) do
local recipe = self.cfg.recipes[recipe_name]
if self.units > 0 and recipe then -- check units
local ok = true
-- check
for id, processor in pairs(processors) do
local reagents, products = recipe.reagents[id], recipe.products[id]
if reagents ~= nil or products ~= nil then
local p_ok = processor[2](user, reagents, products)
if not p_ok then
ok = false
break
end
end
end
if ok then -- do transformation
self.units = self.units-1 -- sub work unit
-- process
for id, processor in pairs(processors) do
local reagents, products = recipe.reagents[id], recipe.products[id]
if reagents ~= nil or products ~= nil then
processor[3](user, reagents, products)
end
end
-- onstep
if self.cfg.onstep then self.cfg.onstep(self, user, recipe_name) end
end
end
end
-- display transformation state to all transforming players
for user,recipe_name in pairs(self.users) do
vRP.EXT.GUI.remote._setProgressBarValue(user.source,"vRP:transformer:"..self.id, self.units/self.cfg.max_units)
if self.units > 0 then -- display units left
vRP.EXT.GUI.remote._setProgressBarText(user.source,"vRP:transformer:"..self.id, recipe_name.."... "..self.units.."/"..self.cfg.max_units)
else
vRP.EXT.GUI.remote._setProgressBarText(user.source,"vRP:transformer:"..self.id, lang.transformer.empty_bar())
end
end
end
-- per minute regen tick
function TransformerDef:regen()
self.units = self.units+self.cfg.units_per_minute
if self.units >= self.cfg.max_units then self.units = self.cfg.max_units end
end
-- Extension
local Transformer = class("Transformer", vRP.Extension)
-- PRIVATE METHODS
-- menu: transformer
local function menu_transformer(self)
local function m_recipe(menu, recipe_name)
local user = menu.user
local tr = menu.data.transformer
if user:inArea("vRP:transformer:"..tr.id) then
tr:bindUser(user, recipe_name)
end
end
vRP.EXT.GUI:registerMenuBuilder("transformer", function(menu)
local tr = menu.data.transformer
local user = menu.user
menu.title = tr.cfg.title
local r,g,b = table.unpack(tr.cfg.color)
menu.css.header_color = "rgba("..r..","..g..","..b..",0.75)"
-- add recipes
for recipe_name,recipe in pairs(tr.cfg.recipes) do
if user:hasPermissions(recipe.permissions or {}) then
local r_info, p_info = "", ""
-- compute info
for id, processor in pairs(self.processors) do
local reagents, products = recipe.reagents[id], recipe.products[id]
if reagents ~= nil or products ~= nil then
local r, p = processor[1](user, reagents, products)
r_info = r_info..r
p_info = p_info..p
end
end
local info = lang.transformer.recipe_description({recipe.description, r_info, p_info})
menu:addOption(recipe_name, m_recipe, info, recipe_name)
end
end
end)
end
local function bind_tr_area(self, user, tr)
local menu
local function enter(user)
if user:hasPermissions(tr.cfg.permissions or {}) then
menu = user:openMenu("transformer", {transformer = tr}) -- open menu
end
end
local function leave(user)
if menu then
user:closeMenu(menu)
end
tr:unbindUser(user)
end
local x,y,z = table.unpack(tr.cfg.position)
user:setArea("vRP:transformer:"..tr.id,x,y,z,tr.cfg.radius,tr.cfg.height,enter,leave)
end
local function unbind_tr_area(self, user, tr)
user:removeArea("vRP:transformer:"..tr.id)
end
-- METHODS
function Transformer:__construct()
vRP.Extension.__construct(self)
self.cfg = module("cfg/transformers")
self:log(#self.cfg.transformers.." static transformers")
self.processors = {} -- registered processors, map of id => {on_display, on_check, on_process}
self.transformers = {} -- map of id => transformer
menu_transformer(self)
-- load transformers from config file
for i,cfg in pairs(self.cfg.transformers) do
self:set("vRP:cfg_static:"..i, cfg)
end
-- task: transformers ticks (every 3 seconds)
local function transformers_tick()
SetTimeout(3000,transformers_tick)
for id,tr in pairs(self.transformers) do
tr:tick()
end
end
SetTimeout(3000,transformers_tick)
-- task: transformers unit regeneration
local function transformers_regen()
SetTimeout(60000,transformers_regen)
for id,tr in pairs(self.transformers) do
tr:regen()
end
end
SetTimeout(60000,transformers_regen)
end
-- register a transformer processor
-- on_display(user, reagents, products): should return r_info, p_info (two html strings to display info about the reagents and products)
-- on_check(user, reagents, products): should return true if the processing can occur
-- on_process(user, reagents, products): should process the transformation
-- for the three callbacks:
--- reagents: reagents data, can be nil
--- products: products data, can be nil
function Transformer:registerProcessor(id, on_display, on_check, on_process)
self.processors[id] = {on_display, on_check, on_process}
end
-- add a transformer
-- id: transformer identitifer (string)
-- cfg: transformer config
--- title
--- color {r,g,b} (255)
--- max_units
--- units_per_minute
--- pos {x,y,z}
--- radius,height (area properties)
--- permissions: (optional)
--- recipes: map of recipe name => recipe {}
---- description (html)
---- reagents: map of processor id => data, see modules transformer processors
---- products: map of processor id => data, see modules transformer processors
---- permissions: (optional) recipe permissions
---- onstart(transformer, user, recipe_name): (optional) called when the recipe starts
---- onstep(transformer, user, recipe_name): (optional) called at each recipe step
---- onstop(transformer, user, recipe_name): (optional) called when the recipe stops
function Transformer:set(id, cfg)
self:remove(id) -- remove pre-existing transformer
-- create transformer
local tr = TransformerDef(id, clone(cfg))
self.transformers[id] = tr
-- bind tr area to all already spawned players
for id,user in pairs(vRP.users) do
bind_tr_area(self, user, tr)
end
end
-- remove a transformer
function Transformer:remove(id)
local tr = self.transformers[id]
if tr then
tr:unbindAll()
-- remove tr area from all already spawned players
for id,user in pairs(vRP.users) do
unbind_tr_area(self,user,tr)
end
self.transformers[id] = nil
end
end
-- EVENT
Transformer.event = {}
function Transformer.event:playerSpawn(user, first_spawn)
if first_spawn then
-- bind transformers areas
for id,tr in pairs(self.transformers) do
bind_tr_area(self, user, tr)
end
end
end
vRP:registerExtension(Transformer)
|
-- Event notes hooks
function onEvent(name, value1, value2)
if name == 'ded' then
removeLuaSprite('ded'); -- i dont if this work or shit i havent tested it
end
end
|
require('torch')
require('nn')
require('libfbnn')
pcall(function() include('Dropout.lua') end) -- because uses async_rng
include('CachingLookupTable.lua')
include('Optim.lua')
include('Probe.lua')
include('TrueNLLCriterion.lua')
include('SparseLinear.lua')
include('ProjectiveGradientNormalization.lua')
include('ClassNLLCriterionWithUNK.lua')
include('test.lua')
-- Former fbcunn.nn_layers
include('ClassHierarchicalNLLCriterion.lua')
include('CrossMapNormalization.lua')
include('GroupKMaxPooling.lua')
include('HSM.lua')
include('KMaxPooling.lua')
include('LinearNB.lua')
include('LocallyConnected.lua')
include('SequentialCriterion.lua')
-- include('SparseConverter.lua')
-- include('SparseKmax.lua')
-- include('SparseLookupTable.lua')
-- include('SparseNLLCriterion.lua')
-- include('SparseSum.lua')
-- include('SparseThreshold.lua')
include('WeightedLookupTable.lua')
-- Former fbcunn.cpu
-- require('fbcode.torch.fb.fbnn.cpu_ext')
|
require 'torch'
require 'cutorch'
require 'densecap.modules.ApplyBoxTransform'
require 'densecap.modules.InvertBoxTransform'
local gradcheck = require 'gradcheck'
local tests = {}
local tester = torch.Tester()
-- Make sure that ApplyBoxTransform -> InvertBoxTransform computes the identity
local function applyInvertFactory(dtype, epsilon)
return function()
local B = 10
local anchor_boxes = torch.randn(B, 4):type(dtype)
anchor_boxes[{{}, {3, 4}}]:abs()
local trans = torch.randn(B, 4):type(dtype)
local apply = nn.ApplyBoxTransform():type(dtype)
local invert = nn.InvertBoxTransform():type(dtype)
local boxes = apply:forward{anchor_boxes, trans}
local trans_alt = invert:forward{anchor_boxes, boxes}
tester:assertTensorEq(trans, trans_alt, epsilon or 1e-4)
end
end
tests.applyInvertFloatTest = applyInvertFactory('torch.FloatTensor')
tests.applyInvertDoubleTest = applyInvertFactory('torch.DoubleTensor', 1e-6)
tests.applyInvertCudaTest = applyInvertFactory('torch.CudaTensor')
-- Make sure that InvertBoxTransform -> ApplyBoxTransform computes the identity
local function invertApplyFactory(dtype, epsilon)
return function()
local B = 10
local anchor_boxes = torch.randn(B, 4):type(dtype)
anchor_boxes[{{}, {3, 4}}]:abs()
local target_boxes = torch.randn(B, 4):type(dtype)
target_boxes[{{}, {3, 4}}]:abs()
local apply = nn.ApplyBoxTransform():type(dtype)
local invert = nn.InvertBoxTransform():type(dtype)
local trans = invert:forward{anchor_boxes, target_boxes}
local boxes = apply:forward{anchor_boxes, trans}
tester:assertTensorEq(boxes, target_boxes, epsilon or 1e-4)
end
end
tests.invertApplyFloatTest = invertApplyFactory('torch.FloatTensor')
tests.invertApplyDoubleTest = invertApplyFactory('torch.DoubleTensor', 1e-6)
tests.invertApplyCudaTest = invertApplyFactory('torch.CudaTensor')
function tests.gradCheck()
local B = 10
local anchor_boxes = torch.randn(B, 4)
anchor_boxes[{{}, {3, 4}}]:abs()
local target_boxes = torch.randn(B, 4)
target_boxes[{{}, {3, 4}}]:abs()
local grad_output = torch.randn(B, 4)
local mod = nn.InvertBoxTransform()
mod:forward{anchor_boxes, target_boxes}
local din = mod:backward({anchor_boxes, target_boxes}, grad_output)
local grad_anchor_boxes, grad_target_boxes = unpack(din)
local function f_anchor(x)
return nn.InvertBoxTransform():forward{x, target_boxes}
end
local function f_target(x)
return nn.InvertBoxTransform():forward{anchor_boxes, x}
end
local grad_anchor_boxes_num = gradcheck.numeric_gradient(f_anchor, anchor_boxes, grad_output)
local grad_target_boxes_num = gradcheck.numeric_gradient(f_target, target_boxes, grad_output)
local anchor_err = gradcheck.relative_error(grad_anchor_boxes, grad_anchor_boxes_num)
local target_err = gradcheck.relative_error(grad_target_boxes, grad_target_boxes_num)
tester:assertle(anchor_err, 1e-7)
tester:assertle(target_err, 1e-7)
end
tester:add(tests)
tester:run()
|
--------------------------------
-- @module ActionTintFrame
-- @extend ActionFrame
-- @parent_module ccs
--------------------------------
-- @function [parent=#ActionTintFrame] getColor
-- @param self
-- @return color3b_table#color3b_table ret (return value: color3b_table)
--------------------------------
-- @function [parent=#ActionTintFrame] getAction
-- @param self
-- @param #float float
-- @return ActionInterval#ActionInterval ret (return value: cc.ActionInterval)
--------------------------------
-- @function [parent=#ActionTintFrame] setColor
-- @param self
-- @param #color3b_table color3b
--------------------------------
-- @function [parent=#ActionTintFrame] ActionTintFrame
-- @param self
return nil
|
--[[
skill_id:技能id
target_type:1敌方,2自己,3我方
shape:攻击范围形状--1圆形,2直线,3扇形
duration:施放时间(毫秒)
detail:每级的具体属性
detail.condition:学习条件--{lv,1}角色等级,{money,100}货币
detail.cd:冷却时间(毫秒)
detail.attack_max_num:攻击最大数量
detail.damage_rate:伤害比率
detail.area:攻击范围--shape为圆形时即半径,直线时即为距离
detail.arge:具体的技能参数,针对不同技能有不同参数,见SkillActions.lua说明
暂不用detail.buff:buff效果,类型为数组,元素结构:{BuffType(详见后端的SceneConst),触发概率(万份之几),作用方(1自己2已方3敌方),数值,持续时间,作用次数}
]]--
local config = {
--男角色技能
[110000] = {
skill_id = 110000, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 200, attack_max_num = 2, damage_rate = 10000, area = 600,
desc = [[男角普攻1]],
},
},
},
[110001] = {
skill_id = 110001, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 200, attack_max_num = 3, damage_rate = 10000, area = 600,
desc = [[男角普攻2]],
},
},
},
[110002] = {
skill_id = 110002, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 200, attack_max_num = 4, damage_rate = 10000, area = 600,
desc = [[男角普攻3]],
},
},
},
[110003] = {
skill_id = 110003, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 200, attack_max_num = 5, damage_rate = 10000, area = 600,
desc = [[男角普攻4]],
},
},
},
[110010] = {
skill_id = 110010, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 5000, attack_max_num = 5, damage_rate = 15000, area = 600,
desc = [[男角技能1,造成50点伤害,并有10%概率减对方50%防御]],
buff = {probability=10000,duration=5000,attr_id=3,value=-5000,is_percent=true}
},
[2] = {
condition = {{lv, 2}}, cd = 5000, attack_max_num = 3, damage_rate = 15000, area = 600,
desc = [[男角技能1,造成50点伤害,并有15%概率减对方60%防御]],
buff = {probability=1500,duration=5000,attr_id=3,value=-6000,is_percent=true}
},
},
},
[110011] = {
skill_id = 110011, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 8000, attack_max_num = 5, damage_rate = 20000, area = 600,
desc = [[男角技能2,造成600点伤害同时有50%的概率让对方晕眩3秒]],
buff = {probability=50000, duration=8000}
},
[2] = {
condition = {{lv, 2}}, cd = 8000, attack_max_num = 5, damage_rate = 22000, area = 700,
desc = [[男角技能2,造成700点伤害同时有20%的概率让对方晕眩4秒]],
buff = {probability=2000, duration=4000}
},
},
},
[110012] = {
skill_id = 120012, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 12000, attack_max_num = 6, damage_rate = 200000, area = 600,
desc = [[男角技能3,造成250点伤害同时有20%的概率让对方冰冻3秒]],
buff = {probability=2000, duration=4000}
},
},
},
[110013] = {
skill_id = 110013, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 15000, attack_max_num = 5, damage_rate = 30000, area = 600,
desc = [[男主大招,5秒内造成5次范围伤害,每次有100%的概率从对方吸收5%血量]],
buff = {probability=10000,suck_interval=0,suck_count=1,value=500,is_percent=true}
},
},
},
--女角色技能
[120000] = {
skill_id = 120000, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 200, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
[120001] = {
skill_id = 120001, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 200, attack_max_num = 3, damage_rate = 10000, area = 600,
},
},
},
[120002] = {
skill_id = 120002, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 200, attack_max_num = 4, damage_rate = 10000, area = 600,
},
},
},
[120003] = {
skill_id = 120003, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 200, attack_max_num = 5, damage_rate = 10000, area = 600,
},
},
},
[120010] = {
skill_id = 120010, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 5000, attack_max_num = 5, damage_rate = 10000, area = 600,
desc = [[女角技能1,造成50点伤害,并有10%概率减对方50%防御]],
buff = {probability=10000,duration=5000,attr_id=3,value=-5000,is_percent=true}
},
},
},
[120011] = {
skill_id = 120011, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 8000, attack_max_num = 15, damage_rate = 10000, area = 600,
desc = [[女角技能2,造成600点伤害同时有50%的概率让对方晕眩3秒]],
buff = {probability=50000, duration=8000}
},
},
},
[120012] = {
skill_id = 120012, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 12000, attack_max_num = 6, damage_rate = 200000, area = 600,
},
},
},
[120013] = {
skill_id = 120013, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 15000, attack_max_num = 5, damage_rate = 10000, area = 600,
desc = [[女主大招,5秒内造成5次范围伤害,每次有100%的概率从对方吸收5%血量]],
buff = {probability=10000,suck_interval=0,suck_count=1,value=500,is_percent=true}
},
},
},
--怪物技能
[200000] = {
skill_id = 200000, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 100, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
[200001] = {
skill_id = 200001, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 100, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
[200100] = {
skill_id = 200100, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 100, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
[200101] = {
skill_id = 200101, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 100, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
[200200] = {
skill_id = 200200, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 100, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
[200201] = {
skill_id = 200201, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 100, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
[200300] = {
skill_id = 200300, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 100, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
[200301] = {
skill_id = 200301, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 100, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
[200400] = {
skill_id = 200400, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 100, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
[200401] = {
skill_id = 200401, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 100, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
[200500] = {
skill_id = 200500, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 100, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
[200501] = {
skill_id = 200501, target_type = 1, shape = 1, duration = 1000, detail = {
[1] = {
condition = {{lv, 1}}, cd = 100, attack_max_num = 2, damage_rate = 10000, area = 600,
},
},
},
}
return config
|
require("moonsc").import_tags()
-- test that sendid is present in error events triggered by send errors
return _scxml{ initial="s0", name="machineName",
_datamodel{
_data{ id="var1" },
_data{ id="var2" },
},
_state{ id="s0",
_onentry{
-- this will raise an error and also store the sendid in var1
_send{ target="baz", event="foo", idlocation="var1" }, -- illegal target
},
-- get the sendid out of the error event:
_transition{ event="error", target="s1", _assign{ location="var2", expr="_event.sendid" }},
_transition{ event="*", target="fail" },
},
_state{ id="s1",
-- make sure that the sendid in the error event matches the one generated when send executed
_transition{ cond="var1==var2", target="pass", _log{ expr="'var1='..var1"}},
_transition{ target="fail" },
},
_final{id='pass'},
_final{id='fail'},
}
|
------------------------------------------------------------------------
-- Academy class - a processor to train students into officers.
-- 'k2cp-academy' is the associated entity.
------------------------------------------------------------------------
Academy = {}
function Academy:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Academy:init(i, n, e)
self.state = {
index = i,
internal_name = n,
entity = e
}
end
|
include( "shared.lua" )
GM.UseMawChat = true
GM.UseMawBlockCHud = true
--hook.Remove( "PostDrawEffects", "RenderHalos" )
function GM:Initialize()
end
function GM:CallScreenClickHook()
end
|
-- invoke as Pandoc writer
-- write lua metadata file for later processing
package.path = package.path .. ';' ..
string.gsub(PANDOC_SCRIPT_FILE, '/[^/]+$', '') .. '/agsman.lua'
local agsman = require('agsman')
local serialize = agsman.serialize
local stringify = (require 'pandoc.utils').stringify
local skipwords = {
['a'] = true,
['and'] = true,
['are'] = true,
['as'] = true,
['at'] = true,
['be'] = true,
['but'] = true,
['by'] = true,
['for'] = true,
['if'] = true,
['in'] = true,
['into'] = true,
['is'] = true,
['it'] = true,
['near'] = true,
['no'] = true,
['not'] = true,
['of'] = true,
['on'] = true,
['or'] = true,
['such'] = true,
['that'] = true,
['the'] = true,
['their'] = true,
['then'] = true,
['there'] = true,
['these'] = true,
['they'] = true,
['this'] = true,
['to'] = true,
['was'] = true,
['will'] = true,
['with'] = true
}
local keywords = {}
local links = {}
function Link(s, src, title)
-- track all link targets
links[src] = (links[src] or 0) + 1
return ''
end
function Space()
return ' '
end
function Str(s)
add_word(s)
return s
end
function Code(s, attr)
for word in s:gmatch('%S+') do
add_word(word)
end
return s
end
function CodeBlock(s, attr)
for word in s:gmatch('%S+') do
add_word(word)
end
return s
end
function add_word(word)
local chars = '%w'
local first = word:sub(1, 1)
local last = word:sub(-1)
-- preserve ' in the middle of the word
if first ~= "'" and last ~= "'" then
chars = chars .. "'"
end
-- preserve - in the middle of the word
if first ~= '-' and last ~= '-' then
chars = chars .. '-'
end
-- split on non-word characters
for w in word:gmatch('[' .. chars .. ']+') do
if w:len() > 1 and not w:match('%d') then
if skipwords[w:lower()] == nil then
keywords[w] = (keywords[w] or 0) + 1
end
end
end
end
function Doc(body, metadata, variables)
local pagemeta = {
links = links,
keywords = keywords,
title = (metadata.title or metadata.docname),
index = {}
}
for i, block in ipairs(PANDOC_DOCUMENT.blocks) do
-- check each header for inline code
if block.t == "Header" then
local header = nil
local itemtype = nil
for i, child in ipairs(block.content) do
-- take the first match and stop checking
if child.t == "Code" then
header = child.text
break
end
end
if header then
-- heading was describing some code
itemtype = 'script'
else
-- if no code matched just convert to a string
itemtype = 'editorial'
header = stringify(block)
end
assert(header:len() > 0)
table.insert(pagemeta["index"],
{ header = header,
itemtype = itemtype,
id = block.attr.identifier })
end
end
return string.format('-- %s\n\nreturn %s', metadata.docname, serialize(pagemeta))
end
local meta = {}
meta.__index =
function(_, key)
return function() return '' end
end
setmetatable(_G, meta)
|
if not modules then modules = { } end modules ['task-ini'] = {
version = 1.001,
comment = "companion to task-ini.mkiv",
author = "Hans Hagen, PRAGMA-ADE, Hasselt NL",
copyright = "PRAGMA ADE / ConTeXt Development Team",
license = "see context related readme files"
}
-- this is a temporary solution, we need to isolate some modules and then
-- the load order can determine the trickery to be applied to node lists
--
-- we can disable more handlers and enable then when really used (*)
--
-- todo: two finalizers: real shipout (can be imposed page) and page shipout (individual page)
--
-- todo: consider moving the kernel kerning/ligaturing functions in the main font loop because
-- there we know if they are needed; doesn't save time but; if we overload unh* commands to
-- not apply the font handler, we can remove all checks for subtypes 255
local tasks = nodes.tasks
local prependaction = tasks.prependaction
local appendaction = tasks.appendaction
local disableaction = tasks.disableaction
local enableaction = tasks.enableaction
local freezegroup = tasks.freezegroup
local freezecallbacks = callbacks.freeze
appendaction("processors", "normalizers", "languages.replacements.handler") -- disabled
appendaction("processors", "normalizers", "typesetters.wrappers.handler") -- disabled
appendaction("processors", "normalizers", "typesetters.characters.handler") -- always on
appendaction("processors", "normalizers", "fonts.collections.process") -- disabled
appendaction("processors", "normalizers", "fonts.checkers.missing") -- disabled
appendaction("processors", "characters", "scripts.autofontfeature.handler")
appendaction("processors", "characters", "scripts.splitters.handler") -- disabled
appendaction("processors", "characters", "typesetters.cleaners.handler") -- disabled
appendaction("processors", "characters", "typesetters.directions.handler") -- disabled
appendaction("processors", "characters", "typesetters.cases.handler") -- disabled
appendaction("processors", "characters", "typesetters.breakpoints.handler") -- disabled
appendaction("processors", "characters", "scripts.injectors.handler") -- disabled
------------("processors", "words", "languages.replacements.handler") -- disabled
appendaction("processors", "words", "languages.words.check") -- disabled -- might move up, no disc check needed then
appendaction("processors", "words", "languages.hyphenators.handler") -- always on
appendaction("processors", "words", "typesetters.initials.handler") -- disabled -- might move up
appendaction("processors", "words", "typesetters.firstlines.handler") -- disabled
appendaction("processors", "fonts", "builders.paragraphs.solutions.splitters.split") -- experimental
appendaction("processors", "fonts", "nodes.handlers.characters") -- maybe todo
appendaction("processors", "fonts", "nodes.injections.handler")
appendaction("processors", "fonts", "typesetters.fontkerns.handler")
appendaction("processors", "fonts", "nodes.handlers.protectglyphs", nil, "nohead") -- maybe todo
appendaction("processors", "fonts", "builders.kernel.ligaturing") -- not always on (could be selective: if only node mode)
appendaction("processors", "fonts", "builders.kernel.kerning") -- not always on (could be selective: if only node mode)
appendaction("processors", "fonts", "nodes.handlers.stripping") -- disabled (might move)
------------("processors", "fonts", "typesetters.italics.handler") -- disabled (after otf/kern handling)
appendaction("processors", "fonts", "nodes.handlers.flatten")
appendaction("processors", "lists", "typesetters.rubies.check") -- disabled (maybe someplace else)
appendaction("processors", "lists", "typesetters.characteralign.handler") -- disabled (we need to to this after otf appliance)
appendaction("processors", "lists", "typesetters.spacings.handler") -- disabled
appendaction("processors", "lists", "typesetters.kerns.handler") -- disabled
appendaction("processors", "lists", "typesetters.digits.handler") -- disabled (after otf handling)
appendaction("processors", "lists", "typesetters.italics.handler") -- disabled (after otf/kern handling)
appendaction("processors", "lists", "languages.visualizediscretionaries") -- disabled
appendaction("processors", "after", "typesetters.marksuspects")
appendaction("shipouts", "normalizers", "typesetters.showsuspects")
appendaction("shipouts", "normalizers", "typesetters.margins.finalhandler") -- disabled
------------("shipouts", "normalizers", "nodes.handlers.cleanuppage") -- disabled
appendaction("shipouts", "normalizers", "builders.paragraphs.expansion.trace") -- disabled
appendaction("shipouts", "normalizers", "typesetters.alignments.handler") -- disabled
appendaction("shipouts", "normalizers", "nodes.references.handler") -- disabled
appendaction("shipouts", "normalizers", "nodes.destinations.handler") -- disabled
appendaction("shipouts", "normalizers", "nodes.rules.handler") -- disabled
appendaction("shipouts", "normalizers", "nodes.shifts.handler") -- disabled
appendaction("shipouts", "normalizers", "structures.tags.handler") -- disabled
appendaction("shipouts", "normalizers", "nodes.handlers.accessibility") -- disabled
appendaction("shipouts", "normalizers", "nodes.handlers.backgrounds") -- disabled
------------("shipouts", "normalizers", "nodes.handlers.export") -- disabled
appendaction("shipouts", "normalizers", "typesetters.rubies.attach") -- disabled
appendaction("shipouts", "finishers", "nodes.visualizers.handler") -- disabled
appendaction("shipouts", "finishers", "attributes.colors.handler") -- disabled
appendaction("shipouts", "finishers", "attributes.transparencies.handler") -- disabled
appendaction("shipouts", "finishers", "attributes.colorintents.handler") -- disabled
appendaction("shipouts", "finishers", "attributes.negatives.handler") -- disabled
appendaction("shipouts", "finishers", "attributes.effects.handler") -- disabled
appendaction("shipouts", "finishers", "attributes.viewerlayers.handler") -- disabled
--maybe integrate relocate and families
appendaction("math", "normalizers", "noads.handlers.showtree", nil, "nohead")
appendaction("math", "normalizers", "noads.handlers.unscript", nil, "nohead") -- always on (maybe disabled)
appendaction("math", "normalizers", "noads.handlers.variants", nil, "nohead") -- always on
appendaction("math", "normalizers", "noads.handlers.relocate", nil, "nohead") -- always on
appendaction("math", "normalizers", "noads.handlers.families", nil, "nohead") -- always on
appendaction("math", "normalizers", "noads.handlers.render", nil, "nohead") -- always on
appendaction("math", "normalizers", "noads.handlers.collapse", nil, "nohead") -- disabled
appendaction("math", "normalizers", "noads.handlers.fixscripts",nil, "nohead") -- * first-- always on
appendaction("math", "normalizers", "noads.handlers.domains", nil, "nohead") -- * last -- disabled
appendaction("math", "normalizers", "noads.handlers.autofences",nil, "nohead") -- disabled
appendaction("math", "normalizers", "noads.handlers.resize", nil, "nohead") -- always on
------------("math", "normalizers", "noads.handlers.respace", nil, "nohead") -- always on
appendaction("math", "normalizers", "noads.handlers.alternates",nil, "nohead") -- always on
appendaction("math", "normalizers", "noads.handlers.tags", nil, "nohead") -- disabled
appendaction("math", "normalizers", "noads.handlers.italics", nil, "nohead") -- disabled
appendaction("math", "normalizers", "noads.handlers.kernpairs", nil, "nohead") -- disabled
appendaction("math", "normalizers", "noads.handlers.classes", nil, "nohead") -- disabled
appendaction("math", "builders", "builders.kernel.mlist_to_hlist") -- always on
------------("math", "builders", "noads.handlers.italics", nil, "nohead") -- disabled
appendaction("math", "builders", "typesetters.directions.processmath") -- disabled (has to happen pretty late)
appendaction("math", "builders", "noads.handlers.makeup", nil, "nohead") -- disabled (has to happen last)
appendaction("math", "builders", "noads.handlers.align", nil, "nohead")
appendaction("finalizers", "lists", "typesetters.paragraphs.normalize") -- moved here
appendaction("finalizers", "lists", "typesetters.margins.localhandler") -- disabled
appendaction("finalizers", "lists", "builders.paragraphs.keeptogether")
------------("finalizers", "lists", "nodes.handlers.graphicvadjust") -- todo
appendaction("finalizers", "fonts", "builders.paragraphs.solutions.splitters.optimize") -- experimental
appendaction("finalizers", "lists", "builders.paragraphs.tag")
-- the next can also be in contributers normalizers (when we remove the loop in the handler)
appendaction("finalizers", "lists", "nodes.linefillers.handler")
appendaction("contributers", "normalizers", "nodes.handlers.flattenline")
appendaction("contributers", "normalizers", "nodes.handlers.textbackgrounds")
appendaction("vboxbuilders", "normalizers", "nodes.handlers.backgroundsvbox")
appendaction("mvlbuilders", "normalizers", "nodes.handlers.backgroundspage")
appendaction("mvlbuilders", "normalizers", "typesetters.margins.globalhandler") -- disabled
appendaction("mvlbuilders", "normalizers", "nodes.handlers.migrate")
appendaction("mvlbuilders", "normalizers", "builders.vspacing.pagehandler") -- last !
appendaction("mvlbuilders", "normalizers", "builders.profiling.pagehandler") -- here !
------------("vboxbuilders", "normalizers", "typesetters.margins.localhandler")
appendaction("vboxbuilders", "normalizers", "builders.vspacing.vboxhandler")
appendaction("vboxbuilders", "normalizers", "builders.profiling.vboxhandler") -- here !
-- experimental too
appendaction("mvlbuilders", "normalizers", "typesetters.checkers.handler")
appendaction("vboxbuilders", "normalizers", "typesetters.checkers.handler")
-- rather special (this might get hardcoded):
prependaction("processors", "before", "nodes.properties.attach") -- enabled but optimized for quick abort
appendaction ("shipouts", "normalizers", "nodes.properties.delayed") -- enabled but optimized for quick abort
-- speedup: only kick in when used
disableaction("processors", "typesetters.wrappers.handler")
disableaction("processors", "languages.replacements.handler")
disableaction("processors", "typesetters.characteralign.handler")
disableaction("processors", "scripts.autofontfeature.handler")
disableaction("processors", "scripts.splitters.handler")
disableaction("processors", "scripts.injectors.handler") -- was enabled
disableaction("processors", "fonts.collections.process")
disableaction("processors", "fonts.checkers.missing")
disableaction("processors", "chars.handle_breakpoints")
disableaction("processors", "typesetters.cleaners.handler")
disableaction("processors", "typesetters.cases.handler")
disableaction("processors", "typesetters.digits.handler")
disableaction("processors", "typesetters.breakpoints.handler")
disableaction("processors", "typesetters.directions.handler")
disableaction("processors", "languages.words.check")
disableaction("processors", "typesetters.initials.handler")
disableaction("processors", "typesetters.firstlines.handler")
disableaction("processors", "typesetters.spacings.handler")
disableaction("processors", "typesetters.kerns.handler")
disableaction("processors", "typesetters.italics.handler")
disableaction("processors", "languages.visualizediscretionaries")
disableaction("processors", "nodes.handlers.stripping")
disableaction("processors", "builders.paragraphs.solutions.splitters.split")
disableaction("processors", "typesetters.rubies.check")
disableaction("processors", "typesetters.fontkerns.handler")
disableaction("processors", "nodes.handlers.flatten")
disableaction("processors", "typesetters.marksuspects")
disableaction("shipouts", "typesetters.showsuspects")
disableaction("shipouts", "typesetters.margins.finalhandler")
disableaction("shipouts", "builders.paragraphs.expansion.trace")
disableaction("shipouts", "typesetters.alignments.handler")
disableaction("shipouts", "nodes.rules.handler")
disableaction("shipouts", "nodes.shifts.handler")
disableaction("shipouts", "attributes.colors.handler")
disableaction("shipouts", "attributes.transparencies.handler")
disableaction("shipouts", "attributes.colorintents.handler")
disableaction("shipouts", "attributes.effects.handler")
disableaction("shipouts", "attributes.negatives.handler")
disableaction("shipouts", "attributes.viewerlayers.handler")
disableaction("shipouts", "structures.tags.handler")
disableaction("shipouts", "nodes.visualizers.handler")
disableaction("shipouts", "nodes.handlers.accessibility")
disableaction("shipouts", "nodes.references.handler")
disableaction("shipouts", "nodes.destinations.handler")
disableaction("shipouts", "nodes.handlers.backgrounds")
-------------("shipouts", "nodes.handlers.export")
disableaction("shipouts", "typesetters.rubies.attach")
disableaction("finalizers", "typesetters.margins.localhandler")
disableaction("finalizers", "builders.paragraphs.keeptogether")
disableaction("finalizers", "builders.paragraphs.solutions.splitters.optimize")
-------------("finalizers", "nodes.handlers.graphicvadjust") -- sort of obsolete
disableaction("finalizers", "builders.paragraphs.tag")
disableaction("finalizers", "nodes.linefillers.handler")
disableaction("contributers","nodes.handlers.flattenline")
disableaction("contributers","nodes.handlers.textbackgrounds")
disableaction("vboxbuilders","nodes.handlers.backgroundsvbox")
disableaction("mvlbuilders", "nodes.handlers.backgroundspage")
disableaction("math", "noads.handlers.showtree")
disableaction("math", "noads.handlers.tags")
disableaction("math", "noads.handlers.italics")
disableaction("math", "noads.handlers.collapse")
disableaction("math", "noads.handlers.kernpairs")
disableaction("math", "noads.handlers.domains")
disableaction("math", "noads.handlers.classes")
disableaction("math", "noads.handlers.autofences")
disableaction("math", "noads.handlers.makeup")
disableaction("math", "typesetters.directions.processmath")
disableaction("mvlbuilders", "typesetters.margins.globalhandler")
disableaction("mvlbuilders", "nodes.handlers.migrate")
disableaction("mvlbuilders", "typesetters.checkers.handler")
disableaction("mvlbuilders", "builders.profiling.pagehandler")
-------------("vboxbuilders","typesetters.margins.localhandler")
disableaction("vboxbuilders","typesetters.checkers.handler")
disableaction("vboxbuilders","builders.profiling.vboxhandler")
freezecallbacks("find_.*_file", "find file using resolver")
freezecallbacks("read_.*_file", "read file at once")
freezecallbacks("open_.*_file", "open file for reading")
-- experimental:
freezegroup("processors", "normalizers")
freezegroup("processors", "characters")
freezegroup("processors", "words")
freezegroup("processors", "fonts")
freezegroup("processors", "lists")
freezegroup("finalizers", "normalizers")
freezegroup("finalizers", "fonts")
freezegroup("finalizers", "lists")
freezegroup("shipouts", "normalizers")
freezegroup("shipouts", "finishers")
freezegroup("mvlbuilders", "normalizers")
freezegroup("vboxbuilders", "normalizers")
-----------("parbuilders", "lists")
-----------("pagebuilders", "lists")
freezegroup("math", "normalizers")
freezegroup("math", "builders")
-- new: disabled here
disableaction("processors", "builders.kernel.ligaturing")
disableaction("processors", "builders.kernel.kerning")
directives.register("nodes.basepass", function(v)
if v then
enableaction("processors", "builders.kernel.ligaturing")
enableaction("processors", "builders.kernel.kerning")
else
disableaction("processors", "builders.kernel.ligaturing")
disableaction("processors", "builders.kernel.kerning")
end
end)
|
--//////////////////////////////////////////////////////////////////////
--************************
--OpenMainMenuEvent
--************************
OpenMainMenuEvent = {}
OpenMainMenuEvent.__index = OpenMainMenuEvent
setmetatable(OpenMainMenuEvent, {__index = Event})
function OpenMainMenuEvent.new()
local self = setmetatable({}, OpenMainMenuEvent)
self.name = 'OpenMainMenuEvent'
self.done = false;
return self
end
function OpenMainMenuEvent:update(input, dt)
print('event - OpenMainMenuEvent')
ui.openMenu()
self.done = true;
end
return OpenMainMenuEvent
|
if not GarbageCollector then
print("init GarbageCollector...")
GarbageCollector = class({})
GarbageCollector.ACTIVE_PARTICLES = {}
GarbageCollector.IGNORED_PARTICLES = {}
GarbageCollector.IGNORED_PARTICLES["particles/dev/empty_particle.vpcf"] = true
end
-- Call custom functions whenever CreateParticle is being called anywhere
local original_CreateParticle = CScriptParticleManager.CreateParticle
CScriptParticleManager.CreateParticle = function(self, sParticleName, iAttachType, hParent)
-- call the original function
local response = original_CreateParticle(self, sParticleName, iAttachType, hParent)
if not GarbageCollector.IGNORED_PARTICLES[sParticleName] then
table.insert(GarbageCollector.ACTIVE_PARTICLES, {response, 0})
end
return response
end
-- Call custom functions whenever CreateParticleForTeam is being called anywhere
local original_CreateParticleForTeam = CScriptParticleManager.CreateParticleForTeam
CScriptParticleManager.CreateParticleForTeam = function(self, sParticleName, iAttachType, hParent, iTeamNumber)
-- call the original function
local response = original_CreateParticleForTeam(self, sParticleName, iAttachType, hParent, iTeamNumber)
if not GarbageCollector.IGNORED_PARTICLES[sParticleName] then
table.insert(GarbageCollector.ACTIVE_PARTICLES, {response, 0})
end
return response
end
-- Call custom functions whenever CreateParticleForPlayer is being called anywhere
local original_CreateParticleForPlayer = CScriptParticleManager.CreateParticleForPlayer
CScriptParticleManager.CreateParticleForPlayer = function(self, sParticleName, iAttachType, hParent, hPlayer)
-- call the original function
local response = original_CreateParticleForPlayer(self, sParticleName, iAttachType, hParent, hPlayer)
if not GarbageCollector.IGNORED_PARTICLES[sParticleName] then
table.insert(GarbageCollector.ACTIVE_PARTICLES, {response, 0})
end
return response
end
function GarbageCollector:OnThink()
for k, v in pairs(self.ACTIVE_PARTICLES) do
if v[2] >= 60 then
if v[1] and type(v[1]) == "number" then
ParticleManager:DestroyParticle(v[1], false)
ParticleManager:ReleaseParticleIndex(v[1])
end
table.remove(self.ACTIVE_PARTICLES, k)
else
self.ACTIVE_PARTICLES[k][2] = self.ACTIVE_PARTICLES[k][2] + 1
end
end
end
|
wifi.setmode(wifi.STATION);
wifi.sta.config("FrontierHSI","")
wifi.sta.sethostname("sen01")
print('\n *** startup.lua ver 2.0')
print(' set mode=STATION (mode='..wifi.getmode()..')')
print(' MAC: ',wifi.sta.getmac())
print(' chip: ',node.chipid())
print(' heap: ',node.heap())
tmr.alarm(1,1000,1,function()
if wifi.sta.getip()==nil then
print("IP unavailable, waiting")
else
tmr.stop(1)
print("Config done, IP is "..wifi.sta.getip())
print("hostname: "..wifi.sta.gethostname())
print("ESP8266 mode is: " .. wifi.getmode())
print("The module MAC address is: " .. wifi.ap.getmac())
print("\n Starting sensor read loop")
end
end)
dofile(read-post.lua)
|
--!A cross-platform build utility based on Lua
--
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_ndk_sdkvers.lua
--
-- find ndk sdk versions
--
-- @param ndk_dir the ndk directory
--
-- @return the ndk sdk version array
--
-- @code
--
-- local ndk_sdkvers = find_ndk_sdkvers("/xxx/android-ndk-r10e")
--
-- @endcode
--
function main(ndk_dir)
-- get ndk directory
if not ndk_dir or not os.isdir(ndk_dir) then
return {}
end
-- find all sdk directories
local ndk_sdkvers = {}
for _, sdkdir in ipairs(os.dirs(path.join(ndk_dir, "platforms/android-*"))) do
-- get version
local filename = path.filename(sdkdir)
local version, count = filename:gsub("android%-", "")
if count > 0 then
-- get the max version
if tonumber(version) > 0 then
table.insert(ndk_sdkvers, version)
end
end
end
-- ok?
return ndk_sdkvers
end
|
function love.event.quit(re)
if love.quit then
love.quit()
end
if re == "restart" then
os.restart()
else
lv1lua.running = false
os.exit()
end
end
|
print("radar type support loaded")
ACFM.RadarBehaviour = ACFM.RadarBehaviour or {}
ACFM.DefaultRadarSound = ACFM.DefaultRadarSound or "buttons/button16.wav"
ACFM.RadarBehaviour["DIR-AM"] =
{
GetDetectedEnts = function(self)
return ACFM_GetMissilesInCone(self:GetPos(), self:GetForward(), self.ConeDegs)
end
}
ACFM.RadarBehaviour["OMNI-AM"] =
{
GetDetectedEnts = function(self)
return ACFM_GetMissilesInSphere(self:GetPos(), self.Range)
end
}
|
local type = require"Toolbox.Utilities.Type".GetType
local Import = require"Toolbox.Import"
local Object = Import.Module.Relative"Object"
local Nested = Import.Module.Relative"Objects.Nested"
local Basic = {
Grammar = Import.Module.Relative"Grammar";
Namespace = Import.Module.Relative"Namespace";
}
return Object(
"Basic.Type.Definition", {
Construct = function(self, Pattern, Syntax, Types)
self.Pattern = Pattern
self.Syntax = Syntax or Nested.Grammar()
self.Types = Types or Basic.Namespace();
end;
Decompose = function(self)
return Basic.Grammar(
self.Pattern,
self.Types,
self.Syntax
)()
end;
Copy = function(self)
return -self.Pattern, -self.Syntax, -self.Types
end;
}
)
|
local helpers = require "spec.helpers"
local conf_loader = require "kong.conf_loader"
local prefix_handler = require "kong.cmd.utils.prefix_handler"
local exists = helpers.path.exists
local join = helpers.path.join
describe("NGINX conf compiler", function()
describe("gen_default_ssl_cert()", function()
local conf = assert(conf_loader(helpers.test_conf_path, {
prefix = "ssl_tmp",
ssl = true,
ssl_cert = "spec/fixtures/kong_spec.crt",
ssl_cert_key = "spec/fixtures/kong_spec.key",
admin_ssl = true,
admin_ssl_cert = "spec/fixtures/kong_spec.crt",
admin_ssl_cert_key = "spec/fixtures/kong_spec.key",
}))
before_each(function()
helpers.dir.makepath("ssl_tmp")
end)
after_each(function()
pcall(helpers.dir.rmtree, "ssl_tmp")
end)
describe("proxy", function()
it("auto-generates SSL certificate and key", function()
assert(prefix_handler.gen_default_ssl_cert(conf))
assert(exists(conf.ssl_cert_default))
assert(exists(conf.ssl_cert_key_default))
end)
it("does not re-generate if they already exist", function()
assert(prefix_handler.gen_default_ssl_cert(conf))
local cer = helpers.file.read(conf.ssl_cert_default)
local key = helpers.file.read(conf.ssl_cert_key_default)
assert(prefix_handler.gen_default_ssl_cert(conf))
assert.equal(cer, helpers.file.read(conf.ssl_cert_default))
assert.equal(key, helpers.file.read(conf.ssl_cert_key_default))
end)
end)
describe("admin", function()
it("auto-generates SSL certificate and key", function()
assert(prefix_handler.gen_default_ssl_cert(conf, true))
assert(exists(conf.admin_ssl_cert_default))
assert(exists(conf.admin_ssl_cert_key_default))
end)
it("does not re-generate if they already exist", function()
assert(prefix_handler.gen_default_ssl_cert(conf, true))
local cer = helpers.file.read(conf.admin_ssl_cert_default)
local key = helpers.file.read(conf.admin_ssl_cert_key_default)
assert(prefix_handler.gen_default_ssl_cert(conf, true))
assert.equal(cer, helpers.file.read(conf.admin_ssl_cert_default))
assert.equal(key, helpers.file.read(conf.admin_ssl_cert_key_default))
end)
end)
end)
describe("compile_kong_conf()", function()
it("compiles the Kong NGINX conf chunk", function()
local kong_nginx_conf = prefix_handler.compile_kong_conf(helpers.test_conf)
assert.matches("lua_package_path '?/init.lua;./kong/?.lua;;';", kong_nginx_conf, nil, true)
assert.matches("lua_code_cache on;", kong_nginx_conf, nil, true)
assert.matches("listen 0.0.0.0:9000;", kong_nginx_conf, nil, true)
assert.matches("listen 0.0.0.0:9001;", kong_nginx_conf, nil, true)
assert.matches("server_name kong;", kong_nginx_conf, nil, true)
assert.matches("server_name kong_admin;", kong_nginx_conf, nil, true)
assert.not_matches("lua_ssl_trusted_certificate", kong_nginx_conf, nil, true)
end)
it("compiles with custom conf", function()
local conf = assert(conf_loader(helpers.test_conf_path, {
lua_code_cache = false,
mem_cache_size = "128k",
proxy_listen = "0.0.0.0:80",
admin_listen = "127.0.0.1:8001"
}))
local kong_nginx_conf = prefix_handler.compile_kong_conf(conf)
assert.matches("lua_code_cache off;", kong_nginx_conf, nil, true)
assert.matches("lua_shared_dict cache 128k;", kong_nginx_conf, nil, true)
assert.matches("listen 0.0.0.0:80;", kong_nginx_conf, nil, true)
assert.matches("listen 127.0.0.1:8001;", kong_nginx_conf, nil, true)
end)
it("disables SSL", function()
local conf = assert(conf_loader(helpers.test_conf_path, {
ssl = false,
admin_ssl = false
}))
local kong_nginx_conf = prefix_handler.compile_kong_conf(conf)
assert.not_matches("listen %d+%.%d+%.%d+%.%d+:%d+ ssl;", kong_nginx_conf)
assert.not_matches("ssl_certificate", kong_nginx_conf)
assert.not_matches("ssl_certificate_key", kong_nginx_conf)
assert.not_matches("ssl_protocols", kong_nginx_conf)
assert.not_matches("ssl_certificate_by_lua_block", kong_nginx_conf)
end)
describe("handles client_ssl", function()
it("on", function()
local conf = assert(conf_loader(helpers.test_conf_path, {
client_ssl = true,
client_ssl_cert = "spec/fixtures/kong_spec.crt",
client_ssl_cert_key = "spec/fixtures/kong_spec.key",
}))
local kong_nginx_conf = prefix_handler.compile_kong_conf(conf)
assert.matches("proxy_ssl_certificate.*spec/fixtures/kong_spec.crt", kong_nginx_conf)
assert.matches("proxy_ssl_certificate_key.*spec/fixtures/kong_spec.key", kong_nginx_conf)
end)
it("off", function()
local conf = assert(conf_loader(helpers.test_conf_path, {
client_ssl = false,
}))
local kong_nginx_conf = prefix_handler.compile_kong_conf(conf)
assert.not_matches("proxy_ssl_certificate.*spec/fixtures/kong_spec.crt", kong_nginx_conf)
assert.not_matches("proxy_ssl_certificate_key.*spec/fixtures/kong_spec.key", kong_nginx_conf)
end)
end)
it("does not include lua_ssl_trusted_certificate/lua_ssl_verify_depth by default", function()
local conf = assert(conf_loader(helpers.test_conf_path, {
lua_ssl_verify_depth = "2"
}))
local kong_nginx_conf = prefix_handler.compile_kong_conf(conf)
assert.not_matches("lua_ssl_trusted_certificate", kong_nginx_conf, nil, true)
assert.not_matches("lua_ssl_verify_depth", kong_nginx_conf, nil, true)
end)
it("sets lua_ssl_trusted_certificate/lua_ssl_verify_depth", function()
local conf = assert(conf_loader(helpers.test_conf_path, {
lua_ssl_trusted_certificate = "/path/to/ca.cert",
lua_ssl_verify_depth = "2"
}))
local kong_nginx_conf = prefix_handler.compile_kong_conf(conf)
assert.matches("lua_ssl_trusted_certificate '/path/to/ca.cert';", kong_nginx_conf, nil, true)
assert.matches("lua_ssl_verify_depth 2;", kong_nginx_conf, nil, true)
end)
it("compiles without anonymous reports", function()
local conf = assert(conf_loader(nil, {
anonymous_reports = false,
}))
local nginx_conf = prefix_handler.compile_kong_conf(conf)
assert.not_matches("error_log syslog:server=.+ error;", nginx_conf)
end)
it("compiles with anonymous reports", function()
local conf = assert(conf_loader(nil, {
anonymous_reports = true,
}))
local nginx_conf = prefix_handler.compile_kong_conf(conf)
assert.matches("error_log syslog:server=.+:61828 error;", nginx_conf)
end)
it("defines the client_max_body_size by default", function()
local conf = assert(conf_loader(nil, {}))
local nginx_conf = prefix_handler.compile_kong_conf(conf)
assert.matches("client_max_body_size 0", nginx_conf, nil, true)
end)
it("writes the client_max_body_size as defined", function()
local conf = assert(conf_loader(nil, {
client_max_body_size = "1m",
}))
local nginx_conf = prefix_handler.compile_kong_conf(conf)
assert.matches("client_max_body_size 1m", nginx_conf, nil, true)
end)
it("defines the client_body_buffer_size directive by default", function()
local conf = assert(conf_loader(nil, {}))
local nginx_conf = prefix_handler.compile_kong_conf(conf)
assert.matches("client_body_buffer_size 8k", nginx_conf, nil, true)
end)
it("writes the client_body_buffer_size directive as defined", function()
local conf = assert(conf_loader(nil, {
client_body_buffer_size = "128k",
}))
local nginx_conf = prefix_handler.compile_kong_conf(conf)
assert.matches("client_body_buffer_size 128k", nginx_conf, nil, true)
end)
end)
describe("compile_nginx_conf()", function()
it("compiles a main NGINX conf", function()
local nginx_conf = prefix_handler.compile_nginx_conf(helpers.test_conf)
assert.matches("worker_processes 1;", nginx_conf, nil, true)
assert.matches("daemon on;", nginx_conf, nil, true)
end)
it("compiles with custom conf", function()
local conf = assert(conf_loader(helpers.test_conf_path, {
nginx_daemon = "off"
}))
local nginx_conf = prefix_handler.compile_nginx_conf(conf)
assert.matches("daemon off;", nginx_conf, nil, true)
end)
it("compiles without opinionated nginx optimizations", function()
local conf = assert(conf_loader(nil, {
nginx_optimizations = false,
}))
local nginx_conf = prefix_handler.compile_nginx_conf(conf)
assert.not_matches("worker_rlimit_nofile %d+;", nginx_conf)
assert.not_matches("worker_connections %d+;", nginx_conf)
assert.not_matches("multi_accept on;", nginx_conf)
end)
it("compiles with opinionated nginx optimizations", function()
local conf = assert(conf_loader(nil, {
nginx_optimizations = true,
}))
local nginx_conf = prefix_handler.compile_nginx_conf(conf)
assert.matches("worker_rlimit_nofile %d+;", nginx_conf)
assert.matches("worker_connections %d+;", nginx_conf)
assert.matches("multi_accept on;", nginx_conf)
end)
it("converts dns_resolver to string", function()
local nginx_conf = prefix_handler.compile_nginx_conf({
dns_resolver = { "8.8.8.8", "8.8.4.4" }
}, [[
"resolver ${{DNS_RESOLVER}} ipv6=off;"
]])
assert.matches("resolver 8.8.8.8 8.8.4.4 ipv6=off;", nginx_conf, nil, true)
end)
end)
describe("prepare_prefix()", function()
local tmp_config = conf_loader(helpers.test_conf_path, {
prefix = "servroot_tmp"
})
before_each(function()
pcall(helpers.dir.rmtree, tmp_config.prefix)
helpers.dir.makepath(tmp_config.prefix)
end)
after_each(function()
pcall(helpers.dir.rmtree, tmp_config.prefix)
end)
it("creates inexistent prefix", function()
finally(function()
pcall(helpers.dir.rmtree, "inexistent")
end)
local config = assert(conf_loader(helpers.test_conf_path, {
prefix = "inexistent"
}))
assert(prefix_handler.prepare_prefix(config))
assert.truthy(exists("inexistent"))
end)
it("ensures prefix is a directory", function()
local tmp = os.tmpname()
finally(function()
os.remove(tmp)
end)
local config = assert(conf_loader(helpers.test_conf_path, {
prefix = tmp
}))
local ok, err = prefix_handler.prepare_prefix(config)
assert.equal(tmp .. " is not a directory", err)
assert.is_nil(ok)
end)
it("creates pids folder", function()
assert(prefix_handler.prepare_prefix(tmp_config))
assert.truthy(exists(join(tmp_config.prefix, "pids")))
end)
it("creates serf folder", function()
assert(prefix_handler.prepare_prefix(tmp_config))
assert.truthy(exists(join(tmp_config.prefix, "serf")))
end)
it("creates NGINX conf and log files", function()
assert(prefix_handler.prepare_prefix(tmp_config))
assert.truthy(exists(tmp_config.kong_env))
assert.truthy(exists(tmp_config.nginx_kong_conf))
assert.truthy(exists(tmp_config.nginx_err_logs))
assert.truthy(exists(tmp_config.nginx_acc_logs))
assert.truthy(exists(tmp_config.nginx_admin_acc_logs))
end)
it("dumps Kong conf", function()
assert(prefix_handler.prepare_prefix(tmp_config))
local in_prefix_kong_conf = assert(conf_loader(tmp_config.kong_env))
assert.same(tmp_config, in_prefix_kong_conf)
end)
it("dump Kong conf (custom conf)", function()
local conf = assert(conf_loader(nil, {
pg_database = "foobar",
prefix = tmp_config.prefix
}))
assert.equal("foobar", conf.pg_database)
assert(prefix_handler.prepare_prefix(conf))
local in_prefix_kong_conf = assert(conf_loader(tmp_config.kong_env))
assert.same(conf, in_prefix_kong_conf)
end)
it("writes custom plugins in Kong conf", function()
local conf = assert(conf_loader(nil, {
custom_plugins = { "foo", "bar" },
prefix = tmp_config.prefix
}))
assert(prefix_handler.prepare_prefix(conf))
local in_prefix_kong_conf = assert(conf_loader(tmp_config.kong_env))
assert.True(in_prefix_kong_conf.plugins.foo)
assert.True(in_prefix_kong_conf.plugins.bar)
end)
it("dumps Serf script", function()
assert(prefix_handler.prepare_prefix(tmp_config))
local identifier = helpers.file.read(tmp_config.serf_event)
assert.is_string(identifier)
end)
it("dumps Serf identifier", function()
assert(prefix_handler.prepare_prefix(tmp_config))
local identifier = helpers.file.read(tmp_config.serf_node_id)
assert.is_string(identifier)
end)
it("preserves Serf identifier if already exists", function()
-- prepare twice
assert(prefix_handler.prepare_prefix(tmp_config))
local identifier_1 = helpers.file.read(tmp_config.serf_node_id)
assert(prefix_handler.prepare_prefix(tmp_config))
local identifier_2 = helpers.file.read(tmp_config.serf_node_id)
assert.equal(identifier_1, identifier_2)
end)
describe("ssl", function()
it("does not create SSL dir if disabled", function()
local conf = conf_loader(nil, {
prefix = tmp_config.prefix,
ssl = false,
admin_ssl = false
})
assert(prefix_handler.prepare_prefix(conf))
assert.falsy(exists(join(conf.prefix, "ssl")))
end)
it("does not create SSL dir if using custom cert", function()
local conf = conf_loader(nil, {
prefix = tmp_config.prefix,
ssl = true,
ssl_cert = "spec/fixtures/kong_spec.crt",
ssl_cert_key = "spec/fixtures/kong_spec.key",
admin_ssl = true,
admin_ssl_cert = "spec/fixtures/kong_spec.crt",
admin_ssl_cert_key = "spec/fixtures/kong_spec.key",
})
assert(prefix_handler.prepare_prefix(conf))
assert.falsy(exists(join(conf.prefix, "ssl")))
end)
it("generates default SSL cert", function()
local conf = conf_loader(nil, {
prefix = tmp_config.prefix,
ssl = true,
admin_ssl = true
})
assert(prefix_handler.prepare_prefix(conf))
assert.truthy(exists(join(conf.prefix, "ssl")))
assert.truthy(exists(conf.ssl_cert_default))
assert.truthy(exists(conf.ssl_cert_key_default))
assert.truthy(exists(conf.admin_ssl_cert_default))
assert.truthy(exists(conf.admin_ssl_cert_key_default))
end)
end)
describe("custom template", function()
local templ_fixture = "spec/fixtures/custom_nginx.template"
it("accepts a custom NGINX conf template", function()
assert(prefix_handler.prepare_prefix(tmp_config, templ_fixture))
assert.truthy(exists(tmp_config.nginx_conf))
local contents = helpers.file.read(tmp_config.nginx_conf)
assert.matches("# This is a custom nginx configuration template for Kong specs", contents, nil, true)
assert.matches("daemon on;", contents, nil, true)
assert.matches("listen 0.0.0.0:9000;", contents, nil, true)
end)
it("errors on non-existing file", function()
local ok, err = prefix_handler.prepare_prefix(tmp_config, "spec/fixtures/inexistent.template")
assert.is_nil(ok)
assert.equal("no such file: spec/fixtures/inexistent.template", err)
end)
end)
end)
end)
|
--[[
Copyright (c) 2015 gameboxcloud.com
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.
]]
local gbc = cc.import("#gbc")
local http = cc.import("#http")
local WebSocketInstance = cc.class("WebSocketInstance", gbc.WebSocketInstanceBase)
local Constants = gbc.Constants
-- local json = cc.import("#json")
--local json_encode = json.encode
-- local json_decode = json.decode
local sdSIG = ngx.shared.sdSIG
local sdLogin = ngx.shared.sdLogin
function WebSocketInstance:ctor(config)
WebSocketInstance.super.ctor(self, config)
self._event:bind(WebSocketInstance.EVENT.CONNECTED, cc.handler(self, self.onConnected))
self._event:bind(WebSocketInstance.EVENT.DISCONNECTED, cc.handler(self, self.onDisconnected))
--self._event:bind(WebSocketInstance.EVENT.CONTROL_MESSAGE, cc.handler(self, self.onControlMessage))
end
function WebSocketInstance:authConnect()
if not sdSIG:get(Constants.SIGINIT) then
return nil, nil, "SIGINIT is not set"
end
local master = self.config.server.master
local token, pid, err = WebSocketInstance.super.authConnect(self)
if not token then
return nil, pid, err
end
--cc.printf("authConnect")
local user = http.Post(master.host, master.port, master.name.."/?action=user.verify", {
sid = token,
authorization = self:GetAuthority(),
})
self._User = user
if user and user.id then
return token, user.id
else
--cc.printf("authConnect failed:"..token)
end
return nil, nil, "authConnect failed"
end
function WebSocketInstance:afterAuth()
local con_id = self:getConnectId()
if con_id then
local lgcnt = sdLogin:incr(con_id, 1, 0)
if lgcnt > 1 then
sdLogin:incr(con_id, -1, 0)
self:sendError("UserLoggedIn")
return false
end
self._locked = true
end
return WebSocketInstance.super.afterAuth(self)
end
function WebSocketInstance:onClose()
local con_id = self:getConnectId()
if self._locked and con_id then
sdLogin:incr(con_id, -1, 0)
end
return WebSocketInstance.super.onClose(self)
end
function WebSocketInstance:onConnected()
local id = self:getConnectId()
cc.printf("onConnected:"..id)
self:runAction("role.load", {})
--玩家连接上了
local redis = self:getRedis()
if redis then
redis:zadd(Constants.USERLIST, math.floor(ngx.now()), id)
end
end
function WebSocketInstance:onDisconnected(event)
local id = self:getConnectId()
cc.printf("onDisconnected:"..id)
if event.reason ~= gbc.Constants.CLOSE_CONNECT then
end
--玩家下线了
local redis = self:getRedis()
if redis then
redis:zrem(Constants.USERLIST, id)
end
end
function WebSocketInstance:heartbeat()
end
function WebSocketInstance:getUser()
return self._User
end
function WebSocketInstance:setPlayer(player)
self._Player = player
end
function WebSocketInstance:getPlayer()
return self._Player
end
return WebSocketInstance
|
print("hello")
--> =hello
print(hello)
--> =world
print(double(2))
--> =4
print(polly.Age)
--> =10
print(polly.Name)
--> =Polly
print(polly.Descr())
--> =age: 10, name: Polly
print(ben.Descr())
--> =age: 5, name: Ben
print(ben.Age)
--> =5
benben = ben.Mix(ben)
print(benben.Descr())
--> =age: 10, name: Ben-Ben
ben.Age = 7
print(ben.Age)
--> =7
benalice = ben.Mix{Name = "Alice", Age = 3}
print(benalice.Descr())
--> =age: 10, name: Ben-Alice
print(mapping.answer)
--> =42
print(mapping["foo"])
--> =nil
mapping["foo"] = 128
print(mapping.foo)
--> =128
print(slice[2])
--> =here
slice[1] = "was"
print(slice[0], slice[1], slice[2])
--> ~I\twas\there
print(sprintf("the %s is %d", "answer", 6*7))
--> =the answer is 42
print(twice(function(n) return 2*n end)(5))
--> =20
print(pcall(panic))
--> ~false\tpanic in go call: OMG
print(tostring(polly))
--> =golib_test.TestStruct{Age:10, Name:"Polly"}
do
go = require("golib")
fmt = go.import("fmt")
sprintf = fmt.Sprintf
print(sprintf("-%s-", "hello"))
end
--> =-hello-
|
solution "hellococoa"
target "hellococoa"
target_type "app"
depends("hellolib", "../hellolib/metabuilder.lua")
includedirs
{
"../hellolib",
}
files
{
"AppDelegate.h",
"AppDelegate.m",
"cocoaapp-Info.plist",
"cocoaapp-Prefix.pch",
"main.m",
"metabuilder.lua",
}
resources
{
"Base.lproj/MainMenu.xib",
"en.lproj/Credits.rtf",
"en.lproj/InfoPlist.strings",
"Images.xcassets/*",
}
frameworks
{
"AppKit.framework",
"Cocoa.framework",
"CoreData.framework",
"Foundation.framework"
}
config "Debug"
defines
{
}
config_end()
config "Release"
defines
{
}
config_end()
config "Master"
defines
{
--Add custom defines here
}
config_end()
target_end()
option("compiler", "INFOPLIST_FILE", "../../../cocoaapp-Info.plist")
solution_end()
|
if minetest.get_modpath("moreblocks") then
function darkage.register_stairs(nodeName)
local ndef = assert(minetest.registered_nodes[nodeName], "Error: "..nodeName.." is not registered")
local mod = "darkage"
local node = nodeName:split(":")[2]
local def = table.copy(ndef)
def.drop = nil
stairsplus:register_all(mod, node, nodeName, def)
end
elseif minetest.get_modpath("stairs") then
function darkage.register_stairs(nodeName)
local ndef = assert(minetest.registered_nodes[nodeName], "Error: "..nodeName.." is not registered")
local node = nodeName:split(":")[2]
-- The stairs api does not allow to use the darkage modname, so we have to call the nodes stairs:stair_darkage_
-- and creating an alias
local subname = "darkage_".. node;
stairs.register_stair_and_slab(subname, nodeName,
ndef.groups, ndef.tiles,
ndef.description.." Stair", ndef.description.." Slab",
ndef.sounds)
--stairs.register_stair_and_slab(subname, recipeitem,
-- groups, images,
-- desc_stair, desc_slab, sounds)
minetest.register_alias("darkage:stair_"..node, "stairs:stair_darkage_"..node)
minetest.register_alias("darkage:slab_"..node, "stairs:slab_darkage_"..node)
end
else
-- No compatible stairs mod found.
minetest.log("error", "[darkage] Darkage requires at least moreblocks or stairs to be installed. Its not possible to register stairs.")
function darkage.register_stairs(nodeName)
minetest.log("warning", "could not create stair of type "..nodeName .." because no compatible stairs mod is installed.")
end
end
--[[
if minetest.get_modpath("xdecor") then
table.insert(workbench.custom_nodes_register, "darkage:straw_bale") -- Straw Bale seems to accidently filtered out
end
]]
-- Uncomment, to check if nodes get registered correctly
--[[
if minetest.get_modpath("xdecor") then
darkage.isCuttable = {}
function darkage.register_stairs(nodeName)
darkage.isCuttable[nodeName] = true;
end
end
]]
--place the folowing funktion inside xdecor, to check if everything works fine.
--[[
then
if( node:split(":")[1] == "darkage" and not darkage.isCuttable[node]) then
minetest.log("error", "Error: "..node.. " should not be cuttable")
end
nodes[#nodes+1] = node
else
if( node:split(":")[1] == "darkage" and darkage.isCuttable[node]) then
minetest.log("error", "Error: "..node.. " should be cuttable")
end
]]
|
factorial = function (n)
local f = function (n, a) -- WRONG !!!!
return n==0 and a or f(n-1, a*n) -- refers to GLOBAL f, crashes
end -- because nil is not callable
return f(n, 1) -- calls local f
end
ok, reason = pcall(factorial, 10) -- hoping for 3628800
assert(ok == false) -- but it fails!
print(reason) -- your output will vary
|
local ingredients = {
"accumulator",
"arithmetic-combinator",
"assembling-machine-1",
"battery",
"big-electric-pole",
"boiler",
"cannon-shell",
"car",
"cargo-wagon",
"chemical-plant",
"coal",
"concrete",
"constant-combinator",
"construction-robot",
"copper-plate",
"decider-combinator",
"discharge-defense-remote",
"effectivity-module",
"electric-mining-drill",
"electronic-circuit",
"empty-barrel",
"engine-unit",
"explosive-cannon-shell",
"explosive-rocket",
"explosives",
"fast-inserter",
"fast-splitter",
"fast-transport-belt",
"fast-underground-belt",
"firearm-magazine",
"flamethrower",
"flamethrower-ammo",
"fluid-wagon",
"gate",
"grenade",
"hazard-concrete",
"heavy-oil",
"inserter",
"iron-chest",
"iron-plate",
"landfill",
"land-mine",
"light-oil",
"logistic-chest-active-provider",
"logistic-chest-buffer",
"logistic-chest-passive-provider",
"logistic-chest-requester",
"logistic-chest-storage",
"logistic-robot",
"long-handed-inserter",
"lubricant",
"medium-electric-pole",
"offshore-pump",
"petroleum-gas",
"piercing-rounds-magazine",
"piercing-shotgun-shell",
"pipe",
"pipe-to-ground",
"plastic-bar",
"poison-capsule",
"power-switch",
"productivity-module",
"programmable-speaker",
"pump",
"rail",
"rail-chain-signal",
"rail-signal",
"repair-pack",
"rocket",
"shotgun-shell",
"slowdown-capsule",
"small-lamp",
"speed-module",
"splitter",
"steam",
"steam-engine",
"steel-chest",
"steel-furnace",
"steel-plate",
"stone-brick",
"stone-furnace",
"stone-wall",
"storage-tank",
"sulfur",
"sulfuric-acid",
"train-stop",
"transport-belt",
"underground-belt",
"water",
"wood",
"wooden-chest",
"advanced-circuit",
"artillery-shell",
"artillery-targeting-remote",
"artillery-wagon",
"assembling-machine-2",
"battery-equipment",
"belt-immunity-equipment",
"cliff-explosives",
"cluster-grenade",
"combat-shotgun",
"effectivity-module-2",
"electric-engine-unit",
"electric-furnace",
"energy-shield-equipment",
"express-splitter",
"express-transport-belt",
"express-underground-belt",
"filter-inserter",
"flamethrower-turret",
"flying-robot-frame",
"gun-turret",
"heat-pipe",
"lab",
"laser-turret",
"light-armor",
"locomotive",
"low-density-structure",
"night-vision-equipment",
"oil-refinery",
"productivity-module-2",
"pumpjack",
"radar",
"refined-concrete",
"refined-hazard-concrete",
"roboport",
"rocket-control-unit",
"rocket-fuel",
"rocket-launcher",
"shotgun",
"solar-panel",
"solar-panel-equipment",
"solid-fuel",
"speed-module-2",
"spidertron-remote",
"stack-filter-inserter",
"stack-inserter",
"submachine-gun",
"substation",
"tank",
"artillery-turret",
"assembling-machine-3",
"atomic-bomb",
"battery-mk2-equipment",
"beacon",
"defender-capsule",
"distractor-capsule",
"exoskeleton-equipment",
"explosive-uranium-cannon-shell",
"heat-exchanger",
"heavy-armor",
"modular-armor",
"nuclear-fuel",
"personal-roboport-equipment",
"processing-unit",
"steam-turbine",
"uranium-235",
"uranium-238",
"uranium-cannon-shell",
"uranium-fuel-cell",
"uranium-ore",
"uranium-rounds-magazine"
}
return ingredients
|
local shallowEqual = require(script.Parent.Parent.shallowEqual)
local toString = require(script.Parent.Parent.toString)
local function expectTable(tab)
return {
toEqual = function(value)
assert(
shallowEqual(tab, value),
string.format("expected: %s\ninstead got: %s", toString(value), toString(tab))
)
end,
}
end
return expectTable
|
GlobalVar("MapLowestZ", max_int)
function CalcMapLowestZ()
local tavg, tmin, tmax = terrain.GetAreaHeight()
return tmin
end
function OnMsg.NewMapLoaded()
if MapLowestZ == max_int and not mapdata.IsPrefabMap then
MapLowestZ = CalcMapLowestZ()
end
end
----- MinimumElevationMarker is used to determine lowest point on map
GlobalVar("there_can_be_only_one_height_marker", false)
DefineClass.MinimumElevationMarker = {
__parents = { "EditorMarker" },
}
function MinimumElevationMarker:Init()
if there_can_be_only_one_height_marker then
print("warning!, this map already has an elevation marker!")
end
if editor.Active == 1 then
self:EditorTextUpdate(true)
end
end
function MinimumElevationMarker:Done()
if there_can_be_only_one_height_marker == self then
there_can_be_only_one_height_marker = nil
end
end
function MinimumElevationMarker:GameInit()
if there_can_be_only_one_height_marker then
print("Killing extra MinimumElevationMarkers!")
DoneObject(self)
end
if MapLowestZ == max_int then
MapLowestZ = self:GetVisualPos():z()
end
there_can_be_only_one_height_marker = self
end
function GetElevation(pos)
return pos:z() and (Max(pos:z() - MapLowestZ, 0) / guim) or 0
end
|
package("tesseract")
set_homepage("https://tesseract-ocr.github.io/")
set_description("Tesseract Open Source OCR Engine")
set_license("Apache-2.0")
add_urls("https://github.com/tesseract-ocr/tesseract/archive/$(version).tar.gz",
"https://github.com/tesseract-ocr/tesseract.git")
add_versions("4.1.1", "2a66ff0d8595bff8f04032165e6c936389b1e5727c3ce5a27b3e059d218db1cb")
add_configs("training", {description = "Build training tools.", default = false, type = "boolean"})
add_deps("cmake")
add_deps("leptonica")
add_deps("libarchive", {optional = true})
on_load(function (package)
if package:config("training") then
package:add("deps", "icu4c")
end
end)
on_install("windows", "linux", function (package)
io.replace("CMakeLists.txt", "find_package(PkgConfig)", "", {plain = true})
io.replace("src/training/CMakeLists.txt", "find_package(PkgConfig)", "", {plain = true})
local configs = {"-DSW_BUILD=OFF", "-DBUILD_TESTS=OFF", "-DUSE_SYSTEM_ICU=ON"}
table.insert(configs, "-DCMAKE_BUILD_TYPE=" .. (package:debug() and "Debug" or "Release"))
table.insert(configs, "-DBUILD_SHARED_LIBS=OFF")
table.insert(configs, "-DWIN32_MT_BUILD=" .. (package:config("vs_runtime"):startswith("MT") and "ON" or "OFF"))
table.insert(configs, "-DBUILD_TRAINING_TOOLS=" .. (package:config("training") and "ON" or "OFF"))
if package:config("pic") ~= false then
table.insert(configs, "-DCMAKE_POSITION_INDEPENDENT_CODE=ON")
end
import("package.tools.cmake").install(package, configs)
package:addenv("PATH", "bin")
end)
on_test(function (package)
os.vrun("tesseract --version")
assert(package:has_cxxtypes("tesseract::TessBaseAPI", {configs = {languages = "c++11"}, includes = "tesseract/baseapi.h"}))
end)
|
return {'nawee','naweeen','nawegen','nawerken','nawerking','nawijzen','nawinter','nawoord','nawuiven','nawijsbaar','naw','nawijn','nawal','nawees','nawerk','nawerkingen','nawerkt','nawerkte','nawerkten','nawezen','nawijs','nawijst','nawinters','nawoog','nawoorden','nawuifde','nawijsbare','nawals'}
|
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
function ENT:Initialize()
self:SetModel("models/hunter/blocks/cube025x025x025.mdl")
local view = table.Random(self.ViewTypes)
self:SetModel(view.model)
if view.action then
view.action(self)
end
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetUseType(SIMPLE_USE)
local phys = self:GetPhysicsObject()
phys:Wake()
self:SetIsActive(true)
end
function ENT:StartTouch(ply)
if not self:GetIsActive() then return end
if not ply:IsPlayer() then return end
self:SetIsActive(false)
self:SetCollisionGroup(COLLISION_GROUP_DEBRIS)
local creditAmount = math.random(5, 10)
XYZChristmasCredits.Database.GiveCredits(ply, creditAmount)
XYZShit.Msg("Christmas Credits", Color(246, 70, 99), ply:Name().." has collected "..creditAmount.." credits")
timer.Simple(math.random(5*60, 10*60), function()
if not IsValid(self) then return end
local view = table.Random(self.ViewTypes)
self:SetModel(view.model)
if view.action then
view.action(self)
end
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetUseType(SIMPLE_USE)
local phys = self:GetPhysicsObject()
if IsValid(phys) then
phys:EnableMotion(false)
end
self:SetCollisionGroup(COLLISION_GROUP_NONE)
self:SetIsActive(true)
end)
end
|
require("logic.computer")
table.insert(computer.apis,{
name = "lan",
description = "The LAN API provides functions to communicate using circuit network",
entities = function(entity)
return entity.name == "computer-interface-entity"
end,
prototype = {
-- Private methods
_readCombinatorSignal = {
"private function lan:_readCombinatorSignal(combinator, wire)",
function(self, combinator, wire)
local signals = {}
local network
if wire then
if type(wire) == "string" then
wire = defines.wire_type[wire]
end
network = combinator.get_circuit_network(wire)
end
if network and network.signals then
for key, value in pairs(network.signals) do
if value.signal and value.signal.name and type(value.count) == "number" then
if not signals[value.signal.name] then
signals[value.signal.name] = {
signal = value.signal,
count = value.count
}
else
signals[value.signal.name].count = signals[value.signal.name].count + value.count
end
end
end
elseif not network then
for key, value in pairs(combinator.get_or_create_control_behavior().parameters.parameters) do
if value.signal and value.signal.name and type(value.count) == "number" then
if not signals[value.signal.name] then
signals[value.signal.name] = {
signal = value.signal,
count = value.count
}
else
signals[value.signal.name].count = signals[value.signal.name].count + value.count
end
end
end
end
return signals
end
},
_writeCombinatorSignal = {
"private function lan:_readCombinatorSignal(combinator, signals)",
function(self, combinator, signals)
local parameters = {}
local index = 1;
if not combinator then return end
for _, signal_count in pairs(signals) do
table.insert(parameters, {
index=index,
signal=signal_count.signal,
count= math.floor(signal_count.count)
})
index = index + 1
end
combinator.get_or_create_control_behavior().parameters = {parameters = parameters}
end
},
-- Public methods
readLeftSignals = {
"lan.readLeftSignals(wire) - Returns left signals",
function(self, wire)
local struct = self.__entityStructure
local signals = {}
local combinator = struct.sub.left_combinator
if not combinator then return end
for key, signal in pairs(self:_readCombinatorSignal(combinator, wire)) do
table.insert(signals, signal)
end
return signals
end
},
readRightSignals = {
"lan.readRightSignals(wire) - Returns right signals",
function(self, wire)
local struct = self.__entityStructure
local signals = {}
local combinator = struct.sub.right_combinator
if not combinator then return end
for key, signal in pairs(self:_readCombinatorSignal(combinator, wire)) do
table.insert(signals, signal)
end
return signals
end
},
writeLeftSignals = {
"lan.writeLeftSignals(signals) - Write signals on left combinator",
function(self, signals)
local struct = self.__entityStructure
local combinator = struct.sub.left_combinator
if not combinator then return end
assert(signals, "lan.writeLeftSignals(signals) : `signals` cannot be nil")
self:_writeCombinatorSignal(combinator, signals)
end
},
writeRightSignals = {
"lan.writeRightSignals(signals) - Write signals on right combinator",
function(self, signals)
local struct = self.__entityStructure
local combinator = struct.sub.right_combinator
if not combinator then return end
assert(signals, "lan.writeRightSignals(signals) : `signals` cannot be nil")
self:_writeCombinatorSignal(combinator, signals)
end
},
-- Alias
getLeftSignals = {
"lan.getLeftSignals(wire) - Returns left signals (Alias: readLeftSignals)",
function(self, ...)
return self:readLeftSignals(...)
end
},
getRightSignals = {
"lan.getRightSignals(wire) - Returns right signals (Alias: readRightSignals)",
function(self, ...)
return self:readRightSignals(...)
end
},
setLeftSignals = {
"lan.setLeftSignals(signals) - Write signals on left combinator (Alias: writeLeftSignals)",
function(self, ...)
return self:writeLeftSignals(...)
end
},
setRightSignals = {
"lan.setRightSignals(signals) - Write signals on right combinator (Alias: writeRightSignals)",
function(self, ...)
return self:writeRightSignals(...)
end
}
}
})
|
slot0 = class("TowerClimbingMap")
slot0.Ctor = function (slot0, slot1, slot2)
slot0._tf = slot1.gameView
slot0.view = slot1
slot0.map = slot2
end
slot0.Init = function (slot0, slot1)
slot0.blocks = {}
slot0.groundContainer = slot0._tf:Find("game")
slot0.blockPlayCon = slot0.groundContainer:Find("block_play_con")
setAnchoredPosition(slot0.blockPlayCon, {
x = 0,
y = 0
})
slot0.blockContainer = slot0.blockPlayCon:Find("blocks")
slot0.hearts = {
slot0._tf:Find("prints/score/hearts/1"),
slot0._tf:Find("prints/score/hearts/2"),
slot0._tf:Find("prints/score/hearts/3")
}
slot0.score = slot0._tf:Find("prints/score/Text"):GetComponent(typeof(Text))
slot0.heartProgress = slot0._tf:Find("prints/score/progress")
slot0.heartProgressTxt = slot0._tf:Find("prints/score/progress/Text"):GetComponent(typeof(Text))
slot0.bg = TowerClimbBgMgr.New(slot0._tf:Find("bgs"))
slot0.bg:Init(slot0.map.id, slot1)
slot0.npc = slot0._tf:Find("prints/npc")
slot0:LoadEffect(slot0.map.id)
slot0.tip = slot0._tf:Find("prints/tip")
setActive(slot0.tip, false)
slot0.timers = {}
end
slot0.LoadEffect = function (slot0, slot1)
if TowerClimbingGameSettings.MAPID2EFFECT[slot1] then
for slot6, slot7 in ipairs(slot2) do
slot0:LoadSingleEffect(slot7[1], slot7[2])
end
end
end
slot0.LoadSingleEffect = function (slot0, slot1, slot2, slot3)
PoolMgr.GetInstance():GetUI(slot1, true, function (slot0)
if not slot0.groundContainer then
PoolMgr.GetInstance():ReturnUI(PoolMgr.GetInstance().ReturnUI, slot0)
else
slot0.name = slot1
SetParent(slot0, slot0.groundContainer)
slot0.transform.anchoredPosition3D = Vector3(slot2[1], slot2[2], -200)
setActive(slot0, true)
if true then
slot3(slot0)
end
end
end)
end
slot0.ReturnEffect = function (slot0, slot1)
if TowerClimbingGameSettings.MAPID2EFFECT[slot1] then
for slot6, slot7 in ipairs(slot2) do
if slot0.groundContainer:Find(slot7[1]) then
PoolMgr.GetInstance():ReturnUI(slot8, slot9.gameObject)
end
end
end
end
slot0.OnReachAwardScore = function (slot0)
if LOCK_TOWERCLIMBING_AWARD then
return
end
if slot0.tipTimer then
slot0.tipTimer:Stop()
slot0.tipTimer = nil
end
setActive(slot0.tip, true)
slot0.tipTimer = Timer.New(function ()
setActive(slot0.tip, false)
setActive.tipTimer:Stop()
setActive.tipTimer.Stop.tipTimer = nil
end, 3, 1)
slot0.tipTimer.Start(slot1)
slot1 = slot0.groundContainer:InverseTransformPoint(slot0.npc.position)
slot2 = slot0.groundContainer:InverseTransformPoint(slot0.player._tf.position)
function slot3()
if not slot0.awardEffect1 then
slot0.LoadSingleEffect(slot2, TowerClimbingGameSettings.AWARDEFFECT1, {
slot1.x,
slot1.y
}, function (slot0)
slot0.awardEffect1 = slot0
slot0()
end)
else
slot0()
end
end
function slot4()
slot0 = Vector3(slot0.x, slot1.y + 200, -200)
table.insert(slot1, Vector3(slot1.x, slot1.y, -200))
table.insert(slot1, slot0)
table.insert(slot1, slot0)
table.insert(slot1, Vector3(slot0.x, slot0.y, -200))
table.insert.awardEffect.transform.localPosition = Vector3(slot1.x, slot1.y, -200)
setActive(slot2.awardEffect, true)
LeanTween.moveLocal(slot2.awardEffect, slot1, 1):setOnComplete(System.Action(function ()
setActive(slot0.awardEffect, false)
slot0.awardEffect()
end))
end
if not slot0.awardEffect then
slot0.LoadSingleEffect(slot0, TowerClimbingGameSettings.AWARDEFFECT, {
slot2.x,
slot2.y
}, function (slot0)
slot0.awardEffect = slot0
slot0()
end)
else
slot4()
end
end
slot0.GetFirstBlock = function (slot0)
return slot0.blocks[1]
end
slot0.GetHitBlock = function (slot0, slot1)
if _.detect(slot0.blocks, function (slot0)
return slot0.go == slot0
end) then
return slot2
end
end
slot0.OnCreateGround = function (slot0, slot1, slot2)
slot0.ground = slot1
TowerClimbingResMgr.GetGround(slot1.name, function (slot0)
slot0.groundGo = slot0
slot0.name = "manjuu"
SetParent(slot0.transform, slot0.groundContainer)
slot0.transform.anchoredPosition = slot1.position
setActive(slot0, true)
slot0:GetComponent("SpineAnimUI").SetAction(slot1, "normal", 0)
setText(slot0.groundGo.transform:Find("Text"), "")
setText()
end)
end
slot0.TranslateBlockPosition = function (slot0, slot1)
return slot0.blockContainer:InverseTransformVector(slot0.groundContainer:TransformVector(slot1))
end
slot0.OnCreateBlock = function (slot0, slot1, slot2)
TowerClimbingResMgr.GetBlock(slot1.type, function (slot0)
SetParent(slot0, slot0.blockContainer)
slot0.transform.anchoredPosition = slot0:TranslateBlockPosition(slot1.position)
slot0.name = TowerClimbingGameSettings.BLOCK_NAME
setActive(slot0, true)
slot2 = {}
for slot6 = 1, slot0:GetComponentsInChildren(typeof(UnityEngine.Collider2D)).Length, 1 do
table.insert(slot2, slot1[slot6 - 1])
end
table.insert(slot0.blocks, {
go = slot0,
block = slot1,
colliders = slot2
})
slot0:OnActiveBlock(slot1)
slot5 = math.random(slot3, slot4)
if slot0.transform:Find("firer") then
slot7 = slot6:GetComponent(typeof(Animation))
slot0.timers[slot1.level] = Timer.New(function ()
slot0:Play("action")
end, slot5, -1)
slot0.timers[slot1.level]:Start()
end
slot2()
end)
end
slot0.OnActiveBlock = function (slot0, slot1)
for slot6, slot7 in ipairs(_.detect(slot0.blocks, function (slot0)
return slot0.block.level == slot0.level
end).colliders) do
slot7.enabled = slot1.isActive
end
end
slot0.SinkHandler = function (slot0, slot1, slot2)
LeanTween.value(slot0.blockPlayCon.gameObject, slot3, slot4, 0.2):setOnUpdate(System.Action_float(function (slot0)
setAnchoredPosition(slot0.blockPlayCon, {
y = slot0
})
end)).setEase(slot5, LeanTweenType.easeOutQuad):setOnComplete(System.Action(slot2))
end
slot0.OnBlockDestory = function (slot0, slot1)
if slot0.timers[slot1] then
slot0.timers[slot1]:Stop()
slot0.timers[slot1] = nil
end
TowerClimbingResMgr.ReturnBlock(_.detect(slot0.blocks, function (slot0)
return slot0.block.level == slot0
end).block.type, _.detect(slot0.blocks, function (slot0)
return slot0.block.level == slot0
end).go)
end
slot0.OnSink = function (slot0, slot1, slot2)
slot0.bg:DoMove(slot1, slot2)
slot2()
end
slot0.OnPlayerLifeUpdate = function (slot0, slot1)
triggerToggle(slot0.hearts[3], slot1 >= 3)
triggerToggle(slot0.hearts[2], slot1 >= 2)
triggerToggle(slot0.hearts[1], slot1 >= 1)
slot0.heartProgressTxt.text = slot1 .. "/" .. 3
setFillAmount(slot0.heartProgress, slot1 / 3)
end
slot0.OnScoreUpdate = function (slot0, slot1)
slot0.score.text = slot1
end
slot0.OnCreatePlayer = function (slot0, slot1, slot2)
slot0.player = TowerClimbingPlayer.New(slot0, slot1)
slot0.player:Init(slot2)
end
slot0.OnEnableStab = function (slot0, slot1, slot2)
slot4 = _.detect(slot0.blocks, function (slot0)
return slot0.block.level == slot0.level
end).go.GetComponent(slot4, typeof(UnityEngine.Collider2D))
for slot8, slot9 in ipairs(_.detect(slot0.blocks, function (slot0)
return slot0.block.level == slot0.level
end).colliders) do
if slot9 ~= slot4 then
slot9.enabled = slot2
end
end
end
slot0.OnEnableGround = function (slot0, slot1)
slot0.groundGo:GetComponent(typeof(UnityEngine.Collider2D)).enabled = slot1
end
slot0.GetPlayer = function (slot0)
return slot0.player
end
slot0.SendEvent = function (slot0, slot1, ...)
slot0.view.controller[slot1](slot0.view.controller, unpack({
...
}))
end
slot0.OnGroundRuning = function (slot0)
slot0.groundGo:GetComponent("SpineAnimUI"):SetAction("up", 0)
end
slot0.OnGroundPositionChange = function (slot0, slot1)
setAnchoredPosition(slot0.groundGo.transform, slot1)
end
slot0.OnGroundSleepTimeChange = function (slot0, slot1)
if math.ceil(slot1) > 0 then
setText(slot0.groundGo.transform:Find("Text"), slot2)
else
setText(slot0.groundGo.transform:Find("Text"), "")
end
end
slot0.Dispose = function (slot0)
if slot0.awardTimer then
slot0.awardTimer:Stop()
slot0.awardTimer = nil
end
slot0.bg:Clear()
slot0:ReturnEffect(slot0.map.id)
if slot0.awardEffect then
PoolMgr.GetInstance():ReturnUI(slot0.awardEffect.name, slot0.awardEffect)
slot0.awardEffect = nil
end
if slot0.awardEffect1 then
PoolMgr.GetInstance():ReturnUI(slot0.awardEffect1.name, slot0.awardEffect1)
slot0.awardEffect1 = nil
end
if slot0.tipTimer then
slot0.tipTimer:Stop()
end
slot0.tipTimer = nil
slot1 = pairs
slot2 = slot0.timers or {}
for slot4, slot5 in slot1(slot2) do
slot5:Stop()
end
slot0.timers = nil
if slot0.player then
slot0.player:Dispose()
slot0.player = nil
end
if slot0.ground and not IsNil(slot0.groundGo) then
TowerClimbingResMgr.ReturnGround(slot0.ground.name, slot0.groundGo)
end
if slot0.blocks then
for slot4, slot5 in ipairs(slot0.blocks) do
if not IsNil(slot5.go) then
TowerClimbingResMgr.ReturnBlock(slot5.block.type, slot5.go)
end
end
slot0.blocks = nil
end
end
return slot0
|
function opponentNoteHit(id, direction, noteType, isSustainNote)
if difficulty == 2 then
if curBeat < 592 then
if curBeat > 528 then
cameraShake('cam', '0.015', '0.1')
end
end
if curBeat < 703 then
if curBeat > 688 then
cameraShake('cam', '0.015', '0.1')
end
end
end
end
function opponentNoteHit()
if mustHitSection == false then
health = getProperty('health')
if getProperty('health') > 0.5 then
setProperty('health', health- 0.04);
end
end
end
|
---@class ActionBar
C_ActionBar = {}
---@param flyoutID number
---@return number slots
function C_ActionBar.FindFlyoutActionButtons(flyoutID) end
---@param petActionID number
---@return number slots
function C_ActionBar.FindPetActionButtons(petActionID) end
---@param spellID number
---@return number slots
function C_ActionBar.FindSpellActionButtons(spellID) end
---@param slotID number
---@return number|nil bonusBarIndex
function C_ActionBar.GetBonusBarIndexForSlot(slotID) end
---@param petActionID number
---@return number slots
function C_ActionBar.GetPetActionPetBarIndices(petActionID) end
---@param flyoutID number
---@return boolean hasFlyoutActionButtons
function C_ActionBar.HasFlyoutActionButtons(flyoutID) end
---@param petActionID number
---@return boolean hasPetActionButtons
function C_ActionBar.HasPetActionButtons(petActionID) end
---@param petActionID number
---@return boolean hasPetActionPetBarIndices
function C_ActionBar.HasPetActionPetBarIndices(petActionID) end
---@param spellID number
---@return boolean hasSpellActionButtons
function C_ActionBar.HasSpellActionButtons(spellID) end
---@param slotID number
---@return boolean isAutoCastPetAction
function C_ActionBar.IsAutoCastPetAction(slotID) end
---@param slotID number
---@return boolean isEnabledAutoCastPetAction
function C_ActionBar.IsEnabledAutoCastPetAction(slotID) end
---@param actionID number
---@param useNeutral boolean
---@return boolean isHarmful
function C_ActionBar.IsHarmfulAction(actionID, useNeutral) end
---@param actionID number
---@param useNeutral boolean
---@return boolean isHelpful
function C_ActionBar.IsHelpfulAction(actionID, useNeutral) end
---@param spellID number
---@return boolean isOnBarOrSpecialBar
function C_ActionBar.IsOnBarOrSpecialBar(spellID) end
---@param slotID number
function C_ActionBar.PutActionInSlot(slotID) end
---@return boolean showHealthBar
function C_ActionBar.ShouldOverrideBarShowHealthBar() end
---@return boolean showManaBar
function C_ActionBar.ShouldOverrideBarShowManaBar() end
---@param slotID number
function C_ActionBar.ToggleAutoCastPetAction(slotID) end
|
local lfs = {
_VERSION = "LuaFileSystem 1.6.3 - FFI",
_DESCRIPTION = "LuaFileSystem-FFI is an implementation of LuaFileSystem functionality using LuaJIT FFI",
_COPYRIGHT = "LFS: Copyright (C) 2003-2015 Kepler Project LFSFFI: Copyright 2015 Pablo A. Mayobre",
_URL = "https://github.com/Positive07/lfs-ffi.lua"
}
local ffi = require "ffi"
local os = ffi.os == "Windows" and "windows" or "unix" --Simplify stuff (Probably shouldn't do so but fuck it for now)
local system = ({ --NOTE: You reading this should check the indexing in the closing bracket
windows = {
--Needs to be tested in x64 too!!
getcwd = "_getcwd",
chdir = "_chdir",
rmdir = "_rmdir",
mkdirn = "_mkdir",
mkdir = "_mkdir (const char *path);",
maxpath = 260,
timet = "typedef __int64 time_t;",
utimes = "_utimebuf",
utime = "_utime",
},
unix = {
getcwd = "getcwd",
chdir = "chdir",
rmdir = "rmdir",
mkdirn = "mkdir",
mkdir = "mkdir (const char *path, uint32_t mode);",
maxpath = 4096, --Good guy unix!
timet = "typedef long int time_t;", --Not sure if long int or long long int or __int32_t so fuck it!
utimes = "utimebuf",
utime = "utime",
}
})[os]
ffi.cdef(
[[
char *]] .. system.getcwd .. [[ ( char *buf, size_t size );
int ]] .. system.chdir .. [[ ( const char *path );
int ]] .. system.rmdir .. [[ (const char *pathname );
int ]] .. system.mkdir .. [[
]] .. system.timet .. [[
struct ]] .. system.utimes .. [[ { time_t actime; time_t modtime; };
int ]] .. system.utime .. [[ ( unsigned char *file, struct ]] .. system.utimes .. [[ *times );
]]
)
--(IMPLEMENTING STAT AND IT'S STRUCTURE IS WAY TOO HARD)
--lfs.attributes
--lfs.symlinkattributes
lfs.currentdir = function ()
local buff = ffi.new("char[?]", system.maxpath)
ffi.C[system.getcwd](buff, system.maxpath)
return ffi.string(buff)
end
lfs.chdir = function (path)
return ffi.C[system.chdir](path) == 0
end
if os == "windows" then
ffi.cdef[[
/* 32 bits only, should be reworked to support 64 bits */
typedef struct _finddata32_t {
uint32_t attrib;
uint32_t time_create; /* -1 for FAT file systems */
uint32_t time_access; /* -1 for FAT file systems */
uint32_t time_write;
uint32_t size;
char name[260];
} _finddata32_t;
int _findfirst32 (const char* filespec, _finddata32_t*);
int _findnext32 (int handle, struct _finddata32_t *fileinfo);
int _findclose (int handle);
]]
lfs.link = function () error("lfs.link is not supported in Windows systems", 1) end
lfs.setmode = function () return true, "binary" end --This is wrong! should be int _setmode(int _fileno(FILE *stream), int mode);
local iterator = function (dir)
if dir.type ~= "directory" then error() end
if dir.closed then error() end
local cfile = ffi.new("struct _finddata32_t")
if dir.hFile == 0 then --First entry
dir.hFile = ffi.C._findfirst32(dir.pattern, cfile)
if dir.hFile == -1 then
return nil, 'Couldn\'t get entries for the directory: "'.. dir.path ..'"'
else
return ffi.string(cfile.name)
end
else
dir.hFile = ffi.C._findnext32(dir.hFile, cfile)
if dir.hFile == -1 then
ffi.C._findclose(dir.hFile)
dir.closed = true
return nil
else
return ffi.string(cfile.name)
end
end
end
local close = function (dir)
if dir.type ~= "directory" then error() end
if not dir.closed and dir.hFile then
ffi.C._findclose(dir.hFile)
dir.closed = true
end
end
local fold = function (path)
return path
end
local dirmeta = {__index = {next = iterator, close = close}}
lfs.dir = function (path)
fold(path) --Windows path minimize (...8/8/8/8.3)
if #path > system.maxpath - 1 then error('The path passed to lfs.dir is too long: "'..#path..'"\n PATH:'..#path..", MAXPATH:"..system.maxpath, 2) end
local dir = setmetatable ({
type = "directory",
path = path,
pattern = path .. "/*",
closed = false,
hFile = 0,
}, dirmeta)
return iterator, dir, nil
end
else
ffi.cdef[[
int link (const char *oldname, const char *newname);
int symlink (const char *oldname, const char *newname);
typedef struct __dirstream DIR;
typedef int32_t off_t;
typedef uint32_t ino_t;
typedef off_t off64_t; /* Probably not usted but whatever */
typedef ino_t ino64_t; /* Probably not usted but whatever */
struct dirent {
ino_t d_ino;
off_t d_off;
unsigned short d_reclen;
unsigned char d_type;
char d_name[256];
};
DIR *opendir (const char *);
struct dirent *readdir (DIR *);
int closedir (DIR *);
]]
lfs.link = function (old, new, symlink)
local f = symlink and ffi.C.symlink or ffi.C.link
return f(old, new) == 0
end
lfs.setmode = function () return true, "binary" end
local iterator = function (dir)
if dir.type ~= "directory" then error() end
if dir.closed then error() end
local entry = ffi.C.readdir(dir.dir)
if entry ~= nil then
return ffi.string(entry.d_name)
else
ffi.C.closedir(dir.dir)
dir.closed = true
return
end
end
local close = function (dir)
if dir.type ~= "directory" then error() end
if not dir.closed and dir.dir then
ffi.C.closedir(dir.dir)
dir.closed = true
end
end
local dirmeta = {__index = {next = iterator, close = close}}
lfs.dir = function (path)
if #path > (system.maxpath - 1) then
error('The path passed to lfs.dir is too long: "'..#path..'"\n PATH:'..#path..", MAXPATH:"..system.maxpath, 2)
end
local dir = ffi.gc(ffi.C.opendir(path), ffi.C.closedir) --Needs to be GC'ed
if dir == nil then error('Couldn\'t open the directory: "'..path..'"', 2) end
local dir = setmetatable ({
type = "directory",
path = path,
dir = dir,
closed = false,
}, dirmeta)
return iterator, dir, nil
end
end
lfs.mkdir = function (path)
local fail
if os == "unix" then
fail = ffi.C[system.mkdirn](path, 509) --octal for 0775 User:RWX, Group:RWX, Other:RX
else
fail = ffi.C[system.mkdirn](path)
end
if fail ~= 0 then
return nil, 'Couldn\'t create the directory: "'..path..'"'
else
return true
end
end
lfs.rmdir = function (path)
local fail = ffi.C[system.rmdir](path)
if fail ~= 0 then
return nil, 'Couldn\'t remove the directory: "'..path..'"'
else
return true
end
end
lfs.touch = function (path, actime, modtime)
local buf
if type(actime) == "number" then
modtime = modtime or actime
buf = ffi.new("struct "..system.utimes)
buf.actime = actime
buf.modtime = modtime
end
local p = ffi.new("unsigned char[?]", #path + 1) --FFI complains if we dont do this first!
ffi.copy(p, path)
if ffi.C[system.utime](p, buf) ~= 0 then
return nil, 'Couldn\'t change the access and modification times of the file: "'..path..'"'
else
return true
end
end
return lfs
|
translate.AddLanguage("en", "English")
LANGUAGE.class_boss_tank = "The Tank"
LANGUAGE.description_boss_tank = "A mutated variant of the common infected that can single-handedly wipe an entire survivor team.\nIts abnormal muscle growth allows it to fling props, dismantle survivors, and resist damage at a distance."
LANGUAGE.controls_boss_tank = "> PRIMARY: Slam\n> SECONDARY: Rock throw\n> RELOAD: Rage\n> ON RAGE: Sprint, charge knockdown, increased rock throw intensity"
|
local rechargeModeLayer = require(ViewPath .. "hall/shortCutRecharge/rechargeModeLayer");
local payChannelIcons_pin_map = require("qnFiles/qnPlist/hall/payChannelIcons_pin");
local shortCutRecharge_pin_map = require("qnFiles/qnPlist/hall/shortCutRecharge_pin");
local rechargeModeItem = require(ViewPath .. "hall/shortCutRecharge/rechargeModeItem");
local RechargeModeItem = class(Node);
RechargeModeItem.ctor = function(self, pmodeInfo)
self.m_root = SceneLoader.load(rechargeModeItem);
self:addChild(self.m_root);
self:setSize(self.m_root:getSize());
self.m_itemBtn = self.m_root:getChildByName("modeItem");
self.m_modeIcon = self.m_itemBtn:getChildByName("icon");
self.m_modeName = self.m_itemBtn:getChildByName("name");
self.m_cornerMarkView = self.m_itemBtn:getChildByName("cornerMarkView");
self.m_modeName:setPickable(false);
self.m_recommended = self.m_itemBtn:getChildByName("recommended");
self.m_modeName:setText(pmodeInfo.name);
self.m_modeIcon:setFile(pmodeInfo.icon);
self.m_validPament = true;
if pmodeInfo.id == PayConfig.ePayMode.LOCAL_CRYSTAL_PMODE then
if pmodeInfo.cornerMark == "" or pmodeInfo.cornerMark == "0" or pmodeInfo.cornerMark == nil then
self.m_recommended:setVisible(true);
else
local m_cornerMark = new(UrlImage, "hall/common/bg_blank.png" ,pmodeInfo.cornerMark);
m_cornerMark:setSize( self.m_cornerMarkView:getSize() );
self.m_cornerMarkView:addChild(m_cornerMark);
end
local hasEnoughCrystal = kUserInfoData:getCrystal() >= pmodeInfo.num and true or false;
if not hasEnoughCrystal then
self.m_itemBtn:setGray(true);
self.m_modeIcon:setGray(true);
self.m_itemBtn:setPickable(false);
self.m_validPament = false;
self.m_recommended:setVisible(false);
end
end
self.m_pmodeInfo = pmodeInfo;
end
RechargeModeItem.getData = function(self)
return self.m_pmodeInfo;
end
RechargeModeItem.isValidPayment = function(self)
return self.m_validPament;
end
----------------------------------------------------------------------------
local RechargeModeLayer = class(CommonGameLayer, false);
local h_index = 0;
local getIndex = function(self)
h_index = h_index + 1;
return h_index;
end
RechargeModeLayer.Delegate = {
onRechargeModeLayerClose = "onRechargeModeLayerClose";
onSelectPayMode = "onSelectPayMode";
}
RechargeModeLayer.s_controls = {
shadeBg = getIndex();
centerView = getIndex();
modeView = getIndex();
goodsDesc = getIndex();
price = getIndex();
closeBtn = getIndex();
}
RechargeModeLayer.ctor = function(self)
super(self, rechargeModeLayer);
self:setFillParent(true, true);
self.m_ctrl = RechargeModeLayer.s_controls;
self:getControl(self.m_ctrl.shadeBg):setEventTouch(nil , function()
end);
self:getControl(self.m_ctrl.shadeBg):setEventDrag(nil , function()
end);
end
RechargeModeLayer.dtor = function(self)
end
RechargeModeLayer.show = function(self, goodsInfo)
Log.v("RechargeModeLayer.show", " goodsInfo = ", goodsInfo);
CommonGameLayer.show(self);
if table.isEmpty(goodsInfo) then
self:onCloseBtnClick();
return;
end
self.m_goodsInfo = goodsInfo;
self:__initView();
end
RechargeModeLayer.__initView = function(self)
local strGoodsDesc = self.m_goodsInfo.name;
if not string.isEmpty(self.m_goodsInfo.priorityDesc) then
strGoodsDesc = strGoodsDesc .. "+" .. self.m_goodsInfo.priorityDesc;
end
self:findViewById(self.m_ctrl.goodsDesc):setText(strGoodsDesc);
self:findViewById(self.m_ctrl.price):setText(self.m_goodsInfo.pamount .."元");
System.setImageFormatPicker(function()
return kRGBGray;
end);
--加一个元素
for k,v in pairs( self.m_goodsInfo.pmodes ) do
v.cornerMark = self.m_goodsInfo.crystalIcon;
end
self:__createPayModeView(self.m_goodsInfo.pmodes);
System.setImageFormatPicker(nil);
end
RechargeModeLayer.__createPayModeView = function(self, pmodes)
local modeView = self:findViewById(self.m_ctrl.modeView);
if table.isEmpty(pmodes) then
modeView:setVisible(false);
return;
end
modeView:setVisible(true);
local w, h = modeView:getSize();
if not self.m_adapter then
self.m_adapter = UIFactory.createCacheAdapter(RechargeModeItem, pmodes);
local gridView = UIFactory.createGridView(0,0,w,h);
modeView:addChild(gridView);
gridView:setAdapter(self.m_adapter);
gridView:setOnItemClick(self, self.onPayModeItemClick);
else
self.m_adapter:changeData(pmodes);
end
end
RechargeModeLayer.onPayModeItemClick = function(self, adapter, view, index)
if view:isValidPayment() then
local pmodeInfo = view:getData();
self:execDelegate(RechargeModeLayer.Delegate.onSelectPayMode, pmodeInfo.id);
end
end
RechargeModeLayer.onCloseBtnClick = function(self)
self:execDelegate(RechargeModeLayer.Delegate.onRechargeModeLayerClose, true);
end
RechargeModeLayer.s_controlConfig = {
[RechargeModeLayer.s_controls.shadeBg] = {"shade_bg"};
[RechargeModeLayer.s_controls.centerView] = {"centerView"};
[RechargeModeLayer.s_controls.modeView] = {"centerView", "modeViewBg", "modeView"};
[RechargeModeLayer.s_controls.goodsDesc] = {"centerView", "bottomView", "goodsDesc"};
[RechargeModeLayer.s_controls.price] = {"centerView", "bottomView", "price"};
[RechargeModeLayer.s_controls.closeBtn] = {"centerView", "closeBtn"};
}
RechargeModeLayer.s_controlFuncMap = {
[RechargeModeLayer.s_controls.closeBtn] = RechargeModeLayer.onCloseBtnClick;
}
return RechargeModeLayer;
|
ESX = nil
local data = {}
local inventoryBusy = {}
local ammo
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
ESX.RegisterServerCallback('esx_armories:isInventoryBusy', function(source, cb, code)
if (inventoryBusy[code] == true) then
cb(true)
else
cb(false)
end
end)
RegisterServerEvent('esx_armories:inventoryBusy')
AddEventHandler('esx_armories:inventoryBusy', function(code, bool)
inventoryBusy[code] = bool
end)
RegisterNetEvent('esx_armories:remove:swapItems')
AddEventHandler('esx_armories:remove:swapItems', function(item, count, code)
local xPlayer = ESX.GetPlayerFromId(source)
local inventoryItem = xPlayer.getInventoryItem(item).count
if inventoryItem >= count then
xPlayer.removeInventoryItem(item, count)
for i=1, count do
MySQL.Async.execute('INSERT INTO storage (code, item, type) VALUES (@code, @item, @type)', {
['@code'] = code,
['@item'] = item,
['@type'] = 'item'
})
end
else
TriggerClientEvent('esx:showNotification', xPlayer.source, 'Invalid Quantity')
end
end)
RegisterNetEvent('esx_armories:remove:swapWeapons')
AddEventHandler('esx_armories:remove:swapWeapons', function(item, code, ammo)
local xPlayer = ESX.GetPlayerFromId(source)
xPlayer.removeWeapon(item)
MySQL.Async.execute('INSERT INTO storage (code, item, type, ammo) VALUES (@code, @item, @type, @ammo)', {
['@code'] = code,
['@item'] = item,
['@type'] = 'weapon',
['@ammo'] = ammo
})
end)
RegisterNetEvent('esx_armories:add:swapWeapons')
AddEventHandler('esx_armories:add:swapWeapons', function(item, code)
local xPlayer = ESX.GetPlayerFromId(source)
MySQL.Async.fetchAll('SELECT ammo FROM storage WHERE code = @code AND item = @item', {
['@code'] = code,
['@item'] = item
}, function(result)
if result[1] ~= nil then
for k,v in pairs(result[1]) do
ammo = v
end
end
end)
Wait(400)
if not xPlayer.hasWeapon(item) then
xPlayer.addWeapon(item, tonumber(ammo))
MySQL.Async.execute('DELETE FROM storage WHERE code = @code AND item = @item LIMIT 1', {
['@code'] = code,
['@item'] = item
})
else
TriggerClientEvent('esx:showNotification', xPlayer.source, 'You already have this weapon')
end
end)
RegisterNetEvent('esx_armories:add:swapItems')
AddEventHandler('esx_armories:add:swapItems', function(item, count, code)
local xPlayer = ESX.GetPlayerFromId(source)
local sourceItem = xPlayer.getInventoryItem(item)
MySQL.Async.fetchAll('SELECT * FROM storage WHERE code = @code AND item = @item', {
['@code']= code,
['@item'] = item
}, function(result)
if result ~= nil then
local amount = 0
for k, v in pairs(result) do
amount = amount + 1
end
if amount >= count then
if sourceItem.limit < count then
TriggerClientEvent('esx:showNotification', xPlayer.source, 'Invalid Quantity')
return
end
if sourceItem.limit ~= -1 and (sourceItem.count + count) > sourceItem.limit then
TriggerClientEvent('esx:showNotification', xPlayer.source, 'Invalid Quantity')
else
xPlayer.addInventoryItem(item, count)
TriggerClientEvent('esx:showNotification', xPlayer.source, 'You have withdrawn x'..count..' '..item)
for i=1, count do
MySQL.Async.execute('DELETE FROM storage WHERE code = @code AND item = @item LIMIT '..tostring(count), {
['@code'] = code,
['@item'] = item
})
break
end
end
end
end
end)
end)
ESX.RegisterServerCallback('esx_armories:getServerData', function(source, cb)
cb(data)
end)
ESX.RegisterServerCallback('esx_armories:getInventory', function(source, cb)
local xPlayer = ESX.GetPlayerFromId(source)
cb(xPlayer.getInventory())
end)
RegisterCommand('changecode', function(source, args, rawCommand)
if args[1] ~= nil and string.len(args[1]) == 4 then
local xPlayer = ESX.GetPlayerFromId(source)
local senderIdentifier = getSteamIdentifier(xPlayer.source)
local newCode = tostring(args[1])
for k, v in pairs(data) do
if senderIdentifier == v.identifier then
MySQL.Async.fetchAll('SELECT * FROM warehouses WHERE identifier = @identifier', {
['@identifier'] = senderIdentifier
}, function(result)
if result ~= nil then
for k, v in pairs(result) do
local oldCode = tostring(v.code)
local oldLocation = vector3(v.x, v.y, v.z)
MySQL.Async.execute('UPDATE warehouses SET code = @code WHERE identifier = @identifier', {
['@code'] = newCode,
['@identifier'] = senderIdentifier,
['@label'] = v.label
}, function(result)
data[oldCode] = nil
data[newCode] = {
identifier = senderIdentifier,
location = oldLocation,
label = v.label
}
TriggerClientEvent('esx:showNotification', xPlayer.source, 'You successfully set your new code to ' .. newCode)
end)
MySQL.Async.execute('UPDATE storage SET code = @code2 WHERE code = @code', {
['@code2'] = newCode,
['@code'] = oldCode
})
end
end
end)
end
end
TriggerClientEvent('esx:showNotification', xPlayer.source, 'You don\'t own a warehouse')
end
end, false)
ESX.RegisterServerCallback('esx_armories:getStorageInventory', function(source, cb, code)
MySQL.Async.fetchAll('SELECT * FROM storage WHERE code = @code', {
['@code'] = code
}, function(result)
local items = {}
if result ~= nil then
for k, v in pairs(result) do
if v.type == 'item' then
if items[v.item] then
items[v.item] = items[v.item] + 1
else
items[v.item] = 1
end
end
end
cb(items)
else
cb(items)
end
end)
end)
ESX.RegisterServerCallback('esx_armories:getWeaponInventory', function(source, cb)
local xPlayer = ESX.GetPlayerFromId(source)
cb(xPlayer.getLoadout())
end)
ESX.RegisterServerCallback('esx_armories:getWeaponStorageInventory', function(source, cb, code)
MySQL.Async.fetchAll('SELECT * FROM storage WHERE code = @code', {
['@code'] = code
}, function(result)
local items = {}
if result ~= nil then
for k, v in pairs(result) do
if v.type == 'weapon' then
if items[v.item] then
items[v.item] = items[v.item] + 1
else
items[v.item] = 1
end
end
end
cb(items)
else
cb(items)
end
end)
end)
ESX.RegisterUsableItem('warehouse', function(source)
local xPlayer = ESX.GetPlayerFromId(source)
TriggerClientEvent('esx_armories:Itemtoclient', xPlayer.source, 1)
end)
RegisterServerEvent('esx_armories:updateLocation')
AddEventHandler('esx_armories:updateLocation', function(code, x, y, z)
local xPlayer = ESX.GetPlayerFromId(source)
MySQL.Async.execute('UPDATE warehouses SET x=@x,y=@y,z=@z WHERE code=@code',{
['@code'] = code,
['@x'] = x,
['@y'] = y,
['@z'] = z
})
Wait(3000)
xPlayer.showNotification('Armory moved successfully')
TriggerClientEvent('esx_armories:allowLoop', -1)
end)
RegisterNetEvent('esx_armories:insertArmory')
AddEventHandler('esx_armories:insertArmory', function(code, label, coords)
local xPlayer = ESX.GetPlayerFromId(source)
local xItem = xPlayer.getInventoryItem('warehouse')
local crew = MySQL.Sync.fetchScalar('SELECT crew FROM users WHERE identifier = @identifier', {['@identifier'] = xPlayer.identifier})
MySQL.Async.fetchAll('SELECT * FROM warehouses WHERE code = @code', {
['@code'] = code
}, function(results)
if (#results > 0) then
TriggerClientEvent('esx:showNotification', xPlayer.source, 'You can\'t use that password!')
else
MySQL.Async.fetchAll('SELECT * FROM warehouses WHERE identifier = @identifier', {
['@identifier'] = getSteamIdentifier(xPlayer.source)
}, function(results)
if (#results > 0) then
TriggerClientEvent('esx:showNotification', xPlayer.source, 'You can\'t have more than one armory!')
else
MySQL.Async.execute('INSERT INTO warehouses (identifier,label, code, x, y, z, crew) VALUES (@identifier,@label, @code, @x, @y, @z, @crew)', {
['@identifier'] = getSteamIdentifier(xPlayer.source),
['@label'] = label,
['@code'] = code,
['@x'] = coords.x,
['@y'] = coords.y,
['@z'] = coords.z - 0.97,
['@crew'] = crew
}, function(affectedRows)
if xItem.count > 0 then
xPlayer.removeInventoryItem('warehouse', 1)
TriggerClientEvent('esx_armories:allowLoop', -1)
data[code] = {
identifier = getSteamIdentifier(xPlayer.source),
location = vector3(coords.x, coords.y, coords.z-0.97),
label = label
}
TriggerClientEvent('esx:showNotification', xPlayer.source, 'Your armory has been successfully created!')
print("[^4"..GetCurrentResourceName().."^7] Armory created with code : ^4"..code.."^7 and label : ^4"..label.."^7")
end
end)
end
end)
end
end)
end)
RegisterCommand('deletearmory', function(source, args, rawCommand)
local xPlayer = ESX.GetPlayerFromId(source)
local senderIdentifier = getSteamIdentifier(xPlayer.source)
for k, v in pairs(data) do
if senderIdentifier == v.identifier then
MySQL.Async.fetchAll('SELECT * FROM warehouses WHERE identifier = @identifier', {
['@identifier'] = senderIdentifier
}, function(result)
if result ~= nil then
for k, v in pairs(result) do
local code = tostring(v.code)
MySQL.Async.execute('DELETE FROM warehouses WHERE identifier = @identifier', {
['@identifier'] = senderIdentifier
}, function(result)
MySQL.Async.execute('DELETE FROM storage WHERE code = @code', {
['@code'] = code
}, function(result)
data[code] = nil
TriggerClientEvent('esx_armories:allowLoop', -1)
TriggerClientEvent('esx:showNotification', xPlayer.source, 'Your warehouse has been deleted')
end)
end)
end
end
end)
return
end
end
TriggerClientEvent('esx:showNotification', xPlayer.source, 'You do not own a warehouse')
end, false)
MySQL.ready(function()
MySQL.Async.fetchAll('SELECT * FROM warehouses', {}, function(result)
if result ~= nil then
for k, v in pairs(result) do
local location = vector3(v.x, v.y, v.z)
local code = tostring(v.code)
local label = v.label
local identifier = tostring(v.identifier)
data[code] = {
identifier = identifier,
location = location,
label = label
}
end
end
end)
end)
RegisterCommand('removearmory', function(source, args, rawCommand)
local xPlayer = ESX.GetPlayerFromId(source)
local code = tonumber(args[1])
if xPlayer.getGroup() ~= 'user' then
for k, v in pairs(data) do
MySQL.Async.fetchAll('SELECT * FROM warehouses WHERE code = @code', {
['@code'] = code
}, function(result)
if result ~= nil then
for k, v in pairs(result) do
local code = tostring(v.code)
MySQL.Async.execute('DELETE FROM warehouses WHERE code = @code', {
['@code'] = code
}, function(result)
MySQL.Async.execute('DELETE FROM storage WHERE code = @code', {
['@code'] = code
}, function(result)
data[code] = nil
TriggerClientEvent('esx:showNotification', xPlayer.source, 'You removed the warehouse with code : ' .. code .. '')
TriggerClientEvent('esx_armories:allowLoop', -1)
end)
end)
end
end
end)
end
else
TriggerClientEvent('esx:showNotification', xPlayer.source, 'No permissions')
end
end)
RegisterCommand('refresharmories', function(source, args, rawCommand)
local xPlayer = ESX.GetPlayerFromId(source)
if xPlayer.getGroup() ~= 'user' then
TriggerClientEvent('esx_armories:allowLoop', -1)
end
end)
function getSteamIdentifier(id)
local identifiers = {}
for i = 0, GetNumPlayerIdentifiers(id) - 1 do
local raw = GetPlayerIdentifier(id, i)
local source, value = raw:match("^([^:]+):(.+)$")
if source and value then
identifiers[source] = value
end
end
return identifiers.steam
end
|
-- BLUA Scripting Project
-- Part of OutlandZoning Division
-- Scripted by Hellgawd
-- Give full credits if posting
function UmbOrcale_OnKill(pUnit,Event)
pUnit:RemoveEvents();
end
function UmbOrcale_EnterCombat(pUnit,Event)
pUnit:RegisterEvent("hittest_1",1000, 0)
pUnit:CastSpell(12550)
end
function hittest_1(pUnit, Event)
if pUnit:GetHealthPct() < 15 then
pUnit:RemoveEvents();
pUnit:CastSpell(26097)
end
end
function UmbOrcale_Start(pUnit, Event)
pUnit:RegisterEvent("hittest_1",1000, 0)
end
RegisterUnitEvent(18077, 1, "UmbOrcale_Start")
RegisterUnitEvent(18077, 3, "UmbOrcale_OnKill")
RegisterUnitEvent(18077, 1, "UmbOrcale_EnterCombat")
|
local AddonName, AddonTable = ...
AddonTable.nighthold = {
144403,
-- Skorpyron
140902,
140901,
140884,
140849,
140888,
140790,
140827,
140898,
140815,
140875,
140876,
140789,
140840,
140862,
-- Chronomatic Anomaly
140791,
140843,
140860,
140872,
140821,
140903,
140853,
140863,
140879,
140831,
140848,
140894,
140792,
140882,
138828,
-- Trilliax
143577,
143579,
143578,
140869,
140880,
140904,
140854,
140838,
140871,
140851,
140812,
140818,
140793,
140865,
140794,
140858,
138366,
138369,
138370,
138373,
138375,
138371,
138364,
138368,
138372,
138374,
138365,
138367,
-- Spellblade Aluriel
140795,
140813,
140850,
140877,
140878,
140868,
140796,
140905,
140832,
140852,
140866,
140867,
140834,
140895,
-- Star Augur Etraeus
143563,
143567,
143573,
140900,
140841,
140885,
140845,
140909,
140864,
140891,
140833,
140803,
140804,
138340,
138327,
138309,
138353,
138377,
138311,
138329,
138352,
138341,
138354,
138328,
138310,
-- High Botanist Tel'arn
140822,
140881,
140801,
140861,
140802,
140839,
140896,
140873,
140883,
140836,
140874,
140908,
140886,
-- Krosus
140870,
140899,
138350,
140907,
138351,
138326,
138349,
138339,
140825,
138320,
140816,
140887,
140799,
140800,
138319,
138346,
138318,
138324,
138325,
138376,
140835,
140857,
-- Tichondrius
143566,
143570,
143576,
140855,
140798,
140906,
140797,
140819,
140824,
140859,
140844,
140892,
138347,
138362,
138323,
138336,
138322,
138380,
138338,
138321,
138361,
138337,
138348,
138363,
-- Elisande
140890,
140889,
140910,
140842,
140806,
138332,
138355,
138342,
140805,
140893,
140837,
138314,
140810,
138343,
138356,
138331,
138312,
138330,
140911,
138378,
138313,
140912,
138357,
-- Gul'dan
140913,
138335,
140808,
138358,
138344,
140826,
137575,
140919,
140807,
138317,
138334,
138315,
138345,
138333,
138359,
138360,
138379,
140817,
140917,
140914,
140820,
138316,
140897,
140823,
140809,
137574,
}
|
local util = require("spec.util")
describe("tl.loader", function()
setup(util.chdir_setup)
teardown(util.chdir_teardown)
describe("on .tl files", function()
it("reports filename correctly in debug info (#508)", function()
local dir_name = util.write_tmp_dir(finally, {
["file1.tl"] = [[
return {
get_src = function()
return debug.getinfo(1, "S").source
end
}
]],
["main.lua"] = [[
local tl = require("tl")
tl.loader()
file1 = require("file1")
print(file1.get_src())
]]
})
local pd, output
util.do_in(dir_name, function()
pd = io.popen(util.lua_cmd("main.lua"), "r")
output = pd:read("*a")
end)
util.assert_popen_close(0, pd:close())
util.assert_line_by_line([[
@./file1.tl
]], output)
end)
end)
end)
|
-- The Computer Language Benchmarks Game
-- http://benchmarksgame.alioth.debian.org/
-- contributed by Mike Pall
local function domandel(pfunc)
local width = 4000
local height, wscale = width, 2.0/width
local m, limit2 = 50, 4.0
--local write, char = io.write, string.char
for y=0,height-1 do
local Ci = 2.0*y / height - 1
for xb=0,width-1,8 do
local bits = 0
local xbb = xb+7
local xblimit
if xbb < width then
xblimit = xbb
else
xblimit = width-1
end
for x=xb,xblimit do
bits = bits + bits
local Zr, Zi, Zrq, Ziq = 0.0, 0.0, 0.0, 0.0
local Cr = x * wscale - 1.5
for i=1,m do
local Zri = Zr*Zi
Zr = Zrq - Ziq + Cr
Zi = Zri + Zri + Ci
Zrq = Zr*Zr
Ziq = Zi*Zi
if Zrq + Ziq > limit2 then
bits = bits + 1
break
end
end
end
if xbb >= width then
for x=width,xbb do bits = bits + bits + 1 end
end
--pfunc(bits)
end
end
end
if ravi then
ravi.compile(domandel)
end
if jit then
-- LuaJIT warmup
domandel(print)
end
t1 = os.clock()
domandel(print)
t2 = os.clock()
print(t2-t1)
|
local Modules = game:GetService("Players").LocalPlayer.PlayerGui.AvatarEditorInGame.Modules
local RoactServices = require(Modules.Common.RoactServices)
local service = RoactServices.createService(script.Name)
return service
|
!# /usr/bin/luajit
dvin=require('dvin')
|
-- lua/rs/Shade.lua
if Server then
-- SHADE
local originalShadeOnInitialized = Shade.OnInitialized
function Shade:OnInitialized()
originalShadeOnInitialized(self)
InitMixin(self, SleeperMixin)
end
function Shade:GetCanSleep()
return not self.moving and self:GetIsBuilt() and not self:GetHasOrder() and self:GetIsAlive() and not self.isRepositioning
end
function Shade:OnOrderGiven(order)
if order then
self:WakeUp()
end
end
-- END SHADE
end
|
electrician_energy_absorption = class({})
LinkLuaModifier("modifier_electrician_energy_absorption", "heroes/electrician/electrician_energy_absorption.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_electrician_energy_absorption_debuff", "heroes/electrician/electrician_energy_absorption.lua", LUA_MODIFIER_MOTION_NONE)
LinkLuaModifier("modifier_electrician_bonus_mana_count", "heroes/electrician/electrician_energy_absorption.lua", LUA_MODIFIER_MOTION_NONE)
--------------------------------------------------------------------------------
function electrician_energy_absorption:GetCooldown(level)
local caster = self:GetCaster()
local base_cooldown = self.BaseClass.GetCooldown(self, level)
-- Talent that decreases cooldown
local talent = caster:FindAbilityByName("special_bonus_electrician_energy_absorption_cooldown")
if talent and talent:GetLevel() > 0 then
return base_cooldown - math.abs(talent:GetSpecialValueFor("value"))
end
return base_cooldown
end
function electrician_energy_absorption:OnSpellStart()
local caster = self:GetCaster()
local casterOrigin = caster:GetAbsOrigin()
local radius = self:GetSpecialValueFor("radius")
-- grab all enemes around the caster
local units = FindUnitsInRadius(
caster:GetTeamNumber(),
casterOrigin,
nil,
radius,
self:GetAbilityTargetTeam(),
self:GetAbilityTargetType(),
DOTA_UNIT_TARGET_FLAG_NONE,
FIND_ANY_ORDER,
false
)
-- Generic aoe particle
local part = ParticleManager:CreateParticle( "particles/econ/generic/generic_aoe_explosion_sphere_1/generic_aoe_explosion_sphere_1.vpcf", PATTACH_ABSORIGIN, caster )
ParticleManager:SetParticleControl( part, 1, Vector( radius, radius, radius ) )
ParticleManager:SetParticleControl( part, 2, Vector( 1, 1, 1 ) )
ParticleManager:ReleaseParticleIndex( part )
-- play sound
caster:EmitSound( "Hero_StormSpirit.StaticRemnantPlant" )
-- don't bother with anything after this if we didnt' hit a single enemy
if #units > 0 then
-- grab abilityspecials
local damage = self:GetSpecialValueFor("damage")
local damageType = self:GetAbilityDamageType()
local mana_absorb_base = self:GetSpecialValueFor("mana_absorb_base")
local mana_absorb_percent = self:GetSpecialValueFor("mana_absorb_percentage")
local speed_absorb_creeps = self:GetSpecialValueFor("speed_absorb_non_heroes")
local speed_absorb_heroes = self:GetSpecialValueFor("speed_absorb_heroes")
local duration = self:GetSpecialValueFor("duration")
-- Talent that increases mana absorb
local talent = caster:FindAbilityByName("special_bonus_electrician_energy_absorption_mana")
if talent and talent:GetLevel() > 0 then
mana_absorb_percent = mana_absorb_percent + talent:GetSpecialValueFor("value")
end
-- set up the amount of mana restored by this cast
local mana_absorbed = 0
local speed_absorbed = 0
-- iterate through each unit struck
for _, target in pairs( units ) do
if target and not target:IsNull() then
-- Get mana values of the target
local target_max_mana = target:GetMaxMana()
local mana_to_remove = mana_absorb_base + target_max_mana*mana_absorb_percent*0.01
local target_current_mana = target:GetMana()
-- Check if target has less mana
if target_current_mana < mana_to_remove then
mana_to_remove = target_current_mana
end
-- Reduce/removed mana of the target (only if not an illusion)
-- Don't remove mana from illusions to prevent weird interactions
if not target:IsIllusion() then
target:ReduceMana(mana_to_remove)
mana_absorbed = mana_absorbed + mana_to_remove
end
if target:IsRealHero() or target:IsCustomBoss() or target:IsRoshan() then
speed_absorbed = speed_absorbed + speed_absorb_heroes
else
speed_absorbed = speed_absorbed + speed_absorb_creeps
end
-- for the mana burn number; restricting to heroes as to
-- reduce spam, can't ignore illusions tho because
-- that'd make it too obvious
if target:IsHero() then
mana_to_remove = math.floor(mana_to_remove)
local numLength = tostring(mana_to_remove):len() + 1
-- Mana burn particle
local partNum = ParticleManager:CreateParticle("particles/units/heroes/hero_nyx_assassin/nyx_assassin_mana_burn_msg.vpcf", PATTACH_OVERHEAD_FOLLOW, target)
ParticleManager:SetParticleControl(partNum, 1, Vector( 1, mana_to_remove, 0 ))
ParticleManager:SetParticleControl(partNum, 2, Vector( 1, numLength, 0 ))
ParticleManager:ReleaseParticleIndex(partNum)
end
-- Add a speed debuff
local speed_debuff = target:FindModifierByNameAndCaster("modifier_electrician_energy_absorption_debuff", caster)
if speed_debuff then
speed_debuff:SetDuration(duration, true)
speed_debuff:SetStackCount(speed_debuff:GetStackCount() + 1)
else
speed_debuff = target:AddNewModifier(caster, self, "modifier_electrician_energy_absorption_debuff", {duration = duration})
if speed_debuff then
speed_debuff:SetStackCount(1)
end
end
-- deal damage
ApplyDamage( {
victim = target,
attacker = caster,
damage = damage,
damage_type = damageType,
damage_flags = DOTA_DAMAGE_FLAG_NONE,
ability = self,
} )
-- play hit sound
target:EmitSound( "Hero_StormSpirit.Attack" )
end
end
-- Check how much mana does the caster have, add excess mana modifier if needed
local missing_mana = caster:GetMaxMana() - caster:GetMana()
if missing_mana < mana_absorbed then
local modifier = caster:FindModifierByName("modifier_electrician_bonus_mana_count")
if modifier then
modifier:SetDuration(duration, true)
modifier:SetStackCount(math.min(modifier:GetStackCount() + mana_absorbed - missing_mana, self:GetSpecialValueFor("bonus_mana_cap")))
else
modifier = caster:AddNewModifier(caster, self, "modifier_electrician_bonus_mana_count", {duration = duration})
if modifier then
modifier:SetStackCount(math.min(mana_absorbed - missing_mana, self:GetSpecialValueFor("bonus_mana_cap")))
end
end
caster:CalculateStatBonus(true)
end
-- Grant mana to the caster (equal to absorbed mana)
caster:GiveMana(mana_absorbed)
-- Overhead message
SendOverheadEventMessage(caster:GetPlayerOwner(), OVERHEAD_ALERT_MANA_ADD, caster, mana_absorbed, nil)
-- give the speed modifier
local speed_modifier = caster:FindModifierByName("modifier_electrician_energy_absorption")
if speed_modifier then
speed_modifier:SetDuration(duration, true)
speed_modifier:SetStackCount(speed_modifier:GetStackCount() + speed_absorbed)
else
speed_modifier = caster:AddNewModifier(caster, self, "modifier_electrician_energy_absorption", {duration = duration})
if speed_modifier then
speed_modifier:SetStackCount(speed_absorbed)
end
end
end
end
---------------------------------------------------------------------------------------------------
modifier_electrician_energy_absorption = class({})
function modifier_electrician_energy_absorption:IsDebuff()
return false
end
function modifier_electrician_energy_absorption:IsHidden()
return false
end
function modifier_electrician_energy_absorption:IsPurgable()
return true
end
function modifier_electrician_energy_absorption:OnCreated(event)
local parent = self:GetParent()
self.partShell = ParticleManager:CreateParticle("particles/hero/electrician/electrician_energy_absorbtion.vpcf", PATTACH_ABSORIGIN_FOLLOW, parent)
ParticleManager:SetParticleControlEnt(self.partShell, 1, parent, PATTACH_ABSORIGIN_FOLLOW, nil, parent:GetAbsOrigin(), true)
end
function modifier_electrician_energy_absorption:OnRefresh(event)
-- destroy the shield particles
if self.partShell then
ParticleManager:DestroyParticle(self.partShell, false)
ParticleManager:ReleaseParticleIndex(self.partShell)
end
self:OnCreated(event)
end
function modifier_electrician_energy_absorption:OnDestroy()
-- destroy the shield particles
if self.partShell then
ParticleManager:DestroyParticle(self.partShell, false)
ParticleManager:ReleaseParticleIndex(self.partShell)
end
end
function modifier_electrician_energy_absorption:DeclareFunctions()
local func = {
MODIFIER_PROPERTY_MOVESPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
}
return func
end
function modifier_electrician_energy_absorption:GetModifierMoveSpeedBonus_Constant()
return self:GetStackCount()
end
function modifier_electrician_energy_absorption:GetModifierAttackSpeedBonus_Constant()
return self:GetStackCount()
end
---------------------------------------------------------------------------------------------------
modifier_electrician_energy_absorption_debuff = class({})
function modifier_electrician_energy_absorption_debuff:IsDebuff()
return true
end
function modifier_electrician_energy_absorption_debuff:IsHidden()
return false
end
function modifier_electrician_energy_absorption_debuff:IsPurgable()
return true
end
function modifier_electrician_energy_absorption_debuff:OnCreated(event)
local parent = self:GetParent()
self.partShell = ParticleManager:CreateParticle("particles/hero/electrician/electrician_energy_absorbtion.vpcf", PATTACH_ABSORIGIN_FOLLOW, parent)
ParticleManager:SetParticleControlEnt(self.partShell, 1, parent, PATTACH_ABSORIGIN_FOLLOW, nil, parent:GetAbsOrigin(), true)
local ability = self:GetAbility()
local speed_absorb_creeps = 5
local speed_absorb_heroes = 10
if ability and not ability:IsNull() then
speed_absorb_creeps = ability:GetSpecialValueFor("speed_absorb_non_heroes")
speed_absorb_heroes = ability:GetSpecialValueFor("speed_absorb_heroes")
end
local stack_count = self:GetStackCount()
if parent:IsRealHero() or parent:IsCustomBoss() or parent:IsRoshan() then
self.speed = -speed_absorb_heroes * stack_count
else
self.speed = -speed_absorb_creeps * stack_count
end
end
function modifier_electrician_energy_absorption_debuff:OnRefresh(event)
-- destroy the shield particles
if self.partShell then
ParticleManager:DestroyParticle(self.partShell, false)
ParticleManager:ReleaseParticleIndex(self.partShell)
end
self:OnCreated(event)
end
function modifier_electrician_energy_absorption_debuff:OnDestroy()
-- destroy the shield particles
if self.partShell then
ParticleManager:DestroyParticle(self.partShell, false)
ParticleManager:ReleaseParticleIndex(self.partShell)
end
end
function modifier_electrician_energy_absorption_debuff:DeclareFunctions()
local func = {
MODIFIER_PROPERTY_MOVESPEED_BONUS_CONSTANT,
MODIFIER_PROPERTY_ATTACKSPEED_BONUS_CONSTANT,
}
return func
end
function modifier_electrician_energy_absorption_debuff:GetModifierMoveSpeedBonus_Constant()
return self.speed
end
function modifier_electrician_energy_absorption_debuff:GetModifierAttackSpeedBonus_Constant()
return self.speed
end
---------------------------------------------------------------------------------------------------
modifier_electrician_bonus_mana_count = class({})
function modifier_electrician_bonus_mana_count:IsHidden()
return false
end
function modifier_electrician_bonus_mana_count:IsDebuff()
return false
end
function modifier_electrician_bonus_mana_count:IsPurgable()
return false
end
function modifier_electrician_bonus_mana_count:DeclareFunctions()
local funcs = {
MODIFIER_PROPERTY_EXTRA_MANA_BONUS,
MODIFIER_EVENT_ON_SPENT_MANA
}
return funcs
end
function modifier_electrician_bonus_mana_count:GetModifierExtraManaBonus()
return self:GetStackCount()
end
function modifier_electrician_bonus_mana_count:OnSpentMana(event)
if IsServer() then
if event.unit == self:GetParent() then
local restore_amount = event.cost
if restore_amount > self:GetStackCount() then
self:Destroy()
else
self:SetStackCount(self:GetStackCount() - restore_amount)
end
end
end
end
|
-- (done) window
-- TODO: make the window topmost
-- (done) receiving drag&drop - should display drag&drop info details
-- (done) the window should accept drag & drop of selected fragment of webpage
-- from firefox ("HTML Format" 0x18b -- see also ClipSpy.exe)
-- See: http://delphidabbler.com/articles?article=24
-- TODO: should then convert the HTML to Markdown
-- (done) should display the Markdown in textarea, with possibility of editing
-- (done) should provide button to append into an .md file, with <a
-- name="DATETIME"/> anchor [ideally as a markdown extension, e.g. [#...] or
-- pandoc's {#...} or [](...) or [][...] or [](#...) or #... or []{#...} or something]
-- TODO: [LATER]: use SQLite to save bookmarks with full text search & display
-- them for browsing & clicking.
-- TODO: invent some interface (GUI) for browsing the SQLite DB (grepping the list of bookmarks)
-- TODO: invent interface for editing; write a copy of file, then remove old, when updating
-- TODO: [LATER] tray icon
FILE = '/Mateusz/bmark.md'
local ffi = require 'ffi'
local winapi = require 'winapi'
require 'winapi.buttonclass'
require 'winapi.editclass'
require 'winapi.messagebox'
require 'winapi.monitor'
require 'winapi.windowclass'
require 'dragdrop'
require 'html_to_md'
-- -- info about the monitor which currently has mouse cursor
local moninfo = winapi.GetMonitorInfo(winapi.MonitorFromPoint(winapi.GetCursorPos(), winapi.MONITOR_DEFAULTTONEAREST))
local maxw, maxh = moninfo.work_rect.w, moninfo.work_rect.h
local w, h = maxw/4, maxh/3
local win = winapi.Window{
title = FILE..'- bmark',
autoquit = true,
-- bottom-right corner of screen
x = moninfo.work_rect.left + maxw-w,
y = moninfo.work_rect.top + maxh-h,
w = w,
h = h,
topmost = true,
}
local edit = winapi.Edit{
parent = win,
multiline = true,
autovscroll = true,
autohscroll = true,
want_return = true,
dont_hide_selection = true,
w = w,
h = h,
}
local add = winapi.Button{
parent = win,
text = '&Add',
}
function add:on_click()
local function msg(text, ok)
winapi.MessageBox(text, 'bmark',
winapi.MB_OK + (ok and winapi.MB_ICONINFORMATION or winapi.MB_ICONERROR),
win.hwnd)
end
if edit.text:gsub('%s*$','') == '' then
msg('Not adding, nothing to add', true)
return
end
-- TODO(akavel): consider UTC or both local+UTC for timestamp
local timestamp = ('{#t%s}'):format(os.date '%Y%m%d_%H%M%S')
local f, err = io.open(FILE, 'ab') -- TODO(akavel): 'a+b' and start by reading the file and counting notes?
if not f then
msg('Error: '..err)
return
end
local chunk = timestamp..'\n'..edit.text:gsub('\r',''):gsub('\n*$', '\n')
local ok, err = f:write(chunk)
if not ok then
msg('Error: '..err)
f:close()
return
end
local ok, err = f:close()
if not ok then
msg('Error: '..err)
return
end
edit.text = ""
-- FIXME - DEBUGGING
collectgarbage()
end
function win:on_resizing()
local region = win:get_client_rect()
add:resize(region.x2, add.h)
edit:resize(region.x2, region.y2-add.h)
add:move(0, edit.h)
end
win:on_resizing()
local effect
drop_target = simpleDropTarget{
DragEnter = function(pDataObj, grfKeyState, pt, pdwEffect)
print '\n-- DragEnter --\n'
local formats = dragDropFormats(pDataObj)
local f = formats['HTML Format']
if not f then
return winapi.E_UNEXPECTED
end
if not winapi.getbit(f.tymed, winapi.TYMED_HGLOBAL) then
print(('error: got "HTML format", but without expected TYMED_HGLOBAL; tymed=%d'):format(f.tymed))
return winapi.E_UNEXPECTED
end
f.dwAspect = winapi.DVASPECT_CONTENT
f.tymed = winapi.TYMED_HGLOBAL
local text = dragDropGetData(pDataObj, f):gsub('\0.*$', '')
print(text)
-- print(string.format('0x%x',pdwEffect[0]))
local fragment = extract_text(text)
edit.text = html_to_md('<html>'..fragment..'</html>'):gsub('\n', '\r\n')
edit.enabled = false
if winapi.getbit(pdwEffect[0], winapi.DROPEFFECT_LINK) then
effect = winapi.DROPEFFECT_LINK
elseif winapi.getbit(pdwEffect[0], winapi.DROPEFFECT_COPY) then
effect = winapi.DROPEFFECT_COPY
else
effect = winapi.DROPEFFECT_NONE
end
pdwEffect[0] = effect
return winapi.S_OK
end,
DragOver = function(grfKeyState, pt, pdwEffect)
pdwEffect[0] = effect
return winapi.S_OK
end,
DragLeave = function()
edit.text = ""
edit.enabled = true
return winapi.S_OK
end,
Drop = function(pDataObj, grfKeyState, pt, pdwEffect)
edit.enabled = true
pdwEffect[0] = effect
return winapi.S_OK
end,
}
drop_target:RegisterDragDrop(win)
-- TODO: winapi.RevokeDragDrop()
--[[ example data from Firefox, in utf-8:
Version:0.9
StartHTML:00000178
EndHTML:00000273
StartFragment:00000212
EndFragment:00000237
SourceURL:http://piwnica.org/wiki/Teksty/Na_dunaj_Nastu%c5%9b_rano_po_wod%c4%99
<html><body>
<!--StartFragment--><em>Na dunaj Nastu┼Ť</em><!--EndFragment-->
</body>
</html>
--]]
function extract_text(raw_html_format)
-- FIXME(akavel): verify Version and find out how old we support; also
-- try to find some official info about the format and versions
local function get(key)
return raw_html_format:gmatch(key..':[^\n\r]*')():sub(#key+2)
end
local url = get 'SourceURL'
local from, to = 1+get'StartFragment', 0+get'EndFragment'
-- TODO(akavel): verify if we have to delete '\r's or not
return url:gsub('&', '&').."\n"..raw_html_format:sub(from, to):gsub('\r', '')
end
-- pass control to the GUI system & message loop
os.exit(winapi.MessageLoop())
|
object_tangible_furniture_lifeday_lifeday_proton_chair = object_tangible_furniture_lifeday_shared_lifeday_proton_chair:new {
}
ObjectTemplates:addTemplate(object_tangible_furniture_lifeday_lifeday_proton_chair, "object/tangible/furniture/lifeday/lifeday_proton_chair.iff")
|
require("deepcore/std/class")
require("deepcore/std/callable")
StoryUtil = require("eawx-util/StoryUtil")
---@class SpawnHeroBuilder
SpawnHeroBuilder = class()
---@param hero string
function SpawnHeroBuilder:new(hero)
self.hero = {hero}
self.Active_Planets = {}
---@type PlayerObject
self.faction = nil
---@type string
self.planet = nil
end
---@param factions string
function SpawnHeroBuilder:for_faction(faction)
self.faction = faction
return self
end
---@param planet string
function SpawnHeroBuilder:on_planet(planet)
self.planet = planet
return self
end
function SpawnHeroBuilder:build()
return callable {
faction = self.faction,
hero = self.hero,
planet = self.planet,
Active_Planets = self.Active_Planets,
call = function(self)
self.Active_Planets = StoryUtil.GetSafePlanetTable()
local player_object = Find_Player(self.faction)
StoryUtil.SpawnAtSafePlanet(self.planet, player_object, self.Active_Planets, self.hero)
end
}
end
|
brightnodes.brightness = tonumber(minetest.setting_get("brightnodes.brightness")) or 14
brightnodes.items = {
"default:dirt",
"default:dirt_with_grass",
"default:dirt_with_dry_grass",
"default:dirt_with_snow",
"default:cobble",
"default:stone",
"default:sand",
"default:desert.*",
"default:.*tree",
"default:.*wood",
"default:.*block",
"default:.*brick",
"default:.*leaves",
"default:.*glass",
"default:papyrus",
"doors:.*",
"flowers:.*",
}
|
local config = require('idris2.config')
local M = {}
function M.request(bufnr)
local bufnr = bufnr or 0
local text_params = vim.lsp.util.make_text_document_params()
vim.lsp.for_each_buffer_client(bufnr, function(client, client_id, bufnr)
if vim.tbl_get(client.handlers, 'textDocument/semanticTokens/full') ~= nil then
vim.lsp.buf_request(bufnr, 'textDocument/semanticTokens/full', { textDocument = text_params })
end
end)
end
function M.refresh(err, result, ctx, cfg)
if err ~= nil then
vim.notify(err, vim.log.levels.ERROR)
return
end
if config.semantic_refresh then
M.request(ctx.bufnr)
end
return vim.NIL
end
function M.full(err, result, ctx, cfg)
if err ~= nil then
vim.notify(tostring(err), vim.log.levels.ERROR)
return
end
local client = vim.lsp.get_client_by_id(ctx.client_id)
local bufnr = ctx.bufnr
local legend = client.server_capabilities.semanticTokensProvider.legend
local token_types = legend.tokenTypes
local data = result.data
if #data == 0 then
return
end
local ns = vim.api.nvim_create_namespace('nvim-lsp-semantic-hl')
vim.api.nvim_buf_clear_namespace(bufnr, ns, 0, -1)
local prev_line, prev_start = nil, 0
for i = 1, #data, 5 do
local delta_line = data[i]
prev_line = prev_line and prev_line + delta_line or delta_line
local delta_start = data[i + 1]
prev_start = delta_line == 0 and prev_start + delta_start or delta_start
local token_type = token_types[data[i + 3] + 1]
local line = vim.api.nvim_buf_get_lines(bufnr, prev_line, prev_line + 1, false)[1]
local byte_start = vim.str_byteindex(line, prev_start)
local byte_end = vim.str_byteindex(line, prev_start + data[i + 2])
vim.api.nvim_buf_add_highlight(bufnr, ns, 'LspSemantic_' .. token_type, prev_line, byte_start, byte_end)
end
vim.notify(vim.fn.expand('%:t') .. ' semantically highlighted', vim.log.levels.INFO)
end
function M.clear()
local ns = vim.api.nvim_create_namespace('nvim-lsp-semantic-hl')
vim.api.nvim_buf_clear_namespace(0, ns, 0, -1)
end
function M.start()
if config.semantic_refresh then
return
end
config.semantic_refresh = true
M.request()
end
function M.stop()
if not config.semantic_refresh then
return
end
config.semantic_refresh = false
M.clear()
end
return M
|
local checkpoint = {}
local function deepCopy(tbl)
-- creates a copy of a network with new modules and the same tensors
local copy = {}
for k, v in pairs(tbl) do
if type(v) == 'table' then
copy[k] = deepCopy(v)
else
copy[k] = v
end
end
if torch.typename(tbl) then
torch.setmetatable(copy, torch.typename(tbl))
end
return copy
end
function copy_core(Net,list)
local all = {}
--print(Net)
for i,k in pairs(list) do
--print(Net[k])
all[k] = deepCopy(Net[k]):float():clearState()
end
return all
end
|
require 'image'
local trans = torch.class('zoo.TransitionTable')
function trans:__init(args)
self.stateDim = args.stateDim
self.numActions = args.numActions
self.histLen = args.histLen
self.maxSize = args.maxSize or 1024^2
self.histType = args.histType or "linear"
self.histSpacing = args.histSpacing or 1
self.zeroFrames = args.zeroFrames or 1
self.gpu = args.gpu
self.numEntries = 0
self.insertIndex = 0
self.histIndices = {}
local histLen = self.histLen
if self.histType == "linear" then
-- History is the last histLen frames.
self.recentMemSize = self.histSpacing*histLen
for i=1,histLen do
self.histIndices[i] = i*self.histSpacing
end
elseif self.histType == "exp2" then
-- The ith history frame is from 2^(i-1) frames ago.
self.recentMemSize = 2^(histLen-1)
self.histIndices[1] = 1
for i=1,histLen-1 do
self.histIndices[i+1] = self.histIndices[i] + 2^(7-i)
end
elseif self.histType == "exp1.25" then
-- The ith history frame is from 1.25^(i-1) frames ago.
self.histIndices[histLen] = 1
for i=histLen-1,1,-1 do
self.histIndices[i] = math.ceil(1.25*self.histIndices[i+1])+1
end
self.recentMemSize = self.histIndices[1]
for i=1,histLen do
self.histIndices[i] = self.recentMemSize - self.histIndices[i] + 1
end
end
self.s = torch.ByteTensor(self.maxSize, self.stateDim):fill(0)
self.a = torch.LongTensor(self.maxSize):fill(0)
self.r = torch.zeros(self.maxSize)
self.t = torch.ByteTensor(self.maxSize):fill(0)
-- Tables for storing the last histLen states. They are used for
-- constructing the most recent agent state more easily.
self.recent_s = {}
self.recent_a = {}
self.recent_t = {}
self:loadBuffers(args.bufferSize)
end
function trans:loadBuffers(bufferSize)
self.bufferSize = bufferSize or 1024
local s_size = self.stateDim*self.histLen
self.buf_s = torch.ByteTensor(self.bufferSize, s_size):fill(0)
self.buf_a = torch.LongTensor(self.bufferSize):fill(0)
self.buf_r = torch.zeros(self.bufferSize)
self.buf_s2 = torch.ByteTensor(self.bufferSize, s_size):fill(0)
self.buf_a2 = torch.LongTensor(self.bufferSize):fill(0)
self.buf_term = torch.ByteTensor(self.bufferSize):fill(0)
if self.gpu and self.gpu >= 0 then
self.gpu_s = self.buf_s:float():cuda()
self.gpu_s2 = self.buf_s2:float():cuda()
end
-- Set this so that we refill the buffer
self.buf_ind = self.bufferSize + 1
end
function trans:reset()
self.numEntries = 0
self.insertIndex = 0
end
function trans:size()
return self.numEntries
end
function trans:empty()
return self.numEntries == 0
end
function trans:fill_buffer()
assert(self.numEntries >= self.bufferSize)
-- clear CPU buffers
self.buf_ind = 1
for buf_ind=1,self.bufferSize do
local idx = self:sample_one(buf_ind)
local s, a, r, s2, a2, term = self:get(idx)
self.buf_s[buf_ind]:copy(s)
self.buf_a[buf_ind] = a
self.buf_r[buf_ind] = r
self.buf_s2[buf_ind]:copy(s2)
self.buf_a2[buf_ind] = a2
self.buf_term[buf_ind] = term
end
self.buf_s = self.buf_s:float():div(255)
self.buf_s2 = self.buf_s2:float():div(255)
if self.gpu and self.gpu >= 0 then
self.gpu_s:copy(self.buf_s)
self.gpu_s2:copy(self.buf_s2)
end
end
function trans:sample_one(buf_ind)
assert(self.numEntries > 1)
local index
local valid = false
while not valid do
-- start at 2 because of previous action
index = torch.random(2, self.numEntries-self.recentMemSize) -- -1 for a2 (on-policy)
if self.t[index+self.recentMemSize-1] == 0 then
valid = true
end
end
return index
end
function trans:sample(batch_size)
local batch_size = batch_size or 1
assert(batch_size <= self.bufferSize)
if not self.buf_ind or self.buf_ind + batch_size - 1 > self.bufferSize then
self:fill_buffer()
end
local index = self.buf_ind
self.buf_ind = self.buf_ind+batch_size
local range = {{index, index+batch_size-1}}
local buf_s, buf_a, buf_r, buf_s2, buf_a2, buf_term = self.buf_s,
self.buf_a, self.buf_r, self.buf_s2, self.buf_a2, self.buf_term
if self.gpu and self.gpu >=0 then
buf_s = self.gpu_s
buf_s2 = self.gpu_s2
end
return buf_s[range], buf_a[range], buf_r[range], buf_s2[range],
buf_a2[range], buf_term[range]
end
function trans:concatFrames(index, use_recent)
if use_recent then
s, t = self.recent_s, self.recent_t
else
s, t = self.s, self.t
end
local fullstate = s[1].new()
fullstate:resize(self.histLen, unpack(s[1]:size():totable()))
-- Zero out frames from all but the most recent episode.
local zero_out = false
local episode_start = self.histLen
for i=self.histLen-1,1,-1 do
if not zero_out then
for j=index+self.histIndices[i]-1,index+self.histIndices[i+1]-2 do
if t[j] == 1 then
zero_out = true
break
end
end
end
if zero_out then
fullstate[i]:zero()
else
episode_start = i
end
end
if self.zeroFrames == 0 then
episode_start = 1
end
-- Copy frames from the current episode.
for i=episode_start,self.histLen do
fullstate[i]:copy(s[index+self.histIndices[i]-1])
end
return fullstate
end
function trans:get_recent()
-- Assumes that the most recent state has been added, but the action has not
return self:concatFrames(1, true):float():div(255)
end
function trans:get(index)
local s = self:concatFrames(index)
local s2 = self:concatFrames(index+1)
local ar_index = index+self.recentMemSize-1
return s, self.a[ar_index], self.r[ar_index], s2, self.a[ar_index+1], self.t[ar_index+1]
end
function trans:add(s, a, r, term)
assert(s, 'State cannot be nil')
assert(a, 'Action cannot be nil')
assert(r, 'Reward cannot be nil')
-- Increment until at full capacity
if self.numEntries < self.maxSize then
self.numEntries = self.numEntries + 1
end
-- Always insert at next index, then wrap around
self.insertIndex = self.insertIndex + 1
-- Overwrite oldest experience once at capacity
if self.insertIndex > self.maxSize then
self.insertIndex = 1
end
-- Overwrite (s,a,r,t) at insertIndex
self.s[self.insertIndex] = s:clone():float():mul(255)
self.a[self.insertIndex] = a
self.r[self.insertIndex] = r
if term then
self.t[self.insertIndex] = 1
else
self.t[self.insertIndex] = 0
end
end
function trans:updatePriority(indices, priority)
end
function trans:add_recent_state(s, term)
local s = s:clone():float():mul(255):byte()
if #self.recent_s == 0 then
for i=1,self.recentMemSize do
table.insert(self.recent_s, s:clone():zero())
table.insert(self.recent_t, 1)
end
end
table.insert(self.recent_s, s)
if term then
table.insert(self.recent_t, 1)
else
table.insert(self.recent_t, 0)
end
-- Keep recentMemSize states.
if #self.recent_s > self.recentMemSize then
table.remove(self.recent_s, 1)
table.remove(self.recent_t, 1)
end
end
function trans:add_recent_action(a)
if #self.recent_a == 0 then
for i=1,self.recentMemSize do
table.insert(self.recent_a, 1)
end
end
table.insert(self.recent_a, a)
-- Keep recentMemSize steps.
if #self.recent_a > self.recentMemSize then
table.remove(self.recent_a, 1)
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.