content
stringlengths 5
1.05M
|
---|
--scifi_nodes by D00Med
--the builder node
local builder_formspec =
"size[8,9]" ..
default.gui_bg ..
default.gui_bg_img ..
default.gui_slots ..
"list[current_name;input;1,1;1,1;]" ..
"list[current_name;output;3,0;4,3;]" ..
"list[current_player;main;0,4.85;8,1;]" ..
"list[current_player;main;0,6.08;8,3;8]" ..
"listring[current_name;input]" ..
"listring[current_name;output]" ..
"listring[current_player;main]" ..
default.get_hotbar_bg(0,4.85)
local input_items = {
{"default:steel_ingot 1", "scifi_nodes:black", "scifi_nodes:blue", "scifi_nodes:rough", "scifi_nodes:rust", "scifi_nodes:white", "scifi_nodes:grey", "scifi_nodes:pplwll", "scifi_nodes:greenmetal", "scifi_nodes:wall", "scifi_nodes:blue_square", "scifi_nodes:mesh", "scifi_nodes:greytile"}
}
minetest.register_node("scifi_nodes:builder", {
description = "Sci-fi Node Builder",
tiles = {
"scifi_nodes_builder.png",
"scifi_nodes_builder.png",
"scifi_nodes_builder_side.png",
"scifi_nodes_builder_side.png",
"scifi_nodes_builder_side.png",
"scifi_nodes_builder_front.png"
},
on_construct = function(pos)
--local meta = minetest.get_meta(pos)
--meta:set_string("infotext", "Node Builder (currently does nothing)")
local meta = minetest.get_meta(pos)
meta:set_string("formspec", builder_formspec)
meta:set_string("infotext", "Node Builder")
local inv = meta:get_inventory()
inv:set_size("output", 4 * 3)
inv:set_size("input", 1 * 1)
end,
on_metadata_inventory_put = function(pos, listname, index, stack, player)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
local player_inv = player:get_inventory()
if listname == "output" then
player_inv:add_item("main", stack)
inv:set_stack("output", index, "")
end
if listname == "input" then
for _, row in ipairs(input_items) do
local item = row[1]
if inv:contains_item("input", item) then
inv:set_stack("output", 1, row[2])
inv:set_stack("output", 2, row[3])
inv:set_stack("output", 3, row[4])
inv:set_stack("output", 4, row[5])
inv:set_stack("output", 5, row[6])
inv:set_stack("output", 6, row[7])
inv:set_stack("output", 7, row[8])
inv:set_stack("output", 8, row[9])
inv:set_stack("output", 9, row[10])
inv:set_stack("output", 10, row[11])
inv:set_stack("output", 11, row[12])
inv:set_stack("output", 12, row[13])
end
end
end
end,
on_metadata_inventory_take = function(pos, listname, index, stack, player)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
local stack = inv:get_stack("input", 1)
local stack_name = stack:get_name()
inv:remove_item("input", stack_name.." 1")
inv:set_stack("output", 1, "")
inv:set_stack("output", 2, "")
inv:set_stack("output", 3, "")
inv:set_stack("output", 4, "")
inv:set_stack("output", 5, "")
inv:set_stack("output", 6, "")
inv:set_stack("output", 7, "")
inv:set_stack("output", 8, "")
inv:set_stack("output", 9, "")
inv:set_stack("output", 10, "")
inv:set_stack("output", 11, "")
inv:set_stack("output", 12, "")
end,
paramtype = "light",
paramtype2 = "facedir",
groups = {cracky=1, oddly_breakable_by_hand=1}
})
--nodes
minetest.register_node("scifi_nodes:grassblk", {
description = "Dirt With Alien Grass",
tiles = {"default_grass.png^[colorize:cyan:80", "default_dirt.png",
{name = "default_dirt.png^(default_grass_side.png^[colorize:cyan:80)",
tileable_vertical = false}},
light_source = 2,
groups = {crumbly=1, oddly_breakable_by_hand=1, soil=1}
})
minetest.register_node("scifi_nodes:light", {
description = "blue lightbox",
sunlight_propagates = false,
tiles = {
"scifi_nodes_lighttop.png",
"scifi_nodes_lighttop.png",
"scifi_nodes_light.png",
"scifi_nodes_light.png",
"scifi_nodes_light.png",
"scifi_nodes_light.png"
},
light_source = 10,
paramtype = "light",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:rfloor", {
description = "rusty floor",
tiles = {
"scifi_nodes_rustfloor.png",
},
paramtype = "light",
paramtype2 = "facedir",
light_source = 10,
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:bfloor", {
description = "blue floor",
tiles = {
"scifi_nodes_bluefloor.png",
},
paramtype = "light",
paramtype2 = "facedir",
light_source = 10,
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:stripes2", {
description = "hazard stripes2",
sunlight_propagates = false,
tiles = {
"scifi_nodes_stripes2top.png",
"scifi_nodes_stripes2top.png",
"scifi_nodes_stripes2.png",
"scifi_nodes_stripes2.png",
"scifi_nodes_stripes2.png",
"scifi_nodes_stripes2.png"
},
paramtype = "light",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:gblock", {
description = "Green metal block",
sunlight_propagates = false,
tiles = {
"scifi_nodes_gblock.png",
"scifi_nodes_gblock.png",
"scifi_nodes_gblock.png",
"scifi_nodes_gblock.png",
"scifi_nodes_gblock.png",
"scifi_nodes_gblock.png"
},
paramtype = "light",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:gblock2", {
description = "Green metal block 2",
sunlight_propagates = false,
tiles = {
"scifi_nodes_gblock2_top.png",
"scifi_nodes_gblock.png",
"scifi_nodes_gblock2.png",
"scifi_nodes_gblock2_fx.png",
"scifi_nodes_gblock.png",
"scifi_nodes_gblock2_front1.png"
},
paramtype = "light",
paramtype2 = "facedir",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:gblock3", {
description = "Green metal block 3",
sunlight_propagates = false,
tiles = {
"scifi_nodes_gblock2_top.png",
"scifi_nodes_gblock.png",
"scifi_nodes_gblock2.png",
"scifi_nodes_gblock2_fx.png",
"scifi_nodes_gblock.png",
"scifi_nodes_gblock2_screen.png"
},
paramtype = "light",
paramtype2 = "facedir",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:green_light", {
description = "green lightbox",
sunlight_propagates = false,
tiles = {
"scifi_nodes_lighttop.png",
"scifi_nodes_lighttop.png",
"scifi_nodes_greenlight.png",
"scifi_nodes_greenlight.png",
"scifi_nodes_greenlight.png",
"scifi_nodes_greenlight.png"
},
light_source = 10,
paramtype = "light",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:red_light", {
description = "red lightbox",
sunlight_propagates = false,
tiles = {
"scifi_nodes_lighttop.png",
"scifi_nodes_lighttop.png",
"scifi_nodes_redlight.png",
"scifi_nodes_redlight.png",
"scifi_nodes_redlight.png",
"scifi_nodes_redlight.png"
},
light_source = 10,
paramtype = "light",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:discs", {
description = "disc shelves",
sunlight_propagates = false,
tiles = {
"scifi_nodes_box_top.png",
"scifi_nodes_box_top.png",
"scifi_nodes_discs.png",
"scifi_nodes_discs.png",
"scifi_nodes_discs.png",
"scifi_nodes_discs.png"
},
paramtype = "light",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:disc", {
description = "disc",
drawtype = "torchlike",
sunlight_propagates = false,
tiles = {
"scifi_nodes_disc.png"
},
inventory_image = "scifi_nodes_disc.png",
wield_image = "scifi_nodes_disc.png",
paramtype = "light",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:blink", {
description = "blinking light",
sunlight_propagates = false,
tiles = {{
name="scifi_nodes_lightbox.png",
animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=2.00},
}},
paramtype = "light",
groups = {cracky=1},
light_source = 5,
})
minetest.register_node("scifi_nodes:black_lights", {
description = "black wallpanel",
sunlight_propagates = false,
tiles = {{
name="scifi_nodes_black_lights.png",
animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=0.50},
}},
paramtype = "light",
groups = {cracky=1},
})
minetest.register_node("scifi_nodes:black_screen", {
description = "black wall screen",
sunlight_propagates = false,
tiles = {{
name="scifi_nodes_black_screen.png",
animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=2.00},
}},
paramtype = "light",
groups = {cracky=1},
light_source = 1,
})
minetest.register_node("scifi_nodes:screen", {
description = "electronic screen",
sunlight_propagates = false,
tiles = {{
name="scifi_nodes_screen.png",
animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=0.50},
}},
paramtype = "light",
groups = {cracky=1},
light_source = 5,
})
minetest.register_node("scifi_nodes:screen2", {
description = "electronic screen 2",
sunlight_propagates = false,
tiles = {{
name="scifi_nodes_screen2.png",
animation={type="vertical_frames", aspect_w=16, aspect_h=16, length=0.50},
}},
paramtype = "light",
groups = {cracky=1},
light_source = 5,
})
minetest.register_node("scifi_nodes:white_pad", {
description = "white keypad",
sunlight_propagates = false,
tiles = {
"scifi_nodes_white2.png",
"scifi_nodes_white2.png",
"scifi_nodes_white2.png",
"scifi_nodes_white2.png",
"scifi_nodes_white2.png",
"scifi_nodes_white_pad.png"
},
paramtype = "light",
paramtype2 = "facedir",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:white_base", {
description = "white wall base",
sunlight_propagates = false,
tiles = {
"scifi_nodes_white2.png",
"scifi_nodes_white2.png",
"scifi_nodes_white_side.png",
"scifi_nodes_white_side.png",
"scifi_nodes_white_side.png",
"scifi_nodes_white_side.png"
},
paramtype = "light",
paramtype2 = "facedir",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:grnpipe", {
description = "green pipe",
sunlight_propagates = false,
tiles = {
"scifi_nodes_greenpipe_front.png",
"scifi_nodes_greenpipe_front.png",
"scifi_nodes_greenpipe_top.png",
"scifi_nodes_greenpipe_top.png",
"scifi_nodes_greenpipe_top.png",
"scifi_nodes_greenpipe_top.png"
},
paramtype = "light",
paramtype2 = "facedir",
groups = {cracky=1},
on_place = minetest.rotate_node
})
minetest.register_node("scifi_nodes:grnpipe2", {
description = "broken green pipe",
sunlight_propagates = false,
tiles = {
"scifi_nodes_greenpipe_front.png",
"scifi_nodes_greenpipe_front.png",
"scifi_nodes_greenpipe2_top.png",
"scifi_nodes_greenpipe2_top.png",
"scifi_nodes_greenpipe2_top.png",
"scifi_nodes_greenpipe2_top.png"
},
paramtype = "light",
paramtype2 = "facedir",
groups = {cracky=1},
on_place = minetest.rotate_node
})
minetest.register_node("scifi_nodes:octrng", {
description = "Orange Octagon Glass",
sunlight_propagates = false,
drawtype = "glasslike",
tiles = {
"scifi_nodes_octrng.png",
},
paramtype = "light",
paramtype2 = "facedir",
use_texture_alpha = true,
light_source = 10,
groups = {cracky=2},
sounds = default.node_sound_glass_defaults(),
})
minetest.register_node("scifi_nodes:octgrn", {
description = "Green Octagon Glass",
sunlight_propagates = false,
drawtype = "glasslike",
tiles = {
"scifi_nodes_octgrn.png",
},
paramtype = "light",
paramtype2 = "facedir",
use_texture_alpha = true,
light_source = 10,
groups = {cracky=2},
sounds = default.node_sound_glass_defaults(),
})
minetest.register_node("scifi_nodes:octbl", {
description = "Blue Octagon Glass",
sunlight_propagates = false,
drawtype = "glasslike",
tiles = {
"scifi_nodes_octbl.png",
},
paramtype = "light",
paramtype2 = "facedir",
use_texture_alpha = true,
light_source = 10,
groups = {cracky=2},
sounds = default.node_sound_glass_defaults(),
})
minetest.register_node("scifi_nodes:octppl", {
description = "Purple Octagon Glass",
sunlight_propagates = false,
drawtype = "glasslike",
tiles = {
"scifi_nodes_octppl.png",
},
paramtype = "light",
paramtype2 = "facedir",
use_texture_alpha = true,
light_source = 10,
groups = {cracky=2},
sounds = default.node_sound_glass_defaults(),
})
minetest.register_node("scifi_nodes:tower", {
description = "Wind tower",
sunlight_propagates = false,
drawtype = "plantlike",
tiles = {{
name = "scifi_nodes_tower_anim.png",
animation = {type = "vertical_frames", aspect_w = 32, aspect_h = 32, length = 1.00},
}},
visual_scale = 2,
inventory_image = "scifi_nodes_tower.png",
paramtype = "light",
groups = {cracky=2},
})
minetest.register_node("scifi_nodes:junk", {
description = "Junk",
sunlight_propagates = true,
paramtype = "light",
liquid_viscosity = 8,
liquidtype = "source",
liquid_alternative_flowing = "scifi_nodes:junk",
liquid_alternative_source = "scifi_nodes:junk",
liquid_renewable = false,
liquid_range = 0,
walkable = false,
tiles = {
"scifi_nodes_junk.png"
},
groups = {snappy=1, oddly_breakable_by_hand=1, liquid=3, dig_immediate=1}
})
--edited wool code (Copyright (C) 2012 celeron55, Perttu Ahola <[email protected]>)
local node = {}
-- This uses a trick: you can first define the recipes using all of the base
-- colors, and then some recipes using more specific colors for a few non-base
-- colors available. When crafting, the last recipes will be checked first.
--add new block using texture name(without "scifi_nodes_" prefix) then the description, and then the name of the block
node.types = {
{"blue", "blue lines", "blue"},
{"holes", "metal with holes","holes"},
{"white2", "plastic", "white2"},
{"super_white", "Super Plastic", "super_white", 11},
{"ultra_white", "Ultra Plastic", "ultra_white", default.LIGHT_MAX},
{"engine", "engine", "engine"},
{"wall", "metal wall", "wall"},
{"white", "plastic wall", "white"},
{"stripes2top", "dirty metal block","metal2"},
{"rough", "rough metal", "rough"},
{"lighttop", "metal block", "metal"},
{"red", "red lines", "red"},
{"green", "green lines", "green"},
{"vent2", "vent", "vent"},
{"stripes", "hazard stripes", "stripes"},
{"rust", "rusty metal", "rust"},
{"mesh", "metal mesh", "mesh"},
{"black", "black wall", "black"},
{"blackoct", "black octagon", "blackoct"},
{"blackpipe", "black pipe", "blackpipe"},
{"blacktile", "black tile", "blktl"},
{"blacktile2", "black tile 2", "blktl2"},
{"blackvent", "black vent", "blkvnt"},
{"bluebars", "blue bars", "bluebars"},
{"bluemetal", "blue metal", "blumtl"},
{"bluetile", "blue tile", "blutl"},
{"greytile", "grey tile", "grytl"},
{"mesh2", "metal floormesh", "mesh2"},
{"white", "plastic wall", "white"},
{"pipe", "wall pipe", "pipe2"},
{"pipeside", "side pipe", "pipe3"},
{"tile", "white tile", "tile"},
{"whiteoct", "white octagon", "whiteoct"},
{"whitetile", "white tile2", "whttl"},
{"black_detail", "black detail", "blckdtl"},
{"green_square", "green metal block", "grnblck"},
{"red_square", "red metal block", "redblck"},
{"grey_square", "grey metal block", "greyblck"},
{"blue_square", "blue metal block", "blublck"},
{"black_mesh", "black vent block", "blckmsh"},
{"dent", "dented metal block", "dent"},
{"greenmetal", "green metal wall", "grnmetl"},
{"greenmetal2", "green metal wall2", "grnmetl2"},
{"greenlights", "green wall lights", "grnlt", 10},
{"greenlights2", "green wall lights2", "grnlt2", 10},
{"greenbar", "green light bar", "grnlghtbr", 10},
{"green2", "green wall panel", "grn2"},
{"greentubes", "green pipes", "grntubes"},
{"grey", "grey wall", "gry"},
{"greybolts", "grey wall bolts", "gryblts"},
{"greybars", "grey bars", "grybrs"},
{"greydots", "grey wall dots", "grydts"},
{"greygreenbar", "gray power pipe", "grygrnbr", 10},
{"octofloor", "Doom floor", "octofloor"},
{"octofloor2", "Brown Doom floor", "octofloor2"},
{"doomwall1", "Doom wall 1", "doomwall1"},
{"doomwall2", "Doom wall 2", "doomwall2"},
{"doomwall3", "Doom wall 3", "doomwall3"},
{"doomwall4", "Doom wall 4", "doomwall4"},
{"doomwall41", "Doom wall 4.1", "doomwall4.1"},
{"doomwall42", "Doom wall 4.2", "doomwall4.2"},
{"doomwall43", "Doom wall 4.3", "doomwall4.3"},
{"doomwall431", "Doom wall 4.3.1", "doomwall4.3.1"},
{"doomwall44", "Doom wall 4.4", "doomwall4.4"},
{"blackdmg", "Damaged black wall", "blckdmg"},
{"blackdmgstripe", "Damaged black wall(stripes)", "blckdmgstripe"},
{"doomengine", "Doom engine wall", "doomengine"},
{"monitorwall", "Wall monitors", "monitorwall"},
{"screen3", "Wall monitor", "screen3"},
{"doomlight", "Doom light", "doomlight", 12},
{"bluwllight", "Blue wall light", "capsule3", default.LIGHT_MAX},
{"bluegrid", "Blue Grid", "bluegrid", 5},
{"fan", "Fan", "fan"},
{"ppllght", "Purple wall light", "", default.LIGHT_MAX},
{"pplwll", "Purple wall", "", 0},
{"pplwll2", "Purple wall2", "", 0},
{"pplwll3", "Purple wall3", "", 0},
{"pplwll4", "Purple wall4", "", 0},
{"pplblk", "Purple tile", "", 0},
{"purple", "Purple node", "", 0},
{"rock", "Moonstone", "", 0},
{"rock2", "Moonstone2", "", 0},
{"blackvnt", "Black vent", "", 0},
{"blackplate", "Black plate", "", 0},
}
for _, row in ipairs(node.types) do
local name = row[1]
local desc = row[2]
local light = row[4]
-- Node Definition
minetest.register_node("scifi_nodes:"..name, {
description = desc,
tiles = {"scifi_nodes_"..name..".png"},
groups = {cracky=1},
paramtype = "light",
paramtype2 = "facedir",
light_source = light,
})
end
node.plants = {
{"flower1", "Glow Flower", 1,0, default.LIGHT_MAX},
{"flower2", "Pink Flower", 1.5,0, 10},
{"flower3", "Triffid", 2,5, 0},
{"flower4", "Weeping flower", 1.5,0, 0},
{"plant1", "Bulb Plant", 1,0, 0},
{"plant2", "Trap Plant", 1.5,0, default.LIGHT_MAX},
{"plant3", "Blue Jelly Plant", 1.2,0, 10},
{"plant4", "Green Jelly Plant", 1.2,0, 10},
{"plant5", "Fern Plant", 1.7,0, 0},
{"plant6", "Curly Plant", 1,0, 10},
{"plant7", "Egg weed", 1,0, 0},
{"plant8", "Slug weed", 1,0, 10},
{"plant9", "Prickly Plant", 1,0, 0},
{"plant10", "Umbrella weed", 1,0, 10},
{"eyetree", "Eye Tree", 2.5,0, 0},
{"grass", "Alien Grass", 1,0, 0},
}
for _, row in ipairs(node.plants) do
local name = row[1]
local desc = row[2]
local size = row[3]
local dmg = row[4]
local light = row[5]
-- Node Definition
minetest.register_node("scifi_nodes:"..name, {
description = desc,
tiles = {"scifi_nodes_"..name..".png"},
drawtype = "plantlike",
inventory_image = {"scifi_nodes_"..name..".png"},
groups = {snappy=1, oddly_breakable_by_hand=1, dig_immediate=3, flora=1},
paramtype = "light",
visual_scale = size,
buildable_to = true,
walkable = false,
damage_per_second = dmg,
selection_box = {
type = "fixed",
fixed = {
{-0.3, -0.5, -0.3, 0.3, 0.5, 0.3},
}
},
is_ground_content = false,
light_source = light,
})
end
--chest code from default(Copyright (C) 2012 celeron55, Perttu Ahola <[email protected]>)
local chest_formspec =
"size[8,9]" ..
default.gui_bg ..
default.gui_bg_img ..
default.gui_slots ..
"list[current_name;main;0,0.3;8,4;]" ..
"list[current_player;main;0,4.85;8,1;]" ..
"list[current_player;main;0,6.08;8,3;8]" ..
"listring[current_name;main]" ..
"listring[current_player;main]" ..
default.get_hotbar_bg(0,4.85)
local function get_locked_chest_formspec(pos)
local spos = pos.x .. "," .. pos.y .. "," .. pos.z
local formspec =
"size[8,9]" ..
default.gui_bg ..
default.gui_bg_img ..
default.gui_slots ..
"list[nodemeta:" .. spos .. ";main;0,0.3;8,4;]" ..
"list[current_player;main;0,4.85;8,1;]" ..
"list[current_player;main;0,6.08;8,3;8]" ..
"listring[nodemeta:" .. spos .. ";main]" ..
"listring[current_player;main]" ..
default.get_hotbar_bg(0,4.85)
return formspec
end
-- Helper functions
local function drop_chest_stuff()
return function(pos, oldnode, oldmetadata, digger)
local meta = minetest.get_meta(pos)
meta:from_table(oldmetadata)
local inv = meta:get_inventory()
for i = 1, inv:get_size("main") do
local stack = inv:get_stack("main", i)
if not stack:is_empty() then
local p = {
x = pos.x + math.random(0, 5)/5 - 0.5,
y = pos.y,
z = pos.z + math.random(0, 5)/5 - 0.5}
minetest.add_item(p, stack)
end
end
end
end
--chest code Copyright (C) 2011-2012 celeron55, Perttu Ahola <[email protected]>
minetest.register_node("scifi_nodes:crate", {
description = "Crate",
tiles = {"scifi_nodes_crate.png"},
paramtype2 = "facedir",
groups = {cracky = 1, oddly_breakable_by_hand = 2, fuel = 8},
legacy_facedir_simple = true,
is_ground_content = false,
sounds = default.node_sound_wood_defaults(),
after_dig_node = drop_chest_stuff(),
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec", chest_formspec)
meta:set_string("infotext", "Crate")
local inv = meta:get_inventory()
inv:set_size("main", 8 * 4)
end,
on_metadata_inventory_move = function(pos, from_list, from_index,
to_list, to_index, count, player)
minetest.log("action", player:get_player_name() ..
" moves stuff in chest at " .. minetest.pos_to_string(pos))
end,
on_metadata_inventory_put = function(pos, listname, index, stack, player)
minetest.log("action", player:get_player_name() ..
" moves stuff to chest at " .. minetest.pos_to_string(pos))
end,
on_metadata_inventory_take = function(pos, listname, index, stack, player)
minetest.log("action", player:get_player_name() ..
" takes stuff from chest at " .. minetest.pos_to_string(pos))
end,
})
minetest.register_node("scifi_nodes:box", {
description = "Storage box",
tiles = {
"scifi_nodes_box_top.png",
"scifi_nodes_box_top.png",
"scifi_nodes_box.png",
"scifi_nodes_box.png",
"scifi_nodes_box.png",
"scifi_nodes_box.png"
},
paramtype2 = "facedir",
groups = {cracky = 1},
legacy_facedir_simple = true,
is_ground_content = false,
sounds = default.node_sound_metal_defaults(),
after_dig_node = drop_chest_stuff(),
on_construct = function(pos)
local meta = minetest.get_meta(pos)
meta:set_string("formspec", chest_formspec)
meta:set_string("infotext", "Box")
local inv = meta:get_inventory()
inv:set_size("main", 8 * 4)
end,
on_metadata_inventory_move = function(pos, from_list, from_index,
to_list, to_index, count, player)
minetest.log("action", player:get_player_name() ..
" moves stuff in chest at " .. minetest.pos_to_string(pos))
end,
on_metadata_inventory_put = function(pos, listname, index, stack, player)
minetest.log("action", player:get_player_name() ..
" moves stuff to chest at " .. minetest.pos_to_string(pos))
end,
on_metadata_inventory_take = function(pos, listname, index, stack, player)
minetest.log("action", player:get_player_name() ..
" takes stuff from chest at " .. minetest.pos_to_string(pos))
end,
})
--end of chest code
minetest.register_node("scifi_nodes:blumetlight", {
description = "blue metal light",
sunlight_propagates = false,
tiles = {
"scifi_nodes_bluemetal.png",
"scifi_nodes_bluemetal.png",
"scifi_nodes_blue_metal_light.png",
"scifi_nodes_blue_metal_light.png",
"scifi_nodes_blue_metal_light.png",
"scifi_nodes_blue_metal_light.png"
},
light_source = 10,
paramtype = "light",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:lightstp", {
description = "twin lights",
sunlight_propagates = false,
tiles = {
"scifi_nodes_lightstripe.png"
},
light_source = default.LIGHT_MAX,
paramtype = "light",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:blklt2", {
description = "black stripe light",
sunlight_propagates = false,
tiles = {
"scifi_nodes_black_light2.png"
},
light_source = 10,
paramtype = "light",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:blumetstr", {
description = "blue stripe light",
sunlight_propagates = false,
tiles = {
"scifi_nodes_blue_metal_stripes2.png"
},
light_source = 10,
paramtype = "light",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:glass", {
description = "dark glass",
drawtype = "glasslike",
sunlight_propagates = false,
tiles = {
"scifi_nodes_glass.png"
},
use_texture_alpha = true,
paramtype = "light",
groups = {cracky=1}
})
minetest.register_node("scifi_nodes:whtlightbnd", {
description = "white light stripe",
sunlight_propagates = false,
tiles = {
"scifi_nodes_lightband.png"
},
light_source = 10,
paramtype = "light",
groups = {cracky=1}
})
--extra stuff
local xpane = minetest.get_modnames()
if xpane == xpane then
dofile(minetest.get_modpath("scifi_nodes").."/panes.lua")
end
dofile(minetest.get_modpath("scifi_nodes").."/doors.lua")
dofile(minetest.get_modpath("scifi_nodes").."/nodeboxes.lua")
dofile(minetest.get_modpath("scifi_nodes").."/models.lua")
dofile(minetest.get_modpath("scifi_nodes").."/crafts.lua")
|
local API_NPC = require(script:GetCustomProperty("API_NPC"))
local API_DS = require(script:GetCustomProperty("APIDifficultySystem"))
local EFFECT_TEMPLATE = script:GetCustomProperty("EffectTemplate")
local TELEGRAPH_TEMPLATE = script:GetCustomProperty("TelegraphTemplate")
local WHIRL_RANGES = {180.0, 200.0, 250.0, 300.0}
local DAMAGE_DELAY = 2.0
function OnTaskStart(npc, animatedMesh)
local telegraphScale = Vector3.New(WHIRL_RANGES[API_DS.GetDifficultyLevel()] / 100.0)
local telegraph = World.SpawnAsset(TELEGRAPH_TEMPLATE, {parent = npc, scale = telegraphScale})
animatedMesh:PlayAnimation("1hand_melee_thrust")
Task.Spawn(function()
Task.Wait(DAMAGE_DELAY)
telegraph:Destroy()
end)
end
function OnTaskEnd(npc, animatedMesh, interrupted)
animatedMesh:StopAnimations()
end
API_NPC.RegisterTaskClient("swampwarrior_whirl", EFFECT_TEMPLATE, OnTaskStart, OnTaskEnd)
|
--配置管理
local log = require("base/log")
function Init(self, path, callback)
log:Info("InitModule:setting, %s", path)
self.m_Data = {}
self.m_Callback = callback
self:LoadSetting(path)
end
function LoadSetting(self, path)
local req = uv.fs_scandir(path)
if not req then
return self:LoadFinish()
end
local function iter()
return uv.fs_scandir_next(req)
end
for entry in iter do
local fullName = path .. "/" .. entry.name
if entry.type then
local pos = string.rfind(entry.name, "%.")
if not pos then return end
local name = string.sub(entry.name, 1, pos-1)
local ext = string.sub(entry.name, pos, #entry.name)
if ext ~= ".lua" then return end
local value = dofile(fullName)
if type(value) == "table" then
table.readonly(value)
end
self.m_Data[name] = value
else
self:LoadSetting(fullName)
end
end
self:LoadFinish()
end
function LoadFinish(self)
if not self.m_Callback then return end
local func = self.m_Callback
self.m_Callback = nil
func()
end
--查询配置,File:文件名
--类似:Query("const", "sex")
function Query(self, file, ...)
local result = self.m_Data[file]
if not result then return end
local ret = result
for _, key in ipairs({...}) do
ret = ret[key]
if not ret then return end
end
return ret
end
|
require "player"
require "blip"
updateList = {}
function wait(sec, blip)
local time = love.timer.getTime() + sec + 0.02 -- Sem o 0.02 os blips 2 e 3 ficavam sincronizados(não sei se apenas no meu computador)
local newUpdate = {time, blip}
table.insert(updateList, newUpdate)
coroutine.yield()
end
function love.keypressed(key)
if key == 'a' then
pos = player.getX()
for i in ipairs(listabls) do
local hit = listabls[i].affected(pos)
if hit then
table.remove(listabls, i) -- esse blip "morre"
return -- assumo que apenas um blip morre
end
end
end
end
function love.load()
player = newplayer()
listabls = {}
for i = 1, 5 do
listabls[i] = newblip(i)
listabls[i]:update()
end
end
function love.draw()
player.draw()
for i = 1,#listabls do
listabls[i].draw()
end
end
function love.update(dt)
player.update(dt)
local time = love.timer.getTime()
local i = 1
local size = #updateList
while(i <= size) do
if(time >= updateList[i][1]) then
updateList[i][2]:update()
table.remove(updateList, i)
size = size - 1
else
i = i + 1
end
end
end
|
local PANEL = {}
local MIN_X, MIN_Y = 800, 600
function PANEL:Init()
self:SetSize(MIN_X, MIN_Y)
self.modelview = vgui.Create('DModelPanel', self)
self.modelview:SetSize(80, 80)
self.modelview:SetPos(20, 30)
self.modelview:SetModel( "models/missiles/bgm_71e.mdl" )
self.modelview.LayoutEntity = function() end
self.modelview:SetFOV( 45 )
local viewent = self.modelview:GetEntity()
local boundmin, boundmax = viewent:GetRenderBounds()
local dist = boundmin:Distance(boundmax)*1.1
local centre = boundmin + (boundmax - boundmin)/2
self.modelview:SetCamPos( centre + Vector( 0, dist, 0 ) )
self.modelview:SetLookAt( centre )
//*
self.close = vgui.Create('DButton', self)
self.close:SetSize(40, 15)
//self.close:SizeToContents()
self.close:SetPos(580, 440)
self.close:SetText('Close')
self.close.DoClick = function() self:Close() end
//*/
self.html = vgui.Create('DHTML', self)
self.html:SetSize(450, 400)
self.html:SetPos(120, 30)
self.html:SetHTML("Fetching Info....")
self.tree = vgui.Create('DTree', self)
self.tree:SetSize(80, 230)
self.tree:SetPos(20, 200)
self:SetVisible(true)
self:Center()
self:SetSizable(true)
self:SetTitle("")
self:MakePopup()
self:ShowCloseButton(false)
self:SetDeleteOnClose(false)
self:InvalidateLayout()
end
function PANEL:SetText(txt)
self.html:SetHTML('<body bgcolor="#f0f0f0"><font face="Helvetica" color="#0f0f0f">' .. txt .. "</font></body>")
end
function PANEL:SetList(HTML, startpage, groups, modelassocs) //TODO: groups, modelassocs
self.tree:Clear()
if not HTML or table.Count(HTML) < 1 then
self:SetText("Failed to load the ACF Missiles Wiki. If this continues, please inform us at https://github.com/Bubbus/ACF-Missiles")
return
end
for k,v in pairsByKeys(HTML) do
local node = self.tree:AddNode(k)
node.DoClick = function()
self.html:SetHTML(v)
end
if k == startpage then
self.html:SetHTML(v)
end
end
end
function PANEL:PerformLayout()
local x, y = self:GetSize()
if x < MIN_X then
x = MIN_X
self:SetWide(MIN_X)
end
if y < MIN_Y then
y = MIN_Y
self:SetTall(MIN_Y)
end
local initWide, initTall, padding = 10, 30, 10
local wide, tall = initWide, initTall
local sidebarWide = 160
self.close:SetPos(x - (self.close:GetWide() + 3), 3)
//self.close:SetWide(self.html:GetWide())
self.modelview:SetPos(wide, tall)
self.modelview:SetWide(sidebarWide)
tall = tall + self.modelview:GetTall() + padding
self.tree:SetPos(wide, tall)
self.tree:SetSize(sidebarWide, y - (tall + padding))
//tall = tall + self.tree:GetTall() + padding
tall = initTall
wide = wide + sidebarWide + padding
self.html:SetPos(wide, tall)
self.html:SetSize(x - (wide + padding), y - (tall + padding))
end
derma.DefineControl( "ACFMissile_Wiki", "Wiki for ACF Missiles", PANEL, "DFrame" )
|
-- foo.server.lua |
--[[
Okazjonalnie uzywany zasob do przeprowadzania wyborów w ekipie
@author Lukasz Biegaj <[email protected]>
@author Karer <[email protected]>
@author WUBE <[email protected]>
@copyright 2011-2013 Lukasz Biegaj <[email protected]>
@license Dual GPLv2/MIT
@package MTA-XyzzyRP
@link https://github.com/lpiob/MTA-XyzzyRP GitHub
]]--
local ID_WYBOROW=5
local M_GLOSOW=3
local D=3
local I=121
local cs=createColSphere(985.61,-2150.13,28.03,2)
setElementDimension(cs,D)
setElementInterior(cs,I)
setElementData(cs,"wybory_cs",true)
local function hasPlayerVoteEnded(dbid)
local q = string.format("SELECT COUNT(*) ilosc FROM psz_wybory WHERE id_wyborow=%d AND player_id=%d;",ID_WYBOROW,dbid)
local dane = exports['psz-mysql']:pobierzWyniki(q)
if (dane.ilosc>= M_GLOSOW) then return true end
return false
end
local function checkDoubleVotes(dbid, u_dbid)
local q = string.format("SELECT 1 FROM psz_wybory WHERE id_wyborow=%d AND player_id=%d AND wybor=%d",ID_WYBOROW,dbid,u_dbid)
local dane = exports['psz-mysql']:pobierzWyniki(q)
if (dane) then return true end
return false
end
addEventHandler("onColShapeHit", cs, function(el,md)
if not md then return end
if getElementType(el)~="player" then return end
if (not getElementData(source,"wybory_cs")) then return end
local level = getElementData(el,"level") or 0
if (level and level<1) then return end
local dbid = getElementData(el,"auth:uid") or 0
if (dbid and dbid<1) then return end
if (hasPlayerVoteEnded(dbid)) then
outputChatBox("Nie możesz oddać już więcej głosów.",el,255,0,0)
return
end
local q = string.format("SELECT COUNT(*) ilosc FROM psz_wybory WHERE id_wyborow=%d AND player_id=%d;",ID_WYBOROW,dbid)
local ilosc = exports['psz-mysql']:pobierzWyniki(q)
local dane = exports['psz-mysql']:pobierzTabeleWynikow("SELECT wp.user_id, wp.serial,wp.description,p.nick FROM psz_wybory_podania wp JOIN psz_postacie p ON p.userid=wp.user_id")
triggerClientEvent(el,"onKartaDoGlosowania",resourceRoot, dane,ilosc.ilosc)
end)
addEvent("onAdminReceiveVote",true)
addEventHandler("onAdminReceiveVote",resourceRoot, function(u_id)
if (not u_id) then return end
local dbid = getElementData(client,"auth:uid")
if (not dbid) then return end
local q = string.format("SELECT COUNT(*) ilosc FROM psz_wybory WHERE id_wyborow=%d AND player_id=%d;",ID_WYBOROW,dbid)
local ilosc = exports['psz-mysql']:pobierzWyniki(q)
if (ilosc and ilosc.ilosc>=M_GLOSOW) then
outputChatBox("NIe możesz oddać więcej głosów.", client, 255,0,0)
return
end
if (checkDoubleVotes(dbid,u_id)) then
outputChatBox("Oddałeś już głos na tą osobę, musisz wybrać inną.",client,255,0,0)
return
end
exports['psz-mysql']:zapytanie(string.format("INSERT INTO psz_wybory SET id_wyborow=%d, player_id=%d, wybor=%d,ts=NOW()",ID_WYBOROW, dbid, u_id))
outputChatBox("Głos został zarejestrowany!",client,255,0,0)
end)
local ped=createPed(54,985.61,-2150.13,28.03,90, false)
setElementInterior(ped, I)
setElementDimension(ped, D)
setElementFrozen(ped, true)
setElementData(ped, "npc", true)
setElementData(ped,"name","Pracownik")
local text = createElement("ctext")
setElementPosition(text,2174.95,-1783.77,1423.33)
setElementData(text,"ctext","Głosowania")
setElementData(text,"scale",2)
setElementInterior(text,I)
setElementDimension(text,D) |
local abs = assert(math.abs)
local M = {}
-- See: http://love2d.org/wiki/HSL_color
function M.hslToRgb(h, s, l)
if s <= 0 then
return l, l, l
end
h, s, l = h * 6, s, l
local c = (1 - abs(2 * l - 1)) * s
local x = (1 - abs(h % 2 - 1)) * c
local m, r, g, b = (l - 0.5 * c), 0, 0, 0
if h < 1 then
r, g, b = c, x, 0
elseif h < 2 then
r, g, b = x, c, 0
elseif h < 3 then
r, g, b = 0, c, x
elseif h < 4 then
r, g, b = 0, x, c
elseif h < 5 then
r, g, b = x, 0, c
else
r, g, b = c, 0, x
end
return r + m, g + m, b + m
end
return M
|
local po = require("po")
local u = require("luaunit")
function test_Message_new()
local msg = po.Message:new(13)
u.assertEquals(msg.id, 13)
u.assertEquals(#msg.comments, 0)
u.assertEquals(msg.fuzzy, false)
u.assertEquals(msg.msgid, nil)
u.assertEquals(msg.msgstr, nil)
u.assertEquals(msg.raw, "")
end
function test_Message_format()
local msg = po.Message:new(13)
msg.msgid = ""
u.assertEquals(msg:format(), "msgid \"\"\n")
table.insert(msg.comments, "#,fuzzy")
msg.msgid = "hello\"\n"
msg.msgstr = "hallo\"\n"
u.assertEquals(msg:format(), [[
#,fuzzy
msgid "hello\"\n"
msgstr "hallo\"\n"
]])
end
function test_File_parse()
local file = po.File:new()
file:parse({
"# header comment",
"msgid \"hello, world\"",
"msgstr \"Hallo, Welt\"",
})
u.assertEquals(#file.messages, 1)
u.assertEquals(file.messages[1].msgid, "hello, world")
u.assertEquals(file.messages[1].msgstr, "Hallo, Welt")
end
function test_formatLine()
local formatLine = po.visibleForTesting.formatLine
local function assertFormatted(name, value, lines)
u.assertEquals(formatLine(name, value), table.concat(lines, "\n") .. "\n")
end
assertFormatted("msgfmt", "", {[[msgfmt ""]]})
assertFormatted("msgfmt", "hello", {[[msgfmt "hello"]]})
assertFormatted("msgfmt", "1\n2", {[[msgfmt ""]], [["1\n"]], [["2"]]})
assertFormatted("msgfmt", ("901234567 "):rep(10), {[[msgfmt ""]], [["901234567 901234567 901234567 901234567 901234567 901234567 901234567 "]], [["901234567 901234567 901234567 "]]})
end
os.exit(u.LuaUnit.run() == 0)
|
local Colors = require "colors"
local Bricks = require "bricks"
local setup = require "setup"
function love.load(arg)
setup()
end
function love.update(dt)
-- body...
end
function love.draw()
love.graphics.setColor(Colors.unpack(COLOR.background))
love.graphics.rectangle("fill", 0, 0, WIN_W, WIN_H)
love.graphics.setColor(Colors.unpack(COLOR.vazio))
love.graphics.rectangle("fill", -(GRID_W*TILE_W-WIN_W)/2, -(GRID_H*TILE_H-WIN_H)/2, GRID_W*TILE_W, GRID_H*TILE_H)
Bricks.draw_brick("t", 10, 10)
end
|
------------------------TCP CLIENT----------------------------
local moon = require("moon")
local socket = require("moon.net.socket")
local function send(session,data)
if not session then
return false
end
local len = #data
return session:send(string.pack(">H",len)..data)
end
local function session_read( session )
if not session then
return false
end
local data,err = session:co_read(2)
if not data then
print(session.connid,"session read error",err)
return false
end
local len = string.unpack(">H",data)
data,err = session:co_read(len)
if not data then
print(session.connid,"session read error",err)
return false
end
return data
end
local config
moon.init(function (cfg )
config = cfg.network
return true
end)
moon.start(function()
local sock = socket.new()
moon.async(function( )
local session,err = sock:co_connect(config.ip,config.port)
if not session then
print("connect failed", err)
return
end
moon.async(function ()
print("Please input:")
repeat
local input = io.read()
if input then
send(session, input)
local rdata = session_read(session)
print("recv", rdata)
end
until(not input)
end)
end)
end) |
NPC.PureName = "Announcer"
NPC.LevelFile = "goldenrod.dat"
NPC.Facing = 3
NPC.Position = Vector3(9, 0, 22)
NPC.Skin = "20"
NPC.PokemonVisible = false
local ClientExtraData = {}
local Tournament = {}
Tournament.Name = "Shitarment"
--[[---------------------------------------------------------
Name: Update
Desc: Function that is called a lot.
-----------------------------------------------------------]]
function Update ()
end
hook.Add ("Update", "Announcer_Update", Update)
--[[---------------------------------------------------------
Name: Update2
Desc: Function that is called every second.
-----------------------------------------------------------]]
function Update2()
local clients = NPC:GetLocalPlayers ()
for i=1, #clients do
local client = clients[i]
if not ClientExtraData[client.ID] then ClientExtraData[client.ID] = { } end
local extraData = ClientExtraData[client.ID]
if ClientIsNear (client) then
if not extraData.ChatInitialized then
NPC:SayPlayerPM(client, translator.AdvTranslate(client, "Greetings", { name = client.Name }))
extraData.ChatInitialized = true
end
else
extraData.ChatInitialized = false
end
end
end
hook.Add ("Update2", "Announcer_Update2", Update2)
--[[---------------------------------------------------------
Name: ClientIsNear
Args: IClient client
Desc: Checks if the client is near NPC (2 blocks).
-----------------------------------------------------------]]
function ClientIsNear(client)
if client.Position:DistanceTo(NPC.Position) < 2 then
return true
else
return false
end
end
--[[---------------------------------------------------------
Name: Update2
Desc: Function that is called every second.
-----------------------------------------------------------]]
function PrivateMessage (client, message)
if message == "/tournament" and (not ClientExtraData[client.ID].TournamentRequest or ClientExtraData[client.ID].TournamentRequest == "no") then
NPC:SayPlayerPM (client, translator.AdvTranslate (client, "Tournament1", { name = Tournament.Name }))
ClientExtraData[client.ID].TournamentRequest = "waiting"
end
if message == "yes" or message == "yep" and (not ClientExtraData[client.ID].TournamentRequest or ClientExtraData[client.ID].TournamentRequest == "waiting") then
NPC:SayPlayerPM (client, translator.AdvTranslate (client, "Tournament2", { name = Tournament.Name }))
ClientExtraData[client.ID].TournamentRequest = "yes"
end
if message == "no" or message == "nope" and (not ClientExtraData[client.ID].TournamentRequest or ClientExtraData[client.ID].TournamentRequest == "waiting") then
NPC:SayPlayerPM (client, translator.AdvTranslate (client, "Tournament3", { name = Tournament.Name }))
ClientExtraData[client.ID].TournamentRequest = "no"
end
if message == "hi" or message == "hai" or message == "hello" then
NPC:SayPlayerPM (client, translator.AdvTranslate(client, "Greetings", { name = client.Name }))
end
if string.find(message, "/move") then
local tFinal = {}
message:gsub("%d+", function(i) table.insert(tFinal, i) end)
local x = tFinal[1]
local y = tFinal[2]
local z = tFinal[3]
NPC.Position = Vector3(tonumber(x), tonumber(y), tonumber(z))
end
end
hook.Add ("PrivateMessage", "Announcer_PrivateMessage", PrivateMessage) |
-- nvim-hardline
-- By Olivier Roques
-- github.com/ojroques
-------------------- VARIABLES -----------------------------
local fn, cmd, vim = vim.fn, vim.cmd, vim
local g, o, wo = vim.g, vim.o, vim.wo
local fmt = string.format
local common = require('hardline.common')
local bufferline = require('hardline.bufferline')
local custom_colors = require('hardline.themes.custom_colors')
local M = {}
-------------------- OPTIONS -------------------------------
M.options = {
bufferline = false,
bufferline_settings = {
exclude_terminal = false,
show_index = false,
separator = '|',
},
theme = 'default',
custom_theme = {
text = {gui = "NONE", cterm = "NONE", cterm16 = "NONE"},
normal = {gui = "NONE", cterm = "NONE", cterm16 = "NONE"},
insert = {gui = "NONE", cterm = "NONE", cterm16 = "NONE"},
replace = {gui = "NONE", cterm = "NONE", cterm16 = "NONE"},
inactive_comment = {gui = "NONE", cterm = "NONE", cterm16 = "NONE"},
inactive_cursor = {gui = "NONE", cterm = "NONE", cterm16 = "NONE"},
inactive_menu = {gui = "NONE", cterm = "NONE", cterm16 = "NONE"},
visual = {gui = "NONE", cterm = "NONE", cterm16 = "NONE"},
command = {gui = "NONE", cterm = "NONE", cterm16 = "NONE"},
alt_text = {gui = "NONE", cterm = "NONE", cterm16 = "NONE"},
warning = {gui = "NONE", cterm = "NONE", cterm16 = "NONE"},
},
sections = {
{class = 'mode', item = require('hardline.parts.mode').get_item},
{class = 'high', item = require('hardline.parts.git').get_item, hide = 100},
{class = 'med', item = require('hardline.parts.filename').get_item},
'%<',
{class = 'med', item = '%='},
{class = 'low', item = require('hardline.parts.wordcount').get_item, hide = 100},
{class = 'error', item = require('hardline.parts.lsp').get_error},
{class = 'warning', item = require('hardline.parts.lsp').get_warning},
{class = 'warning', item = require('hardline.parts.whitespace').get_item},
{class = 'high', item = require('hardline.parts.filetype').get_item, hide = 80},
{class = 'mode', item = require('hardline.parts.line').get_item},
},
}
-------------------- SECTION CACHE -------------------------
local cache = {}
local function refresh_cache()
for winid, _ in pairs(cache) do
if fn.win_id2tabwin(winid) == {0, 0} then
cache[winid] = nil
end
end
end
-------------------- SECTION MANAGEMENT --------------------
local function aggregate_sections(sections)
local aggregated, piv = {}, 1
while piv <= #sections do
if type(sections[piv]) == 'table' then
local items = {}
for j = piv, #sections + 1 do
if j == #sections + 1 or sections[j].class ~= sections[piv].class then
table.insert(aggregated, {
class = sections[piv].class,
item = fmt(' %s ', table.concat(items, ' ')),
})
piv = j
break
end
table.insert(items, sections[j].item)
end
else
table.insert(aggregated, sections[piv])
piv = piv + 1
end
end
return aggregated
end
local function remove_empty_sections(sections)
local filter = function(section)
if type(section) == 'table' then
return section.item ~= ''
end
return section ~= ''
end
return vim.tbl_filter(filter, sections)
end
local function load_section(section)
if type(section) == 'string' then
return section
end
if type(section) == 'function' then
return section()
end
if type(section) == 'table' then
return {
class = section.class or 'none',
item = load_section(section.item),
}
end
common.echo('WarningMsg', 'Invalid section.')
return ''
end
local function load_sections(sections)
return vim.tbl_map(load_section, sections)
end
local function remove_hidden_sections(sections)
local filter = function(s)
return not s.hide or s.hide <= fn.winwidth(0)
end
return vim.tbl_filter(filter, sections)
end
-------------------- SECTION HIGHLIGHTING ------------------
local function get_section_state(section)
if section.class == 'mode' then
if common.is_active() then
local mode = common.modes[fn.mode()] or common.modes['?']
return mode.state
end
end
if section.class == 'bufferline' then
if section.separator then
return 'separator'
end
local state = section.current and 'current' or 'background'
if section.modified then
state = fmt('%s_modified', state)
end
return state
end
return common.is_active() and 'active' or 'inactive'
end
local function highlight_section(section)
if type(section) ~= 'table' then
return section
end
if section.class == 'none' then
return section.item
end
local state = get_section_state(section)
local hlgroup = fmt('Hardline_%s_%s', section.class, state)
if fn.hlexists(hlgroup) == 0 then
return section.item
end
return fmt('%%#%s#%s%%*', hlgroup, section.item)
end
local function highlight_sections(sections)
return vim.tbl_map(highlight_section, sections)
end
-------------------- STATUSLINE ----------------------------
function M.update_statusline()
local sections = cache[g.statusline_winid]
if common.is_active() or not sections then
sections = M.options.sections
sections = remove_hidden_sections(sections)
sections = load_sections(sections)
sections = remove_empty_sections(sections)
sections = aggregate_sections(sections)
cache[g.statusline_winid] = sections
refresh_cache()
end
return table.concat(highlight_sections(sections))
end
-------------------- BUFFERLINE ----------------------------
function M.update_bufferline()
local sections = {}
local settings = M.options.bufferline_settings
local buffers = bufferline.get_buffers(settings)
for i, buffer in ipairs(buffers) do
table.insert(sections, bufferline.to_section(buffer, i, settings))
if i < #buffers then
table.insert(sections, M.options.bufferline_settings.separator)
end
end
return table.concat(highlight_sections(sections))
end
-------------------- SETUP -----------------------------
local function set_theme()
if type(M.options.theme) ~= 'string' then
return
end
if M.options.theme == 'custom' then
M.options.theme = custom_colors.set(M.options.custom_theme)
else
local theme = fmt('hardline.themes.%s', M.options.theme)
M.options.theme = require(theme)
end
end
local function set_hlgroups()
for class, attr in pairs(M.options.theme) do
for state, args in pairs(attr) do
local hlgroup = fmt('Hardline_%s_%s', class, state)
local a = {}
for k, v in pairs(args) do
table.insert(a, fmt('%s=%s', k, v))
end
a = table.concat(a, ' ')
cmd(fmt('autocmd VimEnter,ColorScheme * hi %s %s', hlgroup, a))
end
end
end
local function set_statusline()
o.showmode = false
o.statusline = [[%!luaeval('require("hardline").update_statusline()')]]
wo.statusline = o.statusline
end
local function set_bufferline()
o.showtabline = 2
o.tabline = [[%!luaeval('require("hardline").update_bufferline()')]]
end
function M.setup(user_options)
if user_options then
M.options = vim.tbl_extend('force', M.options, user_options)
end
set_theme()
set_hlgroups()
set_statusline()
if M.options.bufferline then
set_bufferline()
end
end
------------------------------------------------------------
return M
|
--[[
# Copyright 2001-2014 Cisco Systems, Inc. and/or its affiliates. All rights
# reserved.
#
# This file contains proprietary Detector Content created by Cisco Systems,
# Inc. or its affiliates ("Cisco") and is distributed under the GNU General
# Public License, v2 (the "GPL"). This file may also include Detector Content
# contributed by third parties. Third party contributors are identified in the
# "authors" file. The Detector Content created by Cisco is owned by, and
# remains the property of, Cisco. Detector Content from third party
# contributors is owned by, and remains the property of, such third parties and
# is distributed under the GPL. The term "Detector Content" means specifically
# formulated patterns and logic to identify applications based on network
# traffic characteristics, comprised of instructions in source code or object
# code form (including the structure, sequence, organization, and syntax
# thereof), and all documentation related thereto that have been officially
# approved by Cisco. Modifications are considered part of the Detector
# Content.
--]]
--[[
detection_name: KAD
version: 4
description: P2P network that uses the Kademlia algorithm.
--]]
require "DetectorCommon"
local DC = DetectorCommon
local FT = flowTrackerModule
gServiceId = 20079
gServiceName = 'KAD'
gDetector = nil
DetectorPackageInfo = {
name = "KAD",
proto = DC.ipproto.udp,
server = {
init = 'DetectorInit',
validate = 'DetectorValidator',
}
}
gSfAppIdKad = 697
gPatterns = {
kad_req1 = { '\228\032', 0, gSfAppIdKad },
kad_req2 = { '\229\032', 0, gSfAppIdKad },
kad_res = { '\228\040', 0, gSfAppIdKad },
kad_hello_req = { '\228\016', 0, gSfAppIdKad },
kad_hello_res = { '\228\024', 0, gSfAppIdKad },
kad_firewalled_req = { '\228\080', 0, gSfAppIdKad },
kad_firewalled_res = { '\228\088', 0, gSfAppIdKad },
kad_publish_req = { '\228\064', 0, gSfAppIdKad },
kad_publish_res = { '\228\072', 0, gSfAppIdKad },
edonkey_searchfile_req = { '\227\152', 0, gSfAppIdKad },
edonkey_searchfile_res = { '\227\153', 0, gSfAppIdKad },
edonkey_server_status_req = { '\227\150', 0, gSfAppIdKad },
edonkey_server_status_res = { '\227\151', 0, gSfAppIdKad },
edonkey_server_info_req = { '\227\162', 0, gSfAppIdKad },
edonkey_server_info_res = { '\227\163', 0, gSfAppIdKad },
edonkey_unknown1_req = { '\227\014', 0, gSfAppIdKad },
edonkey_unknown1_res = { '\227\015', 0, gSfAppIdKad },
edonkey_unknown2_req = { '\227\012', 0, gSfAppIdKad },
edonkey_unknown2_res = { '\227\013', 0, gSfAppIdKad },
}
gFastPatterns = {
{DC.ipproto.udp, gPatterns.kad_req1},
{DC.ipproto.udp, gPatterns.kad_req2},
{DC.ipproto.udp, gPatterns.kad_res},
{DC.ipproto.udp, gPatterns.kad_hello_req},
{DC.ipproto.udp, gPatterns.kad_hello_res},
{DC.ipproto.udp, gPatterns.kad_firewalled_req},
{DC.ipproto.udp, gPatterns.kad_firewalled_res},
{DC.ipproto.udp, gPatterns.kad_publish_req},
{DC.ipproto.udp, gPatterns.kad_publish_res},
{DC.ipproto.udp, gPatterns.edonkey_searchfile_req},
{DC.ipproto.udp, gPatterns.edonkey_searchfile_res},
{DC.ipproto.udp, gPatterns.edonkey_server_status_req},
{DC.ipproto.udp, gPatterns.edonkey_server_status_res},
{DC.ipproto.udp, gPatterns.edonkey_server_info_req},
{DC.ipproto.udp, gPatterns.edonkey_server_info_res},
{DC.ipproto.udp, gPatterns.edonkey_unknown1_req},
{DC.ipproto.udp, gPatterns.edonkey_unknown1_res},
{DC.ipproto.udp, gPatterns.edonkey_unknown2_req},
{DC.ipproto.udp, gPatterns.edonkey_unknown2_res},
}
gPorts = {
}
client_protocol = nil
client_msg_type = nil
gAppRegistry = {
--AppIdValue Extracts Info
---------------------------------------
{gSfAppIdKad, 0}
}
function serviceInProcess(context)
local flowFlag = context.detectorFlow:getFlowFlag(DC.flowFlags.serviceDetected)
if ((not flowFlag) or (flowFlag == 0)) then
gDetector:inProcessService()
end
DC.printf('%s: Inprocess, packetCount: %d\n', gServiceName, context.packetCount);
return DC.serviceStatus.inProcess
end
function serviceSuccess(context)
local flowFlag = context.detectorFlow:getFlowFlag(DC.flowFlags.serviceDetected)
if ((not flowFlag) or (flowFlag == 0)) then
gDetector:addService(context.serviceid, "", "", gSfAppIdKad)
end
if (context.serviceid == kad_id) then
DC.printf('%s: Detected KAD, packetCount: %d\n', gServiceName, context.packetCount)
else
DC.printf('%s: Detected eDonkey, packetCount: %d\n', gServiceName, context.packetCount)
end
return DC.serviceStatus.success
end
function serviceFail(context)
local flowFlag = context.detectorFlow:getFlowFlag(DC.flowFlags.serviceDetected)
if ((not flowFlag) or (flowFlag == 0)) then
gDetector:failService()
end
context.detectorFlow:clearFlowFlag(DC.flowFlags.continue)
DC.printf('%s: Failed, packetCount: %d\n', gServiceName, context.packetCount);
return DC.serviceStatus.nomatch
end
function registerPortsPatterns()
--register port based detection
for i,v in ipairs(gPorts) do
gDetector:addPort(v[1], v[2])
end
--register pattern based detection
for i,v in ipairs(gFastPatterns) do
if ( gDetector:registerPattern(v[1], v[2][1], #v[2][1], v[2][2], v[2][3]) ~= 0) then
DC.printf ('%s: register pattern failed for %s\n', gServiceName,v[2][1])
else
DC.printf ('%s: register pattern successful for %s\n', gServiceName,v[2][1])
end
end
for i,v in ipairs(gAppRegistry) do
pcall(function () gDetector:registerAppId(v[1],v[2]) end)
end
end
--[[ Core engine calls DetectorInit() to initialize a detector.
--]]
function DetectorInit( detectorInstance)
gDetector = detectorInstance
DC.printf ('%s:DetectorInit()\n', gServiceName);
gDetector:init(gServiceName, 'DetectorValidator', 'DetectorFini')
kad_id = 20079
edonkey_id = 20080
registerPortsPatterns()
return gDetector
end
--[[Validator function registered in DetectorInit()
--]]
function DetectorValidator()
local context = {}
context.detectorFlow = gDetector:getFlow()
context.packetDataLen = gDetector:getPacketSize()
context.packetDir = gDetector:getPacketDir()
context.srcIp = gDetector:getPktSrcAddr()
context.dstIp = gDetector:getPktDstAddr()
context.srcPort = gDetector:getPktSrcPort()
context.dstPort = gDetector:getPktDstPort()
context.flowKey = context.detectorFlow:getFlowKey()
context.packetCount = gDetector:getPktCount()
local size = context.packetDataLen
local dir = context.packetDir
local srcPort = context.srcPort
local dstPort = context.dstPort
local flowKey = context.flowKey
context.serviceid = kad_id
DC.printf('%s: packetCount %d, dir %d, size %d\n', gServiceName,
context.packetCount, dir, size);
matched, flag_raw, msg_type = gDetector:getPcreGroups('(.)(.)', 0)
if (matched) then
flag_num = DC.binaryStringToNumber(flag_raw, 1)
msg_type_num = DC.binaryStringToNumber(msg_type, 1)
else
DC.printf("%s: couldn't match two bytes\n", gServiceName)
return serviceFail(context)
end
if (dir == 0) then
client_protocol = flag_num
client_msg_type = msg_type_num
DC.printf("client packet, proto %d msg type %d\n", client_protocol, client_msg_type)
return serviceInProcess(context)
elseif ((dir == 1) and
(client_protocol) and
(client_protocol == flag_num) and
(client_msg_type)) then
DC.printf("server packet, proto %d, msg type %d\n", flag_num, msg_type_num)
if ((client_protocol == 227) and
(client_msg_type == msg_type_num - 1)) then
DC.printf("its eDonkey\n")
context.serviceid = edonkey_id
return serviceSuccess(context)
end
if ((client_protocol == 228) and
(client_msg_type == msg_type_num - 8)) then
DC.printf("its KAD\n")
return serviceSuccess(context)
end
end
return serviceFail(context)
end
--[[Required DetectorFini function
--]]
function DetectorFini()
--print (gServiceName .. ': DetectorFini()')
end
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('XTemplate', {
group = "Infopanel Sections",
id = "ipColonist",
PlaceObj('XTemplateTemplate', {
'__context_of_kind', "Colonist",
'__template', "Infopanel",
'Description', T{10, --[[XTemplate ipColonist Description]] "<Description>"},
}, {
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelButton",
'RolloverDisabledText', T{8762, --[[XTemplate ipColonist RolloverDisabledText]] "Can't be assigned."},
'OnPressParam', "ToggleInteraction",
}),
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelButton",
'RolloverText', T{116030124982, --[[XTemplate ipColonist RolloverText]] "Selects the previous colonist in the group."},
'RolloverTitle', T{102770097492, --[[XTemplate ipColonist RolloverTitle]] "Previous Colonist"},
'Id', "idPrev",
'OnContextUpdate', function (self, context, ...)
InfopanelCycleUpdate(self:ResolveId("node"))
end,
'OnPress', function (self, gamepad)
local obj = self.context
if obj then
obj:CyclePrev(gamepad)
end
end,
'Icon', "UI/Icons/IPButtons/prev.tga",
}),
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelButton",
'RolloverText', T{232261691824, --[[XTemplate ipColonist RolloverText]] "Selects the next colonist in the group."},
'RolloverTitle', T{388769879592, --[[XTemplate ipColonist RolloverTitle]] "Next Colonist"},
'Id', "idNext",
'OnPress', function (self, gamepad)
local obj = self.context
if obj then
obj:CycleNext(gamepad)
end
end,
'Icon', "UI/Icons/IPButtons/next.tga",
}),
PlaceObj('XTemplateTemplate', {
'__condition', function (parent, context) return context:IsDying() end,
'__template', "InfopanelSection",
'RolloverText', T{4352, --[[XTemplate ipColonist RolloverText]] "The cause of death of this Colonist."},
'Title', T{4351, --[[XTemplate ipColonist Title]] "Cause of death"},
'Icon', "UI/Icons/Sections/colonist.tga",
}, {
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelText",
'HAlign', "center",
'Text', T{766618008675, --[[XTemplate ipColonist Text]] "<UIDeathReason>"},
}),
}),
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelSection",
'RolloverText', T{298540224971, --[[XTemplate ipColonist RolloverText]] "<UIInfo>"},
'Title', T{4290, --[[XTemplate ipColonist Title]] "Colonist"},
'Icon', "UI/Icons/Sections/colonist.tga",
}, {
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelText",
'Text', T{4358, --[[XTemplate ipColonist Text]] "Age Group<right><Age>"},
}),
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelText",
'Text', T{4359, --[[XTemplate ipColonist Text]] "Specialization<right><Specialization>"},
}),
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelText",
'Text', T{4360, --[[XTemplate ipColonist Text]] "Residence<right><h SelectResidence InfopanelSelect><ResidenceDisplayName></h>"},
}),
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelText",
'Text', T{213479829949, --[[XTemplate ipColonist Text]] "<UIWorkplaceLine>"},
}),
}),
PlaceObj('XTemplateForEach', {
'array', function (parent, context) return ColonistStatList end,
'run_after', function (child, context, item, i, n)
child.OnContextUpdate = function(self, context)
context:UIStatUpdate(self, item)
end
end,
}, {
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelSection",
}, {
PlaceObj('XTemplateWindow', {
'__class', "XFrameProgress",
'Id', "idBar",
'Margins', box(10, 15, 10, 14),
'FoldWhenHidden', true,
'Image', "UI/Infopanel/progress_bar.tga",
'FrameBox', box(5, 0, 5, 0),
'MinProgressSize', 8,
'ProgressImage', "UI/Infopanel/progress_bar_green.tga",
'ProgressFrameBox', box(4, 0, 4, 0),
}),
}),
}),
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelSection",
'RolloverText', T{100898279423, --[[XTemplate ipColonist RolloverText]] "<UITraitsRollover>"},
'Title', T{235, --[[XTemplate ipColonist Title]] "Traits"},
'Icon', "UI/Icons/Sections/colonist.tga",
}, {
PlaceObj('XTemplateTemplate', {
'__template', "InfopanelText",
'Text', T{868555682819, --[[XTemplate ipColonist Text]] "<UITraitsList>"},
}),
}),
PlaceObj('XTemplateTemplate', {
'__template', "sectionCheats",
}),
}),
})
|
loadLevel("data/Levels/TurretTest") |
--[[
# Copyright 2001-2014 Cisco Systems, Inc. and/or its affiliates. All rights
# reserved.
#
# This file contains proprietary Detector Content created by Cisco Systems,
# Inc. or its affiliates ("Cisco") and is distributed under the GNU General
# Public License, v2 (the "GPL"). This file may also include Detector Content
# contributed by third parties. Third party contributors are identified in the
# "authors" file. The Detector Content created by Cisco is owned by, and
# remains the property of, Cisco. Detector Content from third party
# contributors is owned by, and remains the property of, such third parties and
# is distributed under the GPL. The term "Detector Content" means specifically
# formulated patterns and logic to identify applications based on network
# traffic characteristics, comprised of instructions in source code or object
# code form (including the structure, sequence, organization, and syntax
# thereof), and all documentation related thereto that have been officially
# approved by Cisco. Modifications are considered part of the Detector
# Content.
--]]
--[[
detection_name: SSL Group "Styx"
version: 2
description: Group of SSL Host detectors.
bundle_description: $VAR1 = {
'Campfire' => 'Business-focused group messaging and enterprise social networking.',
'Postini' => 'A Google product that provides email security and archiving.',
'Zootool' => 'Bookmarking app with visual images.',
'Sony' => 'Official website for Sony Corporation.',
'Flickr' => 'An image hosting and video hosting website, web services suite, and online community.',
'Zapier' => 'Automatically sync the web apps.',
'Readability' => 'A browser plugin and mobile app that converts articles to a cleaner format.',
'WeTransfer' => 'Online file transferring platform.',
'App.net' => 'A site with many apps for various platforms.',
'Fifth Third Bank' => 'A bank.',
'Storify' => 'Collect media, create stories and publish on the any social network.'
};
--]]
require "DetectorCommon"
local DC = DetectorCommon
DetectorPackageInfo = {
name = "ssl_host_group_styx",
proto = DC.ipproto.tcp,
client = {
init = 'DetectorInit',
clean = 'DetectorClean',
minimum_matches = 1
}
}
--serviceId, clientId, ClientType, PayloadId, PayloadType, hostPattern, pathPattern, schemePattern, queryPattern
gSSLHostPatternList = {
-- Zapier
{ 0, 2206, 'zapier.com' },
-- Sony
{ 0, 2234, 'sony.com' },
-- Zootool
{ 0, 2235, 'zootool.com' },
-- WeTransfer
{ 0, 2236, 'wetransfer.com' },
-- Sorify
{ 0, 2237, 'storify.com' },
-- Readability
{ 0, 2243, 'readability.com' },
-- Postini
{ 0, 2244, 'login.postini.com' },
-- Fifth Third Bank
{ 0, 2257, 'www.53.com' },
-- Flickr
{ 0, 159, 'flickr.com'},
{ 0, 159, 'static.flickr.com' },
-- Campfire
{ 0, 2270, 'campfirenow.com'},
-- App.net
{ 0, 2286, 'app.net'},
}
function DetectorInit(detectorInstance)
gDetector = detectorInstance;
if gDetector.addSSLCertPattern then
for i,v in ipairs(gSSLHostPatternList) do
gDetector:addSSLCertPattern(v[1],v[2],v[3]);
end
end
return gDetector;
end
function DetectorClean()
end
|
require 'math'
local Point = require 'util'.point
local factory = require 'datafactory'
local function Tetromino(shape_type, board)
local self = {
board = board,
shape_type = shape_type,
position = Point(0, 0)
}
local _data = factory(shape_type)
local _rotation = 0
local property_getters = {
rotation = function()
return _rotation
end,
parts = function()
return _data[_rotation + 1].parts
end,
bounding_box = function()
return _data[_rotation + 1].bounding_box
end
}
local property_setters = {
rotation = function(value)
_rotation = value % #_data
end
}
local function can_push(delta)
return self.board.can_add_tetromino(self, self.position + delta);
end
local function try_push(delta)
local can_slide = can_push(delta)
if can_slide then
self.position = self.position + delta
end
return can_slide
end
function self.move_to_initial_pos()
board_width = self.board.size.width
tetromino_width = self.bounding_box.width
centered_tetromino_pos = math.ceil((board_width - tetromino_width) / 2.0)
return try_push(Point(centered_tetromino_pos, 0))
end
function self.rotate_right()
local old_rotation = self.rotation
self.rotation = old_rotation + 1
if can_push(Point(0, 0)) then
return true
end
for i = 1, self.bounding_box.width do
if try_push(Point(-i, 0)) then
return true
end
end
self.rotation = old_rotation
return false
end
function self.move_left()
return try_push(Point(-1, 0))
end
function self.move_down()
return try_push(Point(0, 1))
end
function self.move_right()
return try_push(Point(1, 0))
end
setmetatable(self, {
__index = function(obj, key)
local getter = property_getters[key]
if getter ~= nil then
return getter()
else
error('Field ' .. key .. ' does not exists.')
end
end,
__newindex = function(obj, key, value)
local setter = property_setters[key]
if setter ~= nil then
setter(value)
else
error('Field ' .. key .. ' does not exists.')
end
end
})
return self
end
return Tetromino |
-- hercelot - kit kat fat cat chat
-- clean up temporary vfx
level:clearevents({
'MoveRoom',
'ReorderRooms',
'FadeRoom',
'SetBackgroundColor',
'SetRoomContentMode',
'ShowStatusSign',
'TintRows'
})
level:setuprooms()
-- set row visibility
level.rows[2]:setvisibleatstart(false)
level.rows[3]:setvisibleatstart(false)
level.rows[4]:setvisibleatstart(false)
level.rows[5]:setvisibleatstart(false)
level.rows[6]:setvisibleatstart(false)
-- room 0
mainroom = level.rooms[0]
mainroom:settheme(0,'Kaleidoscope')
mainroom:move(0,{x=100,y=50,sx=0,sy=100})
-- room 1
introroom = level.rooms[1]
introroom:settheme(0,'InsomniacDay')
introroom:sepia(0)
introroom:vhs(0)
introroom:abberation(0,true,25)
introroom:move(0,{x=50,y=50,sx=100,sy=100})
level.rows[1]:setroom(0,1)
level:alloutline() -- give every row black outlines
-- at beat 9, change rooms
introroom:move(9,{x=0,y=50,sx=0,sy=100},2,'outExpo')
mainroom:move(9,{x=50,y=50,sx=100,sy=100},2,'outExpo')
|
local _2afile_2a = "fnl/conjure/bridge.fnl"
local _2amodule_name_2a = "conjure.bridge"
local _2amodule_2a
do
package.loaded[_2amodule_name_2a] = {}
_2amodule_2a = package.loaded[_2amodule_name_2a]
end
local _2amodule_locals_2a
do
_2amodule_2a["aniseed/locals"] = {}
_2amodule_locals_2a = (_2amodule_2a)["aniseed/locals"]
end
local function viml__3elua(m, f, opts)
return ("lua require('" .. m .. "')['" .. f .. "'](" .. ((opts and opts.args) or "") .. ")")
end
_2amodule_2a["viml->lua"] = viml__3elua
return _2amodule_2a |
return loadfile(THEME:GetPathB("Fade","In"))() |
Plugin.HasConfig = false
-- Plugin.ConfigName = "serverstart.json"
local md = TGNSMessageDisplayer.Create()
local serverStartTempfilePath = "config://tgns/temp/serverStart.json"
local NUMBER_OF_ACTIVE_MODS_INDICATIVE_OF_A_SERVER_RESTART = 15
local NUMBER_OF_PLAYERS_BEFORE_SCHEDULED_RESTART = 22
local NUMBER_OF_HOURS_SERVER_SEEMS_TO_SURVIVE_WITHOUT_CRASHING = 16 -- 2.5
local SERVER_COMMANDLINE_START_MAP_NAME = "dev_test"
function Plugin:ClientConfirmConnect(client)
end
function Plugin:CreateCommands()
local sh_loghttp = self:BindCommand( "sh_loghttp", nil, function(client)
TGNS.LogHttp = not TGNS.LogHttp
md:ToClientConsole(client, string.format("TGNS.LogHttp: %s", TGNS.LogHttp == true))
end)
sh_loghttp:Help( "Log HTTP requests for map duration. Expensive." )
local warnRestartCommand = self:BindCommand("sh_warnrestart", nil, function(client)
Shine.ScreenText.Add(41, {X = 0.5, Y = 0.35, Text = "Server restarting.\nPlease wait while\nyou reconnect\nautomatically.", Duration = 30, R = 0, G = 255, B = 0, Alignment = TGNS.ShineTextAlignmentCenter, Size = 3, FadeIn = 0, IgnoreFormat = true})
TGNS.DoFor(TGNS.GetPlayerList(), function(p)
TGNS.SendNetworkMessageToPlayer(p, self.RECONNECT, {})
end)
end)
warnRestartCommand:Help("Warn all that server is about to restart and all will reconnect.")
end
function Plugin:GetServerStartData()
return Shine.LoadJSONFile(serverStartTempfilePath) or {}
end
function Plugin:SetServerStartData(data)
Shine.SaveJSONFile(data, serverStartTempfilePath)
end
function Plugin:Initialise()
self.Enabled = true
self:CreateCommands()
TGNS.ScheduleAction(0, function()
Shared.Message("serverstart - TGNS.GetSecondsSinceServerProcessStarted(): " .. tostring(TGNS.GetSecondsSinceServerProcessStarted()))
if TGNS.GetSecondsSinceServerProcessStarted() < 60 then
local serverStartData = self:GetServerStartData()
if serverStartData.startMapName then
local mapNameToSwitchTo = serverStartData.startMapName
serverStartData.startMapName = nil
self:SetServerStartData(serverStartData)
Shared.Message("serverStartData.startMapName: " .. tostring(mapNameToSwitchTo))
TGNS.SwitchToMap(mapNameToSwitchTo)
else
local serverHasJustStartedAndHasMadeAllModsActiveOnFirstMap = Server.GetNumActiveMods() >= NUMBER_OF_ACTIVE_MODS_INDICATIVE_OF_A_SERVER_RESTART
if serverHasJustStartedAndHasMadeAllModsActiveOnFirstMap then
Shared.Message("Switching first map to prevent all clients from having to download all mods...")
TGNS.SwitchToMap(TGNS.GetCurrentMapName())
end
TGNS.RegisterEventHook("ClientConfirmConnect", function(client)
if TGNS.GetSecondsSinceServerProcessStarted() < 300 and not SERVER_COMMANDLINE_START_MAP_NAME ~= TGNS.GetCurrentMapName() then
Shine.ScreenText.Add(71, {X = 0.3, Y = 0.3, Text = "Scheduled server restart complete.", Duration = 10, R = 0, G = 255, B = 0, Alignment = TGNS.ShineTextAlignmentMin, Size = 3, FadeIn = 0, IgnoreFormat = true}, client)
end
end)
TGNS.ScheduleAction(10, function()
if TGNS.IsProduction() then
Shine.Plugins.push:Push("tgns-admin", "Server started.", string.format("%s on %s. Server Info: http://rr.tacticalgamer.com/ServerInfo", TGNS.GetCurrentMapName(), TGNS.GetSimpleServerName()))
end
end)
end
end
end)
local mapNameNotifyNames = {"WINNER_VOTES", "CHOOSING_RANDOM_MAP", "WINNER_CYCLING", "WINNER_NEXT_MAP"}
TGNS.ScheduleAction(5, function()
local originalSendTranslatedNotify = Shine.Plugins.mapvote.SendTranslatedNotify
Shine.Plugins.mapvote.SendTranslatedNotify = function(mapVoteSelf, target, name, params)
if TGNS.Has(mapNameNotifyNames, name) then
local votedInMapName = params.MapName
if votedInMapName then
TGNS.ExecuteEventHooks("MapVoteFinished", votedInMapName)
local hoursSinceServerProcessStarted = TGNS.ConvertSecondsToHours(TGNS.GetSecondsSinceServerProcessStarted())
if votedInMapName ~= SERVER_COMMANDLINE_START_MAP_NAME and hoursSinceServerProcessStarted > NUMBER_OF_HOURS_SERVER_SEEMS_TO_SURVIVE_WITHOUT_CRASHING and Server.GetNumPlayersTotal() >= NUMBER_OF_PLAYERS_BEFORE_SCHEDULED_RESTART then
local serverStartData = self:GetServerStartData()
serverStartData.startMapName = votedInMapName
self:SetServerStartData(serverStartData)
TGNS.ScheduleAction(0, function()
md:ToAllNotifyInfo(string.format("Server will restart to %s. Please wait. Reconnect manually if you aren't reconnected automatically.", votedInMapName))
end)
TGNS.RestartServerProcess()
else
originalSendTranslatedNotify(mapVoteSelf, target, name, params)
end
else
originalSendTranslatedNotify(mapVoteSelf, target, name, params)
end
else
originalSendTranslatedNotify(mapVoteSelf, target, name, params)
end
end
end)
return true
end
function Plugin:Cleanup()
--Cleanup your extra stuff like timers, data etc.
self.BaseClass.Cleanup( self )
end |
-- Internal custom properties
local EQUIPMENT = script:FindAncestorByType('Equipment')
if not EQUIPMENT:IsA('Equipment') then
error(script.name .. " should be part of Equipment object hierarchy.")
end
local ABILITY = script:FindAncestorByType('Ability')
if not ABILITY:IsA('Ability') then
error(script.name .. " should be part of Ability object hierarchy.")
end
local EFFECTS_PARENT = script:GetCustomProperty("EffectsParent"):WaitForObject()
local scanScript = script:GetCustomProperty("ScanScript"):WaitForObject()
local diedHandle = nil
function OnPlayerDied(player, damage)
TriggerVFX(false)
end
function OnEquipped(equipment, player)
diedHandle = player.diedEvent:Connect(OnPlayerDied)
TriggerVFX(false)
end
function OnUnequipped(equipment, player)
if diedHandle then diedHandle:Disconnect() end
TriggerVFX(false)
end
function TriggerVFX(trigger)
if trigger == true then
scanScript.context.Pulse()
end
end
ABILITY.castEvent:Connect(function() TriggerVFX(true) end)
ABILITY.readyEvent:Connect(function() TriggerVFX(false) end)
ABILITY.cooldownEvent:Connect(function() TriggerVFX(false) end)
EQUIPMENT.equippedEvent:Connect(OnEquipped)
EQUIPMENT.unequippedEvent:Connect(OnUnequipped)
TriggerVFX(false) |
#!/usr/bin/env lua
do
end
package.path = package.path..";?/init.lua;"
local M = require("appUmolflowFramework")
return M |
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local lib = ReplicatedStorage:WaitForChild("lib")
local PizzaAlpaca = require(lib:WaitForChild("PizzaAlpaca"))
local Logger = PizzaAlpaca.GameModule:extend("Logger")
local LOG_FORMAT_STRING = "[%s][%s]: %s"
local logtype = {
OUTPUT = 1,
WARNING = 2,
SEVERE = 3,
}
local logtypeNames = {
[logtype.OUTPUT] = "OUTPUT",
[logtype.WARNING] = "WARNING",
[logtype.SEVERE] = "SEVERE",
}
local printFuncs = {
[logtype.OUTPUT] = print,
[logtype.WARNING] = warn,
[logtype.SEVERE] = function(msg)
-- Todo: send this to a webserver so nim can review it
error(msg,3) -- delicious red text.
end
}
function Logger:create() -- constructor, fired on instantiation, core will be nil.
self.logtype = logtype
end
function Logger:createLogger(module)
local logger = {}
logger.logtype = logtype
function logger:log(msg,severity)
severity = severity or logtype.OUTPUT
printFuncs[severity or logtype.OUTPUT](LOG_FORMAT_STRING:format(
tostring(module),
tostring(logtypeNames[severity]),
tostring(msg))
)
end
return logger
end
return Logger |
local metal_caster = table.deepcopy(data.raw['assembling-machine']['oil-refinery'])
metal_caster.crafting_categories = {"melting"}
metal_caster.name = "melter"
metal_caster.placeable_by = {type="ItemToPlace", item="melter", count=1}
metal_caster.minable = {mining_time = 1, result = "melter"}
local item = {
type = "item",
name = "melter",
icons = {icon={icon="__base__/graphics/icons/oil-refinery.png", tint={r=150 , g=150 , b=250 , a=255}}},
icon_size = 64,
stack_size = 100,
subgroup = "metallurgy",
place_result = "melter"
}
local recipe = {
type= "recipe",
name= "melter",
icons = {icon={icon="__base__/graphics/icons/oil-refinery.png", tint={r=150 , g=150 , b=250 , a=255}}},
icon_size = 64,
energy_required = 15,
category = "crafting",
subgroup = "metallurgy",
ingredients = {
{type="item", name="blister-copper", amount=25},
},
results = {
{type="item", name="melter", amount=25},
},
enabled = false,
order = "f"
}
data:extend{metal_caster, item, recipe} |
local function enum(tbl)
local call = {}
for k, v in pairs(tbl) do
if call[v] then
return error(string.format('enum clash for %q and %q', k, call[v]))
end
call[v] = k
end
return setmetatable({}, {
__call = function(_, k)
if call[k] then
return call[k]
else
return error('invalid enumeration: ' .. tostring(k))
end
end,
__index = function(_, k)
if tbl[k] then
return tbl[k]
else
return error('invalid enumeration: ' .. tostring(k))
end
end,
__pairs = function()
return next, tbl
end,
__newindex = function()
return error('cannot overwrite enumeration')
end,
})
end
local enums = {enum = enum}
enums.defaultAvatar = enum {
blurple = 0,
gray = 1,
green = 2,
orange = 3,
red = 4,
}
enums.notificationSetting = enum {
allMessages = 0,
onlyMentions = 1,
}
enums.channelType = enum {
text = 0,
private = 1,
voice = 2,
group = 3,
category = 4,
}
enums.messageType = enum {
default = 0,
recipientAdd = 1,
recipientRemove = 2,
call = 3,
channelNameChange = 4,
channelIconchange = 5,
pinnedMessage = 6,
memberJoin = 7,
}
enums.relationshipType = enum {
none = 0,
friend = 1,
blocked = 2,
pendingIncoming = 3,
pendingOutgoing = 4,
}
enums.gameType = enum {
default = 0,
streaming = 1,
listening = 2,
}
enums.verificationLevel = enum {
none = 0,
low = 1,
medium = 2,
high = 3, -- (╯°□°)╯︵ ┻━┻
veryHigh = 4, -- ┻━┻ ミヽ(ಠ益ಠ)ノ彡┻━┻
}
enums.explicitContentLevel = enum {
none = 0,
medium = 1,
high = 2,
}
enums.permission = enum {
createInstantInvite = 0x00000001,
kickMembers = 0x00000002,
banMembers = 0x00000004,
administrator = 0x00000008,
manageChannels = 0x00000010,
manageGuild = 0x00000020,
addReactions = 0x00000040,
viewAuditLog = 0x00000080,
readMessages = 0x00000400,
sendMessages = 0x00000800,
sendTextToSpeech = 0x00001000,
manageMessages = 0x00002000,
embedLinks = 0x00004000,
attachFiles = 0x00008000,
readMessageHistory = 0x00010000,
mentionEveryone = 0x00020000,
useExternalEmojis = 0x00040000,
connect = 0x00100000,
speak = 0x00200000,
muteMembers = 0x00400000,
deafenMembers = 0x00800000,
moveMembers = 0x01000000,
useVoiceActivity = 0x02000000,
changeNickname = 0x04000000,
manageNicknames = 0x08000000,
manageRoles = 0x10000000,
manageWebhooks = 0x20000000,
manageEmojis = 0x40000000,
}
enums.actionType = enum {
guildUpdate = 1,
channelCreate = 10,
channelUpdate = 11,
channelDelete = 12,
channelOverwriteCreate = 13,
channelOverwriteUpdate = 14,
channelOverwriteDelete = 15,
memberKick = 20,
memberPrune = 21,
memberBanAdd = 22,
memberBanRemove = 23,
memberUpdate = 24,
memberRoleUpdate = 25,
roleCreate = 30,
roleUpdate = 31,
roleDelete = 32,
inviteCreate = 40,
inviteUpdate = 41,
inviteDelete = 42,
webhookCreate = 50,
webhookUpdate = 51,
webhookDelete = 52,
emojiCreate = 60,
emojiUpdate = 61,
emojiDelete = 62,
messageDelete = 72,
}
enums.logLevel = enum {
none = 0,
error = 1,
warning = 2,
info = 3,
debug = 4,
}
return enums
|
--[[
Time Gates
]]
GateActions("Time")
local CurTime = CurTime
local min = math.min
local max = math.max
local date = os.date
GateActions["accumulator"] = {
name = "Accumulator",
inputs = {"A", "Hold", "Reset"},
timed = true,
output = function(gate, A, Hold, Reset)
local DeltaTime = CurTime() - (gate.PrevTime or CurTime())
gate.PrevTime = (gate.PrevTime or CurTime()) + DeltaTime
if (Reset > 0) then
gate.Accum = 0
elseif (Hold <= 0) then
gate.Accum = gate.Accum + A * DeltaTime
end
return gate.Accum or 0
end,
reset = function(gate)
gate.PrevTime = CurTime()
gate.Accum = 0
end,
label = function(Out, A, Hold, Reset) return "A:" .. A .. " Hold:" .. Hold .. " Reset:" .. Reset .. " = " .. Out end
}
GateActions["smoother"] = {
name = "Smoother",
inputs = {"A", "Rate"},
timed = true,
output = function(gate, A, Rate)
local DeltaTime = CurTime() - (gate.PrevTime or CurTime())
gate.PrevTime = (gate.PrevTime or CurTime()) + DeltaTime
local Delta = A - gate.Accum
if (Delta > 0) then
gate.Accum = gate.Accum + min(Delta, Rate * DeltaTime)
elseif (Delta < 0) then
gate.Accum = gate.Accum + max(Delta, -Rate * DeltaTime)
end
return gate.Accum or 0
end,
reset = function(gate)
gate.PrevTime = CurTime()
gate.Accum = 0
end,
label = function(Out, A, Rate) return "A:" .. A .. " Rate:" .. Rate .. " = " .. Out end
}
GateActions["timer"] = {
name = "Timer",
inputs = {"Run", "Reset"},
timed = true,
output = function(gate, Run, Reset)
local DeltaTime = CurTime() - (gate.PrevTime or CurTime())
gate.PrevTime = (gate.PrevTime or CurTime()) + DeltaTime
if (Reset > 0) then
gate.Accum = 0
elseif (Run > 0) then
gate.Accum = gate.Accum + DeltaTime
end
return gate.Accum or 0
end,
reset = function(gate)
gate.PrevTime = CurTime()
gate.Accum = 0
end,
label = function(Out, Run, Reset) return "Run:" .. Run .. " Reset:" .. Reset .. " = " .. Out end
}
GateActions["ostime"] = {
name = "OS Time",
inputs = {},
timed = true,
output = function(gate) return date("%H") * 3600 + date("%M") * 60 + date("%S") end,
label = function(Out) return "OS Time = " .. Out end
}
GateActions["osdate"] = {
name = "OS Date",
inputs = {},
timed = true,
output = function(gate) return date("%Y") * 366 + date("%j") end,
label = function(Out) return "OS Date = " .. Out end
}
GateActions["pulser"] = {
name = "Pulser",
inputs = {"Run", "Reset", "TickTime"},
timed = true,
output = function(gate, Run, Reset, TickTime)
local DeltaTime = CurTime() - (gate.PrevTime or CurTime())
gate.PrevTime = (gate.PrevTime or CurTime()) + DeltaTime
if (Reset > 0) then
gate.Accum = 0
elseif (Run > 0) then
gate.Accum = gate.Accum + DeltaTime
if (gate.Accum >= TickTime) then
gate.Accum = gate.Accum - TickTime
return 1
end
end
return 0
end,
reset = function(gate)
gate.PrevTime = CurTime()
gate.Accum = 0
end,
label = function(Out, Run, Reset, TickTime) return "Run:" .. Run .. " Reset:" .. Reset .. "TickTime:" .. TickTime .. " = " .. Out end
}
GateActions["squarepulse"] = {
name = "Square Pulse",
inputs = {"Run", "Reset", "PulseTime", "GapTime", "Min", "Max"},
timed = true,
output = function(gate, Run, Reset, PulseTime, GapTime, Min, Max)
local DeltaTime = CurTime() - (gate.PrevTime or CurTime())
gate.PrevTime = (gate.PrevTime or CurTime()) + DeltaTime
if (Reset > 0) then
gate.Accum = 0
elseif (Run > 0) then
gate.Accum = gate.Accum + DeltaTime
if (gate.Accum <= PulseTime) then return Max end
if (gate.Accum >= PulseTime + GapTime) then
gate.Accum = 0
end
end
return Min
end,
reset = function(gate)
gate.PrevTime = CurTime()
gate.Accum = 0
end,
label = function(Out, Run, Reset, PulseTime, GapTime) return "Run:" .. Run .. " Reset:" .. Reset .. " PulseTime:" .. PulseTime .. " GapTime:" .. GapTime .. " = " .. Out end
}
GateActions["sawpulse"] = {
name = "Saw Pulse",
inputs = {"Run", "Reset", "SlopeRaiseTime", "PulseTime", "SlopeDescendTime", "GapTime", "Min", "Max"},
timed = true,
output = function(gate, Run, Reset, SlopeRaiseTime, PulseTime, SlopeDescendTime, GapTime, Min, Max)
local DeltaTime = CurTime() - (gate.PrevTime or CurTime())
gate.PrevTime = (gate.PrevTime or CurTime()) + DeltaTime
if Reset > 0 then
gate.Accum = 0
return Min
end
if Run <= 0 then return Min end
SlopeRaiseTime = max(SlopeRaiseTime, 0)
PulseTime = max(PulseTime, 0)
SlopeDescendTime = max(SlopeDescendTime, 0)
GapTime = max(GapTime, 0)
gate.Accum = (gate.Accum + DeltaTime) % (SlopeRaiseTime + PulseTime + SlopeDescendTime + GapTime)
if gate.Accum < SlopeRaiseTime then
return Min + (Max - Min) * gate.Accum / SlopeRaiseTime
elseif gate.Accum < SlopeRaiseTime + PulseTime then
return Max
elseif gate.Accum < SlopeRaiseTime + PulseTime + SlopeDescendTime then
return Max + (Min - Max) * (gate.Accum - SlopeRaiseTime - PulseTime) / SlopeDescendTime
else
return Min
end
end,
reset = function(gate)
gate.PrevTime = CurTime()
gate.Accum = 0
end,
label = function(Out, Run, Reset, PulseTime, GapTime) return "Run:" .. Run .. " Reset:" .. Reset .. " PulseTime:" .. PulseTime .. " GapTime:" .. GapTime .. " = " .. Out end
}
GateActions["derive"] = {
name = "Derivative",
inputs = {"A"},
timed = false,
output = function(gate, A)
local t = CurTime()
local dT = t - gate.LastT
gate.LastT = t
local dA = A - gate.LastA
gate.LastA = A
if dT ~= 0 then
return dA / dT
else
return 0
end
end,
reset = function(gate)
gate.LastT = CurTime()
gate.LastA = 0
end,
label = function(Out, A) return "d/dt[" .. A .. "] = " .. Out end
}
GateActions["delay"] = {
name = "Delay",
inputs = {"Clk", "Delay", "Hold", "Reset"},
outputs = {"Out", "TimeElapsed", "Remaining"},
timed = true,
output = function(gate, Clk, Delay, Hold, Reset)
local DeltaTime = CurTime() - (gate.PrevTime or CurTime())
gate.PrevTime = (gate.PrevTime or CurTime()) + DeltaTime
local out = 0
if (Reset > 0) then
gate.Stage = 0
gate.Accum = 0
end
if (gate.Stage == 1) then
if (gate.Accum >= Delay) then
gate.Stage = 2
gate.Accum = 0
out = 1
else
gate.Accum = gate.Accum + DeltaTime
end
elseif (gate.Stage == 2) then
if (gate.Accum >= Hold) then
gate.Stage = 0
gate.Accum = 0
out = 0
else
out = 1
gate.Accum = gate.Accum + DeltaTime
end
else
if (Clk > 0) then
gate.Stage = 1
gate.Accum = 0
end
end
return out, gate.Accum, Delay - gate.Accum
end,
reset = function(gate)
gate.PrevTime = CurTime()
gate.Accum = 0
gate.Stage = 0
end,
label = function(Out, Clk, Delay, Hold, Reset) return "Clk: " .. Clk .. " Delay: " .. Delay .. "\nHold: " .. Hold .. " Reset: " .. Reset .. "\nTime Elapsed: " .. Out.TimeElapsed .. " = " .. Out.Out end
}
GateActions["monostable"] = {
name = "Monostable Timer",
inputs = {"Run", "Time", "Reset"},
timed = true,
output = function(gate, Run, Time, Reset)
local DeltaTime = CurTime() - (gate.PrevTime or CurTime())
gate.PrevTime = (gate.PrevTime or CurTime()) + DeltaTime
if (Reset > 0) then
gate.Accum = 0
elseif gate.Accum > 0 or Run > 0 then
gate.Accum = gate.Accum + DeltaTime
if (gate.Accum > Time) then
gate.Accum = 0
end
end
if (gate.Accum > 0) then
return 1
else
return 0
end
end,
reset = function(gate)
gate.PrevTime = CurTime()
gate.Accum = 0
end,
label = function(Out, Run, Time, Reset) return "Run:" .. Run .. " Time:" .. Time .. " Reset:" .. Reset .. " = " .. Out end
}
GateActions() |
local SKIP_ANIMATION = script:GetCustomProperty("SkipAnimation"):WaitForObject()
local BUTTON = script:GetCustomProperty("SkipButton"):WaitForObject()
BUTTON.clickedEvent:Connect(function() Events.Broadcast("SkipAnimation") end)
Events.Connect("ShowSkipButton", function() SKIP_ANIMATION.visibility = Visibility.FORCE_ON end)
Events.Connect("HideSkipButton", function() SKIP_ANIMATION.visibility = Visibility.FORCE_OFF end)
|
local lSettings = {}
do
local strBaseDir = "/home/ameen/mygithub/depos/DeepPep/"
lSettings.strFilenameInputSparse = string.format("%s/input_sparseList.csv", strBaseDir)
lSettings.strFilenameTarget = string.format("%s/target.csv", strBaseDir)
lSettings.nInputWidth=50104
return lSettings
end
|
local ASL = LibStub("AceLocale-3.0"):NewLocale("AddOnSkins", "frFR")
if not ASL then return end
ASL["About/Help"] = "À Propos/Aide"
ASL["AddOn Skins"] = "Skins d'AddOn"
ASL["Attach CoolLine to action bar"] = "Attacher CoolLine à la barre d'action"
ASL["Attach SexyCD to action bar"] = "Attacher SexyCD à la barre d'action"
ASL["Auction House"] = "Hôtel des Ventes"
ASL["Available Skins / Skin Requests"] = "Skins Disponible / Demandes de Skins"
ASL["BigWigs Half-Bar"] = "Skin Demi-Bar pour BigWigs"
ASL["Blizzard Skins"] = "Skins Blizzard"
ASL["Changelog Link"] = "Liens pour les derniers changements"
ASL["Credits"] = "Crédits"
ASL["Credits:"] = "Crédits:"
ASL["DBM Transparent Radar"] = "DBM Transparent Radar"
ASL["DBM Half-Bar Skin Spacing looks wrong. How can I fix it?"] = "L'espacement du Skin Demi-Barre de DBM Half-Bar semble mauvais, comment le corriger ?"
ASL["DBM Font Flag"] = "Effet de la Police DBM"
ASL["DBM Font Size"] = "Taille de la Police DBM"
ASL["DBM Font"] = "Police d'écriture DBM"
ASL["DBM Half-bar Skin"] = "Skin Demi-Bar pour DBM"
ASL["Details Backdrop"] = true
ASL["Download Link"] = "Lien de Téléchargement"
ASL["Embed Below Top Tab"] = "Intégrer en dessous de la tabulation du haut"
ASL["Embed for One Window"] = "Embed for One Window"
ASL["Embed Frame Level"] = true
ASL["Embed Frame Strata"] = true
ASL["Embed into Right Chat Panel"] = "Embed into Right Chat Panel"
ASL["Embed OoC Delay"] = "Délais Hors Combat de l'intégration"
ASL["Embed Settings"] = "Réglages d'intégration"
ASL["Embed System Message"] = true
ASL["Embed Transparancy"] = "Transparence de l'intégration"
ASL["Enable Skin Debugging"] = "Enable Skin Debugging"
ASL["FAQ's"] = "QF's"
ASL["GitLab Link / Report Errors"] = "Lien vers GitLab / Rapporter des Erreurs"
ASL["Hide Chat Frame"] = "Cacher le panneau de discussion"
ASL["Left Click to Show"] = "Click Gauche pour Afficher"
ASL["Left Click:"] = "Click Gauche:"
ASL["Links"] = "Links"
ASL["Login Message"] = true
ASL["|cffff7d0aMerathilisUI|r Styling"] = true
ASL["MONOCHROME"] = "MONOCHROME"
ASL["MONOCHROMEOUTLINE"] = "MONOCHROMEOUTLINE"
ASL["None"] = "Aucun"
ASL["Omen Backdrop"] = "Fond de Omen"
ASL["One Window Embed System"] = "One Window Embed System"
ASL["Out of Combat (Hide)"] = "Hors combat(Cacher)"
ASL["OUTLINE"] = "OUTLINE"
ASL["Parchment"] = "Parchment"
ASL["Recount Backdrop"] = "Fond de Recount"
ASL["Right Click to Hide"] = "Click Droit pour Cacher"
ASL["Right Click:"] = "Click Droit:"
ASL["Settings to control Embedded AddOns:\n\nAvailable Embeds: Omen | Skada | Recount | TinyDPS"] = "Réglages pour controler les intégrations d'AddOns:\n\nIntégrations disponible: Omen | Skada | Recount | TinyDPS"
ASL["Skada Backdrop"] = "Fond de Skada"
ASL["Skin Template"] = "Modèle de Skin"
ASL["THICKOUTLINE"] = "THICKOUTLINE"
ASL["To use the DBM Half-Bar skin. You must change the DBM Options. Offset Y needs to be at least 15."] = "Pour utiliser le Skin Demi-Barre de BBM. Vous devez changer une option dans BBM. l'Offset Y doit être d'au moins 15."
ASL["Two Window Embed System"] = "Two Window Embed System"
ASL["Version"] = "Version"
ASL["WeakAura AuraBar"] = "Barre d'Aura de WeakAura"
ASL["WeakAura Cooldowns"] = "WeakAura Cooldowns"
ASL["Window One Embed"] = "Window One Embed"
ASL["Window One Width"] = "Window One Width"
ASL["Window Two Embed"] = "Window Two Embed"
ASL['Enable/Disable this embed.'] = 'Activer/Désactiver cette intégration.'
ASL['Enable/Disable this option.'] = 'Activer/Désactiver cette option.'
ASL['Enable/Disable this skin.\nThis requires a reload to take effect.'] = 'Activer/Désactiver ce skin.'
ASL['Reset Settings'] = 'Reset Settings'
ASL['This option will toggle the corresponding ElvUI option.'] = true
ASL['Toggle Embedded AddOn'] = "Basculer l'AddOn Intégré"
ASL['Toggle Left Chat Panel'] = 'Basculer le panneau de chat Gauche'
ASL['Toggle Options'] = 'Basculer les Options'
ASL['Toggle Right Chat Panel'] = 'Basculer le panneau de chat Droit'
|
local socket = require "socket"
local readbytes = socket.read
local writebytes = socket.write
local sockethelper = {}
local socket_error = setmetatable({} , { __tostring = function() return "[Socket Error]" end })
sockethelper.socket_error = socket_error
function sockethelper.readfunc(fd)
return function (sz)
local ret = readbytes(fd, sz)
if ret then
return ret
else
error(socket_error)
end
end
end
sockethelper.readall = socket.readall
function sockethelper.writefunc(fd)
return function(content)
local ok = writebytes(fd, content)
if not ok then
error(socket_error)
end
end
end
function sockethelper.connect(host, port)
local fd = socket.open(host, port)
if fd then
return fd
end
error(socket_error)
end
function sockethelper.close(fd)
socket.close(fd)
end
return sockethelper
|
import("packages", {alias = "get_packages"})
function main(...)
-- get packages
local packages = get_packages({onlyhost = true})
local tables = {}
local col = 1
local row_max = 0
for _, pkgs in pairs(packages) do
for row, pkg in ipairs(pkgs) do
tables[row] = tables[row] or {}
tables[row][col] = pkg
end
if #pkgs > row_max then
row_max = #pkgs
end
col = col + 1
end
-- generate markdown table
local packages_md = "## All Supported Packages\n\n"
for plat, _ in pairs(packages) do
packages_md = packages_md .. "|" .. plat
end
packages_md = packages_md .. "|\n"
for plat, _ in pairs(packages) do
packages_md = packages_md .. "|" .. (plat:gsub('.', '-'))
end
packages_md = packages_md .. "|\n"
for y = 1, row_max do
for x = 1, col do
local pkg = tables[y][x]
local info = ""
if pkg then
if pkg.generic then
info = pkg.name
else
info = pkg.name .. "(" .. table.concat(pkg.archs, ",") .. ")"
end
end
packages_md = packages_md .. "|" .. info
end
packages_md = packages_md .. "|\n"
end
print(packages_md)
io.writefile(path.join(os.scriptdir(), "..", "PKGLIST.md"), packages_md)
end
|
local mapQuests = {}
local states = {
None = 0x0,
Perform = 0x1,
Complete = 0x2,
PartyQuest = 0x3,
No = 0x4
}
local questIcons = {
questIcon4 = "UI/UIWindow.img/QuestIcon/4/0",
questIcon8 = "UI/UIWindow.img/QuestIcon/8/0",
}
local quests = {
-- Adventurer Tutorial --
Reactor1 = 1008,
Reactor2 = 1020,
RogersApple = 1021,
Minimap = 1031,
AttackPickUpSkill = 1035,
MaiFirstTrainnig = 1041, -- Mai's First Training
MaiSecondTrainnig = 1042, -- Mai's Second Training
MaiThirdTrainnig = 1043, -- Mai's Third Training
MaiFinalTrainnig = 1044, -- Mai's Final Training
-- Dual Blade Missions --
Infiltration = 2351, -- First Mission: Infiltration
-- Other quests --
FreeMarketQuest = 7600,
-- KoC Tutorial --
GreetingsFromYoungEmpress = 20000, -- Greetings From the Young Empress
WelcomeToEreve = 20010, -- Welcome To Ereve
IllShowYouHowToHunt = 20011, -- I'll Show You How to Hunt
KoCTut = 20022, -- hidden
-- Aran Tutorial --
MissingChild = 21000, -- Find the Missing Kid 1
MissingChild2 = 21001, -- Find the Missing Kid 2
AranTut = 21002, -- hidden
AranTut2 = 21019, -- hidden
-- Evan Tutorial --
StrangeDream = 22000, -- Strange Dream
FeedingBullDog = 22001, -- Feeding Bull Dog
DragonEyes = 22012,
EvanTut = 22013, -- hidden
-- Evan --
KiddnapingOfCamila = 22557, -- Kidnapping of Camila
-- Edelstein Tutorial --
VitaEscape = 23007,
Resistance1stJob = 23011,
AStudentResistanceBattleMage = 23100, -- A Student of the Resistance [Battle Mage]
AStudentResistanceWildHunter = 23101, -- A Student of the Resistance [Wild Hunter]
AStudentResistanceMechanic = 23102, -- A Student of the Resistance [Mechanic]
AgilityTraining = 23103,
AttackTraining = 23104,
EnduranceTraining = 23105,
FinalTrainingCourse = 23106,
HideAndSeek = 23999,
-- Explorer Quest --
BeginnerExplorer = 29005, -- Beginner Explorer
TheOneWhosTouchedSky = 29904, -- The One Who's Touched the Sky
ElNathExplorer = 29006, -- El Nath Mts. Explorer
LudusLakeExplorer = 29007, -- Ludus Lake Explorer
UnderseaExplorer = 29008, -- Undersea Explorer
MuLungExplorer = 29009, -- Mu Lung Explorer
NihalDesertExplorer = 29010, -- Nihal Desert Explorer
MinarForestExplorer = 29011, -- Minar Forest Explorer
SleepywoodExplorer = 29014, -- Sleepywood Explorer
-- Adventurer Trainning Quest --
BeginnerAdventurer = 29900, -- Beginner Adventurer
JuniorAdventurer = 29901, -- Junior Adventurer
VeteranAdventurer = 29902, -- Veteran Adventurer
MasterAdventurer = 29903, -- Master Adventurer
-- KoC Trainning Quest --
Noblesse = 29905, -- Noblesse
TrainingKnight = 29906, -- Training Knight
OfficialKnight = 29907, -- Official Knight
AdvancedKnight = 29908, -- Advanced Knight
CaptainKnight = 29909, -- Captain Knight
-- Special Trainning Quest
SpecialTrainingBeginner = 29941, -- Special Training Beginner
SpecialTrainingIntermediate = 29942, -- Special Training Intermediate
SpecialTrainingGraduate = 29943, -- Special Training Graduate
SpecialTrainingSuperior = 29944, -- Special Training Superior
SpecialTrainingMaster = 29945, -- Special Training Master
}
local questExpRewards = {
KidFound3 = 3,
KidFound5 = 5,
RogersAppleFinish = 10,
WelcomeToEreveFinish = 15,
StrangeDreamFinish = 20,
GreetingsFromYoungEmpressFinish = 20,
VitaEscapeBegin = 35,
VitaEscapePart3 = 60,
VitaEscapeFinish = 90
}
function mapQuests.getState(key)
return states[key]
end
function mapQuests.getID(key)
return quests[key]
end
function mapQuests.getQuestExpReward(key)
return questExpRewards[key]
end
return mapQuests |
cnfg = require "config"
game = require "game"
mf = require "mathFunctions"
ff = require "fileFunctions"
nf = require "neatFunctions"
Inputs = cnfg.InputSize+1
Outputs = #cnfg.ButtonNames
form = forms.newform(450, 650, "Metroid-Learning")
netPicture = forms.pictureBox(form, 5, 300, 420, 300)
event.onexit(onExit)
function newInnovation()
pool.innovation = pool.innovation + 1
return pool.innovation
end
function linkMutate(genome, forceBias)
local neuron1 = nf.randomNeuron(genome.genes, false)
local neuron2 = nf.randomNeuron(genome.genes, true)
local newLink = nf.newGene()
-- if both neurons are input nodes, stop
if neuron1 <= Inputs and neuron2 <= Inputs then return end
-- make sure neuron2 is higher than neuron1
if neuron2 <= Inputs then
local temp = neuron1
neuron1 = neuron2
neuron2 = temp
end
newLink.into = neuron1
newLink.out = neuron2
if forceBias then newLink.into = Inputs end
if nf.containsLink(genome.genes, newLink) then return end
newLink.innovation = newInnovation()
newLink.weight = math.random()*4-2
table.insert(genome.genes, newLink)
end
function nodeMutate(genome)
if #genome.genes == 0 then return end
genome.maxneuron = genome.maxneuron + 1
local gene = genome.genes[math.random(1,#genome.genes)]
if not gene.enabled then return end
gene.enabled = false
local gene1 = nf.copyGene(gene)
gene1.out = genome.maxneuron
gene1.weight = 1.0
gene1.innovation = newInnovation()
gene1.enabled = true
table.insert(genome.genes, gene1)
local gene2 = nf.copyGene(gene)
gene2.into = genome.maxneuron
gene2.innovation = newInnovation()
gene2.enabled = true
table.insert(genome.genes, gene2)
end
function enableDisableMutate(genome, enable)
local candidates = {}
for _,gene in pairs(genome.genes) do
if gene.enabled == not enable then table.insert(candidates, gene) end
end
if #candidates == 0 then return end
local gene = candidates[math.random(1,#candidates)]
gene.enabled = not gene.enabled
end
function submutate(p, g, option)
if p > 0 then
if option == 0 then
if math.random() < p then linkMutate(g, false) end
elseif option == 1 then
if math.random() < p then linkMutate(g, true) end
elseif option == 2 then
if math.random() < p then nodeMutate(g) end
elseif option == 3 then
if math.random() < p then enableDisableMutate(g, true) end
elseif option == 4 then
if math.random() < p then enableDisableMutate(g, false) end
end
submutate(p-1, option)
end
end
function mutate(genome)
for mutation,rate in pairs(genome.mutationRates) do
if math.random(1,2) == 1 then genome.mutationRates[mutation] = 0.95*rate else genome.mutationRates[mutation] = 1.05263*rate end
end
if math.random() < genome.mutationRates["connections"] then genome = nf.pointMutate(genome) end
submutate(genome.mutationRates["link"], genome, 0)
submutate(genome.mutationRates["bias"], genome, 1)
submutate(genome.mutationRates["node"], genome, 2)
submutate(genome.mutationRates["enable"], genome, 3)
submutate(genome.mutationRates["disable"], genome, 4)
end
function basicGenome()
local genome = nf.newGenome()
genome.maxneuron = Inputs
mutate(genome)
return genome
end
function addToSpecies(child)
local foundSpecies = false
for s=1,#pool.species do
local species = pool.species[s]
if not foundSpecies and nf.sameSpecies(child, species.genomes[1]) then
table.insert(species.genomes, child)
foundSpecies = true
end
end
if not foundSpecies then
local childSpecies = nf.newSpecies()
table.insert(childSpecies.genomes, child)
table.insert(pool.species, childSpecies)
end
end
function newNetwork(genome)
local network = {}
network.neurons = {}
for i=1,Inputs do network.neurons[i] = nf.newNeuron() end
for o=1,Outputs do network.neurons[cnfg.NeatConfig.MaxNodes+o] = nf.newNeuron() end
table.sort(genome.genes, function (a,b) return (a.out < b.out) end)
for i=1,#genome.genes do
local gene = genome.genes[i]
if gene.enabled then
if network.neurons[gene.out] == nil then network.neurons[gene.out] = nf.newNeuron() end
local neuron = network.neurons[gene.out]
table.insert(neuron.incoming, gene)
if network.neurons[gene.into] == nil then network.neurons[gene.into] = nf.newNeuron() end
end
end
genome.network = network
end
function evaluateNetwork(network, inputs, inputDeltas)
table.insert(inputs, 1)
table.insert(inputDeltas,99)
if #inputs ~= Inputs then
-- console.writeline("Incorrect number of neural network inputs.")
return {}
end
for i=1,Inputs do network.neurons[i].value = inputs[i] * inputDeltas[i] end
for _,neuron in pairs(network.neurons) do
local sum = 0
for j = 1,#neuron.incoming do
local incoming = neuron.incoming[j]
local other = network.neurons[incoming.into]
sum = sum + incoming.weight * other.value
end
if #neuron.incoming > 0 then neuron.value = mf.sigmoid(sum) end
end
local outputs = {}
for o=1,Outputs do
local button = "P1 " .. cnfg.ButtonNames[o]
if network.neurons[cnfg.NeatConfig.MaxNodes+o].value > 0 then outputs[button] = true else outputs[button] = false end
end
return outputs
end
function evaluateCurrent()
local species = pool.species[pool.currentSpecies]
local genome = species.genomes[pool.currentGenome]
local inputDeltas = {}
inputs, inputDeltas = game.getInputs()
controller = evaluateNetwork(genome.network, inputs, inputDeltas)
joypad.set(controller)
end
function initializeRun()
savestate.load(cnfg.StateDir .. cnfg.Filename);
pool.currentFrame = 0
timeout = cnfg.NeatConfig.TimeoutConstant
game.clearJoypad()
startHealth = game.getHealth()
startMissiles = game.getMissiles()
startSuperMissiles = game.getSuperMissiles()
startBombs = game.getBombs()
startTanks = game.getTanks()
checkSamusCollision = true
samusHitCounter = 0
explorationFitness = 0
samusXprev = nil
samusYprev = nil
if health == nil then health = 0 end
local species = pool.species[pool.currentSpecies]
local genome = species.genomes[pool.currentGenome]
newNetwork(genome)
evaluateCurrent()
end
function initializePool()
pool = nf.newPool()
for i=1,cnfg.NeatConfig.Population do
basic = basicGenome()
addToSpecies(basic)
end
initializeRun()
end
if pool == nil then initializePool() end
--##########################################################
-- NEAT Functions
--##########################################################
function cullSpecies(cutToOne)
for s = 1,#pool.species do
local species = pool.species[s]
table.sort(species.genomes, function (a,b) return (a.fitness > b.fitness) end)
local remaining = math.ceil(#species.genomes/2)
if cutToOne then remaining = 1 end
while #species.genomes > remaining do table.remove(species.genomes) end
end
end
function removeStaleSpecies()
local survived = {}
for s = 1,#pool.species do
local species = pool.species[s]
table.sort(species.genomes, function (a,b) return (a.fitness > b.fitness) end)
if species.genomes[1].fitness > species.topFitness then
species.topFitness = species.genomes[1].fitness
species.staleness = 0
else
species.staleness = species.staleness + 1
end
if species.staleness < cnfg.NeatConfig.StaleSpecies or species.topFitness >= pool.maxFitness then table.insert(survived, species) end
end
pool.species = survived
end
function removeWeakSpecies()
local survived = {}
local sum = nf.totalAverageFitness(pool)
for s = 1,#pool.species do
local species = pool.species[s]
breed = math.floor(species.averageFitness / sum * cnfg.NeatConfig.Population)
if breed >= 1 then table.insert(survived, species) end
end
pool.species = survived
end
function rankSpecies()
local global = {}
for s = 1,#pool.species do
local species = pool.species[s]
for g = 1,#species.genomes do table.insert(global, species.genomes[g]) end
end
table.sort(global, function (a,b) return (a.fitness < b.fitness) end)
for g=1,#global do global[g].globalRank = g end
end
function crossoverSpecies(species)
local child = {}
if math.random() < cnfg.NeatConfig.CrossoverChance then
g1 = species.genomes[math.random(1, #species.genomes)]
g2 = species.genomes[math.random(1, #species.genomes)]
child = crossover(g1, g2)
else
g = species.genomes[math.random(1, #species.genomes)]
child = copyGenome(g)
end
mutate(child)
return child
end
function copyGenome(genome)
local genome2 = nf.newGenome()
for g=1,#genome.genes do table.insert(genome2.genes, nf.copyGene(genome.genes[g])) end
genome2.maxneuron = genome.maxneuron
genome2.mutationRates["connections"] = genome.mutationRates["connections"]
genome2.mutationRates["link"] = genome.mutationRates["link"]
genome2.mutationRates["bias"] = genome.mutationRates["bias"]
genome2.mutationRates["node"] = genome.mutationRates["node"]
genome2.mutationRates["enable"] = genome.mutationRates["enable"]
genome2.mutationRates["disable"] = genome.mutationRates["disable"]
return genome2
end
function nextGenome()
pool.currentGenome = pool.currentGenome + 1
if pool.currentGenome > #pool.species[pool.currentSpecies].genomes then
pool.currentGenome = 1
pool.currentSpecies = pool.currentSpecies+1
if pool.currentSpecies > #pool.species then
newGeneration()
pool.currentSpecies = 1
end
end
end
function newGeneration()
-- Cull the bottom half of each species
cullSpecies(false)
rankSpecies()
removeStaleSpecies()
rankSpecies()
for s = 1,#pool.species do
local species = pool.species[s]
species = nf.calculateAverageFitness(species)
end
removeWeakSpecies()
local sum = nf.totalAverageFitness(pool)
local children = {}
for s = 1,#pool.species do
local species = pool.species[s]
breed = math.floor(species.averageFitness / sum * cnfg.NeatConfig.Population) - 1
for i=1,breed do
table.insert(children, crossoverSpecies(species))
end
end
-- Cull all but the top member of each species
cullSpecies(true)
while #children + #pool.species < cnfg.NeatConfig.Population do
local species = pool.species[math.random(1, #pool.species)]
table.insert(children, crossoverSpecies(species))
end
for c=1,#children do
local child = children[c]
addToSpecies(child)
end
pool.generation = pool.generation + 1
ff.writeFile(cnfg.PoolDir .. cnfg.Filename .. ".gen" .. pool.generation .. ".pool", pool)
end
function crossover(g1, g2)
-- Make sure g1 is the higher fitness genome
if g2.fitness > g1.fitness then
tempg = g1
g1 = g2
g2 = tempg
end
local child = nf.newGenome()
local innovations2 = {}
for i=1,#g2.genes do
local gene = g2.genes[i]
innovations2[gene.innovation] = gene
end
for i=1,#g1.genes do
local gene1 = g1.genes[i]
local gene2 = innovations2[gene1.innovation]
if gene2 ~= nil and math.random(2) == 1 and gene2.enabled then
table.insert(child.genes, nf.copyGene(gene2))
else
table.insert(child.genes, nf.copyGene(gene1))
end
end
child.maxneuron = math.max(g1.maxneuron,g2.maxneuron)
for mutation,rate in pairs(g1.mutationRates) do child.mutationRates[mutation] = rate end
return child
end
--##########################################################
-- Display
--##########################################################
function displayGenome(genome)
forms.clear(netPicture, 0xFFDDDDDD)
local network = genome.network
local cells = {}
local i = 1
local cell = {}
for dy=-cnfg.BoxRadius,cnfg.BoxRadius do
for dx=-cnfg.BoxRadius,cnfg.BoxRadius do
cell = {}
cell.x = 50 + 5 * dx
cell.y = 70 + 5 * dy
cell.value = network.neurons[i].value
cells[i] = cell
i = i + 1
end
end
local biasCell = {}
biasCell.x = 80
biasCell.y = 110
biasCell.value = network.neurons[Inputs].value
cells[Inputs] = biasCell
for o = 1,Outputs do
cell = {}
cell.x = 320
cell.y = 30 + 11 * o
cell.value = network.neurons[cnfg.NeatConfig.MaxNodes + o].value
cells[cnfg.NeatConfig.MaxNodes + o] = cell
local color
if cell.value > 0 then color = 0xFF0000FF else color = 0xFF000000 end
forms.drawText(netPicture, 330, 22 + 11 * o, cnfg.ButtonNames[o], color, 9)
end
for n,neuron in pairs(network.neurons) do
cell = {}
if n > Inputs and n <= cnfg.NeatConfig.MaxNodes then
cell.x = 140
cell.y = 40
cell.value = neuron.value
cells[n] = cell
end
end
for n=1,4 do
for _,gene in pairs(genome.genes) do
if gene.enabled then
local c1 = cells[gene.into]
local c2 = cells[gene.out]
if gene.into > Inputs and gene.into <= cnfg.NeatConfig.MaxNodes then
c1.x = 0.75 * c1.x + 0.25 * c2.x
if c1.x >= c2.x then c1.x = c1.x - 40 end
if c1.x < 90 then c1.x = 90 end
if c1.x > 220 then c1.x = 220 end
c1.y = 0.75 * c1.y + 0.25 * c2.y
end
if gene.out > Inputs and gene.out <= cnfg.NeatConfig.MaxNodes then
c2.x = 0.25 * c1.x + 0.75 * c2.x
if c1.x >= c2.x then c2.x = c2.x + 40 end
if c2.x < 90 then c2.x = 90 end
if c2.x > 220 then c2.x = 220 end
c2.y = 0.25 * c1.y + 0.75 * c2.y
end
end
end
end
forms.drawBox(netPicture, 50 - cnfg.BoxRadius * 5 - 3, 70 - cnfg.BoxRadius * 5 - 3, 50 + cnfg.BoxRadius * 5 + 2, 70 + cnfg.BoxRadius * 5 + 2, 0xFF000000, 0x80808080)
for n,cell in pairs(cells) do
if n > Inputs or cell.value ~= 0 then
local color = math.floor((cell.value + 1) / 2 * 256)
if color > 255 then color = 255 end
if color < 0 then color = 0 end
local opacity = 0xFF000000
if cell.value == 0 then opacity = 0x50000000 end
color = opacity + color * 0x10000 + color * 0x100 + color
forms.drawBox(netPicture, cell.x - 2, cell.y - 2, cell.x + 2, cell.y + 2, opacity, color)
end
end
for _,gene in pairs(genome.genes) do
if gene.enabled then
local c1 = cells[gene.into]
local c2 = cells[gene.out]
local opacity = 0xA0000000
if c1.value == 0 then opacity = 0x20000000 end
local color = 0x80 - math.floor(math.abs(mf.sigmoid(gene.weight)) * 0x80)
if gene.weight > 0 then color = opacity + 0x8000 + 0x10000 * color else color = opacity + 0x800000 + 0x100 * color end
forms.drawLine(netPicture, c1.x + 1, c1.y, c2.x - 3, c2.y, color)
end
end
forms.drawBox(netPicture, 49, 71, 51, 78, 0x00000000, 0x80FF0000)
local pos = 160
for mutation,rate in pairs(genome.mutationRates) do
forms.drawText(netPicture, 40, pos, mutation .. ": " .. rate, 0xFF000000, 10)
pos = pos + 15
end
forms.refresh(netPicture)
end
--##########################################################
-- File Management
--##########################################################
ff.writeFile(cnfg.PoolDir .. "temp.pool", pool)
function loadFile(filename)
local file = io.open(filename, "r")
if file == nil then return end
print("Loading pool from " .. filename)
pool = nf.newPool()
pool.generation = file:read("*number")
pool.maxFitness = file:read("*number")
forms.settext(maxLabel, "Max Fitness: " .. math.floor(pool.maxFitness))
local numSpecies = file:read("*number")
for s=1,numSpecies do
local species = nf.newSpecies()
table.insert(pool.species, species)
species.topFitness = file:read("*number")
species.staleness = file:read("*number")
local numGenomes = file:read("*number")
for g=1,numGenomes do
local genome = nf.newGenome()
table.insert(species.genomes, genome)
genome.fitness = file:read("*number")
genome.maxneuron = file:read("*number")
local line = file:read("*line")
while line ~= "done" do
genome.mutationRates[line] = file:read("*number")
line = file:read("*line")
end
local numGenes = file:read("*number")
for n=1,numGenes do
local gene = nf.newGene()
local enabled
local geneStr = file:read("*line")
local geneArr = ff.splitGeneStr(geneStr)
gene.into = tonumber(geneArr[1])
gene.out = tonumber(geneArr[2])
gene.weight = tonumber(geneArr[3])
gene.innovation = tonumber(geneArr[4])
enabled = tonumber(geneArr[5])
if enabled == 0 then gene.enabled = false else gene.enabled = true end
table.insert(genome.genes, gene)
end
end
end
file:close()
while nf.fitnessAlreadyMeasured(pool) do nextGenome() end
initializeRun()
pool.currentFrame = pool.currentFrame + 1
print("Pool loaded.")
end
function flipState()
if cnfg.Running == true then
cnfg.Running = false
forms.settext(startButton, "Start")
else
cnfg.Running = true
forms.settext(startButton, "Stop")
end
end
function savePool()
local filename = cnfg.PoolDir .. forms.gettext(saveLoadFile) .. ".gen" .. pool.generation .. ".pool"
print("Saved: " .. filename)
ff.writeFile(filename, pool)
end
function loadPool()
filename = forms.openfile()
loadFile(filename)
forms.settext(saveLoadFile, string.sub(filename, string.len(cnfg.PoolDir) + 1, (string.len(".gen" .. pool.generation .. ".pool") + 1) * -1))
end
function playTop()
local maxfitness = 0
local maxs, maxg
for s,species in pairs(pool.species) do
for g,genome in pairs(species.genomes) do
if genome.fitness > maxfitness then
maxfitness = genome.fitness
maxs = s
maxg = g
end
end
end
pool.currentSpecies = maxs
pool.currentGenome = maxg
pool.maxFitness = maxfitness
forms.settext(maxLabel, "Max Fitness: " .. math.floor(pool.maxFitness))
initializeRun()
pool.currentFrame = pool.currentFrame + 1
return
end
function onExit() forms.destroy(form) end
generationLabel = forms.label(form, "Generation: " .. pool.generation, 5, 25)
speciesLabel = forms.label(form, "Species: " .. pool.currentSpecies, 110, 25)
genomeLabel = forms.label(form, "Genome: " .. pool.currentGenome, 230, 25)
measuredLabel = forms.label(form, "Measured: " .. "", 330, 25)
fitnessLabel = forms.label(form, "Fitness: " .. "", 5, 50)
maxLabel = forms.label(form, "Max: " .. "", 110, 50)
healthLabel = forms.label(form, "Health: " .. "", 5, 95)
tanksLabel = forms.label(form, "Energy Tanks: " .. "", 110, 95)
dmgLabel = forms.label(form, "Damage: " .. "", 230, 95)
missilesLabel = forms.label(form, "Missiles: " .. "", 5, 120)
superMissilesLabel = forms.label(form, "Super Missiles: " .. "", 110, 120)
bombsLabel = forms.label(form, "Power Bombs: " .. "", 230, 120)
saveButton = forms.button(form, "Save", savePool, 15, 170)
loadButton = forms.button(form, "Load", loadPool, 95, 170)
startButton = forms.button(form, "Start", flipState, 175, 170)
if cnfg.Running == true then forms.settext(startButton, "Stop") end
restartButton = forms.button(form, "Restart", initializePool, 255, 170)
playTopButton = forms.button(form, "Play Top", playTop, 335, 170)
saveLoadLabel = forms.label(form, "Save as:", 15, 210)
saveLoadFile = forms.textbox(form, cnfg.Filename, 170, 25, nil, 15, 233)
--##########################################################
-- Reinforcement Learning
--##########################################################
while true do
if cnfg.Running == true then
local species = pool.species[pool.currentSpecies]
local genome = species.genomes[pool.currentGenome]
displayGenome(genome)
if pool.currentFrame % 5 == 0 then evaluateCurrent() end
joypad.set(controller)
-- Algorithm
game.getPositions()
if samusXprev == nil then samusXprev = samusX end
if samusYprev == nil then samusYprev = samusY end
if samusX ~= samusXprev or samusY ~= samusYprev then
diffX = samusX - samusXprev
if diffX < 0 then diffX = diffX * -1 end
diffY = samusY - samusYprev
if diffY < 0 then diffY = diffY * -1 end
explorationFitness = explorationFitness + diffX + diffY
timeout = cnfg.NeatConfig.TimeoutConstant
else
timeout = timeout - 1
end
samusXprev = samusX
samusYprev = samusY
local hitTimer = game.getSamusHitTimer()
if checkSamusCollision == true then
if hitTimer > 0 then
samusHitCounter = samusHitCounter + 1
console.writeline("Samus took damage, hit counter: " .. samusHitCounter)
checkSamusCollision = false
end
end
if hitTimer == 0 then checkSamusCollision = true end
if pool.currentFrame > 300 and pool.currentFrame % (cnfg.NeatConfig.TimeoutConstant * 10) == 0 then
if samusX == samusXprev then
explorationFitness = explorationFitness - 10000
console.writeline("Cheating detected, abort.")
timeout = -500
end
end
local timeoutBonus = pool.currentFrame / 4
if timeout + timeoutBonus <= 0 then
local missiles = game.getMissiles() - startMissiles
local superMissiles = game.getSuperMissiles() - startSuperMissiles
local bombs = game.getBombs() - startBombs
local tanks = game.getTanks() - startTanks
local pickupFitness = (missiles * 10) + (superMissiles * 100) + (bombs * 100) + (tanks * 1000)
if (missiles + superMissiles + bombs + tanks) > 0 then
console.writeline("Collected Pickups added " .. pickupFitness .. " fitness")
end
local hitPenalty = samusHitCounter * 100
local fitness = explorationFitness + pickupFitness - hitPenalty
health = game.getHealth()
if startHealth < health then
local extraHealthBonus = (health - startHealth) * 1000
fitness = fitness + extraHealthBonus
console.writeline("Extra Health added " .. extraHealthBonus .. " fitness")
end
if explorationFitness > 20000 then
fitness = fitness + 10000
console.writeline("!!!!!!Reached Ridley!!!!!!!")
end
if fitness == 0 then fitness = -1 end
genome.fitness = fitness
if fitness > pool.maxFitness then
pool.maxFitness = fitness
ff.writeFile(cnfg.PoolDir .. cnfg.Filename .. ".gen" .. pool.generation .. ".pool", pool)
end
console.writeline("Gen " .. pool.generation .. " species " .. pool.currentSpecies .. " genome " .. pool.currentGenome .. " fitness: " .. fitness)
pool.currentSpecies = 1
pool.currentGenome = 1
while nf.fitnessAlreadyMeasured(pool) do nextGenome() end
initializeRun()
end
local measured = 0
local total = 0
for _,species in pairs(pool.species) do
for _,genome in pairs(species.genomes) do
total = total + 1
if genome.fitness ~= 0 then measured = measured + 1 end
end
end
gui.drawEllipse(game.screenX-95, game.screenY-85, 200, 200, 0xAA000000)
forms.settext(generationLabel, "Generation: " .. pool.generation)
forms.settext(speciesLabel, "Species: " .. pool.currentSpecies)
forms.settext(genomeLabel, "Genome: " .. pool.currentGenome)
forms.settext(measuredLabel, "Measured: " .. math.floor(measured / total * 100) .. "%")
forms.settext(fitnessLabel, "Fitness: " .. math.floor(explorationFitness - (pool.currentFrame) / 2 - (timeout + timeoutBonus) * 2 / 3))
forms.settext(maxLabel, "Max: " .. math.floor(pool.maxFitness))
forms.settext(healthLabel, "Health: " .. health)
forms.settext(tanksLabel, "Energy Tanks: " .. (game.getTanks() - startTanks))
forms.settext(dmgLabel, "Damage: " .. samusHitCounter)
forms.settext(missilesLabel, "Missiles: " .. (game.getMissiles() - startMissiles))
forms.settext(superMissilesLabel, "Super Missiles: " .. (game.getSuperMissiles() - startSuperMissiles))
forms.settext(bombsLabel, "Power Bombs: " .. (game.getBombs() - startBombs))
pool.currentFrame = pool.currentFrame + 1
end
emu.frameadvance();
end
|
Player = Class{}
require 'Animation'
local MOVE_SPEED = 120
local JUMP_VELOCITY = 400
local GRAVITY = 40
function Player:init(map)
self.width = 16
self.height = 20
self.x = map.tileWidth * 10
self.y = map.tileHeight * (map.mapHeight / 2 - 1) - self.height
self.dx = 0
self.dy = 0
self.map = map
-- sound effects
self.sounds = {
['jump'] = love.audio.newSource('sounds/jump.wav', 'static'),
['hit'] = love.audio.newSource('sounds/hit.wav', 'static'),
['coin'] = love.audio.newSource('sounds/coin.wav', 'static')
}
self.texture = love.graphics.newImage('graphics/blue_alien.png')
self.frames = generateQuads(self.texture, self.width, self.height)
self.state = 'idle'
self.direction = 'right'
self.animations = {
['idle'] = Animation {
texture = self.texture,
frames = {
self.frames[1]
},
interval = 1
},
['walking'] = Animation {
texture = self.texture,
frames = {
self.frames[9], self.frames[10], self.frames[11]
},
interval = 0.15
},
['jumping'] = Animation {
texture = self.texture,
frames = {
self.frames[3]
},
interval = 1
}
}
self.animation = self.animations['idle']
self.behaviors = {
-- add spacebar functionality to trigger jump state
['idle'] = function(dt)
if love.keyboard.wasPressed('space') then
self.dy = -JUMP_VELOCITY
self.state = 'jumping'
self.animation = self.animations['jumping']
self.sounds['jump']:play()
elseif love.keyboard.isDown('a') then
self.direction = 'left'
self.dx = -MOVE_SPEED
self.state = 'walking'
self.animations['walking']:restart()
self.animation = self.animations['walking']
elseif love.keyboard.isDown('d') then
self.direction = 'right'
self.dx = MOVE_SPEED
self.state = 'walking'
self.animations['walking']:restart()
self.animation = self.animations['walking']
else
self.animation = self.animations['idle']
self.dx = 0
end
end,
['walking'] = function(dt)
-- keep track of input to switch movement while walking, or reset
if love.keyboard.wasPressed('space') then
self.dy = -JUMP_VELOCITY
self.state = 'jumping'
self.animation = self.animations['jumping']
self.sounds['jump']:play()
elseif love.keyboard.isDown('a') then
self.dx = -MOVE_SPEED
self.animation = self.animations['walking']
self.direction = 'left'
elseif love.keyboard.isDown('d') then
self.dx = MOVE_SPEED
self.animation = self.animations['walking']
self.direction = 'right'
else
self.dx = 0
self.state = 'idle'
self.animation = self.animations['idle']
end
-- check for collisions moving left and right
self:checkRightCollision()
self:checkLeftCollision()
-- check if there's a tile directly beneath us
if not self.map:collides(self.map:tileAt(self.x, self.y + self.height)) and
not self.map:collides(self.map:tileAt(self.x + self.width - 1, self.y + self.height)) then
-- if so, reset velocity and position and change state
self.state = 'jumping'
self.animation = self.animations['jumping']
end
end,
['jumping'] = function(dt)
-- break if we go below the surface
if self.y > 300 then
return
end
if love.keyboard.isDown('a') or love.keyboard.isDown('left') then
self.direction = 'left'
self.dx = -MOVE_SPEED
elseif love.keyboard.isDown('d') or love.keyboard.isDown('right') then
self.direction = 'right'
self.dx = MOVE_SPEED
end
-- apply map's gravity before y velocity
self.dy = self.dy + GRAVITY
-- check if there's tile directly beneath us
if self.map:collides(self.map:tileAt(self.x, self.y + self.height)) or
self.map:collides(self.map:tileAt(self.x + self.width - 1, self.y + self.height)) then
-- if so, reset velocity and position and change state
self.dy = 0
self.state = 'idle'
self.animation = self.animations['idle']
self.y = (self.map:tileAt(self.x, self.y + self.height)['y'] - 1) * self.map.tileHeight - self.height
end
-- check for collisions moving left and right
self:checkRightCollision()
self:checkLeftCollision()
end
}
end
function Player:update(dt)
self.behaviors[self.state](dt)
self.animation:update(dt)
self.x = self.x + self.dx * dt
self.y = self.y + self.dy * dt
self.x = math.max(0, self.x)
self.x = math.min(map.mapWidthPixels - self.width, self.x)
-- if we have negative y velocity (jumping), check if we collide
-- with any blocks above us
if self.dy < 0 then
if self.map:tileAt(self.x, self.y)['id'] ~= TILE_EMPTY or
self.map:tileAt(self.x, self.width - 1, self.y)['id'] ~= TILE_EMPTY then
-- reset y velocity
self.dy = 0
end
-- change block to diffrent block
local playCoin = false
local playHit = false
if self.map:tileAt(self.x, self.y)['id'] == JUMP_BLOCK then
self.map:setTile(math.floor(self.x / self.map.tileWidth) + 1,
math.floor(self.y / self.map.tileHeight) + 1, JUMP_BLOCK_HIT)
playCoin = true
else
playHit = true
end
if self.map:tileAt(self.x + self.width - 1, self.y)['id'] == JUMP_BLOCK then
self.map:setTile(math.floor((self.x + self.width - 1) / self.map.tileWidth) + 1,
math.floor(self.y / self.map.tileHeight) + 1, JUMP_BLOCK_HIT)
playCoin = true
else
playHit = true
end
if self.map:tileAt(self.x + self.width / 2, self.y)['id'] == JUMP_BLOCK then
self.map:setTile(math.floor((self.x + self.width / 2) / self.map.tileWidth) + 1,
math.floor(self.y / self.map.tileHeight) + 1, JUMP_BLOCK_HIT)
playCoin = true
else
playHit = true
end
if playCoin then
self.sounds['coin']:play()
else
self.sounds['hit']:play()
end
end
end
-- check two tiles to our left to see if a collision occurred
function Player:checkLeftCollision()
if self.dx < 0 then
-- check if there's a tile directly beneath us
if self.map:collides(self.map:tileAt(self.x - 1, self.y)) or
self.map:collides(self.map:tileAt(self.x - 1, self.y + self.height - 1)) then
-- if so, reset velocity asnd position and chnage state
self.dx = 0
self.x = self.map:tileAt(self.x - 1, self.y)['x'] * self.map.tileWidth
end
end
end
-- check two tiles to our right to see if a collision occurred
function Player:checkRightCollision()
if self.dx > 0 then
-- check if there's a tile directly beneath us
if self.map:collides(self.map:tileAt(self.x + self.width, self.y)) or
self.map:collides(self.map:tileAt(self.x + self.width, self.y + self.height - 1)) then
-- if so, reset velocity and position and change state
self.dx = 0
self.x = (self.map:tileAt(self.x + self.width, self.y)['x'] - 1) * self.map.tileWidth - self.width
end
end
end
function Player:render()
local scaleX
if self.direction == 'right' then
scaleX = 1
else
scaleX = -1
end
love.graphics.draw(self.texture, self.animation:getCurrentFrame(),
math.floor(self.x + self.width / 2), math.floor(self.y + self.height / 2),
0, scaleX, 1, -- rotaion, sc, sy
self.width / 2, self.height / 2) -- origin of x, origin of y
end |
---@class MockService
local M = {}
---@class MockContext table key protocName value args
---@type table<string, MockContext>
local responseMocks = {}
---@type table<string, MockContext>
local requestMocksAfterRequest = {}
function M.Init()
end
---@param context MockContext
function M.MockClientRequestResponse(protocName, context)
assert(not responseMocks[protocName])
responseMocks[protocName] = context
end
---@param context MockContext
function M.MockServerRequestAfterRequest(protocName, context)
requestMocksAfterRequest[protocName] = context
end
---@param client ProtocClient
function M.OnClientRequest(protocName, client)
local context = responseMocks[protocName]
if context then
for key, value in pairs(context) do
client:_OnResponse(key, value)
end
return true
end
return false
end
---@param client ProtocClient
function M.OnServerResponse(protocName, client)
M.OnServerRequest(protocName, client)
end
---@param client ProtocClient
function M.OnServerRequest(protocName, client)
local context = requestMocksAfterRequest[protocName]
if context then
for key, value in pairs(context) do
client:_OnServerRequest(key, value)
end
end
end
return M |
local helper = require("curstr.lib.testlib.helper")
local curstr = helper.require("curstr")
describe("file/search", function()
before_each(helper.before_each)
after_each(helper.after_each)
it("file_one", function()
curstr.setup({
sources = {
["file/search"] = {opts = {source_pattern = "\\v^([^#]*)#(\\w+)$", result_pattern = "\\1"}},
},
})
helper.new_file("pattern.txt")
helper.open_new_file("entry", "./pattern.txt#target_pattern")
helper.cd()
curstr.execute("file/search")
assert.file_name("pattern.txt")
assert.current_row(1)
end)
it("file_with_position", function()
curstr.setup({
sources = {
["file/search"] = {
opts = {
source_pattern = "\\v^([^#]*)#(\\w+)$",
result_pattern = "\\1",
search_pattern = "\\2:",
},
},
},
})
helper.new_file("pattern.txt", [[
test:
target_pattern:
]])
helper.open_new_file("entry", "./pattern.txt#target_pattern")
helper.cd()
curstr.execute("file/search")
assert.file_name("pattern.txt")
assert.cursor_word("target_pattern")
end)
it("not_found", function()
helper.open_new_file("entry", "./pattern.txt#target_pattern")
curstr.execute("file/search")
assert.file_name("entry")
end)
it("file_not_found", function()
helper.open_new_file("entry", "./not_found.txt")
curstr.execute("file/search")
assert.file_name("entry")
end)
end)
|
PLUGIN.name = "Alcohol"
PLUGIN.author = "AleXXX_007, Frosty"
PLUGIN.description = "Adds alcohol with effects."
ix.lang.AddTable("english", {
itemBeerDesc = "An alcoholic drink brewed from cereal grains—most commonly from malted barley, though wheat, maize (corn), and rice are also used.",
itemBourbonDesc = "A bottle of American whiskey, a barrel-aged distilled spirit made primarily from corn.",
itemMoonshineDesc = "A bottle of illegally distilled liquor that is so named because its manufacture may be conducted without artificial light at night-time.",
itemNukaColaDarkDesc = 'A ready to drink bottle of Nuka-Cola and rum boasting an alcohol-by-volume content of 35%, the beverage was touted as "the most thirst-quenching way to unwind."',
itemRumDesc = "A distilled spirit derived from fermented cane sugar and molasses.",
itemVodkaDesc = "A clear distilled alcoholic liquor made from grain mash.",
itemWhiskeyDesc = "A liquor distilled from the fermented mash of grain (as rye, corn, or barley).",
itemWineDesc = "An alcoholic beverage made by fermenting the juice of grapes.",
})
ix.lang.AddTable("korean", {
["Alcohol"] = "술",
Drink = "마시기",
["Beer"] = "맥주",
itemBeerDesc = "보리와 같은 곡물을 발효시키고 향신료인 홉을 첨가시켜 맛을 낸 술입니다.",
["Bourbon"] = "버본",
itemBourbonDesc = "미국 켄터키를 중심으로 생산되는 위스키입니다.",
["Moonshine"] = "밀주",
itemMoonshineDesc = "가정에서 양조해서 가끔씩 마시는 술로, 보통 옥수수를 주 원료로 사용한 콘 위스키의 형태를 가지고 있으며 거기에 맥아와 이스트 등을 사용해 발효한 밑술을 위의 제조 공정에 따라 증류하여 만듭니다.",
["Nuka-Cola Dark"] = "누카 콜라 다크",
itemNukaColaDarkDesc = "비쩍 타들어가는 듯한 갈증을 풀어주는 어른들의 누카 콜라입니다.",
["Rum"] = "럼",
itemRumDesc = "사탕수수를 착즙해서 설탕을 만들고 남은 찌꺼기인 당밀이나 사탕수수 즙을 발효시킨 뒤 증류한 술로, 옛날 뱃사람들이 주로 마셨다고 합니다.",
["Vodka"] = "보드카",
itemVodkaDesc = "수수, 옥수수, 감자, 밀, 호밀 등 탄수화물 함량이 높은 식물로 빚은 러시아 원산의 증류주입니다.",
["Whiskey"] = "위스키",
itemWhiskeyDesc = "스코틀랜드에서 유래한 술로 가장 유명한 증류주입니다.",
["Wine"] = "포도주",
itemWineDesc = "포도를 으깨서 나온 즙을 발효시킨 과실주로, 상류층이 주로 즐깁니다.",
["Canned Beer"] = "캔맥주",
})
function PLUGIN:Drunk(client)
local endurance = client:GetCharacter():GetAttribute("end")
local strength = client:GetCharacter():GetAttribute("str")
if endurance == nil then
endurance = 0
end
if strength then
client:GetCharacter():SetAttrib("str", strength + 3)
end
client:SetLocalVar("drunk", client:GetLocalVar("drunk") + client:GetCharacter():GetData("drunk"))
if client:GetLocalVar("drunk") > 100 then
local unctime = (client:GetLocalVar("drunk") - 100) * 7.5
client:ConCommand("say /fallover ".. unctime .."")
end
timer.Create("drunk", 5, 0, function()
client:SetLocalVar("drunk", client:GetLocalVar("drunk") - 1)
client:GetCharacter():SetData("drunk", client:GetLocalVar("drunk"))
if client:GetCharacter():GetData("drunk") == 0 then
if strength then
client:GetCharacter():SetAttrib("str", strength)
end
timer.Remove("drunk")
end
end)
end
if (SERVER) then
function PLUGIN:PostPlayerLoadout(client)
client:SetLocalVar("drunk", 0)
client:GetCharacter():SetData("drunk", 0)
end
function PLUGIN:PlayerDeath(client)
client:SetLocalVar("drunk", 0)
client:GetCharacter():SetData("drunk", 0)
end
end
if (CLIENT) then
function PLUGIN:RenderScreenspaceEffects()
local default = {}
default["$pp_colour_addr"] = 0
default["$pp_colour_addg"] = 0
default["$pp_colour_addb"] = 0
default["$pp_colour_brightness"] = 0
default["$pp_colour_contrast"] = 1
default["$pp_colour_colour"] = 0.90
default["$pp_colour_mulr"] = 0
default["$pp_colour_mulg"] = 0
default["$pp_colour_mulb"] = 0
local a = LocalPlayer():GetLocalVar("drunk")
if a == nil then
a = 0
end
if (a > 20) then
local value = (LocalPlayer():GetLocalVar("drunk"))*0.01
DrawMotionBlur( 0.2, value, 0.05 )
else
DrawColorModify(default)
end
end
end |
-- luacheck: globals __LEMUR__
local ServerStorage = game:GetService("ServerStorage")
local TestEZ = require(ServerStorage.TestEZ)
local results = TestEZ.TestBootstrap:run(ServerStorage.TestDataStoreService, TestEZ.Reporters.TextReporter)
if __LEMUR__ then
if results.failureCount > 0 then
os.exit(1)
end
end |
local util = require 'lspconfig.util'
return {
default_config = {
cmd = { 'bal' },
filetypes = { 'bal' },
root_dir = util.root_pattern('Ballerina.toml')
}
}
|
local state = { variables = {} } -- | 500 | -- Техника
-- Стейт для реализации механики ручных печатей
---------------------------------------------------------------------
function state:Load(object)
state.variables.code = ""
end
---------------------------------------------------------------------
function state:Processing(object,s)
if object:pressed("special1") then
if object:hit("up") and s.up ~= nil then
object:setFrame(s.up)
state.variables.code = state.variables.code .. "u"
elseif object:hit("down") and s.down ~= nil then
object:setFrame(s.down)
state.variables.code = state.variables.code .. "d"
elseif (object:hit("left") or object:hit("right")) and s.forward ~= nil then
if object:hit("left") then object.facing = -1 end
if object:hit("right") then object.facing = 1 end
object:setFrame(s.forward)
state.variables.code = state.variables.code .. "f"
end
if object.wait == 0 then
object.wait = object.frame.wait
end
else
if object.wait == 0 then
object:setFrame(state.variables.code)
state.variables.code = ""
end
end
end
return state |
-- Parts of this file are adapted from the ljsyscall project
-- The ljsyscall project is licensed under the MIT License,
-- and copyrighted as:
-- Copyright (C) 2011-2016 Justin Cormack. All rights reserved.
local ffi = require "ffi"
local log = require "kong.cmd.utils.log"
ffi.cdef [[
extern char **environ;
]]
local function read_all()
log.debug("reading environment variables")
local env = {}
local environ = ffi.C.environ
if not environ then
log.warn("could not access **environ")
return env
end
local i = 0
while environ[i] ~= nil do
local l = ffi.string(environ[i])
local eq = string.find(l, "=", nil, true)
if eq then
local name = string.sub(l, 1, eq - 1)
local val = string.sub(l, eq + 1)
env[name] = val
end
i = i + 1
end
return env
end
return {
read_all = read_all,
}
|
--[[
Name: "sv_hooks.lua".
Product: "kuroScript".
--]]
local MOUNT = MOUNT;
-- Called when kuroScript has loaded all of the entities.
function MOUNT:KuroScriptInitPostEntity()
self:LoadParentData();
self:LoadDoorData();
end; |
local math = require 'math'
local pairs, print, table = pairs, print, table
local maxLineLength = 80
local maxFunctionNesting = 0
local maxTableNesting = 1
local maxTableFields = 5
local maxUpvalues = 5
--- Function compares 2 table entries by LOSC
-- @param functionA First table entry
-- @param functionB Second table entry
-- @author Martin Nagy
-- @return True if functionA LOSC > functionB LOSC
local function compareLOSC(functionA, functionB)
return functionA.LOSC > functionB.LOSC
end
--- Function compares 2 table entries by NOA
-- @param functionA First table entry
-- @param functionB Second table entry
-- @author Martin Nagy
-- @return True if functionA NOA > functionB NOA
local function compareNOA(functionA, functionB)
return functionA.NOA > functionB.NOA
end
--- Function compares 2 table entries by cyclomatic
-- @param functionA First table entry
-- @param functionB Second table entry
-- @author Martin Nagy
-- @return True if functionA cyclomatic > functionB cyclomatic
local function compareCyc(functionA, functionB)
return functionA.cyclomatic > functionB.cyclomatic
end
--- Function compares 2 table entries by EFF
-- @param functionA First table entry
-- @param functionB Second table entry
-- @author Martin Nagy
-- @return True if functionA EFF > functionB EFF
local function compareHal(functionA, functionB)
return functionA.EFF > functionB.EFF
end
--- Function rounds number to n decimal places
-- @param num Number to round
-- @param numDecimalPlaces Decimal places to round
-- @author Martin Nagy
-- @return Number rounded to n decimal places
local function round(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult + 0.5) / mult
end
--- Function gets metrics from AST of file and copy them to return object
-- @param file_metricsAST_list List of AST of all files
-- @author Martin Nagy
-- @return Tables with long method, cyclomatic complexity and number of arguments code smells
local function countFunctionSmells(file_metricsAST_list)
local functionCount = 0
--Create return object
local smell = {
longMethod = {},
cyclomatic = {},
manyParameters = {},
totalFunctions = 0
}
for filename, AST in pairs(file_metricsAST_list) do --Loop through ASTs of files
for _, fun in pairs(AST.metrics.blockdata.fundefs) do --Loop through functions
--Select Global, local or functions in general
if (fun.tag == 'GlobalFunction' or fun.tag == 'LocalFunction' or fun.tag == 'Function') then
functionCount = functionCount + 1
--Only for taged functions (Not anonymous and table field)
if(fun.fcntype == 'global' or fun.fcntype == 'local') then
--Insert data to tables to use independently
table.insert(smell.longMethod, {file = filename, name = fun.name, LOC = fun.metrics.LOC.lines, LOSC = fun.metrics.LOC.lines_code})
table.insert(smell.cyclomatic, {file = filename, name = fun.name, cyclomatic = (fun.metrics.cyclomatic.decisions or 1)})
table.insert(smell.manyParameters, {file = filename, name = fun.name, NOA = fun.metrics.infoflow.arguments_in})
end
end
end
end
--Sort each table descending
table.sort(smell.longMethod, compareLOSC)
table.sort(smell.cyclomatic, compareCyc)
table.sort(smell.manyParameters, compareNOA)
smell.totalFunctions = functionCount
return smell
end
--- Function gets metrics from AST of file and counts maintainability index of project
-- @param file_metricsAST_list List of AST of all files
-- @author Martin Nagy
-- @return Maintainability index of project
local function countMI(file_metricsAST_list)
--variable preparation
local MI = 0
local cyclomatic = 0
local halsteadVol = 0
local LOSC = 0
local comments = 0
local commentPerc = 0
local files = 0
for filename, AST in pairs(file_metricsAST_list) do --Loop through ASTs of files
files = files + 1
if(AST.metrics.cyclomatic ~= nil) then --Count cyclomatic complexity
cyclomatic = cyclomatic + (AST.metrics.cyclomatic.decisions_all or 0)
end
halsteadVol = halsteadVol + AST.metrics.halstead.VOL --Count halstead volume
LOSC = LOSC + AST.metrics.LOC.lines_code --Lines of source code
comments = comments + AST.metrics.LOC.lines_comment --Count comment lines
end
--Count maintainability index
commentPerc = comments / LOSC
MI = 171
- (5.2 * math.log(halsteadVol / files))
- (0.23 * (cyclomatic / files))
- (16.2 * math.log(LOSC / files))
+ (50 * math.sin(math.sqrt(2.4 * (commentPerc / files))))
return round(MI, 2) -- Round on 2 decimal places
end
function lineSplit(text)
if sep == nil then
sep = "%s"
end
local table={} ; i=1
text = string.gsub( text, "\t", " ")
for str in string.gmatch(text, "([^\n]*)\n?") do -- '+' is for skipping over empty lines
table[i] = str
i = i + 1
end
return table
end
local function lineLength(codeText)
local lines = lineSplit(codeText)
local longLines = {}
for key, line in ipairs(lines) do
actualLineLength = #line
if(actualLineLength > maxLineLength) then
table.insert( longLines, { lineNumber = key, length = actualLineLength })
end
end
return longLines
end
--- Function gets metrics from AST of file counts module smells and return them back to AST
-- @param funcAST AST of file
-- @author Martin Nagy
-- @return AST enriched by module smells
local function countFileSmells(funcAST)
local RFC = 0 --Response for class - Sum of no. executed methods and no. methods in class (file)
local CBO = 0 --Coupling between module (file) and other big modules in whole project
local WMC = 0 --Weighted method per class - sum of cyclomatic complexity of functions in class (file)
local NOM = 0 --No. methods in class (file)
--Count RFC
for name, value in pairs(funcAST.metrics.functionExecutions) do
for name, value in pairs(value) do
RFC = RFC + 1
end
end
--Count CBO (without math module)
for name, value in pairs(funcAST.metrics.moduleCalls) do
if(name ~= 'math') then -- something is wrong - math etc. module calls contains math but not table string etc...
CBO = CBO + 1
end
end
--Add RFC and count WMC and NOM
for _, fun in pairs(funcAST.metrics.blockdata.fundefs) do
if (fun.tag == 'GlobalFunction' or fun.tag == 'LocalFunction' or fun.tag == 'Function') then
RFC = RFC + 1
WMC = WMC + (fun.metrics.cyclomatic.decisions or 1)
NOM = NOM + 1
end
end
--Add smell counts back to AST
funcAST.smells = {}
funcAST.smells.RFC = RFC
funcAST.smells.WMC = WMC
funcAST.smells.NOM = NOM
funcAST.smells.responseToNOM = round((RFC / NOM), 2)
funcAST.smells.CBO = CBO
-- TODO pridane
funcAST.smells.longLines = lineLength(funcAST.text)
end
--- Function tries to find statement in ast parents
-- @param ast AST node
-- @author Dominik Stevlik
-- @return name of table, when found
local function findStatement(ast)
local node = ast
while(node.key ~= "Stat" and node.key ~= "LastStat" and node.key ~= "FunctionCall") do
node = node.parent
end
return node
end
--- Function tries to recursively find name in ast childs
-- @param ast AST node
-- @author Dominik Stevlik
-- @return name of table, when found
local function findName(ast)
local name = nil
-- loop throught childs and find node key Name
for k,v in pairs(ast.data) do
if(v.key == "Name") then
return v.text
end
-- continue in recursion when key is not Name
name = findName(v)
if(name) then
-- return when name was found)
return name
end
end
end
--- Function tries to recursively find table name in ast
-- @param ast AST node
-- @author Dominik Stevlik
-- @return name of table
local function findTableName(ast)
local stat = findStatement(ast)
local name = nil
-- in return statement is not possible to create table with name
if(stat.key == "LastStat") then
name = "#AnonymousReturn"
elseif(stat.key == "FunctionCall") then
name = "#AnonymousFunctionParameter"
else
name = findName(stat)
end
if(name == nil) then
name = "Anonymous"
end
return name
end
--- Function tries to find parent(table constructor) of table field and checks its nested level
-- @param ast AST node
-- @param smellsTable Reference to smell table, where stores the smells
-- @author Dominik Stevlik
local function findParent(ast, smellsTable)
if(ast.key == "TableConstructor") then
-- get and store name for table, when unknown
if(ast.name == nil)then
ast.name = findTableName(ast)
end
-- initialize cont of fields to 0
if(not ast.metrics.fieldsCount) then ast.metrics.fieldsCount = 0 end
ast.metrics.fieldsCount = ast.metrics.fieldsCount + 1
-- check count of fields
if(ast.metrics.fieldsCount > maxTableFields) then
-- create table
if(not smellsTable.tableSmells.manyFields) then smellsTable.tableSmells.manyFields = {} end
-- create table
if(not smellsTable.tableSmells.manyFields[ast.name]) then
smellsTable.tableSmells.manyFields[ast.name] = {}
-- initialize count of tables with many fields to 0
if(not smellsTable.tableSmells.manyFields.count) then smellsTable.tableSmells.manyFields.count = 0 end
-- increase ount of tables with many fields
smellsTable.tableSmells.manyFields.count = smellsTable.tableSmells.manyFields.count + 1
end
-- store count of fields to smells table
smellsTable.tableSmells.manyFields[ast.name].count = ast.metrics.fieldsCount
end
return
end
-- when no table contructor, continue in recursion
findParent(ast.parent, smellsTable)
end
--- Function checks if key is key of functions
-- @param key Key of the AST node
-- @author Dominik Stevlik
-- @return true when the key is function, else return false
local function isFunction(key)
return (key == "Function" or key == "GlobalFunction" or key == "LocalFunction")
end
--- Function copy all values on keys to new table
-- @param parentTable Table to copy
-- @author Dominik Stevlik
-- @return new table or nil when parentTable is nil
function copyParents(parentTable)
if(parentTable == nil) then
return nil
end
local newTable = {}
-- loop throught parents and copy each one
for k,v in pairs(parentTable) do
table.insert( newTable, k, v )
end
return newTable
end
--- Function recursively passes ast nodes and searches for smells of tables and functions
-- @param ast AST node
-- @param functionNesting Table which holds nesting level and parents of function
-- @param tableNesting Table which holds nesting level and parents of table
-- @param smellsTable Reference to smell table, where stores the smells
-- @author Dominik Stevlik
local function recursive(ast, functionNesting, tableNesting, smellsTable)
-- set true when nesting level of function is increased, decrease nesting level and remove last parent after return from childs, when this was true
local insertedF = false
-- set true when nesting level of table is increased, decrease nesting level and remove last parent after return from childs, when this was true
local insertedT = false
if(ast) then
if(ast.key == "Field") then
-- search for table constructor
findParent(ast, smellsTable)
elseif (isFunction(ast.key)) then
if(ast.metrics == nil) then
ast.metrics = {}
end
-- store nesting level to current node
ast.metrics.depth = functionNesting.level
-- insert node name as parent for next nested functions
table.insert(functionNesting.parents, ast.name)
-- check function nesting level
if(functionNesting.level > maxFunctionNesting) then
if(not smellsTable.functionSmells[ast.name]) then
if(not smellsTable.functionSmells.count) then smellsTable.functionSmells.count = 0 end
-- increase total count of nested functions
smellsTable.functionSmells.count = smellsTable.functionSmells.count + 1
end
-- store function name, level, parents in smells table
smellsTable.functionSmells[ast.name] = { level = functionNesting.level, parents = copyParents(functionNesting.parents) }
end
-- increase nesting level
functionNesting.level = functionNesting.level + 1
-- set true for decrease nesting level after recursion
insertedF = true
elseif (ast.key == "TableConstructor") then
if(ast.name == nil) then
-- find and store table name, when unknown
ast.name = findTableName(ast)
end
-- store nesting level for table
ast.metrics.depth = tableNesting.level
-- insert node name as parent for next nested functions
table.insert(tableNesting.parents, ast.name)
-- check table nesting level
if(tableNesting.level > maxTableNesting) then
if(not smellsTable.tableSmells.depth) then smellsTable.tableSmells.depth = {} end
if(not smellsTable.tableSmells.depth[ast.name]) then
if(not smellsTable.tableSmells.depth.count) then smellsTable.tableSmells.depth.count = 0 end
-- increase total count of nested tables
smellsTable.tableSmells.depth.count = smellsTable.tableSmells.depth.count + 1
end
-- store table name, level, parents in smells table
smellsTable.tableSmells.depth[ast.name] = { level = tableNesting.level, parents = copyParents(tableNesting.parents) }
end
-- increase nesting level
tableNesting.level = tableNesting.level + 1
-- set true for decrease nesting level after recursion
insertedT = true
end
else
-- stop recursion when ast node is nil
return
end
-- continue in recursion
for key, child in pairs(ast.data) do
recursive(child, functionNesting, tableNesting, smellsTable)
end
-- when function nesting level was increased
if(insertedF) then
functionNesting.level = functionNesting.level - 1
functionNesting.parents[#functionNesting.parents] = nil -- remove last item
end
-- when table nesting level was increased
if(insertedT) then
tableNesting.level = tableNesting.level - 1
tableNesting.parents[#tableNesting.parents] = nil -- remove last item
end
end
--- Function gets upvalues from function definitions and their data
-- @param ast AST node
-- @author Dominik Stevlik
-- @return table with info(function name, variable name, number of uses) and functions(function name(as key), upvalues count)
local function getUpvalues(ast)
upvalues = {info = {}, functions = {}, totalUsages = 0}
-- loop throught all functions
for k, functionTable in pairs(ast.metrics.blockdata.fundefs) do
upvaluesCount = 0
-- loop throught all remotes
for name, vars in pairs(functionTable.metrics.blockdata.remotes) do
upvaluesCount = upvaluesCount + 1
--
--[[for _, node in pairs(vars) do
if (node.isRead) then
upvaluesCount = upvaluesCount + 1
break
end
end --]]
-- store info like function name, variable name and usage count, and create easy access to count of total upvalues
table.insert(upvalues.info, {functionName = functionTable.name, varName = name, usages = #vars})
upvalues.totalUsages = upvalues.totalUsages + #vars
--upvalues[fileName][table.name][name] = #vars
end
-- store count of variables in function
upvalues.functions[functionTable.name] = upvaluesCount
end
return upvalues
end
--- Function recursively search smells for each file in AST list
-- @param AST_list list of AST nodes
-- @author Dominik Stevlik
-- @return table with found smells
local function getSmells(AST_list)
-- table with number keys (1,2,3,....) and values (file name, smells, upvalues)
local result = {}
-- loop throught list of file AST
for file, ast in pairs(AST_list) do
local smellsTable = {tableSmells = {manyFields = {count = 0}, depth = {count = 0}}, functionSmells = {count = 0}}
recursive(ast, {level = 0, parents = {}}, {level = 0, parents = {}}, smellsTable)
-- get upvalues from blockdata
local upvalues = getUpvalues(ast)
table.insert(result, {file = file, smells = smellsTable, upvalues = upvalues})
end
return result
end
--Run countFileSmells function as capture (when creating global AST)
local captures = {
[1] = function(data) countFileSmells(data) return data end, --Run automaticaly when file AST created
}
return {
captures = captures,
countFileSmells = countFileSmells,
countMI = countMI,
countFunctionSmells = countFunctionSmells,
getSmells = getSmells
} |
-----------------------------------
--
-- Zone: Hall_of_the_Gods (251)
--
-----------------------------------
local ID = require("scripts/zones/Hall_of_the_Gods/IDs")
require("scripts/globals/conquest")
require("scripts/globals/missions")
require("scripts/globals/zone")
-----------------------------------
function onInitialize(zone)
end
function onZoneIn(player, prevZone)
local cs = -1
if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then
player:setPos(-0.011, -1.848, -176.133, 192)
elseif player:getCurrentMission(ACP) == tpz.mission.id.acp.REMEMBER_ME_IN_YOUR_DREAMS and prevZone == tpz.zone.ROMAEVE then
cs = 5
end
return cs
end
function onConquestUpdate(zone, updatetype)
tpz.conq.onConquestUpdate(zone, updatetype)
end
function onRegionEnter(player, region)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 5 then
player:completeMission(ACP, tpz.mission.id.acp.REMEMBER_ME_IN_YOUR_DREAMS)
player:addMission(ACP, tpz.mission.id.acp.BORN_OF_HER_NIGHTMARES)
end
end
|
--[[
desc: Grass, a article of grass.
author: Musoucrow
since: 2018-5-30
alter: 2018-8-10
]]--
local _RESMGR = require("actor.resmgr")
---@class Actor.Component.Article.Grass
---@field public frameaniDatas table<number, Lib.RESOURCE.FrameaniData>
local _Grass = require("core.class")()
function _Grass.HandleData(data)
for n=1, #data.frameani do
data.frameani[n] = _RESMGR.GetFrameaniData(data.frameani[n])
end
end
function _Grass:Ctor(data)
self.frameaniDatas = data.frameani
end
return _Grass |
migasiSIM_sorter = require("migasiSIM_sorter") |
local initiative = param.get("initiative", "table")
local member = param.get("member", "table") or app.session.member
-- TODO performance
local initiator
if member then
initiator = Initiator:by_pk(initiative.id, member.id)
end
local initiators_members_selector = initiative:get_reference_selector("initiating_members")
:add_field("initiator.accepted", "accepted")
:add_order_by("member.name")
if initiator and initiator.accepted then
initiators_members_selector:add_where("initiator.accepted ISNULL OR initiator.accepted")
else
initiators_members_selector:add_where("initiator.accepted")
end
local initiators = initiators_members_selector:exec()
ui.sectionHead( "initiativeInfo", function ()
ui.heading {
level = 1,
content = initiative.display_name,
attr = { rtk='initiative-id', rtv=initiative.id },
}
ui.tag{
content="",
attr = {
rtk='initiative-is-admitted',
rtv=tostring(initiative.admitted),
},
}
ui.tag{
content="",
attr = {
rtk='initiative-current_draft-external_reference',
rtv=tostring(initiative.current_draft.external_reference),
},
}
ui.container { attr = { class = "support" }, content = function ()
if initiative.supporter_count == nil then
ui.tag {
attr = { class = "supporterCount" },
content = _"[calculating]"
}
elseif initiative.issue.closed == nil then
ui.tag {
attr = { class = "satisfiedSupporterCount" },
content = _("#{count} supporter", { count = initiative.satisfied_supporter_count })
}
if initiative.potential_supporter_count and
initiative.potential_supporter_count > 0
then
slot.put ( " " )
ui.tag {
attr = { class = "potentialSupporterCount" },
content = _("(+ #{count} potential)", { count = initiative.potential_supporter_count })
}
end
end
slot.put ( "<br />" )
execute.view {
module = "initiative", view = "_bargraph", params = {
initiative = initiative
}
}
end }
if member then
ui.container { attr = { class = "mySupport right" }, content = function ()
if initiative.issue.fully_frozen then
if initiative.issue.member_info.direct_voted then
--ui.image { attr = { class = "icon48 right" }, static = "icons/48/voted_ok.png" }
ui.tag { content = _"You have voted" }
slot.put("<br />")
if not initiative.issue.closed then
ui.link {
module = "vote", view = "list",
params = { issue_id = initiative.issue.id },
text = _"change vote"
}
else
ui.link {
module = "vote", view = "list",
params = { issue_id = initiative.issue.id },
text = _"show vote"
}
end
slot.put(" ")
elseif active_trustee_id then
ui.tag { content = _"You have voted via delegation" }
ui.link {
content = _"Show voting ballot",
module = "vote", view = "list", params = {
issue_id = initiative.issue.id, member_id = active_trustee_id
}
}
elseif not initiative.issue.closed then
ui.link {
attr = { class = "btn btn-default" },
module = "vote", view = "list",
params = { issue_id = initiative.issue.id },
text = _"vote now"
}
end
elseif initiative.member_info.supported then
if initiative.member_info.satisfied then
ui.image { attr = { class = "icon48 right" }, static = "icons/32/support_satisfied.png" }
else
ui.image { attr = { class = "icon48 right" }, static = "icons/32/support_unsatisfied.png" }
end
ui.container { content = _"You are supporter" }
if initiative.issue.member_info.own_participation then
ui.link {
attr = { class = "btn-link" },
module = "initiative", action = "remove_support",
routing = { default = {
mode = "redirect", module = "initiative", view = "show", id = initiative.id
} },
id = initiative.id,
text = _"remove my support"
}
else
ui.link {
module = "delegation", view = "show", params = {
issue_id = initiative.issue_id,
initiative_id = initiative.id
},
content = _"via delegation"
}
end
slot.put(" ")
elseif not initiative.issue.closed then
ui.link {
attr = { class = "btn btn-default" },
module = "initiative", action = "add_support",
routing = { default = {
mode = "redirect", module = "initiative", view = "show", id = initiative.id
} },
id = initiative.id,
text = _"add my support"
}
end
end }
end
slot.put("<br style='clear: both;'/>")
ui.container {
attr = { class = "initiators" },
content = function ()
if app.session:has_access("authors_pseudonymous") then
for i, member in ipairs(initiators) do
if i > 1 then
slot.put(" ")
end
util.micro_avatar(member)
if member.accepted == nil then
slot.put ( " " )
ui.tag { content = _"(invited)" }
end
end -- for i, member
end
end
} -- ui.container "initiators"
ui.container {
attr = { class = "links" },
content = function ()
local drafts_count = initiative:get_reference_selector("drafts"):count()
ui.link {
content = _("suggestions (#{count}) ↓", {
count = # ( initiative.suggestions )
}),
external = "#suggestions"
}
slot.put ( " | " )
ui.link{
module = "initiative", view = "history", id = initiative.id,
content = _("draft history (#{count})", { count = drafts_count })
}
end
} -- ui.containers "links"
end )
execute.view {
module = "initiative", view = "_sidebar_state",
params = { initiative = initiative }
}
|
local L = select(2, ...).L('deDE')
L['ALT key'] = ALT_KEY
L['ALT + CTRL key'] = ALT_KEY_TEXT .. ' + ' .. CTRL_KEY
L['ALT + SHIFT key'] = ALT_KEY_TEXT .. ' + ' .. SHIFT_KEY
-- config
L['Drag items into the window below to add more.'] = 'Ziehe Gegenstände in das Fenster, um sie hinzuzufügen.'
L['Items blacklisted from potentially being processed.'] = 'Ausgeschlossene Gegenstände, die niemals verarbeitet werden.'
L['Right-click to remove item'] = 'Rechtsklicke, um den Gegenstand zu entfernen'
|
local helpers = require('test.functional.helpers')
local clear, feed = helpers.clear, helpers.feed
local eval, eq, neq = helpers.eval, helpers.eq, helpers.neq
local execute, source, expect = helpers.execute, helpers.source, helpers.expect
describe('completion', function()
before_each(function()
clear()
end)
describe('v:completed_item', function()
it('is empty dict until completion', function()
eq({}, eval('v:completed_item'))
end)
it('is empty dict if the candidate is not inserted', function()
feed('ifoo<ESC>o<C-x><C-n><C-e><ESC>')
eq({}, eval('v:completed_item'))
end)
it('returns expected dict in normal completion', function()
feed('ifoo<ESC>o<C-x><C-n><ESC>')
eq('foo', eval('getline(2)'))
eq({word = 'foo', abbr = '', menu = '', info = '', kind = ''},
eval('v:completed_item'))
end)
it('is readonly', function()
feed('ifoo<ESC>o<C-x><C-n><ESC>')
execute('let v:completed_item.word = "bar"')
neq(nil, string.find(eval('v:errmsg'), '^E46: '))
execute('let v:errmsg = ""')
execute('let v:completed_item.abbr = "bar"')
neq(nil, string.find(eval('v:errmsg'), '^E46: '))
execute('let v:errmsg = ""')
execute('let v:completed_item.menu = "bar"')
neq(nil, string.find(eval('v:errmsg'), '^E46: '))
execute('let v:errmsg = ""')
execute('let v:completed_item.info = "bar"')
neq(nil, string.find(eval('v:errmsg'), '^E46: '))
execute('let v:errmsg = ""')
execute('let v:completed_item.kind = "bar"')
neq(nil, string.find(eval('v:errmsg'), '^E46: '))
execute('let v:errmsg = ""')
end)
it('returns expected dict in omni completion', function()
source([[
function! TestOmni(findstart, base) abort
return a:findstart ? 0 : [{'word': 'foo', 'abbr': 'bar',
\ 'menu': 'baz', 'info': 'foobar', 'kind': 'foobaz'}]
endfunction
setlocal omnifunc=TestOmni
]])
feed('i<C-x><C-o><ESC>')
eq('foo', eval('getline(1)'))
eq({word = 'foo', abbr = 'bar', menu = 'baz',
info = 'foobar', kind = 'foobaz'},
eval('v:completed_item'))
end)
end)
describe('completeopt', function()
before_each(function()
source([[
function! TestComplete() abort
call complete(1, ['foo'])
return ''
endfunction
]])
end)
it('inserts the first candidate if default', function()
execute('set completeopt+=menuone')
feed('ifoo<ESC>o<C-x><C-n>bar<ESC>')
eq('foobar', eval('getline(2)'))
feed('o<C-r>=TestComplete()<CR><ESC>')
eq('foo', eval('getline(3)'))
end)
it('selects the first candidate if noinsert', function()
execute('set completeopt+=menuone,noinsert')
feed('ifoo<ESC>o<C-x><C-n><C-y><ESC>')
eq('foo', eval('getline(2)'))
feed('o<C-r>=TestComplete()<CR><C-y><ESC>')
eq('foo', eval('getline(3)'))
end)
it('does not insert the first candidate if noselect', function()
execute('set completeopt+=menuone,noselect')
feed('ifoo<ESC>o<C-x><C-n>bar<ESC>')
eq('bar', eval('getline(2)'))
feed('o<C-r>=TestComplete()<CR>bar<ESC>')
eq('bar', eval('getline(3)'))
end)
it('does not select/insert the first candidate if noselect and noinsert', function()
execute('set completeopt+=menuone,noselect,noinsert')
feed('ifoo<ESC>o<C-x><C-n><ESC>')
eq('', eval('getline(2)'))
feed('o<C-r>=TestComplete()<CR><ESC>')
eq('', eval('getline(3)'))
end)
end)
describe("refresh:always", function()
before_each(function()
source([[
function! TestCompletion(findstart, base) abort
if a:findstart
let line = getline('.')
let start = col('.') - 1
while start > 0 && line[start - 1] =~ '\a'
let start -= 1
endwhile
return start
else
let ret = []
for m in split("January February March April May June July August September October November December")
if m =~ a:base " match by regex
call add(ret, m)
endif
endfor
return {'words':ret, 'refresh':'always'}
endif
endfunction
set completeopt=menuone,noselect
set completefunc=TestCompletion
]])
end )
it('completes on each input char', function ()
feed('i<C-x><C-u>gu<Down><C-y>')
expect('August')
end)
it("repeats correctly after backspace #2674", function ()
feed('o<C-x><C-u>Ja<BS><C-n><C-n><Esc>')
feed('.')
expect([[
June
June]])
end)
end)
end)
|
-- You probably shouldnt touch these.
local AnimationDuration = -1
local ChosenAnimation = ""
local ChosenDict = ""
local IsInAnimation = false
local MostRecentChosenAnimation = ""
local MostRecentChosenDict = ""
local MovementType = 0
local PlayerGender = "male"
local PlayerHasProp = false
local PlayerProps = {}
local PlayerParticles = {}
local SecondPropEmote = false
local PtfxNotif = false
local PtfxPrompt = false
local PtfxWait = 500
local PtfxNoProp = false
Citizen.CreateThread(function()
while true do
if IsPedShooting(PlayerPedId()) and IsInAnimation then
EmoteCancel()
end
if PtfxPrompt then
if not PtfxNotif then
exports["caue-interaction"]:showInteraction(PtfxInfo)
PtfxNotif = true
end
if IsControlPressed(0, 47) then
PtfxStart()
Wait(PtfxWait)
PtfxStop()
end
end
Citizen.Wait(1)
end
end)
-----------------------------------------------------------------------------------------------------
-- Commands / Events --------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------
RegisterNetEvent("dpemotes:emotes")
AddEventHandler("dpemotes:emotes", function()
OpenEmoteMenu()
end)
RegisterNetEvent("dpemotes:e")
AddEventHandler("dpemotes:e", function(pArgs)
EmoteCommandStart(0, pArgs)
end)
RegisterNetEvent("dpemotes:binds")
AddEventHandler("dpemotes:binds", function()
EmoteBindsStart()
end)
RegisterNetEvent("dpemotes:bind")
AddEventHandler("dpemotes:bind", function(pArgs)
EmoteBindStart(0, pArgs)
end)
-----------------------------------------------------------------------------------------------------
------ Functions and stuff --------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------
function EmoteCancel()
if ChosenDict == "MaleScenario" and IsInAnimation then
ClearPedTasksImmediately(PlayerPedId())
IsInAnimation = false
elseif ChosenDict == "Scenario" and IsInAnimation then
ClearPedTasksImmediately(PlayerPedId())
IsInAnimation = false
end
if PtfxNotif then
exports["caue-interaction"]:hideInteraction()
end
PtfxNotif = false
PtfxPrompt = false
if IsInAnimation then
PtfxStop()
ClearPedTasks(PlayerPedId())
DestroyAllProps()
IsInAnimation = false
end
TriggerEvent("animation:cancel")
end
function PtfxStart()
if PtfxNoProp then
PtfxAt = PlayerPedId()
else
PtfxAt = prop
end
UseParticleFxAssetNextCall(PtfxAsset)
Ptfx = StartNetworkedParticleFxLoopedOnEntityBone(PtfxName, PtfxAt, Ptfx1, Ptfx2, Ptfx3, Ptfx4, Ptfx5, Ptfx6, GetEntityBoneIndexByName(PtfxName, "VFX"), 1065353216, 0, 0, 0, 1065353216, 1065353216, 1065353216, 0)
SetParticleFxLoopedColour(Ptfx, 1.0, 1.0, 1.0)
table.insert(PlayerParticles, Ptfx)
end
function PtfxStop()
for a,b in pairs(PlayerParticles) do
StopParticleFxLooped(b, false)
table.remove(PlayerParticles, a)
end
end
function pairsByKeys(t, f)
local a = {}
for n in pairs(t) do
table.insert(a, n)
end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then
return nil
else
return a[i], t[a[i]]
end
end
return iter
end
function EmoteMenuStart(args, hard)
local name = args
local etype = hard
if etype == "dances" then
if DP.Dances[name] ~= nil then
OnEmotePlay(DP.Dances[name])
end
elseif etype == "props" then
if DP.PropEmotes[name] ~= nil then
OnEmotePlay(DP.PropEmotes[name])
end
elseif etype == "emotes" then
if DP.Emotes[name] ~= nil then
OnEmotePlay(DP.Emotes[name])
else
if name ~= "🕺 Dance Emotes" then end
end
elseif etype == "expression" then
if DP.Expressions[name] ~= nil then
OnEmotePlay(DP.Expressions[name])
end
end
end
function EmoteCommandStart(source, args, raw)
if #args > 0 then
local name = string.lower(args[1])
if name == "c" then
EmoteCancel()
return
end
if DP.Emotes[name] ~= nil then
OnEmotePlay(DP.Emotes[name])
elseif DP.Dances[name] ~= nil then
OnEmotePlay(DP.Dances[name])
elseif DP.PropEmotes[name] ~= nil then
OnEmotePlay(DP.PropEmotes[name])
else
TriggerEvent("DoLongHudText", name .. " is not a valid emote.", 2)
end
end
end
function LoadAnim(dict)
while not HasAnimDictLoaded(dict) do
RequestAnimDict(dict)
Wait(10)
end
end
function LoadPropDict(model)
while not HasModelLoaded(GetHashKey(model)) do
RequestModel(GetHashKey(model))
Wait(10)
end
end
function PtfxThis(asset)
while not HasNamedPtfxAssetLoaded(asset) do
RequestNamedPtfxAsset(asset)
Wait(10)
end
UseParticleFxAssetNextCall(asset)
end
function DestroyAllProps()
for _,v in pairs(PlayerProps) do
DeleteEntity(v)
end
PlayerHasProp = false
end
function AddPropToPlayer(prop1, bone, off1, off2, off3, rot1, rot2, rot3)
local Player = PlayerPedId()
local x,y,z = table.unpack(GetEntityCoords(Player))
if not HasModelLoaded(prop1) then
LoadPropDict(prop1)
end
prop = CreateObject(GetHashKey(prop1), x, y, z+0.2, true, true, true)
AttachEntityToEntity(prop, Player, GetPedBoneIndex(Player, bone), off1, off2, off3, rot1, rot2, rot3, true, true, false, true, 1, true)
table.insert(PlayerProps, prop)
PlayerHasProp = true
SetModelAsNoLongerNeeded(prop1)
end
-----------------------------------------------------------------------------------------------------
-- V -- This could be a whole lot better, i tried messing around with "IsPedMale(ped)"
-- V -- But i never really figured it out, if anyone has a better way of gender checking let me know.
-- V -- Since this way doesnt work for ped models.
-- V -- in most cases its better to replace the scenario with an animation bundled with prop instead.
-----------------------------------------------------------------------------------------------------
function CheckGender()
local hashSkinMale = GetHashKey("mp_m_freemode_01")
local hashSkinFemale = GetHashKey("mp_f_freemode_01")
if GetEntityModel(PlayerPedId()) == hashSkinMale then
PlayerGender = "male"
elseif GetEntityModel(PlayerPedId()) == hashSkinFemale then
PlayerGender = "female"
end
end
-----------------------------------------------------------------------------------------------------
------ This is the major function for playing emotes! -----------------------------------------------
-----------------------------------------------------------------------------------------------------
function OnEmotePlay(EmoteName)
-- InVehicle = IsPedInAnyVehicle(PlayerPedId(), true)
-- if InVehicle == 1 then
-- return
-- end
if not DoesEntityExist(PlayerPedId()) then
return false
end
if isDisabled() then
return false
end
ChosenDict,ChosenAnimation,ename = table.unpack(EmoteName)
AnimationDuration = -1
if PlayerHasProp then
DestroyAllProps()
end
if ChosenDict == "Expression" then
TriggerEvent("expressions", {ChosenAnimation})
return
end
if ChosenDict == "MaleScenario" or "Scenario" then
CheckGender()
if ChosenDict == "MaleScenario" then if InVehicle then return end
if PlayerGender == "male" then
ClearPedTasks(PlayerPedId())
TaskStartScenarioInPlace(PlayerPedId(), ChosenAnimation, 0, true)
IsInAnimation = true
else
TriggerEvent("DoLongHudText", "This emote is male only, sorry!", 2)
end
return
elseif ChosenDict == "ScenarioObject" then if InVehicle then return end
BehindPlayer = GetOffsetFromEntityInWorldCoords(PlayerPedId(), 0.0, 0 - 0.5, -0.5);
ClearPedTasks(PlayerPedId())
TaskStartScenarioAtPosition(PlayerPedId(), ChosenAnimation, BehindPlayer["x"], BehindPlayer["y"], BehindPlayer["z"], GetEntityHeading(PlayerPedId()), 0, 1, false)
IsInAnimation = true
return
elseif ChosenDict == "Scenario" then if InVehicle then return end
ClearPedTasks(PlayerPedId())
TaskStartScenarioInPlace(PlayerPedId(), ChosenAnimation, 0, true)
IsInAnimation = true
return
end
end
LoadAnim(ChosenDict)
if EmoteName.AnimationOptions then
if EmoteName.AnimationOptions.EmoteLoop then
MovementType = 1
if EmoteName.AnimationOptions.EmoteMoving then
MovementType = 51
end
elseif EmoteName.AnimationOptions.EmoteMoving then
MovementType = 51
elseif EmoteName.AnimationOptions.EmoteMoving == false then
MovementType = 0
elseif EmoteName.AnimationOptions.EmoteStuck then
MovementType = 50
end
else
MovementType = 0
end
if InVehicle == 1 then
MovementType = 51
end
if EmoteName.AnimationOptions then
if EmoteName.AnimationOptions.EmoteDuration == nil then
EmoteName.AnimationOptions.EmoteDuration = -1
AttachWait = 0
else
AnimationDuration = EmoteName.AnimationOptions.EmoteDuration
AttachWait = EmoteName.AnimationOptions.EmoteDuration
end
if EmoteName.AnimationOptions.PtfxAsset then
PtfxAsset = EmoteName.AnimationOptions.PtfxAsset
PtfxName = EmoteName.AnimationOptions.PtfxName
if EmoteName.AnimationOptions.PtfxNoProp then
PtfxNoProp = EmoteName.AnimationOptions.PtfxNoProp
else
PtfxNoProp = false
end
Ptfx1, Ptfx2, Ptfx3, Ptfx4, Ptfx5, Ptfx6, PtfxScale = table.unpack(EmoteName.AnimationOptions.PtfxPlacement)
PtfxInfo = EmoteName.AnimationOptions.PtfxInfo
PtfxWait = EmoteName.AnimationOptions.PtfxWait
if PtfxNotif then
exports["caue-interaction"]:hideInteraction()
end
PtfxNotif = false
PtfxPrompt = true
PtfxThis(PtfxAsset)
else
PtfxPrompt = false
end
end
TaskPlayAnim(PlayerPedId(), ChosenDict, ChosenAnimation, 2.0, 2.0, AnimationDuration, MovementType, 0, false, false, false)
RemoveAnimDict(ChosenDict)
IsInAnimation = true
MostRecentDict = ChosenDict
MostRecentAnimation = ChosenAnimation
if EmoteName.AnimationOptions then
if EmoteName.AnimationOptions.Prop then
PropName = EmoteName.AnimationOptions.Prop
PropBone = EmoteName.AnimationOptions.PropBone
PropPl1, PropPl2, PropPl3, PropPl4, PropPl5, PropPl6 = table.unpack(EmoteName.AnimationOptions.PropPlacement)
if EmoteName.AnimationOptions.SecondProp then
SecondPropName = EmoteName.AnimationOptions.SecondProp
SecondPropBone = EmoteName.AnimationOptions.SecondPropBone
SecondPropPl1, SecondPropPl2, SecondPropPl3, SecondPropPl4, SecondPropPl5, SecondPropPl6 = table.unpack(EmoteName.AnimationOptions.SecondPropPlacement)
SecondPropEmote = true
else
SecondPropEmote = false
end
Wait(AttachWait)
AddPropToPlayer(PropName, PropBone, PropPl1, PropPl2, PropPl3, PropPl4, PropPl5, PropPl6)
if SecondPropEmote then
AddPropToPlayer(SecondPropName, SecondPropBone, SecondPropPl1, SecondPropPl2, SecondPropPl3, SecondPropPl4, SecondPropPl5, SecondPropPl6)
end
end
end
return true
end |
local wk = require 'which-key'
local map = require('me.settings.map').cmd_map
wk.register({
f = 'Fuzzy find a note',
}, { prefix = ';z' })
_G.my_zk = {}
_G.my_zk.find = function()
local pickers = require 'telescope.pickers'
local finders = require 'telescope.finders'
local conf = require('telescope.config').values
pickers.new({}, {
prompt_title = 'Find notes',
finder = finders.new_oneshot_job({
'zk',
'list',
'-q',
'-P',
'--format',
'{{ abs-path }}\t{{ title }}',
}, {}),
sorter = conf.generic_sorter {},
previewer = conf.file_previewer {},
}):find()
end
map{keys = "<leader>zf", to = "lua my_zk.find()", plugins = true}
-- Don't need to override any special settings for the LSP setup, so return an
-- empty table
return {}
|
---@class LossOfControl
C_LossOfControl = {}
---@param index number
---@return LossOfControlData|nil event
function C_LossOfControl.GetActiveLossOfControlData(index) end
---@param unitToken string
---@param index number
---@return LossOfControlData|nil event
function C_LossOfControl.GetActiveLossOfControlDataByUnit(unitToken, index) end
---@return number count
function C_LossOfControl.GetActiveLossOfControlDataCount() end
---@param unitToken string
---@return number count
function C_LossOfControl.GetActiveLossOfControlDataCountByUnit(unitToken) end
---@class LossOfControlData
---@field locType string
---@field spellID number
---@field displayText string
---@field iconTexture number
---@field startTime number|nil
---@field timeRemaining number|nil
---@field duration number|nil
---@field lockoutSchool number
---@field priority number
---@field displayType number
local LossOfControlData = {}
|
win = {
text = {
"You made it :)",
"Be proud of yourself!",
"",
"",
"Press ESC to quit",
"",
"Press any key to return to the menu"
}
}
function win:enter()
love.graphics.setFont(fonts.text)
end
function win:draw()
local linesTotalHeight = (fonts.text:getHeight() * #self.text)
local textOffsetY = (love.graphics.getHeight() * 0.5) - (linesTotalHeight * 0.5)
for index, line in pairs(self.text) do
love.graphics.print(line, (love.graphics.getWidth() * 0.5) - (fonts.text:getWidth(line) * 0.5), textOffsetY + (fonts.text:getHeight() * (index - 1)))
end
end
function win:keypressed(key)
if key == "escape" then
love.event.push("quit")
else
switchState("menu")
end
end
function win:mousepressed()
switchState("menu")
end |
--ZFUNC-last-v1
local function last( arr ) --> val
return arr[ #arr ]
end
return last
|
--[[
##########################################################
S V U I By: Munglunch
##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
local pairs = _G.pairs;
local ipairs = _G.ipairs;
local type = _G.type;
local error = _G.error;
local pcall = _G.pcall;
local tostring = _G.tostring;
local tonumber = _G.tonumber;
local tinsert = _G.tinsert;
local string = _G.string;
local math = _G.math;
local table = _G.table;
local band = _G.bit.band;
--[[ STRING METHODS ]]--
local format = string.format;
--[[ MATH METHODS ]]--
local abs, ceil, floor, round = math.abs, math.ceil, math.floor, math.round;
--[[ TABLE METHODS ]]--
local tremove, twipe = table.remove, table.wipe;
--BLIZZARD API
local CreateFrame = _G.CreateFrame;
local InCombatLockdown = _G.InCombatLockdown;
local GameTooltip = _G.GameTooltip;
local hooksecurefunc = _G.hooksecurefunc;
local IsAltKeyDown = _G.IsAltKeyDown;
local IsShiftKeyDown = _G.IsShiftKeyDown;
local IsControlKeyDown = _G.IsControlKeyDown;
local IsModifiedClick = _G.IsModifiedClick;
local PlaySound = _G.PlaySound;
local PlaySoundFile = _G.PlaySoundFile;
local PlayMusic = _G.PlayMusic;
local StopMusic = _G.StopMusic;
local GetTime = _G.GetTime;
local C_Timer = _G.C_Timer;
local GetAchievementInfo = _G.GetAchievementInfo;
local GetAchievementLink = _G.GetAchievementLink;
local GetTrackedAchievements = _G.GetTrackedAchievements;
local GetAchievementNumCriteria = _G.GetAchievementNumCriteria;
local GetAchievementCriteriaInfo = _G.GetAchievementCriteriaInfo;
local CRITERIA_TYPE_ACHIEVEMENT = _G.CRITERIA_TYPE_ACHIEVEMENT;
local TRACKER_HEADER_ACHIEVEMENTS = _G.TRACKER_HEADER_ACHIEVEMENTS;
local EVALUATION_TREE_FLAG_PROGRESS_BAR = _G.EVALUATION_TREE_FLAG_PROGRESS_BAR;
--[[
##########################################################
GET ADDON DATA
##########################################################
]]--
local SV = _G['SVUI']
local L = SV.L
local LSM = _G.LibStub("LibSharedMedia-3.0")
local MOD = SV.QuestTracker;
--[[
##########################################################
LOCALS
##########################################################
]]--
local ROW_WIDTH = 300;
local ROW_HEIGHT = 20;
local INNER_HEIGHT = ROW_HEIGHT - 4;
local LARGE_ROW_HEIGHT = ROW_HEIGHT * 2;
local LARGE_INNER_HEIGHT = LARGE_ROW_HEIGHT - 4;
local NO_ICON = SV.NoTexture;
local OBJ_ICON_ACTIVE = [[Interface\COMMON\Indicator-Yellow]];
local OBJ_ICON_COMPLETE = [[Interface\COMMON\Indicator-Green]];
local OBJ_ICON_INCOMPLETE = [[Interface\COMMON\Indicator-Gray]];
local LINE_ACHIEVEMENT_ICON = [[Interface\ICONS\Achievement_General]];
local MAX_OBJECTIVES_SHOWN = 8;
--[[
##########################################################
SCRIPT HANDLERS
##########################################################
]]--
local RowButton_OnEnter = function(self, ...)
GameTooltip:SetOwner(self, "ANCHOR_BOTTOMLEFT", 0, ROW_HEIGHT)
GameTooltip:ClearLines()
GameTooltip:AddLine("View this in the achievements window.")
GameTooltip:Show()
end
local RowButton_OnLeave = function(self, ...)
GameTooltip:Hide()
end
local ViewButton_OnClick = function(self, button)
local achievementID = self:GetID();
if(achievementID and (achievementID ~= 0)) then
if(IsModifiedClick("CHATLINK") and ChatEdit_GetActiveWindow()) then
local achievementLink = GetAchievementLink(achievementID);
if(achievementLink) then
ChatEdit_InsertLink(achievementLink);
end
else
CloseDropDownMenus();
if(not AchievementFrame ) then
AchievementFrame_LoadUI();
end
if(IsModifiedClick("QUESTWATCHTOGGLE") ) then
AchievementObjectiveTracker_UntrackAchievement(self, achievementID);
elseif(not AchievementFrame:IsShown()) then
AchievementFrame_ToggleAchievementFrame();
AchievementFrame_SelectAchievement(achievementID);
else
if(AchievementFrameAchievements.selection ~= achievementID) then
AchievementFrame_SelectAchievement(achievementID);
else
AchievementFrame_ToggleAchievementFrame();
end
end
end
end
end
--[[
##########################################################
TRACKER FUNCTIONS
##########################################################
]]--
local GetAchievementRow = function(self, index)
if(not self.Rows[index]) then
local previousFrame = self.Rows[#self.Rows]
local index = #self.Rows + 1;
local anchorFrame;
if(previousFrame and previousFrame.Objectives) then
anchorFrame = previousFrame.Objectives;
else
anchorFrame = self.Header;
end
local row = CreateFrame("Frame", nil, self)
row:SetPoint("TOPLEFT", anchorFrame, "BOTTOMLEFT", 0, -2);
row:SetPoint("TOPRIGHT", anchorFrame, "BOTTOMRIGHT", 0, -2);
row:SetHeight(ROW_HEIGHT);
row.Badge = CreateFrame("Frame", nil, row)
row.Badge:SetPoint("TOPLEFT", row, "TOPLEFT", 2, -2);
row.Badge:SetSize(INNER_HEIGHT, INNER_HEIGHT);
row.Badge:SetStyle("Frame", "Lite")
row.Badge.Icon = row.Badge:CreateTexture(nil,"OVERLAY")
row.Badge.Icon:SetAllPoints(row.Badge);
row.Badge.Icon:SetTexture(LINE_ACHIEVEMENT_ICON)
row.Badge.Icon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
row.Header = CreateFrame("Frame", nil, row)
row.Header:SetPoint("TOPLEFT", row.Badge, "TOPRIGHT", 2, 0);
row.Header:SetPoint("TOPRIGHT", row, "TOPRIGHT", -2, 0);
row.Header:SetHeight(INNER_HEIGHT);
row.Header.Text = row.Header:CreateFontString(nil,"OVERLAY")
row.Header.Text:SetFontObject(SVUI_Font_Quest);
row.Header.Text:SetJustifyH('LEFT')
row.Header.Text:SetTextColor(1,1,0)
row.Header.Text:SetText('')
row.Header.Text:SetPoint("TOPLEFT", row.Header, "TOPLEFT", 4, 0);
row.Header.Text:SetPoint("BOTTOMRIGHT", row.Header, "BOTTOMRIGHT", 0, 0);
row.Button = CreateFrame("Button", nil, row.Header)
row.Button:SetAllPoints(row.Header);
row.Button:SetStyle("LiteButton")
row.Button:SetID(0)
row.Button:RegisterForClicks("LeftButtonUp", "RightButtonUp")
row.Button:SetScript("OnClick", ViewButton_OnClick)
row.Button:SetScript("OnEnter", RowButton_OnEnter)
row.Button:SetScript("OnLeave", RowButton_OnLeave)
row.Objectives = MOD:NewObjectiveHeader(row);
row.Objectives:SetPoint("TOPLEFT", row, "BOTTOMLEFT", 0, 0);
row.Objectives:SetPoint("TOPRIGHT", row, "BOTTOMRIGHT", 0, 0);
row.Objectives:SetHeight(1);
row.RowID = 0;
self.Rows[index] = row;
return row;
end
return self.Rows[index];
end
local SetAchievementRow = function(self, index, title, details, icon, achievementID)
index = index + 1;
icon = icon or LINE_ACHIEVEMENT_ICON;
local fill_height = 0;
local shown_objectives = 0;
local objective_rows = 0;
local row = self:Get(index);
row.RowID = achievementID
row.Header.Text:SetText(title)
row.Badge.Icon:SetTexture(icon);
row.Badge:SetAlpha(1);
row.Button:Enable();
row.Button:SetID(achievementID);
row:SetHeight(ROW_HEIGHT);
row:FadeIn();
row.Header:FadeIn();
local objective_block = row.Objectives;
local subCount = GetAchievementNumCriteria(achievementID);
for i = 1, subCount do
local description, category, completed, quantity, totalQuantity, _, flags, assetID, quantityString, criteriaID, eligible, duration, elapsed = GetAchievementCriteriaInfo(achievementID, i);
if(completed or (shown_objectives > MAX_OBJECTIVES_SHOWN and not completed)) then
--DO NOTHING
elseif(shown_objectives == MAX_OBJECTIVES_SHOWN and subCount > (MAX_OBJECTIVES_SHOWN + 1)) then
shown_objectives = shown_objectives + 1;
else
if(description and band(flags, EVALUATION_TREE_FLAG_PROGRESS_BAR) == EVALUATION_TREE_FLAG_PROGRESS_BAR) then
if(string.find(quantityString:lower(), "interface\\moneyframe")) then
description = quantityString.."\n"..description;
else
description = string.gsub(quantityString, " / ", "/").." "..description;
end
else
if(category == CRITERIA_TYPE_ACHIEVEMENT and assetID) then
_, description = GetAchievementInfo(assetID);
end
end
if(description and description ~= '') then
shown_objectives = shown_objectives + 1;
fill_height = fill_height + (ROW_HEIGHT + 2);
objective_rows = objective_block:SetInfo(objective_rows, description, completed)
if(duration and elapsed and elapsed < duration) then
fill_height = fill_height + (ROW_HEIGHT + 2);
objective_rows = objective_block:SetTimer(objective_rows, duration, elapsed);
end
end
end
end
if(objective_rows > 0) then
objective_block:SetHeight(fill_height);
objective_block:FadeIn();
end
fill_height = fill_height + (ROW_HEIGHT + 2);
return index, fill_height;
end
local RefreshAchievements = function(self, event, ...)
local list = { GetTrackedAchievements() };
local fill_height = 0;
local rows = 0;
if(#list > 0) then
for i = 1, #list do
local achievementID = list[i];
local _, title, _, completed, _, _, _, details, _, icon, _, _, wasEarnedByMe = GetAchievementInfo(achievementID);
if(not wasEarnedByMe) then
local add_height = 0;
rows, add_height = self:Set(rows, title, details, icon, achievementID)
fill_height = fill_height + add_height
end
end
end
if(rows == 0 or (fill_height <= 1)) then
self:SetHeight(1);
self.Header.Text:SetText('');
self.Header:SetAlpha(0);
self:SetAlpha(0);
else
self:SetHeight(fill_height + 2);
self.Header.Text:SetText(TRACKER_HEADER_ACHIEVEMENTS);
self:FadeIn();
self.Header:FadeIn();
end
end
local ResetAchievementBlock = function(self)
for x = 1, #self.Rows do
local row = self.Rows[x]
if(row) then
row.RowID = 0;
row.Header.Text:SetText('');
row.Header:SetAlpha(0);
row.Button:Disable();
row.Button:SetID(0);
row.Badge.Icon:SetTexture(NO_ICON);
row.Badge:SetAlpha(0);
row:SetHeight(1);
row:SetAlpha(0);
row.Objectives:Reset();
end
end
end
--[[
##########################################################
CORE FUNCTIONS
##########################################################
]]--
function MOD:UpdateAchievements(event, ...)
self.Headers["Achievements"]:Reset()
self.Headers["Achievements"]:Refresh(event, ...)
self:UpdateDimensions();
end
local function UpdateAchievementLocals(...)
ROW_WIDTH, ROW_HEIGHT, INNER_HEIGHT, LARGE_ROW_HEIGHT, LARGE_INNER_HEIGHT = ...;
end
function MOD:InitializeAchievements()
local scrollChild = self.Docklet.ScrollFrame.ScrollChild;
local achievements = CreateFrame("Frame", nil, scrollChild)
achievements:SetWidth(ROW_WIDTH);
achievements:SetHeight(ROW_HEIGHT);
achievements:SetPoint("TOPLEFT", self.Headers["Quests"], "BOTTOMLEFT", 0, -6);
achievements.Header = CreateFrame("Frame", nil, achievements)
achievements.Header:SetPoint("TOPLEFT", achievements, "TOPLEFT", 2, -2);
achievements.Header:SetPoint("TOPRIGHT", achievements, "TOPRIGHT", -2, -2);
achievements.Header:SetHeight(INNER_HEIGHT);
achievements.Header.Text = achievements.Header:CreateFontString(nil,"OVERLAY")
achievements.Header.Text:SetPoint("TOPLEFT", achievements.Header, "TOPLEFT", 2, 0);
achievements.Header.Text:SetPoint("BOTTOMLEFT", achievements.Header, "BOTTOMLEFT", 2, 0);
achievements.Header.Text:SetFontObject(SVUI_Font_Quest_Header);
achievements.Header.Text:SetJustifyH('LEFT')
achievements.Header.Text:SetTextColor(0.28,0.75,1)
achievements.Header.Text:SetText(TRACKER_HEADER_ACHIEVEMENTS)
achievements.Header.Divider = achievements.Header:CreateTexture(nil, 'BACKGROUND');
achievements.Header.Divider:SetPoint("TOPLEFT", achievements.Header.Text, "TOPRIGHT", -10, 0);
achievements.Header.Divider:SetPoint("BOTTOMRIGHT", achievements.Header, "BOTTOMRIGHT", 0, 0);
achievements.Header.Divider:SetTexture([[Interface\AddOns\SVUI_!Core\assets\textures\DROPDOWN-DIVIDER]]);
achievements.Rows = {};
achievements.Get = GetAchievementRow;
achievements.Set = SetAchievementRow;
achievements.Refresh = RefreshAchievements;
achievements.Reset = ResetAchievementBlock;
self.Headers["Achievements"] = achievements;
self:RegisterEvent("TRACKED_ACHIEVEMENT_UPDATE", self.UpdateAchievements);
self:RegisterEvent("TRACKED_ACHIEVEMENT_LIST_CHANGED", self.UpdateAchievements);
self.Headers["Achievements"]:Refresh()
SV.Events:On("QUEST_UPVALUES_UPDATED", UpdateAchievementLocals, true);
end
|
return{
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x7e,0x81,0xa5,0x81,0xbd,0x99,0x81,0x7e,
0x7e,0xff,0xdb,0xff,0xc3,0xe7,0xff,0x7e,
0x6c,0xfe,0xfe,0xfe,0x7c,0x38,0x10,0x00,
0x10,0x38,0x7c,0xfe,0x7c,0x38,0x10,0x00,
0x38,0x7c,0x38,0xfe,0xfe,0x7c,0x38,0x7c,
0x10,0x10,0x38,0x7c,0xfe,0x7c,0x38,0x7c,
0x00,0x00,0x18,0x3c,0x3c,0x18,0x00,0x00,
0xff,0xff,0xe7,0xc3,0xc3,0xe7,0xff,0xff,
0x00,0x3c,0x66,0x42,0x42,0x66,0x3c,0x00,
0xff,0xc3,0x99,0xbd,0xbd,0x99,0xc3,0xff,
0x0f,0x07,0x0f,0x7d,0xcc,0xcc,0xcc,0x78,
0x3c,0x66,0x66,0x66,0x3c,0x18,0x7e,0x18,
0x3f,0x33,0x3f,0x30,0x30,0x70,0xf0,0xe0,
0x7f,0x63,0x7f,0x63,0x63,0x67,0xe6,0xc0,
0x99,0x5a,0x3c,0xe7,0xe7,0x3c,0x5a,0x99,
0x80,0xe0,0xf8,0xfe,0xf8,0xe0,0x80,0x00,
0x02,0x0e,0x3e,0xfe,0x3e,0x0e,0x02,0x00,
0x18,0x3c,0x7e,0x18,0x18,0x7e,0x3c,0x18,
0x66,0x66,0x66,0x66,0x66,0x00,0x66,0x00,
0x7f,0xdb,0xdb,0x7b,0x1b,0x1b,0x1b,0x00,
0x3e,0x63,0x38,0x6c,0x6c,0x38,0xcc,0x78,
0x00,0x00,0x00,0x00,0x7e,0x7e,0x7e,0x00,
0x18,0x3c,0x7e,0x18,0x7e,0x3c,0x18,0xff,
0x18,0x3c,0x7e,0x18,0x18,0x18,0x18,0x00,
0x18,0x18,0x18,0x18,0x7e,0x3c,0x18,0x00,
0x00,0x18,0x0c,0xfe,0x0c,0x18,0x00,0x00,
0x00,0x30,0x60,0xfe,0x60,0x30,0x00,0x00,
0x00,0x00,0xc0,0xc0,0xc0,0xfe,0x00,0x00,
0x00,0x24,0x66,0xff,0x66,0x24,0x00,0x00,
0x00,0x18,0x3c,0x7e,0xff,0xff,0x00,0x00,
0x00,0xff,0xff,0x7e,0x3c,0x18,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x30,0x78,0x78,0x30,0x30,0x00,0x30,0x00,
0x6c,0x6c,0x6c,0x00,0x00,0x00,0x00,0x00,
0x6c,0x6c,0xfe,0x6c,0xfe,0x6c,0x6c,0x00,
0x30,0x7c,0xc0,0x78,0x0c,0xf8,0x30,0x00,
0x00,0xc6,0xcc,0x18,0x30,0x66,0xc6,0x00,
0x38,0x6c,0x38,0x76,0xdc,0xcc,0x76,0x00,
0x60,0x60,0xc0,0x00,0x00,0x00,0x00,0x00,
0x18,0x30,0x60,0x60,0x60,0x30,0x18,0x00,
0x60,0x30,0x18,0x18,0x18,0x30,0x60,0x00,
0x00,0x66,0x3c,0xff,0x3c,0x66,0x00,0x00,
0x00,0x30,0x30,0xfc,0x30,0x30,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x60,
0x00,0x00,0x00,0xfc,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x30,0x30,0x00,
0x06,0x0c,0x18,0x30,0x60,0xc0,0x80,0x00,
0x7c,0xc6,0xce,0xde,0xf6,0xe6,0x7c,0x00,
0x30,0x70,0x30,0x30,0x30,0x30,0xfc,0x00,
0x78,0xcc,0x0c,0x38,0x60,0xcc,0xfc,0x00,
0x78,0xcc,0x0c,0x38,0x0c,0xcc,0x78,0x00,
0x1c,0x3c,0x6c,0xcc,0xfe,0x0c,0x1e,0x00,
0xfc,0xc0,0xf8,0x0c,0x0c,0xcc,0x78,0x00,
0x38,0x60,0xc0,0xf8,0xcc,0xcc,0x78,0x00,
0xfc,0xcc,0x0c,0x18,0x30,0x30,0x30,0x00,
0x78,0xcc,0xcc,0x78,0xcc,0xcc,0x78,0x00,
0x78,0xcc,0xcc,0x7c,0x0c,0x18,0x70,0x00,
0x00,0x30,0x30,0x00,0x00,0x30,0x30,0x00,
0x00,0x30,0x30,0x00,0x00,0x30,0x30,0x60,
0x18,0x30,0x60,0xc0,0x60,0x30,0x18,0x00,
0x00,0x00,0xfc,0x00,0x00,0xfc,0x00,0x00,
0x60,0x30,0x18,0x0c,0x18,0x30,0x60,0x00,
0x78,0xcc,0x0c,0x18,0x30,0x00,0x30,0x00,
0x7c,0xc6,0xde,0xde,0xde,0xc0,0x78,0x00,
0x30,0x78,0xcc,0xcc,0xfc,0xcc,0xcc,0x00,
0xfc,0x66,0x66,0x7c,0x66,0x66,0xfc,0x00,
0x3c,0x66,0xc0,0xc0,0xc0,0x66,0x3c,0x00,
0xf8,0x6c,0x66,0x66,0x66,0x6c,0xf8,0x00,
0xfe,0x62,0x68,0x78,0x68,0x62,0xfe,0x00,
0xfe,0x62,0x68,0x78,0x68,0x60,0xf0,0x00,
0x3c,0x66,0xc0,0xc0,0xce,0x66,0x3e,0x00,
0xcc,0xcc,0xcc,0xfc,0xcc,0xcc,0xcc,0x00,
0x78,0x30,0x30,0x30,0x30,0x30,0x78,0x00,
0x1e,0x0c,0x0c,0x0c,0xcc,0xcc,0x78,0x00,
0xe6,0x66,0x6c,0x78,0x6c,0x66,0xe6,0x00,
0xf0,0x60,0x60,0x60,0x62,0x66,0xfe,0x00,
0xc6,0xee,0xfe,0xfe,0xd6,0xc6,0xc6,0x00,
0xc6,0xe6,0xf6,0xde,0xce,0xc6,0xc6,0x00,
0x38,0x6c,0xc6,0xc6,0xc6,0x6c,0x38,0x00,
0xfc,0x66,0x66,0x7c,0x60,0x60,0xf0,0x00,
0x78,0xcc,0xcc,0xcc,0xdc,0x78,0x1c,0x00,
0xfc,0x66,0x66,0x7c,0x6c,0x66,0xe6,0x00,
0x78,0xcc,0xe0,0x70,0x1c,0xcc,0x78,0x00,
0xfc,0xb4,0x30,0x30,0x30,0x30,0x78,0x00,
0xcc,0xcc,0xcc,0xcc,0xcc,0xcc,0xfc,0x00,
0xcc,0xcc,0xcc,0xcc,0xcc,0x78,0x30,0x00,
0xc6,0xc6,0xc6,0xd6,0xfe,0xee,0xc6,0x00,
0xc6,0xc6,0x6c,0x38,0x38,0x6c,0xc6,0x00,
0xcc,0xcc,0xcc,0x78,0x30,0x30,0x78,0x00,
0xfe,0xc6,0x8c,0x18,0x32,0x66,0xfe,0x00,
0x78,0x60,0x60,0x60,0x60,0x60,0x78,0x00,
0xc0,0x60,0x30,0x18,0x0c,0x06,0x02,0x00,
0x78,0x18,0x18,0x18,0x18,0x18,0x78,0x00,
0x10,0x38,0x6c,0xc6,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,
0x30,0x30,0x18,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x78,0x0c,0x7c,0xcc,0x76,0x00,
0xe0,0x60,0x60,0x7c,0x66,0x66,0xdc,0x00,
0x00,0x00,0x78,0xcc,0xc0,0xcc,0x78,0x00,
0x1c,0x0c,0x0c,0x7c,0xcc,0xcc,0x76,0x00,
0x00,0x00,0x78,0xcc,0xfc,0xc0,0x78,0x00,
0x38,0x6c,0x60,0xf0,0x60,0x60,0xf0,0x00,
0x00,0x00,0x76,0xcc,0xcc,0x7c,0x0c,0xf8,
0xe0,0x60,0x6c,0x76,0x66,0x66,0xe6,0x00,
0x30,0x00,0x70,0x30,0x30,0x30,0x78,0x00,
0x0c,0x00,0x0c,0x0c,0x0c,0xcc,0xcc,0x78,
0xe0,0x60,0x66,0x6c,0x78,0x6c,0xe6,0x00,
0x70,0x30,0x30,0x30,0x30,0x30,0x78,0x00,
0x00,0x00,0xcc,0xfe,0xfe,0xd6,0xc6,0x00,
0x00,0x00,0xf8,0xcc,0xcc,0xcc,0xcc,0x00,
0x00,0x00,0x78,0xcc,0xcc,0xcc,0x78,0x00,
0x00,0x00,0xdc,0x66,0x66,0x7c,0x60,0xf0,
0x00,0x00,0x76,0xcc,0xcc,0x7c,0x0c,0x1e,
0x00,0x00,0xdc,0x76,0x66,0x60,0xf0,0x00,
0x00,0x00,0x7c,0xc0,0x78,0x0c,0xf8,0x00,
0x10,0x30,0x7c,0x30,0x30,0x34,0x18,0x00,
0x00,0x00,0xcc,0xcc,0xcc,0xcc,0x76,0x00,
0x00,0x00,0xcc,0xcc,0xcc,0x78,0x30,0x00,
0x00,0x00,0xc6,0xd6,0xfe,0xfe,0x6c,0x00,
0x00,0x00,0xc6,0x6c,0x38,0x6c,0xc6,0x00,
0x00,0x00,0xcc,0xcc,0xcc,0x7c,0x0c,0xf8,
0x00,0x00,0xfc,0x98,0x30,0x64,0xfc,0x00,
0x1c,0x30,0x30,0xe0,0x30,0x30,0x1c,0x00,
0x18,0x18,0x18,0x00,0x18,0x18,0x18,0x00,
0xe0,0x30,0x30,0x1c,0x30,0x30,0xe0,0x00,
0x76,0xdc,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x10,0x38,0x6c,0xc6,0xc6,0xfe,0x00}
|
local concord = require("lib.concord")
local components = require("components")
local updateViewSectors = concord.system({components.viewSector})
local insert, tau, cos, sin = table.insert, math.tau, math.cos, math.sin
local function generate(e, collider, viewSector)
local vertices = {}
local falloff = viewSector.falloff
local angle = viewSector.fov
insert(vertices, 0)
insert(vertices, 0)
for theta = -angle/2, angle/2, angle / 4 do -- TODO: Sort out this maths (it was done with little water in my brain)
theta = -theta % tau - tau/2
insert(vertices, falloff * cos(theta + tau/4))
insert(vertices, falloff * sin(theta + tau/4))
end
if viewSector.shape then collider:remove(viewSector.shape) end
viewSector.shape = collider:polygon(unpack(vertices))
viewSector.basePolygon = viewSector.shape._polygon
viewSector.currentFalloff, viewSector.currentFov = falloff, angle -- Yes, we're up to date.
end
local function update(e, collider, viewSector)
local epos = e:get(components.position)
viewSector.shape._polygon = viewSector.basePolygon:clone()
viewSector.shape:move(epos.x, epos.y)
viewSector.shape:rotate(epos.theta + math.tau / 2, epos.x, epos.y)
end
function updateViewSectors:update()
local collider = self:getInstance().collider
for i = 1, self.pool.size do
local e = self.pool:get(i)
local viewSector = e:get(components.viewSector)
local ai = e:get(components.ai)
local updateForDraw = e:has(components.camera)
local updateForThink = ai and ai.active and (ai.following or ai.pathfinding)
if updateForDraw or updateForThink then
if not (viewSector.currentFalloff == viewSector.falloff and viewSector.currentFov == viewSector.fov) or not viewSector.basePolygon then
generate(e, collider, viewSector)
end
update(e, collider, viewSector)
end
end
end
return updateViewSectors
|
local argparse = grin.getPackageAPI("Team-CC-Corp/Grin", "argparse")
local parser = argparse.new()
parser
:switch"n"
parser
:argument"args"
:count"*"
local options = parser:parse({args={}}, ...)
if not options then
return
end
if options.n then
write(table.concat(options.args, " "))
else
print(table.concat(options.args, " "))
end
|
local path = require 'pl.path'
local hasMoon, moonscript = pcall(require, 'moonscript')
return function()
local loadOutputHandler = function(busted, output, options)
local handlers = {}
local success, err = pcall(function()
for word in output:gmatch("%a+") do
if word:match('%.lua$') then
table.insert(handlers, dofile(path.normpath(word)))
elseif hasMoon and word:match('%.moon$') then
table.insert(handlers, moonscript.dofile(path.normpath(word)))
else
table.insert(handlers, require('busted.outputHandlers.' .. word))
end
end
end)
if not success and err:match("module '.-' not found:") then
success, err = pcall(function() handler = require(output) end)
end
if not success then
busted.publish({ 'error', 'output' }, { descriptor = 'output', name = output }, nil, err, {})
handler = require('busted.outputHandlers.' .. options.defaultOutput)
end
if options.enableSound then
require 'busted.outputHandlers.sound'(options)
end
for _, handler in pairs(handlers) do
handler(options):subscribe(options)
end
end
return loadOutputHandler
end
|
local Stack = require 'stack'
describe('Stack', function()
describe(':push', function()
it('adds an element to the stack', function()
local stack = Stack:new()
stack:push(1)
assert.are.equal(1, #stack._stack)
end)
it('records minimum values when inserted', function()
local stack = Stack:new()
stack:push(1)
assert.are.equal(1, stack:min())
end)
end)
describe(':pop', function()
it('removes and returns the top element', function()
local stack = Stack:new()
stack:push(1)
local top = stack:pop()
assert.are.equal(1, top)
assert.are.equal(0, #stack._stack)
end)
it('returns nil for an empty stack', function()
local stack = Stack:new()
local top = stack:pop()
assert.is_nil(top)
end)
it('removes min from stack if the top element was minimal', function()
local stack = Stack:new()
stack:push(1)
stack:pop()
assert.is_nil(stack:min())
end)
end)
describe(':min', function()
it('returns the minimum value in the stack', function()
local stack = Stack:new()
stack:push(1)
stack:push(2)
local min = stack:min()
assert.are.equal(1, min)
end)
it('returns nil for an empty stack', function()
local stack = Stack:new()
local min = stack:min()
assert.is_nil(min)
end)
it('resets min after a minimum value was popped', function()
local stack = Stack:new()
stack:push(2)
stack:push(1)
stack:pop()
assert.are.equal(2, stack:min())
end)
end)
describe(':max', function()
it('returns the maximum value in the stack', function()
local stack = Stack:new()
stack:push(1)
stack:push(2)
local max = stack:max()
assert.are.equal(2, max)
end)
it('returns nil for an empty stack', function()
local stack = Stack:new()
local max = stack:max()
assert.is_nil(max)
end)
it('resets min after a minimum value was popped', function()
local stack = Stack:new()
stack:push(1)
stack:push(2)
stack:pop()
assert.are.equal(1, stack:max())
end)
end)
end)
|
local checkpoints = require("Checkpoints/checkpoints")
local key_blocks = require("Modules.GetimOliver.key_blocks")
local volcana3 = {
identifier = "volcana3",
title = "Volcana 3: Fire Walker",
theme = THEME.VOLCANA,
width = 4,
height = 4,
file_name = "volc-3.lvl",
world = 3,
level = 3,
}
local level_state = {
loaded = false,
callbacks = {},
}
volcana3.load_level = function()
if level_state.loaded then return end
level_state.loaded = true
checkpoints.activate()
key_blocks.activate(level_state)
if not checkpoints.get_saved_checkpoint() then
toast(volcana3.title)
end
end
volcana3.unload_level = function()
if not level_state.loaded then return end
checkpoints.deactivate()
key_blocks.deactivate()
local callbacks_to_clear = level_state.callbacks
level_state.loaded = false
level_state.callbacks = {}
for _,callback in ipairs(callbacks_to_clear) do
clear_callback(callback)
end
end
return volcana3
|
local fs = require("fs")
local separator = package.config:match("^([^\n]*)")
local moduleDir = "node_modules"
local packageFile = "package.json"
local function getMain (modulePath)
local packagePath = modulePath..separator..packageFile
if not fs.isFile(packagePath) then
return
end
local content = fs.read(packagePath)
if content then
local main = content:match("\"main\": \"([^\"]+)\"")
return modulePath..separator..main
end
end
local function splitPath (path)
return path:gmatch("[^/\\]+")
end
local function joinPaths (dirs)
return table.concat(dirs, separator)
end
local function checkModule (path, request)
if fs.isDirectory(path..separator..moduleDir..separator..request) and
fs.isFile(path..separator..moduleDir..separator..request..separator..packageFile)
then
return true
else
return false
end
end
local function loadModule (path, request)
local main = getMain(path..separator..moduleDir..separator..request)
print(main)
return fs.load(main)
end
local function nodeResolve (request)
local cwd = fs.currentDir()
local paths = {}
for path in splitPath(cwd) do
table.insert(paths, path)
end
if #paths == 0 then
table.insert(paths, "")
end
while #paths > 0 do
local path = joinPaths(paths)
if checkModule(path, request) then
return loadModule(path, request)
end
table.remove(paths, #paths)
end
end
if package.loaders ~= nil then
table.insert(package.loaders, 2, nodeResolve)
elseif package.searchers ~= nil then
table.insert(package.searchers, 2, nodeResolve)
end
|
--- GENERATED CODE - DO NOT MODIFY
-- AWS CodeBuild (codebuild-2016-10-06)
local M = {}
M.metadata = {
api_version = "2016-10-06",
json_version = "1.1",
protocol = "json",
checksum_format = "",
endpoint_prefix = "codebuild",
service_abbreviation = "",
service_full_name = "AWS CodeBuild",
signature_version = "v4",
target_prefix = "CodeBuild_20161006",
timestamp_format = "",
global_endpoint = "",
uid = "codebuild-2016-10-06",
}
local keys = {}
local asserts = {}
keys.EnvironmentPlatform = { ["languages"] = true, ["platform"] = true, nil }
function asserts.AssertEnvironmentPlatform(struct)
assert(struct)
assert(type(struct) == "table", "Expected EnvironmentPlatform to be of type 'table'")
if struct["languages"] then asserts.AssertEnvironmentLanguages(struct["languages"]) end
if struct["platform"] then asserts.AssertPlatformType(struct["platform"]) end
for k,_ in pairs(struct) do
assert(keys.EnvironmentPlatform[k], "EnvironmentPlatform contains unknown key " .. tostring(k))
end
end
--- Create a structure of type EnvironmentPlatform
-- <p>A set of Docker images that are related by platform and are managed by AWS CodeBuild.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * languages [EnvironmentLanguages] <p>The list of programming languages that are available for the specified platform.</p>
-- * platform [PlatformType] <p>The platform's name.</p>
-- @return EnvironmentPlatform structure as a key-value pair table
function M.EnvironmentPlatform(args)
assert(args, "You must provide an argument table when creating EnvironmentPlatform")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["languages"] = args["languages"],
["platform"] = args["platform"],
}
asserts.AssertEnvironmentPlatform(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.BatchDeleteBuildsInput = { ["ids"] = true, nil }
function asserts.AssertBatchDeleteBuildsInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected BatchDeleteBuildsInput to be of type 'table'")
assert(struct["ids"], "Expected key ids to exist in table")
if struct["ids"] then asserts.AssertBuildIds(struct["ids"]) end
for k,_ in pairs(struct) do
assert(keys.BatchDeleteBuildsInput[k], "BatchDeleteBuildsInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type BatchDeleteBuildsInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * ids [BuildIds] <p>The IDs of the builds to delete.</p>
-- Required key: ids
-- @return BatchDeleteBuildsInput structure as a key-value pair table
function M.BatchDeleteBuildsInput(args)
assert(args, "You must provide an argument table when creating BatchDeleteBuildsInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["ids"] = args["ids"],
}
asserts.AssertBatchDeleteBuildsInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.StartBuildInput = { ["sourceLocationOverride"] = true, ["sourceTypeOverride"] = true, ["timeoutInMinutesOverride"] = true, ["secondarySourcesVersionOverride"] = true, ["privilegedModeOverride"] = true, ["secondaryArtifactsOverride"] = true, ["sourceVersion"] = true, ["idempotencyToken"] = true, ["logsConfigOverride"] = true, ["secondarySourcesOverride"] = true, ["insecureSslOverride"] = true, ["environmentVariablesOverride"] = true, ["computeTypeOverride"] = true, ["projectName"] = true, ["gitCloneDepthOverride"] = true, ["certificateOverride"] = true, ["buildspecOverride"] = true, ["environmentTypeOverride"] = true, ["serviceRoleOverride"] = true, ["sourceAuthOverride"] = true, ["imageOverride"] = true, ["reportBuildStatusOverride"] = true, ["artifactsOverride"] = true, ["cacheOverride"] = true, nil }
function asserts.AssertStartBuildInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected StartBuildInput to be of type 'table'")
assert(struct["projectName"], "Expected key projectName to exist in table")
if struct["sourceLocationOverride"] then asserts.AssertString(struct["sourceLocationOverride"]) end
if struct["sourceTypeOverride"] then asserts.AssertSourceType(struct["sourceTypeOverride"]) end
if struct["timeoutInMinutesOverride"] then asserts.AssertTimeOut(struct["timeoutInMinutesOverride"]) end
if struct["secondarySourcesVersionOverride"] then asserts.AssertProjectSecondarySourceVersions(struct["secondarySourcesVersionOverride"]) end
if struct["privilegedModeOverride"] then asserts.AssertWrapperBoolean(struct["privilegedModeOverride"]) end
if struct["secondaryArtifactsOverride"] then asserts.AssertProjectArtifactsList(struct["secondaryArtifactsOverride"]) end
if struct["sourceVersion"] then asserts.AssertString(struct["sourceVersion"]) end
if struct["idempotencyToken"] then asserts.AssertString(struct["idempotencyToken"]) end
if struct["logsConfigOverride"] then asserts.AssertLogsConfig(struct["logsConfigOverride"]) end
if struct["secondarySourcesOverride"] then asserts.AssertProjectSources(struct["secondarySourcesOverride"]) end
if struct["insecureSslOverride"] then asserts.AssertWrapperBoolean(struct["insecureSslOverride"]) end
if struct["environmentVariablesOverride"] then asserts.AssertEnvironmentVariables(struct["environmentVariablesOverride"]) end
if struct["computeTypeOverride"] then asserts.AssertComputeType(struct["computeTypeOverride"]) end
if struct["projectName"] then asserts.AssertNonEmptyString(struct["projectName"]) end
if struct["gitCloneDepthOverride"] then asserts.AssertGitCloneDepth(struct["gitCloneDepthOverride"]) end
if struct["certificateOverride"] then asserts.AssertString(struct["certificateOverride"]) end
if struct["buildspecOverride"] then asserts.AssertString(struct["buildspecOverride"]) end
if struct["environmentTypeOverride"] then asserts.AssertEnvironmentType(struct["environmentTypeOverride"]) end
if struct["serviceRoleOverride"] then asserts.AssertNonEmptyString(struct["serviceRoleOverride"]) end
if struct["sourceAuthOverride"] then asserts.AssertSourceAuth(struct["sourceAuthOverride"]) end
if struct["imageOverride"] then asserts.AssertNonEmptyString(struct["imageOverride"]) end
if struct["reportBuildStatusOverride"] then asserts.AssertWrapperBoolean(struct["reportBuildStatusOverride"]) end
if struct["artifactsOverride"] then asserts.AssertProjectArtifacts(struct["artifactsOverride"]) end
if struct["cacheOverride"] then asserts.AssertProjectCache(struct["cacheOverride"]) end
for k,_ in pairs(struct) do
assert(keys.StartBuildInput[k], "StartBuildInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type StartBuildInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * sourceLocationOverride [String] <p>A location that overrides for this build the source location for the one defined in the build project.</p>
-- * sourceTypeOverride [SourceType] <p>A source input type for this build that overrides the source input defined in the build project.</p>
-- * timeoutInMinutesOverride [TimeOut] <p>The number of build timeout minutes, from 5 to 480 (8 hours), that overrides, for this build only, the latest setting already defined in the build project.</p>
-- * secondarySourcesVersionOverride [ProjectSecondarySourceVersions] <p> An array of <code>ProjectSourceVersion</code> objects that specify one or more versions of the project's secondary sources to be used for this build only. </p>
-- * privilegedModeOverride [WrapperBoolean] <p>Enable this flag to override privileged mode in the build project.</p>
-- * secondaryArtifactsOverride [ProjectArtifactsList] <p> An array of <code>ProjectArtifacts</code> objects. </p>
-- * sourceVersion [String] <p>A version of the build input to be built, for this build only. If not specified, the latest version will be used. If specified, must be one of:</p> <ul> <li> <p>For AWS CodeCommit: the commit ID to use.</p> </li> <li> <p>For GitHub: the commit ID, pull request ID, branch name, or tag name that corresponds to the version of the source code you want to build. If a pull request ID is specified, it must use the format <code>pr/pull-request-ID</code> (for example <code>pr/25</code>). If a branch name is specified, the branch's HEAD commit ID will be used. If not specified, the default branch's HEAD commit ID will be used.</p> </li> <li> <p>For Bitbucket: the commit ID, branch name, or tag name that corresponds to the version of the source code you want to build. If a branch name is specified, the branch's HEAD commit ID will be used. If not specified, the default branch's HEAD commit ID will be used.</p> </li> <li> <p>For Amazon Simple Storage Service (Amazon S3): the version ID of the object representing the build input ZIP file to use.</p> </li> </ul>
-- * idempotencyToken [String] <p>A unique, case sensitive identifier you provide to ensure the idempotency of the StartBuild request. The token is included in the StartBuild request and is valid for 12 hours. If you repeat the StartBuild request with the same token, but change a parameter, AWS CodeBuild returns a parameter mismatch error. </p>
-- * logsConfigOverride [LogsConfig] <p> Log settings for this build that override the log settings defined in the build project. </p>
-- * secondarySourcesOverride [ProjectSources] <p> An array of <code>ProjectSource</code> objects. </p>
-- * insecureSslOverride [WrapperBoolean] <p>Enable this flag to override the insecure SSL setting that is specified in the build project. The insecure SSL setting determines whether to ignore SSL warnings while connecting to the project source code. This override applies only if the build's source is GitHub Enterprise.</p>
-- * environmentVariablesOverride [EnvironmentVariables] <p>A set of environment variables that overrides, for this build only, the latest ones already defined in the build project.</p>
-- * computeTypeOverride [ComputeType] <p>The name of a compute type for this build that overrides the one specified in the build project.</p>
-- * projectName [NonEmptyString] <p>The name of the AWS CodeBuild build project to start running a build.</p>
-- * gitCloneDepthOverride [GitCloneDepth] <p>The user-defined depth of history, with a minimum value of 0, that overrides, for this build only, any previous depth of history defined in the build project.</p>
-- * certificateOverride [String] <p>The name of a certificate for this build that overrides the one specified in the build project.</p>
-- * buildspecOverride [String] <p>A build spec declaration that overrides, for this build only, the latest one already defined in the build project.</p>
-- * environmentTypeOverride [EnvironmentType] <p>A container type for this build that overrides the one specified in the build project.</p>
-- * serviceRoleOverride [NonEmptyString] <p>The name of a service role for this build that overrides the one specified in the build project.</p>
-- * sourceAuthOverride [SourceAuth] <p>An authorization type for this build that overrides the one defined in the build project. This override applies only if the build project's source is BitBucket or GitHub.</p>
-- * imageOverride [NonEmptyString] <p>The name of an image for this build that overrides the one specified in the build project.</p>
-- * reportBuildStatusOverride [WrapperBoolean] <p> Set to true to report to your source provider the status of a build's start and completion. If you use this option with a source provider other than GitHub, an invalidInputException is thrown. </p>
-- * artifactsOverride [ProjectArtifacts] <p>Build output artifact settings that override, for this build only, the latest ones already defined in the build project.</p>
-- * cacheOverride [ProjectCache] <p>A ProjectCache object specified for this build that overrides the one defined in the build project.</p>
-- Required key: projectName
-- @return StartBuildInput structure as a key-value pair table
function M.StartBuildInput(args)
assert(args, "You must provide an argument table when creating StartBuildInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["sourceLocationOverride"] = args["sourceLocationOverride"],
["sourceTypeOverride"] = args["sourceTypeOverride"],
["timeoutInMinutesOverride"] = args["timeoutInMinutesOverride"],
["secondarySourcesVersionOverride"] = args["secondarySourcesVersionOverride"],
["privilegedModeOverride"] = args["privilegedModeOverride"],
["secondaryArtifactsOverride"] = args["secondaryArtifactsOverride"],
["sourceVersion"] = args["sourceVersion"],
["idempotencyToken"] = args["idempotencyToken"],
["logsConfigOverride"] = args["logsConfigOverride"],
["secondarySourcesOverride"] = args["secondarySourcesOverride"],
["insecureSslOverride"] = args["insecureSslOverride"],
["environmentVariablesOverride"] = args["environmentVariablesOverride"],
["computeTypeOverride"] = args["computeTypeOverride"],
["projectName"] = args["projectName"],
["gitCloneDepthOverride"] = args["gitCloneDepthOverride"],
["certificateOverride"] = args["certificateOverride"],
["buildspecOverride"] = args["buildspecOverride"],
["environmentTypeOverride"] = args["environmentTypeOverride"],
["serviceRoleOverride"] = args["serviceRoleOverride"],
["sourceAuthOverride"] = args["sourceAuthOverride"],
["imageOverride"] = args["imageOverride"],
["reportBuildStatusOverride"] = args["reportBuildStatusOverride"],
["artifactsOverride"] = args["artifactsOverride"],
["cacheOverride"] = args["cacheOverride"],
}
asserts.AssertStartBuildInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DeleteWebhookOutput = { nil }
function asserts.AssertDeleteWebhookOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected DeleteWebhookOutput to be of type 'table'")
for k,_ in pairs(struct) do
assert(keys.DeleteWebhookOutput[k], "DeleteWebhookOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DeleteWebhookOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- @return DeleteWebhookOutput structure as a key-value pair table
function M.DeleteWebhookOutput(args)
assert(args, "You must provide an argument table when creating DeleteWebhookOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
}
asserts.AssertDeleteWebhookOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.InvalidateProjectCacheOutput = { nil }
function asserts.AssertInvalidateProjectCacheOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected InvalidateProjectCacheOutput to be of type 'table'")
for k,_ in pairs(struct) do
assert(keys.InvalidateProjectCacheOutput[k], "InvalidateProjectCacheOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type InvalidateProjectCacheOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- @return InvalidateProjectCacheOutput structure as a key-value pair table
function M.InvalidateProjectCacheOutput(args)
assert(args, "You must provide an argument table when creating InvalidateProjectCacheOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
}
asserts.AssertInvalidateProjectCacheOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListCuratedEnvironmentImagesOutput = { ["platforms"] = true, nil }
function asserts.AssertListCuratedEnvironmentImagesOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListCuratedEnvironmentImagesOutput to be of type 'table'")
if struct["platforms"] then asserts.AssertEnvironmentPlatforms(struct["platforms"]) end
for k,_ in pairs(struct) do
assert(keys.ListCuratedEnvironmentImagesOutput[k], "ListCuratedEnvironmentImagesOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListCuratedEnvironmentImagesOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * platforms [EnvironmentPlatforms] <p>Information about supported platforms for Docker images that are managed by AWS CodeBuild.</p>
-- @return ListCuratedEnvironmentImagesOutput structure as a key-value pair table
function M.ListCuratedEnvironmentImagesOutput(args)
assert(args, "You must provide an argument table when creating ListCuratedEnvironmentImagesOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["platforms"] = args["platforms"],
}
asserts.AssertListCuratedEnvironmentImagesOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.BuildNotDeleted = { ["id"] = true, ["statusCode"] = true, nil }
function asserts.AssertBuildNotDeleted(struct)
assert(struct)
assert(type(struct) == "table", "Expected BuildNotDeleted to be of type 'table'")
if struct["id"] then asserts.AssertNonEmptyString(struct["id"]) end
if struct["statusCode"] then asserts.AssertString(struct["statusCode"]) end
for k,_ in pairs(struct) do
assert(keys.BuildNotDeleted[k], "BuildNotDeleted contains unknown key " .. tostring(k))
end
end
--- Create a structure of type BuildNotDeleted
-- <p>Information about a build that could not be successfully deleted.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * id [NonEmptyString] <p>The ID of the build that could not be successfully deleted.</p>
-- * statusCode [String] <p>Additional information about the build that could not be successfully deleted.</p>
-- @return BuildNotDeleted structure as a key-value pair table
function M.BuildNotDeleted(args)
assert(args, "You must provide an argument table when creating BuildNotDeleted")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["id"] = args["id"],
["statusCode"] = args["statusCode"],
}
asserts.AssertBuildNotDeleted(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Project = { ["logsConfig"] = true, ["timeoutInMinutes"] = true, ["vpcConfig"] = true, ["name"] = true, ["serviceRole"] = true, ["tags"] = true, ["artifacts"] = true, ["lastModified"] = true, ["cache"] = true, ["webhook"] = true, ["created"] = true, ["environment"] = true, ["source"] = true, ["badge"] = true, ["secondaryArtifacts"] = true, ["secondarySources"] = true, ["encryptionKey"] = true, ["arn"] = true, ["description"] = true, nil }
function asserts.AssertProject(struct)
assert(struct)
assert(type(struct) == "table", "Expected Project to be of type 'table'")
if struct["logsConfig"] then asserts.AssertLogsConfig(struct["logsConfig"]) end
if struct["timeoutInMinutes"] then asserts.AssertTimeOut(struct["timeoutInMinutes"]) end
if struct["vpcConfig"] then asserts.AssertVpcConfig(struct["vpcConfig"]) end
if struct["name"] then asserts.AssertProjectName(struct["name"]) end
if struct["serviceRole"] then asserts.AssertNonEmptyString(struct["serviceRole"]) end
if struct["tags"] then asserts.AssertTagList(struct["tags"]) end
if struct["artifacts"] then asserts.AssertProjectArtifacts(struct["artifacts"]) end
if struct["lastModified"] then asserts.AssertTimestamp(struct["lastModified"]) end
if struct["cache"] then asserts.AssertProjectCache(struct["cache"]) end
if struct["webhook"] then asserts.AssertWebhook(struct["webhook"]) end
if struct["created"] then asserts.AssertTimestamp(struct["created"]) end
if struct["environment"] then asserts.AssertProjectEnvironment(struct["environment"]) end
if struct["source"] then asserts.AssertProjectSource(struct["source"]) end
if struct["badge"] then asserts.AssertProjectBadge(struct["badge"]) end
if struct["secondaryArtifacts"] then asserts.AssertProjectArtifactsList(struct["secondaryArtifacts"]) end
if struct["secondarySources"] then asserts.AssertProjectSources(struct["secondarySources"]) end
if struct["encryptionKey"] then asserts.AssertNonEmptyString(struct["encryptionKey"]) end
if struct["arn"] then asserts.AssertString(struct["arn"]) end
if struct["description"] then asserts.AssertProjectDescription(struct["description"]) end
for k,_ in pairs(struct) do
assert(keys.Project[k], "Project contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Project
-- <p>Information about a build project.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * logsConfig [LogsConfig] <p> Information about logs for the build project. A project can create Amazon CloudWatch Logs, logs in an S3 bucket, or both. </p>
-- * timeoutInMinutes [TimeOut] <p>How long, in minutes, from 5 to 480 (8 hours), for AWS CodeBuild to wait before timing out any related build that did not get marked as completed. The default is 60 minutes.</p>
-- * vpcConfig [VpcConfig] <p>Information about the VPC configuration that AWS CodeBuild will access.</p>
-- * name [ProjectName] <p>The name of the build project.</p>
-- * serviceRole [NonEmptyString] <p>The ARN of the AWS Identity and Access Management (IAM) role that enables AWS CodeBuild to interact with dependent AWS services on behalf of the AWS account.</p>
-- * tags [TagList] <p>The tags for this build project.</p> <p>These tags are available for use by AWS services that support AWS CodeBuild build project tags.</p>
-- * artifacts [ProjectArtifacts] <p>Information about the build output artifacts for the build project.</p>
-- * lastModified [Timestamp] <p>When the build project's settings were last modified, expressed in Unix time format.</p>
-- * cache [ProjectCache] <p>Information about the cache for the build project.</p>
-- * webhook [Webhook] <p>Information about a webhook in GitHub that connects repository events to a build project in AWS CodeBuild.</p>
-- * created [Timestamp] <p>When the build project was created, expressed in Unix time format.</p>
-- * environment [ProjectEnvironment] <p>Information about the build environment for this build project.</p>
-- * source [ProjectSource] <p>Information about the build input source code for this build project.</p>
-- * badge [ProjectBadge] <p>Information about the build badge for the build project.</p>
-- * secondaryArtifacts [ProjectArtifactsList] <p> An array of <code>ProjectArtifacts</code> objects. </p>
-- * secondarySources [ProjectSources] <p> An array of <code>ProjectSource</code> objects. </p>
-- * encryptionKey [NonEmptyString] <p>The AWS Key Management Service (AWS KMS) customer master key (CMK) to be used for encrypting the build output artifacts.</p> <p>This is expressed either as the CMK's Amazon Resource Name (ARN) or, if specified, the CMK's alias (using the format <code>alias/<i>alias-name</i> </code>).</p>
-- * arn [String] <p>The Amazon Resource Name (ARN) of the build project.</p>
-- * description [ProjectDescription] <p>A description that makes the build project easy to identify.</p>
-- @return Project structure as a key-value pair table
function M.Project(args)
assert(args, "You must provide an argument table when creating Project")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["logsConfig"] = args["logsConfig"],
["timeoutInMinutes"] = args["timeoutInMinutes"],
["vpcConfig"] = args["vpcConfig"],
["name"] = args["name"],
["serviceRole"] = args["serviceRole"],
["tags"] = args["tags"],
["artifacts"] = args["artifacts"],
["lastModified"] = args["lastModified"],
["cache"] = args["cache"],
["webhook"] = args["webhook"],
["created"] = args["created"],
["environment"] = args["environment"],
["source"] = args["source"],
["badge"] = args["badge"],
["secondaryArtifacts"] = args["secondaryArtifacts"],
["secondarySources"] = args["secondarySources"],
["encryptionKey"] = args["encryptionKey"],
["arn"] = args["arn"],
["description"] = args["description"],
}
asserts.AssertProject(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListProjectsInput = { ["nextToken"] = true, ["sortBy"] = true, ["sortOrder"] = true, nil }
function asserts.AssertListProjectsInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListProjectsInput to be of type 'table'")
if struct["nextToken"] then asserts.AssertNonEmptyString(struct["nextToken"]) end
if struct["sortBy"] then asserts.AssertProjectSortByType(struct["sortBy"]) end
if struct["sortOrder"] then asserts.AssertSortOrderType(struct["sortOrder"]) end
for k,_ in pairs(struct) do
assert(keys.ListProjectsInput[k], "ListProjectsInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListProjectsInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * nextToken [NonEmptyString] <p>During a previous call, if there are more than 100 items in the list, only the first 100 items are returned, along with a unique string called a <i>next token</i>. To get the next batch of items in the list, call this operation again, adding the next token to the call. To get all of the items in the list, keep calling this operation with each subsequent next token that is returned, until no more next tokens are returned.</p>
-- * sortBy [ProjectSortByType] <p>The criterion to be used to list build project names. Valid values include:</p> <ul> <li> <p> <code>CREATED_TIME</code>: List the build project names based on when each build project was created.</p> </li> <li> <p> <code>LAST_MODIFIED_TIME</code>: List the build project names based on when information about each build project was last changed.</p> </li> <li> <p> <code>NAME</code>: List the build project names based on each build project's name.</p> </li> </ul> <p>Use <code>sortOrder</code> to specify in what order to list the build project names based on the preceding criteria.</p>
-- * sortOrder [SortOrderType] <p>The order in which to list build projects. Valid values include:</p> <ul> <li> <p> <code>ASCENDING</code>: List the build project names in ascending order.</p> </li> <li> <p> <code>DESCENDING</code>: List the build project names in descending order.</p> </li> </ul> <p>Use <code>sortBy</code> to specify the criterion to be used to list build project names.</p>
-- @return ListProjectsInput structure as a key-value pair table
function M.ListProjectsInput(args)
assert(args, "You must provide an argument table when creating ListProjectsInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["nextToken"] = args["nextToken"],
["sortBy"] = args["sortBy"],
["sortOrder"] = args["sortOrder"],
}
asserts.AssertListProjectsInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ProjectArtifacts = { ["packaging"] = true, ["name"] = true, ["artifactIdentifier"] = true, ["namespaceType"] = true, ["encryptionDisabled"] = true, ["location"] = true, ["overrideArtifactName"] = true, ["path"] = true, ["type"] = true, nil }
function asserts.AssertProjectArtifacts(struct)
assert(struct)
assert(type(struct) == "table", "Expected ProjectArtifacts to be of type 'table'")
assert(struct["type"], "Expected key type to exist in table")
if struct["packaging"] then asserts.AssertArtifactPackaging(struct["packaging"]) end
if struct["name"] then asserts.AssertString(struct["name"]) end
if struct["artifactIdentifier"] then asserts.AssertString(struct["artifactIdentifier"]) end
if struct["namespaceType"] then asserts.AssertArtifactNamespace(struct["namespaceType"]) end
if struct["encryptionDisabled"] then asserts.AssertWrapperBoolean(struct["encryptionDisabled"]) end
if struct["location"] then asserts.AssertString(struct["location"]) end
if struct["overrideArtifactName"] then asserts.AssertWrapperBoolean(struct["overrideArtifactName"]) end
if struct["path"] then asserts.AssertString(struct["path"]) end
if struct["type"] then asserts.AssertArtifactsType(struct["type"]) end
for k,_ in pairs(struct) do
assert(keys.ProjectArtifacts[k], "ProjectArtifacts contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ProjectArtifacts
-- <p>Information about the build output artifacts for the build project.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * packaging [ArtifactPackaging] <p>The type of build output artifact to create, as follows:</p> <ul> <li> <p>If <code>type</code> is set to <code>CODEPIPELINE</code>, then AWS CodePipeline will ignore this value if specified. This is because AWS CodePipeline manages its build output artifacts instead of AWS CodeBuild.</p> </li> <li> <p>If <code>type</code> is set to <code>NO_ARTIFACTS</code>, then this value will be ignored if specified, because no build output will be produced.</p> </li> <li> <p>If <code>type</code> is set to <code>S3</code>, valid values include:</p> <ul> <li> <p> <code>NONE</code>: AWS CodeBuild will create in the output bucket a folder containing the build output. This is the default if <code>packaging</code> is not specified.</p> </li> <li> <p> <code>ZIP</code>: AWS CodeBuild will create in the output bucket a ZIP file containing the build output.</p> </li> </ul> </li> </ul>
-- * name [String] <p>Along with <code>path</code> and <code>namespaceType</code>, the pattern that AWS CodeBuild will use to name and store the output artifact, as follows:</p> <ul> <li> <p>If <code>type</code> is set to <code>CODEPIPELINE</code>, then AWS CodePipeline will ignore this value if specified. This is because AWS CodePipeline manages its build output names instead of AWS CodeBuild.</p> </li> <li> <p>If <code>type</code> is set to <code>NO_ARTIFACTS</code>, then this value will be ignored if specified, because no build output will be produced.</p> </li> <li> <p>If <code>type</code> is set to <code>S3</code>, this is the name of the output artifact object. If you set the name to be a forward slash ("/"), then the artifact is stored in the root of the output bucket.</p> </li> </ul> <p>For example:</p> <ul> <li> <p> If <code>path</code> is set to <code>MyArtifacts</code>, <code>namespaceType</code> is set to <code>BUILD_ID</code>, and <code>name</code> is set to <code>MyArtifact.zip</code>, then the output artifact would be stored in <code>MyArtifacts/<i>build-ID</i>/MyArtifact.zip</code>. </p> </li> <li> <p> If <code>path</code> is empty, <code>namespaceType</code> is set to <code>NONE</code>, and <code>name</code> is set to "<code>/</code>", then the output artifact would be stored in the root of the output bucket. </p> </li> <li> <p> If <code>path</code> is set to <code>MyArtifacts</code>, <code>namespaceType</code> is set to <code>BUILD_ID</code>, and <code>name</code> is set to "<code>/</code>", then the output artifact would be stored in <code>MyArtifacts/<i>build-ID</i> </code>. </p> </li> </ul>
-- * artifactIdentifier [String] <p> An identifier for this artifact definition. </p>
-- * namespaceType [ArtifactNamespace] <p>Along with <code>path</code> and <code>name</code>, the pattern that AWS CodeBuild will use to determine the name and location to store the output artifact, as follows:</p> <ul> <li> <p>If <code>type</code> is set to <code>CODEPIPELINE</code>, then AWS CodePipeline will ignore this value if specified. This is because AWS CodePipeline manages its build output names instead of AWS CodeBuild.</p> </li> <li> <p>If <code>type</code> is set to <code>NO_ARTIFACTS</code>, then this value will be ignored if specified, because no build output will be produced.</p> </li> <li> <p>If <code>type</code> is set to <code>S3</code>, then valid values include:</p> <ul> <li> <p> <code>BUILD_ID</code>: Include the build ID in the location of the build output artifact.</p> </li> <li> <p> <code>NONE</code>: Do not include the build ID. This is the default if <code>namespaceType</code> is not specified.</p> </li> </ul> </li> </ul> <p>For example, if <code>path</code> is set to <code>MyArtifacts</code>, <code>namespaceType</code> is set to <code>BUILD_ID</code>, and <code>name</code> is set to <code>MyArtifact.zip</code>, then the output artifact would be stored in <code>MyArtifacts/<i>build-ID</i>/MyArtifact.zip</code>.</p>
-- * encryptionDisabled [WrapperBoolean] <p> Set to true if you do not want your output artifacts encrypted. This option is only valid if your artifacts type is Amazon S3. If this is set with another artifacts type, an invalidInputException will be thrown. </p>
-- * location [String] <p>Information about the build output artifact location, as follows:</p> <ul> <li> <p>If <code>type</code> is set to <code>CODEPIPELINE</code>, then AWS CodePipeline will ignore this value if specified. This is because AWS CodePipeline manages its build output locations instead of AWS CodeBuild.</p> </li> <li> <p>If <code>type</code> is set to <code>NO_ARTIFACTS</code>, then this value will be ignored if specified, because no build output will be produced.</p> </li> <li> <p>If <code>type</code> is set to <code>S3</code>, this is the name of the output bucket.</p> </li> </ul>
-- * overrideArtifactName [WrapperBoolean] <p> If this flag is set, a name specified in the buildspec file overrides the artifact name. The name specified in a buildspec file is calculated at build time and uses the Shell Command Language. For example, you can append a date and time to your artifact name so that it is always unique. </p>
-- * path [String] <p>Along with <code>namespaceType</code> and <code>name</code>, the pattern that AWS CodeBuild will use to name and store the output artifact, as follows:</p> <ul> <li> <p>If <code>type</code> is set to <code>CODEPIPELINE</code>, then AWS CodePipeline will ignore this value if specified. This is because AWS CodePipeline manages its build output names instead of AWS CodeBuild.</p> </li> <li> <p>If <code>type</code> is set to <code>NO_ARTIFACTS</code>, then this value will be ignored if specified, because no build output will be produced.</p> </li> <li> <p>If <code>type</code> is set to <code>S3</code>, this is the path to the output artifact. If <code>path</code> is not specified, then <code>path</code> will not be used.</p> </li> </ul> <p>For example, if <code>path</code> is set to <code>MyArtifacts</code>, <code>namespaceType</code> is set to <code>NONE</code>, and <code>name</code> is set to <code>MyArtifact.zip</code>, then the output artifact would be stored in the output bucket at <code>MyArtifacts/MyArtifact.zip</code>.</p>
-- * type [ArtifactsType] <p>The type of build output artifact. Valid values include:</p> <ul> <li> <p> <code>CODEPIPELINE</code>: The build project will have build output generated through AWS CodePipeline.</p> </li> <li> <p> <code>NO_ARTIFACTS</code>: The build project will not produce any build output.</p> </li> <li> <p> <code>S3</code>: The build project will store build output in Amazon Simple Storage Service (Amazon S3).</p> </li> </ul>
-- Required key: type
-- @return ProjectArtifacts structure as a key-value pair table
function M.ProjectArtifacts(args)
assert(args, "You must provide an argument table when creating ProjectArtifacts")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["packaging"] = args["packaging"],
["name"] = args["name"],
["artifactIdentifier"] = args["artifactIdentifier"],
["namespaceType"] = args["namespaceType"],
["encryptionDisabled"] = args["encryptionDisabled"],
["location"] = args["location"],
["overrideArtifactName"] = args["overrideArtifactName"],
["path"] = args["path"],
["type"] = args["type"],
}
asserts.AssertProjectArtifacts(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ProjectSourceVersion = { ["sourceVersion"] = true, ["sourceIdentifier"] = true, nil }
function asserts.AssertProjectSourceVersion(struct)
assert(struct)
assert(type(struct) == "table", "Expected ProjectSourceVersion to be of type 'table'")
assert(struct["sourceIdentifier"], "Expected key sourceIdentifier to exist in table")
assert(struct["sourceVersion"], "Expected key sourceVersion to exist in table")
if struct["sourceVersion"] then asserts.AssertString(struct["sourceVersion"]) end
if struct["sourceIdentifier"] then asserts.AssertString(struct["sourceIdentifier"]) end
for k,_ in pairs(struct) do
assert(keys.ProjectSourceVersion[k], "ProjectSourceVersion contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ProjectSourceVersion
-- <p>A source identifier and its corresponding version.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * sourceVersion [String] <p>The source version for the corresponding source identifier. If specified, must be one of:</p> <ul> <li> <p>For AWS CodeCommit: the commit ID to use.</p> </li> <li> <p>For GitHub: the commit ID, pull request ID, branch name, or tag name that corresponds to the version of the source code you want to build. If a pull request ID is specified, it must use the format <code>pr/pull-request-ID</code> (for example <code>pr/25</code>). If a branch name is specified, the branch's HEAD commit ID will be used. If not specified, the default branch's HEAD commit ID will be used.</p> </li> <li> <p>For Bitbucket: the commit ID, branch name, or tag name that corresponds to the version of the source code you want to build. If a branch name is specified, the branch's HEAD commit ID will be used. If not specified, the default branch's HEAD commit ID will be used.</p> </li> <li> <p>For Amazon Simple Storage Service (Amazon S3): the version ID of the object representing the build input ZIP file to use.</p> </li> </ul>
-- * sourceIdentifier [String] <p>An identifier for a source in the build project.</p>
-- Required key: sourceIdentifier
-- Required key: sourceVersion
-- @return ProjectSourceVersion structure as a key-value pair table
function M.ProjectSourceVersion(args)
assert(args, "You must provide an argument table when creating ProjectSourceVersion")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["sourceVersion"] = args["sourceVersion"],
["sourceIdentifier"] = args["sourceIdentifier"],
}
asserts.AssertProjectSourceVersion(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.EnvironmentVariable = { ["type"] = true, ["name"] = true, ["value"] = true, nil }
function asserts.AssertEnvironmentVariable(struct)
assert(struct)
assert(type(struct) == "table", "Expected EnvironmentVariable to be of type 'table'")
assert(struct["name"], "Expected key name to exist in table")
assert(struct["value"], "Expected key value to exist in table")
if struct["type"] then asserts.AssertEnvironmentVariableType(struct["type"]) end
if struct["name"] then asserts.AssertNonEmptyString(struct["name"]) end
if struct["value"] then asserts.AssertString(struct["value"]) end
for k,_ in pairs(struct) do
assert(keys.EnvironmentVariable[k], "EnvironmentVariable contains unknown key " .. tostring(k))
end
end
--- Create a structure of type EnvironmentVariable
-- <p>Information about an environment variable for a build project or a build.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * type [EnvironmentVariableType] <p>The type of environment variable. Valid values include:</p> <ul> <li> <p> <code>PARAMETER_STORE</code>: An environment variable stored in Amazon EC2 Systems Manager Parameter Store.</p> </li> <li> <p> <code>PLAINTEXT</code>: An environment variable in plaintext format.</p> </li> </ul>
-- * name [NonEmptyString] <p>The name or key of the environment variable.</p>
-- * value [String] <p>The value of the environment variable.</p> <important> <p>We strongly discourage using environment variables to store sensitive values, especially AWS secret key IDs and secret access keys. Environment variables can be displayed in plain text using tools such as the AWS CodeBuild console and the AWS Command Line Interface (AWS CLI).</p> </important>
-- Required key: name
-- Required key: value
-- @return EnvironmentVariable structure as a key-value pair table
function M.EnvironmentVariable(args)
assert(args, "You must provide an argument table when creating EnvironmentVariable")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["type"] = args["type"],
["name"] = args["name"],
["value"] = args["value"],
}
asserts.AssertEnvironmentVariable(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Tag = { ["value"] = true, ["key"] = true, nil }
function asserts.AssertTag(struct)
assert(struct)
assert(type(struct) == "table", "Expected Tag to be of type 'table'")
if struct["value"] then asserts.AssertValueInput(struct["value"]) end
if struct["key"] then asserts.AssertKeyInput(struct["key"]) end
for k,_ in pairs(struct) do
assert(keys.Tag[k], "Tag contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Tag
-- <p>A tag, consisting of a key and a value.</p> <p>This tag is available for use by AWS services that support tags in AWS CodeBuild.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * value [ValueInput] <p>The tag's value.</p>
-- * key [KeyInput] <p>The tag's key.</p>
-- @return Tag structure as a key-value pair table
function M.Tag(args)
assert(args, "You must provide an argument table when creating Tag")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["value"] = args["value"],
["key"] = args["key"],
}
asserts.AssertTag(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DeleteProjectInput = { ["name"] = true, nil }
function asserts.AssertDeleteProjectInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected DeleteProjectInput to be of type 'table'")
assert(struct["name"], "Expected key name to exist in table")
if struct["name"] then asserts.AssertNonEmptyString(struct["name"]) end
for k,_ in pairs(struct) do
assert(keys.DeleteProjectInput[k], "DeleteProjectInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DeleteProjectInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * name [NonEmptyString] <p>The name of the build project.</p>
-- Required key: name
-- @return DeleteProjectInput structure as a key-value pair table
function M.DeleteProjectInput(args)
assert(args, "You must provide an argument table when creating DeleteProjectInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["name"] = args["name"],
}
asserts.AssertDeleteProjectInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.S3LogsConfig = { ["status"] = true, ["location"] = true, nil }
function asserts.AssertS3LogsConfig(struct)
assert(struct)
assert(type(struct) == "table", "Expected S3LogsConfig to be of type 'table'")
assert(struct["status"], "Expected key status to exist in table")
if struct["status"] then asserts.AssertLogsConfigStatusType(struct["status"]) end
if struct["location"] then asserts.AssertString(struct["location"]) end
for k,_ in pairs(struct) do
assert(keys.S3LogsConfig[k], "S3LogsConfig contains unknown key " .. tostring(k))
end
end
--- Create a structure of type S3LogsConfig
-- <p> Information about S3 logs for a build project. </p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * status [LogsConfigStatusType] <p>The current status of the S3 build logs. Valid values are:</p> <ul> <li> <p> <code>ENABLED</code>: S3 build logs are enabled for this build project.</p> </li> <li> <p> <code>DISABLED</code>: S3 build logs are not enabled for this build project.</p> </li> </ul>
-- * location [String] <p> The ARN of an S3 bucket and the path prefix for S3 logs. If your Amazon S3 bucket name is <code>my-bucket</code>, and your path prefix is <code>build-log</code>, then acceptable formats are <code>my-bucket/build-log</code> or <code>arn:aws:s3:::my-bucket/build-log</code>. </p>
-- Required key: status
-- @return S3LogsConfig structure as a key-value pair table
function M.S3LogsConfig(args)
assert(args, "You must provide an argument table when creating S3LogsConfig")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["status"] = args["status"],
["location"] = args["location"],
}
asserts.AssertS3LogsConfig(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.UpdateWebhookOutput = { ["webhook"] = true, nil }
function asserts.AssertUpdateWebhookOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected UpdateWebhookOutput to be of type 'table'")
if struct["webhook"] then asserts.AssertWebhook(struct["webhook"]) end
for k,_ in pairs(struct) do
assert(keys.UpdateWebhookOutput[k], "UpdateWebhookOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type UpdateWebhookOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * webhook [Webhook] <p> Information about a repository's webhook that is associated with a project in AWS CodeBuild. </p>
-- @return UpdateWebhookOutput structure as a key-value pair table
function M.UpdateWebhookOutput(args)
assert(args, "You must provide an argument table when creating UpdateWebhookOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["webhook"] = args["webhook"],
}
asserts.AssertUpdateWebhookOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.StartBuildOutput = { ["build"] = true, nil }
function asserts.AssertStartBuildOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected StartBuildOutput to be of type 'table'")
if struct["build"] then asserts.AssertBuild(struct["build"]) end
for k,_ in pairs(struct) do
assert(keys.StartBuildOutput[k], "StartBuildOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type StartBuildOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * build [Build] <p>Information about the build to be run.</p>
-- @return StartBuildOutput structure as a key-value pair table
function M.StartBuildOutput(args)
assert(args, "You must provide an argument table when creating StartBuildOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["build"] = args["build"],
}
asserts.AssertStartBuildOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DeleteWebhookInput = { ["projectName"] = true, nil }
function asserts.AssertDeleteWebhookInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected DeleteWebhookInput to be of type 'table'")
assert(struct["projectName"], "Expected key projectName to exist in table")
if struct["projectName"] then asserts.AssertProjectName(struct["projectName"]) end
for k,_ in pairs(struct) do
assert(keys.DeleteWebhookInput[k], "DeleteWebhookInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DeleteWebhookInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * projectName [ProjectName] <p>The name of the AWS CodeBuild project.</p>
-- Required key: projectName
-- @return DeleteWebhookInput structure as a key-value pair table
function M.DeleteWebhookInput(args)
assert(args, "You must provide an argument table when creating DeleteWebhookInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["projectName"] = args["projectName"],
}
asserts.AssertDeleteWebhookInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Build = { ["resolvedSourceVersion"] = true, ["logs"] = true, ["secondaryArtifacts"] = true, ["id"] = true, ["arn"] = true, ["sourceVersion"] = true, ["phases"] = true, ["serviceRole"] = true, ["artifacts"] = true, ["cache"] = true, ["networkInterface"] = true, ["environment"] = true, ["source"] = true, ["secondarySourceVersions"] = true, ["vpcConfig"] = true, ["projectName"] = true, ["buildComplete"] = true, ["currentPhase"] = true, ["startTime"] = true, ["secondarySources"] = true, ["initiator"] = true, ["timeoutInMinutes"] = true, ["encryptionKey"] = true, ["endTime"] = true, ["buildStatus"] = true, nil }
function asserts.AssertBuild(struct)
assert(struct)
assert(type(struct) == "table", "Expected Build to be of type 'table'")
if struct["resolvedSourceVersion"] then asserts.AssertNonEmptyString(struct["resolvedSourceVersion"]) end
if struct["logs"] then asserts.AssertLogsLocation(struct["logs"]) end
if struct["secondaryArtifacts"] then asserts.AssertBuildArtifactsList(struct["secondaryArtifacts"]) end
if struct["id"] then asserts.AssertNonEmptyString(struct["id"]) end
if struct["arn"] then asserts.AssertNonEmptyString(struct["arn"]) end
if struct["sourceVersion"] then asserts.AssertNonEmptyString(struct["sourceVersion"]) end
if struct["phases"] then asserts.AssertBuildPhases(struct["phases"]) end
if struct["serviceRole"] then asserts.AssertNonEmptyString(struct["serviceRole"]) end
if struct["artifacts"] then asserts.AssertBuildArtifacts(struct["artifacts"]) end
if struct["cache"] then asserts.AssertProjectCache(struct["cache"]) end
if struct["networkInterface"] then asserts.AssertNetworkInterface(struct["networkInterface"]) end
if struct["environment"] then asserts.AssertProjectEnvironment(struct["environment"]) end
if struct["source"] then asserts.AssertProjectSource(struct["source"]) end
if struct["secondarySourceVersions"] then asserts.AssertProjectSecondarySourceVersions(struct["secondarySourceVersions"]) end
if struct["vpcConfig"] then asserts.AssertVpcConfig(struct["vpcConfig"]) end
if struct["projectName"] then asserts.AssertNonEmptyString(struct["projectName"]) end
if struct["buildComplete"] then asserts.AssertBoolean(struct["buildComplete"]) end
if struct["currentPhase"] then asserts.AssertString(struct["currentPhase"]) end
if struct["startTime"] then asserts.AssertTimestamp(struct["startTime"]) end
if struct["secondarySources"] then asserts.AssertProjectSources(struct["secondarySources"]) end
if struct["initiator"] then asserts.AssertString(struct["initiator"]) end
if struct["timeoutInMinutes"] then asserts.AssertWrapperInt(struct["timeoutInMinutes"]) end
if struct["encryptionKey"] then asserts.AssertNonEmptyString(struct["encryptionKey"]) end
if struct["endTime"] then asserts.AssertTimestamp(struct["endTime"]) end
if struct["buildStatus"] then asserts.AssertStatusType(struct["buildStatus"]) end
for k,_ in pairs(struct) do
assert(keys.Build[k], "Build contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Build
-- <p>Information about a build.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * resolvedSourceVersion [NonEmptyString] <p> An identifier for the version of this build's source code. </p> <ul> <li> <p> For AWS CodeCommit, GitHub, GitHub Enterprise, and BitBucket, the commit ID. </p> </li> <li> <p> For AWS CodePipeline, the source revision provided by AWS CodePipeline. </p> </li> <li> <p> For Amazon Simple Storage Service (Amazon S3), this does not apply. </p> </li> </ul>
-- * logs [LogsLocation] <p>Information about the build's logs in Amazon CloudWatch Logs.</p>
-- * secondaryArtifacts [BuildArtifactsList] <p> An array of <code>ProjectArtifacts</code> objects. </p>
-- * id [NonEmptyString] <p>The unique ID for the build.</p>
-- * arn [NonEmptyString] <p>The Amazon Resource Name (ARN) of the build.</p>
-- * sourceVersion [NonEmptyString] <p>Any version identifier for the version of the source code to be built.</p>
-- * phases [BuildPhases] <p>Information about all previous build phases that are completed and information about any current build phase that is not yet complete.</p>
-- * serviceRole [NonEmptyString] <p>The name of a service role used for this build.</p>
-- * artifacts [BuildArtifacts] <p>Information about the output artifacts for the build.</p>
-- * cache [ProjectCache] <p>Information about the cache for the build.</p>
-- * networkInterface [NetworkInterface] <p>Describes a network interface.</p>
-- * environment [ProjectEnvironment] <p>Information about the build environment for this build.</p>
-- * source [ProjectSource] <p>Information about the source code to be built.</p>
-- * secondarySourceVersions [ProjectSecondarySourceVersions] <p> An array of <code>ProjectSourceVersion</code> objects. Each <code>ProjectSourceVersion</code> must be one of: </p> <ul> <li> <p>For AWS CodeCommit: the commit ID to use.</p> </li> <li> <p>For GitHub: the commit ID, pull request ID, branch name, or tag name that corresponds to the version of the source code you want to build. If a pull request ID is specified, it must use the format <code>pr/pull-request-ID</code> (for example <code>pr/25</code>). If a branch name is specified, the branch's HEAD commit ID will be used. If not specified, the default branch's HEAD commit ID will be used.</p> </li> <li> <p>For Bitbucket: the commit ID, branch name, or tag name that corresponds to the version of the source code you want to build. If a branch name is specified, the branch's HEAD commit ID will be used. If not specified, the default branch's HEAD commit ID will be used.</p> </li> <li> <p>For Amazon Simple Storage Service (Amazon S3): the version ID of the object representing the build input ZIP file to use.</p> </li> </ul>
-- * vpcConfig [VpcConfig] <p>If your AWS CodeBuild project accesses resources in an Amazon VPC, you provide this parameter that identifies the VPC ID and the list of security group IDs and subnet IDs. The security groups and subnets must belong to the same VPC. You must provide at least one security group and one subnet ID.</p>
-- * projectName [NonEmptyString] <p>The name of the AWS CodeBuild project.</p>
-- * buildComplete [Boolean] <p>Whether the build has finished. True if completed; otherwise, false.</p>
-- * currentPhase [String] <p>The current build phase.</p>
-- * startTime [Timestamp] <p>When the build process started, expressed in Unix time format.</p>
-- * secondarySources [ProjectSources] <p> An array of <code>ProjectSource</code> objects. </p>
-- * initiator [String] <p>The entity that started the build. Valid values include:</p> <ul> <li> <p>If AWS CodePipeline started the build, the pipeline's name (for example, <code>codepipeline/my-demo-pipeline</code>).</p> </li> <li> <p>If an AWS Identity and Access Management (IAM) user started the build, the user's name (for example <code>MyUserName</code>).</p> </li> <li> <p>If the Jenkins plugin for AWS CodeBuild started the build, the string <code>CodeBuild-Jenkins-Plugin</code>.</p> </li> </ul>
-- * timeoutInMinutes [WrapperInt] <p>How long, in minutes, for AWS CodeBuild to wait before timing out this build if it does not get marked as completed.</p>
-- * encryptionKey [NonEmptyString] <p>The AWS Key Management Service (AWS KMS) customer master key (CMK) to be used for encrypting the build output artifacts.</p> <p>This is expressed either as the CMK's Amazon Resource Name (ARN) or, if specified, the CMK's alias (using the format <code>alias/<i>alias-name</i> </code>).</p>
-- * endTime [Timestamp] <p>When the build process ended, expressed in Unix time format.</p>
-- * buildStatus [StatusType] <p>The current status of the build. Valid values include:</p> <ul> <li> <p> <code>FAILED</code>: The build failed.</p> </li> <li> <p> <code>FAULT</code>: The build faulted.</p> </li> <li> <p> <code>IN_PROGRESS</code>: The build is still in progress.</p> </li> <li> <p> <code>STOPPED</code>: The build stopped.</p> </li> <li> <p> <code>SUCCEEDED</code>: The build succeeded.</p> </li> <li> <p> <code>TIMED_OUT</code>: The build timed out.</p> </li> </ul>
-- @return Build structure as a key-value pair table
function M.Build(args)
assert(args, "You must provide an argument table when creating Build")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["resolvedSourceVersion"] = args["resolvedSourceVersion"],
["logs"] = args["logs"],
["secondaryArtifacts"] = args["secondaryArtifacts"],
["id"] = args["id"],
["arn"] = args["arn"],
["sourceVersion"] = args["sourceVersion"],
["phases"] = args["phases"],
["serviceRole"] = args["serviceRole"],
["artifacts"] = args["artifacts"],
["cache"] = args["cache"],
["networkInterface"] = args["networkInterface"],
["environment"] = args["environment"],
["source"] = args["source"],
["secondarySourceVersions"] = args["secondarySourceVersions"],
["vpcConfig"] = args["vpcConfig"],
["projectName"] = args["projectName"],
["buildComplete"] = args["buildComplete"],
["currentPhase"] = args["currentPhase"],
["startTime"] = args["startTime"],
["secondarySources"] = args["secondarySources"],
["initiator"] = args["initiator"],
["timeoutInMinutes"] = args["timeoutInMinutes"],
["encryptionKey"] = args["encryptionKey"],
["endTime"] = args["endTime"],
["buildStatus"] = args["buildStatus"],
}
asserts.AssertBuild(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.UpdateProjectOutput = { ["project"] = true, nil }
function asserts.AssertUpdateProjectOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected UpdateProjectOutput to be of type 'table'")
if struct["project"] then asserts.AssertProject(struct["project"]) end
for k,_ in pairs(struct) do
assert(keys.UpdateProjectOutput[k], "UpdateProjectOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type UpdateProjectOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * project [Project] <p>Information about the build project that was changed.</p>
-- @return UpdateProjectOutput structure as a key-value pair table
function M.UpdateProjectOutput(args)
assert(args, "You must provide an argument table when creating UpdateProjectOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["project"] = args["project"],
}
asserts.AssertUpdateProjectOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CloudWatchLogsConfig = { ["status"] = true, ["groupName"] = true, ["streamName"] = true, nil }
function asserts.AssertCloudWatchLogsConfig(struct)
assert(struct)
assert(type(struct) == "table", "Expected CloudWatchLogsConfig to be of type 'table'")
assert(struct["status"], "Expected key status to exist in table")
if struct["status"] then asserts.AssertLogsConfigStatusType(struct["status"]) end
if struct["groupName"] then asserts.AssertString(struct["groupName"]) end
if struct["streamName"] then asserts.AssertString(struct["streamName"]) end
for k,_ in pairs(struct) do
assert(keys.CloudWatchLogsConfig[k], "CloudWatchLogsConfig contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CloudWatchLogsConfig
-- <p> Information about Amazon CloudWatch Logs for a build project. </p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * status [LogsConfigStatusType] <p>The current status of the Amazon CloudWatch Logs for a build project. Valid values are:</p> <ul> <li> <p> <code>ENABLED</code>: Amazon CloudWatch Logs are enabled for this build project.</p> </li> <li> <p> <code>DISABLED</code>: Amazon CloudWatch Logs are not enabled for this build project.</p> </li> </ul>
-- * groupName [String] <p> The group name of the Amazon CloudWatch Logs. For more information, see <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html">Working with Log Groups and Log Streams</a> </p>
-- * streamName [String] <p> The prefix of the stream name of the Amazon CloudWatch Logs. For more information, see <a href="http://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/Working-with-log-groups-and-streams.html">Working with Log Groups and Log Streams</a> </p>
-- Required key: status
-- @return CloudWatchLogsConfig structure as a key-value pair table
function M.CloudWatchLogsConfig(args)
assert(args, "You must provide an argument table when creating CloudWatchLogsConfig")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["status"] = args["status"],
["groupName"] = args["groupName"],
["streamName"] = args["streamName"],
}
asserts.AssertCloudWatchLogsConfig(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.BuildPhase = { ["contexts"] = true, ["phaseType"] = true, ["phaseStatus"] = true, ["durationInSeconds"] = true, ["startTime"] = true, ["endTime"] = true, nil }
function asserts.AssertBuildPhase(struct)
assert(struct)
assert(type(struct) == "table", "Expected BuildPhase to be of type 'table'")
if struct["contexts"] then asserts.AssertPhaseContexts(struct["contexts"]) end
if struct["phaseType"] then asserts.AssertBuildPhaseType(struct["phaseType"]) end
if struct["phaseStatus"] then asserts.AssertStatusType(struct["phaseStatus"]) end
if struct["durationInSeconds"] then asserts.AssertWrapperLong(struct["durationInSeconds"]) end
if struct["startTime"] then asserts.AssertTimestamp(struct["startTime"]) end
if struct["endTime"] then asserts.AssertTimestamp(struct["endTime"]) end
for k,_ in pairs(struct) do
assert(keys.BuildPhase[k], "BuildPhase contains unknown key " .. tostring(k))
end
end
--- Create a structure of type BuildPhase
-- <p>Information about a stage for a build.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * contexts [PhaseContexts] <p>Additional information about a build phase, especially to help troubleshoot a failed build.</p>
-- * phaseType [BuildPhaseType] <p>The name of the build phase. Valid values include:</p> <ul> <li> <p> <code>BUILD</code>: Core build activities typically occur in this build phase.</p> </li> <li> <p> <code>COMPLETED</code>: The build has been completed.</p> </li> <li> <p> <code>DOWNLOAD_SOURCE</code>: Source code is being downloaded in this build phase.</p> </li> <li> <p> <code>FINALIZING</code>: The build process is completing in this build phase.</p> </li> <li> <p> <code>INSTALL</code>: Installation activities typically occur in this build phase.</p> </li> <li> <p> <code>POST_BUILD</code>: Post-build activities typically occur in this build phase.</p> </li> <li> <p> <code>PRE_BUILD</code>: Pre-build activities typically occur in this build phase.</p> </li> <li> <p> <code>PROVISIONING</code>: The build environment is being set up.</p> </li> <li> <p> <code>SUBMITTED</code>: The build has been submitted.</p> </li> <li> <p> <code>UPLOAD_ARTIFACTS</code>: Build output artifacts are being uploaded to the output location.</p> </li> </ul>
-- * phaseStatus [StatusType] <p>The current status of the build phase. Valid values include:</p> <ul> <li> <p> <code>FAILED</code>: The build phase failed.</p> </li> <li> <p> <code>FAULT</code>: The build phase faulted.</p> </li> <li> <p> <code>IN_PROGRESS</code>: The build phase is still in progress.</p> </li> <li> <p> <code>STOPPED</code>: The build phase stopped.</p> </li> <li> <p> <code>SUCCEEDED</code>: The build phase succeeded.</p> </li> <li> <p> <code>TIMED_OUT</code>: The build phase timed out.</p> </li> </ul>
-- * durationInSeconds [WrapperLong] <p>How long, in seconds, between the starting and ending times of the build's phase.</p>
-- * startTime [Timestamp] <p>When the build phase started, expressed in Unix time format.</p>
-- * endTime [Timestamp] <p>When the build phase ended, expressed in Unix time format.</p>
-- @return BuildPhase structure as a key-value pair table
function M.BuildPhase(args)
assert(args, "You must provide an argument table when creating BuildPhase")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["contexts"] = args["contexts"],
["phaseType"] = args["phaseType"],
["phaseStatus"] = args["phaseStatus"],
["durationInSeconds"] = args["durationInSeconds"],
["startTime"] = args["startTime"],
["endTime"] = args["endTime"],
}
asserts.AssertBuildPhase(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.BatchGetBuildsInput = { ["ids"] = true, nil }
function asserts.AssertBatchGetBuildsInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected BatchGetBuildsInput to be of type 'table'")
assert(struct["ids"], "Expected key ids to exist in table")
if struct["ids"] then asserts.AssertBuildIds(struct["ids"]) end
for k,_ in pairs(struct) do
assert(keys.BatchGetBuildsInput[k], "BatchGetBuildsInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type BatchGetBuildsInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * ids [BuildIds] <p>The IDs of the builds.</p>
-- Required key: ids
-- @return BatchGetBuildsInput structure as a key-value pair table
function M.BatchGetBuildsInput(args)
assert(args, "You must provide an argument table when creating BatchGetBuildsInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["ids"] = args["ids"],
}
asserts.AssertBatchGetBuildsInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.BatchGetBuildsOutput = { ["buildsNotFound"] = true, ["builds"] = true, nil }
function asserts.AssertBatchGetBuildsOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected BatchGetBuildsOutput to be of type 'table'")
if struct["buildsNotFound"] then asserts.AssertBuildIds(struct["buildsNotFound"]) end
if struct["builds"] then asserts.AssertBuilds(struct["builds"]) end
for k,_ in pairs(struct) do
assert(keys.BatchGetBuildsOutput[k], "BatchGetBuildsOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type BatchGetBuildsOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * buildsNotFound [BuildIds] <p>The IDs of builds for which information could not be found.</p>
-- * builds [Builds] <p>Information about the requested builds.</p>
-- @return BatchGetBuildsOutput structure as a key-value pair table
function M.BatchGetBuildsOutput(args)
assert(args, "You must provide an argument table when creating BatchGetBuildsOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["buildsNotFound"] = args["buildsNotFound"],
["builds"] = args["builds"],
}
asserts.AssertBatchGetBuildsOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListCuratedEnvironmentImagesInput = { nil }
function asserts.AssertListCuratedEnvironmentImagesInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListCuratedEnvironmentImagesInput to be of type 'table'")
for k,_ in pairs(struct) do
assert(keys.ListCuratedEnvironmentImagesInput[k], "ListCuratedEnvironmentImagesInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListCuratedEnvironmentImagesInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- @return ListCuratedEnvironmentImagesInput structure as a key-value pair table
function M.ListCuratedEnvironmentImagesInput(args)
assert(args, "You must provide an argument table when creating ListCuratedEnvironmentImagesInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
}
asserts.AssertListCuratedEnvironmentImagesInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.BatchGetProjectsInput = { ["names"] = true, nil }
function asserts.AssertBatchGetProjectsInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected BatchGetProjectsInput to be of type 'table'")
assert(struct["names"], "Expected key names to exist in table")
if struct["names"] then asserts.AssertProjectNames(struct["names"]) end
for k,_ in pairs(struct) do
assert(keys.BatchGetProjectsInput[k], "BatchGetProjectsInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type BatchGetProjectsInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * names [ProjectNames] <p>The names of the build projects.</p>
-- Required key: names
-- @return BatchGetProjectsInput structure as a key-value pair table
function M.BatchGetProjectsInput(args)
assert(args, "You must provide an argument table when creating BatchGetProjectsInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["names"] = args["names"],
}
asserts.AssertBatchGetProjectsInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListProjectsOutput = { ["nextToken"] = true, ["projects"] = true, nil }
function asserts.AssertListProjectsOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListProjectsOutput to be of type 'table'")
if struct["nextToken"] then asserts.AssertString(struct["nextToken"]) end
if struct["projects"] then asserts.AssertProjectNames(struct["projects"]) end
for k,_ in pairs(struct) do
assert(keys.ListProjectsOutput[k], "ListProjectsOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListProjectsOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * nextToken [String] <p>If there are more than 100 items in the list, only the first 100 items are returned, along with a unique string called a <i>next token</i>. To get the next batch of items in the list, call this operation again, adding the next token to the call.</p>
-- * projects [ProjectNames] <p>The list of build project names, with each build project name representing a single build project.</p>
-- @return ListProjectsOutput structure as a key-value pair table
function M.ListProjectsOutput(args)
assert(args, "You must provide an argument table when creating ListProjectsOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["nextToken"] = args["nextToken"],
["projects"] = args["projects"],
}
asserts.AssertListProjectsOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.BuildArtifacts = { ["artifactIdentifier"] = true, ["md5sum"] = true, ["sha256sum"] = true, ["encryptionDisabled"] = true, ["location"] = true, ["overrideArtifactName"] = true, nil }
function asserts.AssertBuildArtifacts(struct)
assert(struct)
assert(type(struct) == "table", "Expected BuildArtifacts to be of type 'table'")
if struct["artifactIdentifier"] then asserts.AssertString(struct["artifactIdentifier"]) end
if struct["md5sum"] then asserts.AssertString(struct["md5sum"]) end
if struct["sha256sum"] then asserts.AssertString(struct["sha256sum"]) end
if struct["encryptionDisabled"] then asserts.AssertWrapperBoolean(struct["encryptionDisabled"]) end
if struct["location"] then asserts.AssertString(struct["location"]) end
if struct["overrideArtifactName"] then asserts.AssertWrapperBoolean(struct["overrideArtifactName"]) end
for k,_ in pairs(struct) do
assert(keys.BuildArtifacts[k], "BuildArtifacts contains unknown key " .. tostring(k))
end
end
--- Create a structure of type BuildArtifacts
-- <p>Information about build output artifacts.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * artifactIdentifier [String] <p> An identifier for this artifact definition. </p>
-- * md5sum [String] <p>The MD5 hash of the build artifact.</p> <p>You can use this hash along with a checksum tool to confirm both file integrity and authenticity.</p> <note> <p>This value is available only if the build project's <code>packaging</code> value is set to <code>ZIP</code>.</p> </note>
-- * sha256sum [String] <p>The SHA-256 hash of the build artifact.</p> <p>You can use this hash along with a checksum tool to confirm both file integrity and authenticity.</p> <note> <p>This value is available only if the build project's <code>packaging</code> value is set to <code>ZIP</code>.</p> </note>
-- * encryptionDisabled [WrapperBoolean] <p> Information that tells you if encryption for build artifacts is disabled. </p>
-- * location [String] <p>Information about the location of the build artifacts.</p>
-- * overrideArtifactName [WrapperBoolean] <p> If this flag is set, a name specified in the buildspec file overrides the artifact name. The name specified in a buildspec file is calculated at build time and uses the Shell Command Language. For example, you can append a date and time to your artifact name so that it is always unique. </p>
-- @return BuildArtifacts structure as a key-value pair table
function M.BuildArtifacts(args)
assert(args, "You must provide an argument table when creating BuildArtifacts")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["artifactIdentifier"] = args["artifactIdentifier"],
["md5sum"] = args["md5sum"],
["sha256sum"] = args["sha256sum"],
["encryptionDisabled"] = args["encryptionDisabled"],
["location"] = args["location"],
["overrideArtifactName"] = args["overrideArtifactName"],
}
asserts.AssertBuildArtifacts(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ProjectBadge = { ["badgeRequestUrl"] = true, ["badgeEnabled"] = true, nil }
function asserts.AssertProjectBadge(struct)
assert(struct)
assert(type(struct) == "table", "Expected ProjectBadge to be of type 'table'")
if struct["badgeRequestUrl"] then asserts.AssertString(struct["badgeRequestUrl"]) end
if struct["badgeEnabled"] then asserts.AssertBoolean(struct["badgeEnabled"]) end
for k,_ in pairs(struct) do
assert(keys.ProjectBadge[k], "ProjectBadge contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ProjectBadge
-- <p>Information about the build badge for the build project.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * badgeRequestUrl [String] <p>The publicly-accessible URL through which you can access the build badge for your project. </p>
-- * badgeEnabled [Boolean] <p>Set this to true to generate a publicly-accessible URL for your project's build badge.</p>
-- @return ProjectBadge structure as a key-value pair table
function M.ProjectBadge(args)
assert(args, "You must provide an argument table when creating ProjectBadge")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["badgeRequestUrl"] = args["badgeRequestUrl"],
["badgeEnabled"] = args["badgeEnabled"],
}
asserts.AssertProjectBadge(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.UpdateWebhookInput = { ["projectName"] = true, ["branchFilter"] = true, ["rotateSecret"] = true, nil }
function asserts.AssertUpdateWebhookInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected UpdateWebhookInput to be of type 'table'")
assert(struct["projectName"], "Expected key projectName to exist in table")
if struct["projectName"] then asserts.AssertProjectName(struct["projectName"]) end
if struct["branchFilter"] then asserts.AssertString(struct["branchFilter"]) end
if struct["rotateSecret"] then asserts.AssertBoolean(struct["rotateSecret"]) end
for k,_ in pairs(struct) do
assert(keys.UpdateWebhookInput[k], "UpdateWebhookInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type UpdateWebhookInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * projectName [ProjectName] <p>The name of the AWS CodeBuild project.</p>
-- * branchFilter [String] <p>A regular expression used to determine which branches in a repository are built when a webhook is triggered. If the name of a branch matches the regular expression, then it is built. If it doesn't match, then it is not. If branchFilter is empty, then all branches are built.</p>
-- * rotateSecret [Boolean] <p> A boolean value that specifies whether the associated repository's secret token should be updated. </p>
-- Required key: projectName
-- @return UpdateWebhookInput structure as a key-value pair table
function M.UpdateWebhookInput(args)
assert(args, "You must provide an argument table when creating UpdateWebhookInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["projectName"] = args["projectName"],
["branchFilter"] = args["branchFilter"],
["rotateSecret"] = args["rotateSecret"],
}
asserts.AssertUpdateWebhookInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Webhook = { ["url"] = true, ["secret"] = true, ["lastModifiedSecret"] = true, ["branchFilter"] = true, ["payloadUrl"] = true, nil }
function asserts.AssertWebhook(struct)
assert(struct)
assert(type(struct) == "table", "Expected Webhook to be of type 'table'")
if struct["url"] then asserts.AssertNonEmptyString(struct["url"]) end
if struct["secret"] then asserts.AssertNonEmptyString(struct["secret"]) end
if struct["lastModifiedSecret"] then asserts.AssertTimestamp(struct["lastModifiedSecret"]) end
if struct["branchFilter"] then asserts.AssertString(struct["branchFilter"]) end
if struct["payloadUrl"] then asserts.AssertNonEmptyString(struct["payloadUrl"]) end
for k,_ in pairs(struct) do
assert(keys.Webhook[k], "Webhook contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Webhook
-- <p>Information about a webhook in GitHub that connects repository events to a build project in AWS CodeBuild.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * url [NonEmptyString] <p>The URL to the webhook.</p>
-- * secret [NonEmptyString] <p> The secret token of the associated repository. </p>
-- * lastModifiedSecret [Timestamp] <p> A timestamp indicating the last time a repository's secret token was modified. </p>
-- * branchFilter [String] <p>A regular expression used to determine which branches in a repository are built when a webhook is triggered. If the name of a branch matches the regular expression, then it is built. If it doesn't match, then it is not. If branchFilter is empty, then all branches are built.</p>
-- * payloadUrl [NonEmptyString] <p> The CodeBuild endpoint where webhook events are sent.</p>
-- @return Webhook structure as a key-value pair table
function M.Webhook(args)
assert(args, "You must provide an argument table when creating Webhook")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["url"] = args["url"],
["secret"] = args["secret"],
["lastModifiedSecret"] = args["lastModifiedSecret"],
["branchFilter"] = args["branchFilter"],
["payloadUrl"] = args["payloadUrl"],
}
asserts.AssertWebhook(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DeleteProjectOutput = { nil }
function asserts.AssertDeleteProjectOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected DeleteProjectOutput to be of type 'table'")
for k,_ in pairs(struct) do
assert(keys.DeleteProjectOutput[k], "DeleteProjectOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DeleteProjectOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- @return DeleteProjectOutput structure as a key-value pair table
function M.DeleteProjectOutput(args)
assert(args, "You must provide an argument table when creating DeleteProjectOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
}
asserts.AssertDeleteProjectOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ProjectSource = { ["buildspec"] = true, ["insecureSsl"] = true, ["auth"] = true, ["location"] = true, ["sourceIdentifier"] = true, ["gitCloneDepth"] = true, ["type"] = true, ["reportBuildStatus"] = true, nil }
function asserts.AssertProjectSource(struct)
assert(struct)
assert(type(struct) == "table", "Expected ProjectSource to be of type 'table'")
assert(struct["type"], "Expected key type to exist in table")
if struct["buildspec"] then asserts.AssertString(struct["buildspec"]) end
if struct["insecureSsl"] then asserts.AssertWrapperBoolean(struct["insecureSsl"]) end
if struct["auth"] then asserts.AssertSourceAuth(struct["auth"]) end
if struct["location"] then asserts.AssertString(struct["location"]) end
if struct["sourceIdentifier"] then asserts.AssertString(struct["sourceIdentifier"]) end
if struct["gitCloneDepth"] then asserts.AssertGitCloneDepth(struct["gitCloneDepth"]) end
if struct["type"] then asserts.AssertSourceType(struct["type"]) end
if struct["reportBuildStatus"] then asserts.AssertWrapperBoolean(struct["reportBuildStatus"]) end
for k,_ in pairs(struct) do
assert(keys.ProjectSource[k], "ProjectSource contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ProjectSource
-- <p>Information about the build input source code for the build project.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * buildspec [String] <p>The build spec declaration to use for the builds in this build project.</p> <p>If this value is not specified, a build spec must be included along with the source code to be built.</p>
-- * insecureSsl [WrapperBoolean] <p>Enable this flag to ignore SSL warnings while connecting to the project source code.</p>
-- * auth [SourceAuth] <p>Information about the authorization settings for AWS CodeBuild to access the source code to be built.</p> <p>This information is for the AWS CodeBuild console's use only. Your code should not get or set this information directly (unless the build project's source <code>type</code> value is <code>BITBUCKET</code> or <code>GITHUB</code>).</p>
-- * location [String] <p>Information about the location of the source code to be built. Valid values include:</p> <ul> <li> <p>For source code settings that are specified in the source action of a pipeline in AWS CodePipeline, <code>location</code> should not be specified. If it is specified, AWS CodePipeline will ignore it. This is because AWS CodePipeline uses the settings in a pipeline's source action instead of this value.</p> </li> <li> <p>For source code in an AWS CodeCommit repository, the HTTPS clone URL to the repository that contains the source code and the build spec (for example, <code>https://git-codecommit.<i>region-ID</i>.amazonaws.com/v1/repos/<i>repo-name</i> </code>).</p> </li> <li> <p>For source code in an Amazon Simple Storage Service (Amazon S3) input bucket, the path to the ZIP file that contains the source code (for example, <code> <i>bucket-name</i>/<i>path</i>/<i>to</i>/<i>object-name</i>.zip</code>)</p> </li> <li> <p>For source code in a GitHub repository, the HTTPS clone URL to the repository that contains the source and the build spec. Also, you must connect your AWS account to your GitHub account. To do this, use the AWS CodeBuild console to begin creating a build project. When you use the console to connect (or reconnect) with GitHub, on the GitHub <b>Authorize application</b> page that displays, for <b>Organization access</b>, choose <b>Request access</b> next to each repository you want to allow AWS CodeBuild to have access to. Then choose <b>Authorize application</b>. (After you have connected to your GitHub account, you do not need to finish creating the build project, and you may then leave the AWS CodeBuild console.) To instruct AWS CodeBuild to then use this connection, in the <code>source</code> object, set the <code>auth</code> object's <code>type</code> value to <code>OAUTH</code>.</p> </li> <li> <p>For source code in a Bitbucket repository, the HTTPS clone URL to the repository that contains the source and the build spec. Also, you must connect your AWS account to your Bitbucket account. To do this, use the AWS CodeBuild console to begin creating a build project. When you use the console to connect (or reconnect) with Bitbucket, on the Bitbucket <b>Confirm access to your account</b> page that displays, choose <b>Grant access</b>. (After you have connected to your Bitbucket account, you do not need to finish creating the build project, and you may then leave the AWS CodeBuild console.) To instruct AWS CodeBuild to then use this connection, in the <code>source</code> object, set the <code>auth</code> object's <code>type</code> value to <code>OAUTH</code>.</p> </li> </ul>
-- * sourceIdentifier [String] <p> An identifier for this project source. </p>
-- * gitCloneDepth [GitCloneDepth] <p>Information about the git clone depth for the build project.</p>
-- * type [SourceType] <p>The type of repository that contains the source code to be built. Valid values include:</p> <ul> <li> <p> <code>BITBUCKET</code>: The source code is in a Bitbucket repository.</p> </li> <li> <p> <code>CODECOMMIT</code>: The source code is in an AWS CodeCommit repository.</p> </li> <li> <p> <code>CODEPIPELINE</code>: The source code settings are specified in the source action of a pipeline in AWS CodePipeline.</p> </li> <li> <p> <code>GITHUB</code>: The source code is in a GitHub repository.</p> </li> <li> <p> <code>NO_SOURCE</code>: The project does not have input source code.</p> </li> <li> <p> <code>S3</code>: The source code is in an Amazon Simple Storage Service (Amazon S3) input bucket.</p> </li> </ul>
-- * reportBuildStatus [WrapperBoolean] <p> Set to true to report the status of a build's start and finish to your source provider. This option is only valid when your source provider is GitHub. If this is set and you use a different source provider, an invalidInputException is thrown. </p>
-- Required key: type
-- @return ProjectSource structure as a key-value pair table
function M.ProjectSource(args)
assert(args, "You must provide an argument table when creating ProjectSource")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["buildspec"] = args["buildspec"],
["insecureSsl"] = args["insecureSsl"],
["auth"] = args["auth"],
["location"] = args["location"],
["sourceIdentifier"] = args["sourceIdentifier"],
["gitCloneDepth"] = args["gitCloneDepth"],
["type"] = args["type"],
["reportBuildStatus"] = args["reportBuildStatus"],
}
asserts.AssertProjectSource(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CreateProjectInput = { ["logsConfig"] = true, ["timeoutInMinutes"] = true, ["name"] = true, ["serviceRole"] = true, ["tags"] = true, ["artifacts"] = true, ["badgeEnabled"] = true, ["cache"] = true, ["vpcConfig"] = true, ["environment"] = true, ["source"] = true, ["secondaryArtifacts"] = true, ["secondarySources"] = true, ["encryptionKey"] = true, ["description"] = true, nil }
function asserts.AssertCreateProjectInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected CreateProjectInput to be of type 'table'")
assert(struct["name"], "Expected key name to exist in table")
assert(struct["source"], "Expected key source to exist in table")
assert(struct["artifacts"], "Expected key artifacts to exist in table")
assert(struct["environment"], "Expected key environment to exist in table")
assert(struct["serviceRole"], "Expected key serviceRole to exist in table")
if struct["logsConfig"] then asserts.AssertLogsConfig(struct["logsConfig"]) end
if struct["timeoutInMinutes"] then asserts.AssertTimeOut(struct["timeoutInMinutes"]) end
if struct["name"] then asserts.AssertProjectName(struct["name"]) end
if struct["serviceRole"] then asserts.AssertNonEmptyString(struct["serviceRole"]) end
if struct["tags"] then asserts.AssertTagList(struct["tags"]) end
if struct["artifacts"] then asserts.AssertProjectArtifacts(struct["artifacts"]) end
if struct["badgeEnabled"] then asserts.AssertWrapperBoolean(struct["badgeEnabled"]) end
if struct["cache"] then asserts.AssertProjectCache(struct["cache"]) end
if struct["vpcConfig"] then asserts.AssertVpcConfig(struct["vpcConfig"]) end
if struct["environment"] then asserts.AssertProjectEnvironment(struct["environment"]) end
if struct["source"] then asserts.AssertProjectSource(struct["source"]) end
if struct["secondaryArtifacts"] then asserts.AssertProjectArtifactsList(struct["secondaryArtifacts"]) end
if struct["secondarySources"] then asserts.AssertProjectSources(struct["secondarySources"]) end
if struct["encryptionKey"] then asserts.AssertNonEmptyString(struct["encryptionKey"]) end
if struct["description"] then asserts.AssertProjectDescription(struct["description"]) end
for k,_ in pairs(struct) do
assert(keys.CreateProjectInput[k], "CreateProjectInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CreateProjectInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * logsConfig [LogsConfig] <p> Information about logs for the build project. Logs can be Amazon CloudWatch Logs, uploaded to a specified S3 bucket, or both. </p>
-- * timeoutInMinutes [TimeOut] <p>How long, in minutes, from 5 to 480 (8 hours), for AWS CodeBuild to wait until timing out any build that has not been marked as completed. The default is 60 minutes.</p>
-- * name [ProjectName] <p>The name of the build project.</p>
-- * serviceRole [NonEmptyString] <p>The ARN of the AWS Identity and Access Management (IAM) role that enables AWS CodeBuild to interact with dependent AWS services on behalf of the AWS account.</p>
-- * tags [TagList] <p>A set of tags for this build project.</p> <p>These tags are available for use by AWS services that support AWS CodeBuild build project tags.</p>
-- * artifacts [ProjectArtifacts] <p>Information about the build output artifacts for the build project.</p>
-- * badgeEnabled [WrapperBoolean] <p>Set this to true to generate a publicly-accessible URL for your project's build badge.</p>
-- * cache [ProjectCache] <p>Stores recently used information so that it can be quickly accessed at a later time.</p>
-- * vpcConfig [VpcConfig] <p>VpcConfig enables AWS CodeBuild to access resources in an Amazon VPC.</p>
-- * environment [ProjectEnvironment] <p>Information about the build environment for the build project.</p>
-- * source [ProjectSource] <p>Information about the build input source code for the build project.</p>
-- * secondaryArtifacts [ProjectArtifactsList] <p> An array of <code>ProjectArtifacts</code> objects. </p>
-- * secondarySources [ProjectSources] <p> An array of <code>ProjectSource</code> objects. </p>
-- * encryptionKey [NonEmptyString] <p>The AWS Key Management Service (AWS KMS) customer master key (CMK) to be used for encrypting the build output artifacts.</p> <p>You can specify either the CMK's Amazon Resource Name (ARN) or, if available, the CMK's alias (using the format <code>alias/<i>alias-name</i> </code>).</p>
-- * description [ProjectDescription] <p>A description that makes the build project easy to identify.</p>
-- Required key: name
-- Required key: source
-- Required key: artifacts
-- Required key: environment
-- Required key: serviceRole
-- @return CreateProjectInput structure as a key-value pair table
function M.CreateProjectInput(args)
assert(args, "You must provide an argument table when creating CreateProjectInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["logsConfig"] = args["logsConfig"],
["timeoutInMinutes"] = args["timeoutInMinutes"],
["name"] = args["name"],
["serviceRole"] = args["serviceRole"],
["tags"] = args["tags"],
["artifacts"] = args["artifacts"],
["badgeEnabled"] = args["badgeEnabled"],
["cache"] = args["cache"],
["vpcConfig"] = args["vpcConfig"],
["environment"] = args["environment"],
["source"] = args["source"],
["secondaryArtifacts"] = args["secondaryArtifacts"],
["secondarySources"] = args["secondarySources"],
["encryptionKey"] = args["encryptionKey"],
["description"] = args["description"],
}
asserts.AssertCreateProjectInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListBuildsOutput = { ["nextToken"] = true, ["ids"] = true, nil }
function asserts.AssertListBuildsOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListBuildsOutput to be of type 'table'")
if struct["nextToken"] then asserts.AssertString(struct["nextToken"]) end
if struct["ids"] then asserts.AssertBuildIds(struct["ids"]) end
for k,_ in pairs(struct) do
assert(keys.ListBuildsOutput[k], "ListBuildsOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListBuildsOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * nextToken [String] <p>If there are more than 100 items in the list, only the first 100 items are returned, along with a unique string called a <i>next token</i>. To get the next batch of items in the list, call this operation again, adding the next token to the call.</p>
-- * ids [BuildIds] <p>A list of build IDs, with each build ID representing a single build.</p>
-- @return ListBuildsOutput structure as a key-value pair table
function M.ListBuildsOutput(args)
assert(args, "You must provide an argument table when creating ListBuildsOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["nextToken"] = args["nextToken"],
["ids"] = args["ids"],
}
asserts.AssertListBuildsOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.BatchGetProjectsOutput = { ["projectsNotFound"] = true, ["projects"] = true, nil }
function asserts.AssertBatchGetProjectsOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected BatchGetProjectsOutput to be of type 'table'")
if struct["projectsNotFound"] then asserts.AssertProjectNames(struct["projectsNotFound"]) end
if struct["projects"] then asserts.AssertProjects(struct["projects"]) end
for k,_ in pairs(struct) do
assert(keys.BatchGetProjectsOutput[k], "BatchGetProjectsOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type BatchGetProjectsOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * projectsNotFound [ProjectNames] <p>The names of build projects for which information could not be found.</p>
-- * projects [Projects] <p>Information about the requested build projects.</p>
-- @return BatchGetProjectsOutput structure as a key-value pair table
function M.BatchGetProjectsOutput(args)
assert(args, "You must provide an argument table when creating BatchGetProjectsOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["projectsNotFound"] = args["projectsNotFound"],
["projects"] = args["projects"],
}
asserts.AssertBatchGetProjectsOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CreateWebhookOutput = { ["webhook"] = true, nil }
function asserts.AssertCreateWebhookOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected CreateWebhookOutput to be of type 'table'")
if struct["webhook"] then asserts.AssertWebhook(struct["webhook"]) end
for k,_ in pairs(struct) do
assert(keys.CreateWebhookOutput[k], "CreateWebhookOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CreateWebhookOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * webhook [Webhook] <p>Information about a webhook in GitHub that connects repository events to a build project in AWS CodeBuild.</p>
-- @return CreateWebhookOutput structure as a key-value pair table
function M.CreateWebhookOutput(args)
assert(args, "You must provide an argument table when creating CreateWebhookOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["webhook"] = args["webhook"],
}
asserts.AssertCreateWebhookOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.UpdateProjectInput = { ["logsConfig"] = true, ["timeoutInMinutes"] = true, ["name"] = true, ["serviceRole"] = true, ["tags"] = true, ["artifacts"] = true, ["badgeEnabled"] = true, ["cache"] = true, ["vpcConfig"] = true, ["environment"] = true, ["source"] = true, ["secondaryArtifacts"] = true, ["secondarySources"] = true, ["encryptionKey"] = true, ["description"] = true, nil }
function asserts.AssertUpdateProjectInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected UpdateProjectInput to be of type 'table'")
assert(struct["name"], "Expected key name to exist in table")
if struct["logsConfig"] then asserts.AssertLogsConfig(struct["logsConfig"]) end
if struct["timeoutInMinutes"] then asserts.AssertTimeOut(struct["timeoutInMinutes"]) end
if struct["name"] then asserts.AssertNonEmptyString(struct["name"]) end
if struct["serviceRole"] then asserts.AssertNonEmptyString(struct["serviceRole"]) end
if struct["tags"] then asserts.AssertTagList(struct["tags"]) end
if struct["artifacts"] then asserts.AssertProjectArtifacts(struct["artifacts"]) end
if struct["badgeEnabled"] then asserts.AssertWrapperBoolean(struct["badgeEnabled"]) end
if struct["cache"] then asserts.AssertProjectCache(struct["cache"]) end
if struct["vpcConfig"] then asserts.AssertVpcConfig(struct["vpcConfig"]) end
if struct["environment"] then asserts.AssertProjectEnvironment(struct["environment"]) end
if struct["source"] then asserts.AssertProjectSource(struct["source"]) end
if struct["secondaryArtifacts"] then asserts.AssertProjectArtifactsList(struct["secondaryArtifacts"]) end
if struct["secondarySources"] then asserts.AssertProjectSources(struct["secondarySources"]) end
if struct["encryptionKey"] then asserts.AssertNonEmptyString(struct["encryptionKey"]) end
if struct["description"] then asserts.AssertProjectDescription(struct["description"]) end
for k,_ in pairs(struct) do
assert(keys.UpdateProjectInput[k], "UpdateProjectInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type UpdateProjectInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * logsConfig [LogsConfig] <p> Information about logs for the build project. A project can create Amazon CloudWatch Logs, logs in an S3 bucket, or both. </p>
-- * timeoutInMinutes [TimeOut] <p>The replacement value in minutes, from 5 to 480 (8 hours), for AWS CodeBuild to wait before timing out any related build that did not get marked as completed.</p>
-- * name [NonEmptyString] <p>The name of the build project.</p> <note> <p>You cannot change a build project's name.</p> </note>
-- * serviceRole [NonEmptyString] <p>The replacement ARN of the AWS Identity and Access Management (IAM) role that enables AWS CodeBuild to interact with dependent AWS services on behalf of the AWS account.</p>
-- * tags [TagList] <p>The replacement set of tags for this build project.</p> <p>These tags are available for use by AWS services that support AWS CodeBuild build project tags.</p>
-- * artifacts [ProjectArtifacts] <p>Information to be changed about the build output artifacts for the build project.</p>
-- * badgeEnabled [WrapperBoolean] <p>Set this to true to generate a publicly-accessible URL for your project's build badge.</p>
-- * cache [ProjectCache] <p>Stores recently used information so that it can be quickly accessed at a later time.</p>
-- * vpcConfig [VpcConfig] <p>VpcConfig enables AWS CodeBuild to access resources in an Amazon VPC.</p>
-- * environment [ProjectEnvironment] <p>Information to be changed about the build environment for the build project.</p>
-- * source [ProjectSource] <p>Information to be changed about the build input source code for the build project.</p>
-- * secondaryArtifacts [ProjectArtifactsList] <p> An array of <code>ProjectSource</code> objects. </p>
-- * secondarySources [ProjectSources] <p> An array of <code>ProjectSource</code> objects. </p>
-- * encryptionKey [NonEmptyString] <p>The replacement AWS Key Management Service (AWS KMS) customer master key (CMK) to be used for encrypting the build output artifacts.</p> <p>You can specify either the CMK's Amazon Resource Name (ARN) or, if available, the CMK's alias (using the format <code>alias/<i>alias-name</i> </code>).</p>
-- * description [ProjectDescription] <p>A new or replacement description of the build project.</p>
-- Required key: name
-- @return UpdateProjectInput structure as a key-value pair table
function M.UpdateProjectInput(args)
assert(args, "You must provide an argument table when creating UpdateProjectInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["logsConfig"] = args["logsConfig"],
["timeoutInMinutes"] = args["timeoutInMinutes"],
["name"] = args["name"],
["serviceRole"] = args["serviceRole"],
["tags"] = args["tags"],
["artifacts"] = args["artifacts"],
["badgeEnabled"] = args["badgeEnabled"],
["cache"] = args["cache"],
["vpcConfig"] = args["vpcConfig"],
["environment"] = args["environment"],
["source"] = args["source"],
["secondaryArtifacts"] = args["secondaryArtifacts"],
["secondarySources"] = args["secondarySources"],
["encryptionKey"] = args["encryptionKey"],
["description"] = args["description"],
}
asserts.AssertUpdateProjectInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.StopBuildOutput = { ["build"] = true, nil }
function asserts.AssertStopBuildOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected StopBuildOutput to be of type 'table'")
if struct["build"] then asserts.AssertBuild(struct["build"]) end
for k,_ in pairs(struct) do
assert(keys.StopBuildOutput[k], "StopBuildOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type StopBuildOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * build [Build] <p>Information about the build.</p>
-- @return StopBuildOutput structure as a key-value pair table
function M.StopBuildOutput(args)
assert(args, "You must provide an argument table when creating StopBuildOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["build"] = args["build"],
}
asserts.AssertStopBuildOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ProjectCache = { ["type"] = true, ["location"] = true, nil }
function asserts.AssertProjectCache(struct)
assert(struct)
assert(type(struct) == "table", "Expected ProjectCache to be of type 'table'")
assert(struct["type"], "Expected key type to exist in table")
if struct["type"] then asserts.AssertCacheType(struct["type"]) end
if struct["location"] then asserts.AssertString(struct["location"]) end
for k,_ in pairs(struct) do
assert(keys.ProjectCache[k], "ProjectCache contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ProjectCache
-- <p>Information about the cache for the build project.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * type [CacheType] <p>The type of cache used by the build project. Valid values include:</p> <ul> <li> <p> <code>NO_CACHE</code>: The build project will not use any cache.</p> </li> <li> <p> <code>S3</code>: The build project will read and write from/to S3.</p> </li> </ul>
-- * location [String] <p>Information about the cache location, as follows: </p> <ul> <li> <p> <code>NO_CACHE</code>: This value will be ignored.</p> </li> <li> <p> <code>S3</code>: This is the S3 bucket name/prefix.</p> </li> </ul>
-- Required key: type
-- @return ProjectCache structure as a key-value pair table
function M.ProjectCache(args)
assert(args, "You must provide an argument table when creating ProjectCache")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["type"] = args["type"],
["location"] = args["location"],
}
asserts.AssertProjectCache(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.InvalidateProjectCacheInput = { ["projectName"] = true, nil }
function asserts.AssertInvalidateProjectCacheInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected InvalidateProjectCacheInput to be of type 'table'")
assert(struct["projectName"], "Expected key projectName to exist in table")
if struct["projectName"] then asserts.AssertNonEmptyString(struct["projectName"]) end
for k,_ in pairs(struct) do
assert(keys.InvalidateProjectCacheInput[k], "InvalidateProjectCacheInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type InvalidateProjectCacheInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * projectName [NonEmptyString] <p>The name of the AWS CodeBuild build project that the cache will be reset for.</p>
-- Required key: projectName
-- @return InvalidateProjectCacheInput structure as a key-value pair table
function M.InvalidateProjectCacheInput(args)
assert(args, "You must provide an argument table when creating InvalidateProjectCacheInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["projectName"] = args["projectName"],
}
asserts.AssertInvalidateProjectCacheInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.LogsConfig = { ["s3Logs"] = true, ["cloudWatchLogs"] = true, nil }
function asserts.AssertLogsConfig(struct)
assert(struct)
assert(type(struct) == "table", "Expected LogsConfig to be of type 'table'")
if struct["s3Logs"] then asserts.AssertS3LogsConfig(struct["s3Logs"]) end
if struct["cloudWatchLogs"] then asserts.AssertCloudWatchLogsConfig(struct["cloudWatchLogs"]) end
for k,_ in pairs(struct) do
assert(keys.LogsConfig[k], "LogsConfig contains unknown key " .. tostring(k))
end
end
--- Create a structure of type LogsConfig
-- <p> Information about logs for a build project. Logs can be Amazon CloudWatch Logs, built in a specified S3 bucket, or both. </p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * s3Logs [S3LogsConfig] <p> Information about logs built to an S3 bucket for a build project. S3 logs are not enabled by default. </p>
-- * cloudWatchLogs [CloudWatchLogsConfig] <p> Information about Amazon CloudWatch Logs for a build project. Amazon CloudWatch Logs are enabled by default. </p>
-- @return LogsConfig structure as a key-value pair table
function M.LogsConfig(args)
assert(args, "You must provide an argument table when creating LogsConfig")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["s3Logs"] = args["s3Logs"],
["cloudWatchLogs"] = args["cloudWatchLogs"],
}
asserts.AssertLogsConfig(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CreateProjectOutput = { ["project"] = true, nil }
function asserts.AssertCreateProjectOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected CreateProjectOutput to be of type 'table'")
if struct["project"] then asserts.AssertProject(struct["project"]) end
for k,_ in pairs(struct) do
assert(keys.CreateProjectOutput[k], "CreateProjectOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CreateProjectOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * project [Project] <p>Information about the build project that was created.</p>
-- @return CreateProjectOutput structure as a key-value pair table
function M.CreateProjectOutput(args)
assert(args, "You must provide an argument table when creating CreateProjectOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["project"] = args["project"],
}
asserts.AssertCreateProjectOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.PhaseContext = { ["message"] = true, ["statusCode"] = true, nil }
function asserts.AssertPhaseContext(struct)
assert(struct)
assert(type(struct) == "table", "Expected PhaseContext to be of type 'table'")
if struct["message"] then asserts.AssertString(struct["message"]) end
if struct["statusCode"] then asserts.AssertString(struct["statusCode"]) end
for k,_ in pairs(struct) do
assert(keys.PhaseContext[k], "PhaseContext contains unknown key " .. tostring(k))
end
end
--- Create a structure of type PhaseContext
-- <p>Additional information about a build phase that has an error. You can use this information to help troubleshoot a failed build.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * message [String] <p>An explanation of the build phase's context. This explanation might include a command ID and an exit code.</p>
-- * statusCode [String] <p>The status code for the context of the build phase.</p>
-- @return PhaseContext structure as a key-value pair table
function M.PhaseContext(args)
assert(args, "You must provide an argument table when creating PhaseContext")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["message"] = args["message"],
["statusCode"] = args["statusCode"],
}
asserts.AssertPhaseContext(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.StopBuildInput = { ["id"] = true, nil }
function asserts.AssertStopBuildInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected StopBuildInput to be of type 'table'")
assert(struct["id"], "Expected key id to exist in table")
if struct["id"] then asserts.AssertNonEmptyString(struct["id"]) end
for k,_ in pairs(struct) do
assert(keys.StopBuildInput[k], "StopBuildInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type StopBuildInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * id [NonEmptyString] <p>The ID of the build.</p>
-- Required key: id
-- @return StopBuildInput structure as a key-value pair table
function M.StopBuildInput(args)
assert(args, "You must provide an argument table when creating StopBuildInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["id"] = args["id"],
}
asserts.AssertStopBuildInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.LogsLocation = { ["cloudWatchLogs"] = true, ["s3DeepLink"] = true, ["s3Logs"] = true, ["streamName"] = true, ["groupName"] = true, ["deepLink"] = true, nil }
function asserts.AssertLogsLocation(struct)
assert(struct)
assert(type(struct) == "table", "Expected LogsLocation to be of type 'table'")
if struct["cloudWatchLogs"] then asserts.AssertCloudWatchLogsConfig(struct["cloudWatchLogs"]) end
if struct["s3DeepLink"] then asserts.AssertString(struct["s3DeepLink"]) end
if struct["s3Logs"] then asserts.AssertS3LogsConfig(struct["s3Logs"]) end
if struct["streamName"] then asserts.AssertString(struct["streamName"]) end
if struct["groupName"] then asserts.AssertString(struct["groupName"]) end
if struct["deepLink"] then asserts.AssertString(struct["deepLink"]) end
for k,_ in pairs(struct) do
assert(keys.LogsLocation[k], "LogsLocation contains unknown key " .. tostring(k))
end
end
--- Create a structure of type LogsLocation
-- <p>Information about build logs in Amazon CloudWatch Logs.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * cloudWatchLogs [CloudWatchLogsConfig] <p> Information about Amazon CloudWatch Logs for a build project. </p>
-- * s3DeepLink [String] <p> The URL to an individual build log in an S3 bucket. </p>
-- * s3Logs [S3LogsConfig] <p> Information about S3 logs for a build project. </p>
-- * streamName [String] <p>The name of the Amazon CloudWatch Logs stream for the build logs.</p>
-- * groupName [String] <p>The name of the Amazon CloudWatch Logs group for the build logs.</p>
-- * deepLink [String] <p>The URL to an individual build log in Amazon CloudWatch Logs.</p>
-- @return LogsLocation structure as a key-value pair table
function M.LogsLocation(args)
assert(args, "You must provide an argument table when creating LogsLocation")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["cloudWatchLogs"] = args["cloudWatchLogs"],
["s3DeepLink"] = args["s3DeepLink"],
["s3Logs"] = args["s3Logs"],
["streamName"] = args["streamName"],
["groupName"] = args["groupName"],
["deepLink"] = args["deepLink"],
}
asserts.AssertLogsLocation(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListBuildsInput = { ["nextToken"] = true, ["sortOrder"] = true, nil }
function asserts.AssertListBuildsInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListBuildsInput to be of type 'table'")
if struct["nextToken"] then asserts.AssertString(struct["nextToken"]) end
if struct["sortOrder"] then asserts.AssertSortOrderType(struct["sortOrder"]) end
for k,_ in pairs(struct) do
assert(keys.ListBuildsInput[k], "ListBuildsInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListBuildsInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * nextToken [String] <p>During a previous call, if there are more than 100 items in the list, only the first 100 items are returned, along with a unique string called a <i>next token</i>. To get the next batch of items in the list, call this operation again, adding the next token to the call. To get all of the items in the list, keep calling this operation with each subsequent next token that is returned, until no more next tokens are returned.</p>
-- * sortOrder [SortOrderType] <p>The order to list build IDs. Valid values include:</p> <ul> <li> <p> <code>ASCENDING</code>: List the build IDs in ascending order by build ID.</p> </li> <li> <p> <code>DESCENDING</code>: List the build IDs in descending order by build ID.</p> </li> </ul>
-- @return ListBuildsInput structure as a key-value pair table
function M.ListBuildsInput(args)
assert(args, "You must provide an argument table when creating ListBuildsInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["nextToken"] = args["nextToken"],
["sortOrder"] = args["sortOrder"],
}
asserts.AssertListBuildsInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.CreateWebhookInput = { ["projectName"] = true, ["branchFilter"] = true, nil }
function asserts.AssertCreateWebhookInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected CreateWebhookInput to be of type 'table'")
assert(struct["projectName"], "Expected key projectName to exist in table")
if struct["projectName"] then asserts.AssertProjectName(struct["projectName"]) end
if struct["branchFilter"] then asserts.AssertString(struct["branchFilter"]) end
for k,_ in pairs(struct) do
assert(keys.CreateWebhookInput[k], "CreateWebhookInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type CreateWebhookInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * projectName [ProjectName] <p>The name of the AWS CodeBuild project.</p>
-- * branchFilter [String] <p>A regular expression used to determine which branches in a repository are built when a webhook is triggered. If the name of a branch matches the regular expression, then it is built. If it doesn't match, then it is not. If branchFilter is empty, then all branches are built.</p>
-- Required key: projectName
-- @return CreateWebhookInput structure as a key-value pair table
function M.CreateWebhookInput(args)
assert(args, "You must provide an argument table when creating CreateWebhookInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["projectName"] = args["projectName"],
["branchFilter"] = args["branchFilter"],
}
asserts.AssertCreateWebhookInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListBuildsForProjectInput = { ["projectName"] = true, ["nextToken"] = true, ["sortOrder"] = true, nil }
function asserts.AssertListBuildsForProjectInput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListBuildsForProjectInput to be of type 'table'")
assert(struct["projectName"], "Expected key projectName to exist in table")
if struct["projectName"] then asserts.AssertNonEmptyString(struct["projectName"]) end
if struct["nextToken"] then asserts.AssertString(struct["nextToken"]) end
if struct["sortOrder"] then asserts.AssertSortOrderType(struct["sortOrder"]) end
for k,_ in pairs(struct) do
assert(keys.ListBuildsForProjectInput[k], "ListBuildsForProjectInput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListBuildsForProjectInput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * projectName [NonEmptyString] <p>The name of the AWS CodeBuild project.</p>
-- * nextToken [String] <p>During a previous call, if there are more than 100 items in the list, only the first 100 items are returned, along with a unique string called a <i>next token</i>. To get the next batch of items in the list, call this operation again, adding the next token to the call. To get all of the items in the list, keep calling this operation with each subsequent next token that is returned, until no more next tokens are returned.</p>
-- * sortOrder [SortOrderType] <p>The order to list build IDs. Valid values include:</p> <ul> <li> <p> <code>ASCENDING</code>: List the build IDs in ascending order by build ID.</p> </li> <li> <p> <code>DESCENDING</code>: List the build IDs in descending order by build ID.</p> </li> </ul>
-- Required key: projectName
-- @return ListBuildsForProjectInput structure as a key-value pair table
function M.ListBuildsForProjectInput(args)
assert(args, "You must provide an argument table when creating ListBuildsForProjectInput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["projectName"] = args["projectName"],
["nextToken"] = args["nextToken"],
["sortOrder"] = args["sortOrder"],
}
asserts.AssertListBuildsForProjectInput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.NetworkInterface = { ["subnetId"] = true, ["networkInterfaceId"] = true, nil }
function asserts.AssertNetworkInterface(struct)
assert(struct)
assert(type(struct) == "table", "Expected NetworkInterface to be of type 'table'")
if struct["subnetId"] then asserts.AssertNonEmptyString(struct["subnetId"]) end
if struct["networkInterfaceId"] then asserts.AssertNonEmptyString(struct["networkInterfaceId"]) end
for k,_ in pairs(struct) do
assert(keys.NetworkInterface[k], "NetworkInterface contains unknown key " .. tostring(k))
end
end
--- Create a structure of type NetworkInterface
-- <p>Describes a network interface.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * subnetId [NonEmptyString] <p>The ID of the subnet.</p>
-- * networkInterfaceId [NonEmptyString] <p>The ID of the network interface.</p>
-- @return NetworkInterface structure as a key-value pair table
function M.NetworkInterface(args)
assert(args, "You must provide an argument table when creating NetworkInterface")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["subnetId"] = args["subnetId"],
["networkInterfaceId"] = args["networkInterfaceId"],
}
asserts.AssertNetworkInterface(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.EnvironmentImage = { ["versions"] = true, ["name"] = true, ["description"] = true, nil }
function asserts.AssertEnvironmentImage(struct)
assert(struct)
assert(type(struct) == "table", "Expected EnvironmentImage to be of type 'table'")
if struct["versions"] then asserts.AssertImageVersions(struct["versions"]) end
if struct["name"] then asserts.AssertString(struct["name"]) end
if struct["description"] then asserts.AssertString(struct["description"]) end
for k,_ in pairs(struct) do
assert(keys.EnvironmentImage[k], "EnvironmentImage contains unknown key " .. tostring(k))
end
end
--- Create a structure of type EnvironmentImage
-- <p>Information about a Docker image that is managed by AWS CodeBuild.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * versions [ImageVersions] <p>A list of environment image versions.</p>
-- * name [String] <p>The name of the Docker image.</p>
-- * description [String] <p>The description of the Docker image.</p>
-- @return EnvironmentImage structure as a key-value pair table
function M.EnvironmentImage(args)
assert(args, "You must provide an argument table when creating EnvironmentImage")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["versions"] = args["versions"],
["name"] = args["name"],
["description"] = args["description"],
}
asserts.AssertEnvironmentImage(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListBuildsForProjectOutput = { ["nextToken"] = true, ["ids"] = true, nil }
function asserts.AssertListBuildsForProjectOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListBuildsForProjectOutput to be of type 'table'")
if struct["nextToken"] then asserts.AssertString(struct["nextToken"]) end
if struct["ids"] then asserts.AssertBuildIds(struct["ids"]) end
for k,_ in pairs(struct) do
assert(keys.ListBuildsForProjectOutput[k], "ListBuildsForProjectOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListBuildsForProjectOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * nextToken [String] <p>If there are more than 100 items in the list, only the first 100 items are returned, along with a unique string called a <i>next token</i>. To get the next batch of items in the list, call this operation again, adding the next token to the call.</p>
-- * ids [BuildIds] <p>A list of build IDs for the specified build project, with each build ID representing a single build.</p>
-- @return ListBuildsForProjectOutput structure as a key-value pair table
function M.ListBuildsForProjectOutput(args)
assert(args, "You must provide an argument table when creating ListBuildsForProjectOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["nextToken"] = args["nextToken"],
["ids"] = args["ids"],
}
asserts.AssertListBuildsForProjectOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.VpcConfig = { ["subnets"] = true, ["vpcId"] = true, ["securityGroupIds"] = true, nil }
function asserts.AssertVpcConfig(struct)
assert(struct)
assert(type(struct) == "table", "Expected VpcConfig to be of type 'table'")
if struct["subnets"] then asserts.AssertSubnets(struct["subnets"]) end
if struct["vpcId"] then asserts.AssertNonEmptyString(struct["vpcId"]) end
if struct["securityGroupIds"] then asserts.AssertSecurityGroupIds(struct["securityGroupIds"]) end
for k,_ in pairs(struct) do
assert(keys.VpcConfig[k], "VpcConfig contains unknown key " .. tostring(k))
end
end
--- Create a structure of type VpcConfig
-- <p>Information about the VPC configuration that AWS CodeBuild will access.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * subnets [Subnets] <p>A list of one or more subnet IDs in your Amazon VPC.</p>
-- * vpcId [NonEmptyString] <p>The ID of the Amazon VPC.</p>
-- * securityGroupIds [SecurityGroupIds] <p>A list of one or more security groups IDs in your Amazon VPC.</p>
-- @return VpcConfig structure as a key-value pair table
function M.VpcConfig(args)
assert(args, "You must provide an argument table when creating VpcConfig")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["subnets"] = args["subnets"],
["vpcId"] = args["vpcId"],
["securityGroupIds"] = args["securityGroupIds"],
}
asserts.AssertVpcConfig(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.BatchDeleteBuildsOutput = { ["buildsNotDeleted"] = true, ["buildsDeleted"] = true, nil }
function asserts.AssertBatchDeleteBuildsOutput(struct)
assert(struct)
assert(type(struct) == "table", "Expected BatchDeleteBuildsOutput to be of type 'table'")
if struct["buildsNotDeleted"] then asserts.AssertBuildsNotDeleted(struct["buildsNotDeleted"]) end
if struct["buildsDeleted"] then asserts.AssertBuildIds(struct["buildsDeleted"]) end
for k,_ in pairs(struct) do
assert(keys.BatchDeleteBuildsOutput[k], "BatchDeleteBuildsOutput contains unknown key " .. tostring(k))
end
end
--- Create a structure of type BatchDeleteBuildsOutput
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * buildsNotDeleted [BuildsNotDeleted] <p>Information about any builds that could not be successfully deleted.</p>
-- * buildsDeleted [BuildIds] <p>The IDs of the builds that were successfully deleted.</p>
-- @return BatchDeleteBuildsOutput structure as a key-value pair table
function M.BatchDeleteBuildsOutput(args)
assert(args, "You must provide an argument table when creating BatchDeleteBuildsOutput")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["buildsNotDeleted"] = args["buildsNotDeleted"],
["buildsDeleted"] = args["buildsDeleted"],
}
asserts.AssertBatchDeleteBuildsOutput(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ProjectEnvironment = { ["computeType"] = true, ["certificate"] = true, ["privilegedMode"] = true, ["image"] = true, ["environmentVariables"] = true, ["type"] = true, nil }
function asserts.AssertProjectEnvironment(struct)
assert(struct)
assert(type(struct) == "table", "Expected ProjectEnvironment to be of type 'table'")
assert(struct["type"], "Expected key type to exist in table")
assert(struct["image"], "Expected key image to exist in table")
assert(struct["computeType"], "Expected key computeType to exist in table")
if struct["computeType"] then asserts.AssertComputeType(struct["computeType"]) end
if struct["certificate"] then asserts.AssertString(struct["certificate"]) end
if struct["privilegedMode"] then asserts.AssertWrapperBoolean(struct["privilegedMode"]) end
if struct["image"] then asserts.AssertNonEmptyString(struct["image"]) end
if struct["environmentVariables"] then asserts.AssertEnvironmentVariables(struct["environmentVariables"]) end
if struct["type"] then asserts.AssertEnvironmentType(struct["type"]) end
for k,_ in pairs(struct) do
assert(keys.ProjectEnvironment[k], "ProjectEnvironment contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ProjectEnvironment
-- <p>Information about the build environment of the build project.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * computeType [ComputeType] <p>Information about the compute resources the build project will use. Available values include:</p> <ul> <li> <p> <code>BUILD_GENERAL1_SMALL</code>: Use up to 3 GB memory and 2 vCPUs for builds.</p> </li> <li> <p> <code>BUILD_GENERAL1_MEDIUM</code>: Use up to 7 GB memory and 4 vCPUs for builds.</p> </li> <li> <p> <code>BUILD_GENERAL1_LARGE</code>: Use up to 15 GB memory and 8 vCPUs for builds.</p> </li> </ul>
-- * certificate [String] <p>The certificate to use with this build project.</p>
-- * privilegedMode [WrapperBoolean] <p>Enables running the Docker daemon inside a Docker container. Set to true only if the build project is be used to build Docker images, and the specified build environment image is not provided by AWS CodeBuild with Docker support. Otherwise, all associated builds that attempt to interact with the Docker daemon will fail. Note that you must also start the Docker daemon so that builds can interact with it. One way to do this is to initialize the Docker daemon during the install phase of your build spec by running the following build commands. (Do not run the following build commands if the specified build environment image is provided by AWS CodeBuild with Docker support.)</p> <p>If the operating system's base image is Ubuntu Linux:</p> <p> <code>- nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://0.0.0.0:2375 --storage-driver=overlay& - timeout 15 sh -c "until docker info; do echo .; sleep 1; done"</code> </p> <p>If the operating system's base image is Alpine Linux, add the <code>-t</code> argument to <code>timeout</code>:</p> <p> <code>- nohup /usr/local/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://0.0.0.0:2375 --storage-driver=overlay& - timeout 15 -t sh -c "until docker info; do echo .; sleep 1; done"</code> </p>
-- * image [NonEmptyString] <p>The ID of the Docker image to use for this build project.</p>
-- * environmentVariables [EnvironmentVariables] <p>A set of environment variables to make available to builds for this build project.</p>
-- * type [EnvironmentType] <p>The type of build environment to use for related builds.</p>
-- Required key: type
-- Required key: image
-- Required key: computeType
-- @return ProjectEnvironment structure as a key-value pair table
function M.ProjectEnvironment(args)
assert(args, "You must provide an argument table when creating ProjectEnvironment")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["computeType"] = args["computeType"],
["certificate"] = args["certificate"],
["privilegedMode"] = args["privilegedMode"],
["image"] = args["image"],
["environmentVariables"] = args["environmentVariables"],
["type"] = args["type"],
}
asserts.AssertProjectEnvironment(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.EnvironmentLanguage = { ["images"] = true, ["language"] = true, nil }
function asserts.AssertEnvironmentLanguage(struct)
assert(struct)
assert(type(struct) == "table", "Expected EnvironmentLanguage to be of type 'table'")
if struct["images"] then asserts.AssertEnvironmentImages(struct["images"]) end
if struct["language"] then asserts.AssertLanguageType(struct["language"]) end
for k,_ in pairs(struct) do
assert(keys.EnvironmentLanguage[k], "EnvironmentLanguage contains unknown key " .. tostring(k))
end
end
--- Create a structure of type EnvironmentLanguage
-- <p>A set of Docker images that are related by programming language and are managed by AWS CodeBuild.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * images [EnvironmentImages] <p>The list of Docker images that are related by the specified programming language.</p>
-- * language [LanguageType] <p>The programming language for the Docker images.</p>
-- @return EnvironmentLanguage structure as a key-value pair table
function M.EnvironmentLanguage(args)
assert(args, "You must provide an argument table when creating EnvironmentLanguage")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["images"] = args["images"],
["language"] = args["language"],
}
asserts.AssertEnvironmentLanguage(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.SourceAuth = { ["resource"] = true, ["type"] = true, nil }
function asserts.AssertSourceAuth(struct)
assert(struct)
assert(type(struct) == "table", "Expected SourceAuth to be of type 'table'")
assert(struct["type"], "Expected key type to exist in table")
if struct["resource"] then asserts.AssertString(struct["resource"]) end
if struct["type"] then asserts.AssertSourceAuthType(struct["type"]) end
for k,_ in pairs(struct) do
assert(keys.SourceAuth[k], "SourceAuth contains unknown key " .. tostring(k))
end
end
--- Create a structure of type SourceAuth
-- <p>Information about the authorization settings for AWS CodeBuild to access the source code to be built.</p> <p>This information is for the AWS CodeBuild console's use only. Your code should not get or set this information directly (unless the build project's source <code>type</code> value is <code>BITBUCKET</code> or <code>GITHUB</code>).</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * resource [String] <p>The resource value that applies to the specified authorization type.</p>
-- * type [SourceAuthType] <p>The authorization type to use. The only valid value is <code>OAUTH</code>, which represents the OAuth authorization type.</p>
-- Required key: type
-- @return SourceAuth structure as a key-value pair table
function M.SourceAuth(args)
assert(args, "You must provide an argument table when creating SourceAuth")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["resource"] = args["resource"],
["type"] = args["type"],
}
asserts.AssertSourceAuth(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
function asserts.AssertCacheType(str)
assert(str)
assert(type(str) == "string", "Expected CacheType to be of type 'string'")
end
--
function M.CacheType(str)
asserts.AssertCacheType(str)
return str
end
function asserts.AssertProjectSortByType(str)
assert(str)
assert(type(str) == "string", "Expected ProjectSortByType to be of type 'string'")
end
--
function M.ProjectSortByType(str)
asserts.AssertProjectSortByType(str)
return str
end
function asserts.AssertProjectDescription(str)
assert(str)
assert(type(str) == "string", "Expected ProjectDescription to be of type 'string'")
assert(#str <= 255, "Expected string to be max 255 characters")
end
--
function M.ProjectDescription(str)
asserts.AssertProjectDescription(str)
return str
end
function asserts.AssertEnvironmentType(str)
assert(str)
assert(type(str) == "string", "Expected EnvironmentType to be of type 'string'")
end
--
function M.EnvironmentType(str)
asserts.AssertEnvironmentType(str)
return str
end
function asserts.AssertEnvironmentVariableType(str)
assert(str)
assert(type(str) == "string", "Expected EnvironmentVariableType to be of type 'string'")
end
--
function M.EnvironmentVariableType(str)
asserts.AssertEnvironmentVariableType(str)
return str
end
function asserts.AssertSourceAuthType(str)
assert(str)
assert(type(str) == "string", "Expected SourceAuthType to be of type 'string'")
end
--
function M.SourceAuthType(str)
asserts.AssertSourceAuthType(str)
return str
end
function asserts.AssertNonEmptyString(str)
assert(str)
assert(type(str) == "string", "Expected NonEmptyString to be of type 'string'")
assert(#str >= 1, "Expected string to be min 1 characters")
end
--
function M.NonEmptyString(str)
asserts.AssertNonEmptyString(str)
return str
end
function asserts.AssertStatusType(str)
assert(str)
assert(type(str) == "string", "Expected StatusType to be of type 'string'")
end
--
function M.StatusType(str)
asserts.AssertStatusType(str)
return str
end
function asserts.AssertArtifactPackaging(str)
assert(str)
assert(type(str) == "string", "Expected ArtifactPackaging to be of type 'string'")
end
--
function M.ArtifactPackaging(str)
asserts.AssertArtifactPackaging(str)
return str
end
function asserts.AssertString(str)
assert(str)
assert(type(str) == "string", "Expected String to be of type 'string'")
end
--
function M.String(str)
asserts.AssertString(str)
return str
end
function asserts.AssertBuildPhaseType(str)
assert(str)
assert(type(str) == "string", "Expected BuildPhaseType to be of type 'string'")
end
--
function M.BuildPhaseType(str)
asserts.AssertBuildPhaseType(str)
return str
end
function asserts.AssertPlatformType(str)
assert(str)
assert(type(str) == "string", "Expected PlatformType to be of type 'string'")
end
--
function M.PlatformType(str)
asserts.AssertPlatformType(str)
return str
end
function asserts.AssertValueInput(str)
assert(str)
assert(type(str) == "string", "Expected ValueInput to be of type 'string'")
assert(#str <= 255, "Expected string to be max 255 characters")
assert(#str >= 1, "Expected string to be min 1 characters")
end
--
function M.ValueInput(str)
asserts.AssertValueInput(str)
return str
end
function asserts.AssertSourceType(str)
assert(str)
assert(type(str) == "string", "Expected SourceType to be of type 'string'")
end
--
function M.SourceType(str)
asserts.AssertSourceType(str)
return str
end
function asserts.AssertProjectName(str)
assert(str)
assert(type(str) == "string", "Expected ProjectName to be of type 'string'")
assert(#str <= 255, "Expected string to be max 255 characters")
assert(#str >= 2, "Expected string to be min 2 characters")
end
--
function M.ProjectName(str)
asserts.AssertProjectName(str)
return str
end
function asserts.AssertSortOrderType(str)
assert(str)
assert(type(str) == "string", "Expected SortOrderType to be of type 'string'")
end
--
function M.SortOrderType(str)
asserts.AssertSortOrderType(str)
return str
end
function asserts.AssertComputeType(str)
assert(str)
assert(type(str) == "string", "Expected ComputeType to be of type 'string'")
end
--
function M.ComputeType(str)
asserts.AssertComputeType(str)
return str
end
function asserts.AssertLogsConfigStatusType(str)
assert(str)
assert(type(str) == "string", "Expected LogsConfigStatusType to be of type 'string'")
end
--
function M.LogsConfigStatusType(str)
asserts.AssertLogsConfigStatusType(str)
return str
end
function asserts.AssertLanguageType(str)
assert(str)
assert(type(str) == "string", "Expected LanguageType to be of type 'string'")
end
--
function M.LanguageType(str)
asserts.AssertLanguageType(str)
return str
end
function asserts.AssertArtifactsType(str)
assert(str)
assert(type(str) == "string", "Expected ArtifactsType to be of type 'string'")
end
--
function M.ArtifactsType(str)
asserts.AssertArtifactsType(str)
return str
end
function asserts.AssertArtifactNamespace(str)
assert(str)
assert(type(str) == "string", "Expected ArtifactNamespace to be of type 'string'")
end
--
function M.ArtifactNamespace(str)
asserts.AssertArtifactNamespace(str)
return str
end
function asserts.AssertKeyInput(str)
assert(str)
assert(type(str) == "string", "Expected KeyInput to be of type 'string'")
assert(#str <= 127, "Expected string to be max 127 characters")
assert(#str >= 1, "Expected string to be min 1 characters")
end
--
function M.KeyInput(str)
asserts.AssertKeyInput(str)
return str
end
function asserts.AssertWrapperLong(long)
assert(long)
assert(type(long) == "number", "Expected WrapperLong to be of type 'number'")
assert(long % 1 == 0, "Expected a whole integer number")
end
function M.WrapperLong(long)
asserts.AssertWrapperLong(long)
return long
end
function asserts.AssertGitCloneDepth(integer)
assert(integer)
assert(type(integer) == "number", "Expected GitCloneDepth to be of type 'number'")
assert(integer % 1 == 0, "Expected a while integer number")
end
function M.GitCloneDepth(integer)
asserts.AssertGitCloneDepth(integer)
return integer
end
function asserts.AssertTimeOut(integer)
assert(integer)
assert(type(integer) == "number", "Expected TimeOut to be of type 'number'")
assert(integer % 1 == 0, "Expected a while integer number")
assert(integer <= 480, "Expected integer to be max 480")
assert(integer >= 5, "Expected integer to be min 5")
end
function M.TimeOut(integer)
asserts.AssertTimeOut(integer)
return integer
end
function asserts.AssertWrapperInt(integer)
assert(integer)
assert(type(integer) == "number", "Expected WrapperInt to be of type 'number'")
assert(integer % 1 == 0, "Expected a while integer number")
end
function M.WrapperInt(integer)
asserts.AssertWrapperInt(integer)
return integer
end
function asserts.AssertWrapperBoolean(boolean)
assert(boolean)
assert(type(boolean) == "boolean", "Expected WrapperBoolean to be of type 'boolean'")
end
function M.WrapperBoolean(boolean)
asserts.AssertWrapperBoolean(boolean)
return boolean
end
function asserts.AssertBoolean(boolean)
assert(boolean)
assert(type(boolean) == "boolean", "Expected Boolean to be of type 'boolean'")
end
function M.Boolean(boolean)
asserts.AssertBoolean(boolean)
return boolean
end
function asserts.AssertTimestamp(timestamp)
assert(timestamp)
assert(type(timestamp) == "string", "Expected Timestamp to be of type 'string'")
end
function M.Timestamp(timestamp)
asserts.AssertTimestamp(timestamp)
return timestamp
end
function asserts.AssertImageVersions(list)
assert(list)
assert(type(list) == "table", "Expected ImageVersions to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertString(v)
end
end
--
-- List of String objects
function M.ImageVersions(list)
asserts.AssertImageVersions(list)
return list
end
function asserts.AssertBuildsNotDeleted(list)
assert(list)
assert(type(list) == "table", "Expected BuildsNotDeleted to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertBuildNotDeleted(v)
end
end
--
-- List of BuildNotDeleted objects
function M.BuildsNotDeleted(list)
asserts.AssertBuildsNotDeleted(list)
return list
end
function asserts.AssertSubnets(list)
assert(list)
assert(type(list) == "table", "Expected Subnets to be of type ''table")
assert(#list <= 16, "Expected list to be contain 16 elements")
for _,v in ipairs(list) do
asserts.AssertNonEmptyString(v)
end
end
--
-- List of NonEmptyString objects
function M.Subnets(list)
asserts.AssertSubnets(list)
return list
end
function asserts.AssertProjects(list)
assert(list)
assert(type(list) == "table", "Expected Projects to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertProject(v)
end
end
--
-- List of Project objects
function M.Projects(list)
asserts.AssertProjects(list)
return list
end
function asserts.AssertEnvironmentPlatforms(list)
assert(list)
assert(type(list) == "table", "Expected EnvironmentPlatforms to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertEnvironmentPlatform(v)
end
end
--
-- List of EnvironmentPlatform objects
function M.EnvironmentPlatforms(list)
asserts.AssertEnvironmentPlatforms(list)
return list
end
function asserts.AssertBuildIds(list)
assert(list)
assert(type(list) == "table", "Expected BuildIds to be of type ''table")
assert(#list <= 100, "Expected list to be contain 100 elements")
assert(#list >= 1, "Expected list to be contain 1 elements")
for _,v in ipairs(list) do
asserts.AssertNonEmptyString(v)
end
end
--
-- List of NonEmptyString objects
function M.BuildIds(list)
asserts.AssertBuildIds(list)
return list
end
function asserts.AssertSecurityGroupIds(list)
assert(list)
assert(type(list) == "table", "Expected SecurityGroupIds to be of type ''table")
assert(#list <= 5, "Expected list to be contain 5 elements")
for _,v in ipairs(list) do
asserts.AssertNonEmptyString(v)
end
end
--
-- List of NonEmptyString objects
function M.SecurityGroupIds(list)
asserts.AssertSecurityGroupIds(list)
return list
end
function asserts.AssertPhaseContexts(list)
assert(list)
assert(type(list) == "table", "Expected PhaseContexts to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertPhaseContext(v)
end
end
--
-- List of PhaseContext objects
function M.PhaseContexts(list)
asserts.AssertPhaseContexts(list)
return list
end
function asserts.AssertBuildPhases(list)
assert(list)
assert(type(list) == "table", "Expected BuildPhases to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertBuildPhase(v)
end
end
--
-- List of BuildPhase objects
function M.BuildPhases(list)
asserts.AssertBuildPhases(list)
return list
end
function asserts.AssertProjectSecondarySourceVersions(list)
assert(list)
assert(type(list) == "table", "Expected ProjectSecondarySourceVersions to be of type ''table")
assert(#list <= 12, "Expected list to be contain 12 elements")
for _,v in ipairs(list) do
asserts.AssertProjectSourceVersion(v)
end
end
--
-- List of ProjectSourceVersion objects
function M.ProjectSecondarySourceVersions(list)
asserts.AssertProjectSecondarySourceVersions(list)
return list
end
function asserts.AssertProjectNames(list)
assert(list)
assert(type(list) == "table", "Expected ProjectNames to be of type ''table")
assert(#list <= 100, "Expected list to be contain 100 elements")
assert(#list >= 1, "Expected list to be contain 1 elements")
for _,v in ipairs(list) do
asserts.AssertNonEmptyString(v)
end
end
--
-- List of NonEmptyString objects
function M.ProjectNames(list)
asserts.AssertProjectNames(list)
return list
end
function asserts.AssertEnvironmentLanguages(list)
assert(list)
assert(type(list) == "table", "Expected EnvironmentLanguages to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertEnvironmentLanguage(v)
end
end
--
-- List of EnvironmentLanguage objects
function M.EnvironmentLanguages(list)
asserts.AssertEnvironmentLanguages(list)
return list
end
function asserts.AssertBuildArtifactsList(list)
assert(list)
assert(type(list) == "table", "Expected BuildArtifactsList to be of type ''table")
assert(#list <= 12, "Expected list to be contain 12 elements")
for _,v in ipairs(list) do
asserts.AssertBuildArtifacts(v)
end
end
--
-- List of BuildArtifacts objects
function M.BuildArtifactsList(list)
asserts.AssertBuildArtifactsList(list)
return list
end
function asserts.AssertEnvironmentVariables(list)
assert(list)
assert(type(list) == "table", "Expected EnvironmentVariables to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertEnvironmentVariable(v)
end
end
--
-- List of EnvironmentVariable objects
function M.EnvironmentVariables(list)
asserts.AssertEnvironmentVariables(list)
return list
end
function asserts.AssertEnvironmentImages(list)
assert(list)
assert(type(list) == "table", "Expected EnvironmentImages to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertEnvironmentImage(v)
end
end
--
-- List of EnvironmentImage objects
function M.EnvironmentImages(list)
asserts.AssertEnvironmentImages(list)
return list
end
function asserts.AssertProjectSources(list)
assert(list)
assert(type(list) == "table", "Expected ProjectSources to be of type ''table")
assert(#list <= 12, "Expected list to be contain 12 elements")
for _,v in ipairs(list) do
asserts.AssertProjectSource(v)
end
end
--
-- List of ProjectSource objects
function M.ProjectSources(list)
asserts.AssertProjectSources(list)
return list
end
function asserts.AssertBuilds(list)
assert(list)
assert(type(list) == "table", "Expected Builds to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertBuild(v)
end
end
--
-- List of Build objects
function M.Builds(list)
asserts.AssertBuilds(list)
return list
end
function asserts.AssertProjectArtifactsList(list)
assert(list)
assert(type(list) == "table", "Expected ProjectArtifactsList to be of type ''table")
assert(#list <= 12, "Expected list to be contain 12 elements")
for _,v in ipairs(list) do
asserts.AssertProjectArtifacts(v)
end
end
--
-- List of ProjectArtifacts objects
function M.ProjectArtifactsList(list)
asserts.AssertProjectArtifactsList(list)
return list
end
function asserts.AssertTagList(list)
assert(list)
assert(type(list) == "table", "Expected TagList to be of type ''table")
assert(#list <= 50, "Expected list to be contain 50 elements")
for _,v in ipairs(list) do
asserts.AssertTag(v)
end
end
--
-- List of Tag objects
function M.TagList(list)
asserts.AssertTagList(list)
return list
end
local content_type = require "aws-sdk.core.content_type"
local request_headers = require "aws-sdk.core.request_headers"
local request_handlers = require "aws-sdk.core.request_handlers"
local settings = {}
local function endpoint_for_region(region, use_dualstack)
if not use_dualstack then
if region == "us-east-1" then
return "codebuild.amazonaws.com"
end
end
local ss = { "codebuild" }
if use_dualstack then
ss[#ss + 1] = "dualstack"
end
ss[#ss + 1] = region
ss[#ss + 1] = "amazonaws.com"
if region == "cn-north-1" then
ss[#ss + 1] = "cn"
end
return table.concat(ss, ".")
end
function M.init(config)
assert(config, "You must provide a config table")
assert(config.region, "You must provide a region in the config table")
settings.service = M.metadata.endpoint_prefix
settings.protocol = M.metadata.protocol
settings.region = config.region
settings.endpoint = config.endpoint_override or endpoint_for_region(config.region, config.use_dualstack)
settings.signature_version = M.metadata.signature_version
settings.uri = (config.scheme or "https") .. "://" .. settings.endpoint
end
--
-- OPERATIONS
--
--- Call ListBuilds asynchronously, invoking a callback when done
-- @param ListBuildsInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ListBuildsAsync(ListBuildsInput, cb)
assert(ListBuildsInput, "You must provide a ListBuildsInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.ListBuilds",
}
for header,value in pairs(ListBuildsInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", ListBuildsInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ListBuilds synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ListBuildsInput
-- @return response
-- @return error_type
-- @return error_message
function M.ListBuildsSync(ListBuildsInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ListBuildsAsync(ListBuildsInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call UpdateWebhook asynchronously, invoking a callback when done
-- @param UpdateWebhookInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.UpdateWebhookAsync(UpdateWebhookInput, cb)
assert(UpdateWebhookInput, "You must provide a UpdateWebhookInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.UpdateWebhook",
}
for header,value in pairs(UpdateWebhookInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", UpdateWebhookInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call UpdateWebhook synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param UpdateWebhookInput
-- @return response
-- @return error_type
-- @return error_message
function M.UpdateWebhookSync(UpdateWebhookInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.UpdateWebhookAsync(UpdateWebhookInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call StopBuild asynchronously, invoking a callback when done
-- @param StopBuildInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.StopBuildAsync(StopBuildInput, cb)
assert(StopBuildInput, "You must provide a StopBuildInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.StopBuild",
}
for header,value in pairs(StopBuildInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", StopBuildInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call StopBuild synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param StopBuildInput
-- @return response
-- @return error_type
-- @return error_message
function M.StopBuildSync(StopBuildInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.StopBuildAsync(StopBuildInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call ListBuildsForProject asynchronously, invoking a callback when done
-- @param ListBuildsForProjectInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ListBuildsForProjectAsync(ListBuildsForProjectInput, cb)
assert(ListBuildsForProjectInput, "You must provide a ListBuildsForProjectInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.ListBuildsForProject",
}
for header,value in pairs(ListBuildsForProjectInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", ListBuildsForProjectInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ListBuildsForProject synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ListBuildsForProjectInput
-- @return response
-- @return error_type
-- @return error_message
function M.ListBuildsForProjectSync(ListBuildsForProjectInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ListBuildsForProjectAsync(ListBuildsForProjectInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call BatchGetBuilds asynchronously, invoking a callback when done
-- @param BatchGetBuildsInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.BatchGetBuildsAsync(BatchGetBuildsInput, cb)
assert(BatchGetBuildsInput, "You must provide a BatchGetBuildsInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.BatchGetBuilds",
}
for header,value in pairs(BatchGetBuildsInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", BatchGetBuildsInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call BatchGetBuilds synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param BatchGetBuildsInput
-- @return response
-- @return error_type
-- @return error_message
function M.BatchGetBuildsSync(BatchGetBuildsInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.BatchGetBuildsAsync(BatchGetBuildsInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call ListProjects asynchronously, invoking a callback when done
-- @param ListProjectsInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ListProjectsAsync(ListProjectsInput, cb)
assert(ListProjectsInput, "You must provide a ListProjectsInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.ListProjects",
}
for header,value in pairs(ListProjectsInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", ListProjectsInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ListProjects synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ListProjectsInput
-- @return response
-- @return error_type
-- @return error_message
function M.ListProjectsSync(ListProjectsInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ListProjectsAsync(ListProjectsInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call CreateProject asynchronously, invoking a callback when done
-- @param CreateProjectInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.CreateProjectAsync(CreateProjectInput, cb)
assert(CreateProjectInput, "You must provide a CreateProjectInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.CreateProject",
}
for header,value in pairs(CreateProjectInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", CreateProjectInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call CreateProject synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param CreateProjectInput
-- @return response
-- @return error_type
-- @return error_message
function M.CreateProjectSync(CreateProjectInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.CreateProjectAsync(CreateProjectInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call ListCuratedEnvironmentImages asynchronously, invoking a callback when done
-- @param ListCuratedEnvironmentImagesInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ListCuratedEnvironmentImagesAsync(ListCuratedEnvironmentImagesInput, cb)
assert(ListCuratedEnvironmentImagesInput, "You must provide a ListCuratedEnvironmentImagesInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.ListCuratedEnvironmentImages",
}
for header,value in pairs(ListCuratedEnvironmentImagesInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", ListCuratedEnvironmentImagesInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ListCuratedEnvironmentImages synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ListCuratedEnvironmentImagesInput
-- @return response
-- @return error_type
-- @return error_message
function M.ListCuratedEnvironmentImagesSync(ListCuratedEnvironmentImagesInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ListCuratedEnvironmentImagesAsync(ListCuratedEnvironmentImagesInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call CreateWebhook asynchronously, invoking a callback when done
-- @param CreateWebhookInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.CreateWebhookAsync(CreateWebhookInput, cb)
assert(CreateWebhookInput, "You must provide a CreateWebhookInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.CreateWebhook",
}
for header,value in pairs(CreateWebhookInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", CreateWebhookInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call CreateWebhook synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param CreateWebhookInput
-- @return response
-- @return error_type
-- @return error_message
function M.CreateWebhookSync(CreateWebhookInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.CreateWebhookAsync(CreateWebhookInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call InvalidateProjectCache asynchronously, invoking a callback when done
-- @param InvalidateProjectCacheInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.InvalidateProjectCacheAsync(InvalidateProjectCacheInput, cb)
assert(InvalidateProjectCacheInput, "You must provide a InvalidateProjectCacheInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.InvalidateProjectCache",
}
for header,value in pairs(InvalidateProjectCacheInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", InvalidateProjectCacheInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call InvalidateProjectCache synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param InvalidateProjectCacheInput
-- @return response
-- @return error_type
-- @return error_message
function M.InvalidateProjectCacheSync(InvalidateProjectCacheInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.InvalidateProjectCacheAsync(InvalidateProjectCacheInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call StartBuild asynchronously, invoking a callback when done
-- @param StartBuildInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.StartBuildAsync(StartBuildInput, cb)
assert(StartBuildInput, "You must provide a StartBuildInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.StartBuild",
}
for header,value in pairs(StartBuildInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", StartBuildInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call StartBuild synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param StartBuildInput
-- @return response
-- @return error_type
-- @return error_message
function M.StartBuildSync(StartBuildInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.StartBuildAsync(StartBuildInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call DeleteProject asynchronously, invoking a callback when done
-- @param DeleteProjectInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.DeleteProjectAsync(DeleteProjectInput, cb)
assert(DeleteProjectInput, "You must provide a DeleteProjectInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.DeleteProject",
}
for header,value in pairs(DeleteProjectInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", DeleteProjectInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call DeleteProject synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param DeleteProjectInput
-- @return response
-- @return error_type
-- @return error_message
function M.DeleteProjectSync(DeleteProjectInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.DeleteProjectAsync(DeleteProjectInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call UpdateProject asynchronously, invoking a callback when done
-- @param UpdateProjectInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.UpdateProjectAsync(UpdateProjectInput, cb)
assert(UpdateProjectInput, "You must provide a UpdateProjectInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.UpdateProject",
}
for header,value in pairs(UpdateProjectInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", UpdateProjectInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call UpdateProject synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param UpdateProjectInput
-- @return response
-- @return error_type
-- @return error_message
function M.UpdateProjectSync(UpdateProjectInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.UpdateProjectAsync(UpdateProjectInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call DeleteWebhook asynchronously, invoking a callback when done
-- @param DeleteWebhookInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.DeleteWebhookAsync(DeleteWebhookInput, cb)
assert(DeleteWebhookInput, "You must provide a DeleteWebhookInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.DeleteWebhook",
}
for header,value in pairs(DeleteWebhookInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", DeleteWebhookInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call DeleteWebhook synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param DeleteWebhookInput
-- @return response
-- @return error_type
-- @return error_message
function M.DeleteWebhookSync(DeleteWebhookInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.DeleteWebhookAsync(DeleteWebhookInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call BatchGetProjects asynchronously, invoking a callback when done
-- @param BatchGetProjectsInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.BatchGetProjectsAsync(BatchGetProjectsInput, cb)
assert(BatchGetProjectsInput, "You must provide a BatchGetProjectsInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.BatchGetProjects",
}
for header,value in pairs(BatchGetProjectsInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", BatchGetProjectsInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call BatchGetProjects synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param BatchGetProjectsInput
-- @return response
-- @return error_type
-- @return error_message
function M.BatchGetProjectsSync(BatchGetProjectsInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.BatchGetProjectsAsync(BatchGetProjectsInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call BatchDeleteBuilds asynchronously, invoking a callback when done
-- @param BatchDeleteBuildsInput
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.BatchDeleteBuildsAsync(BatchDeleteBuildsInput, cb)
assert(BatchDeleteBuildsInput, "You must provide a BatchDeleteBuildsInput")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = "CodeBuild_20161006.BatchDeleteBuilds",
}
for header,value in pairs(BatchDeleteBuildsInput.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("json", "POST")
if request_handler then
request_handler(settings.uri, "/", BatchDeleteBuildsInput, headers, settings, cb)
else
cb(false, err)
end
end
--- Call BatchDeleteBuilds synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param BatchDeleteBuildsInput
-- @return response
-- @return error_type
-- @return error_message
function M.BatchDeleteBuildsSync(BatchDeleteBuildsInput, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.BatchDeleteBuildsAsync(BatchDeleteBuildsInput, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
return M
|
local _={}
_[12]={}
_[11]={}
_[10]={tags=_[11],text="ne"}
_[9]={tags=_[12],text="ye"}
_[8]={tags=_[11],text="ok"}
_[7]={_[10]}
_[6]={_[9]}
_[5]={_[8]}
_[4]={_[6],_[7]}
_[3]={"return"}
_[2]={"text",_[5]}
_[1]={"choice",_[4]}
return {_[1],_[2],_[3]}
--[[
{ "choice", { { {
tags = {},
text = "ye"
} }, { {
tags = {},
text = "ne"
} } } }
{ "text", { {
tags = {},
text = "ok"
} } }
{ "return" }
]]-- |
--[[Author: YOLOSPAGHETTI
Date: February 5, 2016
Puts Riki behind the target, if the target is an enemy, applies the bonus damage,
and queues up an attack order on the target]]
function BlinkStrike( keys )
local caster = keys.caster
local target = keys.target
local ability = keys.ability
local ability_level = ability:GetLevel() - 1
-- Ability variables
local bonus_damage = ability:GetLevelSpecialValueFor("bonus_damage", ability_level)
local victim_angle = target:GetAnglesAsVector()
local victim_forward_vector = target:GetForwardVector()
-- Angle and positioning variables
local victim_angle_rad = victim_angle.y*math.pi/180
local victim_position = target:GetAbsOrigin()
local attacker_new = Vector(victim_position.x - 100 * math.cos(victim_angle_rad), victim_position.y - 100 * math.sin(victim_angle_rad), 0)
-- Sets Riki behind the victim and facing it
caster:SetAbsOrigin(attacker_new)
FindClearSpaceForUnit(caster, attacker_new, true)
caster:SetForwardVector(victim_forward_vector)
-- If the target is an enemy then apply the bonus damage
if target:GetTeamNumber() ~= caster:GetTeamNumber() then
ApplyDamage({victim = target, attacker = caster, damage = bonus_damage, damage_type = ability:GetAbilityDamageType()})
end
-- Order the caster to attack the target
-- Necessary on jumps to allies as well (does not actually attack), otherwise Riki will turn back to his initial angle
order =
{
UnitIndex = caster:entindex(),
OrderType = DOTA_UNIT_ORDER_ATTACK_TARGET,
TargetIndex = target:entindex(),
AbilityIndex = ability,
Queue = true
}
ExecuteOrderFromTable(order)
end
|
-- test_hostconnection.lua
package.path = package.path..';../?.lua'
local Connection = require("hostconnection")
local Domain = require("domain")
local function printAttributes(conn)
print("==== printAttributes ====")
print("Host Name: ", conn:getHostName());
print("Encrypted: ", conn:isEncrypted());
print(" Secure: ", conn:isSecure());
print(" Live: ", conn:isAlive());
end
local function reboot(conn, domainname)
-- get a handle on the domain by name
local dom = Domain(conn.Handle, domainname)
if not dom then
return false, "could not get domain"
end
dom:reboot();
return true
end
local hosturi = "qemu:///system"
local conn = Connection(hosturi);
if not conn then
print("No connection established to: ", hosturi)
return
end
printAttributes(conn)
reboot(conn, "win81")
|
cfg = {
classDamageMultiplier = { [0] = 0.7,0.7,0.7,0.7,0.7,0.7,0.7,0.7,0.30,0.7,0.30,0.7,0.7,0.7,0.05,0.05,0.05,0.5,0.5,0.2,0.7,0.05 }
} |
require('neorg').setup {
load = {
['core.defaults'] = {},
['core.norg.concealer'] = {},
['core.norg.dirman'] = {
config = {
workspaces = {
default = '~/notes'
}
}
}
},
}
|
-- Copyright 2008 Steven Barth <[email protected]>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.admin.index", package.seeall)
local debugger = require "luci.debugger"
-- Shellfire Box modifications index function
--[[
function index()
local root = node()
if not root.target then
root.target = alias("admin")
root.index = true
end
local page = node("admin")
page.target = firstchild()
page.title = _("Administration")
page.order = 10
page.sysauth = "root"
page.sysauth_authenticator = "htmlauth"
page.ucidata = true
page.index = true
-- Empty services menu to be populated by addons
entry({"admin", "services"}, firstchild(), _("Services"), 40).index = true
entry({"admin", "logout"}, call("action_logout"), _("Logout"), 90)
end
--]]
function index()
local root = node()
if not root.target then
root.target = alias("admin")
root.index = true
end
local page = node("admin")
page.target = alias("admin", "services", "shellfirebox")
page.title = _("Administration")
page.order = 10
local shellfirebox = require "luci.shellfirebox"
if luci.sys.user.getpasswd("root") then
page.sysauth = "root"
page.sysauth_authenticator = "htmlauth"
entry({"admin", "logout"}, call("action_logout"), _("Logout"), 90)
else
page.sysauth = false
end
page.ucidata = true
page.index = true
-- Empty services menu to be populated by addons
entry({"admin", "services"}, firstchild(), _("Services"), 40).index = true
end
function action_logout()
-- Shellfire Box modiciations below
-- following 2 lines inserted (+ added tabs in if ... statement)
local shellfirebox = require "luci.shellfirebox"
if shellfirebox.isAdvancedMode() then
local dsp = require "luci.dispatcher"
local utl = require "luci.util"
local sid = dsp.context.authsession
if sid then
utl.ubus("session", "destroy", { ubus_rpc_session = sid })
luci.http.header("Set-Cookie", "sysauth=%s; expires=%s; path=%s/" %{
sid, 'Thu, 01 Jan 1970 01:00:00 GMT', dsp.build_url()
})
end
-- Shellfire Box modification below
-- following line inserted
end
luci.http.redirect(dsp.build_url())
end
|
BP = {
--SETTINGS
P_CYLINDER_MAX = 3.8, --max cylinder pressure [at]
P_CYLINDER_ATTACK = 0.4, --max cylinder pressure attack per second [at/s]
P_CYLINDER_RELEASE = 0.2, --max cylinder pressure release per second [at/s]
CYLINDER_VOLUME_RATIO = 0.1, --volume ratio cylinder:resevoir [NaN]
PAD_APPLY_DELAY = 0, --time for which piston travels between release position and wheel [s/at]
P_SENSITIVITY = 0.3, --pressure sensitivity - hysteresis [at]
--public I/O variables
--output
cylinderAnim = 0, --cylinder animation time from beginning (-PAD_APPLY_DELAY - P_CYLINDER_MAX)
pCylinder = 0, --cylinder pressure from direct brake [at]
pMainRes = 0, --INPUT/OUTPUT! - main reservoir pressure [at]
--internal variables
pCylinderTarget = 0,
Update = function(self, control, dTime)
local padApplyEquiv = self.PAD_APPLY_DELAY*self.P_CYLINDER_ATTACK
local hysteresisMultiplier = (self.P_CYLINDER_MAX + 2*self.P_SENSITIVITY + padApplyEquiv)/self.P_CYLINDER_MAX
local _pCylinderTarget = math.min(control*self.P_CYLINDER_MAX*hysteresisMultiplier - self.P_SENSITIVITY - padApplyEquiv, self.pMainRes)
if self.pCylinderTarget > _pCylinderTarget + self.P_SENSITIVITY then
self.pCylinderTarget = _pCylinderTarget + self.P_SENSITIVITY
elseif self.pCylinderTarget < _pCylinderTarget - self.P_SENSITIVITY then
self.pCylinderTarget = _pCylinderTarget - self.P_SENSITIVITY
end
if math.abs(self.cylinderAnim - self.pCylinderTarget) < dTime*math.min(self.P_CYLINDER_RELEASE, self.P_CYLINDER_ATTACK) then
self.cylinderAnim = self.pCylinderTarget
elseif self.cylinderAnim > self.pCylinderTarget then
local clampedCylinderTarget = math.min(math.max(_pCylinderTarget, 0), self.P_CYLINDER_MAX)
local dCylinder = math.max(self.cylinderAnim - math.max(self.pCylinderTarget, clampedCylinderTarget), 0)*dTime*self.P_CYLINDER_RELEASE
self.cylinderAnim = math.max(self.cylinderAnim - dCylinder, self.pCylinderTarget)
elseif self.pCylinderTarget > self.cylinderAnim then
local clampedCylinderTarget = math.min(math.max(_pCylinderTarget, 0), self.P_CYLINDER_MAX)
local dCylinder = math.max(math.min(self.pCylinderTarget, clampedCylinderTarget) - self.cylinderAnim, 0)*dTime*self.P_CYLINDER_ATTACK
self.cylinderAnim = math.min(self.cylinderAnim + dCylinder, self.pCylinderTarget)
self.pMainRes = self.pMainRes - dCylinder*self.CYLINDER_VOLUME_RATIO
end
self.pCylinder = math.max(self.cylinderAnim, 0)
return self.pCylinder/self.P_CYLINDER_MAX
end,
} |
local class = require('middleclass')
--[[
This component provider always returns the same instance of the component. The instance
is passed to the provider at initialisation.
]]
local ComponentInstanceProvider = class('ComponentInstanceProvider')
--[[
Constructor
@param instance The instance to return whenever a component is requested.
]]
function ComponentInstanceProvider:initialize(instance)
self.instance = instance
end
--[[
Used to request a component from this provider
@return The instance
]]
function ComponentInstanceProvider:getComponent()
return self.instance
end
--[[
Used to compare this provider with others. Any provider that returns the same component
instance will be regarded as equivalent.
@return The instance
]]
function ComponentInstanceProvider:identifier()
return self.instance
end
return ComponentInstanceProvider
|
--Torch lib for mpi commnication
local ffi = require("ffi")
ffi.load("libmpi",true)
require 'mpiT'
mpiT.Init()
print('init')
_rank = torch.IntStorage(1)
mpiT.Comm_rank(mpiT.COMM_WORLD,_rank)
rank = _rank[1]
_size = torch.IntStorage(1)
mpiT.Comm_size(mpiT.COMM_WORLD,_size)
size = _size[1]
assert(size>1)
print('size')
_sdata = torch.FloatTensor(1):storage()
_sdata:fill(rank)
_rdata = torch.FloatTensor(1):storage()
_rdata:fill(rank)
src = (rank-1)%size
dest = (rank+1)%size
tag = 0
status = mpiT.Status(1)
print('[' .. rank .. '/' .. size .. ']' .. 's=' .. _sdata[1] .. 'r=' .. _rdata[1] )
if (rank == 0) then
mpiT.Send(_sdata,1,mpiT.FLOAT,dest,tag,mpiT.COMM_WORLD)
mpiT.Recv(_rdata,1,mpiT.FLOAT,src,tag,mpiT.COMM_WORLD,status)
else
mpiT.Recv(_rdata,1,mpiT.FLOAT,src,tag,mpiT.COMM_WORLD,status)
mpiT.Send(_sdata,1,mpiT.FLOAT,dest,tag,mpiT.COMM_WORLD)
end
print('[' .. rank .. '/' .. size .. ']' .. 's=' .. _sdata[1] .. 'r=' .. _rdata[1] )
mpiT.Finalize()
|
local menu = {}
function menu:enter(previous, game)
self.game = game
end
function menu:mousereleased(x, y, button)
if button ~= 1 then return end
for option, menuButton in pairs(self.game.ui.buttons) do
if menuButton:isClicked(x, y) then
local ratios = {
easy = 0.11,
medium = 0.17,
hard = 0.23
}
local board_size = self.game.board.width * self.game.board.height
self.game.total_mines = math.ceil(ratios[option] * board_size)
self.game.difficulty = option
self.game.ui.buttons.easy = nil
self.game.ui.buttons.hard = nil
Gamestate.switch(states.pregame, self.game)
end
end
end
return menu
|
--[[
© 2018 Thriving Ventures AB do not share, re-distribute or modify
without permission of its author ([email protected]).
]]
--
-- Common Prop Protection Interface Support
-- http://ulyssesmod.net/archive/CPPI_v1-1.pdf
--
local randomNumber = math.Round(math.random() * 50000)
CPPI = CPPI or {}
CPPI.CPPI_DEFER = randomNumber
CPPI.CPPI_NOTIMPLEMENTED = randomNumber + 1
--
--
--
function CPPI:GetName()
return "ServerGuard"
end
--
--
--
function CPPI:GetVersion()
return "1.1"
end
--
--
--
function CPPI:GetInterfaceVersion()
return 1.1
end
--
--
--
function CPPI:GetNameFromUID(uniqueID)
local target = util.FindPlayer(tostring(uniqueID))
if (IsValid(target)) then return target:Nick() end
end
local meta = FindMetaTable("Player")
--
--
--
function meta:CPPIGetFriends()
local serverguard = SERVER and self.serverguard or CLIENT and g_serverGuard
return serverguard and serverguard.prop_protection.friends
end
local meta = FindMetaTable("Entity")
--
--
--
function meta:CPPIGetOwner()
if (self.serverguard) then
if (not IsValid(self.serverguard.owner) and self.serverguard.owner ~= game.GetWorld()) then
for k, v in ipairs(player.GetAll()) do
if (v:SteamID() == self.serverguard.steamID) then
self.serverguard.owner = v
end
end
end
if (self.serverguard.owner) then
if (IsValid(self.serverguard.owner) or self.serverguard.owner == game.GetWorld()) then return self.serverguard.owner, self.serverguard.uniqueID end
end
else
if (self.GetPlayer) then
local pPlayer = self:GetPlayer()
if (IsValid(pPlayer)) then
if (SERVER) then
self:CPPISetOwner(pPlayer)
end
return pPlayer, pPlayer:UniqueID()
end
end
end
return CPPI.CPPI_DEFER, CPPI.CPPI_DEFER
end
if (SERVER) then
local plugin = plugin
--
--
--
function meta:CPPISetOwner(pPlayer)
self.serverguard = self.serverguard or {}
local name
local steamID
local uniqueID
if (pPlayer == game.GetWorld()) then
name = "World"
steamID = "World"
uniqueID = "World"
else
name = serverguard.player:GetName(pPlayer)
steamID = pPlayer:SteamID()
uniqueID = pPlayer:UniqueID()
end
self.serverguard.owner = pPlayer
self.serverguard.name = name
self.serverguard.steamID = steamID
self.serverguard.uniqueID = uniqueID
serverguard.netstream.Start(nil, "sgPropProtectionClearEntityData", self)
hook.Call("CPPIAssignOwnership", nil, pPlayer, self, uniqueID)
end
--
--
--
function meta:CPPISetOwnerUID(uniqueID)
self.serverguard.uniqueID = uniqueID
end
--
--
--
function meta:CPPICanTool(pPlayer, toolMode)
return plugin.CanTool(pPlayer, nil, toolMode)
end
--
--
--
function meta:CPPICanPhysgun(pPlayer)
return plugin.PhysgunPickup(pPlayer, self)
end
--
--
--
function meta:CPPICanPickup(pPlayer)
return plugin.GravGunPickupAllowed(pPlayer, self)
end
end |
--shorthand
lg = love.graphics
local shaders = require("src.shaders")
local ui = nil
local detail_scale = 1
local terrain_res = 256
local terrain_size = 200
local terrain_height = 32
local chunky_pixels = 2
function send_uniform_table(shader, t)
for k, v in pairs(t) do
if shader:hasUniform(k) then
shader:send(k, v)
end
end
end
function love.resize(w, h)
cw, ch = math.floor(w / chunky_pixels), math.floor(h / chunky_pixels)
sbc = lg.newCanvas(cw, ch, {
msaa = 0,
})
sbc:setFilter("nearest", "nearest")
if not ui then
ui = require("src.ui")(w, h)
else
ui:resize(w, h)
end
end
function love.load()
first_draw = true
pixel = lg.newCanvas(1, 1)
love.resize(lg.getDimensions())
--terrain geom
local vtable = {
{"VertexPosition", "float", 2},
{"VertexTexCoord", "float", 2},
{"VertexEdgeInfo", "float", 3},
}
local verts = {}
--generate corners
for y = 0, terrain_res do
for x = 0, terrain_res do
local u = x / terrain_res
local v = y / terrain_res
table.insert(verts, {
--centered
(u - 0.5) * terrain_size,
(v - 0.5) * terrain_size,
--uvs
u, v,
--edge info
(x == 0 and -1 or x == terrain_res and 1 or 0.0),
(y == 0 and -1 or y == terrain_res and 1 or 0.0),
0,
})
end
end
--generate index map
local indices = {}
local step_y = terrain_res + 1
for y = 0, terrain_res - 1 do
for x = 0, terrain_res - 1 do
local i = x + y * step_y + 1;
local a = 0
local b = 1
local c = step_y
local d = step_y + 1
table.insert(indices, i + a)
table.insert(indices, i + b)
table.insert(indices, i + c)
table.insert(indices, i + b)
table.insert(indices, i + c)
table.insert(indices, i + d)
end
end
--upload to gpu
terrain_mesh = lg.newMesh(vtable, verts, "triangles", "static")
terrain_mesh:setVertexMap(indices)
--vegetation geom
local veg_verts = {}
local veg_indices = {}
for y = 1, terrain_res do
for x = 1, terrain_res do
local u = (x - 0.5) / terrain_res
local v = (y - 0.5) / terrain_res
local vx = (u - 0.5) * terrain_size
local vy = (v - 0.5) * terrain_size
local hs = 0.75
--centered point
table.insert(veg_verts, {
vx,
vy,
--uvs
u, v,
--edge info
0.0, 0.0, 1.0,
})
local i = #veg_verts
--corners
table.insert(veg_verts, {
vx, vy,
u, v,
--edge info
-1.0, -1.0, 0.0,
})
table.insert(veg_verts, {
vx, vy,
u, v,
--edge info
1.0, -1.0, 0.0,
})
table.insert(veg_verts, {
vx, vy,
u, v,
--edge info
1.0, 1.0, 0.0,
})
table.insert(veg_verts, {
vx, vy,
u, v,
--edge info
-1.0, 1.0, 0.0,
})
table.insert(veg_indices, i)
table.insert(veg_indices, i+1)
table.insert(veg_indices, i+2)
table.insert(veg_indices, i)
table.insert(veg_indices, i+2)
table.insert(veg_indices, i+3)
table.insert(veg_indices, i)
table.insert(veg_indices, i+3)
table.insert(veg_indices, i+4)
table.insert(veg_indices, i)
table.insert(veg_indices, i+4)
table.insert(veg_indices, i+1)
end
end
--
vegetation_mesh = lg.newMesh(vtable, veg_verts, "triangles", "static")
vegetation_mesh:setVertexMap(veg_indices)
--canvas for rendering terrain
terrain_canvas = lg.newCanvas(terrain_res, terrain_res, {format="rgba16f"})
gradient_canvas = lg.newCanvas(terrain_res, terrain_res, {format="rgba16f"})
local climates = {
"cold",
"boreal",
"swamp",
"temperate",
"autumnal",
"dry",
"desert",
}
--pick a random range within the climates
local climate_count = love.math.random(1, 3)
while #climates > climate_count do
local i = love.math.random() < 0.5 and 1 or #climates
table.remove(climates, i)
end
--randomly flip order
if love.math.random() < 0.5 then
local rclimates = {}
for i,v in ipairs(climates) do
table.insert(rclimates, 1, v)
end
climates = rclimates
end
colour_map = love.image.newImageData(16, #climates)
vegetation_map = love.image.newImageData(16, #climates)
height_map = love.image.newImageData(16, #climates)
water_map = love.image.newImageData(16, #climates)
for i,v in ipairs(climates) do
local id = love.image.newImageData(
table.concat{"assets/climates/", v, ".png"}
)
local w = id:getWidth()
for j, onto in ipairs {
colour_map,
vegetation_map,
height_map,
water_map,
} do
onto:paste(id, 0, i-1, 0, j-1, w, 1)
end
end
colour_map = lg.newImage(colour_map)
height_map = lg.newImage(height_map)
vegetation_map = lg.newImage(vegetation_map)
water_map = lg.newImage(water_map, {linear=true})
sea_colour_map = lg.newImage("assets/water/body.png")
foam_colour_map = lg.newImage("assets/water/foam.png")
foam_colour_map:setWrap("repeat")
world_shader_uniforms = {
detail_scale = detail_scale,
seed_offset = {
(love.math.random() - 0.5) * 1000,
(love.math.random() - 0.5) * 1000,
},
t = love.math.random(),
}
send_uniform_table(shaders.world, world_shader_uniforms)
gradient_shader_uniforms = {
texture_size = {terrain_res, terrain_res},
height_map = height_map,
}
send_uniform_table(shaders.gradient, gradient_shader_uniforms)
mesh_shader_uniforms = {
colour_map = colour_map,
vegetation_map = vegetation_map,
height_map = height_map,
water_map = water_map,
height_scale = terrain_height,
terrain = terrain_canvas,
terrain_grad = gradient_canvas,
terrain_res = terrain_res,
obj_euler = {0, 0.0, math.pi * 0.5},
--camera
cam_from = {
0,
-(terrain_height * 1.5), --(only one not filled in in draw)
0,
},
cam_to = {0, 0, 0},
veg_vert_start = veg_offset,
veg_height_scale = 2,
sea_colour_map = sea_colour_map,
foam_colour_map = foam_colour_map,
sea_level = 0, --set in draw
foam_t = 0,
sky_col = {
0x37 / 255,
0x7c / 255,
0xbd / 255,
1
},
}
end
local t_scale = (1 / 1000)
function render_terrain()
local skip_draw = false
if first_draw then
lg.setColor(1,1,1,1)
else
lg.setColor(1,1,1, 0.01)
skip_draw = true
end
if not skip_draw then
lg.setCanvas(terrain_canvas)
lg.setBlendMode("alpha", "alphamultiply")
lg.setShader(shaders.world)
lg.draw(
pixel,
0, 0,
0,
terrain_res, terrain_res
)
lg.setCanvas(gradient_canvas)
lg.setShader(shaders.gradient)
lg.draw(terrain_canvas)
end
lg.setColor(1,1,1,1)
end
local cam_t = love.math.random() * math.pi * 2
local cam_t_scale = (1 / 20) * math.pi * 2
function love.draw()
--update shaders
send_uniform_table(shaders.world, world_shader_uniforms)
local g_t = love.timer.getTime();
local msu = mesh_shader_uniforms
local c_o = msu.cam_from
local l = (0.35 + math.sin(cam_t * 0.3) * 0.1) * terrain_size
c_o[1] = math.sin(cam_t) * l
c_o[3] = math.cos(cam_t) * l
msu.sea_level = terrain_height * (6 / 255) * (1.0 + 0.2 * math.sin(g_t / 10.0))
msu.foam_t = (g_t / 2.0) % 1
for i,v in ipairs{
shaders.terrain_mesh,
shaders.vegetation_mesh,
shaders.sea_mesh,
} do
send_uniform_table(v, msu)
end
--render to canvas
render_terrain()
--render mesh
lg.setBlendMode("alpha", "alphamultiply")
lg.setCanvas({
sbc,
depth = true,
})
lg.setDepthMode("greater", true)
--clear to error col
do
local r = 0x80 / 255
local g = 0xb9 / 255
local b = 0xdf / 255
lg.clear(
r, g, b, 1,
0, 0
)
end
--render island
lg.setShader(shaders.terrain_mesh)
lg.draw(
terrain_mesh,
cw * 0.5, ch * 0.5
)
--render vegetation
lg.setShader(shaders.vegetation_mesh)
lg.draw(
vegetation_mesh,
cw * 0.5, ch * 0.5
)
--render water
lg.setShader(shaders.sea_mesh)
lg.draw(
terrain_mesh,
cw * 0.5, ch * 0.5
)
--upscale canvas to screen
lg.setBlendMode("alpha", "premultiplied")
lg.setDepthMode()
lg.setShader()
lg.setCanvas()
lg.draw(
sbc,
lg.getWidth() * 0.5, lg.getHeight() * 0.5,
0,
chunky_pixels, chunky_pixels,
cw * 0.5, ch * 0.5
)
--draw ui
lg.setBlendMode("alpha", "alphamultiply")
if not hide_ui then
ui:draw()
end
if love.keyboard.isDown("`") then
--debug
lg.draw(terrain_canvas, 0, 0)
lg.draw(gradient_canvas, terrain_canvas:getWidth(), 0)
lg.print(string.format(
"fps: %d - %04.3f",
love.timer.getFPS(),
tostring(last_dt)
))
end
first_draw = false
end
function love.update(dt)
world_shader_uniforms.t = world_shader_uniforms.t + dt * t_scale
cam_t = cam_t + dt * cam_t_scale
ui:update(dt)
last_dt = dt
end
function love.keypressed(k)
if k == "escape" and not closed_welcome then
ui:close_welcome()
return
end
local ctrl = love.keyboard.isDown("lctrl")
if k == "r" then
if ctrl then
love.event.quit("restart")
else
love.load()
end
elseif k == "q" and ctrl or k == "escape" then
love.event.quit()
end
end
--mouse handling
--(single button for now)
local is_clicked = false
function love.mousemoved( x, y, dx, dy, istouch )
ui:pointer(is_clicked and "drag" or "move", x, y)
end
function love.mousepressed( x, y, button, istouch, presses )
if button == 1 then
if hide_ui then
hide_ui = false
else
ui:pointer("click", x, y)
is_clicked = true
end
end
end
function love.mousereleased( x, y, button, istouch, presses )
if button == 1 then
ui:pointer("release", x, y)
is_clicked = false
end
end
|
--====================================================================--
-- Config.lua
--
-- references
-- http://developer.coronalabs.com/content/configuring-projects
-- http://www.coronalabs.com/blog/2012/12/04/the-ultimate-config-lua-file/
--====================================================================--
application =
{
content =
{
width = 320,
height = 568,
scale = "letterBox",
imageSuffix =
{
["@2x"] = 1.5,
},
fps = 60
},
notification =
{
iphone = {
types = {
"badge", "sound", "alert"
}
},
google =
{
projectNumber = "565910089041",
},
},
showRuntimeErrors = false
}
|
-- -*- Mode: Lua; -*-
--
-- loadpkg.lua load an RPL module, which instantiates a run-time package
--
-- © Copyright IBM Corporation 2017, 2018.
-- LICENSE: MIT License (https://opensource.org/licenses/mit-license.html)
-- AUTHOR: Jamie A. Jennings
local ast = require "ast"
local environment = require "environment"
local builtins = require "builtins"
local common = require "common"
local violation = require "violation"
local loadpkg = {}
-- 'validate_block' enforces the structure of an rpl module:
-- rpl_module = language_decl? package_decl? import_decl* statement* ignore
--
-- We could parse a module using that pattern, but we can give more detailed error messages this way.
-- Returns: success, table of messages
-- Side effects: fills in block.block_pdecl, block.block_ideclists; removes ALL decls from block.stmts
function loadpkg.validate_block(a, messages)
assert(ast.block.is(a))
local stmts = a.stmts
if not stmts[1] then
table.insert(messages, violation.warning.new{who='loader', message="Empty input (no statements)", ast=a})
return true
elseif ast.pdecl.is(stmts[1]) then
a.block_pdecl = table.remove(stmts, 1)
common.note("load: in package " .. a.block_pdecl.name)
end
if not stmts[1] then
table.insert(messages, violation.warning.new{who='loader',
message="Empty module (nothing after package declaration)",
ast=a})
return true
end
a.block_ideclists = {}
while stmts[1] and ast.ideclist.is(stmts[1]) do
table.insert(a.block_ideclists, table.remove(stmts, 1))
end
if not stmts[1] then
-- table.insert(messages, violation.info.new{who='loader',
-- message="Module consists only of declarations (no bindings)",
-- ast=a})
return true
end
for _, s in ipairs(stmts) do
if not ast.binding.is(s) then
local errmsg = "Declarations must appear before assignments"
if ast.ldecl.is(s) then
errmsg = "RPL language version declaration must be the first RPL statement"
elseif ast.pdecl.is(s) then
if a.block_pdecl then
errmsg = "Duplicate package declaration"
else
errmsg = "Package decl must precede imports and bindings"
end
end
table.insert(messages, violation.compile.new{who='loader',
message=errmsg,
ast=s})
return false
end
end -- for
return true
end
local function compile(compiler, a, env, source_record, messages)
-- The 'a' parameter is the AST to compile, which is a block that has been parsed, but not
-- expanded yet.
-- All dependencies of the block have been loaded.
-- Bindings for all dependencies have been created already.
-- The 'request' parameter is nil for direct user input, or a loadrequest that indicates why
-- we are compiling the code that produced 'a'.
if not compiler.expand_block(a, env, messages) then return false; end
-- One of the expansion steps is to fill in the pdecl and ideclist slots in the block AST, so
-- we can now use those fields.
local pkgname = a.block_pdecl and a.block_pdecl.name
local request = source_record.origin
if request and request.importpath and (not pkgname) then
local msg = request.importpath .. " is not a module (no package declaration found)"
table.insert(messages, violation.info.new{who='loader', message=msg, ast=a})
end
-- If we are compiling 'a' due to a request and the request has an importpath and a prefix,
-- then those came from an import declaration. The packagename in the request object was
-- not known until now (because we just parsed and expanded the module source).
if request and request.importpath then request.packagename = pkgname; end
if not compiler.compile_block(a, env, request, messages) then
common.note(string.format("load: failed to compile %s", pkgname or "<top level>"))
return false
end
common.note(string.format("load: compiled %s", pkgname or "<top level>"))
return true
end
local load_dependencies;
local function parse_block(compiler, source_record, messages)
local a = compiler.parse_block(source_record, messages)
if not a then return false; end -- errors will be in messages table
if not loadpkg.validate_block(a, messages) then return false; end
-- Via side effects, a.block_pdecl and a.block_ideclists are now filled in.
return a
end
-- 'loadpkg.source' loads rpl source code. That code, source, may or may not define a module. If
-- source defines a module, i.e. it has a package declaration, then:
-- (1) the package will be instantiated (as an environment), and
-- (2) the info needed to create a binding for that package will be returned.
function loadpkg.source(compiler, pkgtable, top_level_env, searchpath, source, origin, messages)
assert(type(compiler)=="table")
assert(type(pkgtable)=="table")
assert(environment.is(top_level_env))
assert(type(searchpath)=="string")
assert(type(source)=="string")
assert(origin==nil or common.loadrequest.is(origin))
assert(type(messages)=="table")
-- loadpkg.source() is used to:
-- (1) load user input, in which case the origin argument is nil, or
-- (2) load code from a file named by the user, in which case:
-- (a) origin.importpath == nil, and
-- (b) origin.filename ~= nil
if origin then assert(origin.importpath==nil); assert(origin.filename); end
local source_record = common.source.new{text=source,
origin=origin,
}
local a = parse_block(compiler, source_record, messages)
if not a then return false; end -- errors will be in messages table
local env
-- If this block of source has a package declaration, it gets its own environment
if a.block_pdecl then
assert(a.block_pdecl.name)
env = environment.new(environment.make_standard_prelude())
env.prefix = a.block_pdecl.name
env.origin = origin
else
env = environment.extend(top_level_env)
end
if not load_dependencies(compiler, pkgtable, searchpath, source_record, a, env, {}, messages) then
return false
end
if not compile(compiler, a, env, source_record, messages) then
return false
end
if a.block_pdecl then
-- The code we compiled defined a module, which we have instantiated as a package (in env).
-- But there is no importpath, so we use the packagename as the loadpath to create an entry
-- in the package table.
if common.pkgtableref(pkgtable, a.block_pdecl.name, nil) then
-- We are overwriting an entry in the package table.
common.note(string.format("load: replacing package %s", a.block_pdecl.name))
common.pkgtableset(pkgtable, a.block_pdecl.name, nil, a.block_pdecl.name, env)
else
common.pkgtableadd(pkgtable, a.block_pdecl.name, nil, a.block_pdecl.name, env)
end
return true, a.block_pdecl.name, env
else
-- The caller must replace their top_level_env with the returned env in order to see the new
-- bindings.
return true, nil, env
end
end
local function import_from_source(compiler, pkgtable, searchpath, source_record, loadinglist, messages)
local src = source_record.text
local origin = source_record.origin
local a = parse_block(compiler, source_record, messages)
if not a then return false; end -- errors will be in messages table
if not a.block_pdecl then
local msg = "imported code is not a module"
table.insert(messages, violation.compile.new{who='loader', message=msg, ast=source_record})
return false
end
origin.packagename = a.block_pdecl.name
local env = environment.new(environment.make_standard_prelude())
env.origin = origin
if not load_dependencies(compiler, pkgtable, searchpath, source_record, a, env, loadinglist, messages) then
return false
end
if not compile(compiler, a, env, source_record, messages) then
return false
end
common.pkgtableadd(pkgtable, origin.importpath, origin.prefix, origin.packagename, env)
return true, origin.packagename, env
end
local function find_module_source(compiler, pkgtable, searchpath, source_record, loadinglist, messages)
local fullpath, src, msg = common.get_file(source_record.origin.importpath, searchpath)
if src then
-- Check to see if fullpath is in the list of "things that are being loaded now",
-- and if so, signal an error that there are circular dependencies
if not loadinglist[fullpath] then
loadinglist[fullpath] = true
return src, fullpath
else
msg = "Detected circular list of module dependencies"
--for k,_ in pairs(loadinglist) do msg = msg .. "\n" .. k; end
end
end
table.insert(messages, violation.compile.new{who='loader', message=msg, ast=source_record})
return false
end
local function create_package_bindings(prefix, pkgenv, target_env)
assert(type(prefix)=="string")
assert(environment.is(pkgenv))
assert(environment.is(target_env))
if prefix=="." then
-- import all exported bindings into the target environment
for name, obj in pkgenv:bindings() do
assert(type(obj)=="table", name .. " bound to " .. tostring(obj))
if obj.exported then -- quack
if target_env:lookup(name) then
common.note("load: rebinding ", name)
else
common.note("load: binding ", name)
end
target_env:bind(name, obj)
end
end -- for each binding in the package
else
-- import the entire package under the desired prefix
if target_env:lookup(prefix) then
common.note("load: rebinding ", prefix)
end
target_env:bind(prefix, pkgenv)
common.note("load: binding package prefix " .. prefix)
end
end
local function import_builtin(importpath, pkgtable, source_record, messages)
local origin = assert(source_record.origin)
local pkgname, env = environment.get_builtin_package(importpath)
if pkgname then
assert(environment.is(env))
common.pkgtableadd(pkgtable, importpath, origin.prefix, pkgname, env)
return true, pkgname, env
end
local msg = "built-in package not found: " .. importpath
table.insert(messages, violation.compile.new{who='loader', message=msg, ast=source_record})
return false
end
local function import_one_force(compiler, pkgtable, searchpath, source_record, loadinglist, messages)
local origin = assert(source_record.origin)
common.note("load: looking for ", origin.importpath)
-- FUTURE: Next, look for a compiled version of the file to load
-- Finally, look for a source file to compile and load
local src, fullpath = find_module_source(compiler, pkgtable, searchpath, source_record, loadinglist, messages)
if not src then return false; end -- message already in 'messages'
if builtins.is_builtin_package(origin.importpath, fullpath) then
common.note("load: loading ", origin.importpath, ", a built-in package")
return import_builtin(origin.importpath, pkgtable, source_record, messages)
end
common.note("load: loading ", origin.importpath, " from ", fullpath)
local sref = common.source.new{text=src,
origin=common.loadrequest.new{importpath=origin.importpath,
prefix=origin.prefix,
packagename=nil,
filename=fullpath},
parent=source_record}
return import_from_source(compiler, pkgtable, searchpath, sref, loadinglist, messages)
end
local function import_one(compiler, pkgtable, searchpath, source_record, loadinglist, messages)
local origin = assert(source_record.origin)
-- First, look in the pkgtable to see if this pkg has been loaded already
local pkgname, pkgenv = common.pkgtableref(pkgtable, origin.importpath, origin.prefix)
if pkgname then
common.note("load: ", origin.importpath, " already loaded")
return true, pkgname, pkgenv
end
return import_one_force(compiler, pkgtable, searchpath, source_record, loadinglist, messages)
end
local function import(importer, compiler, pkgtable, searchpath, packagename, as_name, env, messages)
assert(type(compiler)=="table")
assert(type(pkgtable)=="table")
assert(type(searchpath)=="string")
assert(type(packagename)=="string")
assert(as_name==nil or type(as_name)=="string")
assert(environment.is(env))
assert(type(messages)=="table")
local origin = common.loadrequest.new{importpath=packagename, prefix=as_name}
local source_record = common.source.new{origin=origin}
local ok, pkgname, pkgenv = importer(compiler, pkgtable, searchpath, source_record, {}, messages)
if not ok then return false; end -- message already in 'messages'
create_package_bindings(origin.prefix or pkgname, pkgenv, env)
return true, pkgname
end
-- Do the same as en:load('import foo as bar')
function loadpkg.import(compiler, pkgtable, searchpath, packagename, as_name, env, messages)
return import(import_one, compiler, pkgtable, searchpath, packagename, as_name, env, messages)
end
-- Force a reload of the package if it has already been loaded.
function loadpkg.import_force(compiler, pkgtable, searchpath, packagename, as_name, env, messages)
return import(import_one_force, compiler, pkgtable, searchpath, packagename, as_name, env, messages)
end
-- load_dependencies recursively loads each import in ideclist.
-- Returns success; side-effects the messages argument.
function load_dependencies(compiler, pkgtable, searchpath, source_record, a, target_env, loadinglist, messages)
assert(type(compiler)=="table")
assert(type(pkgtable)=="table")
assert(type(searchpath)=="string")
assert(common.source.is(source_record))
assert(ast.block.is(a))
assert(environment.is(target_env))
assert(type(messages)=="table")
assert(a.block_ideclists==nil or (type(a.block_ideclists)=="table"),
"a.block_ideclists is: "..tostring(a.block_ideclists))
for _, ideclist in ipairs(a.block_ideclists or {}) do
assert(ast.ideclist.is(ideclist))
local idecls = ideclist.idecls
for _, decl in ipairs(idecls) do
assert(decl.sourceref)
local sref = common.source.new{text=source_record.text,
origin=common.loadrequest.new{importpath=decl.importpath,
prefix=decl.prefix},
parent=common.source.new{text=decl.sourceref.text,
s=decl.sourceref.s,
e=decl.sourceref.e,
origin=source_record.origin,
parent=source_record}}
local ok, pkgname, pkgenv = import_one(compiler, pkgtable, searchpath, sref, loadinglist, messages)
if not ok then
common.note("FAILED to import from path " .. tostring(decl.importpath))
local err = violation.compile.new{who="loader",
message="failed to load " .. tostring(decl.importpath),
ast=source_record}
table.insert(messages, err)
return false
end
end
-- With all imports loaded and registered in pkgtable, we can now create bindings in target_env
-- to make the exported bindings accessible.
for _, decl in ipairs(idecls) do
local pkgname, pkgenv = common.pkgtableref(pkgtable, decl.importpath, decl.prefix)
local prefix = decl.prefix or pkgname
assert(type(prefix)=="string")
create_package_bindings(prefix, pkgenv, target_env)
end
end -- for each ideclist in a.block_ideclists
return true
end
return loadpkg
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('XTemplate', {
group = "InGame",
id = "GamepadCheatsDlg",
PlaceObj('XTemplateTemplate', {
'__template', "OverlayDlg",
}, {
PlaceObj('XTemplateWindow', {
'__class', "XLabel",
'Dock', "top",
'HAlign', "right",
'TextStyle', "OverlayTitle",
'Translate', true,
'Text', T(554083515055, --[[XTemplate GamepadCheatsDlg Text]] "CHEATS"),
}),
PlaceObj('XTemplateWindow', {
'__class', "XFrame",
'Margins', box(-80, 6, -160, -100),
'Dock', "top",
'VAlign', "top",
'Image', "UI/Common/bm_pad_small.tga",
'FrameBox', box(170, 0, 170, 0),
'SqueezeY', false,
}),
PlaceObj('XTemplateAction', {
'ActionId', "close",
'ActionName', T(4523, --[[XTemplate GamepadCheatsDlg ActionName]] "CLOSE"),
'ActionToolbar', "ActionBar",
'ActionShortcut', "Escape",
'ActionGamepad', "ButtonB",
'OnActionEffect', "close",
}),
PlaceObj('XTemplateWindow', {
'__context', function (parent, context) return Music end,
'__class', "XContentTemplateList",
'Id', "idList",
'BorderWidth', 0,
'LayoutVSpacing', 6,
'Clip', false,
'Background', RGBA(0, 0, 0, 0),
'FocusedBackground', RGBA(0, 0, 0, 0),
'MouseScroll', true,
'OnContextUpdate', function (self, context, ...)
XContentTemplate.OnContextUpdate(self, context, ...)
if self.focused_item then
self:DeleteThread("select")
self:CreateThread("select", function()
self:SetSelection(self.focused_item)
end)
end
end,
}, {
PlaceObj('XTemplateForEach', {
'comment', "gamepad cheats",
'array', function (parent, context) return GamepadCheatsList end,
'__context', function (parent, context, item, i, n) return item end,
}, {
PlaceObj('XTemplateTemplate', {
'__template', "MenuEntrySmall",
'HAlign', "right",
'OnPress', function (self, gamepad)
self.context.func()
end,
'Text', T(867595017482, --[[XTemplate GamepadCheatsDlg Text]] "<display_name>"),
}),
}),
}),
}),
})
|
--logfile=io.open("C:\\SBERBANK\\QUIK_SMS\\LuaIndicators\\qlua_log.txt", "w")
min_price_step = 0
sec_code = ""
timescale = ""
local w32 = require("w32")
Settings=
{
Name = "*StepNRTR",
Length = 5,
value_type = "ATR",
Kv = 1.5,
StepSize = 0,
Percentage = 0,
Switch = 1, --1 - HighLow, 2 - CloseClose
ShowLine = 1,
PlaySound = 1,
line =
{
{
Name = "NRTR_buy",
Color = RGB(40,240,250),
Type = TYPE_POINT,
Width = 4
},
{
Name = "NRTR_sell",
Color = RGB(255,0,255),
Type = TYPE_POINT,
Width = 4
},
{
Name = "NRTR",
Color = RGB(0, 64, 0),
Type = TYPE_LINE, --TYPE_DASHDOT,
Width = 2
}
}
}
function Init()
myNRTR = cached_NRTR()
return #Settings.line
end
function OnCalculate(index)
if index == 1 then
DSInfo = getDataSourceInfo()
sec_code = DSInfo.sec_code
timescale = DSInfo.interval
min_price_step = getParamEx(DSInfo.class_code, DSInfo.sec_code, "SEC_PRICE_STEP").param_value
--WriteLog ("min_price_step "..tostring(min_price_step))
end
return myNRTR(index, Settings)
end
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
function FindExistCandle(I)
local out = I
while not CandleExist(out) and out > 0 do
out = out -1
end
return out
end
function dValue(i,param)
local v = param or "C"
if not CandleExist(i) then
return nil
end
if v == "O" then
return O(i)
elseif v == "H" then
return H(i)
elseif v == "L" then
return L(i)
elseif v == "C" then
return C(i)
elseif v == "V" then
return V(i)
elseif v == "M" then
return (H(i) + L(i))/2
elseif v == "T" then
return (H(i) + L(i)+C(i))/3
elseif v == "W" then
return (H(i) + L(i)+2*C(i))/4
elseif v == "ATR" then
local previous = i-1
if not CandleExist(previous) then
previous = FindExistCandle(previous)
end
return math.max(math.abs(H(i) - L(i)), math.abs(H(i) - C(previous)), math.abs(C(previous) - L(i)))
else
return C(i)
end
end
function cached_NRTR()
local cache_NRTR={}
local smax1={}
local smin1={}
local trend={}
local isMessage={}
return function(ind, Fsettings, ds)
local Fsettings=(Fsettings or {})
local p = 0
local ATR = 0
local index = ind
local Length = Fsettings.Length or 64
local Kv = Fsettings.Kv or 1
local v_type = Fsettings.value_type or "ATR"
local StepSize = Fsettings.StepSize or 0
local Percentage = Fsettings.Percentage or 0
local Switch = Fsettings.Switch or 1
local ShowLine = Fsettings.ShowLine or 0
local PlaySound = Fsettings.PlaySound or 0
local ratio=Percentage/100.0*min_price_step
local out1 = nil
local out2 = nil
local out3 = nil
SetValue(index-11, 3, nil)
SetValue(index-1, 3, nil)
if index == 1 then
cache_NRTR = {}
cache_NRTR[index] = 0
smax1 = {}
smin1 = {}
trend = {}
smax1[index] = L(index)
smin1[index] = H(index)
trend[index] = 1
isMessage = {}
return nil
end
cache_NRTR[index] = cache_NRTR[index-1]
smax1[index] = smax1[index-1]
smin1[index] = smin1[index-1]
trend[index] = trend[index-1]
if not CandleExist(index) then
return nil
end
if index <= (Length + 3) then
return nil
end
--WriteLog ("---------------------------------")
--WriteLog ("index "..tostring(index))
--WriteLog ("C(index) "..tostring(C(index)))
--WriteLog ("H(index) "..tostring(H(index)))
--WriteLog ("L(index) "..tostring(L(index)))
local Step=StepSizeCalc(Length,Kv,StepSize,index)
if Step == 0 then Step = 1 end
local SizeP=Step*min_price_step
local Size2P=2*SizeP
--WriteLog ("Step "..tostring(Step))
local result
local previous = index-1
if not CandleExist(previous) then
previous = FindExistCandle(previous)
end
if Switch == 1 then
smax0=L(previous)+Size2P
smin0=H(previous)-Size2P
else
smax0=C(previous)+Size2P
smin0=C(previous)-Size2P
end
--WriteLog ("smax0 "..tostring(smax0))
--WriteLog ("smin0 "..tostring(smin0))
--WriteLog ("smax1[index] "..tostring(smax1[index]))
--WriteLog ("smin1[index] "..tostring(smin1[index]))
if C(index)>smax1[index] then trend[index] = 1 end
if C(index)<smin1[index] then trend[index]= -1 end
--WriteLog ("trend "..tostring(trend[index]))
if trend[index]>0 then
if smin0<smin1[index] then smin0=smin1[index] end
result=smin0+SizeP
else
if smax0>smax1[index] then smax0=smax1[index] end
result=smax0-SizeP
end
--WriteLog ("result "..tostring(result))
smax1[index] = smax0
smin1[index] = smin0
--WriteLog ("smax0 "..tostring(smax0))
--WriteLog ("smin0 "..tostring(smin0))
--WriteLog ("smax1[index] "..tostring(smax1[index]))
--WriteLog ("smin1[index] "..tostring(smin1[index]))
if trend[index]>0 then
cache_NRTR[index]=(result+ratio/Step)-Step*min_price_step
end
if trend[index]<0 then
cache_NRTR[index]=(result+ratio/Step)+Step*min_price_step
end
if trend[index]>0 and trend[index-1]<0 then
out1 = O(index)
out2 = nil
end
if trend[index]<0 and trend[index-1]>0 then
out1 = nil
out2 = O(index)
end
--сообщения
if index == Size() and trend[index-1]>0 and trend[index-2]<0 and isMessage[index] == nil then
message("Buy "..tostring(sec_code).." timescale "..tostring(timescale))
if PlaySound == 1 then
PaySoundFile("c:\\windows\\media\\Alarm03.wav")
end
isMessage[index] = 1
end
if index == Size() and trend[index-1]<0 and trend[index-2]>0 and isMessage[index] == nil then
message("Sell "..tostring(sec_code).." timescale "..tostring(timescale))
if PlaySound == 1 then
PaySoundFile("c:\\windows\\media\\Alarm03.wav")
end
isMessage[index] = 1
end
if ShowLine == 1 then
SetValue(index-10, 3, cache_NRTR[index])
out3 = cache_NRTR[index]
end
return out1, out2, out3
end
end
function WriteLog(text)
logfile:write(tostring(os.date("%c",os.time())).." "..text.."\n");
logfile:flush();
LASTLOGSTRING = text;
end;
function PaySoundFile(file_name)
w32.mciSendString("CLOSE QUIK_MP3")
w32.mciSendString("OPEN \"" .. file_name .. "\" TYPE MpegVideo ALIAS QUIK_MP3")
w32.mciSendString("PLAY QUIK_MP3")
end
function StepSizeCalc(Len, Km, Size, index)
local result
if Size == 0 then
local Range=0.0
local ATRmax=-1000000
local ATRmin=1000000
for iii=1, Len do
if CandleExist(index-iii) then
Range=H(index-iii)-L(index-iii)
if Range>ATRmax then ATRmax=Range end
if Range<ATRmin then ATRmin=Range end
end
end
result = round(0.5*Km*(ATRmax+ATRmin)/min_price_step, nil)
else result=Km*Size
end
return result
end
function round(num, idp)
if idp and num then
local mult = 10^(idp or 0)
if num >= 0 then return math.floor(num * mult + 0.5) / mult
else return math.ceil(num * mult - 0.5) / mult end
else return num end
end
|
local Players = game:GetService("Players")
local AgeRestrictionWhitelist = require(script.Parent.AgeRestrictionWhitelist)
local AgeRestrictor = require(script.AgeRestrictor)
local GAME_MINUMUM_AGE_REQUIREMENT = 5000 -- in days
local EVALUATION_RESULT_TYPES = AgeRestrictor.enums.evaluationResultTypes
local GameAgeRestrictor = AgeRestrictor.new(GAME_MINUMUM_AGE_REQUIREMENT, AgeRestrictionWhitelist)
local function setFFlags()
AgeRestrictor.fflags.verifyUserIDsCorrespondToAnAccount = true
AgeRestrictor.fflags.verifyWhitelistedUserIDsHaveUpdatedName = false
end
local function connectPlayer(player)
print("New user connected to server: ".. player.Name)
local resultType, reasonForExemption = GameAgeRestrictor:evaluate(player)
if resultType == EVALUATION_RESULT_TYPES.passed then
print("Age Requirement Met: User meets the minimum age requirement for this experience.")
elseif resultType == EVALUATION_RESULT_TYPES.exempted then
warn("Age Requirement Exemption Notice: User `"..player.Name.."` has been exempt from the games age requirements.")
warn("Reason: "..reasonForExemption)
elseif resultType == EVALUATION_RESULT_TYPES.failed then
player:Kick("this experience is meant for accounts created over "..GAME_MINUMUM_AGE_REQUIREMENT.." days ago.")
warn("Age Requirement Failed: User has been removed from the server.")
end
end
local function connectPlayersThatLoadedBeforeSystemsReady()
for _, player in ipairs(Players:GetPlayers()) do
task.spawn(connectPlayer, player)
end
end
local function connectMainSignals()
Players.PlayerAdded:Connect(connectPlayer)
end
do
setFFlags()
connectPlayersThatLoadedBeforeSystemsReady()
connectMainSignals()
end
|
--Screens
require 'ui.ui_button'
require 'screen.mainmenu_screen'
require 'screen.gameplay_screen'
require 'screen.gameover_screen'
require 'button'
DEBUG_MODE = false
--Game state
-- 0 - mainmenu
-- 1 - play
-- 2 - lose
STATE = 0
--Buttons color (r, g, b, a)
COLOR_RED = {0.8, 0, 0, 1}
COLOR_YELLOW = {0.8, 0.8, 0, 1}
COLOR_GREEN = {0, 0.8, 0, 1}
COLOR_BLUE = {0, 0, 0.8, 1}
COLOR_WHITE = {1, 1, 1, 1}
COLOR_BLACK = {0, 0, 0, 1}
SCREEN_SIZE = {WIDTH = love.graphics.getWidth(), HEIGHT = love.graphics.getHeight(), WORLD_UNITS = 60}
--Game sounds
sounds = {}
table.insert(sounds, love.audio.newSource('sounds/1.wav', 'static'))
table.insert(sounds, love.audio.newSource('sounds/2.wav', 'static'))
table.insert(sounds, love.audio.newSource('sounds/3.wav', 'static'))
table.insert(sounds, love.audio.newSource('sounds/4.wav', 'static'))
Timer = require "library.hump.timer"
Utils = require "util"
function love.load()
oldMouseDown = nil
math.randomseed(os.time())
mainmenu = MainMenuScreen:new()
game = GamePlayScreen:new()
gameover = nil
end
function love.update(dt)
Timer.update(dt)
if(STATE == 0) then
mainmenu:update(dt)
end
if(STATE == 1) then
game:update(dt)
end
if(STATE == 2) then
gameover:update(dt)
end
oldMouseDown = love.mouse.isDown(1)
end
function love.draw()
if(STATE == 0) then
mainmenu:draw()
end
if(STATE == 1) then
game:draw()
end
if(STATE == 2) then
gameover:draw()
end
end
function love.keypressed(key, scancode, isrepeat)
if key == 'q' then
love.event.quit(0)
end
if key == 'r' then
restart()
end
if key == 's' then
if(STATE == 1) then
game.playerActions = {}
game.localstate=2
game.runned = false
end
end
end
function restart()
if(STATE == 2) then
game = GamePlayScreen:new()
gameover = nil
STATE = 1
end
end
|
-- This file is generated by proto-gen-lua. DO NOT EDIT.
-- The protoc version is 'v3.19.2'
-- The proto-gen-lua version is 'Develop'
return {
name = [[nopackage/nopackage.proto]],
message_type = {
{
name = [[Message]],
field = {
{
name = [[string_field]],
number = 1,
label = [[LABEL_OPTIONAL]],
type = [[TYPE_STRING]],
json_name = [[stringField]],
},
{
name = [[enum_field]],
number = 2,
label = [[LABEL_OPTIONAL]],
type = [[TYPE_ENUM]],
type_name = [[.Enum]],
default_value = [[ZERO]],
json_name = [[enumField]],
},
},
},
},
enum_type = {
{
name = [[Enum]],
value = {
{
name = [[ZERO]],
number = 0,
},
},
},
},
options = {
go_package = [[google.golang.org/protobuf/cmd/protoc-gen-go/testdata/nopackage]],
},
} |
local AdjacencyGraph = {
nodes = nil,
edges = nil,
}
function AdjacencyGraph:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
self.nodes = {}
self.edges = {}
return o
end
function AdjacencyGraph:addNode(val)
self.nodes[#self.nodes+1] = val
return #self.nodes
end
function AdjacencyGraph:addEdge(u, v)
self.edges[#self.edges+1] = { u = u, v = v }
...
end
...
|
local visitor = require("kotaro.visitor")
local print_visitor = require("kotaro.visitor.print_visitor")
local utils = require("kotaro.utils")
local tree_utils = {}
function tree_utils.dump(node, stream)
visitor.visit(print_visitor:new(stream), node)
end
local leaf_mutator_visitor = {}
function leaf_mutator_visitor:new(cb, ...)
return setmetatable({ cb = cb, args = {...} }, { __index = leaf_mutator_visitor })
end
function leaf_mutator_visitor:visit_leaf(node)
self.cb(node, unpack(self.args))
end
function leaf_mutator_visitor:visit_node(node, visit)
visit(self, node, visit)
end
function tree_utils.each_leaf(node, cb, ...)
visitor.visit(leaf_mutator_visitor:new(cb, ...), node)
end
local OPEN_SYMBOLS = utils.set {
"(", "[", "{", "do", "repeat", "then", "else"
}
local CLOSE_SYMBOLS = utils.set {
")", "]", "}", "end", "until"
}
function tree_utils.opens_scope(token)
return OPEN_SYMBOLS[token.value]
end
function tree_utils.closes_scope(token)
return CLOSE_SYMBOLS[token.value]
end
local BLOCKS = utils.set {
"if_block",
"do_block",
"while_block",
"for_block",
"function_declaration",
"function_expression",
"repeat_block",
}
function tree_utils.is_block(node)
return BLOCKS[node:type()]
end
return tree_utils
|
-- The Computer Language Benchmarks Game
-- http://benchmarksgame.alioth.debian.org/
-- contributed by Wim Couwenberg
--
-- requires LGMP "A GMP package for Lua 5.1"
--
-- 21 September 2008
local gmp, aux = {}, {}
require "c-gmp"(gmp, aux)
local add, mul, div = gmp.mpz_add, gmp.mpz_mul_ui, gmp.mpz_fdiv_q
local addmul, submul = gmp.mpz_addmul_ui, gmp.mpz_submul_ui
local init, get, set = gmp.mpz_init_set_d, gmp.mpz_get_d, gmp.mpz_set
--
-- Production:
--
-- [m11 m12] [m11 m12][k 4*k+2]
-- [ 0 m22] <-- [ 0 m22][0 2*k+1]
--
local function produce(m11, m12, m22, k)
local p = 2 * k + 1
mul(m12, p, m12)
addmul(m12, m11, 2 * p)
mul(m11, k, m11)
mul(m22, p, m22)
end
--
-- Extraction:
--
-- [m11 m12] [10 -10*d][m11 m12]
-- [ 0 m22] <-- [ 0 1 ][ 0 m22]
--
local function extract(m11, m12, m22, d)
submul(m12, m22, d)
mul(m11, 10, m11)
mul(m12, 10, m12)
end
--
-- Get integral part of p/q where
--
-- [p] [m11 m12][d]
-- [q] = [ 0 m22][1]
--
local function digit(m11, m12, m22, d, tmp)
set(tmp, m12)
addmul(tmp, m11, d)
div(tmp, m22, tmp)
return get(tmp)
end
-- Generate successive digits of PI.
local function pidigits(N)
local write = io.write
local m11, m12, m22, tmp = init(1), init(0), init(1), init(0)
local k, i = 1, 0
while i < N do
local d = digit(m11, m12, m22, 3, tmp)
if d == digit(m11, m12, m22, 4, tmp) then
write(d)
extract(m11, m12, m22, d)
i = i + 1; if i % 10 == 0 then write("\t:", i, "\n") end
else
produce(m11, m12, m22, k)
k = k + 1
end
end
if i % 10 ~= 0 then write(string.rep(" ", 10 - N % 10), "\t:", N, "\n") end
end
local N = tonumber(arg and arg[1]) or 27
pidigits(N)
|
-- Resources:
-- **********
-- IPL list: https://wiki.rage.mp/index.php?title=Interiors_and_Locations
fx_version 'cerulean'
game 'gta5'
author 'Bob_74'
description 'Load and customize your map'
version '2.0.10a'
client_scripts {
"lib/common.lua"
, "lib/observers/interiorIdObserver.lua"
, "lib/observers/officeSafeDoorHandler.lua"
, "client.lua"
-- GTA V
, "gtav/base.lua" -- Base IPLs to fix holes
, "gtav/ammunations.lua"
, "gtav/bahama.lua"
, "gtav/floyd.lua"
, "gtav/franklin.lua"
, "gtav/franklin_aunt.lua"
, "gtav/graffitis.lua"
, "gtav/pillbox_hospital.lua"
, "gtav/lester_factory.lua"
, "gtav/michael.lua"
, "gtav/north_yankton.lua"
, "gtav/red_carpet.lua"
, "gtav/simeon.lua"
, "gtav/stripclub.lua"
, "gtav/trevors_trailer.lua"
, "gtav/ufo.lua"
, "gtav/zancudo_gates.lua"
-- GTA Online
, "gta_online/apartment_hi_1.lua"
, "gta_online/apartment_hi_2.lua"
, "gta_online/house_hi_1.lua"
, "gta_online/house_hi_2.lua"
, "gta_online/house_hi_3.lua"
, "gta_online/house_hi_4.lua"
, "gta_online/house_hi_5.lua"
, "gta_online/house_hi_6.lua"
, "gta_online/house_hi_7.lua"
, "gta_online/house_hi_8.lua"
, "gta_online/house_mid_1.lua"
, "gta_online/house_low_1.lua"
-- DLC High Life
, "dlc_high_life/apartment1.lua"
, "dlc_high_life/apartment2.lua"
, "dlc_high_life/apartment3.lua"
, "dlc_high_life/apartment4.lua"
, "dlc_high_life/apartment5.lua"
, "dlc_high_life/apartment6.lua"
-- DLC Heists
, "dlc_heists/carrier.lua"
, "dlc_heists/yacht.lua"
-- DLC Executives & Other Criminals
, "dlc_executive/apartment1.lua"
, "dlc_executive/apartment2.lua"
, "dlc_executive/apartment3.lua"
-- DLC Finance & Felony
, "dlc_finance/office1.lua"
, "dlc_finance/office2.lua"
, "dlc_finance/office3.lua"
, "dlc_finance/office4.lua"
, "dlc_finance/organization.lua"
-- DLC Bikers
, "dlc_bikers/cocaine.lua"
, "dlc_bikers/counterfeit_cash.lua"
, "dlc_bikers/document_forgery.lua"
, "dlc_bikers/meth.lua"
, "dlc_bikers/weed.lua"
, "dlc_bikers/clubhouse1.lua"
, "dlc_bikers/clubhouse2.lua"
, "dlc_bikers/gang.lua"
-- DLC Import/Export
, "dlc_import/garage1.lua"
, "dlc_import/garage2.lua"
, "dlc_import/garage3.lua"
, "dlc_import/garage4.lua"
, "dlc_import/vehicle_warehouse.lua"
-- DLC Gunrunning
, "dlc_gunrunning/bunkers.lua"
, "dlc_gunrunning/yacht.lua"
-- DLC Smuggler's Run
, "dlc_smuggler/hangar.lua"
-- DLC Doomsday Heist
, "dlc_doomsday/facility.lua"
-- DLC After Hours
, "dlc_afterhours/nightclubs.lua"
-- DLC Diamond Casino (Requires forced build 2060 or higher)
, "dlc_casino/casino.lua"
, "dlc_casino/penthouse.lua"
}
|
local cwThirdPerson = cwThirdPerson;
Clockwork.config:AddToSystem("EnableThirdPerson", "enable_third_person", "EnableThirdPersonDesc");
if (!cwThirdPerson.addedSettings) then
Clockwork.setting:AddCheckBox("ThirdPerson", "EnableThirdPersonView", "cwThirdPerson", "EnableThirdPersonViewDesc");
Clockwork.setting:AddNumberSlider("ThirdPerson", "BackPosition", "cwChaseCamBack", -200, 200, 1, "BackPositionDesc");
Clockwork.setting:AddNumberSlider("ThirdPerson", "RightPosition", "cwChaseCamRight", -200, 200, 1, "RightPositionDesc");
Clockwork.setting:AddNumberSlider("ThirdPerson", "UpPosition", "cwChaseCamUp", -200, 200, 1, "UpPositionDesc");
cwThirdPerson.addedSettings = true;
end; |
local fio = require('fio')
local files = {}
-- class File
local File = {}
function File:new(opts)
assert(type(opts.path) == 'string')
assert(type(opts.content) == 'string' or opts.content == nil)
local file = {}
file.path = opts.path
file.content = opts.content or ''
file.content_was_read = false
setmetatable(file, self)
self.__index = self
return file
end
function File:read()
if self.content_was_read then
return ''
end
self.content_was_read = true
return self.content
end
function File:close()
self.content_was_read = false
end
-- fio functions
fio.path.exists = function(path)
return files[path] ~= nil
end
fio.open = function(path)
return files[path]
end
-- test helpers
fio.path.write_file = function(opts)
assert(type(opts.path) == 'string')
assert(type(opts.content) == 'string' or opts.content == nil)
local file = File:new(opts)
files[file.path] = file
end
fio.path.remove_file = function(path)
files[path] = nil
end
|
require("firecast.lua");
local __o_rrpgObjs = require("rrpgObjs.lua");
require("rrpgGUI.lua");
require("rrpgDialogs.lua");
require("rrpgLFM.lua");
require("ndb.lua");
require("locale.lua");
local __o_Utils = require("utils.lua");
local function constructNew_frmGerencPluginItem()
local obj = GUI.fromHandle(_obj_newObject("form"));
local self = obj;
local sheet = nil;
rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject"));
function obj:setNodeObject(nodeObject)
sheet = nodeObject;
self.sheet = nodeObject;
self:_oldSetNodeObjectFunction(nodeObject);
end;
function obj:setNodeDatabase(nodeObject)
self:setNodeObject(nodeObject);
end;
_gui_assignInitialParentForForm(obj.handle);
obj:beginUpdate();
obj:setName("frmGerencPluginItem");
obj:setTitle("Gerenciar Plugins");
obj:setHeight(30);
local function desinstalarPlugin()
if sheet == nil then
return;
end;
local moduleId = sheet.moduleId;
Dialogs.confirmYesNo(lang("plugins.mgr.uninstallConfirmation"),
function (confirmado)
if confirmado then
local r, msg = Firecast.Plugins.uninstallPlugin(moduleId);
if not r then
showMessage(lang("plugins.mgr.uninstallFailure") .. ": " .. msg);
end;
end;
end);
end;
obj.flwPlug = GUI.fromHandle(_obj_newObject("flowLayout"));
obj.flwPlug:setParent(obj);
obj.flwPlug:setName("flwPlug");
obj.flwPlug:setAlign("top");
obj.flwPlug:setMaxControlsPerLine(2);
obj.flwPlug:setAutoHeight(true);
obj.labNome = GUI.fromHandle(_obj_newObject("label"));
obj.labNome:setParent(obj.flwPlug);
obj.labNome:setName("labNome");
obj.labNome:setField("name");
obj.labNome:setWordWrap(false);
obj.labNome:setFontColor("white");
obj.labNome:setMargins({right=3});
obj.labNome:setAutoSize(true);
obj.label1 = GUI.fromHandle(_obj_newObject("label"));
obj.label1:setParent(obj.flwPlug);
obj.label1:setField("version");
obj.label1:setFontColor("gray");
obj.label1:setFontSize(12);
obj.label1:setName("label1");
obj.label1:setWordWrap(false);
obj.label1:setAutoSize(true);
obj.flowLineBreak1 = GUI.fromHandle(_obj_newObject("flowLineBreak"));
obj.flowLineBreak1:setParent(obj.flwPlug);
obj.flowLineBreak1:setName("flowLineBreak1");
obj.fptDescricao = GUI.fromHandle(_obj_newObject("flowPart"));
obj.fptDescricao:setParent(obj.flwPlug);
obj.fptDescricao:setName("fptDescricao");
obj.fptDescricao:setMinWidth(100);
obj.fptDescricao:setMaxWidth(800);
obj.fptDescricao:setMargins({left=10, right=10});
obj.labDescricao = GUI.fromHandle(_obj_newObject("label"));
obj.labDescricao:setParent(obj.fptDescricao);
obj.labDescricao:setName("labDescricao");
obj.labDescricao:setField("description");
obj.labDescricao:setFontColor("silver");
obj.labDescricao:setFontSize(12);
obj.labDescricao:setAlign("top");
obj.labDescricao:setWordWrap(true);
obj.labDescricao:setAutoSize(true);
obj.flowLineBreak2 = GUI.fromHandle(_obj_newObject("flowLineBreak"));
obj.flowLineBreak2:setParent(obj.flwPlug);
obj.flowLineBreak2:setName("flowLineBreak2");
obj.label2 = GUI.fromHandle(_obj_newObject("label"));
obj.label2:setParent(obj.flwPlug);
obj.label2:setText("@@plugins.mgr.authorLabel");
obj.label2:setFontColor("silver");
obj.label2:setFontSize(12);
obj.label2:setMargins({left=10});
obj.label2:setName("label2");
obj.label2:setWordWrap(false);
obj.label2:setAutoSize(true);
obj.label3 = GUI.fromHandle(_obj_newObject("label"));
obj.label3:setParent(obj.flwPlug);
obj.label3:setField("author");
obj.label3:setFontColor("gray");
obj.label3:setFontSize(11);
obj.label3:setName("label3");
obj.label3:setWordWrap(false);
obj.label3:setAutoSize(true);
obj.flowLineBreak3 = GUI.fromHandle(_obj_newObject("flowLineBreak"));
obj.flowLineBreak3:setParent(obj.flwPlug);
obj.flowLineBreak3:setName("flowLineBreak3");
obj.btnDesinstalar = GUI.fromHandle(_obj_newObject("button"));
obj.btnDesinstalar:setParent(obj.flwPlug);
obj.btnDesinstalar:setName("btnDesinstalar");
obj.btnDesinstalar:setText("@@plugins.mgr.uninstall");
obj.btnDesinstalar:setMargins({left=5, top=5});
obj.btnDesinstalar:setWidth(110);
obj.btnDesinstalar:setHeight(40);
obj.dataLink1 = GUI.fromHandle(_obj_newObject("dataLink"));
obj.dataLink1:setParent(obj);
obj.dataLink1:setField("moduleId");
obj.dataLink1:setName("dataLink1");
obj._e_event0 = obj.flwPlug:addEventListener("onResize",
function (_)
self.height = self.flwPlug.height + 15;
end, obj);
obj._e_event1 = obj.labDescricao:addEventListener("onResize",
function (_)
self.fptDescricao.height = self.labDescricao.height;
end, obj);
obj._e_event2 = obj.btnDesinstalar:addEventListener("onClick",
function (_)
desinstalarPlugin()
end, obj);
obj._e_event3 = obj.dataLink1:addEventListener("onChange",
function (_, field, oldValue, newValue)
self.btnDesinstalar.visible = sheet.moduleId ~= 'RRPG.FIRECAST.FMXModule';
end, obj);
function obj:_releaseEvents()
__o_rrpgObjs.removeEventListenerById(self._e_event3);
__o_rrpgObjs.removeEventListenerById(self._e_event2);
__o_rrpgObjs.removeEventListenerById(self._e_event1);
__o_rrpgObjs.removeEventListenerById(self._e_event0);
end;
obj._oldLFMDestroy = obj.destroy;
function obj:destroy()
self:_releaseEvents();
if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then
self:setNodeDatabase(nil);
end;
if self.btnDesinstalar ~= nil then self.btnDesinstalar:destroy(); self.btnDesinstalar = nil; end;
if self.dataLink1 ~= nil then self.dataLink1:destroy(); self.dataLink1 = nil; end;
if self.fptDescricao ~= nil then self.fptDescricao:destroy(); self.fptDescricao = nil; end;
if self.flwPlug ~= nil then self.flwPlug:destroy(); self.flwPlug = nil; end;
if self.label1 ~= nil then self.label1:destroy(); self.label1 = nil; end;
if self.labDescricao ~= nil then self.labDescricao:destroy(); self.labDescricao = nil; end;
if self.flowLineBreak2 ~= nil then self.flowLineBreak2:destroy(); self.flowLineBreak2 = nil; end;
if self.flowLineBreak1 ~= nil then self.flowLineBreak1:destroy(); self.flowLineBreak1 = nil; end;
if self.label3 ~= nil then self.label3:destroy(); self.label3 = nil; end;
if self.labNome ~= nil then self.labNome:destroy(); self.labNome = nil; end;
if self.flowLineBreak3 ~= nil then self.flowLineBreak3:destroy(); self.flowLineBreak3 = nil; end;
if self.label2 ~= nil then self.label2:destroy(); self.label2 = nil; end;
self:_oldLFMDestroy();
end;
obj:endUpdate();
return obj;
end;
function newfrmGerencPluginItem()
local retObj = nil;
__o_rrpgObjs.beginObjectsLoading();
__o_Utils.tryFinally(
function()
retObj = constructNew_frmGerencPluginItem();
end,
function()
__o_rrpgObjs.endObjectsLoading();
end);
assert(retObj ~= nil);
return retObj;
end;
local _frmGerencPluginItem = {
newEditor = newfrmGerencPluginItem,
new = newfrmGerencPluginItem,
name = "frmGerencPluginItem",
dataType = "",
formType = "undefined",
formComponentName = "form",
title = "Gerenciar Plugins",
description=""};
frmGerencPluginItem = _frmGerencPluginItem;
Firecast.registrarForm(_frmGerencPluginItem);
return _frmGerencPluginItem;
|
TOOL.Category = "NPC Tools 2"
TOOL.Name = "NPC Notarget"
TOOL.Command = nil
TOOL.ConfigName = ""
if(CLIENT) then
TOOL.Information = {
{ name = "left" },
{ name = "right" }
}
language.Add("tool.npctool_notarget.name","No Target")
language.Add("tool.npctool_notarget.desc","Enable/Disable notarget for a NPC or yourself")
language.Add("tool.npctool_notarget.left","Enable/Disable notarget for the NPC you're looking at")
language.Add("tool.npctool_notarget.right","Enable/Disable notarget for yourself")
function TOOL.BuildCPanel(pnl)
pnl:AddControl("Header",{Text = "Notarget",Description = [[Left-Click to enable/disable notarget for the NPC you're looking at.
Right click to enable/disable notarget for yourself.
]]})
end
else
local _R = debug.getregistry()
local meta = _R.Player
if(not meta.GetNoTarget) then
local SetNoTarget = meta.SetNoTarget
function meta:SetNoTarget(...)
self.m_bNoTarget = ...
return SetNoTarget(self,...)
end
function meta:GetNoTarget() return self.m_bNoTarget or false end
end
local meta = _R.NPC
if(not meta.SetNoTarget) then
local tbNPCsNoTarget = {}
local AddEntityRelationship = meta.AddEntityRelationship
function meta:AddEntityRelationship(...)
local ent,disp = ...
local dispCur = self:Disposition(ent)
if(tbNPCsNoTarget[self]) then
tbNPCsNoTarget[self][ent] = disp
return
end
return AddEntityRelationship(self,...)
end
function meta:SetNoTarget(bNoTarget)
if(bNoTarget) then
if(not tbNPCsNoTarget[self]) then
tbNPCsNoTarget[self] = {}
for _,ent in ipairs(ents.GetAll()) do
if(ent:IsNPC() and ent ~= self) then
tbNPCsNoTarget[self][ent] = ent:Disposition(self)
AddEntityRelationship(ent,self,D_NU,100)
end
end
end
return
end
for ent,disp in pairs(tbNPCsNoTarget[self]) do
if(ent:IsValid()) then
AddEntityRelationship(ent,self,disp,100)
end
end
tbNPCsNoTarget[self] = nil
end
hook.Add("OnEntityCreated","ApplyNoTarget",function(ent)
if(ent:IsValid() and ent:IsNPC()) then
for entTgt,_ in pairs(tbNPCsNoTarget) do
if(entTgt:IsValid()) then
tbNPCsNoTarget[entTgt][ent] = ent:Disposition(entTgt)
AddEntityRelationship(ent,entTgt,D_NU,100)
else tbNPCsNoTarget[entTgt] = nil end
end
end
end)
function meta:GetNoTarget()
return tbNPCsNoTarget[self] and true or false
end
end
end
function TOOL:LeftClick(tr)
if(CLIENT) then return true end
if(tr.Entity:IsValid() and tr.Entity:IsNPC()) then
local bNoTarget = not tr.Entity:GetNoTarget()
tr.Entity:SetNoTarget(bNoTarget)
local l = "notification.AddLegacy(\"" .. (bNoTarget and "Enabled " or "Disabled ") .. "notarget for \" .. language.GetPhrase(\"#" .. tr.Entity:GetClass() .. "\") .. \".\",1,8);"
l = l .. "surface.PlaySound(\"buttons/button14.wav\")"
self:GetOwner():SendLua(l)
return true
end
end
function TOOL:RightClick(tr)
if(CLIENT) then return true end
local owner = self:GetOwner()
local bNoTarget = not owner:GetNoTarget()
owner:SetNoTarget(bNoTarget)
local l = "notification.AddLegacy(\"" .. (bNoTarget and "Enabled " or "Disabled ") .. "notarget for " .. owner:GetName() .. ".\",1,8);"
l = l .. "surface.PlaySound(\"buttons/button14.wav\")"
owner:SendLua(l)
return false
end
|
local get_map_options = function(custom_options)
local options = { noremap = true, silent = true }
if custom_options then
options = vim.tbl_extend('force', options, custom_options)
end
return options
end
local M = {}
M.map = function(mode, target, source, opts)
vim.api.nvim_set_keymap(mode, target, source, get_map_options(opts))
end
M.buf_map = function(mode, bufnr, target, source, opts)
vim.api.nvim_buf_set_keymap(bufnr, mode, target, source, get_map_options(opts))
end
for _, mode in ipairs({ 'n', 'o', 'i', 'x', 't' }) do
M[mode .. 'map'] = function(...)
M.map(mode, ...)
end
M['buf_' .. mode .. 'map'] = function(...)
M.buf_map(mode, ...)
end
end
M.command = function(name, fn)
vim.cmd(string.format('command! %s %s', name, fn))
end
M.lua_command = function(name, fn)
M.command(name, 'lua ' .. fn)
end
M.warn = function(msg)
vim.api.nvim_echo({ { msg, 'WarningMsg' } }, true, {})
end
return M
|
class 'piranha_plant_turned'
local AI_SHOWING_UP = 0
local AI_SHOWING_IDLE = 1
local AI_HIDING_DOWN = 2
local AI_HIDING_IDLE = 3
function piranha_plant_turned:hideSprite()
self.npc_obj:setSpriteWarp(1.0, 1, true)
end
function piranha_plant_turned:updateWarp()
self.npc_obj:setSpriteWarp(1.0-(math.abs(self.npc_obj.top-self.npc_obj.bottom)/self.def_height), 1, true)
end
function piranha_plant_turned:initProps()
-- Animation properties
-- Top position (reset size to initial)
self.npc_obj.bottom = self.def_bottom
self.npc_obj.top = self.def_top
self.npc_obj.bottom = self.npc_obj.top
-- Currents
self.cur_mode = AI_HIDING_IDLE
-- if physics are paused, than iterations and collisions are disabled. Paused objects will NOT be detected by other
self.npc_obj.paused_physics = true
-- FOR AI_SHOWING_UP
self.cur_showingUpTicks = 0
-- FOR AI_SHOWING_IDLE
self.cur_showingIdleTicks = 0
-- FOR AI_HIDING_DOWN
self.cur_hidingDownTicks = 0
-- FOR AI_HIDING_IDLE
self.cur_hidingIdleTicks = smbx_utils.ticksToTime(70) -- Initial wait time is 70 ticks!
self:updateWarp()
end
function piranha_plant_turned:__init(npc_obj)
self.npc_obj = npc_obj
-- Config
self.def_top = npc_obj.top
self.def_height = npc_obj.height
self.def_bottom = npc_obj.bottom
self.speed = 1.5
-- FOR AI_SHOWING_UP
self.def_showingUpTicks = smbx_utils.ticksToTime(self.npc_obj.height/self.speed)
-- FOR AI_SHOWING_IDLE
self.def_showingIdleTicks = smbx_utils.ticksToTime(50)
-- FOR AI_HIDING_DOWN
self.def_hidingDownTicks = smbx_utils.ticksToTime(self.npc_obj.height/self.speed)
-- FOR AI_HIDING_IDLE
self.def_hidingIdleTicks = smbx_utils.ticksToTime(75)
-- If player stands over, reset time to -10 seconds
-- self.def_hidingIdleTicks_waitPlayer = smbx_utils.ticksToTime(65)
npc_obj.gravity = 0
self:initProps()
end
function piranha_plant_turned:onActivated()
self:initProps()
end
function piranha_plant_turned:onLoop(tickTime)
if(self.cur_mode == AI_SHOWING_UP)then
if(self.def_showingUpTicks > self.cur_showingUpTicks)then
self.cur_showingUpTicks = self.cur_showingUpTicks + tickTime
self.npc_obj.bottom = self.npc_obj.bottom + smbx_utils.speedConv(self.speed, tickTime)
self:updateWarp()
else
self.cur_mode = AI_SHOWING_IDLE
self.npc_obj.bottom = self.def_bottom
self.npc_obj:resetSpriteWarp()
self.cur_showingUpTicks = 0
end
elseif(self.cur_mode == AI_SHOWING_IDLE)then
if(self.def_showingIdleTicks >= self.cur_showingIdleTicks)then
self.cur_showingIdleTicks = self.cur_showingIdleTicks + tickTime
else
self.cur_mode = AI_HIDING_DOWN
self.cur_showingIdleTicks = 0
end
elseif(self.cur_mode == AI_HIDING_DOWN)then
if(self.def_hidingDownTicks > self.cur_hidingDownTicks)then
self.cur_hidingDownTicks = self.cur_hidingDownTicks + tickTime
self.cur_hidingIdleTicks = self.cur_hidingIdleTicks + tickTime
self.npc_obj.bottom = self.npc_obj.bottom - smbx_utils.speedConv(self.speed, tickTime)
self:updateWarp()
else
self.cur_mode = AI_HIDING_IDLE
self:hideSprite()
self.cur_hidingDownTicks = 0
self.npc_obj.paused_physics=true
end
elseif(self.cur_mode == AI_HIDING_IDLE)then
if(self.def_hidingIdleTicks >= self.cur_hidingIdleTicks)then
self.cur_hidingIdleTicks = self.cur_hidingIdleTicks + tickTime
else
--local players = Player.get()
-- local goUp = true
--for _, player in pairs(players) do
-- if(math.abs(player.center_x - self.npc_obj.center_x) <= 44)then
-- goUp = false
-- self.cur_hidingIdleTicks = self.def_hidingIdleTicks_waitPlayer
-- end
--end
-- if(goUp)then
self.cur_mode = AI_SHOWING_UP
self.npc_obj.paused_physics = false
self.cur_hidingIdleTicks = 0
--end
end
end
end
return piranha_plant_turned
|
--[[=========================================
_ _ _
| | | | | | /\ /\
| | | | | | / \ _ __ _ __ / \ _ __ ___
| | | | | |/ /\ \ | '_ \| '_ \ / /\ \ | '__/ __|
| |___| |__| / ____ \| |_) | |_) / ____ \| | | (__
|______\____/_/ \_\ .__/| .__/_/ \_\_| \___|
Scripting Project | | | | Improved LUA Engine
|_| |_|
SVN: http://svn.burning-azzinoth.de/LUAppArc
LOG: http://luapparc.burning-azzinoth.de/trac/timeline
TRAC: http://luapparc.burning-azzinoth.de/trac
----------------------
Flames of Azzinoth.lua
Original Code by DARKI
Version 1
========================================]]--
function FlameOfAzzinoth_OnSpawn(pUnit,Event)
pUnit:SetUInt64Value(UnitField.UNIT_FIELD_FLAGS, 0)
end
function FlameOfAzzinoth_OnEnterCombat(pUnit,Event)
pUnit:CastSpell(40637)
pUnit:RegisterEvent("FlameOfAzzinoth_FlameBlast", 15000, 0)
end
function FlameOfAzzinoth_FlameBlast(pUnit,Event)
local plr=pUnit:GetRandomPlayer(0)
if ( type(plr) == "userdata") then
pUnit:FullCastSpellOnTarget(40631,plr)
end
end
function FlameOfAzzinoth_OnLeaveCombat(pUnit,Event)
pUnit:RemoveEvents()
end
function FlameOfAzzinoth_OnDied(pUnit,Event)
pUnit:RemoveEvents()
end
RegisterUnitEvent(22997, 1, "FlameOfAzzinoth_OnEnterCombat")
RegisterUnitEvent(22997, 2, "FlameOfAzzinoth_OnLeaveCombat")
RegisterUnitEvent(22997, 4, "FlameOfAzzinoth_OnDied")
function FlameOfAzzinoth_FlameBlast(pUnit,Event)
local plr=pUnit:GetRandomPlayer(0)
if ( type(plr) == "userdata") then
pUnit:FullCastSpellOnTarget(40631,plr)
end
end |
require "ISUI/ISUIElement"
---@class ISLabel : ISUIElement
ISLabel = ISUIElement:derive("ISLabel");
--************************************************************************--
--** ISPanel:initialise
--**
--************************************************************************--
function ISLabel:initialise()
ISUIElement.initialise(self);
end
function ISLabel:getName()
return self.name;
end
function ISLabel:setName(name)
if self.name == name then return end
self.name = name
self:setX(self.originalX)
self:setWidth(getTextManager():MeasureStringX(self.font, name))
if self.left ~= true and not self.center then
self:setX(self.x - self.width)
end
end
function ISLabel:setWidthToName(minWidth)
local width = getTextManager():MeasureStringX(self.font, self.name)
width = math.max(width, minWidth or 0)
if width ~= self.width then
self:setWidth(width)
end
end
function ISLabel:setColor(r,g,b)
self.r = r;
self.g = g;
self.b = b;
end
--************************************************************************--
--** ISPanel:render
--**
--************************************************************************--
function ISLabel:prerender()
local txt = self.name;
if self.translation then
txt = self.translation;
end
local height = getTextManager():MeasureFont(self.font);
-- The above call doesn't handle multi-line text
local height2 = getTextManager():MeasureStringY(self.font, txt)
height = math.max(height, height2)
if not self.center then
self:drawText(txt, 0, (self.height/2)-(height/2), self.r, self.g, self.b, self.a, self.font);
else
self:drawTextCentre(txt, 0, (self.height/2)-(height/2), self.r, self.g, self.b, self.a, self.font);
end
if self.joypadFocused and self.joypadTexture then
local texY = self.height / 2 - 20 / 2
self:drawTextureScaled(self.joypadTexture,-28,texY,20,20,1,1,1,1);
end
self:updateTooltip()
end
function ISLabel:onMouseMove(dx, dy)
self.mouseOver = true;
end
function ISLabel:onMouseMoveOutside(dx, dy)
self.mouseOver = false;
end
function ISLabel:updateTooltip()
if self.disabled then return; end
if self:isMouseOver() and self.tooltip then
local text = self.tooltip
if not self.tooltipUI then
self.tooltipUI = ISToolTip:new()
self.tooltipUI:setOwner(self)
self.tooltipUI:setVisible(false)
self.tooltipUI:setAlwaysOnTop(true)
end
if not self.tooltipUI:getIsVisible() then
if string.contains(self.tooltip, "\n") then
self.tooltipUI.maxLineWidth = 1000 -- don't wrap the lines
else
self.tooltipUI.maxLineWidth = 300
end
self.tooltipUI:addToUIManager()
self.tooltipUI:setVisible(true)
end
self.tooltipUI.description = text
self.tooltipUI:setX(self:getAbsoluteX())
self.tooltipUI:setY(self:getAbsoluteY() + self:getHeight())
else
if self.tooltipUI and self.tooltipUI:getIsVisible() then
self.tooltipUI:setVisible(false)
self.tooltipUI:removeFromUIManager()
end
end
end
function ISLabel:setTooltip(tooltip)
self.tooltip = tooltip;
end
function ISLabel:setJoypadFocused(focused)
self.joypadFocused = focused;
self.joypadTexture = Joypad.Texture.AButton;
end
function ISLabel:setTranslation(translation)
self.translation = translation;
self.x = self.originalX;
if self.font ~= nil then
self.width = getTextManager():MeasureStringX(self.font, translation);
if(self.left ~= true) then
self.x = self.x - self.width;
end
else
self.width = getTextManager():MeasureStringX(UIFont.Small, translation);
if(self.left ~= true) then
self.x = self.x - self.width;
end
self.font = UIFont.Small;
end
end
function ISLabel:new (x, y, height, name, r, g, b, a, font, bLeft)
local o = {}
--o.data = {}
o = ISUIElement:new(x, y, 0, height);
setmetatable(o, self)
self.__index = self
o.x = x;
o.y = y;
o.font = font or UIFont.Small;
o.backgroundColor = {r=0, g=0, b=0, a=0.5};
o.borderColor = {r=1, g=1, b=1, a=0.7};
o.originalX = x;
o.width = getTextManager():MeasureStringX(o.font, name)
if (bLeft ~= true) then
o.x = o.x - o.width
end
o.height = height;
o.left = bLeft;
o.anchorLeft = true;
o.anchorRight = false;
o.anchorTop = true;
o.anchorBottom = false;
o.name = name;
o.r = r;
o.g = g;
o.b = b;
o.a = a;
o.mouseOver = false;
o.tooltip = nil;
o.center = false;
o.joypadFocused = false;
o.translation = nil;
return o
end
|
local query = {}
local utils = require('utils')
-----
-- query (id, title, host, port, type, user, password)
-----
function query.model()
local model = {}
model.SPACE_NAME = 'query'
model.PRIMARY_INDEX = 'primary'
model.ID = 1
model.TITLE = 2
model.HOST = 3
model.PORT = 4
model.TYPE = 5
model.USER = 6
model.PASSWORD = 7
model.QUERY = 8
model.UPDATE_TS = 9
model.PARENT_ID = 10
model.FLAGS = 11
model.ARGS = 12
function model.get_space()
return box.space[model.SPACE_NAME]
end
function model.serialize(query_tuple)
return {
id = query_tuple[model.ID],
title = query_tuple[model.TITLE],
host = query_tuple[model.HOST],
port = query_tuple[model.PORT],
type = query_tuple[model.TYPE],
user = query_tuple[model.USER],
password = query_tuple[model.PASSWORD],
query = query_tuple[model.QUERY],
update_ts = query_tuple[model.UPDATE_TS],
parent_id = query_tuple[model.PARENT_ID],
flags = query_tuple[model.FLAGS],
args = query_tuple[model.ARGS] or {},
}
end
function model.get()
return model.get_space():select({})
end
function model.upsert(query_tuple)
query_tuple[model.UPDATE_TS] = utils.time()
local fields = utils.format_update(query_tuple)
return model.get_space():upsert(query_tuple, fields)
end
function model.delete(query_id)
if utils.not_empty_string(query_id) then
return model.get_space():delete({query_id})
end
end
return model
end
return query
|
--[=[
@Author: Gavin "Mullets" Rosenthal
@Desc: Internal Modular Component System
]=]
local Components = {}
Components._Name = "Modular Component System"
Components._Bindings = {}
local require = require(game:GetService("ReplicatedStorage"):WaitForChild("Loader"))
local Manager = require("Manager")
local RunService = game:GetService("RunService")
--[=[
Construct a new component out of a pre-existing element
@param element GuiObject -- the main component
@return Class
]=]
function Components.new(element: GuiObject): typeof(Components.new())
local config = element:FindFirstChildWhichIsA("Configuration")
do
if not config then
config = Instance.new("Configuration")
config.Name = "MCS_" .. element.Name
config.Parent = element
end
end
return setmetatable({
element = element,
config = config,
}, Components)
end
--[=[
Bind a function to a codename
@param name string -- the name of the binding
@param code function -- the function to bind
@return nil
]=]
function Components:Bind(name: string, code: (any) -> nil): nil
assert(
Components._Bindings[name] == nil,
"Attempted to overwrite binding on '" .. name .. "'"
)
Components._Bindings[name] = code
end
--[=[
Unbind a codename
@param name string -- the name of the binding
@return nil
]=]
function Components:Unbind(name: string): nil
Components._Bindings[name] = nil
end
--[=[
Fire a binded function on a codename
@param name string -- the name of the binding
@param ...? any -- optional parameters to pass
@return nil
]=]
function Components:Fire(name: string, ...): nil
assert(
Components._Bindings[name],
"Attempted to fire a non-existant binding on '" .. name .. "'"
)
local code = Components._Bindings[name]
Manager.Wrap(code, ...)
end
--[=[
Get an attribute value on the component. Checks for value objects first
@param name string -- name of the attribute
@return Value any?
]=]
function Components:Get(name: string): any?
local obj = self.config:FindFirstChild(name)
if obj then
return obj.Value
else
return self.config:GetAttribute(name)
end
end
--[=[
Set an attribute value on the component. Checks for value objects first
@param name string -- name of the attribute
@param value any -- the value to set on an attribute
@return Value any
]=]
function Components:Set(name: string, value: any): any?
local obj = self.config:FindFirstChild(name)
if obj then
obj.Value = value
else
self.config:SetAttribute(name, value)
end
return value
end
--[=[
Update a known attribute with a value & increment numbers
@param name string -- the name of the attribute
@param value any -- the value to update on an attribute
@return Value any
]=]
function Components:Update(name: string, value: any): any
local get = self:Get(name)
assert(get ~= nil, "Attempted to update nil attribute '" .. name .. "'")
if typeof(get) == "number" and typeof(value) == "number" then
get += value
self:Set(name, get)
else
self:Set(name, value)
end
return self:Get(name)
end
--[=[
Bind a function to an attribute that changes. Checks for value objects first
@param name string -- the name of the attribute
@param code function -- the function to connect
@return RBXScriptConnection
]=]
function Components:Attribute(name: string, code: (any, any) -> nil): RBXScriptConnection
local last = self:Get(name)
assert(last ~= nil, "Attempted to bind to nil attribute '" .. name .. "'")
Manager.Wrap(code, last, last)
local obj = self.config:FindFirstChild(name)
local signal
do
if obj then
signal = obj.Changed:Connect(function(new)
Manager.Wrap(code, new, last)
last = new
end)
else
signal = self.config:GetAttributeChangedSignal(name):Connect(function()
local new = self:Get(name)
Manager.Wrap(code, new, last)
last = new
end)
end
end
Manager:ConnectKey("attribute_" .. name, signal)
return signal
end
--[=[
Connect an event to a GuiObject apart of the component
@param object GuiObject -- the object to connect
@param event string -- the connection type
@param code function -- the function to connect
@return RBXScriptSignal
]=]
function Components:Connect(object: GuiObject, event: string, code: (any) -> nil): RBXScriptConnection
local signal = object[event]:Connect(function(...)
code(...)
end)
Manager:ConnectKey("connection_" .. object.Name, signal)
return signal
end
--[=[
Hook a function to a lifecycle event which fires when the component is visible
@param name string -- the name of the lifecycle
@param code function -- the function to run
@return RBXScriptConnection
]=]
function Components:Lifecycle(name: string, code: (number) -> nil): RBXScriptConnection
local signal = RunService.RenderStepped:Connect(function(delta)
if self.element.Visible then
code(delta)
end
end)
Manager:ConnectKey("lifecycle_" .. name, signal)
return signal
end
--[=[
Destroys all the signals connected to a name no matter the type
@param name string -- name of the signal key connected
@return nil
]=]
function Components:Destroy(name: string): nil
Manager:DisconnectKey("attribute_" .. name)
Manager:DisconnectKey("connection_" .. name)
Manager:DisconnectKey("lifecycle_" .. name)
end
--[=[
A custom index method which handles unknown or known indices
@param index any -- the index being called on the component
@return any?
]=]
function Components:__index(index: any): any?
if Components[index] then
return Components[index]
end
if index == self.element.Name then
return self.element
end
if self.element[index] then
return self.element[index]
end
error(
index .. " is not a valid member of " .. self.element:GetFullName() .. " \"" .. self.element.ClassName .. "\"",
2
)
end
--[=[
Shorten getting an attribute attached to the component
@param name string -- name of the component
@param value any? -- include this to also set the component state
@return Value any
]=]
function Components:__call(name: string, value: any?): any?
if value ~= nil then
self:Set(name, value)
end
return self:Get(name)
end
return Components
|
-- Created by Elfansoer
--[[
- TEXTS
Bounce
ACTIVE: Releases a bolt that bounces against enemies and dealing damage.
UPGRADE: Bounces or repeats the main function.
PASSIVE: Damage reflect
Breach
ACTIVE: Shot a long distance arrow that deals damage.
UPGRADE: Increases range of the main function.
PASSIVE: Increases mana capacity.
Crash
ACTIVE: Stuns enemies along the path, dealing damage.
UPGRADE: Stuns affected enemies.
PASSIVE: Reduces damage taken.
Flood
ACTIVE: Creates a slow-moving sphere that deals damage over time.
UPGRADE: Generates a lingering field that deals damage over time.
PASSIVE: Increases health regeneration.
Get
ACTIVE: Shot a bolt that pulls the first enemy hit.
UPGRADE: Add pull effect to affected enemies.
PASSIVE: Grants attack modifier that slows enemies.
Ping
ACTIVE: Toggle on to rapidly shoot bolts that deals damage.
UPGRADE: Reduces cooldown of the main function.
PASSIVE: Increases attack speed.
Purge
ACTIVE: Shot a bolt that deals damage over time to a single target.
UPGRADE: Deals damage per second to affected enemies.
PASSIVE: GGrants attack modifier that reduces enemy's armor.
Switch
ACTIVE: Temporarily dominates the first enemy hit.
UPGRADE: Add switch-allegiance effect to affected enemies.
PASSIVE: Grants percentage stat bonus.
Cull
ACTIVE: Knocks upward enemies in the area.
UPGRADE: Add knockback effect to affected enemies.
PASSIVE: Grants a chance to bash attacked enemies.
Help
ACTIVE: Summons a friend that deals damage on area, which can be affected by modifiers.
UPGRADE: Creates illusions that attacks affected enemies.
PASSIVE: Grants a chance for critical strikes.
Jaunt
ACTIVE: Teleports and deals damage to the target area.
UPGRADE: Reduces manacost of the main function.
PASSIVE: Increases movement speed.
Load
ACTIVE: Creates a packet that deals area damage when attacked by anyone.
UPGRADE: Deals damage in area around each affected enemies.
PASSIVE: Increases attack damage.
Mask
ACTIVE: Turns user invisible, and deal bonus damage when attacks out of invisibility.
UPGRADE: Deals backstab damage to affected enemies if user cannot be seen by them.
PASSIVE: Grants a chance to evade attacks.
Spark
ACTIVE: Produces bolts which fans out from the point, dealing damage.
UPGRADE: Splits the main function into 3 instances.
PASSIVE: Grants cleave to attacks.
Tap
ACTIVE: Damages enemies in area around user, with a lifesteal effect.
UPGRADE: Add lifesteal effect to the main function.
PASSIVE: Increases health capacity
Void
ACTIVE: Adds damage amplification debuff to all enemies in area.
UPGRADE: Add damage amp debuff to affected enemies for half the normal value.
PASSIVE: Increases mana regeneration.
Names
Bounce(), Niola Chein
Breach(), Unknown
Crash(), Red
Cull(), Olmarq
Flood(), Royce Bracket
Get(), Bailey Gilande
Help(), Sybil Reisz
Jaunt(), Preston Moyle
Load(), Wave Tennegan
Mask(), Shomar Shasberg
Ping(), Henter Jallaford
Purge(), Maximilias Darzi
Spark(), Lillian Platt
Switch(), Farrah Yon-Dale
Tap(), Grant Kendrell
Void(), Asher Kendrell
]]
--------------------------------------------------------------------------------
-- Base Ability
--------------------------------------------------------------------------------
generic_base = class({})
generic_base.modifiers = {}
generic_base.passive_name = "modifier_red_transistor_access_modifiers"
--------------------------------------------------------------------------------
-- Init Abilities
function generic_base:Precache( context )
-- PrecacheResource( "soundfile", "soundevents/game_sounds_heroes/game_sounds_generic_base.vsndevts", context )
-- PrecacheResource( "particle", "particles/units/heroes/hero_generic_base/generic_base.vpcf", context )
end
function generic_base:Spawn()
if not IsServer() then return end
self.modifiers = self.modifiers or {}
end
function generic_base:GetBehavior()
if self.passive then
return DOTA_ABILITY_BEHAVIOR_PASSIVE
end
return self.BaseClass.GetBehavior( self )
end
function generic_base:GetCooldown( iLevel )
if self.passive then
return 0
end
return self.BaseClass.GetCooldown( self, iLevel )
end
function generic_base:GetManaCost( iLevel )
if self.passive then
return 0
end
return self.BaseClass.GetManaCost( self, iLevel )
end
--------------------------------------------------------------------------------
-- Install/Uninstall
function generic_base:Install( access, modifiers, slot_type )
self.access = access
self.kv = access.kv
self.slot_type = slot_type
if slot_type=="passive" then
-- set install base
self:InstallPassive()
-- modifier installs
for i,id in ipairs(modifiers) do
self.modifiers[i] = self:ModifierInstallPassive( access.ability_index[ id ] )
end
else
-- set install base
self:InstallBase()
-- modifier installs
for i,id in ipairs(modifiers) do
self.modifiers[i] = access.abilities[ access.ability_index[ id ] ]
self.modifiers[i]:ModifierInstall( self )
end
end
-- set access modifier (for client purposes)
local caster = self:GetCaster()
self.access_modifier = caster:AddNewModifier(
caster, -- player source
self, -- ability source
"modifier_red_transistor_access_modifiers", -- modifier name
{ slot_type = slot_type } -- kv
)
-- set stack
table.insert( modifiers, 1, access.ability_index[ self:GetAbilityName() ] )
local stack = 0
for i,id in pairs(modifiers) do
stack = stack + id * 100^(i-1)
end
self.access_modifier:SetStackCount( stack )
end
function generic_base:Uninstall()
-- destroy access modifier
if self.access_modifier and (not self.access_modifier:IsNull()) then
self.access_modifier:Destroy()
self.access_modifier = nil
end
if self.slot_type=="passive" then
-- modifier uninstalls
for _,modifier in pairs(self.modifiers) do
self:ModifierUninstallPassive( modifier )
end
-- set uninstall base
self:UninstallPassive()
else
-- modifier uninstalls
for _,modifier in pairs(self.modifiers) do
modifier:ModifierUninstall( self )
end
-- set uninstall base
self:UninstallBase()
end
self.modifiers = {}
end
function generic_base:Replace( access, index, name )
if self.slot_type=="passive" then
-- install uninstall
self:ModifierUninstallPassive( self.modifiers[index] )
self.modifiers[index] = self:ModifierInstallPassive( name )
else
-- install uninstall
self.modifiers[index]:ModifierUninstall( self )
self.modifiers[index] = access.abilities[ name ]
self.modifiers[index]:ModifierInstall( self )
end
-- update access modifier
if self.access_modifier and (not self.access_modifier:IsNull()) then
local stack = self.access_modifier:GetStackCount()
local div = 100^(index)
local old_id = math.floor(stack/div)%100 * div
local new_id = access.ability_index[ name ] * div
stack = stack - old_id + new_id
self.access_modifier:SetStackCount( stack )
end
end
function generic_base:InstallPassive()
local name = self.access.passive_name[self:GetAbilityName()]
self.passive_mod = self:GetCaster():AddNewModifier(
self:GetCaster(), -- player source
self, -- ability source
name, -- modifier name
{} -- kv
)
end
function generic_base:UninstallPassive()
if self.passive_mod and (not self.passive_mod:IsNull()) then
self.passive_mod:Destroy()
end
end
function generic_base:ModifierInstallPassive( modifiername )
local name = self.access.passive_name[ modifiername ]
local mod = self:GetCaster():AddNewModifier(
self:GetCaster(), -- player source
self, -- ability source
name, -- modifier name
{} -- kv
)
return mod
end
function generic_base:ModifierUninstallPassive( mod )
if mod and (not mod:IsNull()) then
mod:Destroy()
end
end
--------------------------------------------------------------------------------
-- Upgrade
function generic_base:OnUpgrade()
if self.access and (not self.access.lock) then
self.access:EventUpgrade( self )
end
end
--------------------------------------------------------------------------------
-- Overridden functions
function generic_base:ProjectileLaunch( data ) end
function generic_base:ProjectileThink( loc, data ) end
function generic_base:ProjectileHit( target, loc, data ) end
function generic_base:ProjectileEnd( target, loc, data ) end
function generic_base:InstallBase() end
function generic_base:UninstallBase() end
function generic_base:ModifierInstall( this ) end
function generic_base:ModifierUninstall( this ) end
function generic_base:ModifierProjectileLaunch( this, data ) end
function generic_base:ModifierProjectileThink( this, loc, data ) end
function generic_base:ModifierProjectileHit( this, target, loc, data ) end
function generic_base:ModifierProjectileEnd( this, target, loc, data ) end
function generic_base:ModifierAreaStart( this, data ) end
function generic_base:ModifierAreaThink( this, loc, data ) end
function generic_base:ModifierAreaHit( this, target, loc, data ) end
function generic_base:ModifierAreaEnd( this, loc, data ) end
--------------------------------------------------------------------------------
-- Helper
function generic_base:GetAbilitySpecialValue( ability, name )
if IsClient() and not self.kv then
local access = self:GetCaster():FindAbilityByName( "red_transistor_access" )
if not access then return 0 end
self.kv = access.kv
end
local kv = self.kv[ability]["AbilitySpecial"]
local specials = {}
for _,v in pairs(kv) do
for a,b in pairs(v) do
if a~="var_type" then
specials[a] = b
end
end
end
return specials[name] or 0
end |
local handsUp = false
CreateThread(function()
while not HasAnimDictLoaded("random@mugging3") do
RequestAnimDict("random@mugging3")
Citizen.Wait(0)
end
while true do
Citizen.Wait(0)
if Ped.Active then
local status = true
if Ped.Available and not Ped.InVehicle and Ped.Visible and Ped.Collection then
status = false
if IsControlJustPressed(1, Config.Gesty.handsUp) then
handsUp = not handsUp
if not handsUp then
ClearPedSecondaryTask(Ped.Id)
else
TaskPlayAnim(Ped.Id, "random@mugging3", "handsup_standing_base", 8.0, -8, -1, 49, 0, 0, 0, 0)
end
end
end
if status and handsUp then
handsUp = false
if not Ped.Locked then
ClearPedSecondaryTask(Ped.Id)
end
end
elseif handsUp then
handsUp = false
if Ped.Available then
ClearPedSecondaryTask(PlayerPedId())
end
end
end
end)
RegisterNetEvent('testteddd')
AddEventHandler('testteddd', function()
if Ped.Active then
local status = true
if Ped.Available and not Ped.InVehicle and Ped.Visible and Ped.Collection then
status = false
handsUp = not handsUp
if not handsUp then
ClearPedSecondaryTask(closestPlayer)
else
TaskPlayAnim(closestPlayer, "random@mugging3", "handsup_standing_base", 8.0, -8, -1, 49, 0, 0, 0, 0)
end
end
if status and handsUp then
handsUp = false
if not Ped.Locked then
ClearPedSecondaryTask(closestPlayer)
end
end
elseif handsUp then
handsUp = false
if Ped.Available then
ClearPedSecondaryTask(PlayerPedId())
end
end
end)
CreateThread(function()
while true do
if handsUp then
Citizen.Wait(0)
DisableControlAction(2, 24, true) -- Attack
DisableControlAction(2, 257, true) -- Attack 2
DisableControlAction(2, 25, true) -- Aim
DisableControlAction(2, 263, true) -- Melee Attack 1
DisableControlAction(2, Keys['R'], true) -- Reload
DisableControlAction(2, Keys['TAB'], true) -- Select Weapon
DisableControlAction(2, Keys['F1'], true) -- Disable phone
DisableControlAction(2, Keys['F'], true) -- Also 'enter'?
DisableControlAction(0, 47, true) -- Disable weapon
DisableControlAction(0, 264, true) -- Disable melee
DisableControlAction(0, 257, true) -- Disable melee
DisableControlAction(0, 140, true) -- Disable melee
DisableControlAction(0, 141, true) -- Disable melee
DisableControlAction(0, 142, true) -- Disable melee
DisableControlAction(0, 143, true) -- Disable melee
else
Citizen.Wait(500)
end
end
end) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.