content
stringlengths 5
1.05M
|
|---|
-- NODES
minetest.register_node("seacobble:seacobble", {
description = "Sea cobblestone",
tiles = {"seacobble_seacobble.png"},
is_ground_content = true,
groups = {cracky=3, stone=2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("seacobble:seacobble_cyan", {
description = "Sea cobblestone cyan",
tiles = {"seacobble_seacobble_cyan.png"},
is_ground_content = true,
groups = {cracky=3, stone=2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("seacobble:seacobble_magenta", {
description = "Sea cobblestone magenta",
tiles = {"seacobble_seacobble_magenta.png"},
is_ground_content = true,
groups = {cracky=3, stone=2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("seacobble:seacobble_lime", {
description = "Sea cobblestone lime",
tiles = {"seacobble_seacobble_lime.png"},
is_ground_content = true,
groups = {cracky=3, stone=2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("seacobble:seacobble_aqua", {
description = "Sea cobblestone aqua",
tiles = {"seacobble_seacobble_aqua.png"},
is_ground_content = true,
groups = {cracky=3, stone=2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("seacobble:seacobble_skyblue", {
description = "Sea cobblestone skyblue",
tiles = {"seacobble_seacobble_skyblue.png"},
is_ground_content = true,
groups = {cracky=3, stone=2},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_node("seacobble:seacobble_redviolet", {
description = "Sea cobblestone redviolet",
tiles = {"seacobble_seacobble_redviolet.png"},
is_ground_content = true,
groups = {cracky=3, stone=2},
sounds = default.node_sound_stone_defaults(),
})
-- STAIRS
stairs.register_stair_and_slab("seacobble", "seacobble:seacobble",
{cracky=3, stone=2},
{"seacobble_seacobble.png"},
"Seacobble stair",
"Seacobble slab",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("seacobble_cyan", "seacobble:seacobble_cyan",
{cracky=3, stone=2},
{"seacobble_seacobble_cyan.png"},
"Seacobble stair cyan",
"Seacobble slab cyan",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("seacobble_magenta", "seacobble:seacobble_magenta",
{cracky=3, stone=2},
{"seacobble_seacobble_magenta.png"},
"Seacobble stair magenta",
"Seacobble slab magenta",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("seacobble_lime", "seacobble:seacobble_lime",
{cracky=3, stone=2},
{"seacobble_seacobble_lime.png"},
"Seacobble stair lime",
"Seacobble slab lime",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("seacobble_aqua", "seacobble:seacobble_aqua",
{cracky=3, stone=2},
{"seacobble_seacobble_aqua.png"},
"Seacobble stair aqua",
"Seacobble slab aqua",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("seacobble_skyblue", "seacobble:seacobble_skyblue",
{cracky=3, stone=2},
{"seacobble_seacobble_skyblue.png"},
"Seacobble stair skyblue ",
"Seacobble slab skyblue",
default.node_sound_stone_defaults())
stairs.register_stair_and_slab("seacobble_redviolet", "seacobble:seacobble_redviolet",
{cracky=3, stone=2},
{"seacobble_seacobble_redviolet.png"},
"Seacobble stair redviolet",
"Seacobble slab redviolet",
default.node_sound_stone_defaults())
-- CRAFTING
local register_seacobble_craft = function(output,recipe)
minetest.register_craft({
type = 'shapeless',
output = output,
recipe = recipe,
})
end
register_seacobble_craft("seacobble:seacobble", {'clams:crushedwhite', 'default:cobble'})
register_seacobble_craft("seacobble:seacobble_cyan", {'seacobble:seacobble', 'dye:cyan'})
register_seacobble_craft("seacobble:seacobble_magenta", {'seacobble:seacobble', 'dye:magenta'})
register_seacobble_craft("seacobble:seacobble_lime", {'seacobble:seacobble', 'dye:lime'})
register_seacobble_craft("seacobble:seacobble_aqua", {'seacobble:seacobble', 'dye:aqua'})
register_seacobble_craft("seacobble:seacobble_skyblue", {'seacobble:seacobble', 'dye:skyblue'})
register_seacobble_craft("seacobble:seacobble_redviolet", {'seacobble:seacobble', 'dye:redviolet'})
register_seacobble_craft("seacobble:seacobble_cyan", {'clams:crushedwhite', 'default:cobble','dye:cyan'})
register_seacobble_craft("seacobble:seacobble_magenta", {'clams:crushedwhite', 'default:cobble','dye:magenta'})
register_seacobble_craft("seacobble:seacobble_lime", {'clams:crushedwhite', 'default:cobble','dye:lime'})
register_seacobble_craft("seacobble:seacobble_aqua", {'clams:crushedwhite', 'default:cobble','dye:aqua'})
register_seacobble_craft("seacobble:seacobble_skyblue", {'clams:crushedwhite', 'default:cobble','dye:skyblue'})
register_seacobble_craft("seacobble:seacobble_redviolet", {'clams:crushedwhite', 'default:cobble','dye:redviolet'})
|
function event_combat(e)
if (e.joined == true) then
e.self:Emote("into this room, screaming can be heard in the distance.");
eq.depop_with_timer();
end
end
|
kCollector = KAD_SALVAGER
kRefinery = KAD_RESOURCEFUELPOD
kScout = KAD_ARANEID
kInterceptor = KAD_SWARMER
kBomber = KAD_ASSAULTSWARMER
kCarrier = KAD_CARRIER
kDestroyer = KAD_GUARDIANSPIRIT
kBattleCruiser = KAD_MOTHERSHIPLIGHT
kRepair = KAD_ARANEID
function DetermineDemandWithNoCounterInfo_Kadesh()
if (sg_randFavorShipType < 50) then
ShipDemandAddByClass(eFighter, 1)
elseif (sg_randFavorShipType < 80) then
ShipDemandAddByClass(eCorvette, 1)
elseif (sg_randFavorShipType < 95) then
ShipDemandAddByClass(eFrigate, 1)
else
ShipDemandAdd(kDestroyer, 1)
end
end
function DetermineSpecialDemand_Kadesh()
if (ShipDemandGet( kInterceptor ) > 0 and NumSubSystems(FIGHTERPRODUCTION) > 0 and NumSquadrons(kInterceptor) < 3 and s_militaryPop < 10) then
ShipDemandAdd( kInterceptor, 0.5 )
end
if (NumSubSystems(FRIGATEPRODUCTION) > 0) then
ShipDemandAdd(KAD_FUELPOD,1.5)
end
if (NumSubSystems(CAPSHIPPRODUCTION) > 0) then
ShipDemandAdd(KAD_MULTIBEAMFRIGATE,0.5)
end
-- once we have a bit more military then add a frigate base value
if (s_selfTotalValue > 120) then
local additionalFrigDemand = 0.5
local capscount = NumSubSystems(CAPSHIP) + NumSubSystemsQ(CAPSHIP)
if (capscount > 0) then
additionalFrigDemand = additionalFrigDemand + 0.25
end
ShipDemandAddByClass( eFrigate, additionalFrigDemand )
-- removes the initial bonus for fighters
ShipDemandAddByClass( eFighter, -0.5 )
end
-- tweak the demand for special frigates based on our military strength,
-- we already count these frigates as anti frigate so the fleet vs
-- fleet stuff is already done
-- first see if we have too many special frigates compared to the normal ones
local numSpecial = numQueueOfClass(eCapture)
local numFrigates = numQueueOfClass(eFrigate)
if(numFrigates == 0 or numSpecial / numFrigates > 0.4) then
-- too many, floor the demand
ShipDemandAddByClass( eCapture, -10 )
else
-- not too many, so based on the size of our fleet tweak the demand
if (s_militaryPop < 5) then
ShipDemandAddByClass( eCapture, -4 )
elseif (s_militaryPop < 10) then
ShipDemandAddByClass( eCapture, -2 )
elseif (s_militaryPop < 15) then
ShipDemandAddByClass( eCapture, -1 )
elseif (s_militaryPop > 30) then
ShipDemandAddByClass( eCapture, 1 )
end
end
local numRepair = NumSquadrons(kRepair)
if(numRepair / s_militaryPop > 0.2) then
-- too many, floor the demand
ShipDemandAdd(kRepair, -10)
elseif (numRepair / s_militaryPop < 0.1) then
ShipDemandAdd(kRepair, 10)
end
-- torpedo frigate is a bit useless until we get the upgrade
-- but the upgrade doesn't come unless we have lots of torpedo frigs
local numRUs = GetRU()
-- always add some demand for these two ships - if we are economically sound
if ( (GetNumCollecting() > 9 or numRUs > 1500) and s_militaryPop > 8 and UnderAttackThreat() < -75) then
ShipDemandAdd(kDestroyer, 0.25)
end
-- if enemy has battlecruisers we should increase the request for subsystem attackers
local numEnemyBattleCruisers = PlayersUnitTypeCount( player_enemy, player_total, eBattleCruiser )
if (numEnemyBattleCruisers > 0) then
local ssKillaDemand = numEnemyBattleCruisers/2
if (s_enemyIndex ~= -1) then
local targetEnemyCruisers = PlayersUnitTypeCount( s_enemyIndex, player_max, eBattleCruiser )
if (targetEnemyCruisers > 0) then
ssKillaDemand = ssKillaDemand + targetEnemyCruisers
end
end
ShipDemandAddByClass( eSubSystemAttackers, ssKillaDemand )
end
-- if AI is winning the militaryvalue battle reduce platform demand
if (s_militaryStrength > 25*sg_moreEnemies) then
ShipDemandAddByClass( ePlatform, -2 )
end
end
Proc_DetermineDemandWithNoCounterInfo = DetermineDemandWithNoCounterInfo_Kadesh
Proc_DetermineSpecialDemand = DetermineSpecialDemand_Kadesh
|
#!/usr/bin/env luajit
local ok = pcall(dofile,'../fiddle.lua')
if not ok then dofile'fiddle.lua' end
local getch = require'getch'
targetvel={0,0,0}
targetvel_new={0,0,0}
local servo_names={
"hipyaw",
"hiproll",
"hippitch",
"kneepitch",
"anklepitch",
"ankleroll"
}
local selected_servo = 1
local bias_mag = 0.0675*math.pi/180
function process_keyinput()
local byte=getch.block();
local bias_edited = false
if byte then
local legBias = mcm.get_leg_bias()
-- Walk velocity setting
if byte==string.byte("i") then targetvel_new[1]=targetvel[1]+0.01;
elseif byte==string.byte("j") then targetvel_new[3]=targetvel[3]+0.1;
elseif byte==string.byte("k") then targetvel_new[1],targetvel_new[2],targetvel_new[3]=0,0,0;
elseif byte==string.byte("l") then targetvel_new[3]=targetvel[3]-0.1;
elseif byte==string.byte(",") then targetvel_new[1]=targetvel[1]-0.02;
elseif byte==string.byte("h") then targetvel_new[2]=targetvel[2]+0.02;
elseif byte==string.byte(";") then targetvel_new[2]=targetvel[2]-0.02;
elseif byte==string.byte("1") then
body_ch:send'init'
elseif byte==string.byte("-") then
motion_ch:send'bias'
arm_ch:send'bias'
elseif byte==string.byte("8") then
motion_ch:send'stand'
body_ch:send'stop'
if mcm.get_walk_ismoving()>0 then
print("requesting stop")
mcm.set_walk_stoprequest(1)
end
elseif byte==string.byte("9") then
motion_ch:send'hybridwalk'
elseif byte==string.byte("2") then
selected_servo = 1
bias_edited = true
elseif byte==string.byte("3") then
selected_servo = 2
bias_edited = true
elseif byte==string.byte("4") then
selected_servo = 3
bias_edited = true
elseif byte==string.byte("5") then
selected_servo = 4
bias_edited = true
elseif byte==string.byte("6") then
selected_servo = 5
bias_edited = true
elseif byte==string.byte("7") then
selected_servo = 6
bias_edited = true
elseif byte==string.byte("q") then
legBias[selected_servo]=legBias[selected_servo]-bias_mag
bias_edited = true
elseif byte==string.byte("w") then
legBias[selected_servo]=legBias[selected_servo]+bias_mag
bias_edited = true
elseif byte==string.byte("[") then
legBias[selected_servo+6]=legBias[selected_servo+6]-bias_mag
bias_edited = true
elseif byte==string.byte("]") then
legBias[selected_servo+6]=legBias[selected_servo+6]+bias_mag
bias_edited = true
elseif byte==string.byte("x") then
local cob = mcm.get_stance_COMoffsetBias()
cob=cob+0.005
print("COM offset bias:",cob)
mcm.set_stance_COMoffsetBias(cob)
elseif byte==string.byte("z") then
local cob = mcm.get_stance_COMoffsetBias()
cob=cob-0.005
print("COM offset bias:",cob)
mcm.set_stance_COMoffsetBias(cob)
elseif byte==string.byte("0") then
print(string.format("Current bias: \n%.2f %.2f %.2f %.2f %.2f %.2f\n%.2f %.2f %.2f %.2f %.2f %.2f ",
unpack(vector.new(legBias)*RAD_TO_DEG)))
--Append at the end of calibration file
outfile=assert(io.open("../Config/THOROP0/calibration.lua","a+"));
--TODO: which one should we use?
data=string.format("\n\n-- Updated date: %s\n" , os.date() );
data=data..string.format("cal[\"%s\"].legBias=vector.new({\n ",unix.gethostname());
for i=1,6 do data=data..string.format("%f,",legBias[i]*180/math.pi) end
data=data..'\n '
for i=7,12 do data=data..string.format("%f,",legBias[i]*180/math.pi) end
data=data..'\n })*math.pi/180\n';
outfile:write(data);
outfile:flush();
outfile:close();
end
if bias_edited then
mcm.set_leg_bias(legBias)
print(servo_names[selected_servo]," : ",
legBias[selected_servo]*RAD_TO_DEG,
legBias[selected_servo+6]*RAD_TO_DEG
)
end
local vel_diff = (targetvel_new[1]-targetvel[1])^2+(targetvel_new[2]-targetvel[2])^2+(targetvel_new[3]-targetvel[3])^2
if vel_diff>0 then
targetvel[1],targetvel[2],targetvel[3] = targetvel_new[1],targetvel_new[2],targetvel_new[3]
print(string.format("Target velocity: %.3f %.3f %.3f",unpack(targetvel)))
mcm.set_walk_vel(targetvel)
end
end
end
mcm.set_leg_bias(Config.walk.legBias)
local t_last = Body.get_time()
local tDelay = 0.005*1E6
while true do
process_keyinput(); --why nonblocking reading does not work?
end
|
require('assets/scripts/object')
GameSerializer = Object:new()
local function fileExists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- get all lines from a file, returns an empty
-- list/table if the file does not exist
function GameSerializer:loadLines(file)
if not fileExists(file) then
return
end
local lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
local function split(str, delim, maxNb)
-- Eliminate bad cases...
if string.find(str, delim) == nil then
return { str }
end
if maxNb == nil or maxNb < 1 then
maxNb = 0 -- No limit
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gmatch(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
if nb == maxNb then
break
end
end
-- Handle the last field
if nb ~= maxNb then
result[nb + 1] = string.sub(str, lastPos)
end
return result
end
function GameSerializer:load(fileName)
local lines = self:loadLines(fileName)
if lines == {} then
return {}
end
local data = {}
for i = 1, #lines do
local line = lines[i]
local tempArray = split(line, ", ")
local savedEntry = {level = "", stars = 0}
for i = 1, #tempArray do
local valueArray = split(tempArray[i], ": ")
local value = valueArray[2]
if i == 1 then
savedEntry.level = value
elseif i == 2 then
savedEntry.stars = tonumber(value)
end
end
data[#data + 1] = savedEntry
end
for k, v in ipairs(data) do
print("Loaded Data: Level: "..v.level.." Stars: "..v.stars)
end
return data
end
function GameSerializer:saveNewEntry(newEntry)
local found = false
for k, v in ipairs(Game.savedData) do
if v.level == newEntry.level then
if v.stars < newEntry.stars then
Game.savedData[k].stars = newEntry.stars
end
found = true
break
end
end
if not found then
if Game.savedData == nil then
Game.savedData = { }
end
Game.savedData[#Game.savedData + 1] = newEntry
end
self:save(Config.saveFile)
end
function GameSerializer:save(fileName)
if fileName == nil then
return
end
local file = io.open(fileName, "w+")
io.output(file)
local savedData = Game.savedData
if not savedData == nil then
return
end
for k ,v in ipairs(savedData) do
print("Saved data: Level: "..v.level.." Stars: "..v.stars)
io.write("level: "..v.level..", stars: "..v.stars.."\n")
end
file:close()
end
|
Days:
game.Players.LocalPlayer.playerstats.Days.Value = 30
Kills:
game.Players.LocalPlayer.playerstats.PlayerKill.Defensive.Value = 30
|
-- get the relative path
local thispath = select('1', ...):match(".+%.") or ""
local parent = "unittests."
thispath = string.sub(thispath, 1, string.len(thispath) - string.len(parent))
-- load skeletor module
local Skeletor = require(thispath..'skeletor')
skeletor = Skeletor()
skeletor:newSkeleton('paul')
-- test skeletor:newBone()
skeletor:newBone('paul.arm', {length = 100, angle = 50})
assert(skeletor.skeletons['paul'].childBones['arm'].length == 100)
assert(skeletor.skeletons['paul'].childBones['arm'].angle == 50)
-- test skeletor:getBoneProp()
skeletor:newBone('paul.foot', {angle = 1032})
local prop = skeletor:getBoneProp('paul.foot', 'angle')
--assert(prop == 1032)
-- test skeletor:editBone()
skeletor:newBone('paul.head', {length = 10, angle = 20})
skeletor:editBone('paul.head', {length = 25, angle = 35})
assert(skeletor.skeletons['paul'].childBones['head'].length == 25)
assert(skeletor.skeletons['paul'].childBones['head'].angle == 35)
-- test skeletor:deleteBone()
skeletor:newBone('paul.toe')
assert(skeletor.skeletons['paul'].childBones['toe'] ~= nil)
skeletor:deleteBone('paul.toe')
assert(skeletor.skeletons['paul'].childBones['toe'] == nil)
|
function resourceStart(res)
if (res==getThisResource()) then
setTimer(saveGuns, 15000, 0)
end
end
addEventHandler("onClientResourceStart", getRootElement(), resourceStart)
function saveGuns()
local loggedin = getElementData(getLocalPlayer(), "loggedin")
if (loggedin==1) then
local weaponstring = ""
local ammostring = ""
for i=0, 12 do
local weapon = tostring(getPedWeapon(getLocalPlayer(), i))
local ammo = tostring(getPedTotalAmmo(getLocalPlayer(), i))
weaponstring = weaponstring .. weapon .. ";"
ammostring = ammostring .. ammo .. ";"
end
setElementData(getLocalPlayer(), "weapons", weaponstring)
setElementData(getLocalPlayer(), "ammo", ammostring)
end
end
|
local schemas = require "kong.dao.schemas_validation"
local validate_entity = schemas.validate_entity
--require "kong.tools.ngx_stub"
describe("Schemas", function()
-- Ok kids, today we're gonna test a custom validation schema,
-- grab a pair of glasses, this stuff can literally explode.
describe("#validate_entity()", function()
local schema = {
fields = {
string = { type = "string", required = true, immutable = true},
table = {type = "table"},
number = {type = "number"},
timestamp = {type = "timestamp"},
url = {regex = "^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\\-]*[A-Za-z0-9])$"},
date = {default = 123456, immutable = true},
allowed = {enum = {"hello", "world"}},
boolean_val = {type = "boolean"},
endpoint = { type = "url" },
enum_array = { type = "array", enum = { "hello", "world" }},
default = {default = function(t)
assert.truthy(t)
return "default"
end},
custom = {func = function(v, t)
if v then
if t.default == "test_custom_func" then
return true
else
return false, "Nah"
end
else
return true
end
end}
}
}
it("should confirm a valid entity is valid", function()
local values = {string = "example entity", url = "example.com"}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.True(valid)
end)
describe("[required]", function()
it("should invalidate entity if required property is missing", function()
local values = {url = "example.com"}
local valid, err = validate_entity(values, schema)
assert.False(valid)
assert.truthy(err)
assert.are.same("string is required", err.string)
end)
it("errors if required property is set to ngx.null", function()
local values = { string = ngx.null }
local ok, err = validate_entity(values, schema)
assert.falsy(ok)
assert.equal("string is required", err.string)
end)
end)
describe("[type]", function()
--[]
it("should validate the type of a property if it has a type field", function()
-- Failure
local values = {string = "foo", table = "bar"}
local valid, err = validate_entity(values, schema)
assert.False(valid)
assert.truthy(err)
assert.are.same("table is not a table", err.table)
-- Success
local values = {string = "foo", table = {foo = "bar"}}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.True(valid)
-- Failure
local values = {string = 1, table = {foo = "bar"}}
local valid, err = validate_entity(values, schema)
assert.False(valid)
assert.truthy(err)
assert.are.same("string is not a string", err.string)
-- Success
local values = {string = "foo", number = 10}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.True(valid)
-- Success
local values = {string = "foo", number = "10"}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
assert.are.same("number", type(values.number))
-- Success
local values = {string = "foo", boolean_val = true}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
assert.are.same("boolean", type(values.boolean_val))
-- Success
local values = {string = "foo", boolean_val = "true"}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
-- Failure
local values = {string = "foo", endpoint = ""}
local valid, err = validate_entity(values, schema)
assert.falsy(valid)
assert.truthy(err)
assert.are.equal("endpoint is not a url", err.endpoint)
-- Failure
local values = {string = "foo", endpoint = "asdasd"}
local valid, err = validate_entity(values, schema)
assert.falsy(valid)
assert.truthy(err)
-- Success
local values = {string = "foo", endpoint = "http://google.com"}
local valid, err = validate_entity(values, schema)
assert.truthy(valid)
assert.falsy(err)
-- Success
local values = {string = "foo", endpoint = "http://google.com/"}
local valid, err = validate_entity(values, schema)
assert.truthy(valid)
assert.falsy(err)
-- Success
local values = {string = "foo", endpoint = "http://google.com/hello/?world=asd"}
local valid, err = validate_entity(values, schema)
assert.truthy(valid)
assert.falsy(err)
end)
it("should return error when an invalid boolean value is passed", function()
local values = {string = "test", boolean_val = "ciao"}
local valid, err = validate_entity(values, schema)
assert.falsy(valid)
assert.truthy(err)
assert.are.same("boolean_val is not a boolean", err.boolean_val)
end)
it("should not return an error when a true boolean value is passed", function()
local values = {string = "test", boolean_val = true}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
end)
it("should not return an error when a false boolean value is passed", function()
local values = {string = "test", boolean_val = false}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
end)
it("should consider `id` as a type", function()
local s = {
fields = {
id = {type = "id"}
}
}
local values = {id = "123"}
local valid, err = validate_entity(values, s)
assert.falsy(err)
assert.truthy(valid)
end)
it("should consider `timestamp` as a type", function()
local s = {
fields = {
created_at = {type = "timestamp"}
}
}
local values = {created_at = "123"}
local valid, err = validate_entity(values, s)
assert.falsy(err)
assert.truthy(valid)
end)
it("should consider `array` as a type", function()
local s = {
fields = {
array = {type = "array"}
}
}
-- Success
local values = {array = {"hello", "world"}}
local valid, err = validate_entity(values, s)
assert.True(valid)
assert.falsy(err)
-- Failure
local values = {array = {hello="world"}}
local valid, err = validate_entity(values, s)
assert.False(valid)
assert.truthy(err)
assert.equal("array is not an array", err.array)
end)
describe("[aliases]", function()
it("should not return an error when a `number` is passed as a string", function()
local values = {string = "test", number = "10"}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
assert.same("number", type(values.number))
end)
it("should not return an error when a `boolean` is passed as a string", function()
local values = {string = "test", boolean_val = "false"}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
assert.same("boolean", type(values.boolean_val))
end)
it("should not return an error when a `timestamp` is passed as a string", function()
local values = {string = "test", timestamp = "123"}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
assert.same("number", type(values.timestamp))
end)
it("should return an error when a `timestamp` is not a number", function()
local values = {string = "test", timestamp = "just a string"}
local valid, err = validate_entity(values, schema)
assert.falsy(valid)
assert.are.same("timestamp is not a timestamp", err.timestamp)
end)
it("should return an error when a `timestamp` is a negative number", function()
local values = {string = "test", timestamp = "-123"}
local valid, err = validate_entity(values, schema)
assert.falsy(valid)
assert.are.same("timestamp is not a timestamp", err.timestamp)
end)
it("should alias a string to `array`", function()
local s = {
fields = {
array = {type = "array"}
}
}
-- It should also strip the resulting strings
local values = { array = "hello, world" }
local valid, err = validate_entity(values, s)
assert.True(valid)
assert.falsy(err)
assert.same({"hello", "world"}, values.array)
end)
it("preserves escaped commas in comma-separated arrays", function()
-- Note: regression test for arrays of PCRE URIs:
-- https://github.com/Mashape/kong/issues/2780
local s = {
fields = {
array = { type = "array" }
}
}
local values = {
array = [[hello\, world,goodbye world\,,/hello/\d{1\,3}]]
}
local valid, err = validate_entity(values, s)
assert.True(valid)
assert.falsy(err)
assert.same({ "hello, world", "goodbye world,", [[/hello/\d{1,3}]] },
values.array)
end)
end)
end)
describe("[default]", function()
it("should set default values if those are variables or functions specified in the validator", function()
-- Variables
local values = {string = "example entity", url = "example.com"}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
assert.are.same(123456, values.date)
-- Functions
local values = {string = "example entity", url = "example.com"}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
assert.are.same("default", values.default)
end)
it("should override default values if specified", function()
-- Variables
local values = {string = "example entity", url = "example.com", date = 654321}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
assert.are.same(654321, values.date)
-- Functions
local values = {string = "example entity", url = "example.com", default = "abcdef"}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
assert.are.same("abcdef", values.default)
end)
it("sets to default when a field is given ngx.null", function()
local values = { string = "foo", default = ngx.null }
local ok, err = validate_entity(values, schema)
assert.falsy(err)
assert.is_true(ok)
assert.equal("default", values.default)
end)
end)
describe("[regex]", function()
it("should validate a field against a regex", function()
local values = {string = "example entity", url = "example_!"}
local valid, err = validate_entity(values, schema)
assert.falsy(valid)
assert.truthy(err)
assert.are.same("url has an invalid value", err.url)
end)
end)
describe("[enum]", function()
it("should validate a field against an enum", function()
-- Success
local values = {string = "somestring", allowed = "hello"}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
-- Failure
local values = {string = "somestring", allowed = "hello123"}
local valid, err = validate_entity(values, schema)
assert.falsy(valid)
assert.truthy(err)
assert.are.same("\"hello123\" is not allowed. Allowed values are: \"hello\", \"world\"", err.allowed)
end)
it("should validate an enum into an array", function()
-- Failure
local values = {string = "somestring", enum_array = "hello1"}
local valid, err = validate_entity(values, schema)
assert.truthy(err)
assert.falsy(valid)
assert.are.same("\"hello1\" is not allowed. Allowed values are: \"hello\", \"world\"", err.enum_array)
-- Failure
local values = {string = "somestring", enum_array = {"hello1"}}
local valid, err = validate_entity(values, schema)
assert.truthy(err)
assert.falsy(valid)
assert.are.same("\"hello1\" is not allowed. Allowed values are: \"hello\", \"world\"", err.enum_array)
-- Success
local values = {string = "somestring", enum_array = {"hello"}}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
-- Success
local values = {string = "somestring", enum_array = {"hello", "world"}}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
-- Failure
local values = {string = "somestring", enum_array = {"hello", "world", "another"}}
local valid, err = validate_entity(values, schema)
assert.truthy(err)
assert.falsy(valid)
assert.are.same("\"another\" is not allowed. Allowed values are: \"hello\", \"world\"", err.enum_array)
-- Success
local values = {string = "somestring", enum_array = {}}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
end)
end)
describe("[func]", function()
it("should validate a field against a custom function", function()
-- Success
local values = {string = "somestring", custom = true, default = "test_custom_func"}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
-- Failure
local values = {string = "somestring", custom = true, default = "not the default :O"}
local valid, err = validate_entity(values, schema)
assert.falsy(valid)
assert.truthy(err)
assert.are.same("Nah", err.custom)
end)
it("is called with arg1 'nil' when given ngx.null", function()
spy.on(schema.fields.custom, "func")
local values = { string = "foo", custom = ngx.null }
local ok, err = validate_entity(values, schema)
assert.falsy(err)
assert.is_true(ok)
assert.is_nil(values.custom)
assert.spy(schema.fields.custom.func).was_called_with(nil, values, "custom")
end)
end)
it("should return error when unexpected values are included in the schema", function()
local values = {string = "example entity", url = "example.com", unexpected = "abcdef"}
local valid, err = validate_entity(values, schema)
assert.falsy(valid)
assert.truthy(err)
end)
it("should be able to return multiple errors at once", function()
local values = {url = "example.com", unexpected = "abcdef"}
local valid, err = validate_entity(values, schema)
assert.falsy(valid)
assert.truthy(err)
assert.are.same("string is required", err.string)
assert.are.same("unexpected is an unknown field", err.unexpected)
end)
it("should not check a custom function if a `required` condition is false already", function()
local f = function() error("should not be called") end -- cannot use a spy which changes the type to table
local schema = {
fields = {
property = {required = true, func = f}
}
}
assert.has_no_errors(function()
local valid, err = validate_entity({}, schema)
assert.False(valid)
assert.are.same("property is required", err.property)
end)
end)
describe("Sub-schemas", function()
-- To check wether schema_from_function was called, we will simply use booleans because
-- busted's spy methods create tables and metatable magic, but the validate_entity() function
-- only callse v.schema if the type is a function. Which is not the case with a busted spy.
local called, called_with
local schema_from_function = function(t)
called = true
called_with = t
if t.error_loading_sub_sub_schema then
return nil, "Error loading the sub-sub-schema"
end
return {fields = {sub_sub_field_required = {required = true}}}
end
local nested_schema = {
fields = {
some_required = { required = true },
sub_schema = {
type = "table",
schema = {
fields = {
sub_field_required = {required = true},
sub_field_default = {default = "abcd"},
sub_field_number = {type = "number"},
error_loading_sub_sub_schema = {}
}
}
}
}
}
it("should validate a property with a sub-schema", function()
-- Success
local values = { some_required = "somestring", sub_schema = {sub_field_required = "sub value"}}
local valid, err = validate_entity(values, nested_schema)
assert.falsy(err)
assert.truthy(valid)
assert.are.same("abcd", values.sub_schema.sub_field_default)
-- Failure
local values = {some_required = "somestring", sub_schema = {sub_field_default = ""}}
local valid, err = validate_entity(values, nested_schema)
assert.truthy(err)
assert.falsy(valid)
assert.are.same("sub_field_required is required", err["sub_schema.sub_field_required"])
end)
it("should validate a property with a sub-schema from a function", function()
nested_schema.fields.sub_schema.schema.fields.sub_sub_schema = {schema = schema_from_function}
-- Success
local values = {some_required = "somestring", sub_schema = {
sub_field_required = "sub value",
sub_sub_schema = {sub_sub_field_required = "test"}
}}
local valid, err = validate_entity(values, nested_schema)
assert.falsy(err)
assert.truthy(valid)
-- Failure
local values = {some_required = "somestring", sub_schema = {
sub_field_required = "sub value",
sub_sub_schema = {}
}}
local valid, err = validate_entity(values, nested_schema)
assert.truthy(err)
assert.falsy(valid)
assert.are.same("sub_sub_field_required is required", err["sub_schema.sub_sub_schema.sub_sub_field_required"])
end)
it("should call the schema function with the actual parent t table of the subschema", function()
local values = {some_required = "somestring", sub_schema = {
sub_field_default = "abcd",
sub_field_required = "sub value",
sub_sub_schema = {sub_sub_field_required = "test"}
}}
local valid, err = validate_entity(values, nested_schema)
assert.falsy(err)
assert.truthy(valid)
assert.True(called)
assert.are.same(values.sub_schema, called_with)
end)
it("should retrieve errors when cannot load schema from function", function()
local values = {some_required = "somestring", sub_schema = {
sub_field_default = "abcd",
sub_field_required = "sub value",
error_loading_sub_sub_schema = true,
sub_sub_schema = {sub_sub_field_required = "test"}
}}
local valid, err = validate_entity(values, nested_schema)
assert.truthy(err)
assert.falsy(valid)
assert.are.same("Error loading the sub-sub-schema", err["sub_schema.sub_sub_schema"])
end)
it("should instanciate a sub-value if sub-schema has a `default` value and do that before `required`", function()
local function validate_value(value)
if not value.some_property then
return false, "value.some_property must not be empty"
end
return true
end
local schema = {
fields = {
value = {type = "table", schema = {fields = {some_property={default="hello"}}}, func = validate_value, required = true}
}
}
local obj = {}
local valid, err = validate_entity(obj, schema)
assert.falsy(err)
assert.True(valid)
assert.are.same("hello", obj.value.some_property)
end)
it("should mark a value required if sub-schema has a `required`", function()
local schema = {
fields = {
value = {type = "table", schema = {fields = {some_property={required=true}}}}
}
}
local obj = {}
local valid, err = validate_entity(obj, schema)
assert.truthy(err)
assert.False(valid)
assert.are.same("value.some_property is required", err.value)
end)
it("should work with flexible schemas", function()
local schema = {
fields = {
flexi = { type = "table",
schema = {
flexible = true,
fields = {
name = {type = "string"},
age = {type = "number"}
}
}
}
}
}
local obj = {
flexi = {
somekey = {
name = "Mark",
age = 12
}
}
}
local valid, err = validate_entity(obj, schema)
assert.falsy(err)
assert.True(valid)
assert.are.same({flexi = {
somekey = {
name = "Mark",
age = 12
}
}}, obj)
obj = {
flexi = {
somekey = {
name = "Mark",
age = 12
},
hello = {
name = "Mark2",
age = 13
}
}
}
valid, err = validate_entity(obj, schema)
assert.falsy(err)
assert.True(valid)
assert.are.same({flexi = {
somekey = {
name = "Mark",
age = 12
},
hello = {
name = "Mark2",
age = 13
}
}}, obj)
end)
it("should return proper errors with a flexible schema", function()
local schema = {
fields = {
flexi = { type = "table",
schema = {
flexible = true,
fields = {
name = {type = "string"},
age = {type = "number"}
}
}
}
}
}
local obj = {
flexi = {
somekey = {
name = "Mark",
age = "hello"
}
}
}
local valid, err = validate_entity(obj, schema)
assert.truthy(err)
assert.falsy(valid)
assert.are.same("age is not a number", err["flexi.somekey.age"])
end)
it("should return proper errors with a flexible schema an an unknown field", function()
local schema = {
fields = {
flexi = { type = "table",
schema = {
flexible = true,
fields = {
name = {type = "string"},
age = {type = "number"}
}
}
}
}
}
local obj = {
flexi = {
somekey = {
name = "Mark",
age = 12,
asd = "hello"
}
}
}
local valid, err = validate_entity(obj, schema)
assert.truthy(err)
assert.falsy(valid)
assert.are.same("asd is an unknown field", err["flexi.somekey.asd"])
end)
it("should return proper errors with a flexible schema with two keys and an unknown field", function()
local schema = {
fields = {
flexi = { type = "table",
schema = {
flexible = true,
fields = {
name = {type = "string"},
age = {type = "number"}
}
}
}
}
}
local obj = {
flexi = {
somekey = {
name = "Mark"
},
somekey2 = {
name = "Mark",
age = 12,
asd = "hello"
}
}
}
local valid, err = validate_entity(obj, schema)
assert.truthy(err)
assert.falsy(valid)
assert.are.same("asd is an unknown field", err["flexi.somekey2.asd"])
end)
it("errors if required sub-schema is given ngx.null", function()
local values = { some_required = "foo", sub_schema = ngx.null }
local ok, err = validate_entity(values, nested_schema)
assert.falsy(ok)
assert.same({
["sub_schema"] = "sub_schema.sub_field_required is required",
["sub_schema.sub_field_required"] = "sub_field_required is required",
["sub_schema.sub_sub_schema"] = "sub_sub_schema.sub_sub_field_required is required",
}, err)
end)
it("gives NULL to sub-schema if given ngx.null in update", function()
local values = { some_required = "foo", sub_schema = ngx.null }
local ok, err = validate_entity(values, nested_schema, { update = true })
assert.falsy(err)
assert.is_true(ok)
assert.equal(ngx.null, values.sub_schema)
end)
it("errors if required sub-schema is given ngx.null in a full update", function()
local values = { some_required = "foo", sub_schema = ngx.null }
local ok, err = validate_entity(values, nested_schema, { update = true, full_update = true })
assert.falsy(ok)
assert.same({
["sub_schema"] = "sub_schema.sub_field_required is required",
["sub_schema.sub_field_required"] = "sub_field_required is required",
["sub_schema.sub_sub_schema"] = "sub_sub_schema.sub_sub_field_required is required",
}, err)
end)
end)
describe("[update] (partial)", function()
it("should ignore required properties and defaults if we are updating because the entity might be partial", function()
local values = {}
local valid, err = validate_entity(values, schema, {update = true})
assert.falsy(err)
assert.True(valid)
assert.falsy(values.default)
assert.falsy(values.date)
end)
it("should still validate set properties", function()
local values = {string = 123}
local valid, err = validate_entity(values, schema, {update = true})
assert.False(valid)
assert.equal("string is not a string", err.string)
end)
it("should ignore immutable fields if they are required", function()
local values = {string = "somestring"}
local valid, err = validate_entity(values, schema, {update = true})
assert.falsy(err)
assert.True(valid)
end)
it("should prevent immutable fields to be changed", function()
-- Success
local values = {string = "somestring", date = 5678}
local valid, err = validate_entity(values, schema)
assert.falsy(err)
assert.truthy(valid)
-- Failure
local valid, err = validate_entity(values, schema, {update = true, old_t = {date = 1234}})
assert.False(valid)
assert.truthy(err)
assert.equal("date cannot be updated", err.date)
end)
it("passes NULL if a field with default is given ngx.null", function()
local values = { string = "foo", date = ngx.null }
local ok, err = validate_entity(values, schema, { update = true })
assert.falsy(err)
assert.is_true(ok)
assert.equal(ngx.null, values.date) -- DAO will handle ngx.null to 'NULL'
end)
it("calls 'func' with arg1 'nil' when given ngx.null", function()
spy.on(schema.fields.custom, "func")
local values = { string = "foo", custom = ngx.null }
local ok, err = validate_entity(values, schema, { update = true })
assert.falsy(err)
assert.is_true(ok)
assert.equal(ngx.null, values.custom)
assert.spy(schema.fields.custom.func).was_called_with(nil, values, "custom")
end)
it("errors when a required field is given ngx.null", function()
spy.on(schema.fields.custom, "func")
local values = { string = ngx.null }
local ok, err = validate_entity(values, schema, { update = true })
assert.falsy(ok)
assert.equal("string is required", err.string)
end)
end)
describe("[update] (full)", function()
it("should not ignore required properties", function()
local values = {}
local valid, err = validate_entity(values, schema, {update = true, full_update = true})
assert.False(valid)
assert.truthy(err)
assert.equal("string is required", err.string)
end)
it("should complete default fields", function()
local values = {string = "foo", date = 123456}
local valid, err = validate_entity(values, schema, {update = true, full_update = true})
assert.True(valid)
assert.falsy(err)
assert.equal("default", values.default)
end)
it("sets a field to its default if given ngx.null", function()
local values = { string = "foo", date = ngx.null }
local ok, err = validate_entity(values, schema, {update = true, full_update = true})
assert.falsy(err)
assert.is_true(ok)
assert.is_number(values.date)
end)
it("calls 'func' with arg1 'nil' when given ngx.null", function()
spy.on(schema.fields.custom, "func")
local values = { string = "foo", custom = ngx.null }
local ok, err = validate_entity(values, schema, { update = true, full_update = true })
assert.falsy(err)
assert.is_true(ok)
assert.is_nil(values.custom)
assert.spy(schema.fields.custom.func).was_called_with(nil, values, "custom")
end)
it("errors when a required field is given ngx.null", function()
spy.on(schema.fields.custom, "func")
local values = { string = ngx.null }
local ok, err = validate_entity(values, schema, { update = true, full_update = true })
assert.falsy(ok)
assert.equal("string is required", err.string)
end)
end)
end)
end)
|
--E・HERO フォレストマン
function c754346950.initial_effect(c)
--to hand
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(754346950,0))
e1:SetCategory(CATEGORY_TOHAND)
e1:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetCountLimit(1)
e1:SetCondition(c754346950.con)
e1:SetTarget(c754346950.tg)
e1:SetOperation(c754346950.op)
c:RegisterEffect(e1)
end
function c754346950.con(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c754346950.filter(c)
return (c:IsCode(24094653) or c:IsCode(45906428) or c:IsCode(12071500) or c:IsCode(94820406) or c:IsCode(35255456) or c:IsCode(54283059)) and c:IsAbleToHand() and not c:IsHasEffect(EFFECT_NECRO_VALLEY)
end
function c754346950.tg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c754346950.filter,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,0,1,0,LOCATION_DECK+LOCATION_GRAVE)
end
function c754346950.op(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c754346950.filter,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
|
--------------------------------------------------------------------------------
returnState = {}
--------------------------------------------------------------------------------
--function returnState.enter()
-- return returnState.enterWith({ignoreDistance = false})
--end
function returnState.enterWith(args)
if type(args) ~= "table" or args.ignoreDistance == nil then return nil end
if self.homeBin ~= nil or self.spawnPoint ~= nil then
local position = mcontroller.position()
local range = entity.configParameter("gardenSettings.wanderRange") or 60
local hPos = nil
if self.homeBin ~= nil and world.entityExists(self.homeBin) then
hPos = world.entityPosition(self.homeBin)
hPos[2] = hPos[2] - mcontroller.boundBox()[2] -- adjust for height
else
hPos = self.spawnPoint
end
local toTarget = world.distance(hPos, position)
local distance = world.magnitude(toTarget)
--if (type(args) == "table" and args.ignoreDistance) then world.logInfo("FORCED RETURN TO HOME") end
if (type(args) == "table" and args.ignoreDistance) or distance > range then
return {
targetPosition = hPos,
timer = travelTime(distance)--(entity.configParameter("gardenSettings.returnTime", 15)
}
end
end
return nil,entity.configParameter("gardenSettings.cooldown", 15)
end
--------------------------------------------------------------------------------
function returnState.update(dt, stateData)
if mcontroller.liquidMovement() then dt = dt/2 end
stateData.timer = stateData.timer - dt
if stateData.targetPosition == nil then
return true,entity.configParameter("gardenSettings.cooldown", 15)
end
local position = mcontroller.position()
local toTarget = world.distance(stateData.targetPosition, position)
local distance = world.magnitude(toTarget)
util.debugLine(mcontroller.position(),vec2.add(mcontroller.position(),toTarget),"red")
if distance < 3 * entity.configParameter("gardenSettings.interactRange") then
stateData.timer = -1
self.ignoreIds = {}
setAnimationState("movement", "idle")
else
if self.stuckCount > 50 or (stateData.timer < 0 and not canReachTarget(stateData.targetPosition)) then
local p = stateData.targetPosition
mcontroller.setPosition({p[1], p[2]})-- + 0.5 + math.abs(mcontroller.boundBox()[2])})
status.addEphemeralEffect("beamin",0.25)
mcontroller.setVelocity({0,-1 * world.gravity(mcontroller.position())})
setAnimationState("movement", "idle")
else
move({toTarget[1], toTarget[2]})
end
end
return stateData.timer <= -1,entity.configParameter("gardenSettings.cooldown", 15)
end
|
--alltypes.lua
local ffi = require("ffi")
require("bits/alltypes")
--[[
ffi.cdef[[
TYPEDEF unsigned _Addr size_t;
TYPEDEF unsigned _Addr uintptr_t;
TYPEDEF _Addr ptrdiff_t;
TYPEDEF _Addr ssize_t;
TYPEDEF _Addr intptr_t;
TYPEDEF _Addr regoff_t;
TYPEDEF _Reg register_t;
]]
ffi.cdef[[
typedef unsigned int mode_t;
typedef unsigned int nlink_t;
typedef int64_t off_t;
typedef uint64_t ino_t;
typedef uint64_t dev_t;
typedef long blksize_t;
typedef int64_t blkcnt_t;
typedef uint64_t fsblkcnt_t;
typedef uint64_t fsfilcnt_t;
typedef unsigned int wint_t;
typedef unsigned long wctype_t;
typedef void * timer_t;
typedef int clockid_t;
typedef long clock_t;
struct timeval { time_t tv_sec; suseconds_t tv_usec; };
struct timespec { time_t tv_sec; long tv_nsec; };
typedef int pid_t;
typedef unsigned int id_t;
typedef unsigned int uid_t;
typedef unsigned int gid_t;
typedef int key_t;
typedef unsigned int useconds_t;
]]
ffi.cdef[[
typedef struct _IO_FILE FILE;
]]
|
module(..., package.seeall)
function new(x,y)
local group = display.newGroup()
local redBar = display.newRect(x, y, 35, 4)
redBar.anchorX, redBar.anchorY = 0, 0
group:insert(redBar)
redBar:setFillColor(255/255, 0/255, 0/255)
local greenBar = display.newRect(x, y, 35, 4)
greenBar.anchorX, greenBar.anchorY = 0, 0
group:insert(greenBar)
greenBar:setFillColor(0/255, 255/255, 0/255)
function group:setHealth(current, max)
local percent = current / max
if percent <= 0 then
percent = 0.0001
greenBar.alpha = 0
else
greenBar.alpha = 1
end
greenBar.xScale = percent
--greenBar.x = redBar.x + greenBar.xReference
end
return group
end
|
local PLUGIN = PLUGIN;
local COMMAND = Clockwork.command:New("Drink");
COMMAND.tip = "Take a drink from a water source (You need to be standing in the water).";
COMMAND.text = "<none>";
COMMAND.flags = CMD_DEFAULT;
-- Called when the command has been run.
function COMMAND:OnRun(player, arguments)
if (player:WaterLevel() >= 1) then
player:SetCharacterData( "thirst", math.Clamp(player:GetCharacterData("thirst") - 25, 0, 100) )
player:EmitSound("npc/barnacle/barnacle_gulp1.wav");
else
Clockwork.player:Notify(player, "You aren't in water!");
end;
end;
COMMAND:Register();
|
object_mobile_hologram_rancor = object_mobile_hologram_shared_rancor:new {
}
ObjectTemplates:addTemplate(object_mobile_hologram_rancor, "object/mobile/hologram/rancor.iff")
|
function gen(n)
if n < 2 then
return n;
end
local n1 = n + 1;
local n2 = n + 2;
return n1 + n2;
end
local r = gen(4);
print(r);
|
r = math.random(#zensko_ime_nom);
name = zensko_ime_nom[r];
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by heyqule.
--- DateTime: 03/16/2020 1:56 PM
---
local ErmConfig = require('__enemyracemanager__/lib/global_config')
local ERM_UnitHelper = require('__enemyracemanager__/lib/unit_helper')
local ERM_DebugHelper = require('__enemyracemanager__/lib/debug_helper')
local Table = require('__stdlib__/stdlib/utils/table')
local String = require('__stdlib__/stdlib/utils/string')
require('util')
require('__stdlib__/stdlib/utils/defines/time')
require('__enemyracemanager__/global')
local health_multiplier = settings.startup["enemyracemanager-level-multipliers"].value
local max_hitpoint_multiplier = settings.startup["enemyracemanager-max-hitpoint-multipliers"].value
local resistance_mutiplier = settings.startup["enemyracemanager-level-multipliers"].value
-- Handles acid and poison resistance
local base_acid_resistance = 25
local incremental_acid_resistance = 55
-- Handles physical resistance
local base_physical_resistance = 0
local incremental_physical_resistance = 80
-- Handles fire and explosive resistance
local base_fire_resistance = 10
local incremental_fire_resistance = 70
-- Handles laser and electric resistance
local base_electric_resistance = 0
local incremental_electric_resistance = 80
-- Handles cold resistance
local base_cold_resistance = 25
local incremental_cold_resistance = 55
local setting_utils = require("__ArmouredBiters__/setting-utils")
local s_r = setting_utils.getPositivePercentageOf("ab-small-armoured-biter-spawn-probability")
local m_r = setting_utils.getPositivePercentageOf("ab-medium-armoured-biter-spawn-probability")
local b_r = setting_utils.getPositivePercentageOf("ab-big-armoured-biter-spawn-probability")
local bb_r = setting_utils.getPositivePercentageOf("ab-behemoth-armoured-biter-spawn-probability")
local l_r = setting_utils.getPositivePercentageOf("ab-leviathan-armoured-biter-spawn-probability")
function makeLevelSpawners(level, type)
local spawner = util.table.deepcopy(data.raw['unit-spawner'][type])
local original_hitpoint = spawner['max_health']
spawner['localised_name'] = { 'entity-name.' .. MOD_NAME .. '/' .. spawner['name'], level }
spawner['name'] = MOD_NAME .. '/' .. spawner['name'] .. '/' .. level;
spawner['max_health'] = ERM_UnitHelper.get_building_health(original_hitpoint, original_hitpoint * max_hitpoint_multiplier, health_multiplier, level)
spawner['resistances'] = {
{ type = "acid", percent = ERM_UnitHelper.get_resistance(base_acid_resistance, incremental_acid_resistance, resistance_mutiplier, level) },
{ type = "poison", percent = ERM_UnitHelper.get_resistance(base_acid_resistance, incremental_acid_resistance, resistance_mutiplier, level) },
{ type = "physical", percent = ERM_UnitHelper.get_resistance(base_physical_resistance, incremental_physical_resistance, resistance_mutiplier, level) },
{ type = "fire", percent = ERM_UnitHelper.get_resistance(base_fire_resistance, incremental_fire_resistance, resistance_mutiplier, level) },
{ type = "explosion", percent = ERM_UnitHelper.get_resistance(base_fire_resistance, incremental_fire_resistance, resistance_mutiplier, level) },
{ type = "laser", percent = ERM_UnitHelper.get_resistance(base_electric_resistance, incremental_electric_resistance, resistance_mutiplier, level) },
{ type = "electric", percent = ERM_UnitHelper.get_resistance(base_electric_resistance, incremental_electric_resistance, resistance_mutiplier, level) },
{ type = "cold", percent = ERM_UnitHelper.get_resistance(base_cold_resistance, incremental_cold_resistance, resistance_mutiplier, level) }
}
spawner['healing_per_tick'] = ERM_UnitHelper.get_building_healing(original_hitpoint, max_hitpoint_multiplier, health_multiplier, level)
local result_units = {
{ MOD_NAME .. '/small-armoured-biter/' .. level, { { 0.0, 0.3 * s_r }, { 0.6, 0.0 } } },
{ MOD_NAME .. '/medium-armoured-biter/' .. level, { { 0.2, 0.0 }, { 0.6, 0.3 * m_r }, { 0.8, 0 } } },
{ MOD_NAME .. '/big-armoured-biter/' .. level, { { 0.5, 0.0 }, { 1.0, 0.55 * b_r } } },
{ MOD_NAME .. '/behemoth-armoured-biter/' .. level, { { 0.9, 0.0 }, { 1.0, 0.35 * bb_r } } }
}
if l_r > 0 then
table.insert(result_units, { MOD_NAME .. '/leviathan-armoured-biter/' .. level, { { 0.965, 0.0 }, { 1.0, 0.05 * l_r } } })
end
spawner['result_units'] = result_units
return spawner
end
local level = ErmConfig.MAX_LEVELS
for i = 1, level do
if settings.startup["ab-enable-nest"].value then
data:extend({ makeLevelSpawners(i, 'armoured-biter-spawner') })
else
local biterSpawner = data.raw["unit-spawner"][MOD_NAME .. '/biter-spawner/' .. i]
if biterSpawner then
local unitSet = biterSpawner["result_units"]
unitSet[#unitSet + 1] = { MOD_NAME .. "/small-armoured-biter/" .. i, { { 0.0, 0.3 * s_r }, { 0.6, 0.0 } } }
unitSet[#unitSet + 1] = { MOD_NAME .. "/medium-armoured-biter/" .. i, { { 0.2, 0.0 }, { 0.6, 0.3 * m_r }, { 0.7, 0.0 } } }
unitSet[#unitSet + 1] = { MOD_NAME .. "/big-armoured-biter/" .. i, { { 0.5, 0.0 }, { 1.0, 0.55 * b_r } } }
unitSet[#unitSet + 1] = { MOD_NAME .. "/behemoth-armoured-biter/" .. i, { { 0.9, 0.0 }, { 1.0, 0.35 * bb_r } } }
if l_r > 0 then
unitSet[#unitSet + 1] = { MOD_NAME .. '/leviathan-armoured-biter/' .. level, { { 0.965, 0.0 }, { 1.0, 0.05 * l_r } } }
end
end
end
end
|
return{
{
id = 0,
name = "stand9.png",
{ tex = 1, src = {221, 4, 304, 4, 304, 182, 221, 182, }, screen = {896, 192, 2224, 192, 2224, 3040, 896, 3040, } },
type = "picture",
},
{
id = 1,
name = "stand8.png",
{ tex = 1, src = {310, 4, 392, 4, 392, 181, 310, 181, }, screen = {912, 192, 2224, 192, 2224, 3024, 912, 3024, } },
type = "picture",
},
{
id = 2,
name = "stand5.png",
{ tex = 1, src = {807, 4, 882, 4, 882, 179, 807, 179, }, screen = {1024, 224, 2224, 224, 2224, 3024, 1024, 3024, } },
type = "picture",
},
{
id = 3,
name = "stand4.png",
{ tex = 1, src = {398, 4, 470, 4, 470, 181, 398, 181, }, screen = {1056, 208, 2208, 208, 2208, 3040, 1056, 3040, } },
type = "picture",
},
{
id = 4,
name = "stand7.png",
{ tex = 1, src = {553, 4, 634, 4, 634, 180, 553, 180, }, screen = {928, 208, 2224, 208, 2224, 3024, 928, 3024, } },
type = "picture",
},
{
id = 5,
name = "stand6.png",
{ tex = 1, src = {640, 4, 718, 4, 718, 179, 640, 179, }, screen = {976, 224, 2224, 224, 2224, 3024, 976, 3024, } },
type = "picture",
},
{
id = 6,
name = "stand1.png",
{ tex = 1, src = {4, 4, 129, 4, 129, 186, 4, 186, }, screen = {720, 208, 2720, 208, 2720, 3120, 720, 3120, } },
type = "picture",
},
{
id = 7,
name = "stand3.png",
{ tex = 1, src = {476, 4, 547, 4, 547, 181, 476, 181, }, screen = {1056, 208, 2192, 208, 2192, 3040, 1056, 3040, } },
type = "picture",
},
{
id = 8,
name = "stand2.png",
{ tex = 1, src = {135, 4, 215, 4, 215, 184, 135, 184, }, screen = {1008, 144, 2288, 144, 2288, 3024, 1008, 3024, } },
type = "picture",
},
{
id = 9,
name = "stand10.png",
{ tex = 1, src = {724, 4, 801, 4, 801, 179, 724, 179, }, screen = {992, 224, 2224, 224, 2224, 3024, 992, 3024, } },
type = "picture",
},
{
id = 10,
type = "animation",
export = "stand",
component = {
{id = 6},
{id = 8},
{id = 7},
{id = 3},
{id = 2},
{id = 5},
{id = 4},
{id = 1},
{id = 0},
{id = 9},
},
{
{{index = 0, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 0, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 1, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 1, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 2, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 2, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 3, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 3, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 4, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 4, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 5, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 5, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 6, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 6, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 7, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 7, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 8, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 8, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 9, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 9, mat = {1024, 0, 0, 1024, 0, 0}},},
{{index = 0, mat = {1024, 0, 0, 1024, 0, 0}},},
},
},
}
|
-- An iterator of files
local ffi = require("ffi")
local w32 = require("peettles.w32")
local FileSystemItem = require("FileSystemItem");
local k32Lib = ffi.load("kernel32");
local function file_iter_gen(param, status)
if status == 0 then
-- close the handle
if (param.RawHandle ~= INVALID_HANDLE_VALUE) then
k32Lib.CloseHandle(param.RawHandle);
end
return nil;
end
local value = {
BasePath = param.BasePath;
Attributes = param.FileData.dwFileAttributes;
Name = w32.toAnsi(param.FileData.cFileName);
Size = (param.FileData.nFileSizeHigh * (MAXDWORD+1)) + param.FileData.nFileSizeLow;
};
value.FullPath = value.BasePath..'\\'..value.Name;
-- move to the next one before we return
local status = k32Lib.FindNextFileW(param.RawHandle, param.FileData);
return status, value;
end
local function fileiterator(basepath, filter)
local pattern = basepath..'\\'..filter
local lpFileName = w32.toUnicode(pattern);
local fInfoLevelId = ffi.C.FindExInfoBasic;
local lpFindFileData = ffi.new("WIN32_FIND_DATAW");
local fSearchOp = ffi.C.FindExSearchNameMatch;
local lpSearchFilter = nil;
local dwAdditionalFlags = 0;
local rawHandle = k32Lib.FindFirstFileExW(lpFileName,
fInfoLevelId,
lpFindFileData,
fSearchOp,
lpSearchFilter,
dwAdditionalFlags);
--print("rawHandle: ", rawHandle)
local status = 1
if (rawHandle == INVALID_HANDLE_VALUE) then
status = 0
end
return file_iter_gen, {FileData = lpFindFileData, RawHandle = rawHandle, BasePath = basepath, Filter = filter}, status
end
return fileiterator
|
object_tangible_collection_dancing_droid_01 = object_tangible_collection_shared_dancing_droid_01:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_dancing_droid_01, "object/tangible/collection/dancing_droid_01.iff")
|
local util = require "util"
local core = {}
local logger = log.getLogger("core")
local tinsert = table.insert
---@class AccessoryConf:table Accessory configuration.
---
---@field plugin string Plugin name.
---@class PluginConf:table Plugin configuration.
---
---@field name string Plugin name.
---@class Plugin:table Plugin.
---
---@field init fun(conf: PluginConf|nil, report: fun(plugin: string, accessory: HapAccessory)): boolean Initialize plugin.
---@field deinit fun() Deinitialize plugin.
---@field gen fun(conf: AccessoryConf): HapAccessory|nil Generate accessory via configuration.
---@field isPending fun(): boolean Whether the accessory is waiting to be generated.
local priv = {
plugins = {},
accessories = {},
done = nil
}
---Report generated bridged accessory.
---@param name string Plugin name.
---@param accessory HapAccessory Accessory.
local function _report(name, accessory)
tinsert(priv.accessories, accessory)
if priv.plugins[name].isPending() == false then
priv.plugins[name] = nil
if util.isEmptyTable(priv.plugins) then
priv.done(priv.accessories)
priv.accessories = {}
priv.done = nil
end
end
end
---Load plugin.
---@param name string Plugin name.
---@param conf? PluginConf Plugin configuration.
---@return Plugin|nil
local function loadPlugin(name, conf)
if priv.plugins[name] then
return priv.plugins[name]
end
local plugin = require(name .. ".plugin")
if util.isEmptyTable(plugin) then
return nil
end
local fields = {
init = "function",
deinit = "function",
gen = "function",
isPending = "function",
}
for k, t in pairs(fields) do
if not plugin[k] then
logger:error(("No field '%s' in plugin '%s'"):format(k, name))
return nil
end
local _t = type(plugin[k])
if _t ~= t then
logger:error(("%s.%s: type error, expected %s, got %s"):format(name, k, t, _t))
return nil
end
end
if plugin.init(conf, _report) == false then
logger:error(("Failed to init plugin '%s'"):format(name))
return nil
end
priv.plugins[name] = plugin
return plugin
end
---Load plugins and generate bridged accessories.
---@param pluginConfs PluginConf[] Plugin configurations.
---@param accessoryConfs AccessoryConf[] Accessory configurations.
---@param done async fun(bridgedAccessories: HapAccessory[]) Function called after the bridged accessories is generated.
function core.start(pluginConfs, accessoryConfs, done)
if pluginConfs then
for _, conf in ipairs(pluginConfs) do
loadPlugin(conf.name, conf)
end
end
if accessoryConfs then
for _, conf in ipairs(accessoryConfs) do
local plugin = loadPlugin(conf.plugin)
if plugin ~= nil then
tinsert(priv.accessories, plugin.gen(conf))
end
end
end
for name, plugin in pairs(priv.plugins) do
if plugin.isPending() == false then
priv.plugins[name] = nil
end
end
if util.isEmptyTable(priv.plugins) then
done(priv.accessories)
priv.accessories = {}
else
priv.done = done
end
end
return core
|
-----------------------------------
-- Area: Norg
-- NPC: Vuliaie
-- Type: Tenshodo Merchant
-- !pos -24.259 0.891 -19.556 252
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/keyitems");
local ID = require("scripts/zones/Norg/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:hasKeyItem(tpz.ki.TENSHODO_MEMBERS_CARD)) then
if (player:sendGuild(60424,9,23,7)) then
player:showText(npc, ID.text.VULIAIE_SHOP_DIALOG);
end
else
-- player:startEvent(150);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
|
return function(Sunshine, entity)
local hazard = entity.hazard
local collider = entity.collider
if hazard and collider then
Sunshine:update(function()
for _,hitEntity in pairs(collider.hitEntities) do
if hitEntity and hitEntity.health and not hitEntity.health.invulnerable then
hitEntity.health.invulnerable = true
hitEntity.health.health = hitEntity.health.health - hazard.damage
end
end
end, entity)
end
end
|
-- http.lua - implements fetching of documents via HTTP(S)
function GET(url, headers)
-- If it's just a basic HTTP GET, use the socket.http library
if not headers and url:match("^http://") then
local b, c, h = http.request(url)
return b or ""
else
-- Cut URL into scheme, domain, port and URI
local scheme, domain, uri = url:match("^([a-z]+)://([^/]+)(/.*)$")
local port = domain:match(":(%d+)$") or (scheme == "http" and 80 or 443)
domain = domain:match("^([^:]+)")
-- plain HTTP connection
if scheme == "http" then
local response_body = {}
local b, c, h = http.request{
url = url,
sink = ltn12.sink.table(response_body),
headers = headers,
redirect = false
}
return table.concat(response_body, "")
-- HTTPS requests
elseif scheme == "https" then
local ssl_params = {
mode = "client",
protocol = "sslv23",
verify = "none",
options = "all",
}
local ip = socket.dns.toip(domain)
local try = socket.try
local protect = socket.protect
function create()
local t = {c=socket.tcp()}
function idx (tbl, key)
return function (prxy, ...)
local c = prxy.c
return c[key](c,...)
end
end
function t:connect(host, port)
self.c:settimeout(15)
port = 443 -- XXX: bug-sy malone?
local success, err = self.c:connect(host, port)
if err then
print(err)
end
self.c = try(ssl.wrap(self.c,ssl_params))
local s = try(self.c:dohandshake())
return 1
end
return setmetatable(t, {__index = idx})
end
local response_body = {}
local b, c, h = http.request{
url = url,
headers = headers,
sink = ltn12.sink.table(response_body),
create = create,
redirect = false
}
return table.concat(response_body, "")
end
end
end
|
-----------------------------------
-- Area: Waughroon Shrine
-- Mob: Seeker
-- Mission 2-3 BCNM Fight
-----------------------------------
require("scripts/globals/status")
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(tpz.mobMod.HP_STANDBACK, 50)
end
function onMobDeath(mob, player, isKiller)
end
|
function getPlayerFromSerial ( serial )
assert ( type ( serial ) == "string" and #serial == 32, "getPlayerFromSerial - invalid serial" )
for index, player in ipairs ( getElementsByType ( "player" ) ) do
if ( getPlayerSerial ( player ) == serial ) then
return player
end
end
return false
end
function getPedWeapons(ped)
local playerWeapons = {}
if ped and isElement(ped) and getElementType(ped) == "ped" or getElementType(ped) == "player" then
for i=0, 12 do
local wep = getPedWeapon(ped, i)
local ammo = getPedTotalAmmo (ped, i);
if wep and wep ~= 0 and ammo ~= 0 then
table.insert(playerWeapons, {id = wep, ammo = ammo});
end
end
else
return false
end
return playerWeapons
end
function findPlayer (name)
local name = name and name:gsub("#%x%x%x%x%x%x", ""):lower() or nil
if name then
for _, player in ipairs(getElementsByType("player")) do
local name_ = getPlayerName(player):gsub("#%x%x%x%x%x%x", ""):lower()
if name_:find(name, 1, true) then
return player
end
end
end
end
|
local Cone = {}
function Cone.negotiate(header, available_values)
if available_values == nil or available_values == {} then
return nil
end
if header == nil or header == '' then
return available_values[1]
end
header = header:gsub('%s+', '')
acceptable_values = {}
unacceptable_values = {}
for qualified_value in header:gmatch('([^,]+)') do
value, quality = Cone.parse_qualified_value(qualified_value)
if quality == 0 then
table.insert(unacceptable_values, value)
else
table.insert(acceptable_values, { value, quality})
end
end
-- Sort the values by quality in descending order.
table.sort(acceptable_values, function(a, b) return a[2] > b[2] end)
for _, qualified_acceptable_value in ipairs(acceptable_values) do
acceptable_value = qualified_acceptable_value[1]
for _, available_value in pairs(available_values) do
if acceptable_value == available_value then
return acceptable_value
end
end
end
for _, available_value in ipairs(available_values) do
if not contains(available_value, unacceptable_values) then
return available_value
end
end
return available_values[1]
end
function Cone.parse_qualified_value(qualified_value)
if qualified_value:find(';q=') then
value, quality = qualified_value:match("(.*)%;q=(.*)")
quality = tonumber(quality)
else
value = qualified_value
quality = 1
end
return value, quality
end
function contains(needle, haystack)
for _, haystack_value in pairs(haystack) do
if haystack_value == needle then
return true
end
end
return false
end
return Cone
|
--[[
confetteSpawn
Spawns item when confette'd
]]--
-- Variables --
confette = {}
confette.item = 39 -- Item to throw (6 = ball, 39 = apple)
confette.defSpeed = 10 -- Speed of throw
confette.height = 5 -- Height of throw
confette.defAngle = 90 -- Angle of item
confette.defOffset = 30 -- In front of mouse
-- --
-- Events --
-- When someone does an emote
function eventEmotePlayed (player, emoteId)
if (emoteId == 9) then
throwConfette (player, confette.item)
elseif (emoteId == 5) then
throwConfette(player, 17, true)
end
end
-- --
-- Functions --
-- Throw item on confette
function throwConfette (player, item, ghost)
-- Player values
t = tfm.get.room.playerList[player]
vx = t["vx"] -- Velocity x
vy = t["vy"] -- Velocity y
jump = t["isJumping"]
movLeft = t["movingLeft"]
movRight = t["movingRight"]
adj = 15 -- Adjustment
x = t["x"] + vx + tern(movLeft, -adj, 0) + tern(movRight, adj, 0)
y = t["y"] + vy + tern(jump, -adj, 0)
faceRight = t["isFacingRight"]
-- Check which side to throw depending on faceRight
angle = tern(faceRight, confette.defAngle, -confette.defAngle)
speed = tern(faceRight, confette.defSpeed, -confette.defSpeed)
offset = tern(faceRight, confette.defOffset, -confette.defOffset)
height = -confette.height
-- Throw item
tfm.exec.addShamanObject(item, x+offset, y, angle, speed, height, ghost)
end
--
-- Ternary
function tern (cond, T, F)
if cond then return T else return F end
end
-- Short tostring
function tostr(str) return tostring(str) end
-- --
|
return {
armpeep = {
acceleration = 0.21562,
bankscale = 1,
blocking = false,
brakerate = 0.0112,
buildcostenergy = 1352,
buildcostmetal = 35,
builder = false,
buildpic = "armpeep.dds",
buildtime = 2100,
canfly = true,
canguard = true,
canmove = true,
canpatrol = true,
canstop = 1,
category = "ALL MOBILE SCOUT VTOL",
collide = false,
cruisealt = 180,
defaultmissiontype = "VTOL_standby",
description = "Scout Plane",
explodeas = "SMALL_UNITEX",
footprintx = 2,
footprintz = 2,
icontype = "air",
idleautoheal = 5,
idletime = 1800,
losemitheight = 4,
maneuverleashlength = 1280,
mass = 35,
maxdamage = 80,
maxslope = 10,
maxvelocity = 13.8,
maxwaterdepth = 0,
mobilestandorders = 1,
name = "Peeper",
noautofire = false,
objectname = "ARMPEEP",
radardistance = 1000,
radaremitheight = 4,
seismicsignature = 0,
selfdestructas = "BIG_UNIT_VTOL",
selfdestructcountdown = 1,
sightdistance = 850,
standingmoveorder = 1,
steeringmode = 1,
turninplaceanglelimit = 140,
turninplacespeedlimit = 9.108,
turnrate = 880,
unitname = "armpeep",
customparams = {
buildpic = "armpeep.dds",
faction = "ARM",
},
sfxtypes = {
pieceexplosiongenerators = {
[1] = "piecetrail0",
[2] = "piecetrail1",
[3] = "piecetrail2",
[4] = "piecetrail3",
[5] = "piecetrail4",
[6] = "piecetrail6",
},
},
sounds = {
canceldestruct = "cancel2",
underattack = "warning1",
cant = {
[1] = "cantdo4",
},
count = {
[1] = "count6",
[2] = "count5",
[3] = "count4",
[4] = "count3",
[5] = "count2",
[6] = "count1",
},
ok = {
[1] = "vtolarmv",
},
select = {
[1] = "vtolarac",
},
},
},
}
|
return {'fouilleren','fouillering','fouilleringsactie','fouilleringsbevoegdheid','foulard','foundation','fourieranalyse','fourierreeks','fourierreeksontwikkeling','fouriertransformatie','fourneren','fournituren','fourniturenzaak','fournituur','fourragere','fourwheeldrive','fout','foutafhandeling','foutanalyse','foutcorrectie','foutenbron','foutenfestival','foutenlast','foutenlijst','foutenlijsten','foutenmarge','foutenpercentage','foutenverzameling','foutgevoelig','foutherstel','foutief','foutlijn','foutloos','foutmarge','foutmelding','foutparkeerder','foutparkeren','foutspelling','foutverbetering','foutvrij','foutslag','foutcode','foutbericht','foutenanalyse','foutenrapport','foutkans','foutloosheid','fouttolerantie','foutpercentage','foutboodschap','fouad','fouchier','fouilleer','fouilleerde','fouilleerden','fouilleert','foulards','fourierreeksen','fouriertransformaties','fourneer','fourneerde','fourneerden','fourneert','foute','fouten','foutenbronnen','foutenmarges','fouter','foutieve','foutje','foutjes','foutloze','foutlozer','foutmeldingen','foutverbeteringen','fouilleringen','foundations','fourwheeldrives','foutenpercentages','foutlijnen','foutmarges','foutparkeerders','foutgeparkeerd','foutslagen','fouads','foutcodes','foutberichten','foutgevoelige','foutvrije','foutboodschappen','foutkansen','fouilleringsacties','foutste','foutst'}
|
local modes, config, data, FILE_PATH = ...
if data.lang ~= "en" then
local tmp = FILE_PATH .. "lang_" .. data.lang .. ".luac"
local fh = io.open(tmp)
if fh ~= nil then
io.close(fh)
loadfile(tmp)(modes, config)
collectgarbage()
end
end
if data.voice ~= "en" then
local fh = io.open(FILE_PATH .. data.voice .. "/on.wav")
if fh ~= nil then
io.close(fh)
else
data.voice = "en"
end
end
return 0
|
-- outputdir need to be defined, like:
-- outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
project "utils"
language "C++"
architecture "x86_64"
cppdialect "C++17"
kind "StaticLib"
warnings "Default"
location ""
targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}")
objdir ("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}")
files {
"src/**.h",
"src/**.cpp"
}
filter "platforms:WASM"
linkoptions { "-s WASM=1", "-s EXPORTED_RUNTIME_METHODS='[\"cwrap\"]'" }
targetname ("%{prj.name}.html")
filter "platforms:Linux"
targetname ("%{prj.name}")
|
---------------------------------
----------- VIM-TEST ------------
---------------------------------
-- vim.g['test#strategy'] = 'tslime'
-- vim.g.tslime_always_current_session = 1
-- vim.g.tslime_autoset_pane = 1
--
-- vim.g.tslime = {
-- ['session'] = '0',
-- ['window'] = 3,
-- }
-- vim.api.nvim_exec(
-- [[
-- let g:tslime = {}
-- let sessions = split(system('tmux list-panes -F "active=#{pane_active} #{session_name},#{window_index},#{pane_index}" | grep "active=1" | cut -d " " -f 2 | tr , "\n"'), '\n')
-- let g:tslime['session'] = sessions[0]
-- let g:tslime['window'] = 3
-- let g:tslime['pane'] = 0
-- ]],
-- true
-- )
-- test invocation
-- vim.api.nvim_set_keymap('n', '<Leader>ta', ':TestSuite<CR>', default_opts)
-- vim.api.nvim_set_keymap('n', '<Leader>tf', ':TestFile<CR>', default_opts)
-- vim.api.nvim_set_keymap('n', '<Leader>tn', ':TestNearest<CR>', default_opts)
---------------------------------
---------- VIM-ULTEST -----------
---------------------------------
local ultest = require('ultest')
vim.g.ultest_max_threads = 5
vim.g.ultest_use_pty = 1
ultest.setup({})
-- vim.api.nvim_set_keymap('n', '', '<Plug>(ultest-next-fail)', default_opts) -- Jump to next failed test.
-- vim.api.nvim_set_keymap('n', '', '<Plug>(ultest-prev-fail)', default_opts) -- Jump to previous failed test.
vim.api.nvim_set_keymap('n', '<Leader>tf', '<Plug>(ultest-run-file)', {}) -- Run all tests in a file.
vim.api.nvim_set_keymap('n', '<Leader>tn', '<Plug>(ultest-run-nearest)', {}) -- Run test closest to the cursor.
vim.api.nvim_set_keymap('n', '<Leader>tso', '<cmd>UltestSummary<CR>', default_opts) -- Toggle the summary window between open and closed
-- vim.api.nvim_set_keymap('n', '<Leader>tsj', '<Plug>(ultest-summary-jump)', default_opts) -- Jump to the summary window (opening if it isn't already)
-- vim.api.nvim_set_keymap('n', '<Leader>tos', '<Plug>(ultest-output-show)', default_opts) -- Show error output of the nearest test. (Will jump to popup window in Vim)
-- vim.api.nvim_set_keymap('n', '', '<Plug>(ultest-output-jump)', default_opts) -- Show error output of the nearest test. (Same behabviour as <Plug>(ultest-output-show) in Vim)
-- vim.api.nvim_set_keymap('n', '<Leader>ta', '<Plug>(ultest-attach)', default_opts) -- Attach to the nearest test's running process.
-- vim.api.nvim_set_keymap('n', '', '<Plug>(ultest-stop-file)', default_opts) -- Stop all running jobs for current file
-- vim.api.nvim_set_keymap('n', '', '<Plug>(ultest-stop-nearest)', default_opts) -- Stop any running jobs for nearest test
-- vim.api.nvim_set_keymap('n', '', '<Plug>(ultest-debug)', default_opts) -- Debug the current file with nvim-dap
-- vim.api.nvim_set_keymap('n', '', '<Plug>(ultest-debug-nearest)', default_opts) -- Debug the nearest test with nvim-dap
|
local hotload = require "hotload"
local dom = hotload "dom"
return function(path, method, status, message)
assert(type(path) == "string", "view is missing parameters")
return dom{
dom["!doctype"] "html",
dom.html{
dom.header{
dom.title(tostring(status or "error")),
dom.meta{charset = "utf-8"}
},
dom.body{
dom.h1 "server could not respond to your request",
dom.div(string.format("requested url: %s", path)),
method and dom.div(string.format("request method: %s", method)),
status and dom.div(string.format("response status code: %s", status)),
message and dom.div(string.format("response message: %s", message))
}
}
}.htmlsource
end
|
--[[
Title: Explorer App
Author(s): big
CreateDate: 2019.01.18
ModifyDate: 2021.12.16
Desc: This is explorer app
Place: Foshan
use the lib:
------------------------------------------------------------
NPL.load('(gl)Mod/ExplorerApp/main.lua')
local ExplorerApp = commonlib.gettable('Mod.ExplorerApp')
------------------------------------------------------------
]]
NPL.load('(gl)Mod/ExplorerApp/store/ExplorerStore.lua')
NPL.load('(gl)script/ide/System/Core/UniString.lua')
NPL.load('(gl)script/apps/Aries/Creator/Game/Login/LocalLoadWorld.lua')
NPL.load('(gl)script/apps/Aries/Creator/Game/Common/Translation.lua')
-- store
local ExplorerStore = commonlib.gettable('Mod.ExplorerApp.store.Explorer')
-- pages
local MainPage = NPL.load('(gl)Mod/ExplorerApp/pages/MainPage/MainPage.lua')
local GameOver = NPL.load('(gl)Mod/ExplorerApp/pages/GameProcess/GameOver/GameOver.lua')
-- utils
local Utils = NPL.load('(gl)Mod/WorldShare/helper/Utils.lua')
-- filters
local Filters = NPL.load('(gl)Mod/ExplorerApp/filters/Filters.lua')
local ExplorerApp = commonlib.inherit(commonlib.gettable('Mod.ModBase'), commonlib.gettable('Mod.ExplorerApp'))
ExplorerApp:Property({'Name', 'ExplorerApp', 'GetName', 'SetName', { auto = true }})
ExplorerApp:Property({'Desc', 'This is explorer app', 'GetDesc', 'SetDesc', { auto = true }})
ExplorerApp.version = '0.0.5'
LOG.std(nil, 'info', 'ExplorerApp', 'explorer app version %s', ExplorerApp.version)
function ExplorerApp:init()
Filters:Init()
end
function ExplorerApp:Init(callback, classId, defaulOpenValue)
if not Mod or not Mod.WorldShare then
_guihelper.MessageBox(L'ExplorerApp 依赖 WorldShare Mod')
return false
end
-- register explorer store to store list
Mod.WorldShare.Store.storeList.explorer = ExplorerStore
MainPage:ShowPage(callback, classId, defaulOpenValue)
end
function ExplorerApp:OnWorldLoad()
end
|
function NS2Gamerules_GetUpgradedAlienDamage( target, attacker, doer, damage, armorFractionUsed, healthPerArmor, damageType, hitPoint, weapon )
if attacker:GetHasUpgrade( kTechId.Crush ) then --CragHive
local spurLevel = GetSpurLevel( kTeam2Index )
if spurLevel > 0 then
if target:isa("Exo") or target.GetReceivesStructuralDamage and target:GetReceivesStructuralDamage(damageType) then
damage = damage + ( damage * ( spurLevel * kAlienCrushDamagePercentByLevel ) )
elseif target:isa("Player") then
armorFractionUsed = kBaseArmorUseFraction + ( spurLevel * kAlienCrushDamagePercentByLevel )
end
end
end
if Server then
if attacker:GetHasUpgrade( kTechId.Vampirism ) and target:isa("Player") then --ShadeHive
local shellLevel = GetShellLevel( kTeam2Index )
if shellLevel > 0 then
local leechedHealth = NS2Gamerules_GetAlienVampiricLeechFactor( attacker, doer, damageType, shellLevel )
if attacker:GetIsAlive() then
attacker:AddHealth( leechedHealth, true, kAlienVampirismNotHealArmor ) --TODO Find better method/location to perform this
end
end
end
end
if attacker:GetHasUpgrade( kTechId.Focus ) and DoesFocusAffectAbility(weapon) then
local veilLevel = GetVeilLevel( kTeam2Index )
local damageBonus = kAlienFocusDamageBonusAtMax
if weapon == kTechId.Spit then -- gorge spit is a special case
damageBonus = kGorgeSpitDamageBonusAtMax
elseif weapon == kTechId.Stab then -- preparing for anticipated changes...
damageBonus = kStabDamageBonusAtMax
end
damage = damage * (1 + (veilLevel/3) * damageBonus) --1.0, 1.333, 1.666, 2
end
--!!!Note: if more than damage and armor fraction modified, be certain the calling-point of this function is updated
return damage, armorFractionUsed
end
|
local BasePlugin = require "kong.plugins.base_plugin"
local CtxCheckerHandler = BasePlugin:extend()
CtxCheckerHandler.PRIORITY = 1000
local function get_ctx(ctx_kind)
if ctx_kind == "kong.ctx.shared" then
return kong.ctx.shared
end
if ctx_kind == "kong.ctx.plugin" then
return kong.ctx.plugin
end
return ngx.ctx
end
local function set_header(conf, name, value)
if conf.ctx_kind == "kong.ctx.shared"
or conf.ctx_kind == "kong.ctx.plugin" then
return kong.response.set_header(name, value)
end
ngx.header[name] = value
end
function CtxCheckerHandler:new()
CtxCheckerHandler.super.new(self, "ctx-checker")
end
function CtxCheckerHandler:access(conf)
CtxCheckerHandler.super.access(self)
local set_field = conf.ctx_set_field
if not set_field then
return
end
local ctx = get_ctx(conf.ctx_kind)
if ctx[set_field] and conf.throw_error then
error("Expected to be able to set" ..
conf.ctx_kind,
"['" .. set_field ..
"'] but it was already set. Found value: " ..
tostring(ctx[set_field]))
end
ctx[set_field] = conf.ctx_set_value
end
function CtxCheckerHandler:header_filter(conf)
CtxCheckerHandler.super.header_filter(self)
local check_field = conf.ctx_check_field
if not check_field then
return
end
local ctx = get_ctx(conf.ctx_kind)
if not conf.ctx_check_value or ctx[check_field] == conf.ctx_check_value then
set_header(conf,
self._name .. "-" .. check_field,
ctx[check_field])
end
if conf.throw_error then
error("Expected " .. conf.ctx_kind .. "['" ..
check_field .. "'] to be set, but it was " .. tostring(ctx[check_field]))
end
end
return CtxCheckerHandler
|
---@meta
--- websocket object
--- https://github.com/openresty/lua-resty-websocket
---
---@class resty.websocket : table
---@field sock tcpsock
---@field fatal boolean
---@field max_payload_len number
---@field send_masked boolean
resty_websocket = {}
---@param ms integer sets the timeout delay (in milliseconds) for the network-related operations
function resty_websocket:set_timeout(ms) end
---Sends the text argument out as an unfragmented data frame of the text type.
---
---Returns the number of bytes that have actually been sent on the TCP level.
---
---In case of errors, returns nil and a string describing the error.
---
---@param text string
---@return integer? bytes
---@return string? error
function resty_websocket:send_text(text) end
---Sends the data argument out as an unfragmented data frame of the binary type.
---
---Returns the number of bytes that have actually been sent on the TCP level.
---
---In case of errors, returns nil and a string describing the error.
---
---@param data string
---@return integer? bytes
---@return string? error
function resty_websocket:send_binary(data) end
---Sends out a ping frame with an optional message specified by the msg argument.
---Returns the number of bytes that have actually been sent on the TCP level.
---
---In case of errors, returns nil and a string describing the error.
---
---Note that this method does not wait for a pong frame from the remote end.
---
---@param msg? string
---@return integer? bytes
---@return string? error
function resty_websocket:send_ping(msg) end
---Sends out a pong frame with an optional message specified by the msg argument.
---Returns the number of bytes that have actually been sent on the TCP level.
---
---In case of errors, returns nil and a string describing the error.
---@param msg? string
---@return integer? bytes
---@return string? error
function resty_websocket:send_pong(msg) end
---Sends out a close frame with an optional status code and a message.
---
---In case of errors, returns nil and a string describing the error.
---
---For a list of valid status code, see the following document:
---
---http://tools.ietf.org/html/rfc6455#section-7.4.1
---
---Note that this method does not wait for a close frame from the remote end.
---@param code? integer
---@param msg? string
---@return integer? bytes
---@return string? error
function resty_websocket:send_close(code, msg) end
---Sends out a raw websocket frame by specifying the fin field (boolean value), the opcode, and the payload.
---
---For a list of valid opcode, see
---
---http://tools.ietf.org/html/rfc6455#section-5.2
---
---In case of errors, returns nil and a string describing the error.
---
---To control the maximal payload length allowed, you can pass the max_payload_len option to the new constructor.
---
---To control whether to send masked frames, you can pass true to the send_masked option in the new constructor method. By default, unmasked frames are sent.
---@param fin boolean
---@param opcode resty.websocket.protocol.opcode
---@param payload string
---@return integer? bytes
---@return string? error
function resty_websocket:send_frame(fin, opcode, payload) end
---Receives a WebSocket frame from the wire.
---
---In case of an error, returns two nil values and a string describing the error.
---
---The second return value is always the frame type, which could be one of continuation, text, binary, close, ping, pong, or nil (for unknown types).
---
---For close frames, returns 3 values: the extra status message (which could be an empty string), the string "close", and a Lua number for the status code (if any). For possible closing status codes, see
---
---http://tools.ietf.org/html/rfc6455#section-7.4.1
---
---For other types of frames, just returns the payload and the type.
---
---For fragmented frames, the err return value is the Lua string "again".
---
---@return string? data
---@return resty.websocket.protocol.type? typ
---@return string|integer? error_or_status_code
function resty_websocket:recv_frame() end
---@class resty.websocket.new.opts : table
---@field max_payload_len integer maximal length of payload allowed when sending and receiving WebSocket frames
---@field send_masked boolean whether to send out masked WebSocket frames
---@field timeout integer network timeout threshold in milliseconds
return resty_websocket
|
function player_init()
player_x = 10 * 8
player_y = 10 * 8
player_dir = 0
player_coins = 10
player_seeds = 0
player_movecount = 0
player_was_interact_pressed = false
end
function player_tick()
local xm = 0
local ym = 0
if key(0) then ym = ym - 1 end
if key(1) then xm = xm - 1 end
if key(2) then ym = ym + 1 end
if key(3) then xm = xm + 1 end
player_move(xm, ym)
if key(4) then
if not player_was_interact_pressed then
player_interact()
player_was_interact_pressed = true
end
else
player_was_interact_pressed = false
end
player_render()
end
function player_render()
local spr_id = -1
if player_dir == 0 then spr_id = 16
else spr_id = 17 end
local move_phase = math.floor((player_movecount + 9) / 10) % 2
spr_id = spr_id + 16 * move_phase
spr(spr_id, player_x - 4, player_y - 4)
end
function player_move(xm, ym)
if xm ~= 0 or ym ~= 0 then
player_movecount = player_movecount + 1
else
player_movecount = 0
return
end
local xt0 = (player_x - 4) / 8
local yt0 = (player_y - 4) / 8
local xt1 = (player_x + 4) / 8
local yt1 = (player_y + 4) / 8
local new_x = player_x + xm
local new_y = player_y + ym
local xto0 = (new_x - 4) / 8
local yto0 = (new_y - 4) / 8
local xto1 = (new_x + 4) / 8
local yto1 = (new_y + 4) / 8
local can_move_x = true
local can_move_y = true
for y = yto0, yto1 do
if y < 0 or y >= map_h then can_move_y = false end
for x = xto0, xto1 do
if x < 0 or x >= map_w then can_move_x = false end
end
end
if can_move_x then player_x = new_x end
if can_move_y then player_y = new_y end
if xm < 0 then player_dir = 0
elseif xm > 0 then player_dir = 1 end
end
function player_interact()
local interact_x = player_x
local interact_y = player_y
local interact_xt = math.floor(interact_x / 8)
local interact_yt = math.floor(interact_y / 8)
player_interact_on_tile(interact_xt, interact_yt)
end
function player_interact_on_tile(xt, yt)
if xt < 0 or xt >= map_w or yt < 0 or yt >= map_h then
return
end
t_id = get_tile(xt, yt)
if t_id == 0 then -- dirt tile without seeds
player_try_plant(xt, yt)
elseif t_id >= 1 and t_id <= 4 then -- dirt with seeds/crops
player_harvest(xt, yt)
elseif (t_id >= 48 and t_id <= 51) or (t_id >= 64 and t_id <= 67) then -- buy seeds tiles
player_try_buy()
end
end
function player_try_plant(xt, yt)
if player_seeds > 0 then
player_seeds = player_seeds - 1
level_set_tile(xt, yt, 1)
sfx('plant_seed')
end
end
function player_harvest(xt, yt)
local tile = get_tile(xt, yt)
if tile == 3 then -- perfect grown crop
player_coins = player_coins + math.random(2, 6)
if player_coins >= 1000 then
win_game()
end
end
level_set_tile(xt, yt, 0) -- set clean dirt
sfx('harvest')
end
function player_try_buy()
if player_coins > 0 then
player_seeds = player_seeds + 1
player_coins = player_coins - 1
sfx('buy_seed')
end
end
|
Queue = {}
Queue.first = nil
Queue.last = nil
Queue.N = 0
Queue.node = {}
Queue.node.value = nil
Queue.node.next = nil
function Queue:Enqueue(value)
local oldLast = self.last
self.last = self.node(value)
if oldLast ~= nil then
oldLast.next = self.last
end
if self.first == nil then
self.first = self.last
end
self.N = self.N + 1
end
function Queue:Dequeue()
local oldFirst = self.first
if oldFirst == nil then
return nil
end
local value = oldFirst.value
self.first = oldFirst.next
self.N = self.N - 1
if self.first == nil then
self.last = nil
end
return value
end
function Queue:Size()
return self.N
end
function Queue:IsEmpty()
return self.N == 0
end
function Queue:Clear()
self.first = nil
self.last = nil
self.N = 0
end
return Queue
|
--- items ---
--[[ -- keep this --
minetest.register_craftitem("beer_test:barrle_tap", {
description = "Barrel Tap",
inventory_image = "default_paper.png",
})
]] --
-----------------
-- beer barrle --
-----------------
minetest.register_node("beer_test:barrel", {
description = "Barrel",
drawtype = "nodebox",
tiles = {"beer_test_barrel_top.png", "beer_test_barrel_top.png", "beer_test_barrel_side_2.png",
"beer_test_barrel_side_2.png", "beer_test_barrel_side_2.png", "beer_test_barrel_side_2.png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {cracky=2},
sounds = default.node_sound_wood_defaults(),
on_punch = function(pos, node, puncher)
local tool = puncher:get_wielded_item():get_name()
if tool and tool == "beer_test:mixed_beer_grain" then
node.name = "beer_test:barrel_mixed_beer_grain"
minetest.env:set_node(pos, node)
puncher:get_inventory():remove_item("main", ItemStack("beer_test:mixed_beer_grain"))
end
local tool = puncher:get_wielded_item():get_name()
if tool and tool == "beer_test:mixed_ale_grain" then
node.name = "beer_test:barrel_mixed_ale_grain"
minetest.env:set_node(pos, node)
puncher:get_inventory():remove_item("main", ItemStack("beer_test:mixed_ale_grain"))
end
local tool = puncher:get_wielded_item():get_name()
if tool and tool == "beer_test:mixed_mead_grain" then
node.name = "beer_test:barrel_mixed_mead_grain"
minetest.env:set_node(pos, node)
puncher:get_inventory():remove_item("main", ItemStack("beer_test:mixed_mead_grain"))
end
end,
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("infotext", "Barrel")
end,
node_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, 0.5, 0.5, 0.5, 0.35}, -- side f
{-0.5, -0.5, -0.5, 0.5, -0.35, 0.5}, -- bottom
{-0.5, -0.5, -0.5, -0.35, 0.5, 0.5}, -- side l
{0.35, -0.5, -0.5, 0.5, 0.5, 0.5}, -- side r
{-0.5, -0.5, -0.35, 0.5, 0.5, -0.5}, -- frount
},
},
selection_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},
},
},
})
-- tankard --
minetest.register_node("beer_test:tankard", {
description = "Tankard",
stack_max = 25,
wield_image = "beer_test_tankard.png",
inventory_image = "beer_test_tankard.png",
tiles = {"beer_test_tankard_top.png","beer_test_tankard_top.png","beer_test_tankard_side.png",
"beer_test_tankard_side.png","beer_test_tankard_side.png","beer_test_tankard_side.png"},
drawtype = "nodebox",
paramtype = "light",
paramtype2 = "facedir",
groups = {cracky=3,dig_immediate=3},
sounds = default.node_sound_tankard_defaults(),
node_box = {
type = "fixed",
fixed = {
{-0.18, -0.5, 0.125, 0.18, 0.18, 0.18},
{0.125, -0.5, -0.18, 0.18, 0.18, 0.18},
{-0.18, -0.5, -0.18, -0.125, 0.18, 0.18},
{-0.18, -0.5, -0.18, 0.18, 0.18, -0.125},
{-0.25, -0.5, -0.25, 0.25, -0.44, 0.25},
{-0.315, -0.3, 0.04, -0.36 , 0.1, -0.05},
{-0.15, -0.0, 0.04, -0.35 , 0.05, -0.05},
{-0.15, -0.25, 0.04, -0.35 , -0.2, -0.05},
-- side , top , side , side , bottom, side,
},
},
selection_box = {
type = "fixed",
fixed = {
--{-0.25, -0.5, -0.25, 0.25, 0.25, 0.25},
{-0.125, -0.5, -0.125, 0.125, 0.18, 0.125},
{-0.18, -0.5, -0.18, 0.18, 0.18, 0.18},
{-0.25, -0.5, -0.25, 0.25, -0.44, 0.25}, -- INNER ONE --
--{-0.25, -0.5, -0.25, 0.25, -0.125, 0.25},
{-0.315, -0.3, 0.04, -0.36 , 0.1, -0.05},
{-0.15, -0.0, 0.04, -0.315 , 0.05, -0.05},
{-0.15, -0.25, 0.04, -0.315 , -0.2, -0.05},
},
},
})
-- Rum Stuff --
minetest.register_node("beer_test:barrel_rum", {
description = "Rum Barrel",
tiles = {"beer_test_barrel_side_2.png", "beer_test_barrel_side_2.png", "beer_test_barrel_side.png",
"beer_test_barrel_side.png", "beer_test_barrel_top.png", "beer_test_barrel_top.png"},
paramtype = "light",
paramtype2 = "facedir",
drop = "beer_test:barrel",
sounds = default.node_sound_barrel_defaults(),
groups = {cracky=2},
--sounds = default.node_sound_wood_defaults(),
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("infotext", "Rum (Brewed)")
end,
on_punch = function(pos, node, puncher)
local tool = puncher:get_wielded_item():get_name()
if tool and tool == "beer_test:tankard" then
node.name = "beer_test:barrel_rum"
minetest.env:set_node(pos, node)
puncher:get_inventory():remove_item("main", ItemStack("beer_test:tankard"))
puncher:get_inventory():add_item("main", ItemStack("beer_test:tankard_rum"))
end
end
})
-- tankards rum --
minetest.register_node("beer_test:tankard_rum", {
description = "Tankard with Rum",
stack_max = 1,
wield_image = "beer_test_tankard_beer.png",
inventory_image = "beer_test_tankard_beer.png",
tiles = {"beer_test_tankard_top_rum.png","beer_test_tankard_top.png","beer_test_tankard_side.png",
"beer_test_tankard_side.png","beer_test_tankard_side.png","beer_test_tankard_side.png"},
drawtype = "nodebox",
paramtype = "light",
paramtype2 = "facedir",
groups = {cracky=3,dig_immediate=3},
on_use = minetest.item_eat(1, "beer_test:tankard"),
sounds = default.node_sound_tankard_defaults(),
node_box = {
type = "fixed",
fixed = {
{-0.18, -0.5, 0.125, 0.18, 0.18, 0.18},
{0.125, -0.5, -0.18, 0.18, 0.18, 0.18},
{-0.18, -0.5, -0.18, -0.125, 0.18, 0.18},
{-0.18, -0.5, -0.18, 0.18, 0.18, -0.125},
{-0.25, -0.5, -0.25, 0.25, -0.44, 0.25},
{-0.315, -0.3, 0.04, -0.36 , 0.1, -0.05},
{-0.15, -0.0, 0.04, -0.35 , 0.05, -0.05},
{-0.15, -0.25, 0.04, -0.35 , -0.2, -0.05},
{-0.18, -0.5, -0.18, 0.18, 0.1, 0.18},
-- side , top , side , side , bottom, side,
},
},
selection_box = {
type = "fixed",
fixed = {
--{-0.25, -0.5, -0.25, 0.25, 0.25, 0.25},
{-0.125, -0.5, -0.125, 0.125, 0.18, 0.125},
{-0.18, -0.5, -0.18, 0.18, 0.18, 0.18},
{-0.25, -0.5, -0.25, 0.25, -0.44, 0.25}, -- INNER ONE --
--{-0.25, -0.5, -0.25, 0.25, -0.125, 0.25},
{-0.315, -0.3, 0.04, -0.36 , 0.1, -0.05},
{-0.15, -0.0, 0.04, -0.315 , 0.05, -0.05},
{-0.15, -0.25, 0.04, -0.315 , -0.2, -0.05},
},
},
})
-- moonsine --
minetest.register_node("beer_test:barrel_moonsine", {
description = "Moonsine Barrel",
tiles = {"beer_test_barrel_side_2.png", "beer_test_barrel_side_2.png", "beer_test_barrel_side.png",
"beer_test_barrel_side.png", "beer_test_barrel_top.png", "beer_test_barrel_top.png"},
paramtype = "light",
paramtype2 = "facedir",
drop = "beer_test:barrel",
sounds = default.node_sound_barrel_defaults(),
groups = {cracky=2},
--sounds = default.node_sound_wood_defaults(),
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("infotext", "Moonsine (Brewed)")
end,
on_punch = function(pos, node, puncher)
local tool = puncher:get_wielded_item():get_name()
if tool and tool == "beer_test:tankard" then
node.name = "beer_test:barrel_moonsine"
minetest.env:set_node(pos, node)
puncher:get_inventory():remove_item("main", ItemStack("beer_test:tankard"))
puncher:get_inventory():add_item("main", ItemStack("beer_test:tankard_moonsine"))
end
end
})
-- tankards rum --
minetest.register_node("beer_test:tankard_moonsine", {
description = "Tankard with Moonsine",
stack_max = 1,
wield_image = "beer_test_tankard_beer.png",
inventory_image = "beer_test_tankard_beer.png",
tiles = {"beer_test_tankard_top_moonsine.png","beer_test_tankard_top.png","beer_test_tankard_side.png",
"beer_test_tankard_side.png","beer_test_tankard_side.png","beer_test_tankard_side.png"},
drawtype = "nodebox",
paramtype = "light",
paramtype2 = "facedir",
groups = {cracky=3,dig_immediate=3},
on_use = minetest.item_eat(1, "beer_test:tankard"),
sounds = default.node_sound_tankard_defaults(),
node_box = {
type = "fixed",
fixed = {
{-0.18, -0.5, 0.125, 0.18, 0.18, 0.18},
{0.125, -0.5, -0.18, 0.18, 0.18, 0.18},
{-0.18, -0.5, -0.18, -0.125, 0.18, 0.18},
{-0.18, -0.5, -0.18, 0.18, 0.18, -0.125},
{-0.25, -0.5, -0.25, 0.25, -0.44, 0.25},
{-0.315, -0.3, 0.04, -0.36 , 0.1, -0.05},
{-0.15, -0.0, 0.04, -0.35 , 0.05, -0.05},
{-0.15, -0.25, 0.04, -0.35 , -0.2, -0.05},
{-0.18, -0.5, -0.18, 0.18, 0.1, 0.18},
-- side , top , side , side , bottom, side,
},
},
selection_box = {
type = "fixed",
fixed = {
--{-0.25, -0.5, -0.25, 0.25, 0.25, 0.25},
{-0.125, -0.5, -0.125, 0.125, 0.18, 0.125},
{-0.18, -0.5, -0.18, 0.18, 0.18, 0.18},
{-0.25, -0.5, -0.25, 0.25, -0.44, 0.25}, -- INNER ONE --
--{-0.25, -0.5, -0.25, 0.25, -0.125, 0.25},
{-0.315, -0.3, 0.04, -0.36 , 0.1, -0.05},
{-0.15, -0.0, 0.04, -0.315 , 0.05, -0.05},
{-0.15, -0.25, 0.04, -0.315 , -0.2, -0.05},
},
},
})
-- mulled wine --
minetest.register_node("beer_test:barrel_mulledWine", {
description = "Mulled Wine Barrel",
tiles = {"beer_test_barrel_side_2.png", "beer_test_barrel_side_2.png", "beer_test_barrel_side.png",
"beer_test_barrel_side.png", "beer_test_barrel_top.png", "beer_test_barrel_top.png"},
paramtype = "light",
paramtype2 = "facedir",
drop = "beer_test:barrel",
sounds = default.node_sound_barrel_defaults(),
groups = {cracky=2},
--sounds = default.node_sound_wood_defaults(),
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("infotext", "Mulled Wine (Brewed)")
end,
on_punch = function(pos, node, puncher)
local tool = puncher:get_wielded_item():get_name()
if tool and tool == "beer_test:tankard" then
node.name = "beer_test:barrel_mulledWine"
minetest.env:set_node(pos, node)
puncher:get_inventory():remove_item("main", ItemStack("beer_test:tankard"))
puncher:get_inventory():add_item("main", ItemStack("beer_test:tankard_mulledWine"))
end
end
})
-- tankards rum --
minetest.register_node("beer_test:tankard_mulledWine", {
description = "Tankard with Mulled Wine",
stack_max = 1,
wield_image = "beer_test_tankard_beer.png",
inventory_image = "beer_test_tankard_beer.png",
tiles = {"beer_test_tankard_top_mulledWine.png","beer_test_tankard_top.png","beer_test_tankard_side.png",
"beer_test_tankard_side.png","beer_test_tankard_side.png","beer_test_tankard_side.png"},
drawtype = "nodebox",
paramtype = "light",
paramtype2 = "facedir",
groups = {cracky=3,dig_immediate=3},
on_use = minetest.item_eat(1, "beer_test:tankard"),
sounds = default.node_sound_tankard_defaults(),
node_box = {
type = "fixed",
fixed = {
{-0.18, -0.5, 0.125, 0.18, 0.18, 0.18},
{0.125, -0.5, -0.18, 0.18, 0.18, 0.18},
{-0.18, -0.5, -0.18, -0.125, 0.18, 0.18},
{-0.18, -0.5, -0.18, 0.18, 0.18, -0.125},
{-0.25, -0.5, -0.25, 0.25, -0.44, 0.25},
{-0.315, -0.3, 0.04, -0.36 , 0.1, -0.05},
{-0.15, -0.0, 0.04, -0.35 , 0.05, -0.05},
{-0.15, -0.25, 0.04, -0.35 , -0.2, -0.05},
{-0.18, -0.5, -0.18, 0.18, 0.1, 0.18},
-- side , top , side , side , bottom, side,
},
},
selection_box = {
type = "fixed",
fixed = {
--{-0.25, -0.5, -0.25, 0.25, 0.25, 0.25},
{-0.125, -0.5, -0.125, 0.125, 0.18, 0.125},
{-0.18, -0.5, -0.18, 0.18, 0.18, 0.18},
{-0.25, -0.5, -0.25, 0.25, -0.44, 0.25}, -- INNER ONE --
--{-0.25, -0.5, -0.25, 0.25, -0.125, 0.25},
{-0.315, -0.3, 0.04, -0.36 , 0.1, -0.05},
{-0.15, -0.0, 0.04, -0.315 , 0.05, -0.05},
{-0.15, -0.25, 0.04, -0.315 , -0.2, -0.05},
},
},
})
print("Beer_test: brewing_other.lua [ok]")
|
local cmd = vim.cmd
-- local hiLinks = require "settings.utils".hiLinks
-- local apply_globals = require "settings.utils".apply_globals
-- local highlights = require "settings.utils".highlights
cmd "syntax sync fromstart"
cmd "syntax enable"
cmd "set termguicolors"
-- inactive statuslines as thin splitlines
cmd "hi! StatusLineNC gui=underline guibg=NONE guifg='#101010'"
-- gruvbox
cmd "colorscheme gruvbox-material"
-- cmd "colorscheme gruvbox-flat"
-- apply_globals(
-- {
-- gruvbox_material_palette = "material",
-- gruvbox_material_background = "hard",
-- gruvbox_material_enable_italic = 1,
-- gruvbox_material_disable_italic_comment = 1,
-- gruvbox_material_enable_bold = 1,
-- gruvbox_material_diagnostic_line_highlight = 1,
-- gruvbox_material_current_word = "bold",
-- gruvbox_material_sign_column_background = "bg0"
-- -- gruvbox_material_better_performance = 1
-- }
-- )
-- g:gruvbox_material_palette = {
-- \ 'bg0': ['#101010', '234'],
-- \ 'bg1': ['#262727', '235'],
-- \ 'bg2': ['#282828', '235'],
-- \ 'bg3': ['#3c3836', '237'],
-- \ 'bg4': ['#3c3836', '237'],
-- \ 'bg5': ['#504945', '239'],
|
workspace "windows-lockscreen-extractor"
architecture "x64"
startproject "windows-lockscreen-extractor"
configurations
{
"Debug",
"Release",
"Dist"
}
flags
{
"MultiProcessorCompile"
}
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
IncludeDir = {}
IncludeDir["Glad"] = "%{wks.location}/windows-lockscreen-extractor/vendor/Glad/include"
IncludeDir["GLFW"] = "%{wks.location}/windows-lockscreen-extractor/vendor/GLFW/include"
IncludeDir["ImGui"] = "%{wks.location}/windows-lockscreen-extractor/vendor/ImGui"
IncludeDir["stb_image"] = "%{wks.location}/windows-lockscreen-extractor/vendor/stb_image"
group "Dependencies"
include "vendor/premake"
include "windows-lockscreen-extractor/vendor/Glad"
include "windows-lockscreen-extractor/vendor/GLFW"
include "windows-lockscreen-extractor/vendor/ImGui"
group ""
include "windows-lockscreen-extractor"
|
-- @module layout How Ido looks
local layout = {}
-- The default layout of Ido
-- @field results_start string The decoration before the results
-- @field results_selected string The decoration before the selected result
-- @field results_separator string The decoration separating the results
-- @field results_end string The decoration after the results
-- @field suggest_start string The decoration before the suggestion
-- @field suggest_end string The decoration after the suggestion
layout.default = {
results_start = "{",
results_selected = "",
results_separator = " | ",
results_end = "}",
suggest_start = "[",
suggest_end = "]",
}
-- Create new layout
-- Accepts a layout specification in the form of a table
-- The contents of the table has to be in the same format as shown
-- in the default layout
-- @param options table The specification for the layout
-- @return nil in case of errors, else true
function layout.new(options)
-- Some error handling
if options.name == nil then
print("Name of the layout is not defined")
return nil
end
if options.name == "new" then
print("Invalid layout name: "..options.name)
return nil
end
-- Register the layout
layout[options.name] = vim.tbl_extend("keep", options, layout.default)
layout[options.name].name = nil
return true
end
return layout
|
-- ONES ALREADY DONE, JUST NEED PASTING IN HERE
-- measure-numbers_freund.lua
-- FIX ALL THINGS CATEGORY DEFS (defaults only)
-- fix tempo alterations
local categorydefs = finale.FCCategoryDefs()
categorydefs:LoadAll()
name = finale.FCString()
tempoAlterationsFontInfo = finale.FCFontInfo()
tempoAlterationsFontInfo.Italic = true
tempoAlterationsFontInfo.Bold = true
tempoAlterationsFontInfo.Name = "Times New Roman"
tempoAlterationsFontInfo.Absolute = true
tempoAlterationsFontInfo.Size = 12
tempoAlterationsFontInfo.Underline = false
tempoAlterationsFontInfo.Hidden = false
tempoAlterationsFontInfo.StrikeOut = false
for eachDef in each(categorydefs) do
eachDef:GetName(name)
if (name.LuaString == "Tempo Alterations") then
eachDef:SetTextFontInfo(tempoAlterationsFontInfo)
categorydefs:SaveAll()
end
end
|
local tickno
local refl_x
local refl_y
local refl_w
local refl_h
local refl_radius
local refl_radius_sq
local refl_speed_x
local refl_speed_y
local refl_grav
local refl_tap_boost
local dist_travelled
local hit_parts
local hit_parts_delay
local menuchange_delay
local app_over
local border_standoff
local points_xdist
local points_mindist_y
local ground_tbl_top
local ground_tbl_bot
local ground_tbl_x
local app_menu_id
local last_time
function init_reflector_screen(menu_id)
--------------
local canvas = gre.get_canvas("reflector_canvas")
local size = canvas:get_dimensions()
canvas:fill_rect(0, 0, size.width, size.height, 0xF6F6F6)
--------------
tickno = 0
refl_x = 20
refl_y = 300
refl_w = 40
refl_h = 40
refl_radius = 15
refl_radius_sq = refl_radius*refl_radius
refl_speed_x = 4
refl_speed_y = 0
refl_grav = 0.2
refl_tap_boost = 4
dist_travelled = 0
hit_parts = {}
hit_parts_delay = 20
menuchange_delay = hit_parts_delay + 50
app_over = -1
border_standoff = 10
points_xdist = 40
points_mindist_y = 100
ground_tbl_top = {}
ground_tbl_bot = {}
ground_tbl_x = 0
if menu_id == nil then app_menu_id = 0 else app_menu_id = menu_id end
last_time = gre.mstime()
end
function draw_debug_rect_at(x, y)
local canvas = gre.get_canvas("reflector_canvas")
local pts = {{x=x-2,y=y-2},{x=x-2,y=y+2},{x=x+2,y=y+2},{x=x+2,y=y-2}}
canvas:fill_poly(pts, 0x00ff00)
end
function draw_rect_at(x, y, w, h, color, alpha)
local canvas = gre.get_canvas("reflector_canvas")
local pts = {{x=x,y=y},{x=x+w,y=y},{x=x+w,y=y+h},{x=x,y=y+h}}
canvas:set_alpha(alpha)
canvas:fill_poly(pts, color)
canvas:set_alpha(255)
end
--Copy pasted from:
--https://stackoverflow.com/questions/2752725/finding-whether-a-point-lies-inside-a-rectangle-or-not
function hittest_point_rect(x, y, ax, ay, bx, by, dx, dy)
local bax = bx - ax
local bay = by - ay
local dax = dx - ax
local day = dy - ay
if ((x - ax) * bax + (y - ay) * bay < 0.0) then return false end
if ((x - bx) * bax + (y - by) * bay > 0.0) then return false end
if ((x - ax) * dax + (y - ay) * day < 0.0) then return false end
if ((x - dx) * dax + (y - dy) * day > 0.0) then return false end
return true
end
--Hit test of circle vs line segment (just rectangular, not obround)
function hittest_circle_line_seg(x, y, radius, ax, ay, bx, by)
--The perpendicular (normal) vector can be found by
--swapping the x and y values and negating one of the two
local perpvec_x = by-ay
local perpvec_y = -(bx-ax)
local perplen = math.sqrt(perpvec_x*perpvec_x + perpvec_y*perpvec_y)
local proport = radius / perplen
local scaled_x = perpvec_x*proport
local scaled_y = perpvec_y*proport
--{bx-scaled_x, by-scaled_y} would be bottom right point, for y pointing downwards
return hittest_point_rect(x, y, ax+scaled_x, ay+scaled_y, ax-scaled_x, ay-scaled_y, bx+scaled_x, by+scaled_y)
end
function hittest_circle_point(x, y, radius_sq, ax, ay)
local dist_x = (ax-x)
local dist_y = (ay-y)
if dist_x*dist_x + dist_y*dist_y <= radius_sq then
return true
end
return false
end
function draw_str_at(str, x, y, color, size)
local canvas = gre.get_canvas("reflector_canvas")
local attrs = {}
attrs.font = "fonts/OpenSans-Regular.ttf"
attrs.size = size
attrs.x = x
attrs.y = y
attrs.color = color
canvas:draw_text(str, attrs)
end
function reflector_update()
local canvas = gre.get_canvas("reflector_canvas")
local size = canvas:get_dimensions()
tickno = tickno + 1
if app_menu_id == 0 then
canvas:fill_rect(0, 0, size.width, size.height, 0xF6F6F6)
str_x = 60
str_y = 70
str_kern = 60
str_phase = 0.7
draw_str_at("\70", str_x, str_y + math.sin(tickno/5)*30, 0x94012C, 90)
draw_str_at("\76", str_x+str_kern, str_y + math.sin(tickno/5 + str_phase)*30, 0x2D288B, 90)
draw_str_at("\65", str_x+str_kern*2, str_y + math.sin(tickno/5 + str_phase*2)*30, 0x639D01, 90)
draw_str_at("\80", str_x+str_kern*3, str_y + math.sin(tickno/5 + str_phase*3)*30, 0xC8A601, 90)
draw_str_at("\80", str_x+str_kern*4, str_y + math.sin(tickno/5 + str_phase*4)*30, 0xC8A601, 90)
draw_str_at("\89", str_x+str_kern*5, str_y + math.sin(tickno/5 + str_phase*5)*30, 0x00766A, 90)
draw_str_at("Reflector", str_x - 15, str_y+120, 0x94012C, 90)
draw_str_at("(tap screen to \112\108\97\121)", 42, 450, 0x000000, 44)
elseif app_menu_id == 1 then
for k, v in pairs(hit_parts) do
v.vy = v.vy + refl_grav
v.x = v.x + v.vx
v.y = v.y + v.vy
end
if app_over == -1 then
refl_y = refl_y + refl_speed_y
if refl_y < 0 then
refl_speed_y = 0
refl_y = 0
elseif refl_y > size.height - refl_h then
refl_speed_y = -refl_speed_y * 0.7
refl_y = size.height - refl_h
end
refl_speed_y = refl_speed_y + refl_grav
--if refl_speed_y > 7 then refl_speed_y = 7 end
dist_travelled = dist_travelled + refl_speed_x
ground_tbl_x = ground_tbl_x - refl_speed_x
while ground_tbl_x < -points_xdist do
ground_tbl_x = ground_tbl_x + points_xdist
table.remove(ground_tbl_bot, 1)
table.remove(ground_tbl_top, 1)
end
--In the following line, + 2 for additional left/right vertex
for i=1, size.width / points_xdist - #ground_tbl_bot + 2 do
local mntn_size = 300
if dist_travelled < 30 then mntn_size = 150 end
local new_top = border_standoff + mntn_size*math.random()
local new_bot = size.height - border_standoff - mntn_size*math.random()
if new_bot - new_top < points_mindist_y then
local correction = points_mindist_y - (new_bot - new_top)
new_top = new_top - math.ceil(correction/2)
new_bot = new_bot + math.ceil(correction/2)
if new_top < border_standoff then new_top = border_standoff end
if new_bot > size.height - border_standoff then new_bot = size.height - border_standoff end
end
table.insert(ground_tbl_top, new_top)
table.insert(ground_tbl_bot, new_bot)
end
--In the following lines, + 1 because Lua starts at 1
local idx_before = math.floor((refl_x - ground_tbl_x) / points_xdist) + 1
local idx_after = math.ceil((refl_x + refl_w - ground_tbl_x) / points_xdist) + 1
--print("Before: " .. idx_before .. " / After: " .. idx_after)
local has_hit = false
for i = math.max(1, idx_before), math.min(idx_after, (#ground_tbl_bot) - 1) do
--This is duplicated code for 2 variables, should put in a function:
if true then
--draw_debug_rect_at((i-1)*points_xdist+ground_tbl_x, ground_tbl_bot[i])
local x = (i-1)*points_xdist+ground_tbl_x
local y = ground_tbl_bot[i]
local x_next = (i)*points_xdist+ground_tbl_x
local y_next = ground_tbl_bot[i+1]
if hittest_circle_line_seg(refl_x + refl_w/2, refl_y + refl_h/2, refl_radius, x, y, x_next, y_next) then
has_hit = true
end
if hittest_circle_point(refl_x + refl_w/2, refl_y + refl_h/2, refl_radius_sq, x, y) then
has_hit = true
end
end
if true then
--draw_debug_rect_at((i-1)*points_xdist+ground_tbl_x, ground_tbl_bot[i])
local x = (i-1)*points_xdist+ground_tbl_x
local y = ground_tbl_top[i]
local x_next = (i)*points_xdist+ground_tbl_x
local y_next = ground_tbl_top[i+1]
if hittest_circle_line_seg(refl_x + refl_w/2, refl_y + refl_h/2, refl_radius, x, y, x_next, y_next) then
has_hit = true
end
if hittest_circle_point(refl_x + refl_w/2, refl_y + refl_h/2, refl_radius_sq, x, y) then
has_hit = true
end
end
end
if has_hit then
--draw_debug_rect_at(10, 10)
--init_reflector_screen(1)
app_over = tickno
end
end
if app_over ~= -1 then
if tickno - app_over == hit_parts_delay then
for i = 1,20 do
local rand_vx = math.random()*5
if math.random() < 0.5 then rand_vx = -rand_vx end
local rand_vy = math.random()*5
if math.random() < 0.5 then rand_vy = -rand_vy end
table.insert(hit_parts, {x=refl_x+refl_w*math.random(),y=refl_y+refl_h*math.random(),vx=rand_vx,vy=rand_vy})
end
end
if tickno - app_over == menuchange_delay then
app_menu_id = 2
end
end
--------------------------------------------------------------
--Draw screen:
canvas:fill_rect(0, 0, size.width, size.height, 0xF6F6F6)
local pts_top = {{x=0,y=0},{x=0,y=border_standoff}}
local pts_bot = {{x=0,y=size.height},{x=0,y=size.height-border_standoff}}
local ctr = 0
for k,v in pairs(ground_tbl_bot) do
table.insert(pts_bot, {x=ctr*points_xdist+ground_tbl_x,y=v})
--canvas:fill_poly({10,20,15,10}, {10,20,15,10}, 0xFF0000)
--canvas:fill_poly({{x=10,y=10},{x=10,y=20},{x=20,y=20},{x=10,y=10}}, 0xFF0000)
--canvas:fill_poly({10,10,20,10}, {10,20,20,10}, 0xFF0000)
--print(k .. "/" .. v)
ctr = ctr + 1
end
ctr = 0
for k,v in pairs(ground_tbl_top) do
table.insert(pts_top, {x=ctr*points_xdist+ground_tbl_x,y=v})
ctr = ctr + 1
end
table.insert(pts_top, {x=size.width,y=border_standoff})
table.insert(pts_top, {x=size.width,y=0})
table.insert(pts_bot, {x=size.width,y=size.height-border_standoff})
table.insert(pts_bot, {x=size.width,y=size.height})
canvas:fill_poly(pts_top, 0x0097BA)
canvas:fill_poly(pts_bot, 0x0097BA)
if(app_over == -1 or tickno - app_over < hit_parts_delay) then
local attrs = {}
attrs.x = refl_x
attrs.y = refl_y
attrs.w = refl_w
attrs.h = refl_h
canvas:draw_image("images/Targets/RFI_0.5@4x.png", attrs)
end
for k, v in pairs(hit_parts) do
--print(k, v.x, v.y, v.vx, v.vy)
draw_rect_at(v.x-3, v.y-3, 6, 6, 0x000000, 255)
end
local dist_str = tostring(dist_travelled)
local attrs = {}
attrs.font = "fonts/OpenSans-Regular.ttf"
attrs.size = 24
local strSize = gre.get_string_size(attrs.font, attrs.size, dist_str, 0)
attrs.x = size.width - strSize.width - 10
attrs.y = 10
canvas:draw_text(dist_str, attrs)
elseif app_menu_id == 2 then
draw_str_at("You \98\114\111\107\101 a reflector!", 35, 50, 0x000000, 40)
draw_rect_at(100, 250, 280, 150, 0xCCCCCC, 100)
draw_str_at("Main menu", 100 + 45, 300, 0x000000, 36)
draw_rect_at(100, 450, 280, 150, 0xCCCCCC, 100)
draw_str_at("Re\112\108\97\121", 100 + 85, 500, 0x000000, 36)
end
local new_time = gre.mstime()
--print(new_time - last_time)
last_time = new_time
end
function hndl_reflector_press(mapargs)
local evt = mapargs["context_event_data"]
local press_x = evt["x"]
local press_y = evt["y"]
if app_over == -1 then
refl_y = refl_y - 1
refl_speed_y = refl_speed_y - refl_tap_boost
end
if app_menu_id == 0 then
app_menu_id = 1
elseif app_menu_id == 2 then
if press_x >= 100 and press_x <= 100+280 and
press_y >= 250 and press_y <= 250+150 then
change_screen_internal("home_screen")
elseif press_x >= 100 and press_x <= 100+280 and
press_y >= 450 and press_y <= 450+150 then
init_reflector_screen(1)
end
end
end
local reflector_timer = nil
function hndl_show_reflector_screen()
init_reflector_screen()
reflector_timer = gre.timer_set_interval(
reflector_update,
16
)
end
function hndl_hide_reflector_screen()
if reflector_timer ~= nil then
gre.timer_clear_interval(reflector_timer)
reflector_timer = nil
end
end
|
local PlayerData = class("PlayerData")
function PlayerData:ctor(playerid, player_obj)
self._playerid = playerid
self._data = {}
if player_obj ~= nil then
fill_data_by_path(PLAYER_DATA["BASE_INFO"], self._data, player_obj)
end
end
function PlayerData:get_playerid()
return self._playerid
end
function PlayerData:get_player_obj()
return get_data_by_path(PLAYER_DATA["BASE_INFO"], self._data)
end
function PlayerData:set_player_obj(player_obj)
if self:get_player_obj() == nil then
fill_data_by_path(PLAYER_DATA["BASE_INFO"], self._data, player_obj)
end
end
function PlayerData:get_data()
return self._data
end
return PlayerData
|
--- === plugins.finalcutpro.advanced.backupinterval ===
---
--- Change Final Cut Pro's Backup Interval.
local require = require
local fcp = require "cp.apple.finalcutpro"
local i18n = require "cp.i18n"
local plugin = {
id = "finalcutpro.advanced.backupinterval",
group = "finalcutpro",
dependencies = {
["finalcutpro.preferences.manager"] = "prefs",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Only load plugin if FCPX is supported:
--------------------------------------------------------------------------------
if not fcp:isSupported() then return end
--------------------------------------------------------------------------------
-- Setup Preferences Panel:
--------------------------------------------------------------------------------
local panel = deps.prefs.panel
if panel then
panel
:addContent(2207.1, [[
<style>
.backupInterval select {
margin-left: 90px;
}
.backupMinimumDuration select {
margin-left: 25px;
}
</style>
]], false)
:addParagraph(2207.2, "<br />", false)
:addSelect(2208,
{
class = "backupInterval",
required = true,
width = 100,
label = i18n("backupInterval"),
value = function() return fcp.preferences.FFPeriodicBackupInterval or "15" end,
options = function()
local options = {}
for i=1, 15 do
table.insert(options, {
value = tostring(i),
label = tostring(i) .. " " .. i18n("mins")
})
end
return options
end,
onchange = function(_, params)
fcp.preferences:set("FFPeriodicBackupInterval", params.value)
end,
}
)
panel
:addSelect(2209,
{
class = "backupMinimumDuration",
required = true,
width = 100,
label = i18n("backupMinimumDuration"),
value = function() return fcp.preferences.FFPeriodicBackupMinimumDuration or "5" end,
options = function()
local options = {}
for i=1, 15 do
table.insert(options, {
value = tostring(i),
label = tostring(i) .. " " .. i18n("mins")
})
end
return options
end,
onchange = function(_, params)
fcp.preferences:set("FFPeriodicBackupMinimumDuration", params.value)
end,
}
)
end
end
return plugin
|
local match = require("luassert.match")
local BehaviourTree = require 'lib/behaviour_tree'
describe('Priority selector', function()
local subject
before_each(function()
subject = BehaviourTree.Priority:new({})
end)
describe(':initialize', function()
it('should copy any attributes to the node', function()
local node = BehaviourTree:new({testfield = 'foobar'})
assert.is_equal(node.testfield, 'foobar')
end)
it('should register the node if the name is set', function()
local node = BehaviourTree:new({name = 'foobar'})
assert.is_equal(BehaviourTree.getNode('foobar'), node)
end)
end)
describe(':start', function()
it('should set the object', function()
assert.is_nil(subject.object)
subject:start('foobar')
assert.is_equal(subject.object, 'foobar')
end)
it('should set actualTask', function()
assert.is_nil(subject.actualTask)
subject:start()
assert.is_equal(subject.actualTask, 1)
end)
end)
describe(':finish', function()
it('has a finish method', function()
assert.is_function(subject.finish)
end)
end)
describe(':run', function()
it('should call _run if it still has tasks', function()
subject.nodes = {BehaviourTree.Task:new()}
subject:start()
stub(subject, '_run')
subject:run()
assert.stub(subject._run).was.called()
end)
it('should not call run if it has no tasks', function()
subject.nodes = {}
subject:start()
stub(subject, '_run')
subject:run()
assert.stub(subject._run).was_not.called()
end)
end)
describe(':_run', function()
local node
before_each(function()
node = BehaviourTree.Task:new()
subject.nodes = {node}
subject:start()
end)
it('should set the current node', function()
subject:_run()
assert.is_equal(subject.node, node)
end)
it('should get the current node from the registry', function()
BehaviourTree.register('mynode', node)
subject.nodes = {'mynode'}
subject:_run()
assert.is_equal(subject.node, node)
end)
it('should set the current nodes control', function()
stub(node, 'setControl')
subject:_run()
assert.stub(node.setControl).was.called_with(match.is_ref(node), subject)
end)
it('should call start on the current node if first run', function()
stub(node, 'start')
subject:_run('foo')
assert.stub(node.start).was.called_with(match.is_ref(node), 'foo')
end)
it('should not call start on the current node if running', function()
subject.node = node
subject.nodeRunning = true
stub(node, 'start')
subject:_run()
assert.stub(node.start).was_not.called()
end)
it('should call run on the current node', function()
stub(node, 'run')
subject:_run('foo')
assert.stub(node.run).was.called_with(match.is_ref(node), 'foo')
end)
end)
describe(':setObject', function()
it('should set the object on the node', function()
subject:setObject('foobar')
assert.is_equal(subject.object, 'foobar')
end)
end)
describe(':setControl', function()
it('should set the controller on the node', function()
subject:setControl('foobar')
assert.is_equal(subject.control, 'foobar')
end)
end)
describe(':running', function()
local node
before_each(function()
node = BehaviourTree.Task:new()
subject.control = {running = function()end}
subject.node = node
end)
it('should set nodeRunning', function()
subject:running()
assert.is_true(subject.nodeRunning)
end)
it('should call running on control', function()
stub(subject.control, 'running')
subject:running()
assert.stub(subject.control.running).was.called()
end)
end)
describe(':success', function()
local node
before_each(function()
node = BehaviourTree.Task:new()
subject.control = {success = function()end}
subject.nodeRunning = true
subject.node = node
end)
it('should set nodeRunning as nil', function()
subject:success()
assert.is_false(subject.nodeRunning)
end)
it('should call finish on current node', function()
stub(node, 'finish')
subject:success()
assert.stub(node.finish).was.called()
end)
it('should set current node as nil', function()
subject:success()
assert.is_nil(subject.node)
end)
it('should call success on control', function()
stub(subject.control, 'success')
subject:success()
assert.stub(subject.control.success).was.called()
end)
end)
describe(':fail', function()
local node
before_each(function()
node = BehaviourTree.Task:new()
subject.control = {fail = function()end}
subject.actualTask = 1
subject.nodeRunning = true
subject.nodes = {node}
subject.node = node
end)
it('should set nodeRunning as nil', function()
subject:fail()
assert.is_false(subject.nodeRunning)
end)
it('should call finish on current node', function()
stub(node, 'finish')
subject:fail()
assert.stub(node.finish).was.called()
end)
it('should set current node as nil', function()
subject:fail()
assert.is_nil(subject.node)
end)
it('should call _run if there are more tasks', function()
subject.nodes = {'a', 'b'}
stub(subject, '_run')
subject:fail()
assert.stub(subject._run).was.called()
end)
end)
end)
|
local ipairs = ipairs
local tab_insert = table.insert
local tab_new = require('resty.core.base').new_tab
local balancer = require('apicast.balancer')
local mapping_rules_matcher = require('apicast.mapping_rules_matcher')
local UpstreamSelector = require('upstream_selector')
local Request = require('request')
local Rule = require('rule')
local _M = require('apicast.policy').new('Routing policy', 'builtin')
local new = _M.new
local function init_rules(config)
if not config or not config.rules then return tab_new(0, 0) end
local res = tab_new(#config.rules, 0)
for _, config_rule in ipairs(config.rules) do
local rule, err = Rule.new_from_config_rule(config_rule)
if rule then
tab_insert(res, rule)
else
ngx.log(ngx.WARN, err)
end
end
return res
end
function _M.new(config)
local self = new(config)
self.upstream_selector = UpstreamSelector.new()
self.rules = init_rules(config)
return self
end
function _M:access(context)
-- All route definition needs to happen in the access phase to make sure that
-- the mapping rule with the owner_id happens before the APIcast policy and
-- metrics in APIcast rule can be updated correctly.
--
-- This can also make sense to have in the rewrite phase, but on that phase
-- headers are not available to read so some matcher will not work correctly.
--
-- This should be moved to the place where the context is started, so other
-- policies can use it.
context.request = context.request or Request.new()
-- Once request is in the context, we should move this to wherever the jwt is
-- validated.
context.request:set_validated_jwt(context.jwt or {})
context.route_upstream = self.upstream_selector:select(self.rules, context)
-- this function substract the usage that does not match with the owner_id by
-- the matched_rules
context.route_upstream_usage_cleanup = function(self, usage, matched_rules)
if not self.route_upstream then
return
end
local usage_diff = mapping_rules_matcher.clean_usage_by_owner_id(
matched_rules , self.route_upstream:has_owner_id())
usage:merge(usage_diff)
end
end
function _M:content(context)
if context.route_upstream then
context.route_upstream:call(context)
else
return nil, 'no upstream'
end
end
_M.balancer = balancer.call
return _M
|
lvim.plugins = {
-- Themes
{ "sainnhe/everforest" },
-- Telescope
{ "nvim-telescope/telescope-fzy-native.nvim" },
{
"benfowler/telescope-luasnip.nvim",
after = "telescope.nvim",
config = function()
require("telescope").load_extension("luasnip")
end,
},
-- LSP
{
"ThePrimeagen/refactoring.nvim",
event = "BufRead",
requires = { "nvim-lua/plenary.nvim", "nvim-treesitter/nvim-treesitter" },
config = function()
require("refactoring").setup({})
end,
},
-- { "github/copilot.vim" },
{
"zbirenbaum/copilot.lua",
event = { "VimEnter" },
config = function()
vim.defer_fn(function()
require("copilot").setup({
plugin_manager_path = get_runtime_dir() .. "/site/pack/packer",
})
end, 100)
end,
},
{ "zbirenbaum/copilot-cmp", after = { "copilot.lua", "nvim-cmp" } },
-- Treesitter
{
"windwp/nvim-ts-autotag",
event = "InsertEnter",
config = function()
require("nvim-ts-autotag").setup()
end,
},
{
"folke/todo-comments.nvim",
event = "BufRead",
config = function()
require("todo-comments").setup()
end,
},
{
"norcalli/nvim-colorizer.lua",
config = function()
require("colorizer").setup()
end,
},
{
"danymat/neogen",
config = function()
require("neogen").setup({})
end,
requires = "nvim-treesitter/nvim-treesitter",
tag = "*",
},
{
"tpope/vim-surround",
keys = { "c", "d", "y", "S" },
},
{
"felipec/vim-sanegx",
event = "BufRead",
},
{ "mtdl9/vim-log-highlighting" },
{ "p00f/nvim-ts-rainbow" },
-- Git
{
"ThePrimeagen/git-worktree.nvim",
after = "telescope.nvim",
config = function()
require("telescope").load_extension("git_worktree")
end,
},
-- Navigation
{
"ThePrimeagen/harpoon",
event = "BufWinEnter",
requires = { "nvim-lua/plenary.nvim", "nvim-lua/popup.nvim" },
config = function()
require("olrtg.plugins.harpoon").config()
end,
},
{
"nacro90/numb.nvim",
event = "BufRead",
config = function()
require("olrtg.plugins.numb").config()
end,
},
{
"ethanholz/nvim-lastplace",
event = "BufRead",
config = function()
require("olrtg.plugins.lastplace")
end,
},
-- Docs
{ "milisims/nvim-luaref" },
{ "nanotee/luv-vimdocs" },
-- Misc
{ "tjdevries/cyclist.vim" },
{
"folke/persistence.nvim",
event = "BufReadPre", -- this will only start session saving when an actual file was opened
module = "persistence",
config = function()
require("persistence").setup({
dir = vim.fn.expand(vim.fn.stdpath("config") .. "/session/"),
options = { "buffers", "curdir", "tabpages", "winsize" },
})
end,
},
}
table.insert(lvim.builtin.cmp.sources, { name = "copilot", group_index = 0 })
|
DEFINE_BASECLASS("ma2_proj_ppc_lvl1")
AddCSLuaFile()
ENT.Base = "ma2_proj_ppc_lvl1"
ENT.Damage = 540
ENT.ParticleAttach = "gm_MA2_PPC_lvl3"
ENT.FireSound = Sound("MA2_Weapon.PPC3")
PrecacheParticleSystem("gm_MA2_PPC_lvl3")
|
--[[ periodictimer.lua v1.0.0 by AGD
Description:
Periodic timer
Requirements:
- EventListener
Link: https://www.hiveworkshop.com/threads/323354/
]]--
--[[
API:
PeriodicTimer(number: period = 1.00)
PeriodicTimer:register(function: callback [, ...]) -> self
PeriodicTimer:deregister(function: callback) -> self
]]--
PeriodicTimer = {
TIMEOUT_ACCURACY = 7,
TIMEOUT_OFFSET_TOLERANCE = 0.01
}
do
local timer = {}
setmetatable(PeriodicTimer, timer)
timer.__index = timer
local cache = {}
local function GetTimerSlot(self)
local stack = self.timer_stack
if stack then
for i = 1, #stack do
if TimerGetRemaining(stack[i].timer) <= PeriodicTimer.TIMEOUT_OFFSET_TOLERANCE or
IsTimerPaused(stack[i].timer) then
-- timer is available, return its slot
return stack, i
end
end
-- no available timers in stack, append new timer to stack
stack[#stack + 1] = {
timer = CreateTimer(),
listener = Listener.new(),
listener_size = 0
}
return stack, #stack
end
-- stack is not yet created, create now
stack = {}
stack[1] = {
timer = CreateTimer(),
listener = Listener(),
listener_size = 0
}
self.timer_stack = stack
return stack, 1
end
---@param period number
local timeout_accuracy = math.pow(10, PeriodicTimer.TIMEOUT_ACCURACY)
function timer:__call(period)
period = math.floor(period*timeout_accuracy)
cache[period] = cache[period] or
setmetatable({period = period, timer_stack = {}}, timer)
return cache[period]
end
function timer:register(...)
local stack, i = GetTimerSlot(self)
stack = stack[i]
if stack.listener_size == 0 then
TimerStart(stack.timer, self.period, true, function ()
stack.listener:execute()
end)
end
stack.listener_size = stack.listener_size + 1
stack.listener:register(...)
return self
end
function timer:deregister(...)
for i = 1, #self.timer_stack do
local stack = self.timer_stack[i]
stack.listener:deregister(...)
stack.listener_size = stack.listener_size - 1
if stack.listener_size == 0 then
PauseTimer(timer)
end
end
return self
end
end
|
-- @group UI
-- @brief Draws a number of images in a batch.
-- @full Draws a number of images in a batch. The subtextures of the images
-- must belong to the same texture.
local ImageBatch,super = ae.oo.subclass(ae.ui.Component)
-- @func
-- @brief Creates an image batch
-- @param texture The texture.
-- @return The new image batch.
function ImageBatch.new(texture)
local self = ae.oo.new(ImageBatch)
ImageBatch.construct(self,texture)
return self
end
-- @func
-- @brief Constructs an image batch.
-- @param self The image batch object.
-- @param texture The texture.
function ImageBatch.construct(self,texture)
super.construct(self)
self.texture = ae.ui.textures:load(texture.filename)
self.images = {}
end
-- @brief Creates a batch from images.
-- @param texture The texture with the image subtextures.
-- @param images The images.
function ImageBatch.createFromImages(texture,images)
local batch = ImageBatch.new(texture)
for _,image in pairs(images) do
batch:append(image)
end
return batch
end
-- @brief Adds an image to draw at the beginning of the list.
-- @param image The image to draw.
function ImageBatch:prepend(image)
image.draw = function()
end
ae.itable.prepend(self.images,image)
end
-- @brief Adds an image to draw at the end of the list.
-- @param image The image to draw.
function ImageBatch:append(image)
image.draw = function()
end
ae.itable.append(self.images,image)
end
-- @brief Draws the images.
function ImageBatch:draw()
ae.gl.enableBlend()
-- buffer
local buffer = ae.ui.drawers.tex.buffer
buffer:rewind()
-- drawer
local drawer = ae.ui.drawers.tex.drawer
drawer:drawStart()
-- color
drawer:setColor(1,1,1,1)
-- texture
self.texture.texture:bind()
-- append rectangles
local count = 0
local images = self.images
for index = 1,#images do
local bounds = images[index].itemBounds
if not bounds:isOutsideDisplay() then
count = count + 1
buffer:appendRect(
bounds.x,bounds.y,bounds.width,bounds.height,images[index].uv)
end
end
-- draw
drawer:draw(count * ae.draw2d.indicesPerRect)
end
-- @brief Gets a string which represents the image batch.
-- @return The string representing the image batch.
function ImageBatch:__tostring()
return ae.oo.tostring('ae.ui.ImageBatch',
'#images=' .. tostring(#self.images) ..
', texture=' .. tostring(self.texture),super.__tostring(self))
end
return ImageBatch
|
--[[headerData = {
type = "header",
name = "My Header", -- or string id or function returning a string
tooltip = "My Tooltip", -- or string id or function returning a string (optional)
width = "full", -- or "half" (optional)
helpUrl = "https://www.esoui.com/portal.php?id=218&a=faq", -- a string URL or a function that returns the string URL (optional)
reference = "MyAddonHeader" -- unique global reference to control (optional)
} ]]
local widgetVersion = 11
local LAM = LibAddonMenu2
if not LAM:RegisterWidget("header", widgetVersion) then return end
local wm = WINDOW_MANAGER
local function UpdateValue(control)
control.header:SetText(LAM.util.GetStringFromValue(control.data.name))
end
local MIN_HEIGHT = 30
function LAMCreateControl.header(parent, headerData, controlName)
local control = LAM.util.CreateBaseControl(parent, headerData, controlName)
local isHalfWidth = control.isHalfWidth
local width = control:GetWidth()
control:SetDimensions(isHalfWidth and width / 2 or width, MIN_HEIGHT)
control.divider = wm:CreateControlFromVirtual(nil, control, "ZO_Options_Divider")
local divider = control.divider
divider:SetWidth(isHalfWidth and width / 2 or width)
divider:SetAnchor(TOPLEFT)
control.header = wm:CreateControlFromVirtual(nil, control, "ZO_Options_SectionTitleLabel")
local header = control.header
header:SetAnchor(TOPLEFT, divider, BOTTOMLEFT)
header:SetAnchor(BOTTOMRIGHT)
header:SetText(LAM.util.GetStringFromValue(headerData.name))
LAM.util.SetUpTooltip(header, headerData)
local faqTexture = LAM.util.CreateFAQTexture(control)
if faqTexture then
faqTexture:SetAnchor(RIGHT, header, RIGHT, 0, 0)
end
control.UpdateValue = UpdateValue
LAM.util.RegisterForRefreshIfNeeded(control)
return control
end
|
#!/usr/bin/env lua
--
function test()
return true
end
|
------------------------------------------------------------------------------
--
-- This file is part of the Corona game engine.
-- For overview and more information on licensing please refer to README.md
-- Home page: https://github.com/coronalabs/corona
-- Contact: support@coronalabs.com
--
------------------------------------------------------------------------------
simulator =
{
device = "android-tv",
screenOriginX = 0,
screenOriginY = 0,
screenWidth = 720,
screenHeight = 1280,
androidDisplayApproximateDpi = 320, -- xhdpi
displayManufacturer = "OUYA",
displayName = "OUYA Console",
supportsScreenRotation = false,
isUprightOrientationPortrait = false,
windowTitleBarName = "Ouya",
safeScreenInsetTop = 64,
safeScreenInsetLeft = 36,
safeScreenInsetBottom = 64,
safeScreenInsetRight = 36,
safeLandscapeScreenInsetTop = 36,
safeLandscapeScreenInsetLeft = 64,
safeLandscapeScreenInsetBottom = 36,
safeLandscapeScreenInsetRight = 64,
}
simulator.defaultFontSize = 18.0 * (simulator.androidDisplayApproximateDpi / 160)
|
local filesystem = require("filesystem")
local component = require("component")
function filesystem.makeDirectory(path)
if filesystem.exists(path) then
return nil, "file or directory with that name already exists"
end
local node, rest = filesystem.findNode(path)
if node.fs and rest then
local success, reason = node.fs.makeDirectory(rest)
if not success and not reason and node.fs.isReadOnly() then
reason = "filesystem is readonly"
end
return success, reason
end
if node.fs then
return nil, "virtual directory with that name already exists"
end
return nil, "cannot create a directory in a virtual directory"
end
function filesystem.lastModified(path)
local node, rest, vnode, vrest = filesystem.findNode(path, false, true)
if not node or not vnode.fs and not vrest then
return 0 -- virtual directory
end
if node.fs and rest then
return node.fs.lastModified(rest)
end
return 0 -- no such file or directory
end
function filesystem.mounts()
local tmp = {}
for path,node in pairs(filesystem.fstab) do
table.insert(tmp, {node.fs,path})
end
return function()
local next = table.remove(tmp)
if next then return table.unpack(next) end
end
end
function filesystem.link(target, linkpath)
checkArg(1, target, "string")
checkArg(2, linkpath, "string")
if filesystem.exists(linkpath) then
return nil, "file already exists"
end
local linkpath_parent = filesystem.path(linkpath)
if not filesystem.exists(linkpath_parent) then
return nil, "no such directory"
end
local linkpath_real, reason = filesystem.realPath(linkpath_parent)
if not linkpath_real then
return nil, reason
end
if not filesystem.isDirectory(linkpath_real) then
return nil, "not a directory"
end
local _, _, vnode, _ = filesystem.findNode(linkpath_real, true)
vnode.links[filesystem.name(linkpath)] = target
return true
end
function filesystem.umount(fsOrPath)
checkArg(1, fsOrPath, "string", "table")
local real
local fs
local addr
if type(fsOrPath) == "string" then
real = filesystem.realPath(fsOrPath)
addr = fsOrPath
else -- table
fs = fsOrPath
end
local paths = {}
for path,node in pairs(filesystem.fstab) do
if real == path or addr == node.fs.address or fs == node.fs then
table.insert(paths, path)
end
end
for _,path in ipairs(paths) do
local node = filesystem.fstab[path]
filesystem.fstab[path] = nil
node.fs = nil
node.parent.children[node.name] = nil
end
return #paths > 0
end
function filesystem.size(path)
local node, rest, vnode, vrest = filesystem.findNode(path, false, true)
if not node or not vnode.fs and (not vrest or vnode.links[vrest]) then
return 0 -- virtual directory or symlink
end
if node.fs and rest then
return node.fs.size(rest)
end
return 0 -- no such file or directory
end
function filesystem.isLink(path)
local name = filesystem.name(path)
local node, rest, vnode, vrest = filesystem.findNode(filesystem.path(path), false, true)
if not node then return nil, rest end
local target = vnode.links[name]
-- having vrest here indicates we are not at the
-- owning vnode due to a mount point above this point
-- but we can have a target when there is a link at
-- the mount point root, with the same name
if not vrest and target ~= nil then
return true, target
end
return false
end
function filesystem.copy(fromPath, toPath)
local data = false
local input, reason = filesystem.open(fromPath, "rb")
if input then
local output = filesystem.open(toPath, "wb")
if output then
repeat
data, reason = input:read(1024)
if not data then break end
data, reason = output:write(data)
if not data then data, reason = false, "failed to write" end
until not data
output:close()
end
input:close()
end
return data == nil, reason
end
local function readonly_wrap(proxy)
checkArg(1, proxy, "table")
if proxy.isReadOnly() then
return proxy
end
local function roerr() return nil, "filesystem is readonly" end
return setmetatable({
rename = roerr,
open = function(path, mode)
checkArg(1, path, "string")
checkArg(2, mode, "string")
if mode:match("[wa]") then
return roerr()
end
return proxy.open(path, mode)
end,
isReadOnly = function()
return true
end,
write = roerr,
setLabel = roerr,
makeDirectory = roerr,
remove = roerr,
}, {__index=proxy})
end
local function bind_proxy(path)
local real, reason = filesystem.realPath(path)
if not real then
return nil, reason
end
if not filesystem.isDirectory(real) then
return nil, "must bind to a directory"
end
local real_fs, real_fs_path = filesystem.get(real)
if real == real_fs_path then
return real_fs
end
-- turn /tmp/foo into foo
local rest = real:sub(#real_fs_path + 1)
local function wrap_relative(fp)
return function(path, ...)
return fp(filesystem.concat(rest, path), ...)
end
end
local bind = {
type = "filesystem_bind",
address = real,
isReadOnly = real_fs.isReadOnly,
list = wrap_relative(real_fs.list),
isDirectory = wrap_relative(real_fs.isDirectory),
size = wrap_relative(real_fs.size),
lastModified = wrap_relative(real_fs.lastModified),
exists = wrap_relative(real_fs.exists),
open = wrap_relative(real_fs.open),
remove = wrap_relative(real_fs.remove),
read = real_fs.read,
write = real_fs.write,
close = real_fs.close,
getLabel = function() return "" end,
setLabel = function() return nil, "cannot set the label of a bind point" end,
}
return bind
end
filesystem.internal = {}
function filesystem.internal.proxy(filter, options)
checkArg(1, filter, "string")
checkArg(2, options, "table", "nil")
options = options or {}
local address, proxy, reason
if options.bind then
proxy, reason = bind_proxy(filter)
else
-- no options: filter should be a label or partial address
for c in component.list("filesystem", true) do
if component.invoke(c, "getLabel") == filter then
address = c
break
end
if c:sub(1, filter:len()) == filter then
address = c
break
end
end
if not address then
return nil, "no such file system"
end
proxy, reason = component.proxy(address)
end
if not proxy then
return proxy, reason
end
if options.readonly then
proxy = readonly_wrap(proxy)
end
return proxy
end
|
--- Embedded HTTP framework.
-- @module haproxy.embed
local http = {}
--- RFC2616 HTTP/1.1 status codes
http.status = {
CONTINUE = 100, -- `100 Continue`
SWITCHING_PROTOCOLS = 101, -- `101 Switching Protocols`
OK = 200, -- `200 OK`
CREATED = 201, -- `201 Created`
ACCEPTED = 202, -- `202 Accepted`
NON_AUTHORITATIVE_INFORMATION = 203, -- `203 Non-Authoritative Information`
NO_CONTENT = 204, -- `204 No Content`
RESET_CONTENT = 205, -- `205 Reset Content`
PARTIAL_CONTENT = 206, -- `206 Partial Content`
MULTIPLE_CHOICES = 300, -- `300 Multiple Choices`
MOVED_PERMANENTLY = 301, -- `301 Moved Permanently`
FOUND = 302, -- `302 Found`
SEE_OTHER = 303, -- `303 See Other`
NOT_MODIFIED = 304, -- `304 Not Modified`
USE_PROXY = 305, -- `305 Use Proxy`
TEMPORARY_REDIRECT = 307, -- `307 Temporary Redirect`
BAD_REQUEST = 400, -- `400 Bad Request`
UNAUTHORIZED = 401, -- `401 Unauthorized`
PAYMENT_REQUIRED = 402, -- `402 Payment Required`
FORBIDDEN = 403, -- `403 Forbidden`
NOT_FOUND = 404, -- `404 Not Found`
METHOD_NOT_ALLOWED = 405, -- `405 Method Not Allowed`
NOT_ACCEPTABLE = 406, -- `406 Not Acceptable`
PROXY_AUTHENTICATION_REQUIRED = 407, -- `407 Proxy Authentication Required`
REQUEST_TIME_OUT = 408, -- `408 Request Time-out`
CONFLICT = 409, -- `409 Conflict`
GONE = 410, -- `410 Gone`
LENGTH_REQUIRED = 411, -- `411 Length Required`
PRECONDITION_FAILED = 412, -- `412 Precondition Failed`
REQUEST_ENTITY_TOO_LARGE = 413, -- `413 Request Entity Too Large`
REQUEST_URI_TOO_LARGE = 414, -- `414 Request-URI Too Large`
UNSUPPORTED_MEDIA_TYPE = 415, -- `415 Unsupported Media Type`
REQUESTED_RANGE_NOT_SATISFIABLE = 416, -- `416 Requested range not satisfiable`
EXPECTATION_FAILED = 417, -- `417 Expectation Failed`
IM_A_TEAPOT = 418, -- `I'm a teapot`
INTERNAL_SERVER_ERROR = 500, -- `500 Internal Server Error`
NOT_IMPLEMENTED = 501, -- `501 Not Implemented`
BAD_GATEWAY = 502, -- `502 Bad Gateway`
SERVICE_UNAVAILABLE = 503, -- `503 Service Unavailable`
GATEWAY_TIME_OUT = 504, -- `504 Gateway Time-out`
HTTP_VERSION_NOT_SUPPORTED = 505, -- `505 HTTP Version not supported`
}
--- RFC2616 HTTP/1.1 methods
http.method = {
DELETE = 'DELETE',
GET = 'GET',
HEAD = 'HEAD',
OPTIONS = 'OPTIONS',
PATCH = 'PATCH',
POST = 'POST',
PUT = 'PUT',
}
return http
|
local M = {}
local jenkins96, bin = require("casc.jenkins96"), require("casc.bin")
local uint32_le, int32_le, to_bin, ssub = bin.uint32_le, bin.int32_le, bin.to_bin, string.sub
local function toBinHash(h, hexLength)
return #h == hexLength and to_bin(h) or h
end
local wow_mt = {__index={}} do
local wow = wow_mt.__index
local function nextVariant(e, i)
i = (i or -1) + 2
local h = e and e[i]
if h then
return i, h, e[i+1]
end
end
function wow:getFileVariants(nameOrID)
local fid = nameOrID
if type(nameOrID) ~= "number" then
fid = self[1][jenkins96.hash_path(nameOrID)]
end
return nextVariant, self[2][fid]
end
function wow:addFileVariant(path, chash, flags)
local nameMap, idVariantMap = self[1], self[2]
local hpath = jenkins96.hash_path(path)
local fid = nameMap[hpath]
if not fid then
fid = (self[3] or 10041)-1
nameMap[hpath], idVariantMap[fid], self[3] = fid, {}, fid
end
local t = idVariantMap[fid]
t[#t+1], t[#t+2] = toBinHash(chash, 32), flags
end
function wow:getFileID(path)
return self[1][jenkins96.hash_path(path)]
end
function wow:addFileIDPaths(map, pathsArePrehashed)
local nameMap, idVariantMap = self[1], self[2]
for k,v in pairs(map) do
local tk, tv, path, fileID = type(k), type(v)
if tk == "number" and tv == "string" then
path, fileID = v, k
elseif tk == "string" and tv == "number" then
path, fileID = k, v
end
if not path then
error("root:addFileIDPaths: map kv pairs should be (string, number) or (number, string).")
end
local h = pathsArePrehashed and to_bin(path, 16) or jenkins96.hash_path(path)
if nameMap[h] == nil and idVariantMap[fileID] then
nameMap[h] = fileID
end
end
end
end
local function parseLegacy(data)
local pos, dl, nameMap, idVariantMap = 0, #data, {}, {}
while pos < dl do
if dl < (pos+12) then
return false, 'Root file invalid: expected to read at least 12 bytes from position ' .. pos
end
local n, info = uint32_le(data, pos), {uint32_le(data, pos+4), uint32_le(data, pos+8)}
local p2, lfid, tfid = pos + 12, 0
if dl < (p2+28*n) then
return false, 'Root file invalid: expected to read at least ' .. (28*n) .. ' bytes from position ' .. p2
end
pos = p2 + 4*n
for i=1,n do
local chash, tfid = ssub(data, pos+1, pos+16), lfid+int32_le(data, p2)
local nhash = ssub(data, pos+17, pos+24)
pos, p2 = pos + 24, p2 + 4
local t, tsz = idVariantMap[tfid] or {}
if (nameMap[nhash] or tfid) ~= tfid then
return false, 'Root manifest invalid: file name name ' .. ('%02x'):rep(#nhash):format(nhash:byte(1, #nhash)) .. ' maps to multiple file IDs'
end
nameMap[nhash], idVariantMap[tfid], tsz = tfid, t, #t
t[tsz+1], t[tsz+2], lfid = chash, info, tfid + 1
end
end
return setmetatable({nameMap, idVariantMap}, wow_mt)
end
local function parseMFST(data)
if #data < 16 then
return false, 'Root manifest invalid: expected to read at least 16 bytes from position 0'
end
local pos, dl, nameMap, idVariantMap = 12, #data, {}, {}
local readFiles, readNamedFiles = 0, 0
local two28, two29 = 2^28, 2^29
while pos < dl do
if dl < (pos+12) then
return false, 'Root manifest invalid: expected to read at least 12 bytes from position ' .. pos
end
local n, info = uint32_le(data, pos), {uint32_le(data, pos+4), uint32_le(data, pos+8)}
local p2, p3, lfid, tfid = pos + 12, pos + 12 + 20*n, 0
local hasNameHashes = (info[1] % two29 < two28) and 1
if dl < (p2+(hasNameHashes and 28 or 20)*n) then
return false, 'Root manifest invalid: expected to read at least ' .. (28*n) .. ' bytes from position ' .. p2
end
pos = p2 + 4*n
for i=1,n do
local chash, tfid = ssub(data, pos+1, pos+16), lfid+int32_le(data, p2)
pos, p2 = pos + 16, p2 + 4
local t, tsz = idVariantMap[tfid] or {}
if hasNameHashes then
local nhash = ssub(data, p3+1, p3+8)
if (nameMap[nhash] or tfid) ~= tfid then
return false, 'Root manifest invalid: file name name ' .. ('%02x'):rep(#nhash):format(nhash:byte(1, #nhash)) .. ' maps to multiple file IDs'
end
nameMap[nhash], p3 = tfid, p3 + 8
end
idVariantMap[tfid], tsz = t, #t
t[tsz+1], t[tsz+2], lfid = chash, info, tfid + 1
readFiles, readNamedFiles = readFiles + 1, readNamedFiles + (hasNameHashes or 0)
end
pos = p3
end
if readFiles ~= uint32_le(data, 4) then
return false, 'Root manifest invalid: expected ' .. uint32_le(data, 4) .. ' files; found ' .. readFiles
end
if readNamedFiles ~= uint32_le(data, 8) then
return false, 'Root manifest invalid: expected ' .. uint32_le(data, 8) .. ' named files; found ' .. readNamedFiles
end
return setmetatable({nameMap, idVariantMap}, wow_mt)
end
function M.parse(data)
if data:sub(1,4) == "TSFM" then
return parseMFST(data)
end
return parseLegacy(data)
end
function M.empty()
return setmetatable({{}, {}}, wow_mt)
end
return M
|
<%- partial('../sidebar') %>
<div id='content'>
<div class='panel'>
<div class='header'>
<ul class='breadcrumb'>
<li><a href='/'>主页</a><span class='divider'>/</span></li>
<li class='active'><a href="/user/<%- user.loginname %>"><%- user.loginname %>的主页</a></li>
</ul>
</div>
</div>
<div class='panel'>
<div class="header"><%- user.loginname %> 创建的话题</div>
<div class="inner padding">
<% if type(topics) == 'table' and #topics > 0 then %>
<%- partial('../topic/list', {topics = topics, pages = pages, current_pages = current_page, base = '/user/'..user.loginname..'/topics'}) %>
<% else %>
<div class='inner'>
<p>无话题</p>
</div>
<% end %>
</div>
</div>
</div>
|
--
-- different roles:
-- passive : manual config, will be mapped to the menu system
-- keymap : current keyboard state will be pushed unto map,
-- map defines SYM/key -> ledid translation
-- custom : separate function, invoked from clock_pulse
-- dispmap : separate function, sample-rate triggered clock
--
-- if a device doesn't have a matching profile, it will always go to passive
--
local readback_handler;
local profile_path = "devmaps/led";
local devices = {
passive = {},
keymap = {},
custom = {},
};
local profiles = {};
local function tryload(map)
res = system_load(profile_path .. "/" .. map, 0);
if (not res) then
warning(string.format("ledm, system_load on map %s failed", map));
return;
end
local okstate, devtbl = pcall(res);
if (not okstate or not type(devtbl) == "table") then
warning(string.format("ledm, couldn't load/parse %s", map));
return;
end
-- FIXME: type-validation
return devtbl;
end
local function load_profiles()
local list = glob_resource(profile_path .. "/*.lua");
if (not list) then
return;
end
table.sort(list);
for k,v in ipairs(list) do
local res = tryload(v);
if (res and type(res.role) == "string" and devices[res.role] ~= nil) then
table.insert(profiles, res);
end
end
end
function ledm_added(tbl)
-- shouldn't trigger anything but protect against platform bugs
ledm_removed(tbl);
for i,v in ipairs(profiles) do
if ((v.matchdev and tbl.domain == "platform" and tbl.devid == v.matchdev) or
(v.matchlbl == tbl.label)) then
local newt = {};
for k,v in pairs(v) do
newt[k] = v;
end
newt.devid = tbl.devid;
table.insert(devices[v.role], newt);
return;
end
end
-- still here, then it's a passive one
table.insert(devices.passive, {
domain = tbl.domain,
devid = tbl.devid,
role = "passive",
label = tbl.label,
name = tostring(tbl.devid)
});
end
-- Find device reference and invoke event handler, note that the event
-- layer does not track device label, only domain+id
function ledm_removed(tbl)
for k, d in pairs(devices) do
for i, v in ipairs(d) do
if (v.domain == tbl.domain and v.devid == tbl.devid) then
if (v.destroy) then
v:destroy();
end
table.remove(d, i);
return;
end
end
end
end
-- check and see if there's a specific color to indicate for [path],
local function resolve_path_color(v, path, fb_col)
local res = {255, 255, 255};
if (v[fb_col]) then
res = v[fb_col];
elseif (v.default_color) then
res = v.default_color;
end
-- it's possible to add custom colors to paths or path prefixes in
-- order to distinguish between different bindings in a file-grained
-- manner
if (v.path_colors) then
-- strip out any =value
local vt = string.split(pathdescr, "=");
if (#vt > 0) then
path = vt[1];
end
-- always favor exact matches so that we can handle:
-- !window/* and !window/1/weird
for k,v in pairs(v.path_colors) do
if (k == path) then
return v;
elseif (string.sub(k, string.len(k)) == "*") then
local ps = string.sub(k, 1, string.len(k)-1);
local paths = string.sub(path, 1, string.len(ps));
if (paths == ps) then
res = v;
return res;
end
end
end
end
return res;
end
-- updated when selection changes, locked state changes or meta- key state
-- changes.
function ledm_kbd_state(m1, m2, locked, globals, locals)
if (locked) then
for k,v in ipairs(devices.keymap) do
local cl = v.default_color;
if (v.proxy) then
v.proxy(v.devid, -1, cl[1], cl[2], cl[3]);
else
ledfun(v.devid, -1, cl[1], cl[2], cl[3]);
end
end
return;
end
-- reset everything, light up m1/m2 unless they are pressed.
for k,v in ipairs(devices.keymap) do
local cl = v.default_color;
local ledfun = v.proxy and v.proxy or set_led_rgb;
ledfun(v.devid, -1, 0, 0, 0, true);
if (not m1) then
local cl = v.m1_color;
ledfun(v.devid, v.m1, cl[1], cl[2], cl[3], true);
end
if (not m2) then
local cl = v.m2_color;
ledfun(v.devid, v.m2, cl[1], cl[2], cl[3], true);
end
if (globals) then
for i,d in ipairs(globals) do
if (v.symtable[d[1]]) then
local cl = resolve_path_color(v, d[2], "global_color");
ledfun(v.devid, v.symtable[d[1]], cl[1], cl[2], cl[3], true);
end
end
end
ledfun(v.devid, 255, 0, 0, 0);
--
-- reserved for now as the shmif- part actually misses the modifier information
-- if (locals) then
-- for i,d in ipairs(locals) do
-- if (v.symtable[d]) then
-- set_led_rgb(v.devid, v.symtable[d], unpack(v.target_custom_color), true);
-- end
-- end
-- end
-- abuse the last id as a way to commit without tracking more state
end
end
-- FIXME: display_map listener
--
-- return a table of all the present LED devices that match all or one role
--
function ledm_devices(role)
local res = {};
if (role) then
return (devices[role] and devices[role] or res);
end
for k, d in pairs(devices) do
for i, v in ipairs(d) do
local ent = {
label = v.label and v.label or tostring(v.devid),
name = v.name and v.name or tostring(v.devid),
devid = v.devid
};
ent.description = "Access LED device " .. ent.label;
table.insert(res, ent);
end
end
return res;
end
function ledm_tick()
local ledf = function(k, v)
if (v.counter == nil or v.counter == 1) then
v.counter = v.tickrate;
v.clock(v.devid);
else
v.counter = v.counter - 1;
end
end
for k,v in ipairs(devices.custom) do
ledf(k, v);
end
for k,v in ipairs(devices.keymap) do
if (v.clock) then
ledf(k, v);
end
end
end
load_profiles();
|
-- This file assumes ``autorun/webaudio.lua`` ran right before it.
local Common = _G.WebAudio.Common
local Modify = Common.Modify
util.AddNetworkString("wa_create") -- To send to the client to create a Clientside WebAudio struct
util.AddNetworkString("wa_change") -- To send to the client to modify Client WebAudio structs
util.AddNetworkString("wa_ignore") -- To receive from the client to make sure to ignore players to send to in WebAudio transmissions
util.AddNetworkString("wa_enable") -- To receive from the client to make sure people with wa_enable 0 don't get WebAudio transmissions
util.AddNetworkString("wa_info") -- To receive information about BASS / IGmodAudioChannel streams from clients that create them.
util.AddNetworkString("wa_fft") -- Receive fft data.
local WebAudio = Common.WebAudio
-- TODO: Make this table + hash table version cancer an object or just do this another way. I'm not sure how to do it.
-- I would use a CRecipientFilter but I also need to add the people with wa_enable to 0 rather than just the people who used wa_purge to kill certain objects.
-- If you could merge two CRecipientFilters that'd be cool
local StreamDisabledPlayers = { -- People who have wa_enabled set to 0
__hash = {},
__net = {} -- Net friendly array
}
--- Adds a modify flag to the payload to be sent on transmission
-- @param number n Modify flag from the Modify struct in wa_common
-- @return boolean Whether it modified. Will return nil if stream is destroyed.
function WebAudio:AddModify(n)
if self:IsDestroyed() then return end
self.modified = bit.bor(self.modified, n)
end
--- Sets the volume of the stream
-- Does not transmit
-- @param number vol Float Volume (1 is 100%, 2 is 200% ..)
-- @return boolean Successfully set time, will return nil if stream or 'vol' are invalid or 'vol' didn't change.
function WebAudio:SetVolume(vol)
if self:IsDestroyed() then return end
if isnumber(vol) and self.volume ~= vol then
self.volume = vol
self:AddModify(Modify.volume)
return true
end
end
--- Sets the current playback time of the stream.
-- Does not transmit
-- @param number time UInt16 Playback time
-- @return boolean Successfully set time, will return nil if stream is invalid.
function WebAudio:SetTime(time)
if self:IsDestroyed() then return end
if isnumber(time) then
self.time = time
self.stopwatch:SetTime(time)
self:AddModify(Modify.time)
return true
end
end
--- Sets the position of the stream.
-- @param Vector pos Position
-- @return boolean Successfully set position, will return nil if stream or 'pos' are invalid or if 'pos' didn't change.
function WebAudio:SetPos(pos)
if self:IsDestroyed() then return end
if self:IsParented() then return end
if isvector(pos) and self.pos ~= pos then
self.pos = pos
self:AddModify(Modify.pos)
return true
end
end
--- Sets the direction in which the stream will play
-- @param Vector dir Direction to set to
-- @return boolean Successfully set direction, will return nil if stream or 'dir' are invalid or if 'dir' didn't change.
function WebAudio:SetDirection(dir)
if self:IsDestroyed() then return end
if isvector(dir) and self.direction ~= dir then
self.direction = dir
self:AddModify(Modify.direction)
return true
end
end
--- Resumes or starts the stream.
-- @return boolean Successfully played, will return nil if the stream is destroyed or if already playing
function WebAudio:Play()
if self:IsDestroyed() then return end
if self.playing == false then
self:AddModify(Modify.playing)
self.playing = true
self:Transmit()
return true
end
end
--- Pauses the stream and automatically transmits.
-- @return boolean Successfully paused, will return nil if the stream is destroyed or if already paused
function WebAudio:Pause()
if self:IsDestroyed() then return end
if self.playing then
self:AddModify(Modify.playing)
self.playing = false
self:Transmit()
return true
end
end
--- Sets the playback rate of the stream.
-- @param number rate Playback rate. Float64 that clamps to 255.
-- @return boolean Successfully set rate, will return nil if stream or 'rate' are invalid or if 'rate' didn't change.
function WebAudio:SetPlaybackRate(rate)
if self:IsDestroyed() then return end
if not isnumber(rate) then return end
rate = math.min(rate, 255)
if self.playback_rate ~= rate then
self.stopwatch:SetRate(rate)
self.playback_rate = rate
self:AddModify(Modify.playback_rate)
return true
end
end
--- Sets the radius of the stream. Uses Set3DFadeDistance internally.
-- @param number radius UInt16 radius
-- @return boolean Successfully set radius, will return nil if the stream or 'radius' are invalid or if radius didn't change.
function WebAudio:SetRadius(radius)
if self:IsDestroyed() then return end
if isnumber(radius) and self.radius ~= radius then
self.radius = radius
self:AddModify(Modify.radius)
return true
end
end
--- Sets the parent of the WebAudio object. Nil to unparent
-- @param entity? parent Entity to parent to or nil to unparent.
-- @return boolean Whether it was successfully parented. Returns nil if the stream is invalid.
function WebAudio:SetParent(ent)
if self:IsDestroyed() then return end
if isentity(ent) and ent:IsValid() then
self.parented = true
self.parent = ent
else
self.parented = false
self.parent = nil
end
self:AddModify(Modify.parented)
return true
end
--- Makes the stream loop or stop looping.
-- @param boolean loop Whether it should be looping
-- @return boolean If we set the value or not. Returns nil if the stream isn't valid or if the value didn't change.
function WebAudio:SetLooping(loop)
if self:IsDestroyed() then return end
if self.looping ~= loop then
self.stopwatch:SetLooping(loop)
self.looping = loop
self:AddModify(Modify.looping)
return true
end
end
--- Set the stream to accept FFT data periodically.
-- @param boolean enabled Whether it's enabled or not.
-- @return boolean If we set the value or not. Returns nil if the stream isn't valid or if the value didn't change.
function WebAudio:SetFFTEnabled(enabled)
if self.fft_enabled ~= enabled then
self.fft_enabled = enabled
self:AddModify(Modify.fft_enabled)
return true
end
end
local hasModifyFlag = Common.hasModifyFlag
--- Transmits all stored data on the server about the WebAudio object to the clients
-- @return boolean If successfully transmitted.
function WebAudio:Transmit()
if self:IsDestroyed() then return end
net.Start("wa_change", true)
-- Always present values
WebAudio:writeID(self.id)
local modified = self.modified
WebAudio:writeModify(modified)
if not hasModifyFlag(modified, Modify.destroyed) then
if hasModifyFlag(modified, Modify.volume) then
net.WriteFloat(self.volume)
end
if hasModifyFlag(modified, Modify.time) then
net.WriteUInt(self.time, 16)
end
if hasModifyFlag(modified, Modify.pos) then
net.WriteVector(self.pos)
end
if hasModifyFlag(modified, Modify.direction) then
net.WriteVector(self.direction)
end
if hasModifyFlag(modified, Modify.playback_rate) then
net.WriteFloat(self.playback_rate)
end
if hasModifyFlag(modified, Modify.radius) then
net.WriteUInt(self.radius, 16)
end
if hasModifyFlag(modified, Modify.looping) then
net.WriteBool(self.looping)
end
if hasModifyFlag(modified, Modify.fft_enabled) then
net.WriteBool(self.fft_enabled)
end
if hasModifyFlag(modified, Modify.parented) then
net.WriteBool(self.parented)
if self.parented then
net.WriteEntity(self.parent)
end
end
if hasModifyFlag(modified, Modify.playing) then
net.WriteBool(self.playing)
end
end
self:Broadcast()
self.modified = 0 -- Reset any modifications
return true
end
--- Registers an object to not send any net messages to from WebAudio transmissions.
-- This is called by clientside destruction.
-- @param Player ply The player to stop sending net messages to
function WebAudio:Unsubscribe(ply)
self.ignored:AddPlayer(ply)
end
--- Registers an object to send net messages to a chip after calling Unsubscribe on it.
-- @param Player ply The player to register to get messages again
function WebAudio:Subscribe(ply)
self.ignored:RemovePlayer(ply)
end
--- Runs net.SendOmit for you, just broadcasts the webaudio to all players with the object enabled.
-- Does not broadcast to people who have destroyed the object on their client
-- Does not broadcast to people with wa_enable set to 0.
function WebAudio:Broadcast()
net.SendOmit( table.Add(self.ignored:GetPlayers(), StreamDisabledPlayers.__net) )
end
--- Stop sending net messages to players who want to ignore certain streams.
net.Receive("wa_ignore", function(len, ply)
if WebAudio:isSubscribed(ply) == false then return end -- They already have wa_enable set to 0
local n_ignores = net.ReadUInt(8)
for k = 1, n_ignores do
local stream = WebAudio:getFromID(WebAudio:readID())
if stream then
stream:Unsubscribe(ply)
end -- Doesn't exist anymore, maybe got removed when the net message was sending
end
end)
--- This receives net messages when the SERVER wants information about a webaudio stream you created.
-- It gets stuff like average bitrate and length of the song this way.
-- You'll only be affecting your own streams and chip, so there's no point in "abusing" this.
net.Receive("wa_info", function(len, ply)
local stream = WebAudio:getFromID( WebAudio:readID() )
if stream and stream.needs_info and stream.owner == ply then
-- Make sure the stream exists, hasn't already received client info & That the net message sender is the owner of the WebAudio object.
local length = net.ReadUInt(16)
local file_name = net.ReadString()
stream.length = length
stream.filename = file_name
stream.needs_info = false
local watch = stream.stopwatch
watch:SetDuration(length)
watch:SetRate(stream.playback_rate)
watch:SetTime(stream.time)
watch:Start()
end
end)
net.Receive("wa_enable", function(len, ply)
local enabled = net.ReadBool()
if enabled then
WebAudio:subscribe(ply)
else
WebAudio:unsubscribe(ply)
end
end)
-- FFT will be an array of UInts (check FFTSAMP_LEN). It may not be fully filled to 64 samples, some may be nil to conserve bandwidth. Keep this in mind.
-- We don't have to care for E2 since e2 automatically gives you 0 instead of nil or an error.
net.Receive("wa_fft", function(len, ply)
local stream = WebAudio:getFromID( WebAudio:readID() )
if stream and stream.fft_enabled and stream.owner == ply then
local samp_len = WebAudio.FFTSAMP_LEN
local samples = (len - WebAudio.ID_LEN) / samp_len
local t = stream.fft
for i = 1, 64 do
t[i] = i > samples and 0 or net.ReadUInt(samp_len)
end
end
end)
hook.Add("PlayerDisconnected", "wa_player_cleanup", function(ply)
if ply:IsBot() then return end
table.RemoveByValue(StreamDisabledPlayers.__net, ply)
StreamDisabledPlayers.__hash[ply] = nil
end)
hook.Add("PlayerInitialSpawn", "wa_player_init", function(ply, transition)
if ply:IsBot() then return end
if ply:GetInfoNum("wa_enable", 1) == 0 then
WebAudio:unsubscribe(ply)
end
end)
local WebAudioStatic = WebAudio:getStatics()
--- Unsubscribe a player from receiving WebAudio net messages
-- Like the non-static method but for all future Streams & Messages
-- @param Player ply Player to check
function WebAudioStatic:unsubscribe(ply)
if WebAudio:isSubscribed(ply) then
StreamDisabledPlayers.__hash[ply] = true
table.insert(StreamDisabledPlayers.__net, ply)
end
end
--- Resubscribe a player to receive WebAudio net messages
-- @param Player ply Player to subscribe
function WebAudioStatic:subscribe(ply)
if not WebAudio:isSubscribed(ply) then
StreamDisabledPlayers.__hash[ply] = false
table.RemoveByValue(StreamDisabledPlayers.__net, ply)
end
end
--- Returns whether the player is subscribed to receive WebAudio net messages or not.
-- @param Player ply Player to check
-- @return boolean If the player is subscribed.
function WebAudioStatic:isSubscribed(ply)
return StreamDisabledPlayers.__hash[ply] ~= false
end
|
-- Lua 5.1 doesn't have support for bitwise operations
function testFlag(set, flag)
return set % (2*flag) >= flag
end
function setFlag(set, flag)
if set % (2*flag) >= flag then
return set
end
return set + flag
end
function clearFlag(set, flag)
if set % (2*flag) >= flag then
return set - flag
end
return set
end
|
local Class = require '30log'
context('Instances (Objects)',function()
context('When a class is created', function()
local Window
before(function()
Window = Class {size = 100}
function Window:setSize(size) self.size = size end
end)
test('new objects can be created via Class:new()',function()
assert_equal(type(Window:new()),'table')
end)
test('new objects can be created calling the class as a function',function()
assert_equal(type(Window()),'table')
end)
test('new objects share their class attributes',function()
assert_equal((Window()).size,100)
end)
test('new objects share their class methods',function()
local win = Window()
win:setSize(10)
assert_equal(win.size,10)
end)
test('Objects cannot call new()', function()
local win = Window()
local function should_err() local win_new = win:new() end
local function should_err2() local win_new = win() end
assert_error(should_err)
assert_error(should_err2)
end)
end)
context('Providing an __init() method to classes',function()
local Window
before(function()
Window = Class {size = 100}
function Window:setSize(size) self.size = size end
function Window:__init(size) self.size = size end
end)
test('Overrides instantiation scheme with Class:new()',function()
local window = Window:new(25)
assert_equal(window.size,25)
end)
test('Overrides instantiation scheme with Class()',function()
local window = Window(90)
assert_equal(window.size,90)
end)
end)
context('Through the initializer', function()
test('class methods are callable', function()
local upvalue = false
local foo = Class()
function foo:__init(bool)
self:set_upvalue(bool)
end
function foo:set_upvalue(bool)
upvalue = bool
end
local foo_obj = foo(true)
assert_true(upvalue)
end)
end)
context('.__init can also be a table of named args for static instantiation',function()
local Window
before(function()
Window = Class()
function Window:setSize(size) self.size = size end
Window.__init = {size = 25}
end)
test('Overrides instantiation scheme with Class:new()',function()
local window = Window:new(100)
assert_equal(window.size,25)
end)
test('Overrides instantiation scheme with Class()',function()
local window = Window(90)
assert_equal(window.size,25)
end)
end)
context('tostring', function()
test('objects from unnammed classes can be stringified', function()
local myClass = Class()
assert_equal(tostring(myClass()):match('(.+):<.+>$'), 'object(of ?)')
end)
test('objects from named classes can be stringified', function()
local myClass = Class()
myClass.__name = 'aClass'
assert_equal(tostring(myClass()):match('(.+):<.+>$'), 'object(of aClass)')
end)
end)
end)
|
box = class("box")
function box:init(x, y)
--PHYSICS STUFF
self.cox = x
self.coy = y
self.x = x-14/16
self.y = y-12/16
self.speedy = 0
self.speedx = 0
self.width = 12/16
self.height = 12/16
self.static = false
self.active = true
self.category = 9
self.parent = nil
self.portaloverride = true
self.mask = { true,
false, false, false, false, false,
false, true, false, true, true,
false, false, true, false, false,
true, true, false, false, true,
false, true, true, false, false,
true, false, true, true, true}
self.emancipatecheck = true
self.userect = adduserect(self.x, self.y, 12/16, 12/16, self)
--IMAGE STUFF
self.drawable = true
self.graphic = boximg
self.quad = boxquad[1]
self.offsetX = 6
self.offsetY = 2
self.quadcenterX = 6
self.quadcenterY = 6
self.rotation = 0 --for portals
self.gravitydirection = math.pi/2
self.falling = false
self.destroying = false
self.outtable = {}
self.portaledframe = false
end
function box:update(dt)
local friction = boxfrictionair
if self.falling == false then
friction = boxfriction
end
--Funnels and fuck
if self.funnel and not self.infunnel then
self:enteredfunnel(true)
end
if self.infunnel and not self.funnel then
self:enteredfunnel(false)
end
self.funnel = false
if not self.pushed then
if self.speedx > 0 then
self.speedx = self.speedx - friction*dt
if self.speedx < 0 then
self.speedx = 0
end
else
self.speedx = self.speedx + friction*dt
if self.speedx > 0 then
self.speedx = 0
end
end
else
self.pushed = false
end
self.rotation = 0
if self.parent then
local oldx = self.x
local oldy = self.y
self.x = self.parent.x+math.sin(-self.parent.pointingangle)*0.3
self.y = self.parent.y-math.cos(-self.parent.pointingangle)*0.3
if self.portaledframe == false then
for h, u in pairs(emancipationgrills) do
if u.active then
if u.dir == "hor" then
if inrange(self.x+6/16, u.startx-1, u.endx, true) and inrange(u.y-14/16, oldy, self.y, true) then
self:emancipate(h)
end
else
if inrange(self.y+6/16, u.starty-1, u.endy, true) and inrange(u.x-14/16, oldx, self.x, true) then
self:emancipate(h)
end
end
end
end
end
self.rotation = self.parent.rotation
end
self.userect.x = self.x
self.userect.y = self.y
--check if offscreen
if self.y > mapheight+2 then
self:destroy()
end
self.portaledframe = false
if self.destroying then
return true
else
return false
end
end
function box:globalcollide(a, b, c, d, dir)
if a == "platform" or a == "seesawplatform" then
if dir == "floor" then
if self.jumping and self.speedy < -jumpforce + 0.1 then
return true
end
else
return true
end
end
end
function box:ceilcollide(a, b)
if self:globalcollide(a, b, c, d, "ceil") then
return false
end
end
function box:leftcollide(a, b)
if self:globalcollide(a, b, c, d, "left") then
return false
end
if a == "button" then
self.y = b.y - self.height
self.x = b.x + b.width - 0.01
if self.speedy > 0 then
self.speedy = 0
end
return false
elseif a == "player" then
self.pushed = true
return false
end
end
function box:rightcollide(a, b)
if self:globalcollide(a, b, c, d, "right") then
return false
end
if a == "button" then
self.y = b.y - self.height
self.x = b.x - self.width+0.01
if self.speedy > 0 then
self.speedy = 0
end
return false
elseif a == "player" then
self.pushed = true
return false
end
end
function box:floorcollide(a, b)
if self:globalcollide(a, b, c, d, "floor") then
return false
end
if self.falling then
self.falling = false
end
if a == "enemy" and b.killedbyboxes then
b:stomp()
addpoints(200, self.x, self.y)
playsound("stomp")
self.falling = true
self.speedy = -10
return false
end
end
function box:passivecollide(a, b)
if self:globalcollide(a, b, c, d, "passive") then
return false
end
if a == "player" then
if self.x+self.width > b.x+b.width then
self.x = b.x+b.width
else
self.x = b.x-self.width
end
end
end
function box:startfall()
self.falling = true
end
function box:emancipate()
if not self.destroying then
local speedx, speedy = self.speedx, self.speedy
if self.parent then
self.parent:cubeemancipate()
speedx = speedx + self.parent.speedx
speedy = speedy + self.parent.speedy
end
table.insert(emancipateanimations, emancipateanimation:new(self.x, self.y, self.width, self.height, self.graphic, self.quad, speedx, speedy, self.rotation, self.offsetX, self.offsetY, self.quadcenterX, self.quadcenterY))
self:destroy()
end
end
function box:destroy()
self.userect.delete = true
self.destroying = true
for i = 1, #self.outtable do
if self.outtable[i][1].input then
self.outtable[i][1]:input("toggle", self.outtable[i][2])
end
end
end
function box:addoutput(a, t)
table.insert(self.outtable, {a, t})
end
function box:used(id)
self.parent = objects["player"][id]
self.active = false
objects["player"][id]:pickupbox(self)
end
function box:dropped()
self.parent = nil
self.active = true
end
function box:portaled()
self.portaledframe = true
end
function box:enteredfunnel(inside)
if inside then
self.infunnel = true
else
self.infunnel = false
self.gravity = nil
end
end
function box:faithplate(dir)
self.falling = true
end
function box:onbutton(s)
if s then
self.quad = boxquad[2]
else
self.quad = boxquad[1]
end
end
|
---
-- Sink a signal and do nothing. This sink accepts any data type.
--
-- @category Sinks
-- @block NopSink
--
-- @signature in:any >
--
-- @usage
-- local snk = radio.NopSink()
-- top:connect(src, snk)
local block = require('radio.core.block')
local NopSink = block.factory("NopSink")
function NopSink:instantiate()
-- Accept all input types
self:add_type_signature({block.Input("in", function (t) return true end)}, {})
end
function NopSink:process(x)
-- Do nothing
end
return NopSink
|
--[[
CurrentInput
Useful to let the game respond to input type change.
Took inspiration from Sleitnick's version of PreferredInput
]]
local UserInputService = game:GetService("UserInputService")
local package = script.Parent.Parent.Parent
local components = package.Components
local signal = require(components.Signal)
local currentActive = nil
-- signal events
local onChange = signal.new()
local function switchCurrent(inputType: string)
if inputType ~= currentActive then
currentActive = inputType
onChange:Fire(inputType)
end
end
local function checkInput(inputType: Enum)
if inputType == Enum.UserInputType.Touch then
switchCurrent("Touch")
elseif string.sub(inputType.Name, 1, 7) == "Gamepad" then
switchCurrent("Gamepad")
elseif string.sub(inputType.Name, 1, 5) == "Mouse" or UserInputService.KeyboardEnabled then
switchCurrent("MouseKeyboard")
end
end
checkInput(UserInputService:GetLastInputType())
UserInputService.LastInputTypeChanged:Connect(checkInput)
return onChange
|
function gameStates.core.load()
love.graphics.setScreen('top')
core = {} --create a table to hold variables for the core
core.state = 0
core.image = love.graphics.newImage('img/core/core.png') --load the core img
core.x = (love.graphics.getWidth() / 2) - (core.image:getWidth() / 2) --center the core
core.y = 2
core.opacity = 255
core.fade = 0
function core.quit()
love.audio.stop()
--core.bgm = nil
love.load()
end
cliff = {}
cliff.image = love.graphics.newImage('img/core/cliff.png')
cliff.x = 0
cliff.y = love.graphics.getHeight() - cliff.image:getHeight()
frisk = {}
frisk.image = love.graphics.newImage('img/core/frisk.png')
frisk.x = love.graphics.getWidth() - 144
frisk.y = cliff.y - 10
--core.bgm = love.audio.newSource('snd/mus_anothermedium.wav') --load the bgm
--core.bgm:setLooping(true)
--core.bgm:play()
end
function gameStates.core.draw()
love.graphics.setBackgroundColor(0, 0, 0)
if core.state == 1 then
love.graphics.setScreen('top')
love.graphics.setColor(255, 255, 255, core.opacity)
love.graphics.setDepth(4)
love.graphics.draw(core.image, core.x, core.y)
love.graphics.setColor(255, 255, 255, 255)
love.graphics.setDepth(1.5)
love.graphics.draw(cliff.image, cliff.x, cliff.y)
love.graphics.setDepth(1)
love.graphics.draw(frisk.image, frisk.x, frisk.y)
end
end
function gameStates.core.update(gt)
if core.state == 1 then
core.fade = core.fade + gt
core.opacity = 170 + 85 * math.sin(0.5 * core.fade)
else
core.state = 1
end
if love.keyboard.isDown("b") then
gameState = 'menu'
love.audio.stop()
core.quit()
end
end
|
local t = require( "taptest" )
local marry = require( "marry" )
local same = require( "same" )
local keys = { "even", "odd", "name" }
local values = { 2, 3, "pierrot" }
t( same( marry( keys, values ), { even=2, odd=3, name="pierrot" } ), true )
t()
|
local super = Class("XMLLoader", LuaObject).getSuperclass()
function XMLLoader:init(xmlPath, rootContainer, controller)
super.init(self)
self.xmlPath = xmlPath
self.rootContainer = rootContainer or nil
self.controller = controller or rootContainer
self.scriptEnv = {}
return self
end
function XMLLoader:setRoot(rootContainer)
self.rootContainer = rootContainer
end
function XMLLoader:getRoot()
return self.rootContainer
end
function XMLLoader:setController(controller)
self.controller = controller
end
function XMLLoader:getController()
return self.controller
end
function XMLLoader:load()
local xmlRootNode = xmlLoadFile(self.xmlPath)
if(xmlRootNode) then
local component = self:loadNode(xmlRootNode, self.rootContainer)
xmlUnloadFile(xmlRootNode)
return component
end
return false
end
function XMLLoader:loadNode(xmlRootNode, parentComponent)
local container = self:parseNode(xmlRootNode, parentComponent)
local childrenNode = xmlFindChild(xmlRootNode, 'children', 0)
if(childrenNode) then
local childrenTable = xmlNodeGetChildren(childrenNode)
for i, xmlNode in ipairs(childrenTable) do
local component = self:loadNode(xmlNode)
if(component) then
container:add(component)
end
end
end
return container
end
function XMLLoader:parseNode(xmlNode, parentComponent)
local nodeName = xmlNodeGetName(xmlNode)
local componentName = string.lower(nodeName)
local layoutX = tonumber(xmlNodeGetAttribute(xmlNode, "layoutX")) or 0
local layoutY = tonumber(xmlNodeGetAttribute(xmlNode, "layoutY")) or 0
local prefWidth = tonumber(xmlNodeGetAttribute(xmlNode, "prefWidth")) or 100
local prefHeight = tonumber(xmlNodeGetAttribute(xmlNode, "prefHeight")) or 20
local text = xmlNodeGetAttribute(xmlNode, "text") or ""
local componentId = xmlNodeGetAttribute(xmlNode, "fx:id") or ""
local styleNode = xmlFindChild(xmlNode, 'style', 0)
if(styleNode) then
self:parseNode(styleNode, parentComponent)
end
local scriptNode = xmlFindChild(xmlNode, 'script', 0)
if(scriptNode) then
self:parseNode(scriptNode, parentComponent)
end
local component = nil
if(componentName == "nop") then
elseif(componentName == "script") then
local code = xmlNodeGetValue(xmlNode)
local chunk = loadstring(code)
if(chunk) then
local selfObject = {}
self.scriptEnv.self = self:getController()
setfenv(chunk, setmetatable(self.scriptEnv, { __index = _G }))
chunk()
--local controller = self:getController()
--setfenv(chunk, _G)
--outputDebugString(self.scriptEnv.teste)
--getfenv(chunk)['handleButtonAction']({})
end
--[[
--------------
var1 = "Hello"
local function one()
local var2 = "world"
local code = "outputChatBox(var1 .. var2)"
chunk = loadstring(code)
local locals = { var2 = var2, }
setfenv(chunk, setmetatable(locals, { __index = _G }))
chunk()
end
one()
]]
elseif(componentName == "style") then
local css = xmlNodeGetValue(xmlNode)
Graphics.getInstance():setStylesheet(StylesheetParser():parsestr(css))
elseif(componentName == "anchorpane") then
component = parentComponent
elseif(componentName == "pane") then
component = Panel()
local foreground = xmlNodeGetAttribute(xmlNode, "foreground")
if foreground then component:setForeground(tocolor(getColorFromString(foreground))) end
local background = xmlNodeGetAttribute(xmlNode, "background")
if background then component:setBackground(tocolor(getColorFromString(background))) end
elseif(componentName == "label") then
component = Label()
component:setText(text)
component:setForeground(tocolor(getColorFromString(xmlNodeGetAttribute(xmlNode, "textFill"))))
component:setBackground(tocolor(0,0,0,0))
elseif(componentName == "button") then
component = Button(text)
component:setActionCommand(componentId)
local locator, handlerName = XMLLoader.getHandler(xmlNodeGetAttribute(xmlNode, "onAction"))
if(locator == "controller") then
local controller = self:getController()
local handler = controller[handlerName]
component:addActionListener({
actionPerformed = function(e)
handler(controller, e)
end
})
else
local controller = self:getController()
local handler = self.scriptEnv[handlerName]
component:addActionListener({
actionPerformed = function(e)
handler(e)
end
})
end
elseif(componentName == "textfield") then
component = TextField()
component:setText(text)
elseif(componentName == "passwordfield") then
component = PasswordField()
component:setText(text)
end
if(component) then
if(componentId) then
component:setId(componentId)
self.scriptEnv.self[componentId] = component
end
--component:setForeground(tocolor(math.random(255),math.random(255),math.random(255)))
--component:setBackground(tocolor(math.random(255),math.random(255),math.random(255)))
component:setBounds(layoutX, layoutY, prefWidth, prefHeight)
end
return component
end
function XMLLoader.getHandler(text)
local locator = string.sub(text, 1, 1)
if(locator == "#") then
return "controller", string.sub(text, 2)
else
return "default", string.sub(text, 1)
end
end
|
local red_envelope_reciever_swf_info =
{
["fps"] = 24,
["fnum"] = 48,
["width"] = 100,
["height"] = 130,
["frames"] =
{
{{1,2,1,79,101,},{2,1,2,{0.9468,0,0,0.9468,13.7514,21.0866,},0,0,0,},{1,4,2,67,84,},{2,2,4,{1.1783,0,0,1.1783,10.977,19.4614,},0,0,0,},{1,5,3,34.3,34.3,},{2,3,5,{1,0,0,1,33.55,44.6,},0,5,0,},{1,7,4,16,16,},{2,6,7,{0.0446,0,0,0.0446,66.1432,106.0932,},0,0,0,},{2,8,7,{0.3839,0,0,0.3839,20.4288,76.7288,},0,0,0,},},
{{2,2,0,{1.1997,0,0,1.1997,10.2601,18.6126,},{1,1,1,0.9375,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,4,4,0,0,},0,0,},{2,6,0,{0.4268,0,0,0.4268,63.0856,98.9856,},0,0,0,},{2,8,0,{0.7276,0,0,0.7276,17.6792,70.3292,},0,0,0,},},
{{2,2,0,{1.221,0,0,1.221,9.5465,17.818,},{1,1,1,0.875,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,8,8,0,0,},0,0,},{2,6,0,{0.809,0,0,0.809,60.028,91.878,},0,0,0,},{2,8,0,{1.0714,0,0,1.0714,14.9288,63.9288,},0,0,0,},},
{{2,2,0,{1.2421,0,0,1.2421,8.8397,16.9818,},{1,1,1,0.8125,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,11,12,0,0,},0,0,},{1,8,5,7.9,29.9,},{2,4,8,{1.0352,-0.7926,1.3643,1.7817,4.9147,48.6944,},{1,1,1,1,11,12,0,0,},0,0,},{2,6,0,{1.1913,0,0,1.1913,56.9696,84.7196,},0,0,0,},{2,8,0,{1.4151,0,0,1.4151,12.1792,57.5292,},0,0,0,},},
{{2,2,0,{1.2632,0,0,1.2632,8.1328,16.1456,},{1,1,1,0.75,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,15,16,0,0,},0,0,},{2,4,0,{1.0405,-0.7946,1.3711,1.7955,6.2921,47.8959,},{1,1,1,1,15,16,0,0,},0,0,},{2,6,0,{1.5735,0,0,1.5735,53.912,77.612,},0,0,0,},{2,8,0,{1.0714,0,0,1.0714,14.9288,56.6288,},0,0,0,},},
{{2,2,0,{1.2843,0,0,1.2843,7.426,15.3094,},{1,1,1,0.6875,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,19,20,0,0,},0,0,},{2,4,0,{1.0464,-0.799,1.3824,1.8104,7.5498,47.0906,},{1,1,1,1,19,20,0,0,},0,0,},{2,6,0,{1.1913,0,0,1.1913,56.9696,76.6196,},0,0,0,},{2,8,0,{0.7276,0,0,0.7276,17.6792,55.7292,},0,0,0,},},
{{2,2,0,{1.3052,0,0,1.3052,6.7258,14.5316,},{1,1,1,0.625,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,23,24,0,0,},0,0,},{2,4,0,{1.0523,-0.8035,1.3937,1.8252,8.9076,46.2871,},{1,1,1,1,23,24,0,0,},0,0,},{2,6,0,{0.8091,0,0,0.8091,60.0272,75.6272,},0,0,0,},{2,8,0,{0.3839,0,0,0.3839,20.4288,54.8288,},0,0,0,},},
{{2,2,0,{1.3261,0,0,1.3261,6.0256,13.7038,},{1,1,1,0.5625,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,26,28,0,0,},0,0,},{2,4,0,{1.0582,-0.808,1.4049,1.8401,10.1669,45.4821,},{1,1,1,1,26,28,0,0,},0,0,},{2,6,0,{0.4268,0,0,0.4268,63.0856,74.6356,},0,0,0,},{2,8,0,{0.0401,0,0,0.0401,23.1792,53.9792,},0,0,0,},},
{{2,2,0,{1.3469,0,0,1.3469,5.3289,12.8802,},{1,1,1,0.5,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,30,32,0,0,},0,0,},{2,4,0,{1.0642,-0.8124,1.4162,1.8549,11.4742,44.7282,},{1,1,1,1,30,32,0,0,},0,0,},{2,6,0,{0.0446,0,0,0.0446,66.1432,73.6432,},0,0,0,},{2,8,0,{0.0401,0,0,0.0401,23.1792,50.3292,},0,0,0,},},
{{2,2,0,{1.3526,0,0,1.3526,5.1379,12.6908,},{1,1,1,0.4453,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,34,36,0,0,},0,0,},{2,4,0,{1.0701,-0.8169,1.4275,1.8698,12.882,43.9732,},{1,1,1,1,34,36,0,0,},0,0,},{2,6,0,{0.0446,0,0,0.0446,66.1432,69.5932,},0,0,0,},{2,7,7,{0.0401,0,0,0.0401,28.4292,110.9792,},0,0,0,},{2,8,0,{0.3839,0,0,0.3839,20.4288,43.9288,},0,0,0,},},
{{2,2,0,{1.3584,0,0,1.3584,4.9436,12.3972,},{1,1,1,0.3906,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,38,40,0,0,},0,0,},{2,4,0,{1.076,-0.8215,1.4388,1.8846,14.1397,43.1702,},{1,1,1,1,38,40,0,0,},0,0,},{2,6,0,{0.4268,0,0,0.4268,63.0856,62.4356,},0,0,0,},{2,7,0,{0.3839,0,0,0.3839,25.6788,104.6288,},0,0,0,},{2,8,0,{0.7276,0,0,0.7276,17.6792,37.5292,},0,0,0,},},
{{2,2,0,{1.364,0,0,1.364,4.756,12.162,},{1,1,1,0.332,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,41,44,0,0,},0,0,},{2,4,0,{1.0819,-0.8259,1.45,1.8995,15.449,42.3648,},{1,1,1,1,41,44,0,0,},0,0,},{2,6,0,{0.809,0,0,0.809,60.028,55.328,},0,0,0,},{2,7,0,{0.7276,0,0,0.7276,22.9292,98.2292,},0,0,0,},{2,8,0,{1.0714,0,0,1.0714,14.9288,31.1288,},0,0,0,},},
{{2,2,0,{1.3696,0,0,1.3696,4.5684,11.9768,},{1,1,1,0.2773,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,45,48,0,0,},0,0,},{2,4,0,{1.0879,-0.8304,1.4613,1.9144,16.8064,41.6098,},{1,1,1,1,45,48,0,0,},0,0,},{2,6,0,{1.1913,0,0,1.1913,56.9696,48.2196,},0,0,0,},{2,7,0,{1.0714,0,0,1.0714,20.1788,91.8288,},0,0,0,},{2,8,0,{1.4151,0,0,1.4151,12.1792,24.7292,},0,0,0,},},
{{2,2,0,{1.3753,0,0,1.3753,4.3774,11.6874,},{1,1,1,0.2227,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,49,52,0,0,},0,0,},{2,4,0,{1.0938,-0.8349,1.4726,1.9293,18.1141,40.7548,},{1,1,1,1,49,52,0,0,},0,0,},{2,6,0,{1.5735,0,0,1.5735,53.912,41.112,},0,0,0,},{2,7,0,{1.4151,0,0,1.4151,17.4292,85.4292,},0,0,0,},{2,8,0,{1.0714,0,0,1.0714,14.9288,23.8288,},0,0,0,},},
{{2,2,0,{1.3808,0,0,1.3808,4.1932,11.4564,},{1,1,1,0.168,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,53,56,0,0,},0,0,},{2,4,0,{1.0997,-0.8394,1.4839,1.9441,19.3719,40.0013,},{1,1,1,1,53,56,0,0,},0,0,},{2,6,0,{1.1913,0,0,1.1913,56.9696,40.1196,},0,0,0,},{2,7,0,{1.0714,0,0,1.0714,20.1788,84.5288,},0,0,0,},{2,8,0,{0.7276,0,0,0.7276,17.6792,22.9292,},0,0,0,},},
{{3,8,},{2,2,0,{1.3864,0,0,1.3864,4.0056,11.2712,},{1,1,1,0.1094,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,56,60,0,0,},0,0,},{2,4,0,{1.1056,-0.8439,1.4951,1.959,20.7311,39.1964,},{1,1,1,1,56,60,0,0,},0,0,},{2,6,0,{0.8091,0,0,0.8091,60.0272,39.1272,},0,0,0,},{2,7,0,{0.7276,0,0,0.7276,22.9292,83.6292,},0,0,0,},},
{{2,2,0,{1.3919,0,0,1.3919,3.8214,10.9902,},{1,1,1,0.0547,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,60,64,0,0,},0,0,},{2,4,0,{1.1116,-0.8483,1.5064,1.9738,22.0385,38.4425,},{1,1,1,1,60,64,0,0,},0,0,},{2,6,0,{0.4268,0,0,0.4268,63.0856,38.0856,},0,0,0,},{2,7,0,{0.3839,0,0,0.3839,25.6788,82.7288,},0,0,0,},},
{{2,2,0,{1.407,0,0,1.407,3.3155,10.356,},{1,1,1,0,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,56,60,0,0,},0,0,},{2,4,0,{1.1175,-0.8528,1.5177,1.9887,23.2963,37.6875,},{1,1,1,1,56,60,0,0,},0,0,},{2,6,0,{0.0446,0,0,0.0446,66.1432,37.0932,},0,0,0,},{2,7,0,{0.0401,0,0,0.0401,28.4292,81.8292,},0,0,0,},},
{{3,2,},{2,3,0,0,{1,1,1,1,53,56,0,0,},0,0,},{2,4,0,{1.1249,-0.859,1.532,2.0063,24.6532,36.8489,},{1,1,1,1,53,56,0,0,},0,0,},{2,6,0,{0.0446,0,0,0.0446,66.1432,33.0432,},0,0,0,},{2,7,0,{0.0401,0,0,0.0401,28.4292,78.1792,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,2,1,0,0,},0,0,},{2,3,0,0,{1,1,1,1,49,53,0,0,},0,0,},{2,4,0,{1.0998,-0.8394,1.557,2.0401,25.6786,34.8661,},{1,1,1,1,49,53,0,0,},0,0,},{2,6,0,{0.4268,0,0,0.4268,63.0856,25.9356,},0,0,0,},{2,7,0,{0.3839,0,0,0.3839,25.6788,71.7788,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,4,3,0,0,},0,0,},{2,3,0,0,{1,1,1,1,46,49,0,0,},0,0,},{2,4,0,{1.0763,-0.8214,1.5849,2.0767,26.5544,32.7479,},{1,1,1,1,46,49,0,0,},0,0,},{2,6,0,{0.809,0,0,0.809,60.028,18.828,},0,0,0,},{2,7,0,{0.7276,0,0,0.7276,22.9292,65.3792,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,5,4,0,0,},0,0,},{2,3,0,0,{1,1,1,1,42,45,0,0,},0,0,},{2,4,0,{1.0527,-0.8035,1.6129,2.1133,27.429,30.63,},{1,1,1,1,42,45,0,0,},0,0,},{2,6,0,{1.1913,0,0,1.1913,56.9696,11.7196,},0,0,0,},{2,7,0,{1.0714,0,0,1.0714,20.1788,58.9788,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,7,6,0,0,},0,0,},{2,3,0,0,{1,1,1,1,39,41,0,0,},0,0,},{2,4,0,{1.0291,-0.7855,1.641,2.1499,28.4021,28.4617,},{1,1,1,1,39,41,0,0,},0,0,},{2,6,0,{1.5735,0,0,1.5735,53.912,4.562,},0,0,0,},{2,7,0,{1.4151,0,0,1.4151,17.4292,52.5792,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,9,7,0,0,},0,0,},{2,3,0,0,{1,1,1,1,35,38,0,0,},0,0,},{2,4,0,{1.0056,-0.7675,1.669,2.1865,29.3263,26.4935,},{1,1,1,1,35,38,0,0,},0,0,},{2,6,0,{1.1913,0,0,1.1913,56.9696,3.5696,},0,0,0,},{2,7,0,{1.0714,0,0,1.0714,20.1788,51.6788,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,11,9,0,0,},0,0,},{2,3,0,0,{1,1,1,1,32,34,0,0,},0,0,},{2,4,0,{0.982,-0.7496,1.697,2.2231,30.151,24.3756,},{1,1,1,1,32,34,0,0,},0,0,},{2,6,0,{0.8091,0,0,0.8091,60.0272,2.5772,},0,0,0,},{2,7,0,{0.7276,0,0,0.7276,22.9292,50.7792,},0,0,0,},},
{{3,6,},{2,1,0,0,{1,1,1,1,13,10,0,0,},0,0,},{2,3,0,0,{1,1,1,1,28,30,0,0,},0,0,},{2,4,0,{0.9584,-0.7316,1.725,2.2597,31.1256,22.3073,},{1,1,1,1,28,30,0,0,},0,0,},{2,7,0,{0.3839,0,0,0.3839,25.6788,49.8788,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,15,12,0,0,},0,0,},{2,3,0,0,{1,1,1,1,25,26,0,0,},0,0,},{2,4,0,{0.9349,-0.7137,1.753,2.2963,32.0498,20.1894,},{1,1,1,1,25,26,0,0,},0,0,},{2,7,0,{0.0401,0,0,0.0401,28.4292,48.9792,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,16,13,0,0,},0,0,},{2,2,4,{1.1783,0,0,1.1783,10.977,19.4614,},0,0,0,},{2,3,0,0,{1,1,1,1,21,23,0,0,},0,0,},{2,4,0,{0.9113,-0.6957,1.781,2.3329,32.8744,18.0712,},{1,1,1,1,21,23,0,0,},0,0,},{2,7,0,{0.0401,0,0,0.0401,28.4292,45.3292,},0,0,0,},{2,8,7,{0.047,0,0,0.047,19.974,128.024,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,18,15,0,0,},0,0,},{2,2,0,{1.1997,0,0,1.1997,10.2601,18.6126,},{1,1,1,0.9375,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,18,19,0,0,},0,0,},{2,4,0,{0.8877,-0.6778,1.809,2.3694,33.849,16.0548,},{1,1,1,1,18,19,0,0,},0,0,},{2,7,0,{0.3839,0,0,0.3839,25.6788,38.9288,},0,0,0,},{2,8,0,{0.4499,0,0,0.4499,16.7508,119.4008,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,20,16,0,0,},0,0,},{2,2,0,{1.221,0,0,1.221,9.5465,17.818,},{1,1,1,0.875,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,14,15,0,0,},0,0,},{2,4,0,{0.8641,-0.6598,1.8371,2.406,34.7722,13.8865,},{1,1,1,1,14,15,0,0,},0,0,},{2,7,0,{0.7276,0,0,0.7276,22.9292,32.5292,},0,0,0,},{2,8,0,{0.8528,0,0,0.8528,13.5276,110.7776,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,18,15,0,0,},0,0,},{2,2,0,{1.2421,0,0,1.2421,8.8397,16.9818,},{1,1,1,0.8125,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,11,11,0,0,},0,0,},{2,4,0,{0.8406,-0.6419,1.8651,2.4426,35.6964,11.8186,},{1,1,1,1,11,11,0,0,},0,0,},{2,7,0,{1.0714,0,0,1.0714,20.1788,26.1288,},0,0,0,},{2,8,0,{1.2556,0,0,1.2556,10.3052,102.1552,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,16,13,0,0,},0,0,},{2,2,0,{1.2632,0,0,1.2632,8.1328,16.1456,},{1,1,1,0.75,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,7,8,0,0,},0,0,},{2,4,0,{0.817,-0.6239,1.8931,2.4791,36.521,9.7519,},{1,1,1,1,7,8,0,0,},0,0,},{2,7,0,{1.4151,0,0,1.4151,17.4292,19.7292,},0,0,0,},{2,8,0,{1.6585,0,0,1.6585,7.082,93.532,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,15,12,0,0,},0,0,},{2,2,0,{1.2843,0,0,1.2843,7.426,15.3094,},{1,1,1,0.6875,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,4,4,0,0,},0,0,},{2,4,0,{0.794,-0.6079,1.9275,2.5173,37.3476,7.6176,},{1,1,1,1,4,4,0,0,},0,0,},{2,7,0,{1.0714,0,0,1.0714,20.1788,18.8288,},0,0,0,},{2,8,0,{1.2557,0,0,1.2557,10.3044,91.3044,},0,0,0,},},
{{3,4,},{2,1,0,0,{1,1,1,1,13,10,0,0,},0,0,},{2,2,0,{1.3052,0,0,1.3052,6.7258,14.5316,},{1,1,1,0.625,0,0,0,0,},0,0,},{2,3,0,0,{1,1,1,1,0,0,0,0,},0,0,},{2,7,0,{0.7276,0,0,0.7276,22.9292,17.8792,},0,0,0,},{2,8,0,{0.8528,0,0,0.8528,13.5276,89.1276,},0,0,0,},},
{{3,7,},{2,1,0,0,{1,1,1,1,11,9,0,0,},0,0,},{2,2,0,{1.3261,0,0,1.3261,6.0256,13.7038,},{1,1,1,0.5625,0,0,0,0,},0,0,},{2,8,0,{0.4499,0,0,0.4499,16.7508,86.9508,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,9,7,0,0,},0,0,},{2,2,0,{1.3469,0,0,1.3469,5.3289,12.8802,},{1,1,1,0.5,0,0,0,0,},0,0,},{2,8,0,{0.047,0,0,0.047,19.974,84.774,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,7,6,0,0,},0,0,},{2,2,0,{1.3526,0,0,1.3526,5.1379,12.6908,},{1,1,1,0.4453,0,0,0,0,},0,0,},{2,8,0,{0.047,0,0,0.047,19.974,79.374,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,5,4,0,0,},0,0,},{2,2,0,{1.3584,0,0,1.3584,4.9436,12.3972,},{1,1,1,0.3906,0,0,0,0,},0,0,},{2,8,0,{0.4499,0,0,0.4499,16.7508,70.7508,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,4,3,0,0,},0,0,},{2,2,0,{1.364,0,0,1.364,4.756,12.162,},{1,1,1,0.332,0,0,0,0,},0,0,},{2,6,7,{0.0401,0,0,0.0401,47.9292,112.4292,},0,0,0,},{2,8,0,{0.8528,0,0,0.8528,13.5276,62.1276,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,2,1,0,0,},0,0,},{2,2,0,{1.3696,0,0,1.3696,4.5684,11.9768,},{1,1,1,0.2773,0,0,0,0,},0,0,},{2,6,0,{0.3839,0,0,0.3839,45.1788,108.4288,},0,0,0,},{2,8,0,{1.2556,0,0,1.2556,10.3052,53.5052,},0,0,0,},},
{{2,1,0,0,{1,1,1,1,0,0,0,0,},0,0,},{2,2,0,{1.3753,0,0,1.3753,4.3774,11.6874,},{1,1,1,0.2227,0,0,0,0,},0,0,},{2,6,0,{0.7276,0,0,0.7276,42.4292,104.4292,},0,0,0,},{2,8,0,{1.6585,0,0,1.6585,7.082,44.882,},0,0,0,},},
{{2,2,0,{1.3808,0,0,1.3808,4.1932,11.4564,},{1,1,1,0.168,0,0,0,0,},0,0,},{2,6,0,{1.0714,0,0,1.0714,39.6788,100.4288,},0,0,0,},{2,8,0,{1.2557,0,0,1.2557,10.3044,42.7044,},0,0,0,},},
{{2,2,0,{1.3864,0,0,1.3864,4.0056,11.2712,},{1,1,1,0.1094,0,0,0,0,},0,0,},{2,6,0,{1.4151,0,0,1.4151,36.9292,96.4292,},0,0,0,},{2,8,0,{0.8528,0,0,0.8528,13.5276,40.4776,},0,0,0,},},
{{2,2,0,{1.3919,0,0,1.3919,3.8214,10.9902,},{1,1,1,0.0547,0,0,0,0,},0,0,},{2,6,0,{1.0714,0,0,1.0714,39.6788,97.9288,},0,0,0,},{2,8,0,{0.4499,0,0,0.4499,16.7508,38.3008,},0,0,0,},},
{{2,2,0,{1.407,0,0,1.407,3.3155,10.356,},{1,1,1,0,0,0,0,0,},0,0,},{2,6,0,{0.7276,0,0,0.7276,42.4292,99.4292,},0,0,0,},{2,8,0,{0.047,0,0,0.047,19.974,36.124,},0,0,0,},},
{{3,2,},{2,6,0,{0.3839,0,0,0.3839,45.1788,100.9288,},0,0,0,},{2,8,0,{0.047,0,0,0.047,19.974,30.724,},0,0,0,},},
{{2,6,0,{0.0401,0,0,0.0401,47.9292,102.4292,},0,0,0,},{2,8,0,{0.8528,0,0,0.8528,13.5276,18.8776,},0,0,0,},},
{{3,6,},{3,8,},},
},
["imagePinMapName"] = "red_envelope_reciever_swf_pin_map",
["imageName"] = "red_envelope_reciever",
["images"] =
{
[1] = 1,
[2] = 2,
[3] = 3,
[4] = 4,
[5] = 5,
},
}
return red_envelope_reciever_swf_info
|
local Lib = require('library')
-- Run comand hooks
local function runHookCmds(cmds, hook_name)
if not Lib.isEmptyTable(cmds) then
for _,cmd in ipairs(cmds) do
Lib.logger.debug(string.format("Running %s command: %s", hook_name, cmd))
local success, result = pcall(vim.cmd, cmd)
if not success then Lib.logger.error(string.format("Error running %s. error: %s", cmd, result)) end
end
end
end
----------- Setup ----------
local Config = {}
local AutoSession = {
conf = {}
}
local defaultConf = {
logLevel = vim.g["auto_session_log_level"] or AutoSession.conf.logLevel or 'info'
}
-- Set default config on plugin load
AutoSession.conf = defaultConf
Lib.conf = {
logLevel = AutoSession.conf.logLevel
}
function AutoSession.setup(config)
AutoSession.conf = Config.normalize(config)
Lib.setup({
logLevel = AutoSession.conf.logLevel
})
end
------ MAIN FUNCTIONS ------
-- This function avoids calling SaveSession automatically when argv is not nil.
function AutoSession.AutoSaveSession(sessions_dir)
if next(vim.fn.argv()) == nil then
AutoSession.SaveSession(sessions_dir, true)
end
end
function AutoSession.getRootDir()
if AutoSession.valiated then
return AutoSession.conf.root_dir
end
local root_dir = vim.g["auto_session_root_dir"] or AutoSession.conf.root_dir or Lib.ROOT_DIR
Lib.initRootDir(root_dir)
AutoSession.conf.root_dir = Lib.validateRootDir(root_dir)
AutoSession.validated = true
return root_dir
end
function AutoSession.getCmds(typ)
return AutoSession.conf[typ.."_cmds"] or vim.g["auto_session_"..typ.."_cmds"]
end
-- Saves the session, overriding if previously existing.
function AutoSession.SaveSession(sessions_dir, auto)
if Lib.isEmpty(sessions_dir) then
sessions_dir = AutoSession.getRootDir()
else
sessions_dir = Lib.appendSlash(sessions_dir)
end
local pre_cmds = AutoSession.getCmds("pre_save")
runHookCmds(pre_cmds, "pre-save")
local session_name = Lib.getEscapedSessionNameFromCwd()
local full_path = string.format(sessions_dir.."%s.vim", session_name)
local cmd = "mks! "..full_path
if auto then
Lib.logger.debug("Session saved at "..full_path)
else
Lib.logger.info("Session saved at "..full_path)
end
vim.cmd(cmd)
local post_cmds = AutoSession.getCmds("post_save")
runHookCmds(post_cmds, "post-save")
end
-- This function avoids calling RestoreSession automatically when argv is not nil.
function AutoSession.AutoRestoreSession(sessions_dir)
if next(vim.fn.argv()) == nil then
AutoSession.RestoreSession(sessions_dir)
end
end
-- TODO: make this more readable!
-- Restores the session by sourcing the session file if it exists/is readable.
function AutoSession.RestoreSession(sessions_dir_or_file)
Lib.logger.debug("sessions dir or file", sessions_dir_or_file)
local sessions_dir = nil
local session_file = nil
if Lib.isEmpty(sessions_dir_or_file) then
sessions_dir = AutoSession.getRootDir()
elseif vim.fn.isdirectory(vim.fn.expand(sessions_dir_or_file)) == Lib._VIM_TRUE then
sessions_dir = Lib.appendSlash(sessions_dir_or_file)
else
session_file = sessions_dir_or_file
end
local restore = function(file_path)
local pre_cmds = AutoSession.getCmds("pre_restore")
runHookCmds(pre_cmds, "pre-restore")
local cmd = "source "..file_path
vim.cmd(cmd)
Lib.logger.info("Session restored from "..file_path)
local post_cmds = AutoSession.getCmds("post_restore")
runHookCmds(post_cmds, "post-restore")
end
if sessions_dir then
Lib.logger.debug("==== Using session DIR")
local session_name = Lib.getEscapedSessionNameFromCwd()
local session_file_path = string.format(sessions_dir.."%s.vim", session_name)
local legacy_session_name = Lib.getLegacySessionNameFromCmd()
local legacy_file_path = string.format(sessions_dir.."%s.vim", legacy_session_name)
if Lib.isReadable(session_file_path) then
restore(session_file_path)
elseif Lib.isReadable(legacy_file_path) then
restore(legacy_file_path)
else
Lib.logger.debug("File not readable, not restoring session")
end
elseif session_file then
Lib.logger.debug("==== Using session FILE")
local escaped_file = session_file:gsub("%%", "\\%%")
if Lib.isReadable(escaped_file) then
Lib.logger.debug("isReadable, calling restore")
restore(escaped_file)
else
Lib.logger.debug("File not readable, not restoring session")
end
else
Lib.logger.error("Error while trying to parse session dir or file")
end
end
return AutoSession
|
local K, C, L = unpack(KkthnxUI)
local Module = K:GetModule("Miscellaneous")
local _G = _G
local wipe, select, pairs = _G.wipe, _G.select, _G.pairs
local ATTACHMENTS_MAX_RECEIVE, ERR_MAIL_DELETE_ITEM_ERROR = _G.ATTACHMENTS_MAX_RECEIVE, _G.ERR_MAIL_DELETE_ITEM_ERROR
local C_Mail_HasInboxMoney = _G.C_Mail.HasInboxMoney
local C_Mail_IsCommandPending = _G.C_Mail.IsCommandPending
local C_Timer_After = _G.C_Timer.After
local GetInboxNumItems, GetInboxHeaderInfo, GetInboxItem, GetItemInfo = _G.GetInboxNumItems, _G.GetInboxHeaderInfo, _G.GetInboxItem, _G.GetItemInfo
local GetSendMailPrice, GetMoney = _G.GetSendMailPrice, _G.GetMoney
local InboxItemCanDelete, DeleteInboxItem, TakeInboxMoney, TakeInboxItem = _G.InboxItemCanDelete, _G.DeleteInboxItem, _G.TakeInboxMoney, _G.TakeInboxItem
local NORMAL_STRING = _G.GUILDCONTROL_OPTION16
local OPENING_STRING = _G.OPEN_ALL_MAIL_BUTTON_OPENING
local mailIndex, timeToWait, totalCash, inboxItems = 0, 0.15, 0, {}
local isGoldCollecting
function Module:MailBox_DelectClick()
local selectedID = self.id + (InboxFrame.pageNum - 1) * 7
if InboxItemCanDelete(selectedID) then
DeleteInboxItem(selectedID)
else
UIErrorsFrame:AddMessage(K.InfoColor .. ERR_MAIL_DELETE_ITEM_ERROR)
end
end
function Module:MailItem_AddDelete(i)
local bu = CreateFrame("Button", nil, self)
bu:SetPoint("BOTTOMRIGHT", self:GetParent(), "BOTTOMRIGHT", -10, 5)
bu:SetSize(16, 16)
bu.id = i
bu:SetScript("OnClick", Module.MailBox_DelectClick)
K.AddTooltip(bu, "ANCHOR_RIGHT", DELETE, "system")
end
function Module:InboxItem_OnEnter()
if not self.index then -- may receive fake mails from Narcissus
return
end
wipe(inboxItems)
local itemAttached = select(8, GetInboxHeaderInfo(self.index))
if itemAttached then
for attachID = 1, 12 do
local _, itemID, _, itemCount = GetInboxItem(self.index, attachID)
if itemCount and itemCount > 0 then
inboxItems[itemID] = (inboxItems[itemID] or 0) + itemCount
end
end
if itemAttached > 1 then
GameTooltip:AddLine(L["Attach List"])
for itemID, count in pairs(inboxItems) do
local itemName, _, itemQuality, _, _, _, _, _, _, itemTexture = GetItemInfo(itemID)
if itemName then
local r, g, b = GetItemQualityColor(itemQuality)
GameTooltip:AddDoubleLine(" |T" .. itemTexture .. ":12:12:0:0:50:50:4:46:4:46|t " .. itemName, count, r, g, b)
end
end
GameTooltip:Show()
end
end
end
function Module:MailBox_CollectGold()
if mailIndex > 0 then
if not C_Mail_IsCommandPending() then
if C_Mail_HasInboxMoney(mailIndex) then
TakeInboxMoney(mailIndex)
end
mailIndex = mailIndex - 1
end
C_Timer_After(timeToWait, Module.MailBox_CollectGold)
else
isGoldCollecting = false
Module:UpdateOpeningText()
end
end
function Module:MailBox_CollectAllGold()
if isGoldCollecting then
return
end
if totalCash == 0 then
return
end
isGoldCollecting = true
mailIndex = GetInboxNumItems()
Module:UpdateOpeningText(true)
Module:MailBox_CollectGold()
end
function Module:TotalCash_OnEnter()
local numItems = GetInboxNumItems()
if numItems == 0 then
return
end
for i = 1, numItems do
totalCash = totalCash + select(5, GetInboxHeaderInfo(i))
end
if totalCash > 0 then
GameTooltip:SetOwner(self, "ANCHOR_RIGHT")
GameTooltip:AddLine(L["Total Gold"])
GameTooltip:AddLine(" ")
GameTooltip:AddLine(K.FormatMoney(totalCash, true), 1, 1, 1)
GameTooltip:Show()
end
end
function Module:TotalCash_OnLeave()
K:HideTooltip()
totalCash = 0
end
function Module:UpdateOpeningText(opening)
if opening then
Module.GoldButton:SetText(OPENING_STRING)
else
Module.GoldButton:SetText(NORMAL_STRING)
end
end
function Module:MailBox_CreatButton(parent, width, height, text, anchor)
local button = CreateFrame("Button", nil, parent, "UIPanelButtonTemplate")
button:SetSize(width, height)
button:SetPoint(unpack(anchor))
button:SetText(text)
return button
end
function Module:CollectGoldButton()
OpenAllMail:ClearAllPoints()
OpenAllMail:SetPoint("TOPLEFT", InboxFrame, "TOPLEFT", 70, -28)
local button = Module:MailBox_CreatButton(InboxFrame, 120, 24, "", { "LEFT", OpenAllMail, "RIGHT", 3, 0 })
button:SetScript("OnClick", Module.MailBox_CollectAllGold)
button:SetScript("OnEnter", Module.TotalCash_OnEnter)
button:SetScript("OnLeave", Module.TotalCash_OnLeave)
Module.GoldButton = button
Module:UpdateOpeningText()
end
function Module:MailBox_CollectAttachment()
for i = 1, ATTACHMENTS_MAX_RECEIVE do
local attachmentButton = OpenMailFrame.OpenMailAttachments[i]
if attachmentButton:IsShown() then
TakeInboxItem(InboxFrame.openMailID, i)
C_Timer_After(timeToWait, Module.MailBox_CollectAttachment)
return
end
end
end
function Module:MailBox_CollectCurrent()
if OpenMailFrame.cod then
UIErrorsFrame:AddMessage(K.InfoColor .. L["Mail Is COD"])
return
end
local currentID = InboxFrame.openMailID
if C_Mail_HasInboxMoney(currentID) then
TakeInboxMoney(currentID)
end
Module:MailBox_CollectAttachment()
end
function Module:CollectCurrentButton()
local button = Module:MailBox_CreatButton(OpenMailFrame, 82, 22, L["Take All"], { "RIGHT", "OpenMailReplyButton", "LEFT", -1, 0 })
button:SetScript("OnClick", Module.MailBox_CollectCurrent)
end
function Module:ArrangeDefaultElements()
InboxTooMuchMail:ClearAllPoints()
InboxTooMuchMail:SetPoint("BOTTOM", MailFrame, "TOP", 0, 5)
SendMailNameEditBox:SetWidth(155)
SendMailNameEditBoxMiddle:SetWidth(146)
SendMailCostMoneyFrame:SetAlpha(0)
SendMailMailButton:HookScript("OnEnter", function(self)
GameTooltip:SetOwner(self, "ANCHOR_TOP")
GameTooltip:ClearLines()
local sendPrice = GetSendMailPrice()
local colorStr = "|cffffffff"
if sendPrice > GetMoney() then
colorStr = "|cffff0000"
end
GameTooltip:AddLine(SEND_MAIL_COST .. colorStr .. K.FormatMoney(sendPrice, true))
GameTooltip:Show()
end)
SendMailMailButton:HookScript("OnLeave", K.HideTooltip)
end
function Module:CreateImprovedMail()
if not C["Misc"].EnhancedMail then
return
end
if IsAddOnLoaded("Postal") then
return
end
-- Delete buttons
for i = 1, 7 do
local itemButton = _G["MailItem" .. i .. "Button"]
Module.MailItem_AddDelete(itemButton, i)
end
-- Tooltips for multi-items
hooksecurefunc("InboxFrameItem_OnEnter", Module.InboxItem_OnEnter)
-- Elements
Module:ArrangeDefaultElements()
Module:CollectGoldButton()
Module:CollectCurrentButton()
end
Module:RegisterMisc("ImprovedMail", Module.CreateImprovedMail)
|
local bytecodes = {}
bytecodes.SCOPE_POLICIES = {
FAIL_ON_COMPLETED = 0x01,
FAIL_ON_TERMINATED = 0x02
}
bytecodes.INSTRUCTIONS = {
SCOPE = 0x00,
RETURN = 0x01,
RETRACE = 0x02,
JUMP = 0x03,
SET_POLICY = 0x10,
CREATE = 0x20,
CREATE_M = 0x21,
SELECT_ALL = 0x22,
SELECT_ALL_M = 0x23,
SELECT_ONE = 0x24,
SELECT_ONE_M = 0x25,
REACT_ALL = 0x26,
REACT_ALL_M = 0x27,
REACT_ONE = 0x28,
REACT_ONE_M = 0x29,
GROUP = 0x2A,
GROUP_M = 0x2B,
REFER = 0x30,
REFLECT = 0x31,
GUARD = 0x40,
DESCRIBE = 0x41,
WRITE = 0x42,
RETRACT = 0x43,
COLLECT = 0x50,
DO = 0x60,
FORK = 0x61,
ASSERT = 0x62,
TRY = 0x63
}
local SCOPE_POLICY_NAMES = {}
for k, v in pairs(bytecodes.SCOPE_POLICIES) do
SCOPE_POLICY_NAMES[v] = k
end
bytecodes.SCOPE_POLICY_NAMES = SCOPE_POLICY_NAMES
local INSTRUCTION_NAMES = {}
for k, v in pairs(bytecodes.INSTRUCTIONS) do
INSTRUCTION_NAMES[v] = k
end
bytecodes.INSTRUCTION_NAMES = INSTRUCTION_NAMES
return bytecodes
|
say("This is the first line!")
say("This is the second!")
say("And this is the last one!")
|
object_tangible_collection_col_force_shui_table_02 = object_tangible_collection_shared_col_force_shui_table_02:new {
gameObjectType = 8211,}
ObjectTemplates:addTemplate(object_tangible_collection_col_force_shui_table_02, "object/tangible/collection/col_force_shui_table_02.iff")
|
-- Tile.lua
local tile = {
x = 0,
y = 0,
name = "",
layer = "middleground",
}
tile.__index = tile
function tile:new( data )
local data = data or {}
local self = setmetatable(data,tile)
if map.level then
if map.level[self.layer] then
map.add(self)
if gamestate == "Game" then
--collider information
end
end
end
end
function tile:update( dt )
if gamestate == "Game" then
if self.onupdate then self.onupate( dt ) end
end
end
function tile:draw()
if gamestate == "Game" then
if self.texture and textures[self.texture] then
love.graphics.draw( textures[self.texture], self.x, self.y )
end
end
end
|
help([[Automake: GNU Standards-compliant Makefile generator - Homepage: http://www.gnu.org/software/automake/automake.html]])
whatis([[Description: Automake: GNU Standards-compliant Makefile generator - Homepage: http://www.gnu.org/software/automake/automake.html]])
local root = "/opt/apps/software/Automake/1.15-foss-2016b"
conflict("Automake")
if not isloaded("foss/2016b") then
load("foss/2016b")
end
if not isloaded("Autoconf/2.69-foss-2016b") then
load("Autoconf/2.69-foss-2016b")
end
prepend_path("ACLOCAL_PATH", pathJoin(root, "share/aclocal"))
prepend_path("MANPATH", pathJoin(root, "share/man"))
prepend_path("PATH", pathJoin(root, "bin"))
setenv("EBROOTAUTOMAKE", root)
setenv("EBVERSIONAUTOMAKE", "1.15")
setenv("EBDEVELAUTOMAKE", pathJoin(root, "easybuild/Automake-1.15-foss-2016b-easybuild-devel"))
-- Built with EasyBuild version 3.1.0
|
local cb = require("CppBuild")
local print_c = require("../IO")
os.chdir(_WORKING_DIR)
-- Require function success:
function requireSuccess(func)
local status, info = pcall(func)
if not status then
printf("\tError: %s", info)
return false
end
return true
end
-- Parse args
function parseArgs()
if _ACTION == nil then
error("No action specified.")
return
end
end
-- Main function:
function main()
if not requireSuccess(parseArgs) then
return false
end
-- Initialize global settings:
Packages = cb.PackageManager.new()
-- Load package:
local pkgPath = path.join(_WORKING_DIR, "package")
local project = require(pkgPath)
-- Use `CppBuild.Quick` to handle package
cb.quick.autodetect(project)
end
-- Execute main function:
if not requireSuccess(main) then
return false
end
|
lt.config.short_name = "Sprites Test"
lt.config.design_width = 480
lt.config.design_height = 320
lt.config.world_bottom = -5
lt.config.world_top = 5
lt.config.world_left = -7.5
lt.config.world_right = 7.5
|
{"slots":{"0":{"name":"slot1","type":{"events":[],"methods":[]}},"1":{"name":"slot2","type":{"events":[],"methods":[]}},"2":{"name":"slot3","type":{"events":[],"methods":[]}},"3":{"name":"slot4","type":{"events":[],"methods":[]}},"4":{"name":"slot5","type":{"events":[],"methods":[]}},"5":{"name":"slot6","type":{"events":[],"methods":[]}},"6":{"name":"slot7","type":{"events":[],"methods":[]}},"7":{"name":"slot8","type":{"events":[],"methods":[]}},"8":{"name":"slot9","type":{"events":[],"methods":[]}},"9":{"name":"slot10","type":{"events":[],"methods":[]}},"-1":{"name":"unit","type":{"events":[],"methods":[]}},"-2":{"name":"system","type":{"events":[],"methods":[]}},"-3":{"name":"library","type":{"events":[],"methods":[]}}},"handlers":[{"code":"playerId = unit.getMasterPlayerId()\nplayerName = system.getPlayerName(playerId)\nweightLeave = slot2.getItemsMass()\ntimeLeave = system.getTime()","filter":{"args":[{"variable":"*"}],"signature":"leave(id)","slotKey":"0"},"key":"0"},{"code":"--[[\nslot1: Detector\nslot2: Container\nslot3: Databank\nslot4: Screen\n\n]]--\nsystem.print(\"enter:\"..weightEnter..\" leave:\"..weightLeave)\n\nif weightEnter > weightLeave then \n slot3.setStringValue(timeLeave,\n playerId .. \",\" .. \n playerName .. \",\" .. \n timeEnter.. \",\" .. \n timeLeave .. \",\" .. \n weightEnter .. \",\".. \n weightLeave )\nend\n\nlocal weightItem = 27.19 --export: Put in the weight of the item you want to keep track off\nlocal itemName = \"Items\" --export: Name of the item\n-- function to calculate time from seconds, TODO still need to do date\nfunction SecondsToClock(seconds)\n local seconds = tonumber(seconds)\n\n if seconds <= 0 then\n return \"00:00:00\";\n else \n hours = string.format(\"%02.f\", math.floor(seconds/3600));\n mins = string.format(\"%02.f\", math.floor(seconds/60 - (hours*60)));\n secs = string.format(\"%02.f\", math.floor(seconds - hours*3600 - mins *60));\n return hours..\":\"..mins..\":\"..secs\n end\nend\n\n\n--strip first and last letter from the getKeys(), it returns it as a string but still keeps the brackets\n--array = string.sub(slot1.getKeys(),2,-2)\n\nlist = {}\n--cut the string at the comma and remove bracket from the getKeys\nfor i in string.gmatch(string.sub(slot3.getKeys(),2,-2), \"[^,]+\") do\n table.insert(list, string.sub(i,2,-2))\nend\n\nlists = {}\n-- Cut the 6 things i need from the string out of the databank\nfor i=1, #list do \n lists[i] = {}\n k = slot3.getStringValue(list[i])\n for j in string.gmatch(k, \"[^,]+\") do \n table.insert(lists[i], j)\n end\nend\n\nhtmlTable = \"\"\n\nfor i=1, #lists do\n htmlTable = htmlTable .. \"<tr> <th>\" .. lists[i][1] .. \"</th><th>\" .. lists[i][2] .. \"</th><th>\".. SecondsToClock(string.sub(lists[i][3],6)) .. \" / \" .. SecondsToClock(string.sub(lists[i][4],6)) .. \"</th><th>\".. math.floor(lists[i][5] / weightItem) .. \" / \" .. math.floor(lists[i][6] / weightItem) .. \"</th></tr>\"\t\nend\n\n\nhtml = [[\n<div class=\"bootstrap\">\n<h1 style=\"\n\tfont-size: 30px;\n\">Main header</h1>\n<table \nstyle=\"\n\ttext-align: left;\n\tmargin-top: 30px;\n\tmargin-left: auto;\n\tmargin-right: auto;\n\twidth: 95%;\n\tfont-size: 2em;\n\t\">\n\t</br>\n\t<tr\n\tstyle=\"\n\tcolor:green;\n\tfont-size: 1.5em;\n\t\">\n\t<th>ID</th>\n\t<th>Name</th>\n\t<th>Enter / Left</th>\n\t<th>]].. itemName ..[[</th>\n\t</tr>\n\t]]..htmlTable..[[\n\t</table>\n\t</div>\n]]\n\nslot4.setHTML(html)","filter":{"args":[],"signature":"stop()","slotKey":"-1"},"key":"1"},{"code":"timeEnter = system.getTime()\nweightEnter = slot2.getItemsMass() \nslot4.activate()\n\nunit.hide()","filter":{"args":[],"signature":"start()","slotKey":"-1"},"key":"2"}],"methods":[],"events":[]}
|
-----------------------------------------------------
--name : lib/crunch/24_variable_prefix.lua
--description: crunch module, adds 'local a,b,c="hello", 123456789...' prefix on top of the file
--author : mpmxyz
--github page: https://github.com/mpmxyz/ocprograms
--forum page : none
-----------------------------------------------------
return {
run = function(context, options)
--TODO
end,
}
|
-- =============================================================
-- Copyright Roaming Gamer, LLC. 2008-2017 (All Rights Reserved)
-- =============================================================
-- inmobi_helpers.lua
-- =============================================================
--[[
Includes these functions:
inmobi_helpers.setID( os, adType, id ) - Set an id manually (do before init if at all).
inmobi_helpers.init( [ delay [, logLevel ] ] ) - Initialize ads with optional delay.
inmobi_helpers.loadBanner( params ) - Load banner ad.
inmobi_helpers.loadInterstitial( params ) - Load interstitial ad.
inmobi_helpers.showBanner( [ position [, targetingOptions ] ] ) - Show banner ad.
inmobi_helpers.showInterstitial( [ targetingOptions ] ) - Show interstitial ad.
inmobi_helpers.isLoadedBanner() - Returns true if banner ad is loaded.
inmobi_helpers.isLoadedInterstitial() - Returns true if interstitial ad is loaded.
inmobi_helpers.hide( ) - Hide any showing revMob ad.
inmobi_helpers.testStatus( phase ) - Returns true if phase has been triggered in listener.
inmobi_helpers.clearStatus( phase ) - Clear the flag for the named 'phase'
inmobi_helpers.setPhaseCB( phase [, cb [, once ] ] ) - Provide a special callback to execute when the
listener event 'phase' occurs. If once is set to 'true', the callback is called once then cleared.
--]]
-- =============================================================
-- =============================================================
local inMobi = require( "plugin.inMobi" )
local lastID -- Set 'on show' to simplify call to hide
local debugLevel = 0
local function dPrint( level, ... )
if( level <= debugLevel ) then
print( unpack( arg ) )
end
end
local inmobi_helpers = {}
function inmobi_helpers.setDebugLevel( newLevel )
debugLevel = newLevel or 0
end
-- Place to store phase callback records [see: inmobi_helpers.setPhaseCB()]
--
local phaseCallbacks = {}
-- Special statuses (based on phases and other actions)
--[[
]]
local status = {}
inmobi_helpers.status = status
function inmobi_helpers.testStatus( phase )
return fnn(status[phase], false)
end
function inmobi_helpers.clearStatus( phase )
status[phase] = false
end
-- ==
-- Table of ids, separated by OS and type (banner or interstitial)
-- ==
local ids =
{
android =
{
banner = ANDROID_BANNER_ID,
interstitial = ANDROID_INTERSTITIAL_ID,
},
ios =
{
banner = IOS_BANNER_ID,
interstitial = IOS_INTERSTITIAL_ID,
},
}
-- ==
-- inMobi Listener
-- ==
local function listener( event )
-- Extract base set of useful event details:
local isError = (event.isError == nil) and false or event.isError
local phase = (event.phase == nil) and "unknown" or event.phase
local eType = (event.type == nil) and "unknown" or event.type
local response = (event.name == nil) and "unknown" or event.response
dPrint( 3, "inMobi Listener Event @ ", system.getTimer )
dPrint( 3, 'isError: ' .. tostring( isError ) .. '; phase == "' .. tostring(phase) .. '"; response == "' .. tostring(response) .. '"' )
-- Do something with the above details...
--
if( isError ) then
dPrint( 1, "inMobi is getting errors.")
for k,v in pairs( event ) do
dPrint( 1, k,v)
end
else
-- Note: There may be more phases.
if( phase == "init" ) then
elseif( phase == "loaded" ) then
elseif( phase == "failed" ) then
elseif( phase == "displayed" ) then
elseif( phase == "closed" ) then
else
dPrint( 1, "inMobi is getting a weird event.phase value?! ==> " .. tostring( event.phase ) )
for k,v in pairs( event ) do
dPrint( 1, k,v)
end
end
status[phase or "error"] = true
local cb = phaseCallbacks[phase]
if( cb ) then
cb.cb(event)
if(cb.once) then
phaseCallbacks[phase] = nil
end
end
end
end
-- =============================================================
-- setID( os, adType, id ) - Set an id for a specific OS and ad type
--
-- os - 'android' or 'ios'
-- adType - 'banner', 'interstitial'
-- id - Must be a valid ID
--
-- =============================================================
function inmobi_helpers.setID( os, adType, id )
ids[os][adType] = id
end
-- =============================================================
-- setPhaseCB( phase [, cb [, once]] ) - Set up custom callback/listener
-- to call when the named 'phase' occurs.
--
-- phase - String containing name of phase this callback goes with.
-- cb ('nil') - Callback (listener) function (see below for example.)
-- once ('true') - If 'true', callback is called once, then cleared automatically.
--
-- Example callback definition:
--
--[[
local function onInit( event )
dPrint( 3, ("Init phase completed!")
table.dump(event)
end
inmobi_helpers.setPhaseCB( "init", onInit, true )
]]
--
-- =============================================================
function inmobi_helpers.setPhaseCB( phase, cb, once )
once = fnn( once, true )
phaseCallbacks[phase] = (cb) and { cb = cb, once = once } or nil
end
-- =============================================================
-- init( [ delay [, logLevel ] ] ) - Initilize revMob ad network.
-- If delay is specified, wait 'delay' ms then initialize.
--
-- logLevel - "debug" or "error"
--
-- https://docs.coronalabs.com/daily/plugin/inmobi/init.html
-- =============================================================
function inmobi_helpers.init( delay, logLevel )
-- Set default delay if not provided
delay = delay or 0
-- A function that we may call immediately or with a delay
-- to do the initialization work.
local function doInit()
-- If on Android,
if( onAndroid ) then
-- and a interstial ID was provided, then init with it
if( ids.android.interstitial ) then
inMobi.init( listener, { accountId = ids.android.interstitial, logLevel = logLevel } )
-- or a banner id was supplied and init with it
elseif( ids.android.banner ) then
inMobi.init( listener, { accountId = ids.android.banner, logLevel = logLevel } )
end
-- else if on iOS,
elseif( oniOS ) then
-- and a interstial ID was provided, then init with it
if( ids.ios.interstitial ) then
inMobi.init( listener, { accountId = ids.ios.interstitial, logLevel = logLevel } )
-- or a banner id was supplied and init with it
elseif( ids.ios.banner ) then
inMobi.init( listener, { accountId = ids.ios.banner, logLevel = logLevel } )
end
end
end
-- Initialize immediately or wait a little while?
--
if( delay < 1 ) then
doInit()
else
timer.performWithDelay( delay, doInit )
end
end
-- =============================================================
-- loadBanner( params ) -- Load a banner if we can.
-- loadInterstitial( params ) -- Load an interstitial if we can.
--
-- https://docs.coronalabs.com/daily/plugin/inmobi/load.html
-- =============================================================
function inmobi_helpers.loadBanner( params )
params = params or {}
if( onAndroid ) then
inMobi.load( "banner", ids.android.banner, params )
elseif( oniOS ) then
inMobi.load( "banner", ids.ios.banner, params )
end
end
function inmobi_helpers.loadInterstitial( params )
params = params or {}
if( onAndroid ) then
inMobi.load( "interstitial", ids.android.interstitial, params )
elseif( oniOS ) then
inMobi.load( "interstitial", ids.ios.interstitial, params )
end
end
-- =============================================================
-- showBanner( [ position ] ) -- Show a banner if we can.
-- position "top", "bottom, "center" (default: "top" )
--
-- showInterstitial() -- Show an interstitial if we can.
--
-- https://docs.coronalabs.com/daily/plugin/inmobi/show.html
-- =============================================================
function inmobi_helpers.showBanner( position )
position = position or "top"
if( onAndroid ) then
inMobi.show( ids.android.banner, { yAlign = position } )
lastID = ids.android.banner
elseif( oniOS ) then
inMobi.show( ids.ios.banner, { yAlign = position } )
lastID = ids.ios.banner
end
end
function inmobi_helpers.showInterstitial()
if( onAndroid ) then
inMobi.show( ids.android.interstitial )
lastID = ids.android.interstitial
elseif( oniOS ) then
inMobi.show( ids.ios.interstitial )
lastID = ids.ios.interstitial
end
end
-- =============================================================
-- isLoadedBanner() - Returns true if banner ad is loaded.
-- isLoadedInterstitial() - Returns true if interstitial ad is loaded.
--
-- https://docs.coronalabs.com/daily/plugin/inmobi/isLoaded.html
-- =============================================================
function inmobi_helpers.isLoadedBanner()
if( onAndroid ) then
return inMobi.isLoaded( ids.android.banner )
elseif( oniOS ) then
return inMobi.isLoaded( ids.ios.banner )
end
return false
end
function inmobi_helpers.isLoadedInterstitial()
if( onAndroid ) then
return inMobi.isLoaded( ids.android.interstitial )
elseif( oniOS ) then
return inMobi.isLoaded( ids.ios.interstitial )
end
return false
end
-- =============================================================
-- hide() -- Hide (last shown) inMobi ad.
--
-- https://docs.coronalabs.com/daily/plugin/inMobi/hide.html
-- =============================================================
function inmobi_helpers.hide( )
if( lastID ) then
inMobi.hide( lastID )
lastID = nil
end
end
return inmobi_helpers
|
-----------------------------------------
-- ID: 6268
-- Komanezumi
-----------------------------------------
function onItemCheck(target)
return 0
end
function onItemUse(target)
end
|
local mtmsg = require("mtmsg")
local function printf(...)
print(string.format(...))
end
local N = 5000
local withName = false
local function printTime(title, startTime)
local t = mtmsg.time() - startTime
printf("%-15s %10.3f kop/sec, %6.3f msecs/op", title, N / t / 1000, t / N * 1000)
end
for run = 1, 2 do
collectgarbage()
printf("N = %d, withName = %s", N, tostring(withName))
local idlist = {}
local lslist = {}
--------------------------------------------------------------
local startTime = mtmsg.time()
do
for i = 1, N do
local b
if withName then
local name = "foo"..i or nil
b = mtmsg.newlistener(name)
else
b = mtmsg.newlistener()
end
lslist[i] = b
idlist[i] = b:id()
end
end
printTime("Creation:", startTime)
--------------------------------------------------------------
local startTime = mtmsg.time()
for i = 1, N do
assert(lslist[i]:id() == idlist[i])
end
printTime("Direct call:", startTime)
--------------------------------------------------------------
local startTime = mtmsg.time()
for i = 1, N do
local id = idlist[i]
assert(mtmsg.listener(id):id() == id)
end
printTime("Search by id:", startTime)
--------------------------------------------------------------
local startTime = mtmsg.time()
for i = 1, N do
assert(mtmsg.listener(idlist[i]):id() == idlist[i])
end
printTime("Call by id:", startTime)
--------------------------------------------------------------
end
print("OK.")
|
Audio = class.set()
function Audio:init()
self.shoot = love.audio.newSource("audio/shoot.wav", "static")
self.boom1 = love.audio.newSource("audio/boom1.wav", "static")
self.cityboom = love.audio.newSource("audio/cityboom.wav", "static")
self.gameover = love.audio.newSource("audio/gameover.wav", "static")
self.baseboom = love.audio.newSource("audio/baseboom.wav", "static")
self.outofammo = love.audio.newSource("audio/outofammo.wav", "static")
self.redball = love.audio.newSource("audio/redball.wav", "static")
self.levelup = love.audio.newSource("audio/levelup.wav", "static")
self.ufo = love.audio.newSource("audio/ufo.wav", "static")
self.beam = love.audio.newSource("audio/beam.wav", "static")
end
return class.new(Audio)
|
Citizen.CreateThread(function() Wait(1000)
if (((Plugins.PickableFruits) and not (_StartError_) and (Framework.Vorp) and not (Framework.RedEmRP))) then
--------------------------------------------------------------------------------
----------------------------------- DevDokus -----------------------------------
--------------------------------------------------------------------------------
function Wait(args) Citizen.Wait(args) end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local Location = nil
local Harvesting = false
local InRange = false
--------------------------------------------------------------------------------
-- Get Distance from entities
Citizen.CreateThread(function()
while true do Wait(1000)
local ped = PlayerPedId()
local coords = GetEntityCoords(ped)
local x, y, z = table.unpack(coords)
for k, v in pairs(PickableFruits.Bushes) do
local hash = GetHashKey(tostring(v.ID))
local Near = DoesObjectOfTypeExistAtCoords(x, y, z, 0.85, hash, true)
if Location == nil and Near then Location = v.ID end
if Location == v.ID then
if not Near and InRange then InRange = false Location = nil end
if Near and not InRange then
InRange = true
TriggerEvent('DevDokus:PickableFruits:C:AwaitHarvest', ped, x, y, z, v)
end
end
end
end
end)
RegisterNetEvent('DevDokus:PickableFruits:C:AwaitHarvest')
AddEventHandler('DevDokus:PickableFruits:C:AwaitHarvest', function(ped, x, y, z, v)
while InRange do Wait(1)
local Space = IsControlJustPressed(0, Keys['SPACEBAR'])
if not Harvesting then DrawInfo(_('PickableFruits_PressSpace'), 0.5, 0.95, 0.75) end
if Space then
Harvesting = true
local hash = 'mech_pickup@plant@berries'
RequestAnimDict(hash)
while not HasAnimDictLoaded(hash) do Wait(100) end
TaskPlayAnim(ped, hash, "enter_lf", 8.0, - 0.5, - 1, 0, 0, true, 0, false, 0, false) Wait(800)
TaskPlayAnim(ped, hash, "base", 8.0, - 0.5, - 1, 0, 0, true, 0, false, 0, false) Wait(4300)
ClearPedTasksImmediately(ped)
Harvesting = false
TriggerServerEvent('DevDokus:PickableFruits:S:GiveItems', v.Label)
end
end
end)
end
end)
|
local data = {
label1 = {
widget = "label",
pos = {5, 3},
dim = {50, 5},
text = "Just some simple text",
},
button1 = {
widget = "button",
pos = {5, 10},
dim = {30, 10},
text = "button 1",
},
button2 = {
widget = "button",
pos = {45, 10},
dim = {30, 20},
text = "button 2",
images = {
normal = {
{
fileName = "cathead.png",
color = {1, 1, 1, 1},
},
},
hover = {
{
fileName = "cathead.png",
color = {1, 0, 0, 1},
},
},
pushed = {
{
fileName = "cathead.png",
color = {0, 1, 0, 1},
},
},
disabled = {
{
fileName = "cathead.png",
color = {0, 0, 0, 1},
},
},
},
},
image1 = {
widget = "image",
pos = {5, 23},
dim = {22, 15},
text = "Image",
textHorzAlign = "center",
textVertAlign = "bottom",
images = {
{
fileName = "cathead.png",
},
},
},
-- progressBar1 = {
-- widget = "progress bar",
-- pos = {45, 33},
-- dim = {30, 5},
-- },
label2 = {
widget = "label",
pos = {5, 60},
dim = {30, 5},
text = "Slide Me",
},
slider1 = {
widget = "slider",
pos = {35, 60},
dim = {50, 5},
vert = false,
maxValue = 20,
minValue = 1,
},
label3 = {
widget = "label",
pos = {5, 70},
dim = {30, 5},
text = "Enter Text",
},
edit1 = {
widget = "edit box",
pos = {35, 70},
dim = {50, 5},
},
}
for i = 1, 3 do
local radio = {}
radio.widget = "radio button"
radio.pos = {(i - 1) * 25 + 5, 40}
radio.dim = {20, 4}
radio.text = "Radio"
radio.radioButtonGroup = 1
data["radio" .. i] = radio
end
for i = 1, 3 do
local check = {}
check.widget = "check box"
check.pos = {(i - 1) * 25 + 5, 50}
check.dim = {20, 4}
check.text = "Check"
check.radioButtonGroup = 1
data["check" .. i] = check
end
return data
|
local battle_defs = require "battle/battle_defs"
local BATTLE_EVENT = battle_defs.EVENT
local CARD_FLAGS = battle_defs.CARD_FLAGS
local ITEMS =
{
etb_mixed_bogberries =
{
name = "Mixed Bogberries",
desc = "Has an unknown effect each time you eat it.",
icon = "battle/seedling.tex",
cost = 1,
target_type = TARGET_TYPE.FRIENDLY_OR_SELF,
max_charges = 1,
effects =
{
blue =
{
hunger_restoration = 2,
health_gain = 3,
resolve_gain = 3,
cards = {"gassy", "bloated"},
},
striped =
{
hunger_restoration = 1,
resolve_gain = 7,
cards = {"drunk"},
},
purple =
{
hunger_restoration = 1,
health_gain = 7,
cards = {"ulcer"},
},
spotted =
{
hunger_restoration = 1,
resolve_gain = -10,
cards = {"sick"},
},
red =
{
hunger_restoration = 1,
health_gain = -10,
cards = {"numbness"},
},
rotten =
{
hunger_restoration = 1,
health_gain = -20,
max_health_gain = 5,
cards = {"drunk", "drunk_player"},
},
},
food_data_fn_etb = function(self)
local chosen_effect
if self.userdata and self.userdata.available_effects and #self.userdata.available_effects > 0 then
chosen_effect = table.arraypick(self.userdata.available_effects)
table.arrayremove(self.userdata.available_effects, chosen_effect)
end
if not chosen_effect then
chosen_effect = table.arraypick(copykeys(self.effects))
end
local effect_table = self.effects[chosen_effect]
assert(effect_table, "Invalid effect: " .. chosen_effect)
return deepcopy(effect_table)
end,
OnPostResolve = function( self, battle, attack)
local chosen_effect
if self.userdata and self.userdata.available_effects and #self.userdata.available_effects > 0 then
chosen_effect = table.arraypick(self.userdata.available_effects)
table.arrayremove(self.userdata.available_effects, chosen_effect)
end
if not chosen_effect then
chosen_effect = table.arraypick(copykeys(self.effects))
end
local effect_table = self.effects[chosen_effect]
assert(effect_table, "Invalid effect: " .. chosen_effect)
if (effect_table.health_gain or 0) > 0 then
self.target:HealHealth( effect_table.health_gain, self )
elseif (effect_table.health_gain or 0) < 0 then
self.target:DeltaHealth( effect_table.health_gain )
end
if (effect_table.resolve_gain or 0) > 0 then
self.target:AddCondition("CONCENTRATION", effect_table.resolve_gain, self)
elseif (effect_table.resolve_gain or 0) < 0 then
self.target:AddCondition("IMPAIR", math.ceil(-effect_table.resolve_gain / 2), self)
end
if (effect_table.max_health_gain or 0) ~= 0 then
self.target:DeltaMaxHealth(effect_table.max_health_gain)
self.target:GetAgent().health:AddStatModifier( "BOG_BERRIES", effect_table.max_health_gain )
end
end,
},
etb_mixed_monster_meat =
{
name = "Mixed Monster Meat",
desc = "{HEAL} {1} health and gain {2} {DISEASED}.",
desc_fn = function(self, fmt_str)
return loc.format(fmt_str, self.heal_amt, self.diseased_amt)
end,
flavour = "'It's food, right?'",
icon = "negotiation/grisly_trophy.tex",
cost = 1,
target_type = TARGET_TYPE.FRIENDLY_OR_SELF,
flags = CARD_FLAGS.CONSUME,
heal_amt = 5,
diseased_amt = 2,
food_data_etb =
{
hunger_restoration = 2,
health_gain = 5,
},
OnPostResolve = function( self, battle, attack)
self.target:HealHealth( self.heal_amt, self )
self.target:AddCondition("DISEASED", self.diseased_amt, self)
end,
},
etb_big_game_meat =
{
name = "Big Game Meat",
desc = "{HEAL} {1} health.",
desc_fn = function(self, fmt_str)
return loc.format(fmt_str, self.heal_amt)
end,
flavour = "'Looks like meat is back on the menu!'",
icon = "negotiation/hearty.tex",
cost = 2,
target_type = TARGET_TYPE.FRIENDLY_OR_SELF,
max_charges = 2,
heal_amt = 9,
food_data_etb =
{
hunger_restoration = 3,
health_gain = 9,
},
OnPostResolve = function( self, battle, attack)
self.target:HealHealth( self.heal_amt, self )
end,
},
}
for i, id, data in sorted_pairs( ITEMS ) do
data.item_tags = (data.item_tags or 0) | ITEM_TAGS.COMBAT
data.flags = (data.flags or 0) | CARD_FLAGS.ITEM
data.rarity = data.rarity or CARD_RARITY.UNIQUE
data.series = CARD_SERIES.GENERAL
Content.AddBattleCard( id, data )
end
|
slash = {"\", "/"}
imenilac2 = math.random(3) + 2;
imenilac1 = imenilac2 + math.random(5);
broj1 = 2 + math.random(imenilac1 - 3);
broj2 = 1 + math.random(imenilac2 - 2);
brojilac1 = broj1 * imenilac2
brojilac2 = broj2 * imenilac1
imenilac = imenilac1 * imenilac2
summ = brojilac1 + brojilac2
if (summ < imenilac) then
broj1 = imenilac1 - 1
broj2 = imenilac2 - 1
brojilac1 = broj1 * imenilac2
brojilac2 = broj2 * imenilac1
imenilac = imenilac1 * imenilac2
summ = brojilac1 + brojilac2
end
part1 = imenilac - brojilac1
part2 = brojilac2 - part1
temp = lib.math.gcd(imenilac, summ)
broj = summ / temp
imen = imenilac / temp
value = broj/imen
condition = "is_ok = math.eq(whole + numerator/denominator, "..tostring(value)..");"
swhole = math.floor(value)
snum = lib.math.round((value - swhole) * imen)
g = lib.math.gcd(snum, imen)
sln = "numerator="..tostring(snum/g)..";denominator="..tostring(imen/g)..";whole="..tostring(swhole)..";"
|
ui = {}
for _,type in ipairs {
'Window', 'Box', 'Tree', 'VList', 'Expander', 'Stack',
'TextLine', 'WrappingTextLine', 'LeftRightTextLine', 'EntityLine',
'Inventory',
} do
ui[type] = require('ui.'..type)
end
function ui.layout()
local w,h = tty.termsize()
log.debug('Performing layout calculations: %dx%d', w, h)
ui.screen:layout { w=w, h=h }
end
function ui.init()
tty.init()
ui.screen = ui.Window {
name = "screen";
position = { 0, 0 };
size = { inf, inf };
x = 0; y = 0;
render = function(self)
tty.colour(255, 255, 255, 0, 0, 0)
tty.style('o')
tty.clear()
end;
}
function ui.screen:cmd_exit_game()
love.event.quit()
end
-- Log fills the left side of the screen.
ui.log_win = require 'ui.log_win' {
position = { 0, 0 };
size = { 40, inf };
}
ui.screen:attach(ui.log_win)
-- HUD overlays log in the upper left.
ui.hud_win = require 'ui.hud_win' {
position = { 0, 0 };
size = { 40, 0 };
}
ui.screen:attach(ui.hud_win)
-- main view takes up the remaining space
ui.main_win = ui.Stack {
name = 'main stack';
position = { 1, 0 };
size = { -40, inf };
}
ui.main_win:attach(require 'ui.main_win' {
position = { 0, 0 };
size = { inf, inf };
})
ui.screen:attach(ui.main_win)
ui.layout()
end
function ui.draw()
if flags.parsed.ui_perf then
log.debug('-- render begin --')
end
ui.screen:renderAll()
tty.flip()
if flags.parsed.ui_perf then
log.debug('-- render end --')
end
end
-- Set the HUD title and contents. 'content' should be a table of ui elements,
-- which will become the contents of the HUD's internal VList; if passed a string,
-- it will automatically be turned into a WrappingTextLine.
function ui.setHUD(title, content)
if type(content) == 'string' then
local ww = ui.hud_win:getChildBB().w
content = {
ui.WrappingTextLine { text = content, wrap_width = ww };
}
end
assert(type(content) == 'table', 'invalid argument passed to setHUD: '..repr(content))
ui.hud_win:setContent(title, content)
end
-- Draw a box with the upper left corner at (x,y)
function ui.box(rect, title, walls)
if not rect then
local w,h = tty.size()
rect = { x = 0; y = 0; w = w; h = h; name = "anonymous box"; }
end
local w,h = tty.push(rect)
local default_walls = {
nw = "┏"; n = "━"; ne = "┓";
w = "┃"; c = " "; e = "┃";
sw = "┗"; s = "━"; se = "┛";
}
default_walls.__index = default_walls
walls = setmetatable(walls or {}, default_walls)
tty.put(0, 0, walls.nw..walls.n:rep(w-2)..walls.ne)
for row=1,h-2 do
tty.put(0, row, walls.w..walls.c:rep(w-2)..walls.e)
end
tty.put(0, h-1, walls.sw..walls.s:rep(w-2)..walls.se)
if title then
-- tty.put(1, 0, '┫'..title:sub(1, w-4)..'┣')
tty.put(1, 0, '╾'..title..'╼')
end
tty.pop()
end
function ui.hline(row)
local w,h = tty.size()
tty.put(0, row, ("━"):rep(w))
end
function ui.vline(col)
local w,h = tty.size()
for i=1,h do
tty.put(col, i-1, "┃")
end
end
function ui.mainmenu()
ui.tree {
title = 'Main Menu';
{ text = 'Return to Game';
help = 'Close the menu and return to the game in progress.';
cmd_activate = function() ui.sendEvent(nil, 'cancel'); return true; end; };
{ text = 'Configuration';
cmd_activate = function() settings.edit(); return true; end;
help = 'Change game settings and key bindings.' };
table.copy(require 'ui.debug');
{ text = 'Save Game';
cmd_activate = function() game.save(); ui.sendEvent(nil, 'cancel'); return true; end;
help = 'Save your game in progress.' };
{ text = 'Load Game';
cmd_activate = function() game.load(game.name()); ui.sendEvent(nil, 'cancel'); return true; end;
help = 'Load your last save.' };
{ text = 'Quit And Save';
cmd_activate = function() game.save(); love.event.quit(); end;
help = 'Save your game and then quit TTYmor.' };
{ text = 'Quit Without Saving';
cmd_activate = love.event.quit;
help = 'Immediately quit the same without saving.' };
}
end
-- Turn a tree into a Tree and activate it, running until one of the handlers
-- returns a value.
function ui.tree(tree)
tree = ui.Tree(tree)
ui.main_win:attach(tree)
ui.main_win:layout()
return tree
end
function ui.message(title, message)
if type(message) == 'string' then
return ui.message(title, {message})
end
for i,line in ipairs(message) do
if type(line) == 'string' then
message[i] = ui.WrappingTextLine {
text = line;
wrap_width = (ui.main_win.w/2):floor()
}
end
end
local box = ui.Box {
title = title;
content = ui.VList(message);
position = { 0.5, 0.5 };
}
function box:key_any()
self:destroy()
return true
end
ui.main_win:attach(box)
ui.main_win:layout()
return box
end
function ui.fill(rect, char)
char = char or ' '
tty.push(rect)
for y=0,rect.h-1 do
tty.put(0, y, char:rep(rect.w))
end
tty.pop()
end
function ui.sendEvent(key, evt)
ui.screen:keyEvent(key, evt)
end
|
name = "Hello World"
width = 740
height = 480
display_width = 740*2
display_height = 480*2
manifest = "manifest.lua"
--
-- This script is expected to be an asset in the manifest file.
-- It's executed at the start
--
main_script = "Main.lua"
on_update = "update()"
webserver = true
|
return {
EmotesWheelMinSize = Vector2.new(320, 320),
EmotesWheelMaxSize = Vector2.new(640, 640),
ErrorFrameSize = UDim2.new(0.6, 0, 0.2, 0),
ErrorFramePosition = UDim2.new(0, 0, 0.1, 0),
ErrorFrameAspectRatio = 6,
ErrorFrameMinSize = Vector2.new(336, 56),
ErrorFrameMaxSize = Vector2.new(432, 72),
ErrorTextFont = Enum.Font.Gotham,
ErrorTextSize = 48,
ErrorIcon = "rbxasset://textures/ui/Emotes/ErrorIcon.png",
ErrorIconOffset = 10,
MiddleTextSize = 48,
MiddleTextFont = Enum.Font.Gotham,
SlotNumberTextSize = 48,
SlotNumberFont = Enum.Font.Gotham,
CircleBackground = "rbxasset://textures/ui/Emotes/TenFoot/CircleBackground.png",
SegmentedCircle = "rbxasset://textures/ui/Emotes/TenFoot/SegmentedCircle.png",
SelectedLine = "rbxasset://textures/ui/Emotes/TenFoot/SelectedLine.png",
SelectedLineImageSize = Vector2.new(18, 107),
SelectedLinePadding = 5,
SelectedGradient = "rbxasset://textures/ui/Emotes/TenFoot/SelectedGradient.png",
SelectedGradientImageSize = Vector2.new(292, 225),
}
|
-- parse packetlogs from wireshark (follow tcp stream, c array), and output interpretation in vegastrike protocol
-- ./start.sh -packetlog packetlogs/buy.c
local kFromTxtClient = "client"
local kFromTxtServer = "server"
function PacketLogParse (path)
print("-- "..path)
local packetconvert_lua = {}
for line in io.lines(gMainWorkingDir..path) do
-- char peer0_0[] = { 0x00, 0x00, 0x00, 0x34, 0x01, 0x00, 0x00, 0x00 };
local a,b,comment = string.find(line,"(//.*)")
if (comment) then print("-- "..comment) end
line = string.gsub(line,"//.*","") -- remove comment
line = string.gsub(line,"^[ \t]+","") -- trim
line = string.gsub(line,"[ \t]+$","") -- trum
if (line ~= "") then
line = string.gsub(line,"char.*peer0_.+%{","MyClient({")
line = string.gsub(line,"char.*peer1_.+%{","MyServer({")
line = string.gsub(line,"};","})")
table.insert(packetconvert_lua,line)
--~ print(line)
end
end
function MyClient (data) PacketLog_Arr(data,kFromTxtClient) end
function MyServer (data) PacketLog_Arr(data,kFromTxtServer) end
-- translate c syntax packetlog to lua and then run it
packetconvert_lua = table.concat(packetconvert_lua,"\n")
assert(loadstring(packetconvert_lua))()
os.exit(0)
end
local fifos = {}
fifos[kFromTxtClient] = CreateFIFO()
fifos[kFromTxtServer] = CreateFIFO()
function PacketLog_Arr (data,fromtxt)
local fifo = fifos[fromtxt]
--~ fifo:Clear()
for k,v in ipairs(data) do fifo:PushNetUint8(v) end
while (MyDecodePacket(fifo,fromtxt)) do end
end
local netbuf = cVegaNetBuf:New()
local fifo_payload = CreateFIFO()
function MyDecodePacket (fifo,fromtxt)
-- check if packet is complete
local fifolen_full = fifo:Size()
if (fifolen_full <= 0) then return end
local bPrintIncomplete = false
--~ local bPrintIncomplete = true
local lmin = VNet.PreHeaderLen+VNet.HeaderLen if (lmin > fifolen_full) then if (bPrintIncomplete) then print("-- from:"..fromtxt.." packet incomplete, headers",lmin,fifolen_full) end return false end
local lmin = VNet.PreHeaderLen+VNet.PeekPreHeaderLen(fifo) if (lmin > fifolen_full) then if (bPrintIncomplete) then print("-- from:"..fromtxt.." packet incomplete, datalen prehead",lmin,fifolen_full) end return false end
local lmin = VNet.PreHeaderLen+VNet.HeaderLen+VNet.PeekHeaderLen(fifo,VNet.PreHeaderLen) if (lmin > fifolen_full) then if (bPrintIncomplete) then print("-- from:"..fromtxt.." packet incomplete, datalen head",lmin,fifolen_full) end return false end
-- pop headers
local ph = VNet.PopPreHeader(fifo)
local h = VNet.PopHeader(fifo)
local cmdname = VNet.GetCmdName(h.command)
local datalen = h.data_length
local fifolen_data = fifo:Size()
-- pop data
if (datalen >= 0 and datalen <= fifo:Size()) then
fifo_payload:Clear()
fifo_payload:PushFIFOPartRaw(fifo,0,min(datalen,fifo:Size()))
if (datalen > 0) then fifo:PopRaw(datalen) end
--~ print("removing payload data. removed,remaining=",datalen,fifo:Size())
else
print("failed to remove payload data, clearing fifo for recovery. payload request, actual size",datalen,fifo:Size())
fifo:Clear()
end
-- extract chunks from data
netbuf:ReInit(fifo_payload)
local chunks = {}
local txt_chunks = {}
while true do
local chunk = {netbuf:getNextPair()}
if (not chunk[1]) then break end
table.insert(chunks,chunk)
-- produce human readable text
local txt_chunk = ""
local c = chunk[1]
for k,v in ipairs(chunk) do
if (k == 1) then
txt_chunk = GetNBTypeName(v) or (tostring(v))
else
if (type(v) == "string") then v = sprintf("%q",v) end
if (c == NBType.NB_BUFFER) then v = "RawData("..v:Size()..",\"...\")" end -- TODO: hex+asci dump ?
txt_chunk = txt_chunk..","..tostring(v)
end
end
table.insert(txt_chunks,"("..txt_chunk..")")
end
local s = fifo_payload:Size() if (s > 0) then table.insert(txt_chunks,"data:"..s) end
txt_chunks = "{"..table.concat(txt_chunks,",").."}"
-- print output
local txt_prehead = "{len="..ph._len..",pri="..ph._pri..",flags="..Hex(ph._flags).."}"
local txt_head = "{cmd="..h.command..",serial="..h.serial..",datalen="..h.data_length..",flags="..Hex(h.flags).."}"
local txt_add = ""
--~ txt_add = txt_add .. ",fifolen_full="..fifolen_full..",fifolen_data="..fifolen_data..",fifolen_left="..fifo:Size()
txt_add = txt_add .. ","..txt_chunks
local txt_subcmd = ""
if (h.command == VNet.Cmd.CMD_DOWNLOAD) then
--~ local sc = netbuf:getChar() -- todo: this removes data, make copy if buffer is analyzed
local sc = chunks[1][2] -- 1st chunk, 2=data
txt_subcmd = ",submd="..VNet.GetDownloadSubCmdName(sc)
end
print("Packet({from="..fromtxt..",cmd="..(cmdname or h.command)..txt_subcmd..",head={"..txt_prehead..","..txt_head.."}"..txt_add.."})")
return true
end
|
local cjson = require ("cjson");
local PreparedStatement = require ("Sql").PreparedStatement;
local cedegjson = [[{
"number": 1092,
"holder": "jose luis",
"records": [{"code": "023", "name": "cuentas por pagar"},{"code": "024", "name": "cuentas por cobrar"}]
}]];
local cedeg = cjson.decode (cedegjson);
local Q = PreparedStatement:New([[SELECT "Name" FROM "AccountingAccount" WHERE "Code"='?';]]);
Q:SetString (cedeg.number);
print (Q:ToString());
|
local events = {
ProcessEventsInterval = 8,
GameKey = "",
SecretKey = "",
Build = "",
_availableResourceCurrencies = {},
_availableResourceItemTypes = {},
}
local store = require(script.Parent.Store)
local logger = require(script.Parent.Logger)
local version = require(script.Parent.Version)
local validation = require(script.Parent.Validation)
local threading = require(script.Parent.Threading)
local http_api = require(script.Parent.HttpApi)
local utilities = require(script.Parent.Utilities)
local GAResourceFlowType = require(script.Parent.GAResourceFlowType)
local GAProgressionStatus = require(script.Parent.GAProgressionStatus)
local GAErrorSeverity = require(script.Parent.GAErrorSeverity)
local HTTP = game:GetService("HttpService")
local CategorySessionStart = "user"
local CategorySessionEnd = "session_end"
local CategoryBusiness = "business"
local CategoryResource = "resource"
local CategoryProgression = "progression"
local CategoryDesign = "design"
local CategoryError = "error"
local CategorySdkError = "sdk_error"
local MAX_EVENTS_TO_SEND_IN_ONE_BATCH = 500
local MAX_AGGREGATED_EVENTS = 2000
local function addDimensionsToEvent(playerId, eventData)
if not eventData or not playerId then
return
end
local PlayerData = store:GetPlayerDataFromCache(playerId)
-- add to dict (if not nil)
if PlayerData and PlayerData.CurrentCustomDimension01 and #PlayerData.CurrentCustomDimension01 > 0 then
eventData["custom_01"] = PlayerData.CurrentCustomDimension01
end
if PlayerData and PlayerData.CurrentCustomDimension02 and #PlayerData.CurrentCustomDimension02 > 0 then
eventData["custom_02"] = PlayerData.CurrentCustomDimension02
end
if PlayerData and PlayerData.CurrentCustomDimension03 and #PlayerData.CurrentCustomDimension03 > 0 then
eventData["custom_03"] = PlayerData.CurrentCustomDimension03
end
end
local function getClientTsAdjusted(playerId)
if not playerId then
return os.time()
end
local PlayerData = store:GetPlayerDataFromCache(playerId)
local clientTs = os.time()
local clientTsAdjustedInteger = clientTs + PlayerData.ClientServerTimeOffset
if validation:validateClientTs(clientTsAdjustedInteger) then
return clientTsAdjustedInteger
else
return clientTs
end
end
local DUMMY_SESSION_ID = HTTP:GenerateGUID(false):lower()
local function recursiveToString(object)
if typeof(object) == "table" then
local str = "{\n"
for i,v in pairs(object) do
if typeof(i) == "string" then
str = str .. i .. " = "
else
str = str .. "[" .. tostring(i) .. "] = "
end
str = str .. tostring(v) .. ",\n"
end
str = str .. "}"
return str
else
return tostring(object)
end
end
local function Length(Table)
local counter = 0
for _, v in pairs(Table) do
counter =counter + 1
end
return counter
end
local function getEventAnnotations(playerId)
local PlayerData
local id
if playerId then
id = playerId
PlayerData = store:GetPlayerDataFromCache(playerId)
else
id = "DummyId"
PlayerData = {
OS = "uwp_desktop 0.0.0",
Platform = "uwp_desktop",
SessionID = DUMMY_SESSION_ID,
Sessions = 1,
CustomUserId = "Server"
}
end
local annotations = {
-- ---- REQUIRED ----
-- collector event API version
["v"] = 2,
-- User identifier
["user_id"] = tostring(id) .. PlayerData.CustomUserId,
-- Client Timestamp (the adjusted timestamp)
["client_ts"] = getClientTsAdjusted(playerId),
-- SDK version
["sdk_version"] = "roblox " .. version.SdkVersion,
-- Operation system version
["os_version"] = PlayerData.OS,
-- Device make (hardcoded to apple)
["manufacturer"] = "unknown",
-- Device version
["device"] = "unknown",
-- Platform (operating system)
["platform"] = PlayerData.Platform,
-- Session identifier
["session_id"] = PlayerData.SessionID,
-- Session number
["session_num"] = PlayerData.Sessions
}
if not utilities:isStringNullOrEmpty(PlayerData.CountryCode) then
annotations["country_code"] = PlayerData.CountryCode
end
if validation:validateBuild(events.Build) then
annotations["build"] = events.Build
end
if PlayerData.Configurations and Length(PlayerData.Configurations) > 0 then
annotations["configurations"] = PlayerData.Configurations
end
if not utilities:isStringNullOrEmpty(PlayerData.AbId) then
annotations["ab_id"] = PlayerData.AbId
end
if not utilities:isStringNullOrEmpty(PlayerData.AbVariantId) then
annotations["ab_variant_id"] = PlayerData.AbVariantId
end
return annotations
end
local function addEventToStore(playerId, eventData)
-- Get default annotations
local ev = getEventAnnotations(playerId)
-- Merge with eventData
for k in pairs(eventData) do
ev[k] = eventData[k]
end
-- Create json string representation
local json = HTTP:JSONEncode(ev)
-- output if VERBOSE LOG enabled
logger:ii("Event added to queue: " .. json)
-- Add to store
store.EventsQueue[#store.EventsQueue + 1] = ev
end
local function dequeueMaxEvents()
if #store.EventsQueue <= MAX_EVENTS_TO_SEND_IN_ONE_BATCH then
local eventsQueue = store.EventsQueue
store.EventsQueue = {}
return eventsQueue
else
logger:w(("More than %d events queued! Sending %d."):format(MAX_EVENTS_TO_SEND_IN_ONE_BATCH, MAX_EVENTS_TO_SEND_IN_ONE_BATCH))
if #store.EventsQueue > MAX_AGGREGATED_EVENTS then
logger:w(("DROPPING EVENTS: More than %d events queued!"):format(MAX_AGGREGATED_EVENTS))
end
-- Expensive operation to get ordered events cleared out (O(n))
local eventsQueue = table.create(MAX_EVENTS_TO_SEND_IN_ONE_BATCH)
for i = 1, MAX_EVENTS_TO_SEND_IN_ONE_BATCH do
eventsQueue[i] = store.EventsQueue[i]
end
-- Shift everything down and overwrite old events
local eventCount = #store.EventsQueue
for i = 1, math.min(MAX_AGGREGATED_EVENTS, eventCount) do
store.EventsQueue[i] = store.EventsQueue[i + MAX_EVENTS_TO_SEND_IN_ONE_BATCH]
end
-- Clear additional events
for i = MAX_AGGREGATED_EVENTS + 1, eventCount do
store.EventsQueue[i] = nil
end
return eventsQueue
end
end
local function processEvents()
local queue = dequeueMaxEvents()
if #queue == 0 then
logger:i("Event queue: No events to send")
return
end
-- Log
logger:i("Event queue: Sending " .. tostring(#queue) .. " events.")
local eventsResult = http_api:sendEventsInArray(events.GameKey, events.SecretKey, queue)
local statusCode = eventsResult.statusCode
local responseBody = eventsResult.body
if statusCode == http_api.EGAHTTPApiResponse.Ok and responseBody then
logger:i("Event queue: " .. tostring(#queue) .. " events sent.")
else
if statusCode == http_api.EGAHTTPApiResponse.NoResponse then
logger:w("Event queue: Failed to send events to collector - Retrying next time")
for _, e in pairs(queue) do
if #store.EventsQueue < MAX_AGGREGATED_EVENTS then
store.EventsQueue[#store.EventsQueue + 1] = e
else
break
end
end
else
if statusCode == http_api.EGAHTTPApiResponse.BadRequest and responseBody then
logger:w("Event queue: " .. tostring(#queue) .. " events sent. " .. tostring(#responseBody) .. " events failed GA server validation.")
else
logger:w("Event queue: Failed to send events.")
end
end
end
end
function events:processEventQueue()
processEvents()
threading:scheduleTimer(events.ProcessEventsInterval, function()
events:processEventQueue()
end)
end
function events:setBuild(build)
if not validation:validateBuild(build) then
logger:w("Validation fail - configure build: Cannot be null, empty or above 32 length. String: " .. build)
return
end
self.Build = build
logger:i("Set build version: " .. build)
end
function events:setAvailableResourceCurrencies(availableResourceCurrencies)
if not validation:validateResourceCurrencies(availableResourceCurrencies) then
return
end
self._availableResourceCurrencies = availableResourceCurrencies
logger:i("Set available resource currencies: (" .. table.concat(availableResourceCurrencies, ", ") .. ")")
end
function events:setAvailableResourceItemTypes(availableResourceItemTypes)
if not validation:validateResourceCurrencies(availableResourceItemTypes) then
return
end
self._availableResourceItemTypes = availableResourceItemTypes
logger:i("Set available resource item types: (" .. table.concat(availableResourceItemTypes, ", ") .. ")")
end
function events:addSessionStartEvent(playerId, teleportData)
local PlayerData = store:GetPlayerDataFromCache(playerId)
if teleportData then
PlayerData.Sessions = teleportData.Sessions
else
local eventDict = {}
-- Event specific data
eventDict["category"] = CategorySessionStart
-- Increment session number and persist
PlayerData.Sessions = PlayerData.Sessions + 1
-- Add custom dimensions
addDimensionsToEvent(playerId, eventDict)
-- Add to store
addEventToStore(playerId, eventDict)
logger:i("Add SESSION START event")
processEvents()
end
end
function events:addSessionEndEvent(playerId)
local PlayerData = store:GetPlayerDataFromCache(playerId)
local session_start_ts = PlayerData.SessionStart
local client_ts_adjusted = getClientTsAdjusted(playerId)
local sessionLength = 0
if client_ts_adjusted ~= nil and session_start_ts ~= nil then
sessionLength = client_ts_adjusted - session_start_ts
end
if sessionLength < 0 then
-- Should never happen.
-- Could be because of edge cases regarding time altering on device.
logger:w("Session length was calculated to be less then 0. Should not be possible. Resetting to 0.")
sessionLength = 0
end
-- Event specific data
local eventDict = {}
eventDict["category"] = CategorySessionEnd
eventDict["length"] = sessionLength
-- Add custom dimensions
addDimensionsToEvent(playerId, eventDict)
-- Add to store
addEventToStore(playerId, eventDict)
PlayerData.SessionStart = 0
logger:i("Add SESSION END event.")
processEvents()
end
function events:addBusinessEvent(playerId, currency, amount, itemType, itemId, cartType)
-- Validate event params
if not validation:validateBusinessEvent(currency, amount, cartType, itemType, itemId) then
-- TODO: add sdk error event
return
end
-- Create empty eventData
local eventDict = {}
-- Increment transaction number and persist
local PlayerData = store:GetPlayerDataFromCache(playerId)
PlayerData.Transactions = PlayerData.Transactions + 1
-- Required
eventDict["event_id"] = itemType .. ":" .. itemId
eventDict["category"] = CategoryBusiness
eventDict["currency"] = currency
eventDict["amount"] = amount
eventDict["transaction_num"] = PlayerData.Transactions
-- Optional
if not utilities:isStringNullOrEmpty(cartType) then
eventDict["cart_type"] = cartType
end
-- Add custom dimensions
addDimensionsToEvent(playerId, eventDict)
logger:i("Add BUSINESS event: {currency:" .. currency .. ", amount:" .. tostring(amount) .. ", itemType:" .. itemType .. ", itemId:" .. itemId .. ", cartType:" .. cartType .. "}")
-- Send to store
addEventToStore(playerId, eventDict)
end
function events:addResourceEvent(playerId, flowType, currency, amount, itemType, itemId)
-- Validate event params
if not validation:validateResourceEvent(GAResourceFlowType, flowType, currency, amount, itemType, itemId, self._availableResourceCurrencies, self._availableResourceItemTypes) then
-- TODO: add sdk error event
return
end
-- If flow type is sink reverse amount
if flowType == GAResourceFlowType.Sink then
amount = (-1 * amount)
end
-- Create empty eventData
local eventDict = {}
-- insert event specific values
local flowTypeString = GAResourceFlowType[flowType]
eventDict["event_id"] = flowTypeString .. ":" .. currency .. ":" .. itemType .. ":" .. itemId
eventDict["category"] = CategoryResource
eventDict["amount"] = amount
-- Add custom dimensions
addDimensionsToEvent(playerId, eventDict)
logger:i("Add RESOURCE event: {currency:" .. currency .. ", amount:" .. tostring(amount) .. ", itemType:" .. itemType .. ", itemId:" .. itemId .. "}")
-- Send to store
addEventToStore(playerId, eventDict)
end
function events:addProgressionEvent(playerId, progressionStatus, progression01, progression02, progression03, score)
-- Validate event params
if not validation:validateProgressionEvent(GAProgressionStatus, progressionStatus, progression01, progression02, progression03) then
-- TODO: add sdk error event
return
end
-- Create empty eventData
local eventDict = {}
-- Progression identifier
local progressionIdentifier
if utilities:isStringNullOrEmpty(progression02) then
progressionIdentifier = progression01
elseif utilities:isStringNullOrEmpty(progression03) then
progressionIdentifier = progression01 .. ":" .. progression02
else
progressionIdentifier = progression01 .. ":" .. progression02 .. ":" .. progression03
end
local statusString = GAProgressionStatus[progressionStatus]
-- Append event specifics
eventDict["category"] = CategoryProgression
eventDict["event_id"] = statusString .. ":" .. progressionIdentifier
-- Attempt
local attempt_num = 0
-- Add score if specified and status is not start
if score ~= nil and progressionStatus ~= GAProgressionStatus.Start then
eventDict["score"] = score
end
local PlayerData = store:GetPlayerDataFromCache(playerId)
-- Count attempts on each progression fail and persist
if progressionStatus == GAProgressionStatus.Fail then
-- Increment attempt number
local progressionTries = PlayerData.ProgressionTries[progressionIdentifier] or 0
PlayerData.ProgressionTries[progressionIdentifier] = progressionTries + 1
end
-- increment and add attempt_num on complete and delete persisted
if progressionStatus == GAProgressionStatus.Complete then
-- Increment attempt number
local progressionTries = PlayerData.ProgressionTries[progressionIdentifier] or 0
PlayerData.ProgressionTries[progressionIdentifier] = progressionTries + 1
-- Add to event
attempt_num = PlayerData.ProgressionTries[progressionIdentifier]
eventDict["attempt_num"] = attempt_num
-- Clear
PlayerData.ProgressionTries[progressionIdentifier] = 0
end
-- Add custom dimensions
addDimensionsToEvent(playerId, eventDict)
local progression02String = ""
if not utilities:isStringNullOrEmpty(progression02) then
progression02String = progression02
end
local progression03String = ""
if not utilities:isStringNullOrEmpty(progression03) then
progression03String = progression03
end
logger:i("Add PROGRESSION event: {status:" .. statusString .. ", progression01:" .. progression01 .. ", progression02:" .. progression02String .. ", progression03:" .. progression03String .. ", score:" .. tostring(score) .. ", attempt:" .. tostring(attempt_num) .. "}")
-- Send to store
addEventToStore(playerId, eventDict)
end
function events:addDesignEvent(playerId, eventId, value)
-- Validate
if not validation:validateDesignEvent(eventId) then
-- TODO: add sdk error event
return
end
-- Create empty eventData
local eventData = {}
-- Append event specifics
eventData["category"] = CategoryDesign
eventData["event_id"] = eventId
if value ~= nil then
eventData["value"] = value
end
-- Add custom dimensions
addDimensionsToEvent(playerId, eventData)
logger:i("Add DESIGN event: {eventId:" .. eventId .. ", value:" .. tostring(value) .. "}")
-- Send to store
addEventToStore(playerId, eventData)
end
function events:addErrorEvent(playerId, severity, message)
-- Validate
if not validation:validateErrorEvent(GAErrorSeverity, severity, message) then
-- TODO: add sdk error event
return
end
-- Create empty eventData
local eventData = {}
local severityString = GAErrorSeverity[severity]
eventData["category"] = CategoryError
eventData["severity"] = severityString
eventData["message"] = message
-- Add custom dimensions
addDimensionsToEvent(playerId, eventData)
local messageString = ""
if not utilities:isStringNullOrEmpty(message) then
messageString = message
end
logger:i("Add ERROR event: {severity:" .. severityString .. ", message:" .. messageString .. "}")
-- Send to store
addEventToStore(playerId, eventData)
end
function events:addSdkErrorEvent(playerId, category, area, action, parameter, reason)
-- Create empty eventData
local eventData = {}
eventData["category"] = CategorySdkError
eventData["error_category"] = category
eventData["error_area"] = area
eventData["error_action"] = action
if not utilities:isStringNullOrEmpty(parameter) then
eventData["error_parameter"] = parameter
end
if not utilities:isStringNullOrEmpty(reason) then
eventData["reason"] = reason
end
logger:i("Add SDK ERROR event: {error_category:" .. category .. ", error_area:" .. area .. ", error_action:" .. action .. "}")
-- Send to store
addEventToStore(playerId, eventData)
end
return events
|
AddRoom("BurntForestStart", {
colour={r=.010,g=.010,b=.010,a=.50},
value = GROUND.FOREST,
contents = {
countprefabs= {
firepit=1,
},
distributepercent = 0.6,
distributeprefabs= {
evergreen = 3 + math.random(4),
charcoal = 0.2,
},
prefabdata={
evergreen = {burnt=true},
}
}
})
AddRoom("SafeSwamp", {
colour={r=0.2,g=0.0,b=0.2,a=0.3},
value = GROUND.MARSH,
contents = {
countprefabs= {
mandrake = math.random(1,2),
},
distributepercent = 0.2,
distributeprefabs = {
marsh_tree=1,
marsh_bush=1,
--TODO: Traps need to be not "owned" by player
}
}
})
|
---------------------------------------------------------------
-- Copyright 2020 Deviap (https://deviap.com/) --
---------------------------------------------------------------
-- Made available under the MIT License: --
-- https://github.com/deviap/sample-apps/blob/master/LICENSE --
---------------------------------------------------------------
for x = 1, 10 do
for y = 1, 10 do
local block = core.construct("block", {
position = vector3(x, y, 0),
scale = vector3(0.7, 0.7, 0.7),
colour = colour.random()
})
if x == 5 and y == 4 then
block.renderQueue = 240
end
end
end
core.scene.camera.position = vector3(5, 5, -15)
core.scene.camera:lookAt(vector3(5, 5, 0))
core.graphics.upperAmbient = colour(3, 3, 3)
core.graphics.ambientDirection = vector3(0, 1, 0)
sleep(1)
require("devgit:source/application/utilities/camera.lua")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.