content
stringlengths 1
1.05M
| size
int64 5
1.05M
| max_stars_repo_name
stringlengths 5
114
|
|---|---|---|
--[[
General -> Profiles Tab -> General & Advanced Tabs
--]]
local L = Grid2Options.L
--==============================
local GetAllProfiles, GetUnusedProfiles
do
local profiles, values = {}, {}
local function GetProfiles(showCurrent)
wipe(profiles)
wipe(values)
Grid2.db:GetProfiles(profiles)
for _,k in pairs(profiles) do
values[k] = k
end
if not showCurrent then
values[Grid2.db:GetCurrentProfile()] = nil
end
return values
end
GetAllProfiles = function() return GetProfiles(true) end
GetUnusedProfiles = function() return GetProfiles(false) end
end
--==============================
local options = {}
options.title = {
order = 1,
type = "description",
name = L["You can change the active database profile, so you can have different settings for every character.\n"],
}
options.current = {
type = "select",
name = L["Current Profile"],
desc = L["Select one of your currently available profiles."],
order = 2,
get = function() return Grid2.db:GetCurrentProfile() end,
set = function(_, v) Grid2.db:SetProfile(v) end,
validate = function() return not InCombatLockdown() or L["Profile cannot be changed in combat"] end,
disabled = InCombatLockdown,
values = GetAllProfiles,
}
options.reset = {
order = 3,
type = "execute",
width = "half",
name = L["Reset"],
desc = L["Reset the current profile back to its default values."],
confirm = true,
confirmText = L["Are you sure you want to reset current profile?"],
func = function()
Grid2:ProfileShutdown()
Grid2.db:ResetProfile()
end,
}
--==============
if not Grid2.isClassic then
options.prodesc = {
order = 8,
type = "description",
name = " ",
}
options.proenabled = {
type = "toggle",
name = "|cffffd200".. L["Enable profiles by Specialization"] .."|r",
desc = L["When enabled, your profile will be set according to the character specialization."],
descStyle = "inline",
order = 9,
width = "full",
get = function(info) return Grid2.profiles.char[1] and Grid2.profiles.char.enabled end,
set = function(info, value)
local db = Grid2.profiles.char
wipe(db)
db.enabled = value or nil
if value then
local pro = Grid2.db:GetCurrentProfile()
for i=1,GetNumSpecializations() or 0 do
db[i] = pro
end
end
Grid2:ReloadProfile()
end,
}
for i=GetNumSpecializations(),1, -1 do
options['profile'..i] = {
type = "select",
name = select( 2, GetSpecializationInfo(i) ),
desc = "",
order = 10.5+i,
get = function() return Grid2.profiles.char[i] end,
set = function(_, v)
Grid2.profiles.char[i] = v
Grid2:ReloadProfile()
end,
values = GetAllProfiles,
hidden = function() return type(Grid2.profiles.char[1])~='string' end,
}
end
end
--==============
options.newdesc = {
order = 15,
type = "description",
name = "\n" .. L["Create a new empty profile by entering a name in the editbox."],
}
options.new = {
name = L["New Profile"],
desc = L["Create a new empty profile by entering a name in the editbox."],
type = "input",
order = 20,
get = false,
set = function(_, v) Grid2.db:SetProfile(v) end,
}
--==============
options.copydesc = {
order = 25,
type = "description",
name = "\n" .. L["Copy the settings from one existing profile into the currently active profile."],
}
options.copyfrom = {
type = "select",
name = L['Copy From'],
desc = L["Copy the settings from one existing profile into the currently active profile."],
order = 30,
get = false,
set = function(_, v)
Grid2:ProfileShutdown()
Grid2.db:CopyProfile(v)
end,
values = GetUnusedProfiles,
confirm = true,
confirmText = L["Are you sure you want to overwrite current profile values?"],
}
--==============
options.deletedesc = {
order = 35,
type = "description",
name = "\n" .. L["Delete existing and unused profiles from the database."],
}
options.delete = {
type = "select",
name = L['Delete a Profile'],
desc = L["Delete existing and unused profiles from the database."],
order = 40,
get = false,
set = function(_, v) Grid2.db:DeleteProfile(v) end,
values = GetUnusedProfiles,
confirm = true,
confirmText = L["Are you sure you want to delete the selected profile?"],
}
--==============================
Grid2Options:AddGeneralOptions("Profiles", nil, {
type = "group",
childGroups = "tab",
order = 100,
name = L["Profiles"],
desc = "",
args = {
general = { type = "group", order= 100, name = L["General"], desc = "", args = options },
import = Grid2Options.AdvancedProfileOptions or {},
},
}, 490 )
| 4,568
|
mrbandler/wow-ui
|
local defaults = require'hop.defaults'
local hint = require'hop.hint'
local M = {}
M.hint = hint.hint
-- Setup user settings.
M.opts = defaults
function M.setup(opts)
-- Look up keys in user-defined table with fallback to defaults.
M.opts = setmetatable(opts or {}, {__index = defaults})
-- Insert the highlights and register the autocommand if asked to.
local highlight = require'hop.highlight'
highlight.insert_highlights()
if M.opts.create_hl_autocmd then
highlight.create_autocmd()
end
end
return M
| 527
|
rish987/hop.nvim
|
registerNpc(394, {
walk_speed = 290,
run_speed = 670,
scale = 225,
r_weapon = 1036,
l_weapon = 0,
level = 112,
hp = 139,
attack = 643,
hit = 370,
def = 802,
res = 246,
avoid = 175,
attack_spd = 120,
is_magic_damage = 0,
ai_type = 132,
give_exp = 509,
drop_type = 385,
drop_money = 0,
drop_item = 99,
union_number = 99,
need_summon_count = 0,
sell_tab0 = 0,
sell_tab1 = 0,
sell_tab2 = 0,
sell_tab3 = 0,
can_target = 0,
attack_range = 250,
npc_type = 10,
hit_material_type = 1,
face_icon = 0,
summon_mob_type = 0,
quest_type = 0,
height = 0
});
function OnInit(entity)
return true
end
function OnCreate(entity)
return true
end
function OnDelete(entity)
return true
end
function OnDead(entity)
end
function OnDamaged(entity)
end
| 1,076
|
RavenX8/osirosenew
|
--[[
/////// //////////////////
/////// PROJECT: MTA iLife - German Fun Reallife Gamemode
/////// VERSION: 1.7.2
/////// DEVELOPERS: See DEVELOPERS.md in the top folder
/////// LICENSE: See LICENSE.md in the top folder
/////// /////////////////
]]
CInfoPickupManager = inherit(cSingleton)
function CInfoPickupManager:constructor()
local start = getTickCount()
local qh = CDatabase:getInstance():query("select * from infopickups")
for i,v in ipairs(qh) do
local infopickup = createPickup(v["X"],v["Y"],v["Z"],3,1239,0)
setElementInterior(infopickup,v["Int"])
setElementDimension(infopickup,v["Dim"])
enew(infopickup,CInfoPickup,v["ID"],v["X"],v["Y"],v["Z"],v["Int"],v["Dim"],v["Text"])
end
outputDebugString("Es wurden "..#InfoPickups.." Infopickups gefunden (" .. getTickCount() - start .. "ms)", 3)
end
| 828
|
Noneatme/iLife-SA
|
rifle_acid_beam = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "Acid beam",
directObjectTemplate = "object/weapon/ranged/rifle/rifle_acid_beam.iff",
craftingValues = {
{"mindamage",60,110,0},
{"maxdamage",170,360,0},
{"attackspeed",12.7,7.4,0},
{"woundchance",11,25,0},
{"hitpoints",750,750,0},
{"attackhealthcost",62,31,0},
{"attackactioncost",53,26,0},
{"attackmindcost",115,57,0},
{"roundsused",30,65,0},
{"zerorangemod",-70,-70,0},
{"maxrangemod",-10,15,0},
{"midrange",50,50,0},
{"midrangemod",10,10,0},
},
customizationStringNames = {},
customizationValues = {},
-- randomDotChance: The chance of this weapon object dropping with a random dot on it. Higher number means less chance. Set to 0 to always have a random dot.
randomDotChance = 1000,
junkDealerTypeNeeded = JUNKWEAPONS,
junkMinValue = 20,
junkMaxValue = 60
}
addLootItemTemplate("rifle_acid_beam", rifle_acid_beam)
| 937
|
V-Fib/FlurryClone
|
ESX = nil
Citizen.CreateThread(function()
while true do
Wait(5)
if ESX ~= nil then
else
ESX = nil
TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end)
end
end
end)
local Keys = {
["ESC"] = 322, ["F1"] = 288, ["F2"] = 289, ["F3"] = 170, ["F5"] = 166, ["F6"] = 167, ["F7"] = 168, ["F8"] = 169, ["F9"] = 56, ["F10"] = 57,
["~"] = 243, ["1"] = 157, ["2"] = 158, ["3"] = 160, ["4"] = 164, ["5"] = 165, ["6"] = 159, ["7"] = 161, ["8"] = 162, ["9"] = 163, ["-"] = 84, ["="] = 83, ["BACKSPACE"] = 177,
["TAB"] = 37, ["Q"] = 44, ["W"] = 32, ["E"] = 38, ["R"] = 45, ["T"] = 245, ["Y"] = 246, ["U"] = 303, ["P"] = 199, ["["] = 39, ["]"] = 40, ["ENTER"] = 18,
["CAPS"] = 137, ["A"] = 34, ["S"] = 8, ["D"] = 9, ["F"] = 23, ["G"] = 47, ["H"] = 74, ["K"] = 311, ["L"] = 182,
["LEFTSHIFT"] = 21, ["Z"] = 20, ["X"] = 73, ["C"] = 26, ["V"] = 0, ["B"] = 29, ["N"] = 249, ["M"] = 244, [","] = 82, ["."] = 81,
["LEFTCTRL"] = 36, ["LEFTALT"] = 19, ["SPACE"] = 22, ["RIGHTCTRL"] = 70,
["HOME"] = 213, ["PAGEUP"] = 10, ["PAGEDOWN"] = 11, ["DELETE"] = 178,
["LEFT"] = 174, ["RIGHT"] = 175, ["TOP"] = 27, ["DOWN"] = 173,
["NENTER"] = 201, ["N4"] = 108, ["N5"] = 60, ["N6"] = 107, ["N+"] = 96, ["N-"] = 97, ["N7"] = 117, ["N8"] = 61, ["N9"] = 118
}
local fishing = false
local lastInput = 0
local pause = false
local pausetimer = 0
local correct = 0
local bait = "none"
local blip = AddBlipForCoord(Config.SellFish.x, Config.SellFish.y, Config.SellFish.z)
SetBlipSprite (blip, 356)
SetBlipDisplay(blip, 4)
SetBlipScale (blip, 1.1)
SetBlipColour (blip, 17)
SetBlipAsShortRange(blip, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Fish selling")
EndTextCommandSetBlipName(blip)
local blip2 = AddBlipForCoord(Config.SellTurtle.x, Config.SellTurtle.y, Config.SellTurtle.z)
SetBlipSprite (blip2, 68)
SetBlipDisplay(blip2, 4)
SetBlipScale (blip2, 0.9)
SetBlipColour (blip2, 49)
SetBlipAsShortRange(blip2, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Sea Turtle dealer")
EndTextCommandSetBlipName(blip2)
local blip3 = AddBlipForCoord(Config.SellShark.x, Config.SellShark.y, Config.SellShark.z)
SetBlipSprite (blip3, 68)
SetBlipDisplay(blip3, 4)
SetBlipScale (blip3, 0.9)
SetBlipColour (blip3, 49)
SetBlipAsShortRange(blip3, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Shark meat dealer")
EndTextCommandSetBlipName(blip3)
for _, info in pairs(Config.MarkerZones) do
info.blip = AddBlipForCoord(info.x, info.y, info.z)
SetBlipSprite(info.blip, 455)
SetBlipDisplay(info.blip, 4)
SetBlipScale(info.blip, 1.0)
SetBlipColour(info.blip, 20)
SetBlipAsShortRange(info.blip, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString("Boat rental")
EndTextCommandSetBlipName(info.blip)
end
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
for k in pairs(Config.MarkerZones) do
DrawMarker(1, Config.MarkerZones[k].x, Config.MarkerZones[k].y, Config.MarkerZones[k].z, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 3.0, 1.0, 0, 150, 150, 100, 0, 0, 0, 0)
end
end
end)
function DisplayHelpText(str)
SetTextComponentFormat("STRING")
AddTextComponentString(str)
DisplayHelpTextFromStringLabel(0, 0, 1, -1)
end
Citizen.CreateThread(function()
while true do
Wait(600)
if pause and fishing then
pausetimer = pausetimer + 1
end
end
end)
Citizen.CreateThread(function()
while true do
Wait(5)
if fishing then
if IsControlJustReleased(0, Keys['1']) then
input = 1
end
if IsControlJustReleased(0, Keys['2']) then
input = 2
end
if IsControlJustReleased(0, Keys['3']) then
input = 3
end
if IsControlJustReleased(0, Keys['4']) then
input = 4
end
if IsControlJustReleased(0, Keys['5']) then
input = 5
end
if IsControlJustReleased(0, Keys['6']) then
input = 6
end
if IsControlJustReleased(0, Keys['7']) then
input = 7
end
if IsControlJustReleased(0, Keys['8']) then
input = 8
end
if IsControlJustReleased(0, Keys['X']) then
fishing = false
ESX.ShowNotification("~r~Stopped fishing")
end
if fishing then
playerPed = GetPlayerPed(-1)
local pos = GetEntityCoords(GetPlayerPed(-1))
if pos.y >= 7700 or pos.y <= -4000 or pos.x <= -3700 or pos.x >= 4300 or IsPedInAnyVehicle(GetPlayerPed(-1)) then
else
fishing = false
ESX.ShowNotification("~r~Stopped fishing")
end
if IsEntityDead(playerPed) or IsEntityInWater(playerPed) then
ESX.ShowNotification("~r~Stopped fishing")
end
end
if pausetimer > 3 then
input = 99
end
if pause and input ~= 0 then
pause = false
if input == correct then
TriggerServerEvent('fishing:catch', bait)
else
ESX.ShowNotification("~r~Fish got free")
end
end
end
if GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(-1)), Config.SellFish.x, Config.SellFish.y, Config.SellFish.z, true) <= 3 then
TriggerServerEvent('fishing:startSelling', "fish")
Citizen.Wait(4000)
end
if GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(-1)), Config.SellShark.x, Config.SellShark.y, Config.SellShark.z, true) <= 3 then
TriggerServerEvent('fishing:startSelling', "shark")
Citizen.Wait(4000)
end
if GetDistanceBetweenCoords(GetEntityCoords(GetPlayerPed(-1)), Config.SellTurtle.x, Config.SellTurtle.y, Config.SellTurtle.z, true) <= 3 then
TriggerServerEvent('fishing:startSelling', "turtle")
Citizen.Wait(4000)
end
end
end)
Citizen.CreateThread(function()
while true do
Wait(1)
DrawMarker(1, Config.SellFish.x, Config.SellFish.y, Config.SellFish.z , 0.0, 0.0, 0.0, 0, 0.0, 0.0, 3.0, 3.0, 2.0, 0, 70, 250, 30, false, true, 2, false, false, false, false)
DrawMarker(1, Config.SellTurtle.x, Config.SellTurtle.y, Config.SellTurtle.z , 0.0, 0.0, 0.0, 0, 0.0, 0.0, 3.0, 3.0, 2.0, 0, 70, 250, 30, false, true, 2, false, false, false, false)
DrawMarker(1, Config.SellShark.x, Config.SellShark.y, Config.SellShark.z, 0.0, 0.0, 0.0, 0, 0.0, 0.0, 3.0, 3.0, 2.0, 0, 70, 250, 30, false, true, 2, false, false, false, false)
end
end)
Citizen.CreateThread(function()
while true do
local wait = math.random(Config.FishTime.a , Config.FishTime.b)
Wait(wait)
if fishing then
pause = true
correct = math.random(1,8)
ESX.ShowNotification("~g~Fish is taking the bait \n ~h~Press " .. correct .. " to catch it")
input = 0
pausetimer = 0
end
end
end)
RegisterNetEvent('fishing:message')
AddEventHandler('fishing:message', function(message)
ESX.ShowNotification(message)
end)
RegisterNetEvent('fishing:break')
AddEventHandler('fishing:break', function()
fishing = false
ClearPedTasks(GetPlayerPed(-1))
end)
RegisterNetEvent('fishing:spawnPed')
AddEventHandler('fishing:spawnPed', function()
RequestModel( GetHashKey( "A_C_SharkTiger" ) )
while ( not HasModelLoaded( GetHashKey( "A_C_SharkTiger" ) ) ) do
Citizen.Wait( 1 )
end
local pos = GetEntityCoords(GetPlayerPed(-1))
local ped = CreatePed(29, 0x06C3F072, pos.x, pos.y, pos.z, 90.0, true, false)
SetEntityHealth(ped, 0)
end)
RegisterNetEvent('fishing:setbait')
AddEventHandler('fishing:setbait', function(bool)
bait = bool
print(bait)
end)
RegisterNetEvent('fishing:fishstart')
AddEventHandler('fishing:fishstart', function()
playerPed = GetPlayerPed(-1)
local pos = GetEntityCoords(GetPlayerPed(-1))
print('started fishing' .. pos)
if IsPedInAnyVehicle(playerPed) then
ESX.ShowNotification("~y~You can not fish from a vehicle")
else
if pos.y >= 7700 or pos.y <= -4000 or pos.x <= -3700 or pos.x >= 4300 then
ESX.ShowNotification("~g~Fishing started")
TaskStartScenarioInPlace(GetPlayerPed(-1), "WORLD_HUMAN_STAND_FISHING", 0, true)
fishing = true
else
ESX.ShowNotification("~y~You need to go further away from the shore")
end
end
end, false)
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
for k in pairs(Config.MarkerZones) do
local ped = PlayerPedId()
local pedcoords = GetEntityCoords(ped, false)
local distance = Vdist(pedcoords.x, pedcoords.y, pedcoords.z, Config.MarkerZones[k].x, Config.MarkerZones[k].y, Config.MarkerZones[k].z)
if distance <= 1.40 then
DisplayHelpText('Press E to rent a boat')
if IsControlJustPressed(0, Keys['E']) and IsPedOnFoot(ped) then
OpenBoatsMenu(Config.MarkerZones[k].xs, Config.MarkerZones[k].ys, Config.MarkerZones[k].zs)
end
elseif distance < 1.45 then
ESX.UI.Menu.CloseAll()
end
end
end
end)
function OpenBoatsMenu(x, y , z)
local ped = PlayerPedId()
PlayerData = ESX.GetPlayerData()
local elements = {}
table.insert(elements, {label = '<span style="color:green;">Dinghy</span> <span style="color:red;">2500$</span>', value = 'boat'})
table.insert(elements, {label = '<span style="color:green;">Suntrap</span> <span style="color:red;">3500$</span>', value = 'boat6'})
table.insert(elements, {label = '<span style="color:green;">Jetmax</span> <span style="color:red;">4500$</span>', value = 'boat5'})
table.insert(elements, {label = '<span style="color:green;">Toro</span> <span style="color:red;">5500$</span>', value = 'boat2'})
table.insert(elements, {label = '<span style="color:green;">Marquis</span> <span style="color:red;">6000$</span>', value = 'boat3'})
table.insert(elements, {label = '<span style="color:green;">Tug boat</span> <span style="color:red;">7500$</span>', value = 'boat4'})
--If user has police job they will be able to get free Police Predator boat
if PlayerData.job.name == "police" then
table.insert(elements, {label = '<span style="color:green;">Police Predator</span>', value = 'police'})
end
ESX.UI.Menu.CloseAll()
ESX.UI.Menu.Open(
'default', GetCurrentResourceName(), 'client',
{
title = 'Rent a boat',
align = 'bottom-right',
elements = elements,
},
function(data, menu)
if data.current.value == 'boat' then
ESX.UI.Menu.CloseAll()
TriggerServerEvent("fishing:lowmoney", 2500)
TriggerEvent("chatMessage", 'You rented a boat for', {255,0,255}, '$' .. 2500)
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "dinghy4")
end
if data.current.value == 'boat2' then
ESX.UI.Menu.CloseAll()
TriggerServerEvent("fishing:lowmoney", 5500)
TriggerEvent("chatMessage", 'You rented a boat for', {255,0,255}, '$' .. 5500)
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "TORO")
end
if data.current.value == 'boat3' then
ESX.UI.Menu.CloseAll()
TriggerServerEvent("fishing:lowmoney", 6000)
TriggerEvent("chatMessage", 'You rented a boat for', {255,0,255}, '$' .. 6000)
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "MARQUIS")
end
if data.current.value == 'boat4' then
ESX.UI.Menu.CloseAll()
TriggerServerEvent("fishing:lowmoney", 7500)
TriggerEvent("chatMessage", 'You rented a boat for', {255,0,255}, '$' .. 7500)
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "tug")
end
if data.current.value == 'boat5' then
ESX.UI.Menu.CloseAll()
TriggerServerEvent("fishing:lowmoney", 4500)
TriggerEvent("chatMessage", 'You rented a boat for', {255,0,255}, '$' .. 4500)
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "jetmax")
end
if data.current.value == 'boat6' then
ESX.UI.Menu.CloseAll()
TriggerServerEvent("fishing:lowmoney", 3500)
TriggerEvent("chatMessage", 'You rented a boat for', {255,0,255}, '$' .. 3500)
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "suntrap")
end
if data.current.value == 'police' then
ESX.UI.Menu.CloseAll()
TriggerEvent("chatMessage", 'You took out a boat')
SetPedCoordsKeepVehicle(ped, x, y , z)
TriggerEvent('esx:spawnVehicle', "predator")
end
ESX.UI.Menu.CloseAll()
end,
function(data, menu)
menu.close()
end
)
end
| 12,118
|
Proof93/Zero2HeroRP_ESX
|
local utils = require("rust-tools.utils.utils")
local util = vim.lsp.util
local config = require("rust-tools.config")
local M = {}
local function get_params()
return vim.lsp.util.make_position_params()
end
M._state = { winnr = nil, commands = nil }
local set_keymap_opt = { noremap = true, silent = true }
-- run the command under the cursor, if the thing under the cursor is not the
-- command then do nothing
function M._run_command()
local line = vim.api.nvim_win_get_cursor(M._state.winnr)[1]
if line > #M._state.commands then
return
end
local action = M._state.commands[line]
M._close_hover()
M.execute_rust_analyzer_command(action)
end
function M.execute_rust_analyzer_command(action)
local fn = vim.lsp.commands[action.command]
if fn then
fn(action)
end
end
function M._close_hover()
if M._state.winnr ~= nil then
vim.api.nvim_win_close(M._state.winnr, true)
end
end
local function parse_commands()
local prompt = {}
for i, value in ipairs(M._state.commands) do
if value.command == "rust-analyzer.gotoLocation" then
table.insert(
prompt,
string.format("%d. Go to %s (%s)", i, value.title, value.tooltip)
)
elseif value.command == "rust-analyzer.showReferences" then
table.insert(prompt, string.format("%d. %s", i, "Go to " .. value.title))
else
table.insert(prompt, string.format("%d. %s", i, value.title))
end
end
return prompt
end
function M.handler(_, result)
if not (result and result.contents) then
-- return { 'No information available' }
return
end
local markdown_lines = util.convert_input_to_markdown_lines(result.contents)
if result.actions then
M._state.commands = result.actions[1].commands
local prompt = parse_commands()
local l = {}
for _, value in ipairs(prompt) do
table.insert(l, value)
end
markdown_lines = vim.list_extend(l, markdown_lines)
end
markdown_lines = util.trim_empty_lines(markdown_lines)
if vim.tbl_isempty(markdown_lines) then
-- return { 'No information available' }
return
end
local bufnr, winnr = util.open_floating_preview(
markdown_lines,
"markdown",
vim.tbl_extend("keep", config.options.tools.hover_actions, {
focusable = true,
focus_id = "rust-tools-hover-actions",
close_events = { "CursorMoved", "BufHidden", "InsertCharPre" },
})
)
if config.options.tools.hover_actions.auto_focus then
vim.api.nvim_set_current_win(winnr)
end
if M._state.winnr ~= nil then
return
end
-- update the window number here so that we can map escape to close even
-- when there are no actions, update the rest of the state later
M._state.winnr = winnr
vim.api.nvim_buf_set_keymap(
bufnr,
"n",
"<Esc>",
":lua require'rust-tools.hover_actions'._close_hover()<CR>",
set_keymap_opt
)
vim.api.nvim_buf_attach(bufnr, false, {
on_detach = function()
M._state.winnr = nil
end,
})
--- stop here if there are no possible actions
if result.actions == nil then
return
end
-- makes more sense in a dropdown-ish ui
vim.api.nvim_win_set_option(winnr, "cursorline", true)
-- run the command under the cursor
vim.api.nvim_buf_set_keymap(
bufnr,
"n",
"<CR>",
":lua require'rust-tools.hover_actions'._run_command()<CR>",
set_keymap_opt
)
-- close on escape
vim.api.nvim_buf_set_keymap(
bufnr,
"n",
"<Esc>",
":lua require'rust-tools.hover_actions'._close_hover()<CR>",
set_keymap_opt
)
end
-- Sends the request to rust-analyzer to get hover actions and handle it
function M.hover_actions()
utils.request(0, "textDocument/hover", get_params(), M.handler)
end
return M
| 3,734
|
zmtq05/rust-tools.nvim
|
local Tunnel = module("vrp","lib/Tunnel")
local Proxy = module("vrp","lib/Proxy")
vRP = Proxy.getInterface("vRP")
--[ ARRAY ]------------------------------------------------------------------------------------------------------------------------------
local valores = {
{ item = "cafe", quantidade = 1, compra = 8 },
{ item = "cafecleite", quantidade = 1, compra = 10 },
{ item = "cafeexpresso", quantidade = 1, compra = 14 },
{ item = "capuccino", quantidade = 1, compra = 17 },
{ item = "frappuccino", quantidade = 1, compra = 18 },
{ item = "cha", quantidade = 1, compra = 9 },
{ item = "icecha", quantidade = 1, compra = 9 },
{ item = "sanduiche", quantidade = 1, compra = 12 },
{ item = "rosquinha", quantidade = 1, compra = 9 },
}
--[ COMPRAR ]----------------------------------------------------------------------------------------------------------------------------
RegisterServerEvent("cafeteria-comprar")
AddEventHandler("cafeteria-comprar",function(item)
local source = source
local user_id = vRP.getUserId(source)
if user_id then
for k,v in pairs(valores) do
if item == v.item then
if vRP.getInventoryWeight(user_id)+vRP.getItemWeight(v.item)*v.quantidade <= vRP.getInventoryMaxWeight(user_id) then
local preco = parseInt(v.compra)
if preco then
if vRP.hasPermission(user_id,"ultimate.permissao") then
desconto = math.floor(preco*20/100)
pagamento = math.floor(preco-desconto)
elseif vRP.hasPermission(user_id,"platinum.permissao") then
desconto = math.floor(preco*15/100)
pagamento = math.floor(preco-desconto)
elseif vRP.hasPermission(user_id,"gold.permissao") then
desconto = math.floor(preco*10/100)
pagamento = math.floor(preco-desconto)
elseif vRP.hasPermission(user_id,"standard.permissao") then
desconto = math.floor(preco*5/100)
pagamento = math.floor(preco-desconto)
else
pagamento = math.floor(preco)
end
if vRP.tryPayment(user_id,parseInt(pagamento)) then
TriggerClientEvent("Notify",source,"sucesso","Comprou <b>"..parseInt(v.quantidade).."x "..vRP.itemNameList(v.item).."</b> por <b>$"..vRP.format(parseInt(pagamento)).." dólares</b>.")
vRP.giveInventoryItem(user_id,v.item,parseInt(v.quantidade))
else
TriggerClientEvent("Notify",source,"negado","Dinheiro insuficiente.")
end
end
else
TriggerClientEvent("Notify",source,"negado","Espaço insuficiente.")
end
end
end
end
end)
| 2,503
|
brazucas/fivem-data
|
if mods['Krastorio2'] then
data:extend({
-- -- Basic science
{
type = "bool-setting",
name = "k2-automation-science-pack",
default_value = true,
setting_type = "startup",
order = "AA-AA-S1"
},
-- K2 extended science packs
{
type = "bool-setting",
name = "basic-tech-card",
default_value = true,
hidden = true,
forced_value = true,
setting_type = "startup",
order = "KK-K2-S1"
},
{
type = "bool-setting",
name = "matter-tech-card",
default_value = true,
setting_type = "startup",
order = "KK-K2-S2"
},
{
type = "bool-setting",
name = "advanced-tech-card",
default_value = true,
setting_type = "startup",
order = "KK-K2-S3"
},
{
type = "bool-setting",
name = "singularity-tech-card",
default_value = true,
setting_type = "startup",
order = "KK-K2-S4"
}
})
end
| 1,061
|
RedRafe/science-not-invited
|
--------------------------------------------------------------------------------
-- config.lua
--------------------------------------------------------------------------------
local aspectRatio = display.pixelHeight / display.pixelWidth
application = {
content = {
width = aspectRatio > 1.5 and 800 or math.ceil(1200 / aspectRatio),
height = aspectRatio < 1.5 and 1200 or math.ceil(800 * aspectRatio),
scale = "letterBox",
fps = 60,
imageSuffix = {
["@2x"] = 1.3
}
}
}
| 487
|
GymbylCoding/CBEffects
|
--[[ Copyright (C) 2018 Google Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
]]
local log = require 'common.log'
local asserts = require 'testing.asserts'
local test_runner = require 'testing.test_runner'
local function mockWriter(expectedText)
local writer = {
text = '',
expectedText = false,
messageWritten = false,
}
function writer:write(text)
if text == expectedText then
self.expectedText = true
end
self.text = self.text .. text
end
function writer:flush()
self.messageWritten = true
end
return writer
end
local tests = {}
function tests.info()
local writer = mockWriter('Hello')
log.setOutput(writer)
log.setLogLevel(log.NEVER)
log.info('Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.ERROR)
log.info('Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.WARN)
log.info('Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.INFO)
log.info('Hello')
assert(writer.messageWritten and writer.expectedText)
local writer2 = mockWriter('Hello2')
log.setOutput(writer2)
log.setLogLevel(1)
log.info('Hello2')
assert(writer2.messageWritten and writer2.expectedText)
end
function tests.warn()
local writer = mockWriter('Hello')
log.setOutput(writer)
log.setLogLevel(log.NEVER)
log.warn('Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.ERROR)
log.warn('Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.WARN)
log.warn('Hello')
assert(writer.messageWritten and writer.expectedText)
local writer2 = mockWriter('Hello2')
log.setOutput(writer2)
log.setLogLevel(log.INFO)
log.warn('Hello2')
assert(writer2.messageWritten and writer2.expectedText)
end
function tests.error()
local writer = mockWriter('Hello')
log.setOutput(writer)
log.setLogLevel(log.NEVER)
log.error('Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.ERROR)
log.error('Hello')
assert(writer.messageWritten and writer.expectedText)
local writer2 = mockWriter('Hello2')
log.setOutput(writer2)
log.setLogLevel(log.WARN)
log.error('Hello2')
assert(writer2.messageWritten and writer2.expectedText)
end
function tests.v()
local writer = mockWriter('Hello')
log.setOutput(writer)
log.setLogLevel(log.NEVER)
log.v(2, 'Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.ERROR)
log.v(2, 'Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.WARN)
log.v(2, 'Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(log.INFO)
log.v(2, 'Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(1)
log.v(2, 'Hello')
assert(not writer.messageWritten and not writer.expectedText)
log.setLogLevel(2)
log.v(2, 'Hello')
assert(writer.messageWritten and writer.expectedText)
end
function tests.infoToString()
local writer = mockWriter('25')
log.setOutput(writer)
log.setLogLevel(log.INFO)
log.info(25)
assert(writer.messageWritten and writer.expectedText)
end
return test_runner.run(tests)
| 3,962
|
xuyanbo03/lab
|
#!/usr/bin/env lua
return { -- MySQL
connect = {
name = 'MySQL-test',
user = 'luadbi',
pass = 'testing12345!!!',
},
encoding_test = {
{'unsigned', 12435212 },
{'unsigned', 463769 },
{'signed', 8574678 },
{'signed', -12435212 },
{'unsigned', 0 },
{'signed', 0 },
{'signed', 9998212 },
{'decimal(7,2)', 7653.25 },
{'decimal', 7635236 },
{'decimal(4,3)', 0.000 },
{'decimal(7,2)', -7653.25 },
{'decimal(9,5)', 1636.94783 },
{'char', "string 1" },
{'char(14)', "another_string" },
{'char', "really long string with some escapable chars: #&*%#;@'" },
},
placeholder = '?',
have_last_insert_id = false,
have_typecasts = true,
have_booleans = false,
have_rowcount = true
}
| 835
|
moteus/lua-odbc-dbi
|
---------------------------------------------------------------------------------------------------
-- User story: https://github.com/smartdevicelink/sdl_requirements/issues/2
-- Use case: https://github.com/smartdevicelink/sdl_requirements/blob/master/detailed_docs/current_module_status_data.md
-- Item: Use Case 1: Main Flow
--
-- Requirement summary:
-- [SDL_RC] Current module status data GetInteriorVehicleData
-- [SDL_RC] Policy support of basic RC functionality
--
-- Description:
-- In case:
-- 1) "moduleType" in app's assigned policies has an empty array
-- 2) and RC app sends GetInteriorVehicleData request with valid parameters
-- SDL must:
-- 1) Allow this RPC to be processed
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local runner = require('user_modules/script_runner')
local json = require('modules/json')
local common = require("test_scripts/RC/commonRC")
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
local function PTUfunc(tbl)
local appId = config.application1.registerAppInterfaceParams.fullAppID
tbl.policy_table.app_policies[appId] = common.getRCAppConfig()
tbl.policy_table.app_policies[appId].moduleType = json.EMPTY_ARRAY
end
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions, { false })
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("RAI", common.registerApp)
runner.Step("PTU", common.policyTableUpdate, { PTUfunc })
runner.Step("Activate App", common.activateApp)
runner.Title("Test")
for _, mod in pairs(common.modulesWithoutSeat) do
runner.Step("GetInteriorVehicleData " .. mod, common.rpcAllowed, { mod, 1, "GetInteriorVehicleData" })
end
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
| 1,872
|
ychernysheva/sdl_atf_test_scripts
|
--[[
desc:
* Container, be responsible for saving object.
* CAREFULLY: Container isn't object's upper, it doesn't manage object.
author: Musoucrow
since: 2018-3-11
alter: 2019-8-19
]]--
---@param start int @defalut=1
local function _RefreshTransfer(self, start)
start = start or 1
for n=start, #self._transfer.list do
self._transfer.map[self._transfer.list[n]] = n
end
end
---@param tag string
---@param order int
local function _Remove(self, tag, order)
table.remove(self._list, order)
table.remove(self._transfer.list, order)
if (tag) then
self._map[tag] = nil
self._transfer.map[tag] = nil
end
_RefreshTransfer(self, order)
end
---@class Core.Container
---@field public _list list
---@field public _map map
---@field protected _transfer Core.Container.Transfer
---@field protected _willClean boolean
local _Container = require("core.class")()
function _Container:Ctor()
self._list = {}
self._map = {}
---@class Core.Container.Transfer
self._transfer = {
list = {},
map = {}
}
self._willClean = false
end
---@param name string
function _Container:RunEvent_All(name, ...)
for n in ipairs(self._list) do
self._list[n][name](self._list[n], ...)
end
end
---@param tag string
---@param name string
function _Container:RunEvent_Member(tag, name, ...)
self._map[tag][name](self._map[tag], ...)
end
---@param obj table
---@param tag string
---@param order int
function _Container:Add(obj, tag, order)
if (tag and self._map[tag]) then
self:Del(tag)
end
local max = #self._list + 1
order = order or max
if (order > max) then
order = max
end
table.insert(self._list, order, obj)
if (tag) then
table.insert(self._transfer.list, order, tag)
self._map[tag] = obj
end
_RefreshTransfer(self, order)
end
---@param tag string
function _Container:Del(tag)
local order = self._transfer.map[tag]
if (order) then
_Remove(self, tag, order)
end
end
function _Container:DelWithIndex(index)
local tag = self._transfer.list[index]
if (tag) then
_Remove(self, tag, index)
end
end
---@param tag string
---@return table
function _Container:Get(tag)
return self._map[tag]
end
function _Container:GetWithIndex(index)
return self._list[index]
end
---@return int
function _Container:GetLength()
return #self._list
end
function _Container:Iter()
local index = 0
return function()
index = index + 1
return self._list[index], self._transfer.list[index], index
end
end
function _Container:Pairs()
return pairs(self._map)
end
---@param Func function
function _Container:Sort(Func)
for n=1, #self._list-1 do
for m=1, #self._list-n do
if (not Func(self._list[m], self._list[m+1])) then -- For compatibility with table.sort
local tmp = self._list[m]
self._list[m] = self._list[m+1]
self._list[m+1] = tmp
if (self._transfer.list[m] and self._transfer.list[m+1]) then
tmp = self._transfer.list[m]
self._transfer.list[m] = self._transfer.list[m+1]
self._transfer.list[m+1] = tmp
tmp = self._transfer.map[self._transfer.list[m]]
self._transfer.map[self._transfer.list[m]] = self._transfer.map[self._transfer.list[m+1]]
self._transfer.map[self._transfer.list[m+1]] = tmp
end
end
end
end
end
function _Container:TryClean()
if (self._willClean) then
for n=#self._list, 1, -1 do
if (self._list[n].HasDestroyed and self._list[n]:HasDestroyed()) then
_Remove(self, self._transfer.list[n], n)
end
end
self._willClean = not self._willClean
end
end
function _Container:ReadyClean()
self._willClean = true
end
function _Container:Print() --For test.
for n=1, #self._transfer.list do
print (self._transfer.list[n], self._transfer.map[self._transfer.list[n]])
end
end
function _Container:DelAll()
self._list = {}
self._map = {}
self._transfer = {
list = {},
map = {}
}
end
return _Container
| 3,848
|
LeomRonald/DFQ-Original
|
local assert = assert
do --- local
local a, b, c
a, b, c = 0, 1
assert(a == 0)
assert(b == 1)
assert(c == nil)
a, b = a+1, b+1, a+b
assert(a == 1)
assert(b == 2)
a, b, c = 0
assert(a == 0)
assert(b == nil)
assert(c == nil)
end
do --- global !private_G
a, b, c = 0, 1
assert(a == 0)
assert(b == 1)
assert(c == nil)
a, b = a+1, b+1, a+b
assert(a == 1)
assert(b == 2)
a, b, c = 0
assert(a == 0)
assert(b == nil)
assert(c == nil)
end
do --- local lhs in key on lhs
local a = {}
local i = 3
i, a[i] = i+1, 20
assert(i == 4)
assert(a[3] == 20)
end
do --- global lhs in key on lhs !private_G
a = {}
i = 3
i, a[i] = i+1, 20
assert(i == 4)
assert(a[3] == 20)
end
| 724
|
DemiMarie/LuaJIT-test-cleanup
|
-- Copyright © 2016 Silv3r <silv3r@proshine-bot.com>
-- This work is free. You can redistribute it and/or modify it under the
-- terms of the Do What The Fuck You Want To Public License, Version 2,
-- as published by Sam Hocevar. See the LICENSE file for more details.
name = "Leveling: Route 20 (near Cinnabar)"
author = "Silv3r"
description = [[This script will train the first pokémon of your team.
It will also try to capture shinies by throwing pokéballs.
Start anywhere between Cinnabar Island and Route 20.
You need a pokémon with surf.]]
function onPathAction()
if isPokemonUsable(1) then
if getMapName() == "Pokecenter Cinnabar" then
moveToMap("Cinnabar Island")
elseif getMapName() == "Cinnabar Island" then
moveToMap("Route 20")
elseif getMapName() == "Route 20" then
moveToWater()
end
else
if getMapName() == "Route 20" then
moveToMap("Cinnabar Island")
elseif getMapName() == "Cinnabar Island" then
moveToMap("Pokecenter Cinnabar")
elseif getMapName() == "Pokecenter Cinnabar" then
usePokecenter()
end
end
end
function onBattleAction()
if isWildBattle() and isOpponentShiny() then
if useItem("Ultra Ball") or useItem("Great Ball") or useItem("Pokeball") then
return
end
end
if getActivePokemonNumber() == 1 then
return attack() or run() or sendUsablePokemon() or sendAnyPokemon()
else
return run() or attack() or sendUsablePokemon() or sendAnyPokemon()
end
end
| 1,430
|
liquid8796/ProScript
|
local tbTable = GameMain:GetMod("_SkillScript")
local tbSkill = tbTable:GetSkill("ZSZY")
function tbSkill:Cast(skilldef, from)
end
function tbSkill:Apply(skilldef, key, from)
end
function tbSkill:FightBodyApply(skilldef, fightbody, from)
if fightbody and fightbody.Npc then
local npc = fightbody.Npc
npc:AddModifier("ZSZY")
end
end
function tbSkill:MissileBomb(skilldef, pos, from)
end
function tbSkill:GetValueAddv(skilldef, fightbody, from)
return self.power
end
function tbSkill:FlyCheck(skilldef, keys, from)
return 0
end
| 574
|
xArshy/Skycoveringworld
|
--- ATLAS PARK
local spawnOnce = false
-- Called after MOTD for now.
function player_connected(id)
--Id is player entity Id
printDebug('player_connected Id: ' .. tostring(id))
Tasks.UpdateTasksForZone('Atlas Park')
Contacts.SpawnContacts('Atlas Park')
if spawnOnce == false then
--spinners gather location data
spinSpawners()
spinPersists()
spinCivilians()
spinCars()
--RandomSpawns attempt #x creations of the type (encounter is default)
RandomSpawn(45)
RandomSpawn(80, "Civilians")
RandomSpawn(30, "Cars")
spawnOnce = true
print("Initiating map auto-refresh")
MapInstance.SetOnTickCallback(contactsForZone.TimeCop.entityId, contactsForZone.TimeCop.onTickCallBack);
TimeCopMode(true, 45, 120)
end
return ''
end
function npc_added(id)
printDebug('npc_added Id: ' .. tostring(id))
Contacts.SpawnedContact(id)
-- Spawn next contact
Contacts.SpawnContacts('Atlas Park')
return ''
end
entity_interact = function(id, location)
Contacts.SetContactDialogsWithHeroName(heroName)
if location ~= nil then
printDebug("entity id " .. tostring(id) .. " location info: x: " .. tostring(location.x) .. " y: " .. tostring(location.y) .. " z: " .. tostring(location.z))
else
printDebug("entity id " .. tostring(id))
end
if(Contacts.OpenContactDialog(id) ~= true) then
-- Generic NPC
-- Create generic NPC message script for zone?
end
--[[ NPC chat message test
MapClientSession.npcMessage(client, 'Hello Hero!', id)
MapClientSession.npcMessage(client, 'What are you doing here?', id)
]]
return ""
end
dialog_button = function(id) -- Will be called if no callback is set
printDebug("No Callback set! ButtonId: " .. tostring(id))
return ""
end
contact_call = function(contactIndex)
printDebug("Contact Call. contactIndex: " .. tostring(contactIndex))
return ""
end
revive_ok = function(id)
printDebug("revive Ok. Entity: " .. tostring(id))
Character.respawn(client, 'Gurney'); -- Hospital
Player.Revive(0);
return "ok"
end
| 2,189
|
cat4hurricane/Segs
|
--[[
- util.lua
- Handy module containing various functions for game development in lua,
particularly with Love2D.
- Authored by Thomas Smallridge (sundowns)
- https://github.com/sundowns/lua-utils
MIT LICENSE
Copyright (c) 2011 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
local meta = {
__index = function(table, key)
if key == "l" then
return rawget(table, "love")
elseif key == "m" then
return rawget(table, "maths")
elseif key == "t" then
return rawget(table, "table")
elseif key == "f" then
return rawget(table, "file")
elseif key == "d" then
return rawget(table, "debug")
elseif key == "s" then
return rawget(table, "string")
else
return rawget(table, key)
end
end;
}
local util = {}
util.love = {}
util.maths = {}
util.table = {}
util.file = {}
util.debug = {}
util.string = {}
setmetatable(util, meta)
---------------------- TABLES
function util.table.print(table, name)
print("==================")
if not table then
print("<EMPTY TABLE>")
return
end
if type(table) ~= "table" then
assert(false,"Attempted to print NON-TABLE TYPE: "..type(table))
return
end
if name then print("Printing table: " .. name) end
deepprint(table)
end
function deepprint(table, depth)
local d = depth or 0
local spacer = ""
for i=0,d do
spacer = spacer.." "
end
for k, v in pairs(table) do
if type(v) == "table" then
print(spacer.."["..k.."]:")
deepprint(v, d + 1)
else
print(spacer.."[" .. tostring(k) .. "]: " .. tostring(v))
end
end
end
function util.table.concat(t1,t2)
for i=1,#t2 do
t1[#t1+1] = t2[i]
end
return t1
end
-- Recursively creates a copy of the given table.
-- Not my code, taken from: https://www.youtube.com/watch?v=dZ_X0r-49cw#t=9m30s
function util.table.copy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[util.table.copy(orig_key)] = util.table.copy(orig_value)
end
else
copy = orig
end
return copy
end
--sums two tables of numbers together
function util.table.sum (t1, t2)
local result = {}
for key, val in pairs(t1) do
result[key] = (result[key] or 0) + val
end
for key, val in pairs(t2) do
result[key] = (result[key] or 0) + val
end
return result
end;
---------------------- MATHS
function util.maths.roundToNthDecimal(num, n)
local mult = 10^(n or 0)
return math.floor(num * mult + 0.5) / mult
end
function util.maths.withinVariance(val1, val2, variance)
local diff = math.abs(val1 - val2)
if diff < variance then
return true
else
return false
end
end
function util.maths.clamp(val, min, max)
assert(min < max, "Minimum value must be less than maximum when clamping values.")
if min - val > 0 then
return min
end
if max - val < 0 then
return max
end
return val
end
function util.maths.midpoint(x1, y1, x2, y2)
assert(x1 and y1 and x2 and y2, "Received invalid input to util.maths.midpoint")
return (x2+x1)/2, (y2+y1)/2
end
function util.maths.jitterBy(value, spread)
assert(love, "This function uses love.math.random for the time being")
return value + love.math.random(-1*spread, spread)
end
--Taken from: https://love2d.org/wiki/HSV_color
function util.maths.HSVtoRGB255(hue, sat, val)
if sat <= 0 then return val,val,val end
local h, s, v = hue/256*6, sat/255, val/255
local c = v*s
local x = (1-math.abs((h%2)-1))*c
local m,r,g,b = (v-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)*255,(g+m)*255,(b+m)*255
end
--Taken from: https://love2d.org/wiki/HSV_color
function util.maths.HSVtoRGB(hue, sat, val)
if sat <= 0 then return val,val,val end
local h, s, v = hue/256*6, sat/255, val/255
local c = v*s
local x = (1-math.abs((h%2)-1))*c
local m,r,g,b = (v-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
function util.maths.distanceBetween(x1, y1, x2, y2)
return math.sqrt(((x2 - x1)^2) + ((y2 - y1)^2))
end
---------------------- DEBUG
function util.debug.log(text)
if debug then
print(text)
end
end
---------------------- FILE
function util.file.exists(name)
if love then assert(false, "Not to be used in love games, use love.filesystem.getInfo") end
local f=io.open(name,"r")
if f~=nil then io.close(f) return true else return false end
end
function util.file.getLuaFileName(url)
return string.gsub(url, ".lua", "")
end
---------------------- LOVE2D
function util.love.resetColour()
love.graphics.setColor(1,1,1,1)
end
function util.love.renderStats(x, y)
if not x then x = 0 end
if not y then y = 0 end
local stats = love.graphics.getStats()
love.graphics.print("texture memory (MB): ".. stats.texturememory / 1024 / 1024, x, y)
love.graphics.print("drawcalls: ".. stats.drawcalls, x, y+20)
love.graphics.print("canvasswitches: ".. stats.canvasswitches , x, y+40)
love.graphics.print("images loaded: ".. stats.images, x, y+60)
love.graphics.print("canvases loaded: ".. stats.canvases, x, y+80)
love.graphics.print("fonts loaded: ".. stats.fonts, x, y+100)
end
if not love then util.love = nil end
---------------------- STRING
function util.string.randomString(l)
if l < 1 then return nil end
local stringy=""
for i=1,l do
stringy=stringy..util.string.randomLetter()
end
return stringy
end
function util.string.randomLetter()
return string.char(math.random(97, 122));
end
return util
| 6,953
|
sundowns/grim-gamers
|
-- Copyright 2008 Yanira <forum-2008@email.de>
-- Licensed to the public under the Apache License 2.0.
require("nixio.fs")
m = Map("hd-idle", translate("HDD Idle"),
translate("HDD Idle is a utility program for spinning-down external " ..
"disks after a period of idle time."))
s = m:section(TypedSection, "hd-idle", translate("Settings"))
s.anonymous = true
s:option(Flag, "enabled", translate("Enable"))
disk = s:option(Value, "disk", translate("Disk"))
disk.rmempty = true
for dev in nixio.fs.glob("/dev/[sh]d[a-z]") do
disk:value(nixio.fs.basename(dev))
end
s:option(Value, "idle_time_interval", translate("Idle time")).default = 10
s.rmempty = true
unit = s:option(ListValue, "idle_time_unit", translate("Idle time unit"))
unit.default = "minutes"
unit:value("minutes", translate("min"))
unit:value("hours", translate("h"))
unit.rmempty = true
return m
| 868
|
spiccinini/luci
|
shaders = require("core.shaders")
BaseEntity = require("entities.core.baseentity")
NPCBullet = require("entities.npcbullet")
Goomba = require("entities.core.goomba")
Gorilla = class("Gorilla", Goomba)
Gorilla.spritesheet = SpriteSheet:new("sprites/gorilla.png", 32, 32)
function Gorilla:initialize()
Goomba.initialize(self)
-- control variables
self.type = "NPC"
self.collisiongroup = "shared"
self.attackDelay = 0
self.reloadDelay = 1.5
self.clipsize = 3
self.cone = 40 -- in radians
self.health = 500 -- health
self.range = 250 -- range of attack
self.shootFacingPlayer = false -- shoot only facing player
self.canAim = false -- can it aim at the player?
self.stopBeforeShooting = true
self.bulletOffsetX = 20
self.bulletOffsetY = -12
-- no touchy
self.attackAnim = 0
end
function Gorilla:update(dt)
Goomba.update(self, dt)
if self.nextReload <= 0.3 and self.attackAnim <= 0 then
self.attackAnim = 0.75
end
self.attackAnim = self.attackAnim - dt
end
function Gorilla:draw()
self.anim = 7 + math.floor(love.timer.getTime() * 10)%6
if self.attackAnim > 0 then
local a = math.floor((1 - (self.attackAnim / 0.75)) * 7) % 7
self.anim = a
end
love.graphics.scale(2, 2)
love.graphics.scale(-self.ang, 1)
self.spritesheet:draw(self.anim, 0, -16, -21)
if self.lastDamaged > 0 then
love.graphics.setStencil(function ()
love.graphics.setShader(shaders.mask_effect)
self.spritesheet:draw(self.anim, 0, -16, -21)
love.graphics.setShader()
end)
love.graphics.setColor(255, 255, 255, 255)
love.graphics.rectangle("fill", -16, -21, 32, 32)
love.graphics.setStencil()
end
end
return Gorilla
| 1,830
|
qwook/dpsht
|
--[[----------------------------------------------------------------------------
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
------------------------------------------------------------------------------]]
local tnt = require 'torchnet'
require 'donkey'
-- create an instance of DataSetJSON to make roidb and scoredb
-- that are passed to threads
local roidb, scoredb
do
local ds = loadDataSet(opt)
ds:loadROIDB(opt.best_proposals_number)
roidb, scoredb = ds.roidb, ds.scoredb
end
local loader = createTrainLoader(opt, roidb, scoredb, 1)
local bbox_regr = loader:setupData()
g_mean_std = bbox_regr
local opt = tnt.utils.table.clone(opt)
local function getIterator()
return tnt.ParallelDatasetIterator{
nthread = opt.nDonkeys,
init = function(idx)
require 'torchnet'
require 'donkey'
torch.manualSeed(opt.manualSeed + idx)
g_donkey_idx = idx
end,
closure = function()
local loaders = {}
for i=1,(opt.integral and opt.nDonkeys or 1) do
loaders[i] = createTrainLoader(opt, roidb, scoredb, i)
end
for i,v in ipairs(loaders) do
v.bbox_regr = bbox_regr
end
return tnt.ListDataset{
list = torch.range(1,opt.epochSize):long(),
load = function(idx)
return {loaders[torch.random(#loaders)]:sample()}
end,
}
end,
}
end
return getIterator
| 1,695
|
wanyenlo/multipathnet
|
-- @start
-- @namespace com.github.mounthuaguo.mongkeyking.lua
-- @version 0.1
-- @name Base64 Encode
-- @description Base64 encode and decode
-- @author heramerom
-- @type action
-- @action Copy With Base64 Encode
-- @action Copy With Base64 Decode
-- @action Replace With Base64 Encode
-- @action Replace With Base64 Decode
-- @action Output With Base64 Encode
-- @action Output With Base64 Decode
-- @require https://raw.githubusercontent.com/toastdriven/lua-base64/master/base64.lua
-- @end
function inputText()
local text = event.selectionModel.selectedText
if text == nil or text == '' then
toast.warn('Please select text')
return nil
end
return text
end
if menu == 'Copy With Base64 Encode' then
local text = inputText()
if not text then
return
end
clipboard.setContents(to_base64(text))
toast.info('Copied!')
end
if menu == 'Copy With Base64 Decode' then
local text = inputText()
if not text then
return
end
clipboard.setContents(from_base64(text))
toast.info('Copied!')
end
if menu == 'Replace With Base64 Encode' then
local text = inputText()
if not text then
return
end
event.document.replaceString(
action.selectionModel.selectionStart,
action.selectionModel.selectionEnd,
to_base64(text))
end
if menu == 'Replace With Base64 Decode' then
local text = inputText()
if not text then
return
end
event.document.replaceString(
action.selectionModel.selectionStart,
action.selectionModel.selectionEnd,
from_base64(text))
end
if menu == 'Output With Base64 Encode' then
local text = inputText()
if not text then
return
end
print(to_base64(text))
end
if menu == 'Output With Base64 Decode' then
local text = inputText()
if not text then
return
end
print(from_base64(text))
end
| 1,986
|
Mount-Huaguo/MonkeyKingScripts
|
local geezifylua = require('geezifylua')
local test_data = require('test_case')
describe('arabify', function()
it('should convert every geez number in the test data to its equivalent arab number', function()
for i,v in ipairs(test_data) do
print(v[2])
assert.equal(geezifylua.arabify.arabify(v[2]), v[1])
end
end)
end)
| 412
|
yilkalargaw/geezify-lua
|
include("shared.lua")
function ENT:Draw()
local ret = hook.Call("onDrawSpawnedWeapon", nil, self)
if ret ~= nil then return end
self:DrawModel()
if self.dt.amount == 1 then return end
local Pos = self:GetPos()
local Ang = self:GetAngles()
local text = FrenchRP.getPhrase("amount") .. self.dt.amount
surface.SetFont("HUDNumber5")
local TextWidth = surface.GetTextSize(text)
Ang:RotateAroundAxis(Ang:Forward(), 90)
cam.Start3D2D(Pos + Ang:Up(), Ang, 0.11)
draw.WordBox(2, 0, -40, text, "HUDNumber5", Color(140, 0, 0, 100), Color(255,255,255,255))
cam.End3D2D()
Ang:RotateAroundAxis(Ang:Right(), 180)
cam.Start3D2D(Pos + Ang:Up() * 3, Ang, 0.11)
draw.WordBox(2, -TextWidth, -40, text, "HUDNumber5", Color(140, 0, 0, 100), Color(255,255,255,255))
cam.End3D2D()
end
/*---------------------------------------------------------------------------
Create a shipment from a spawned_weapon
---------------------------------------------------------------------------*/
properties.Add("createShipment",
{
MenuLabel = "Create a shipment",
Order = 2002,
MenuIcon = "icon16/add.png",
Filter = function(self, ent, ply)
if not IsValid(ent) then return false end
return ent.IsSpawnedWeapon
end,
Action = function(self, ent)
if not IsValid(ent) then return end
RunConsoleCommand("frenchrp", "makeshipment", ent:EntIndex())
end
})
/*---------------------------------------------------------------------------
Interface
---------------------------------------------------------------------------*/
FrenchRP.hookStub{
name = "onDrawSpawnedWeapon",
description = "Draw spawned weapons.",
realm = "Client",
parameters = {
{
name = "weapon",
description = "The weapon to perform drawing operations on.",
type = "Player"
}
},
returns = {
{
name = "value",
description = "Return a value to completely override drawing",
type = "any"
}
}
}
| 2,218
|
Sxcret/FrenchRP
|
WireLib = WireLib or {}
local pairs = pairs
local setmetatable = setmetatable
local rawget = rawget
local next = next
local IsValid = IsValid
local LocalPlayer = LocalPlayer
local Entity = Entity
local string = string
local hook = hook
-- extra table functions
-- Returns a noniterable version of tbl. So indexing still works, but pairs(tbl) won't find anything
-- Useful for hiding entity lookup tables, since Garrydupe uses util.TableToJSON, which crashes on tables with entity keys
function table.MakeNonIterable(tbl)
return setmetatable({}, { __index = tbl, __setindex = tbl})
end
-- Checks if the table is empty, it's faster than table.Count(Table) > 0
function table.IsEmpty(Table)
return (next(Table) == nil)
end
-- Compacts an array by rejecting entries according to cb.
function table.Compact(tbl, cb, n)
n = n or #tbl
local cpos = 1
for i = 1, n do
if cb(tbl[i]) then
tbl[cpos] = tbl[i]
cpos = cpos + 1
end
end
local new_n = cpos-1
while (cpos <= n) do
tbl[cpos] = nil
cpos = cpos + 1
end
end
-- I don't even know if I need this one.
-- HUD indicator needs this one
function table.MakeSortedKeys(tbl)
local result = {}
for k,_ in pairs(tbl) do table.insert(result, k) end
table.sort(result)
return result
end
-- works like pairs() except that it iterates sorted by keys.
-- criterion is optional and should be a function(a,b) returning whether a is less than b. (same as table.sort's criterions)
function pairs_sortkeys(tbl, criterion)
tmp = {}
for k,v in pairs(tbl) do table.insert(tmp,k) end
table.sort(tmp, criterion)
local iter, state, index, k = ipairs(tmp)
return function()
index,k = iter(state, index)
if index == nil then return nil end
return k,tbl[k]
end
end
-- sorts by values
function pairs_sortvalues(tbl, criterion)
local crit = criterion and
function(a,b)
return criterion(tbl[a],tbl[b])
end
or
function(a,b)
return tbl[a] < tbl[b]
end
tmp = {}
tbl = tbl or {}
for k,v in pairs(tbl) do table.insert(tmp,k) end
table.sort(tmp, crit)
local iter, state, index, k = ipairs(tmp)
return function()
index,k = iter(state, index)
if index == nil then return nil end
return k,tbl[k]
end
end
-- like ipairs, except it maps the value with mapfunction before returning.
function ipairs_map(tbl, mapfunction)
local iter, state, k = ipairs(tbl)
return function(state, k)
local v
k,v = iter(state, k)
if k == nil then return nil end
return k,mapfunction(v)
end, state, k
end
-- like pairs, except it maps the value with mapfunction before returning.
function pairs_map(tbl, mapfunction)
local iter, state, k = pairs(tbl)
return function(state, k)
local v
k,v = iter(state, k)
if k == nil then return nil end
return k,mapfunction(v)
end, state, k
end
-- end extra table functions
local table = table
local pairs_sortkeys = pairs_sortkeys
local pairs_sortvalues = pairs_sortvalues
local ipairs_map = ipairs_map
local pairs_map = pairs_map
--------------------------------------------------------------------------------
do -- containers
local function new(metatable, ...)
local tbl = {}
setmetatable(tbl, metatable)
local init = metatable.Initialize
if init then init(tbl, ...) end
return tbl
end
local function newclass(container_name)
meta = { new = new }
meta.__index = meta
WireLib.containers[container_name] = meta
return meta
end
WireLib.containers = { new = new, newclass = newclass }
do -- class deque
local deque = newclass("deque")
function deque:Initialize()
self.offset = 0
end
function deque:size()
return #self-self.offset
end
-- Prepends the given element.
function deque:unshift(value)
if offset < 1 then
-- TODO: improve
table.insert(self, 1, value)
return
end
self.offset = self.offset - 1
self[self.offset+1] = value
end
-- Removes the first element and returns it
function deque:shift()
--do return table.remove(self, 1) end
local offset = self.offset + 1
local ret = self[offset]
if not ret then self.offset = offset-1 return nil end
self.offset = offset
if offset > 127 then
for i = offset+1,#self-offset do
self[i-offset] = self[i]
end
for i = #self-offset+1,#self do
self[i-offset],self[i] = self[i],nil
end
self.offset = 0
end
return ret
end
-- Appends the given element.
function deque:push(value)
self[#self+1] = value
end
-- Removes the last element and returns it.
function deque:pop()
local ret = self[#self]
self[#self] = nil
return ret
end
-- Returns the last element.
function deque:top()
return self[#self]
end
-- Returns the first element.
function deque:bottom()
return self[self.offset+1]
end
end -- class deque
do -- class autocleanup
local autocleanup = newclass("autocleanup")
function autocleanup:Initialize(depth, parent, parentindex)
rawset(self, "depth", depth or 0)
rawset(self, "parent", parent)
rawset(self, "parentindex", parentindex)
rawset(self, "data", {})
end
function autocleanup:__index(index)
local data = rawget(self, "data")
local element = data[index]
if element then return element end
local depth = rawget(self, "depth")
if depth == 0 then return nil end
element = new(autocleanup, depth-1, self, index)
return element
end
function autocleanup:__newindex(index, value)
local data = rawget(self, "data")
local parent = rawget(self, "parent")
local parentindex = rawget(self, "parentindex")
if value ~= nil and not next(data) and parent then parent[parentindex] = self end
data[index] = value
if value == nil and not next(data) and parent then parent[parentindex] = nil end
end
function autocleanup:__pairs()
local data = rawget(self, "data")
return pairs(data)
end
pairs_ac = autocleanup.__pairs
end -- class autocleanup
end -- containers
--------------------------------------------------------------------------------
--[[ wire_addnotify: send notifications to the client
WireLib.AddNotify([ply, ]Message, Type, Duration[, Sound])
If ply is left out, the notification is sent to everyone. If Sound is left out, no sound is played.
On the client, only the local player can be notified.
]]
do
-- The following sounds can be used:
NOTIFYSOUND_NONE = 0 -- optional, default
NOTIFYSOUND_DRIP1 = 1
NOTIFYSOUND_DRIP2 = 2
NOTIFYSOUND_DRIP3 = 3
NOTIFYSOUND_DRIP4 = 4
NOTIFYSOUND_DRIP5 = 5
NOTIFYSOUND_ERROR1 = 6
NOTIFYSOUND_CONFIRM1 = 7
NOTIFYSOUND_CONFIRM2 = 8
NOTIFYSOUND_CONFIRM3 = 9
NOTIFYSOUND_CONFIRM4 = 10
if CLIENT then
local sounds = {
[NOTIFYSOUND_DRIP1 ] = "ambient/water/drip1.wav",
[NOTIFYSOUND_DRIP2 ] = "ambient/water/drip2.wav",
[NOTIFYSOUND_DRIP3 ] = "ambient/water/drip3.wav",
[NOTIFYSOUND_DRIP4 ] = "ambient/water/drip4.wav",
[NOTIFYSOUND_DRIP5 ] = "ambient/water/drip5.wav",
[NOTIFYSOUND_ERROR1 ] = "buttons/button10.wav",
[NOTIFYSOUND_CONFIRM1] = "buttons/button3.wav",
[NOTIFYSOUND_CONFIRM2] = "buttons/button14.wav",
[NOTIFYSOUND_CONFIRM3] = "buttons/button15.wav",
[NOTIFYSOUND_CONFIRM4] = "buttons/button17.wav",
}
function WireLib.AddNotify(ply, Message, Type, Duration, Sound)
if isstring(ply) then
Message, Type, Duration, Sound = ply, Message, Type, Duration
elseif ply ~= LocalPlayer() then
return
end
GAMEMODE:AddNotify(Message, Type, Duration)
if Sound and sounds[Sound] then surface.PlaySound(sounds[Sound]) end
end
net.Receive("wire_addnotify", function(netlen)
local Message = net.ReadString()
local Type = net.ReadUInt(8)
local Duration = net.ReadFloat()
local Sound = net.ReadUInt(8)
WireLib.AddNotify(LocalPlayer(), Message, Type, Duration, Sound)
end)
elseif SERVER then
NOTIFY_GENERIC = 0
NOTIFY_ERROR = 1
NOTIFY_UNDO = 2
NOTIFY_HINT = 3
NOTIFY_CLEANUP = 4
util.AddNetworkString("wire_addnotify")
function WireLib.AddNotify(ply, Message, Type, Duration, Sound)
if isstring(ply) then ply, Message, Type, Duration, Sound = nil, ply, Message, Type, Duration end
if ply && !ply:IsValid() then return end
net.Start("wire_addnotify")
net.WriteString(Message)
net.WriteUInt(Type or 0,8)
net.WriteFloat(Duration)
net.WriteUInt(Sound or 0,8)
if ply then net.Send(ply) else net.Broadcast() end
end
end
end -- wire_addnotify
--[[ wire_clienterror: displays Lua errors on the client
Usage: WireLib.ClientError("Hello", ply)
]]
if CLIENT then
net.Receive("wire_clienterror", function(netlen)
local message = net.ReadString()
print("sv: "..message)
local lines = string.Explode("\n", message)
for i,line in ipairs(lines) do
if i == 1 then
WireLib.AddNotify(line, NOTIFY_ERROR, 7, NOTIFYSOUND_ERROR1)
else
WireLib.AddNotify(line, NOTIFY_ERROR, 7)
end
end
end)
elseif SERVER then
util.AddNetworkString("wire_clienterror")
function WireLib.ClientError(message, ply)
net.Start("wire_clienterror")
net.WriteString(message)
net.Send(ply)
end
end
function WireLib.ErrorNoHalt(message)
-- ErrorNoHalt clips messages to 512 characters, so chain calls if necessary
for i=1,#message, 511 do
ErrorNoHalt(message:sub(i,i+510))
end
end
--[[ wire_netmsg system
A basic framework for entities that should send newly connecting players data
Server requirements: ENT:Retransmit(ply) -- Should send all data to one player
Client requirements:
WireLib.netRegister(self) in ENT:Initialize()
ENT:Receive()
To send:
function ENT:Retransmit(ply)
WireLib.netStart(self) -- This automatically net.WriteEntity(self)'s
net.Write*...
WireLib.netEnd(ply) -- you can pass a Player or a table of players to only send to some clients, otherwise it broadcasts
end
To receive:
function ENT:Receive()
net.Read*...
end
To unregister: WireLib.netUnRegister(self) -- Happens automatically on entity removal
]]
if SERVER then
util.AddNetworkString("wire_netmsg_register")
util.AddNetworkString("wire_netmsg_registered")
function WireLib.netStart(self)
net.Start("wire_netmsg_registered")
net.WriteEntity(self)
end
function WireLib.netEnd(ply)
if ply then net.Send(ply) else net.Broadcast() end
end
net.Receive("wire_netmsg_register", function(netlen, ply)
local self = net.ReadEntity()
if IsValid(self) and self.Retransmit then self:Retransmit(ply) end
end)
elseif CLIENT then
function WireLib.netRegister(self)
net.Start("wire_netmsg_register") net.WriteEntity(self) net.SendToServer()
end
net.Receive("wire_netmsg_registered", function(netlen)
local self = net.ReadEntity()
if IsValid(self) and self.Receive then self:Receive() end
end)
end
--[[ wire_ports: client-side input/output names/types/descs
umsg format:
any number of the following:
Char start
start==0: break
start==-1: delete inputs
start==-2: delete outputs
start==-3: set eid
start==-4: connection state
start > 0:
Char amount
abs(amount)*3 strings describing name, type, desc
]]
-- Checks if the entity has wire ports.
-- Works for every entity that has wire in-/output.
-- Very important and useful for checks!
function WireLib.HasPorts(ent)
if (ent.IsWire) then return true end
if (ent.Base == "base_wire_entity") then return true end
-- Checks if the entity is in the list, it checks if the entity has self.in-/outputs too.
local In, Out = WireLib.GetPorts(ent)
if (In and (ent.Inputs or CLIENT)) then return true end
if (Out and (ent.Outputs or CLIENT)) then return true end
return false
end
if SERVER then
local INPUT,OUTPUT = 1,-1
local DELETE,PORT,LINK = 1,2,3
local ents_with_inputs = {}
local ents_with_outputs = {}
--local IOlookup = { [INPUT] = ents_with_inputs, [OUTPUT] = ents_with_outputs }
util.AddNetworkString("wire_ports")
timer.Create("Debugger.PoolTypeStrings",1,1,function()
if WireLib.Debugger and WireLib.Debugger.formatPort then
for typename,_ in pairs(WireLib.Debugger.formatPort) do util.AddNetworkString(typename) end -- Reduce bandwidth
end
end)
local queue = {}
function WireLib.GetPorts(ent)
local eid = ent:EntIndex()
return ents_with_inputs[eid], ents_with_outputs[eid]
end
function WireLib._RemoveWire(eid, DontSend) -- To remove the inputs without to remove the entity. Very important for IsWire checks!
local hasinputs, hasoutputs = ents_with_inputs[eid], ents_with_outputs[eid]
if hasinputs or hasoutputs then
ents_with_inputs[eid] = nil
ents_with_outputs[eid] = nil
if not DontSend then
net.Start("wire_ports")
net.WriteInt(-3, 8) -- set eid
net.WriteUInt(eid, 16) -- entity id
if hasinputs then net.WriteInt(-1, 8) end -- delete inputs
if hasoutputs then net.WriteInt(-2, 8) end -- delete outputs
net.WriteInt(0, 8) -- break
net.Broadcast()
end
end
end
hook.Add("EntityRemoved", "wire_ports", function(ent)
if not ent:IsPlayer() then
WireLib._RemoveWire(ent:EntIndex())
end
end)
function WireLib._SetInputs(ent, lqueue)
local queue = lqueue or queue
local eid = ent:EntIndex()
if not ents_with_inputs[eid] then ents_with_inputs[eid] = {} end
queue[#queue+1] = { eid, DELETE, INPUT }
for Name, CurPort in pairs_sortvalues(ent.Inputs, WireLib.PortComparator) do
local entry = { Name, CurPort.Type, CurPort.Desc or "" }
ents_with_inputs[eid][#ents_with_inputs[eid]+1] = entry
queue[#queue+1] = { eid, PORT, INPUT, entry, CurPort.Num }
end
for Name, CurPort in pairs_sortvalues(ent.Inputs, WireLib.PortComparator) do
WireLib._SetLink(CurPort, lqueue)
end
end
function WireLib._SetOutputs(ent, lqueue)
local queue = lqueue or queue
local eid = ent:EntIndex()
if not ents_with_outputs[eid] then ents_with_outputs[eid] = {} end
queue[#queue+1] = { eid, DELETE, OUTPUT }
for Name, CurPort in pairs_sortvalues(ent.Outputs, WireLib.PortComparator) do
local entry = { Name, CurPort.Type, CurPort.Desc or "" }
ents_with_outputs[eid][#ents_with_outputs[eid]+1] = entry
queue[#queue+1] = { eid, PORT, OUTPUT, entry, CurPort.Num }
end
end
function WireLib._SetLink(input, lqueue)
local ent = input.Entity
local num = input.Num
local state = input.SrcId and true or false
local queue = lqueue or queue
local eid = ent:EntIndex()
queue[#queue+1] = {eid, LINK, num, state}
end
local eid = 0
local numports, firstportnum, portstrings = {}, {}, {}
local function writeCurrentStrings()
-- Write the current (input or output) string information
for IO=OUTPUT,INPUT,2 do -- so, k= -1 and k= 1
if numports[IO] then
net.WriteInt(firstportnum[IO], 8) -- Control code for inputs/outputs is also the offset (the first port number we're writing over)
net.WriteUInt(numports[IO], 8) -- Send number of ports
net.WriteBit(IO==OUTPUT)
for i=1,numports[IO]*3 do net.WriteString(portstrings[IO][i] or "") end
numports[IO] = nil
end
end
end
local function writemsg(msg)
-- First write a signed int for the command code
-- Then sometimes write extra data specific to the command (type varies)
if msg[1] ~= eid then
eid = msg[1]
writeCurrentStrings() -- We're switching to talking about a different entity, lets send port information
net.WriteInt(-3,8)
net.WriteUInt(eid,16)
end
local msgtype = msg[2]
if msgtype == DELETE then
numports[msg[3]] = nil
net.WriteInt(msg[3] == INPUT and -1 or -2, 8)
elseif msgtype == PORT then
local _,_,IO,entry,num = unpack(msg)
if not numports[IO] then
firstportnum[IO] = num
numports[IO] = 0
portstrings[IO] = {}
end
local i = numports[IO]*3
portstrings[IO][i+1] = entry[1]
portstrings[IO][i+2] = entry[2]
portstrings[IO][i+3] = entry[3]
numports[IO] = numports[IO]+1
elseif msgtype == LINK then
local _,_,num,state = unpack(msg)
net.WriteInt(-4, 8)
net.WriteUInt(num, 8)
net.WriteBit(state)
end
end
local function FlushQueue(lqueue, ply)
// Zero these two for the writemsg function
eid = 0
numports = {}
net.Start("wire_ports")
for i=1,#lqueue do
writemsg(lqueue[i])
end
writeCurrentStrings()
net.WriteInt(0,8)
if ply then net.Send(ply) else net.Broadcast() end
end
hook.Add("Think", "wire_ports", function()
if not next(queue) then return end
FlushQueue(queue)
queue = {}
end)
hook.Add("PlayerInitialSpawn", "wire_ports", function(ply)
local lqueue = {}
for eid, entry in pairs(ents_with_inputs) do
WireLib._SetInputs(Entity(eid), lqueue)
end
for eid, entry in pairs(ents_with_outputs) do
WireLib._SetOutputs(Entity(eid), lqueue)
end
FlushQueue(lqueue, ply)
end)
elseif CLIENT then
local ents_with_inputs = {}
local ents_with_outputs = {}
net.Receive("wire_ports", function(netlen)
local eid = 0
local connections = {} -- In case any cmd -4's come in before link strings
while true do
local cmd = net.ReadInt(8)
if cmd == 0 then
break
elseif cmd == -1 then
ents_with_inputs[eid] = nil
elseif cmd == -2 then
ents_with_outputs[eid] = nil
elseif cmd == -3 then
eid = net.ReadUInt(16)
elseif cmd == -4 then
connections[#connections+1] = {eid, net.ReadUInt(8), net.ReadBit() ~= 0} -- Delay this process till after the loop
elseif cmd > 0 then
local entry
local amount = net.ReadUInt(8)
if net.ReadBit() ~= 0 then
-- outputs
entry = ents_with_outputs[eid]
if not entry then
entry = {}
ents_with_outputs[eid] = entry
end
else
-- inputs
entry = ents_with_inputs[eid]
if not entry then
entry = {}
ents_with_inputs[eid] = entry
end
end
local endindex = cmd+amount-1
for i = cmd,endindex do
entry[i] = {net.ReadString(), net.ReadString(), net.ReadString()}
end
end
end
for i=1, #connections do
local eid, num, state = unpack(connections[i])
local entry = ents_with_inputs[eid]
if not entry then
entry = {}
ents_with_inputs[eid] = entry
elseif entry[num] then
entry[num][4] = state
end
end
end)
function WireLib.GetPorts(ent)
local eid = ent:EntIndex()
return ents_with_inputs[eid], ents_with_outputs[eid]
end
function WireLib._RemoveWire(eid) -- To remove the inputs without to remove the entity.
ents_with_inputs[eid] = nil
ents_with_outputs[eid] = nil
end
local flag = false
function WireLib.TestPorts()
flag = not flag
if flag then
local lasteid = 0
hook.Add("HUDPaint", "wire_ports_test", function()
local ent = LocalPlayer():GetEyeTraceNoCursor().Entity
--if not ent:IsValid() then return end
local eid = IsValid(ent) and ent:EntIndex() or lasteid
lasteid = eid
local text = "ID "..eid.."\nInputs:\n"
for num,name,tp,desc,connected in ipairs_map(ents_with_inputs[eid] or {}, unpack) do
text = text..(connected and "-" or " ")
text = text..string.format("%s (%s) [%s]\n", name, tp, desc)
end
text = text.."\nOutputs:\n"
for num,name,tp,desc in ipairs_map(ents_with_outputs[eid] or {}, unpack) do
text = text..string.format("%s (%s) [%s]\n", name, tp, desc)
end
draw.DrawText(text,"Trebuchet24",10,300,Color(255,255,255,255),0)
end)
else
hook.Remove("HUDPaint", "wire_ports_test")
end
end
end
-- For transmitting the yellow lines showing links between controllers and ents, as used by the Adv Entity Marker
if SERVER then
util.AddNetworkString("WireLinkedEnts")
function WireLib.SendMarks(controller, marks)
if not IsValid(controller) or not (controller.Marks or marks) then return end
net.Start("WireLinkedEnts")
net.WriteEntity(controller)
net.WriteUInt(#(controller.Marks or marks), 16)
for k,v in pairs(controller.Marks or marks) do
net.WriteEntity(v)
end
net.Broadcast()
end
else
net.Receive("WireLinkedEnts", function(netlen)
local Controller = net.ReadEntity()
if IsValid(Controller) then
Controller.Marks = {}
for i=1, net.ReadUInt(16) do
local link = net.ReadEntity()
if IsValid(link) then
table.insert(Controller.Marks, link)
end
end
end
end)
end
--[[
Returns the "distance" between two strings
ie the amount of character swaps you have to do to get the first string to equal the second
Example:
levenshtein( "test", "toast" ) returns 2, because two steps: 'e' swapped to 'o', and 'a' is added
Very useful for searching algorithms
Used by custom spawn menu search & gate tool search, for example
Credits go to: http://lua-users.org/lists/lua-l/2009-07/msg00461.html
]]
function WireLib.levenshtein( s, t )
local d, sn, tn = {}, #s, #t
local byte, min = string.byte, math.min
for i = 0, sn do d[i * tn] = i end
for j = 0, tn do d[j] = j end
for i = 1, sn do
local si = byte(s, i)
for j = 1, tn do
d[i*tn+j] = min(d[(i-1)*tn+j]+1, d[i*tn+j-1]+1, d[(i-1)*tn+j-1]+(si == byte(t,j) and 0 or 1))
end
end
return d[#d]
end
--[[
nicenumber
by Divran
Adds several functions to format numbers into millions, billions, etc
Adds a function to format a number (assumed seconds) into a duration (weeks, days, hours, minutes, seconds, etc)
This is used, for example, by the wire screen.
]]
WireLib.nicenumber = {}
local nicenumber = WireLib.nicenumber
local numbers = {
{
name = "septillion",
short = "sep",
symbol = "Y",
prefix = "yotta",
zeroes = 10^24,
},
{
name = "sextillion",
short = "sex",
symbol = "Z",
prefix = "zetta",
zeroes = 10^21,
},
{
name = "quintillion",
short = "quint",
symbol = "E",
prefix = "exa",
zeroes = 10^18,
},
{
name = "quadrillion",
short = "quad",
symbol = "P",
prefix = "peta",
zeroes = 10^15,
},
{
name = "trillion",
short = "T",
symbol = "T",
prefix = "tera",
zeroes = 10^12,
},
{
name = "billion",
short = "B",
symbol = "B",
prefix = "giga",
zeroes = 10^9,
},
{
name = "million",
short = "M",
symbol = "M",
prefix = "mega",
zeroes = 10^6,
},
{
name = "thousand",
short = "K",
symbol = "K",
prefix = "kilo",
zeroes = 10^3
}
}
local one = {
name = "ones",
short = "",
symbol = "",
prefix = "",
zeroes = 1
}
-- returns a table of tables that inherit from the above info
local floor = math.floor
local min = math.min
function nicenumber.info( n, steps )
if not n or n < 0 then return {} end
if n > 10 ^ 300 then n = 10 ^ 300 end
local t = {}
steps = steps or #numbers
local displayones = true
local cursteps = 0
for i = 1, #numbers do
local zeroes = numbers[i].zeroes
local nn = floor(n / zeroes)
if nn > 0 then
cursteps = cursteps + 1
if cursteps > steps then break end
t[#t+1] = setmetatable({value = nn},{__index = numbers[i]})
n = n % numbers[i].zeroes
displayones = false
end
end
if n >= 0 and displayones then
t[#t+1] = setmetatable({value = n},{__index = one})
end
return t
end
local sub = string.sub
-- returns string
-- example 12B 34M
function nicenumber.format( n, steps )
local t = nicenumber.info( n, steps )
steps = steps or #numbers
local str = ""
for i=1,#t do
if i > steps then break end
str = str .. t[i].value .. t[i].symbol .. " "
end
return sub( str, 1, -2 ) -- remove trailing space
end
-- returns string with decimals
-- example 12.34B
local round = math.Round
function nicenumber.formatDecimal( n, decimals )
local t = nicenumber.info( n, 1 )
decimals = decimals or 2
local largest = t[1]
if largest then
n = n / largest.zeroes
return round( n, decimals ) .. largest.symbol
else
return "0"
end
end
-------------------------
-- nicetime
-------------------------
local floor = math.floor
local times = {
{ "y", 31556926 }, -- years
{ "mon", 2629743.83 }, -- months
{ "w", 604800 }, -- weeks
{ "d", 86400 }, -- days
{ "h", 3600 }, -- hours
{ "m", 60 }, -- minutes
{ "s", 1 }, -- seconds
}
function nicenumber.nicetime( n )
n = math.abs( n )
if n == 0 then return "0s" end
local prev_name = ""
local prev_val = 0
for i=1,#times do
local name = times[i][1]
local num = times[i][2]
local temp = floor(n / num)
if temp > 0 or prev_name ~= "" then
if prev_name ~= "" then
return prev_val .. prev_name .. " " .. temp .. name
else
prev_name = name
prev_val = temp
n = n % num
end
end
end
if prev_name ~= "" then
return prev_val .. prev_name
else
return "0s"
end
end
| 24,256
|
Python1320/wire
|
-- https://github.com/windwp/nvim-autopairs
require("nvim-autopairs").setup()
| 78
|
brucelee07/nvim-config
|
--[[
# 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: Minecraft
version: 1
description: Online game.
--]]
require "DetectorCommon"
local DC = DetectorCommon
local FT = flowTrackerModule
DetectorPackageInfo = {
name = "Minecraft",
proto = DC.ipproto.tcp,
client = {
init = 'client_init',
clean = 'client_clean',
validate = 'client_validate',
minimum_matches = 1
}
}
gSfAppIdMinecraft = 1802
gPatterns = {
init = { '\019\000\047\013', 0, gSfAppIdMinecraft},
second = { '\008\000\006\086\048\109\105\099\097', 0, gSfAppIdMinecraft}
}
gFastPatterns = {
{DC.ipproto.tcp, gPatterns.init},
}
gAppRegistry = {
--AppIdValue Extracts Info
---------------------------------------
{gSfAppIdMinecraft, 0}
}
--contains detector specific data related to a flow
flowTrackerTable = {}
function clientInProcess(context)
DC.printf('minecraft client: Inprocess Client, packetCount: %d\n', context.packetCount)
return DC.clientStatus.inProcess
end
function clientSuccess(context)
context.detectorFlow:setFlowFlag(DC.flowFlags.clientAppDetected)
DC.printf('minecraft client: Detected Client, packetCount: %d\n', context.packetCount)
gDetector:client_addApp(appServiceId, appTypeId, appProductId, "", gSfAppIdMinecraft);
return DC.clientStatus.success
end
function clientFail(context)
DC.printf('minecraft client: Failed Client, packetCount: %d\n', context.packetCount)
return DC.clientStatus.einvalid
end
--[[ Core engine calls DetectorInit() to initialize a detector.
--]]
function client_init( detectorInstance, configOptions)
gDetector = detectorInstance
DC.printf ('%s:DetectorInit()\n', DetectorPackageInfo.name)
gDetector:client_init()
appTypeId = 19
appProductId = 469
appServiceId = 20192
DC.printf ('%s:DetectorValidator(): appTypeId %d, product %d, service %d\n', DetectorPackageInfo.name, appTypeId, appProductId, appServiceId)
--register pattern based detection
for i,v in ipairs(gFastPatterns) do
if ( gDetector:client_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', DetectorPackageInfo.name,v[2][1])
else
DC.printf ('%s: register pattern successful for %s\n', DetectorPackageInfo.name,v[2][1])
end
end
for i,v in ipairs(gAppRegistry) do
pcall(function () gDetector:registerAppId(v[1],v[2]) end)
end
return gDetector
end
--[[Validator function registered in DetectorInit()
--]]
function client_validate()
local context = {}
context.detectorFlow = gDetector:getFlow()
context.packetCount = gDetector:getPktCount()
context.packetSize = gDetector:getPacketSize()
context.packetDir = gDetector:getPacketDir()
context.flowKey = context.detectorFlow:getFlowKey()
context.srcPort = gDetector:getPktSrcPort()
context.dstPort = gDetector:getPktDstPort()
local size = context.packetSize
local dir = context.packetDir
local flowKey = context.flowKey
DC.printf ('minecraft client packetCount %d dir %d, size %d\n', context.packetCount, dir, size)
local rft = FT.getFlowTracker(flowKey)
if (not rft) then
DC.printf ('minecraft client adding ft for flowKey %s\n', flowKey)
rft = FT.addFlowTracker(flowKey, {p=1})
end
if (rft.p == 1 and size >= 20) then
rft.p = 2
DC.printf ('minecraft client first packet\n')
return clientInProcess(context)
end
if (rft.p == 2 and
gDetector:memcmp(gPatterns.second[1], #gPatterns.second[1], gPatterns.second[2]) == 0) then
DC.printf ('got minecraft client\n')
FT.delFlowTracker(flowKey)
return clientSuccess(context)
end
FT.delFlowTracker(flowKey)
return clientFail(context)
end
function client_clean()
end
| 4,954
|
Snur/proxySSL
|
bristleback_bristleback_lua = class({})
LinkLuaModifier( "modifier_bristleback_bristleback_lua", "lua_abilities/bristleback_bristleback_lua/modifier_bristleback_bristleback_lua", LUA_MODIFIER_MOTION_NONE )
--------------------------------------------------------------------------------
-- Passive Modifier
function bristleback_bristleback_lua:GetIntrinsicModifierName()
return "modifier_bristleback_bristleback_lua"
end
| 422
|
GIANTCRAB/dota-2-lua-abilities
|
function onStepIn(cid, item, position, fromPosition)
level = 150
if getPlayerLevel(cid) < level then
doTeleportThing(cid, fromPosition, true)
doSendMagicEffect(getThingPos(cid), CONST_ME_MAGIC_RED)
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_RED, "Somente level " .. level .. " ou mais podem passar aqui.")
end
if item.actionid == 19456 then
end
return TRUE
end
| 384
|
Renanziinz/Otziinz
|
local K, C, L, _ = select(2, ...):unpack()
if C["Loot"].rolllootframe ~= true then return end
local unpack = unpack
local pairs = pairs
local time = time
local CreateFrame, UIParent = CreateFrame, UIParent
local IsShiftKeyDown = IsShiftKeyDown
local GetLootRollTimeLeft = GetLootRollTimeLeft
-- Based on teksLoot(by Tekkub)
local pos = "TOP"
local frames = {}
local cancelled_rolls = {}
local rolltypes = {"need", "greed", "disenchant", [0] = "pass"}
local LootRollAnchor = CreateFrame("Frame", "LootRollAnchor", UIParent)
LootRollAnchor:SetSize(313, 26)
local function ClickRoll(frame)
RollOnLoot(frame.parent.rollid, frame.rolltype)
end
local function HideTip() GameTooltip:Hide() end
local function HideTip2() GameTooltip:Hide() ResetCursor() end
local function SetTip(frame)
GameTooltip:SetOwner(frame, "ANCHOR_TOPLEFT")
GameTooltip:SetText(frame.tiptext)
if frame:IsEnabled() == 0 then GameTooltip:AddLine("|cffff3333"..L_LOOT_CANNOT) end
for name, roll in pairs(frame.parent.rolls) do if roll == rolltypes[frame.rolltype] then GameTooltip:AddLine(name, 1, 1, 1) end end
GameTooltip:Show()
end
local function SetItemTip(frame)
if not frame.link then return end
GameTooltip:SetOwner(frame, "ANCHOR_TOPLEFT")
GameTooltip:SetHyperlink(frame.link)
if IsShiftKeyDown() then GameTooltip_ShowCompareItem() end
if IsModifiedClick("DRESSUP") then ShowInspectCursor() else ResetCursor() end
end
local function ItemOnUpdate(self)
if IsShiftKeyDown() then GameTooltip_ShowCompareItem() end
CursorOnUpdate(self)
end
local function LootClick(frame)
if IsControlKeyDown() then DressUpItemLink(frame.link)
elseif IsShiftKeyDown() then ChatEdit_InsertLink(frame.link) end
end
local function OnEvent(frame, event, rollid)
cancelled_rolls[rollid] = true
if frame.rollid ~= rollid then return end
frame.rollid = nil
frame.time = nil
frame:Hide()
end
local function StatusUpdate(frame)
if not frame.parent.rollid then return end
local t = GetLootRollTimeLeft(frame.parent.rollid)
local perc = t / frame.parent.time
frame:SetValue(t)
end
local function CreateRollButton(parent, ntex, ptex, htex, rolltype, tiptext, ...)
local f = CreateFrame("Button", nil, parent)
f:SetPoint(...)
f:SetSize(28, 28)
f:SetNormalTexture(ntex)
if ptex then f:SetPushedTexture(ptex) end
f:SetHighlightTexture(htex)
f.rolltype = rolltype
f.parent = parent
f.tiptext = tiptext
f:SetScript("OnEnter", SetTip)
f:SetScript("OnLeave", HideTip)
f:SetScript("OnClick", ClickRoll)
f:SetMotionScriptsWhileDisabled(true)
local txt = f:CreateFontString(nil, nil)
txt:SetFont(C["Media"].Font, C["Media"].Font_Size, C["Media"].Font_Style)
txt:SetShadowOffset((K.Mult or 1), -(K.Mult or 1))
txt:SetPoint("CENTER", 0, rolltype == 2 and 1 or rolltype == 0 and -1.2 or 0)
return f, txt
end
local function CreateRollFrame()
local frame = CreateFrame("Frame", nil, UIParent)
K.CreateBorder(frame, 10, 2)
frame:SetBackdrop(K.BorderBackdrop)
frame:SetBackdropColor(unpack(C["Media"].Backdrop_Color))
frame:SetSize(280, 22)
frame:SetFrameStrata("MEDIUM")
frame:SetFrameLevel(10)
frame:SetScript("OnEvent", OnEvent)
frame:RegisterEvent("CANCEL_LOOT_ROLL")
frame:Hide()
local button = CreateFrame("Button", nil, frame)
button:SetPoint("LEFT", -29, 0)
button:SetSize(22, 22)
K.CreateBorder(button, 10, 2)
button:SetBackdrop(K.BorderBackdrop)
button:SetBackdropColor(unpack(C["Media"].Backdrop_Color))
button:SetScript("OnEnter", SetItemTip)
button:SetScript("OnLeave", HideTip2)
button:SetScript("OnUpdate", ItemOnUpdate)
button:SetScript("OnClick", LootClick)
frame.button = button
button.icon = button:CreateTexture(nil, "OVERLAY")
button.icon:SetAllPoints()
button.icon:SetTexCoord(0.1, 0.9, 0.1, 0.9)
local status = CreateFrame("StatusBar", nil, frame)
status:SetSize(326, 20)
status:SetPoint("TOPLEFT", 0, 0)
status:SetPoint("BOTTOMRIGHT", 0, 0)
status:SetScript("OnUpdate", StatusUpdate)
status:SetFrameLevel(status:GetFrameLevel() - 1)
status:SetStatusBarTexture(C["Media"].Texture)
status:SetStatusBarColor(0.8, 0.8, 0.8, 0.9)
status.parent = frame
frame.status = status
status.bg = status:CreateTexture(nil, "BACKGROUND")
status.bg:SetAlpha(0.1)
status.bg:SetAllPoints()
status.bg:SetDrawLayer("BACKGROUND", 2)
local need, needtext = CreateRollButton(frame, "Interface\\Buttons\\UI-GroupLoot-Dice-Up", "Interface\\Buttons\\UI-GroupLoot-Dice-Highlight", "Interface\\Buttons\\UI-GroupLoot-Dice-Down", 1, NEED, "LEFT", frame.button, "RIGHT", 5, -1)
local greed, greedtext = CreateRollButton(frame, "Interface\\Buttons\\UI-GroupLoot-Coin-Up", "Interface\\Buttons\\UI-GroupLoot-Coin-Highlight", "Interface\\Buttons\\UI-GroupLoot-Coin-Down", 2, GREED, "LEFT", need, "RIGHT", 0, -1)
local de, detext = CreateRollButton(frame, "Interface\\Buttons\\UI-GroupLoot-DE-Up", "Interface\\Buttons\\UI-GroupLoot-DE-Highlight", "Interface\\Buttons\\UI-GroupLoot-DE-Down", 3, ROLL_DISENCHANT, "LEFT", greed, "RIGHT", 0, -1)
local pass, passtext = CreateRollButton(frame, "Interface\\Buttons\\UI-GroupLoot-Pass-Up", nil, "Interface\\Buttons\\UI-GroupLoot-Pass-Down", 0, PASS, "LEFT", de or greed, "RIGHT", 0, 2.2)
frame.needbutt, frame.greedbutt, frame.disenchantbutt = need, greed, de
frame.need, frame.greed, frame.pass, frame.disenchant = needtext, greedtext, passtext, detext
local bind = frame:CreateFontString()
bind:SetPoint("LEFT", pass, "RIGHT", 3, 1)
bind:SetFont(C["Media"].Font, C["Media"].Font_Size, C["Media"].Font_Style)
bind:SetShadowOffset((K.Mult or 1), -(K.Mult or 1))
frame.fsbind = bind
local loot = frame:CreateFontString(nil, "ARTWORK")
loot:SetFont(C["Media"].Font, C["Media"].Font_Size, C["Media"].Font_Style)
loot:SetShadowOffset((K.Mult or 1), -(K.Mult or 1))
loot:SetPoint("LEFT", bind, "RIGHT", 0, 0)
loot:SetPoint("RIGHT", frame, "RIGHT", -5, 0)
loot:SetSize(200, 10)
loot:SetJustifyH("LEFT")
frame.fsloot = loot
frame.rolls = {}
return frame
end
local function GetFrame()
for i, f in ipairs(frames) do
if not f.rollid then return f end
end
local f = CreateRollFrame()
if pos == "TOP" then
f:SetPoint("TOPRIGHT", next(frames) and frames[#frames] or LootRollAnchor, "BOTTOMRIGHT", next(frames) and 0 or -2, next(frames) and -7 or -5)
else
f:SetPoint("BOTTOMRIGHT", next(frames) and frames[#frames] or LootRollAnchor, "TOPRIGHT", next(frames) and 0 or -2, next(frames) and 7 or 5)
end
table.insert(frames, f)
return f
end
local function START_LOOT_ROLL(rollid, time)
if cancelled_rolls[rollid] then return end
local f = GetFrame()
f.rollid = rollid
f.time = time
for i in pairs(f.rolls) do f.rolls[i] = nil end
f.need:SetText(0)
f.greed:SetText(0)
f.pass:SetText(0)
f.disenchant:SetText(0)
local texture, name, count, quality, bop, canNeed, canGreed, canDisenchant = GetLootRollItemInfo(rollid)
f.button.icon:SetTexture(texture)
f.button.link = GetLootRollItemLink(rollid)
if C["Loot"].auto_greed and K.Level == MAX_PLAYER_LEVEL and quality == 2 and not bop then return end
if canNeed then f.needbutt:Enable() else f.needbutt:Disable() end
if canGreed then f.greedbutt:Enable() else f.greedbutt:Disable() end
if canDisenchant then f.disenchantbutt:Enable() else f.disenchantbutt:Disable() end
SetDesaturation(f.needbutt:GetNormalTexture(), not canNeed)
SetDesaturation(f.greedbutt:GetNormalTexture(), not canGreed)
SetDesaturation(f.disenchantbutt:GetNormalTexture(), not canDisenchant)
if canNeed then f.needbutt:SetAlpha(1) else f.needbutt:SetAlpha(0.2) end
if canGreed then f.greedbutt:SetAlpha(1) else f.greedbutt:SetAlpha(0.2) end
if canDisenchant then f.disenchantbutt:SetAlpha(1) else f.disenchantbutt:SetAlpha(0.2) end
f.fsbind:SetText(bop and "BoP" or "BoE")
f.fsbind:SetVertexColor(bop and 1 or 0.3, bop and 0.3 or 1, bop and 0.1 or 0.3)
local color = ITEM_QUALITY_COLORS[quality]
f.fsloot:SetVertexColor(color.r, color.g, color.b)
f.fsloot:SetText(name)
f:SetBackdropBorderColor(color.r, color.g, color.b, 1)
f.button:SetBackdropBorderColor(color.r, color.g, color.b, 1)
f.status:SetStatusBarColor(color.r, color.g, color.b, 0.7)
f.status:SetMinMaxValues(0, time)
f.status:SetValue(time)
f:SetPoint("CENTER", WorldFrame, "CENTER")
f:Show()
end
local locale = GetLocale()
local rollpairs = locale == "deDE" and {
["(.*) passt automatisch bei (.+), weil [ersie]+ den Gegenstand nicht benutzen kann.$"] = "pass",
["(.*) würfelt nicht für: (.+|r)$"] = "pass",
["(.*) hat für (.+) 'Gier' ausgewählt"] = "greed",
["(.*) hat für (.+) 'Bedarf' ausgewählt"] = "need",
["(.*) hat für '(.+)' Entzauberung gewählt."] = "disenchant",
} or locale == "frFR" and {
["(.*) a passé pour : (.+) parce qu'((il)|(elle)) ne peut pas ramasser cette objet.$"] = "pass",
["(.*) a passé pour : (.+)"] = "pass",
["(.*) a choisi Cupidité pour : (.+)"] = "greed",
["(.*) a choisi Besoin pour : (.+)"] = "need",
["(.*) a choisi Désenchantement pour : (.+)"] = "disenchant",
} or locale == "zhTW" and {
["(.*)自動放棄:(.+),因為他無法拾取該物品$"] = "pass",
["(.*)自動放棄:(.+),因為她無法拾取該物品$"] = "pass",
["(.*)放棄了:(.+)"] = "pass",
["(.*)選擇了貪婪:(.+)"] = "greed",
["(.*)選擇了需求:(.+)"] = "need",
["(.*)選擇了分解:(.+)"] = "disenchant",
} or locale == "zhCN" and {
["(.*)自动放弃了(.+),因为他无法拾取该物品。$"] = "pass",
["(.*)放弃了:(.+)"] = "pass",
["(.*)选择了贪婪取向:(.+)"] = "greed",
["(.*)选择了需求取向:(.+)"] = "need",
["(.*)选择了分解取向:(.+)"] = "disenchant",
} or locale == "ruRU" and {
["(.*) автоматически передает предмет (.+), поскольку не может его забрать"] = "pass",
["(.*) пропускает розыгрыш предмета \"(.+)\", поскольку не может его забрать"] = "pass",
["(.*) отказывается от предмета (.+)%."] = "pass",
["Разыгрывается: (.+)%. (.*): \"Не откажусь\""] = "greed",
["Разыгрывается: (.+)%. (.*): \"Мне это нужно\""] = "need",
["Разыгрывается: (.+)%. (.*): \"Распылить\""] = "disenchant",
} or locale == "koKR" and {
["(.*)님이 획득할 수 없는 아이템이어서 자동으로 주사위 굴리기를 포기했습니다: (.+)"] = "pass",
["(.*)님이 주사위 굴리기를 포기했습니다: (.+)"] = "pass",
["(.*)님이 차비를 선택했습니다: (.+)"] = "greed",
["(.*)님이 입찰을 선택했습니다: (.+)"] = "need",
["(.*)님이 마력 추출을 선택했습니다: (.+)"] = "disenchant",
} or (locale == "esES" or locale == "esMX") and {
["^(.*) pasó automáticamente de: (.+) porque no puede despojar este objeto.$"] = "pass",
["^(.*) pasó de: (.+|r)$"] = "pass",
["(.*) eligió Codicia para: (.+)"] = "greed",
["(.*) eligió Necesidad para: (.+)"] = "need",
["(.*) eligió Desencantar para: (.+)"] = "disenchant",
} or locale == "ptBR" and {
["^(.*) abdicou de (.+) automaticamente porque não pode saquear o item.$"] = "pass",
["^(.*) dispensou: (.+|r)$"] = "pass",
["(.*) selecionou Ganância para: (.+)"] = "greed",
["(.*) escolheu Necessidade para: (.+)"] = "need",
["(.*) selecionou Desencantar para: (.+)"] = "disenchant",
} or {
["^(.*) automatically passed on: (.+) because s?he cannot loot that item.$"] = "pass",
["^(.*) passed on: (.+|r)$"] = "pass",
["(.*) has selected Greed for: (.+)"] = "greed",
["(.*) has selected Need for: (.+)"] = "need",
["(.*) has selected Disenchant for: (.+)"] = "disenchant",
}
local function ParseRollChoice(msg)
for i,v in pairs(rollpairs) do
local _, _, playername, itemname = string.find(msg, i)
if locale == "ruRU" and (v == "greed" or v == "need" or v == "disenchant") then
local temp = playername
playername = itemname
itemname = temp
end
if playername and itemname and playername ~= "Everyone" then return playername, itemname, v end
end
end
local function CHAT_MSG_LOOT(msg)
local playername, itemname, rolltype = ParseRollChoice(msg)
if playername and itemname and rolltype then
for _,f in ipairs(frames) do
if f.rollid and f.button.link == itemname and not f.rolls[playername] then
f.rolls[playername] = rolltype
f[rolltype]:SetText(tonumber(f[rolltype]:GetText()) + 1)
return
end
end
end
end
LootRollAnchor:RegisterEvent("ADDON_LOADED")
LootRollAnchor:SetScript("OnEvent", function(frame, event, addon)
if addon ~= "KkthnxUI" then return end
LootRollAnchor:UnregisterEvent("ADDON_LOADED")
LootRollAnchor:RegisterEvent("START_LOOT_ROLL")
LootRollAnchor:RegisterEvent("CHAT_MSG_LOOT")
UIParent:UnregisterEvent("START_LOOT_ROLL")
UIParent:UnregisterEvent("CANCEL_LOOT_ROLL")
LootRollAnchor:SetScript("OnEvent", function(frame, event, ...) if event == "CHAT_MSG_LOOT" then return CHAT_MSG_LOOT(...) else return START_LOOT_ROLL(...) end end)
LootRollAnchor:SetPoint(unpack(C["position"].group_loot))
end)
SlashCmdList.TESTROLL = function()
local f = GetFrame()
local items = {32837, 34196, 33820, 84004}
if f:IsShown() then
f:Hide()
else
local item = items[math.random(1, #items)]
local _, _, quality, _, _, _, _, _, _, texture = GetItemInfo(item)
local r, g, b = GetItemQualityColor(quality or 1)
f.button.icon:SetTexture(texture)
f.button.icon:SetTexCoord(0.1, 0.9, 0.1, 0.9)
f.fsloot:SetText(GetItemInfo(item))
f.fsloot:SetVertexColor(r, g, b)
f.status:SetMinMaxValues(0, 100)
f.status:SetValue(math.random(50, 90))
f.status:SetStatusBarColor(r, g, b, 0.9)
f.status.bg:SetTexture(r, g, b)
f:SetBackdropBorderColor(r, g, b, 0.9)
f.button:SetBackdropBorderColor(r, g, b, 0.9)
f.need:SetText(0)
f.greed:SetText(0)
f.pass:SetText(0)
f.disenchant:SetText(0)
f.button.link = "item:"..item..":0:0:0:0:0:0:0"
f:Show()
end
end
SLASH_TESTROLL1 = "/testroll"
SLASH_TESTROLL2 = "/tr"
| 13,310
|
mopd/KkthnxUI_WotLK
|
identitycontrols = {};
function setCurrent(name)
local idctrl = identitycontrols[name];
if idctrl then
-- Deactivate all identities
for k, v in pairs(identitycontrols) do
v.setCurrent(false);
end
-- Set active
idctrl.setCurrent(true);
end
end
function addIdentity(name, isgm)
local idctrl = identitycontrols[name];
-- Create control if not found
if not idctrl then
createControl("identitylistentry", "ctrl_" .. name);
idctrl = self["ctrl_" .. name];
identitycontrols[name] = idctrl;
idctrl.createLabel(name, isgm);
end
end
function removeIdentity(name)
local idctrl = identitycontrols[name];
if idctrl then
idctrl.destroy();
identitycontrols[name] = nil;
end
end
function renameGmIdentity(name)
for k,v in pairs(identitycontrols) do
if v.gmidentity then
v.rename(name);
identitycontrols[name] = v;
identitycontrols[k] = nil;
return;
end
end
end
function onInit()
GmIdentityManager.registerIdentityList(self);
end
| 1,047
|
sweetrpg/fantasy-grounds-genesys-ruleset
|
function TelekeneticBlobGetMarkedTarget(caster)
local ability = caster:FindAbilityByName("telekenetic_blob_mark_target")
if ability ~= nil then
return ability.lastCastTaget
end
return nil
end
function TelekeneticBlobFlySetup(modifier, fixedSpeed)
if modifier:ApplyHorizontalMotionController() == false or modifier:ApplyVerticalMotionController() == false then
modifier:Destroy()
return
end
modifier.vStartPosition = GetGroundPosition( modifier:GetParent():GetOrigin(), modifier:GetParent() )
modifier.vTargetPosition = modifier:GetAbility():GetCursorPosition()
modifier.flStartHeight = GetGroundHeight( modifier.vStartPosition, modifier:GetParent())
modifier.flTargetHeight = GetGroundHeight( modifier.vTargetPosition, modifier:GetParent())
modifier.flHeight = modifier:GetAbility():GetSpecialValueFor("fly_height")
modifier.vDirection = (modifier.vTargetPosition - modifier.vStartPosition):Normalized()
modifier.flDistance = (modifier.vTargetPosition - modifier.vStartPosition):Length2D()
if fixedSpeed then
modifier.flHorizontalSpeed = modifier:GetAbility():GetSpecialValueFor("fly_speed")
modifier.fDuration = modifier.flDistance / modifier:GetAbility():GetSpecialValueFor("fly_speed")
else
modifier.flHorizontalSpeed = modifier.flDistance / modifier:GetAbility():GetSpecialValueFor("fly_duration")
modifier.fDuration = modifier:GetAbility():GetSpecialValueFor("fly_duration")
end
EmitSoundOnLocationWithCaster(modifier.vStartPosition, "Ability.TossThrow", modifier:GetParent())
end
function TelekeneticBlobFlyTearDown(modifier)
if IsServer() then
modifier:GetParent():RemoveHorizontalMotionController(modifier)
modifier:GetParent():RemoveVerticalMotionController(modifier)
end
end
function TelekeneticBlobFlyUpdateHorizontal(me, dt, modifier)
if IsServer() then
local vOldPosition = me:GetOrigin()
local vNewPos = vOldPosition + modifier.vDirection * modifier.flHorizontalSpeed * dt
me:SetOrigin(vNewPos)
end
end
function TelekeneticBlobFlyUpdateVertical(me, dt, modifier, landingCallback)
if IsServer() then
local vOrigin = me:GetOrigin()
local vDistance = (vOrigin - modifier.vStartPosition):Length2D()
local vZ = (2*modifier.flTargetHeight-2*modifier.flStartHeight-4*modifier.flHeight)/(modifier.fDuration*modifier.fDuration) * (modifier:GetElapsedTime()*modifier:GetElapsedTime()) + (4*modifier.flHeight+modifier.flStartHeight-modifier.flTargetHeight) / modifier.fDuration * modifier:GetElapsedTime() + modifier.flStartHeight
vOrigin.z = vZ
local flGroundHeight = GetGroundHeight( vOrigin, modifier:GetParent() )
local bLanded = false
if (modifier:GetElapsedTime() >= modifier.fDuration) then
vOrigin.z = flGroundHeight
bLanded = true
end
me:SetOrigin(vOrigin)
if bLanded == true then
if landingCallback ~= nil then
landingCallback(modifier)
end
local pid = ParticleManager:CreateParticle("particles/econ/items/earthshaker/earthshaker_totem_ti6/earthshaker_totem_ti6_leap_impact.vpcf", PATTACH_ABSORIGIN, modifier:GetParent())
ParticleManager:SetParticleControl(pid, 0, me:GetOrigin())
ParticleManager:ReleaseParticleIndex(pid)
EmitSoundOnLocationWithCaster(modifier:GetParent():GetOrigin(), "Ability.TossImpact", modifier:GetParent())
modifier:GetParent():RemoveHorizontalMotionController(modifier)
modifier:GetParent():RemoveVerticalMotionController(modifier)
modifier:SetDuration(0.01, true)
end
end
end
modifier_telekenetic_blob = class({})
function modifier_telekenetic_blob:IsPurgable() return false end
function modifier_telekenetic_blob:IsHidden() return true end
function modifier_telekenetic_blob:RemoveOnDeath() return false end
function modifier_telekenetic_blob:DeclareFunctions() return {MODIFIER_PROPERTY_DISABLE_AUTOATTACK} end
function modifier_telekenetic_blob:GetDisableAutoAttack() return 1 end
function modifier_telekenetic_blob:CheckState()
return {[MODIFIER_STATE_DISARMED] = true}
end
| 4,240
|
GuChenGuYing/DOTA2-AI-Fun
|
-- 微信验证
-- 每个需要用到的服务都需要在启动的时候调wx.init
--
local http = require "bw.web.http_helper"
local sha256 = require "bw.auth.sha256"
local json = require "cjson.safe"
local map = {} -- appid -> access
local function request_access_token(appid, secret)
assert(appid and secret)
local ret, resp = http.get("https://api.weixin.qq.com/cgi-bin/token", {
grant_type = "client_credential",
appid = appid,
secret = secret,
})
if ret then
resp = json.decode(resp)
local access = {}
access.token = resp.access_token
access.exires_in = resp.expires_in
access.time = os.time()
map[appid] = access
else
error(resp)
end
end
local M = {}
function M.get_access_token(appid, secret)
assert(appid and secret)
local access = map[appid]
if not access or os.time() - access.time > access.exires_in then
request_access_token(appid, secret)
return map[appid]
end
return access.token
end
function M.check_code(appid, secret, js_code)
assert(appid and secret and js_code)
local ret, resp = http.get("https://api.weixin.qq.com/sns/jscode2session",{
js_code = js_code,
grant_type = "authorization_code",
appid = appid,
secret = secret,
})
if ret then
return json.decode(resp)
else
error(resp)
end
end
-- data {score = 100, gold = 300}
function M:set_user_storage(appid, secret, openid, session_key, data)
local kv_list = {}
for k, v in pairs(data) do
table.insert(kv_list, {key = k, value = v})
end
local post = json.encode({kv_list = kv_list})
local url = "https://api.weixin.qq.com/wxa/set_user_storage?"..http.url_encoding({
access_token = M.get_access_token(appid, secret),
openid = openid,
appid = appid,
signature = sha256.hmac_sha256(post, session_key),
sig_method = "hmac_sha256",
})
local ret, resp = http.post(url, post)
if ret then
return json.decode(resp)
else
error(resp)
end
end
-- key_list {"score", "gold"}
function M:remove_user_storage(appid, secret, openid, session_key, key_list)
local post = json.encode({key = key_list})
local url = "https://api.weixin.qq.com/wxa/remove_user_storage?"..http.url_encoding({
access_token = M.get_access_token(appid, secret),
openid = openid,
appid = appid,
signature = sha256.hmac_sha256(post, session_key),
sig_method = "hmac_sha256",
})
local ret, resp = http.post(url, post)
if ret then
return json.decode(resp)
else
error(resp)
end
end
return M
| 2,717
|
xiaozia/bewater
|
require("bin.npc")
require("bin.gstate")
require("bin.battlestate")
lvgp = lvgp or love.graphics
local val = 0
platform = {}
volume = 1
focusvar = love.window.hasMouseFocus()
scrw, scrh = lvgp.getDimensions()
function love.load()
minimx = 736
exitx = 768
guiRender = true
isPaused = false
Pausable = true
insertbool = insertbool or true
window_x, window_y, window_d = love.window.getPosition( )
window_w = 800
window_h = 500
window_scale = window_scale or 1
game_w = game_w or window_w
game_h = game_h or window_h
game_scale = game_scale or 1
esc_name = esc_name or 'def'
esc_addr = 'assets/gfx/esc/' .. tostring(esc_name)
banner = banner or lvgp.newImage(esc_addr .. '/banner.png')
minimize = minimize or lvgp.newImage(esc_addr .. '/min.png')
exitout = exitout or lvgp.newImage(esc_addr .. '/exit.png')
icon = icon or lvgp.newImage(esc_addr .. '/icon.png')
hpbar = hpbar or lvgp.newImage('assets/gfx/gui/btl/hp_bar.png')
bstate = Gstate.New("bstate")
currstate = bstate
npc1 = Npc.New(2)
npc1.desc = "An old man with a beard. His clothes seem otherworldly."
npc1:AArray(npc1, 1, "Hello there!")
npc1:AArray(npc1, 2, "Well, goodbye now!")
npc1.array = {"Look, it works!"}
titleicon = love.image.newImageData('assets/title.png')
canvas = bstate.canvas or lvgp.newCanvas(game_w*game_scale, game_h*game_scale,"normal",0)
canvas:setFilter( "nearest", "nearest" )
escvas = lvgp.newCanvas(window_w, window_h,"normal",0)
escvas:setFilter( "nearest", "nearest" )
love.window.setMode(window_w, window_h, {borderless=true, vsync=false})
bstate.load()
end
function love.update(dt)
--player.update()
function saveClose(exitmode)
local mode = exitmode or "save"
if mode == "save" then
local title = "Escape"
local message = "Are you sure you want to leave?"
local buttons = {"Yes","No",enterbutton = 2,escapebutton = 1}
local pressedbutton = love.window.showMessageBox(title, message, buttons)
if pressedbutton == 2 then
isPaused = false
elseif pressedbutton == 1 then
love.event.quit()
end
elseif mode == "exit" then
love.event.quit()
elseif mode == "reset" then
end
end
if focusvar == true then
--focusvar = 1
titleicon:paste(love.image.newImageData('assets/title.png'), 0, 0)
end
if focusvar == false then
--focusvar = 0
titleicon:paste(love.image.newImageData('assets/title1.png'), 0, 0)
end
h = h or 1
hh = hh or 1
rot = rot or 0
function love.keypressed(key)
if key == "insert" then
insertbool = not insertbool
love.mouse.setVisible(not love.mouse.isVisible())
guiRender = insertbool
end
if key == "home" then
love.window.setPosition(0,0,1)
end
if key == "r" then
h = h + 1
end
if key == "f" then
h = h - 1
end
if key == "t" then
hh = hh + 1
end
if key == "g" then
hh = hh - 1
end
if key == "y" then
rot = rot + 1/45
end
if key == "h" then
rot = rot - 1/45
end
if key == "escape" then
if Pausable == true then
isPaused = not isPaused
elseif isPaused == true then
isPaused = false
end
end
end
success = love.window.setIcon(titleicon)
bstate.update()
mx = tonumber(love.mouse.getX()/scrh*255)
my = tonumber(love.mouse.getY()/scrh*255)
if love.mouse.getY() <= banner:getHeight() and love.mouse.getY() <= 32 and isPaused == true then
bar_focus = true
end
if love.mouse.isDown(1) then
minitX = minitX or love.mouse.getX()
minitY = minitY or love.mouse.getY()
bar_focus = bar_focus or false
w_x,w_y= love.window.getPosition( )
if isPaused == true and bar_focus == true and (minitX ~= love.mouse.getX() or minitY ~= love.mouse.getY()) then
if love.window.hasMouseFocus() then
--love.mouse.setGrabbed(true)
love.window.setPosition( w_x-(minitX-love.mouse.getX()), w_y-(minitY-love.mouse.getY()),1)
end
else
love.mouse.setGrabbed(false)
end
else
if bar_focus == true then
minitX = love.mouse.getX()
minitY = love.mouse.getY()
if love.mouse.isGrabbed == true and isPaused == true then
love.mouse.setGrabbed(false)
end
end
end
function love.mousepressed(x, y, button, istouch)
if button == 1 then
if love.mouse.getX() > minimx and love.mouse.getX() < minimx + minimize:getWidth() and isPaused == true and love.mouse.getY() <= banner:getHeight() then
love.window.minimize()
bar_focus = false
end
if love.mouse.getX() > exitx and love.mouse.getX() < exitx + exitout:getWidth() and isPaused == true and love.mouse.getY() <= banner:getHeight() then
saveClose("exit")
bar_focus = false
end
end
end
end
function love.draw()
--player.draw()
lvgp.setBackgroundColor(0,0,0)
lvgp.setColor(255,255,255)
lvgp.setCanvas(canvas)
lvgp.setColor(love.mouse.getX(),10,10)
lvgp.rectangle("fill", 0, 0, game_w*game_scale, game_h*game_scale)
lvgp.setColor(255,255,255)
bstate.draw()
lvgp.circle('fill', love.mouse.getX(), love.mouse.getY(), h, hh)
lvgp.setCanvas()
if focusvar == true then
titleicon:paste(love.image.newImageData('assets/title.png'), 0, 0)
lvgp.print(esc_addr .. '/banner.png',16,16)
end
if focusvar == false then
titleicon:paste(love.image.newImageData('assets/title1.png'), 0, 0)
lvgp.print("npc.dialog[draw]: " .. tostring(npc1.array[1]), 16, 272)
end
lvgp.draw(canvas, 0, 0, rot, window_scale, window_scale)
lvgp.setCanvas(escvas)
if isPaused == true and Pausable == true then
if not pausebg then
lvgp.rectangle("fill",0,0,game_w*window_scale,game_h*window_scale)
else
lvgp.draw(pausebg,0,(banner:getHeight() or 32),window_scale)
end
lvgp.draw(banner,0,0,0,window_scale)
lvgp.draw(minimize,736*window_scale,0,0,window_scale)
lvgp.draw(exitout,768*window_scale,0,0,window_scale)
lvgp.draw(icon,0,0,0,window_scale)
end
lvgp.setCanvas()
if isPaused == true then
lvgp.draw(escvas, 0, 0, 0, window_scale, window_scale)
else
if insertbool == true then
edraw = lvgp.newQuad(10 + love.mouse.getX() / window_w * hpbar:getWidth(), 0, (1 - love.mouse.getX() / window_w) * hpbar:getWidth(), hpbar:getHeight(), hpbar:getWidth(), hpbar:getHeight())
gdraw = lvgp.newQuad(0, 0, love.mouse.getX() / window_w * hpbar:getWidth(), hpbar:getHeight(), hpbar:getWidth(), hpbar:getHeight())
lvgp.setColor(108,108,108,128)
drawe = lvgp.draw(hpbar, edraw, 310 + love.mouse.getX() / window_w * hpbar:getWidth(), 100)
drawg = lvgp.draw(hpbar, gdraw, 300, 100)
lvgp.setColor(158,158,158,255)
drawe = lvgp.draw(hpbar, edraw, 305 + love.mouse.getX() / window_w * hpbar:getWidth(), 90)
lvgp.setColor(255,255,255,255)
drawg = lvgp.draw(hpbar, gdraw, 295, 90)
lvgp.print("HP%: " .. tostring(love.mouse.getX() / window_w * hpbar:getWidth()),305,90)
end
end
end
| 6,845
|
Aggrotadpole/brack
|
#! /usr/bin/env lua
--
-- libtest-reflect-var.lua
-- Copyright (C) 2015 Adrian Perez <aperez@igalia.com>
--
-- Distributed under terms of the MIT license.
--
local libtest = require("eol").load("libtest")
assert.Not.Nil(libtest)
function check_variable(variable, expected_name, expected_readonly,
expected_type, expected_type_sizeof)
assert.Not.Nil(variable)
assert.Equal(expected_name, variable.__name)
assert.Equal(libtest, variable.__library)
assert.Match(expected_type, variable.__type.name)
assert.Equal(expected_readonly, variable.__type.readonly)
if expected_type_sizeof ~= nil then
assert.Equal(expected_type_sizeof, variable.__type.sizeof)
end
end
check_variable(libtest.const_int, "const_int", true, "int%d+_t")
check_variable(libtest.var_u16, "var_u16", false, "uint16_t", 2)
check_variable(libtest.intvar, "intvar", false, "int%d+_t")
| 879
|
aperezdc/eris
|
class "SkeletonAnimation"
function SkeletonAnimation:SkeletonAnimation(...)
local arg = {...}
for k,v in pairs(arg) do
if type(v) == "table" then
if v.__ptr ~= nil then
arg[k] = v.__ptr
end
end
end
if self.__ptr == nil and arg[1] ~= "__skip_ptr__" then
self.__ptr = Polycode.SkeletonAnimation(unpack(arg))
end
end
function SkeletonAnimation:getName()
local retVal = Polycode.SkeletonAnimation_getName(self.__ptr)
return retVal
end
function SkeletonAnimation:Play(once)
local retVal = Polycode.SkeletonAnimation_Play(self.__ptr, once)
end
function SkeletonAnimation:Stop()
local retVal = Polycode.SkeletonAnimation_Stop(self.__ptr)
end
function SkeletonAnimation:Reset()
local retVal = Polycode.SkeletonAnimation_Reset(self.__ptr)
end
function SkeletonAnimation:Update(elapsed)
local retVal = Polycode.SkeletonAnimation_Update(self.__ptr, elapsed)
end
function SkeletonAnimation:setSpeed(speed)
local retVal = Polycode.SkeletonAnimation_setSpeed(self.__ptr, speed)
end
function SkeletonAnimation:setWeight(newWeight)
local retVal = Polycode.SkeletonAnimation_setWeight(self.__ptr, newWeight)
end
function SkeletonAnimation:getWeight()
local retVal = Polycode.SkeletonAnimation_getWeight(self.__ptr)
return retVal
end
function SkeletonAnimation:isPlaying()
local retVal = Polycode.SkeletonAnimation_isPlaying(self.__ptr)
return retVal
end
function SkeletonAnimation:__delete()
if self then Polycode.delete_SkeletonAnimation(self.__ptr) end
end
| 1,493
|
my-digital-decay/Polycode
|
--[[ BattleguardSartura.lua
********************************
* *
* The LUA++ Scripting Project *
* *
********************************
This software is provided as free and open source by the
staff of The LUA++ Scripting Project, in accordance with
the AGPL license. This means we provide the software we have
created freely and it has been thoroughly tested to work for
the developers, but NO GUARANTEE is made it will work for you
as well. Please give credit where credit is due, if modifying,
redistributing and/or using this software. Thank you.
~~End of License Agreement
-- LUA++ staff, March 26, 2008. ]]
--[[
Battleguard Sartura yells: I sentence you to death!
Battleguard Sartura yells: I serve to the last!
Battleguard Sartura yells: You will be judged for defiling these sacred grounds! The laws of the Ancients will not be challenged! Trespassers will be annihilated!
]]--
function Sartura_Knockback(pUnit, event)
pUnit:CastSpellOnTarget(10689, pUnit:GetRandomPlayer(0))
local kbtimer = math.random(25000, 60000)
pUnit:RegisterEvent("Sartura_Knockback2", kbtimer, 1)
end
function Sartura_Knockback2(pUnit, event)
pUnit:CastSpellOnTarget(10689, pUnit:GetRandomPlayer(0))
local kbtimer = math.random(25000, 60000)
pUnit:RegisterEvent("Sartura_Knockback", kbtimer, 1)
end
function Sartura_Whirlwind(Unit)
Unit:CastSpell(46270)
end
function Sartura_Phase2(Unit, event)
if (Unit:GetHealthPct() < 20) then
Unit:RemoveEvents()
Unit:CastSpell(28747)
Unit:RegisterEvent("Sartura_Enrage", 1000, 0)
end
end
function Sartura_Enrage(Unit)
local vars = getvars(Unit);
vars.EnrageTimer = vars.EnrageTimer + 1;
if (vars.EnrageTimer == 600) then
vars.EnrageTimer = 0;
setvars(Unit, vars);
Unit:CastSpell(34624)
end
setvars(Unit, vars);
end
function Sartura_OnCombat(Unit, event)
setvars(Unit, {EnrageTimer = 1});
local kbtimer=math.random(25000, 60000)
Unit:PlaySoundToSet(8646)
Unit:SendChatMessage(12, 0, "You will be judged for defiling these sacred grounds! The laws of the Ancients will not be challenged! Trespassers will be annihilated!")
Unit:RegisterEvent("Sartura_Whirlwind", 30000, 0)
Unit:RegisterEvent("Sartura_Phase2", 1000, 0)
Unit:RegisterEvent("Sartura_Knockback", kbtimer, 1)
Unit:RegisterEvent("Sartura_Enrage", 1000, 0)
end
function Sartura_OnLeaveCombat(Unit, event)
Unit:RemoveEvents()
end
function Sartura_OnKilledTarget(Unit, event)
Unit:PlaySoundToSet(8647)
Unit:SendChatMessage(12, 0, "I sentence you to death!")
end
function Sartura_OnDied(Unit, event)
Unit:PlaySoundToSet(8648)
Unit:SendChatMessage(12, 0, "I serve to the last!")
Unit:RemoveEvents()
end
RegisterUnitEvent(15516, 1, "Sartura_OnCombat")
RegisterUnitEvent(15516, 2, "Sartura_OnLeaveCombat")
RegisterUnitEvent(15516, 3, "Sartura_OnKilledTarget")
RegisterUnitEvent(15516, 4, "Sartura_OnDied")
| 2,958
|
499453466/Lua-Other
|
---------------------------------------------
-- Slowga
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
---------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0
end
function onPetAbility(target, pet, skill, summoner)
local duration = 180 + summoner:getMod(tpz.mod.SUMMONING)
if duration > 350 then
duration = 350
end
if target:addStatusEffect(tpz.effect.SLOW, 3000, 0, duration) then
skill:setMsg(tpz.msg.basic.SKILL_ENFEEB_IS)
else
skill:setMsg(tpz.msg.basic.SKILL_NO_EFFECT)
end
return tpz.effect.SLOW
end
| 757
|
PaulAnthonyReitz/topaz
|
-------------
--- Armor ---
-------------
-- Ver 1.0 --
-- Fire-Forged Armor --
armor:register_armor("draconis:helmet_fire_draconic_steel", {
description = "Fire-forged Draconic Steel Helmet",
inventory_image = "draconis_inv_helmet_fire_draconic_steel.png",
groups = {armor_head=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_fire=1},
armor_groups = {fleshy=30},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
armor:register_armor("draconis:chestplate_fire_draconic_steel", {
description = "Fire-forged Draconic Steel Chestplate",
inventory_image = "draconis_inv_chestplate_fire_draconic_steel.png",
groups = {armor_torso=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_fire=1},
armor_groups = {fleshy=40},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
armor:register_armor("draconis:leggings_fire_draconic_steel", {
description = "Fire-forged Draconic Steel Leggings",
inventory_image = "draconis_inv_leggings_fire_draconic_steel.png",
groups = {armor_legs=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_fire=1},
armor_groups = {fleshy=40},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
armor:register_armor("draconis:boots_fire_draconic_steel", {
description = "Fire-forged Draconic Steel Boots",
inventory_image = "draconis_inv_boots_fire_draconic_steel.png",
groups = {armor_feet=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_fire=1},
armor_groups = {fleshy=30},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
-- Ice-Forged Armor --
armor:register_armor("draconis:helmet_ice_draconic_steel", {
description = "Ice-forged Draconic Steel Helmet",
inventory_image = "draconis_inv_helmet_ice_draconic_steel.png",
groups = {armor_head=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_water=1},
armor_groups = {fleshy=30},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
armor:register_armor("draconis:chestplate_ice_draconic_steel", {
description = "Ice-forged Draconic Steel Chestplate",
inventory_image = "draconis_inv_chestplate_ice_draconic_steel.png",
groups = {armor_torso=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_water=1},
armor_groups = {fleshy=40},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
armor:register_armor("draconis:leggings_ice_draconic_steel", {
description = "Ice-forged Draconic Steel Leggings",
inventory_image = "draconis_inv_leggings_ice_draconic_steel.png",
groups = {armor_legs=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_water=1},
armor_groups = {fleshy=40},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
armor:register_armor("draconis:boots_ice_draconic_steel", {
description = "Ice-forged Draconic Steel Boots",
inventory_image = "draconis_inv_boots_ice_draconic_steel.png",
groups = {armor_feet=1, armor_heal=18, armor_use=100,
physics_speed=0.5, physics_gravity=0.05, physics_jump=0.15, armor_water=1},
armor_groups = {fleshy=30},
damage_groups = {cracky=2, snappy=3, choppy=2, crumbly=1, level=2},
})
| 3,675
|
ronoaldo/draconis
|
object_building_general_ord_cantina = object_building_general_shared_ord_cantina:new {
}
ObjectTemplates:addTemplate(object_building_general_ord_cantina, "object/building/general/ord_cantina.iff")
| 197
|
V-Fib/FlurryClone
|
-- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
require("luci.tools.webadmin")
local fs = require "nixio.fs"
local util = require "nixio.util"
local tp = require "luci.template.parser"
local block = io.popen("block info", "r")
local ln, dev, devices = nil, nil, {}
repeat
ln = block:read("*l")
dev = ln and ln:match("^/dev/(.-):")
if dev then
local e, s, key, val = { }
for key, val in ln:gmatch([[(%w+)="(.-)"]]) do
e[key:lower()] = val
devices[val] = e
end
s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev)))
e.dev = "/dev/%s" % dev
e.size = s and math.floor(s / 2048)
devices[e.dev] = e
end
until not ln
block:close()
m = Map("fstab", translate("Mount Points"))
s = m:section(TypedSection, "global", translate("Global Settings"))
s.addremove = false
s.anonymous = true
detect = s:option(Button, "block_detect", translate("Generate Config"), translate("Find all currently attached filesystems and swap and replace configuration with defaults based on what was detected"))
detect.inputstyle = "reload"
detect.write = function(self, section)
luci.sys.call("block detect >/etc/config/fstab")
luci.http.redirect(luci.dispatcher.build_url("admin/system", "fstab"))
end
o = s:option(Flag, "anon_swap", translate("Anonymous Swap"), translate("Mount swap not specifically configured"))
o.default = o.disabled
o.rmempty = false
o = s:option(Flag, "anon_mount", translate("Anonymous Mount"), translate("Mount filesystems not specifically configured"))
o.default = o.disabled
o.rmempty = false
o = s:option(Flag, "auto_swap", translate("Automount Swap"), translate("Automatically mount swap on hotplug"))
o.default = o.enabled
o.rmempty = false
o = s:option(Flag, "auto_mount", translate("Automount Filesystem"), translate("Automatically mount filesystems on hotplug"))
o.default = o.enabled
o.rmempty = false
o = s:option(Flag, "check_fs", translate("Check filesystems before mount"), translate("Automatically check filesystem for errors before mounting"))
o.default = o.disabled
o.rmempty = false
local mounts = luci.sys.mounts()
local non_system_mounts = {}
for rawmount, val in pairs(mounts) do
if (string.find(val.mountpoint, "/tmp/.jail") == nil) then
repeat
val.umount = false
if (val.mountpoint == "/") then
break
elseif (val.mountpoint == "/overlay") then
break
elseif (val.mountpoint == "/rom") then
break
elseif (val.mountpoint == "/tmp") then
break
elseif (val.mountpoint == "/tmp/shm") then
break
elseif (val.mountpoint == "/tmp/upgrade") then
break
elseif (val.mountpoint == "/dev") then
break
end
val.umount = true
until true
non_system_mounts[rawmount] = val
end
end
v = m:section(Table, non_system_mounts, translate("Mounted file systems"))
fs = v:option(DummyValue, "fs", translate("Filesystem"))
mp = v:option(DummyValue, "mountpoint", translate("Mount Point"))
avail = v:option(DummyValue, "avail", translate("Available"))
function avail.cfgvalue(self, section)
return luci.tools.webadmin.byte_format(
( tonumber(mounts[section].available) or 0 ) * 1024
) .. " / " .. luci.tools.webadmin.byte_format(
( tonumber(mounts[section].blocks) or 0 ) * 1024
)
end
used = v:option(DummyValue, "used", translate("Used"))
function used.cfgvalue(self, section)
return ( mounts[section].percent or "0%" ) .. " (" ..
luci.tools.webadmin.byte_format(
( tonumber(mounts[section].used) or 0 ) * 1024
) .. ")"
end
-- unmount = v:option(Button, "unmount", translate("Unmount"))
-- unmount.render = function(self, section, scope)
-- if non_system_mounts[section].umount then
-- self.title = translate("Unmount")
-- self.inputstyle = "remove"
-- Button.render(self, section, scope)
-- end
-- end
-- unmount.write = function(self, section)
-- if non_system_mounts[section].umount then
-- luci.sys.call("/bin/umount '%s'" % luci.util.shellstartsqescape(non_system_mounts[section].mountpoint))
-- return luci.http.redirect(luci.dispatcher.build_url("admin/system", "fstab"))
-- end
-- end
mount = m:section(TypedSection, "mount", translate("Mount Points"), translate("Mount Points define at which point a memory device will be attached to the filesystem"))
mount.anonymous = true
mount.addremove = true
mount.template = "cbi/tblsection"
mount.extedit = luci.dispatcher.build_url("admin/system/fstab/mount/%s")
mount.create = function(...)
local sid = TypedSection.create(...)
if sid then
luci.http.redirect(mount.extedit % sid)
return
end
end
mount:option(Flag, "enabled", translate("Enabled")).rmempty = false
dev = mount:option(DummyValue, "device", translate("Device"))
dev.rawhtml = true
dev.cfgvalue = function(self, section)
local v, e
v = m.uci:get("fstab", section, "uuid")
e = v and devices[v]
if v and e and e.size then
return "UUID: %s (%s, %d MB)" %{ tp.pcdata(v), e.dev, e.size }
elseif v and e then
return "UUID: %s (%s)" %{ tp.pcdata(v), e.dev }
elseif v then
return "UUID: %s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") }
end
v = m.uci:get("fstab", section, "label")
e = v and devices[v]
if v and e and e.size then
return "Label: %s (%s, %d MB)" %{ tp.pcdata(v), e.dev, e.size }
elseif v and e then
return "Label: %s (%s)" %{ tp.pcdata(v), e.dev }
elseif v then
return "Label: %s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") }
end
v = Value.cfgvalue(self, section) or "?"
e = v and devices[v]
if v and e and e.size then
return "%s (%d MB)" %{ tp.pcdata(v), e.size }
elseif v and e then
return tp.pcdata(v)
elseif v then
return "%s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") }
end
end
mp = mount:option(DummyValue, "target", translate("Mount Point"))
mp.cfgvalue = function(self, section)
if m.uci:get("fstab", section, "is_rootfs") == "1" then
return "/overlay"
else
return Value.cfgvalue(self, section) or "?"
end
end
fs = mount:option(DummyValue, "fstype", translate("Filesystem"))
fs.cfgvalue = function(self, section)
local v, e
v = m.uci:get("fstab", section, "uuid")
v = v or m.uci:get("fstab", section, "label")
v = v or m.uci:get("fstab", section, "device")
e = v and devices[v]
return e and e.type or m.uci:get("fstab", section, "fstype") or "?"
end
op = mount:option(DummyValue, "options", translate("Options"))
op.cfgvalue = function(self, section)
return Value.cfgvalue(self, section) or "defaults"
end
rf = mount:option(DummyValue, "is_rootfs", translate("Root"))
rf.cfgvalue = function(self, section)
local target = m.uci:get("fstab", section, "target")
if target == "/" then
return translate("yes")
elseif target == "/overlay" then
return translate("overlay")
else
return translate("no")
end
end
ck = mount:option(DummyValue, "enabled_fsck", translate("Check"))
ck.cfgvalue = function(self, section)
return Value.cfgvalue(self, section) == "1"
and translate("yes") or translate("no")
end
swap = m:section(TypedSection, "swap", "SWAP", translate("If your physical memory is insufficient unused data can be temporarily swapped to a swap-device resulting in a higher amount of usable <abbr title=\"Random Access Memory\">RAM</abbr>. Be aware that swapping data is a very slow process as the swap-device cannot be accessed with the high datarates of the <abbr title=\"Random Access Memory\">RAM</abbr>."))
swap.anonymous = true
swap.addremove = true
swap.template = "cbi/tblsection"
swap.extedit = luci.dispatcher.build_url("admin/system/fstab/swap/%s")
swap.create = function(...)
local sid = TypedSection.create(...)
if sid then
luci.http.redirect(swap.extedit % sid)
return
end
end
swap:option(Flag, "enabled", translate("Enabled")).rmempty = false
dev = swap:option(DummyValue, "device", translate("Device"))
dev.cfgvalue = function(self, section)
local v
v = m.uci:get("fstab", section, "uuid")
if v then return "UUID: %s" % v end
v = m.uci:get("fstab", section, "label")
if v then return "Label: %s" % v end
v = Value.cfgvalue(self, section) or "?"
e = v and devices[v]
if v and e and e.size then
return "%s (%s MB)" % {v, e.size}
else
return v
end
end
return m
| 8,343
|
WYC-2020/luci
|
--
-- YATM Brewery
--
local mod = foundation.new_module("yatm_brewery", "0.2.0")
mod:require("registries.lua")
mod:require("api.lua")
mod:require("nodes.lua")
mod:require("items.lua")
mod:require("fluids.lua")
mod:require("tests.lua")
| 239
|
IceDragon200/mt-yatm
|
-- lightsout v0.0.0
--
--
-- llllllll.co/t/lightsout
--
--
--
-- ▼ instructions below ▼
grid__=include("lightsout/lib/ggrid")
MusicUtil = require "musicutil"
lattice=require("lattice")
engine.name="PolyPerc"
function init()
grid_=grid__:new()
local redrawer=metro.init()
redrawer.time=1/15
redrawer.count=-1
redrawer.event=redraw
redrawer:start()
scale_full=MusicUtil.generate_scale_of_length(12, 1, 64)
for _, note in ipairs(MusicUtil.generate_scale_of_length(12, 1, 128)) do
table.insert(scale_full,note)
end
-- shuffled = {}
-- for i, v in ipairs(scale_full) do
-- local pos = math.random(1, #shuffled+1)
-- table.insert(shuffled, pos, v)
-- end
-- scale_full=shuffled
scales={}
k=1
for col=1,16 do
for row=1,8 do
if col==1 then
scales[row]={}
end
scales[row][col]=scale_full[k]
k=k+1
end
k = k - 3
end
-- start lattice
local sequencer=lattice:new{
ppqn=96
}
divisions={1/2,1/4,1/8,1/16,1/2,1/4,1/8,1/16,1/2,1/4,1/8,1/16,1/2,1/4,1/8,1/16}
for i=1,16 do
local step=0
sequencer:new_pattern({
action=function(t)
step=step+1
play_note(i,step)
end,
division=divisions[i],
})
end
sequencer:hard_restart()
end
function play_note(col,step)
local row=(step-1)%8+1
local light=grid_.lightsout[row][col]
if light>0 then
print(row,col)
print(scales[row][col])
local freq = MusicUtil.note_num_to_freq(scales[row][col])
grid_.visual[row][col]=15
engine.hz(freq)
-- grid_:toggle_key(row,col)
end
end
function enc(k,d)
end
function key(k,z)
end
function redraw()
screen.clear()
screen.move(32,64)
screen.text("lightsout")
screen.update()
end
function rerun()
norns.script.load(norns.state.script)
end
function cleanup()
end
function table.reverse(t)
local len = #t
for i = len - 1, 1, -1 do
t[len] = table.remove(t, i)
end
end
| 1,944
|
schollz/lightsout
|
local t = require('luatest')
local http_lib = require('http.lib')
local g = t.group()
g.test_template_1 = function()
t.assert_equals(http_lib.template("<% for i = 1, cnt do %> <%= abc %> <% end %>",
{abc = '1 <3>&" ', cnt = 3}),
' 1 <3>&" 1 <3>&" 1 <3>&" ',
'tmpl1')
end
g.test_template_2 = function()
t.assert_equals(http_lib.template('<% for i = 1, cnt do %> <%= ab %> <% end %>',
{abc = '1 <3>&" ', cnt = 3}),
' nil nil nil ', 'tmpl2')
end
g.test_broken_template = function()
local r, msg = pcall(http_lib.template, '<% ab() %>', {ab = '1'})
t.assert(r == false and msg:match("call local 'ab'") ~= nil, 'bad template')
end
g.test_rendered_template_truncated_gh_18 = function()
local template = [[
<html>
<body>
<table border='1'>
% for i,v in pairs(t) do
<tr>
<td><%= i %></td>
<td><%= v %></td>
</tr>
% end
</table>
</body>
</html>
]]
local tt = {}
for i=1, 100 do
tt[i] = string.rep('#', i)
end
local rendered, _ = http_lib.template(template, { t = tt })
t.assert(#rendered > 10000, 'rendered size')
t.assert_equals(rendered:sub(#rendered - 7, #rendered - 1), '</html>', 'rendered eof')
end
g.test_incorrect_arguments_escaping_leads_to_segfault_gh_51 = function()
local template = [[<%= {{continue}} %>"]]
local result = http_lib.template(template, {continue = '/'})
t.assert(result:find('\"') ~= nil)
end
| 1,598
|
a1div0/http
|
--[[
This is a guide for how to use this game as a starting point to create your own RPGs or other games.
This entire system uses one shared storage key. Go to 'Window' -> 'Shared Storage', and create a key or make one of your
existing keys associated with this game. Find 'APISharedKey' in Project Content, and change the "StorageKey" custom
property to point to your new shared key. You may have to select 'All Content' and do a bit of scrolling to make this
work.
You can turn on cheats by checking 'Enable' custom property on the 'Developer Cheats' script (under System->Developer
Cheats). It will print to the Event Log on preview start what you can do.
Use the 'DifficultyLevel' custom property on the 'DifficultySystem' group under 'System' to set difficulty. It is set up
to support 1 through 4 (Normal, Hard, Nightmare, Infinite).
In general, the 'System' folder controls how everything works, and should be identical between any dungeons or zones you
use. Right now there isn't a great way to keep that synchronized, just be careful when you make changes.
The 'Data' Folder includes everything that would be different between different dungeons. Use that to add new enemies,
change where enemies are, what attacks they have, what they drop, etc.
The API scripts are a good place to start, and generally have good comments, especially at the top describing how pieces
work. Also, for all of the sections below, copying an existing example that is similar is a way safer than making one
from scratch.
Adding Abilities:
1. Make a single script, generally named "Ability_[Name]".
2. Look at an existing ability script to see how they are set up. They do not exist in the hierarchy.
3. Add your new script as a custom property to APIAbility in Project Content. Leave the property name as is.
4. Note that onCastclient returns the time until it should spawn effects, and must not yield (or you may see janky
behavior.
Adding Status Effects:
1. Make a single script, generally named StatusEffect_[Name]".
2. Add two instances of that script to the hierarchy, under
System->Status Effect Controller->ClientStatusEffectDefinitions and
System->Status Effect Controller->ServerStatusEffectDefinitions.
3. Look at existing scripts to see how these are set up. Any start, tick, or end functions should not yield.
Adding Enemy Tasks:
1. Make two scripts, generally called "Task_[EnemyName]_[TaskName]_[Client/Server]". Put them under
Data->NPC System->Tasks->ClientTasks and Data->NPC System->Tasks->ServerTasks.
2. See existing scripts for examples and API_NPC for a description of what pieces are required.
3. Be VERY careful with timing and edge cases of players connecting/disconnecting. You cannot yield so these make a lot
of use of Tasks, but players can leave or enemies despawn in the middle of a task. Worse, if one of these causes a
script error, it usually results in all enemies no longer responding at all.
Adding Loot:
Loot is defined by a bunch of scripts with 'DATA' in the name. These were created by the spreadsheet below, but they
can also be edited directly.
1. Go to the following spreadsheet and make a copy for yourself:
https://docs.google.com/spreadsheets/d/12KBbew9zlaZre2ByMuCX4WBBaH20W1PXt242qcoHrKw/edit?usp=sharing
2. Edit as desired. Go to each tab and select 'File->Download->Comma-separated values (.csv, current sheeet)'. This will
give you about 20 .csv files.
3. Open https://csv-to-lua.netlify.app/. For each .csv file, open it in a text editor, paste the contents into the left
box, press 'Convert to Lua', then copy paste the right box into the corresponding 'DATA' script.
Adding Enemies:
Enemies are found in Data->NPC System->NPCs->[Foldername]. This is one of the few systems that requires specific
hierarchy setup, and that last folder must be there or they won't work. Those folders also can have a custom property
'Prerequestite' which most of them do, which tells the system which pull must be cleared first. The NPCs are fairly
expensive, so if you have more than ~8 active at a time, it may perform poorly.
NPCs are controlled almost entirely through their custom properties. Many are self-explanatory. Capsule size is used for
nameplate positioning, click targeting, and a few other things. They can drop from as many drop keys as you'd like, and
have as many tasks as you'd like as well. The FollowRoot is used so that client-side movement is smooth.
Controls:
We investigated changing the control scheme some, and may still down the road. We specifically looked to more action RPG
control styles where your cursor is hidden by default and your mouse controls your camera. Here are some of the major
issues we hit:
- The 'classic' MMO control scheme informs certain ability and enemy designs, and having a different control scheme
would probably be better with different abilities and enemies.
- An 'action' RPG control scheme is fairly incompatible with a targeting system entirely. That could be removed with
certain design choices.
- We did not make a robust system to control cursor visibility and interaction, and the 'action' RPG control scheme ran
into MANY issues here. You need the cursor visible whenever inventory/help, etc. are open. You need a way to show the
cursor so a player can rearrange their action bar, or click on UI buttons. This is definitely something that can be
written, but does not currently exist.
]]
| 5,480
|
Core-Team-META/Corehaven
|
-- icon set definition format
--
-- indexed by unique identifier, referenced with icon_ prefix
-- search path is prefixed icons/setname (same as lua file)
--
-- source to the synthesizers and builtin shaders are in icon.lua
--
-- 1. static image:
-- ["myicon"] = {
-- [24] = "myicon_24px.png",
-- [16] = "myicon_16px.png"
-- }
--
-- 2. postprocessed (custom color, SDFs, ...)
-- ["myicon"] = {
-- [24] = function()
-- return icon_synthesize_src("myicon_24px.png", 24,
-- icon_colorize, {color = {"fff", 1.0, 0.0, 0.0}});
-- end
-- }
--
-- 3. synthesized
-- ["myicon"] = {
-- generator =
-- function(px)
-- return icon_synthesize(px,
-- icon_unit_circle, {radius = {"f", 0.5}, color = {"fff", 1.0, 0.0, 0.0}})
-- end
-- }
--
-- and they can be mixed, i.e. if there is no direct match for a certain px size,
-- the generator will be invoked. This is to allow both a SDF based vector synth
-- as well as hand drawn overrides.
--
-- It is up to the UI component that uses the icon to deal with the desired px
-- size not actually being the returned one, and many will rather pad/relayout
-- than force-scale. In that case, use the 3. method with icon_synthesize_src.
--
return {
["cli"] =
{
[24] = function()
return icon_synthesize_src("cli_24px.png", 24,
icon_colorize, {color = {"fff", 0.0, 1.0, 1.0}});
end,
}
};
| 1,335
|
letoram/durden
|
workspace "LiquidEngine"
basedir "../workspace/"
language "C++"
cppdialect "C++17"
architecture "x86_64"
-- Set editor as starting project
startproject "Liquidator"
setupLibraryDirectories{}
setupPlatformDefines{}
linkPlatformLibraries{}
setupToolsetOptions{}
includedirs {
"../engine/src",
"../engine/rhi/core/include",
"../engine/rhi/vulkan/include",
"../engine/platform-tools/include"
}
configurations { "Debug", "Release", "Profile-Debug", "Profile-Release" }
filter { "toolset:msc-*" }
flags { "FatalCompileWarnings" }
filter {"configurations:Debug or configurations:Profile-Debug"}
defines { "LIQUID_DEBUG" }
symbols "On"
filter {"configurations:Release or configurations:Profile-Release"}
defines { "LIQUID_RELEASE" }
optimize "On"
filter {"configurations:Profile-Debug or configurations:Profile-Release"}
defines { "LIQUID_PROFILER" }
| 1,012
|
GasimGasimzada/liquid-engine
|
-----------------------------------
-- Area: The Garden of Ru'Hmet
-- Mob: Ix'aern DRG
-----------------------------------
local ID = require("scripts/zones/The_Garden_of_RuHmet/IDs")
-----------------------------------
function onMobFight(mob, target)
-- Spawn the pets if they are despawned
-- TODO: summon animations?
local mobId = mob:getID()
local x = mob:getXPos()
local y = mob:getYPos()
local z = mob:getZPos()
for i = mobId + 1, mobId + 3 do
local wynav = GetMobByID(i)
if not wynav:isSpawned() then
local repopWynavs = wynav:getLocalVar("repop") -- see Wynav script
if mob:getBattleTime() - repopWynavs > 10 then
wynav:setSpawn(x + math.random(1, 5), y, z + math.random(1, 5))
wynav:spawn()
wynav:updateEnmity(target)
end
end
end
end
function onMobDeath(mob, player, isKiller)
-- despawn pets
local mobId = mob:getID()
for i = mobId + 1, mobId + 3 do
if GetMobByID(i):isSpawned() then
DespawnMob(i)
end
end
end
function onMobDespawn( mob )
-- despawn pets
local mobId = mob:getID()
for i = mobId + 1, mobId + 3 do
if GetMobByID(i):isSpawned() then
DespawnMob(i)
end
end
-- Pick a new PH for Ix'Aern (DRG)
local groups = ID.mob.AWAERN_DRG_GROUPS
SetServerVariable("[SEA]IxAernDRG_PH", groups[math.random(1, #groups)] + math.random(0, 2))
end
| 1,497
|
MatthewJHBerry/topaz
|
--[[
This file has been modified by
Andreas Pittrich <andreas.pittrich@web.de>
in behalf of the german pirate party (Piratenpartei)
www.piratenpartei.de
Original Disclaimer:
-------
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
luci.i18n.loadc("freifunk")
local uci = require "luci.model.uci".cursor()
local fs = require "luci.fs"
m = Map("freifunk", "Custom Splash")
d = m:section(NamedSection, "custom_splash", "settings", "Custom Splash")
----------------
active=d:option(ListValue, "mode", "Custom Splash benutzen?")
active.widget="radio"
active.size=1
active:value("enabled", "Ja")
active:value("disabled", "Nein")
msg=d:option(ListValue, "messages", "Nachrichten aktivieren?")
msg.widget="radio"
msg.size=1
msg:value("enabled", "Ja")
msg:value("disabled", "Nein")
----------------
header=d:option(TextValue, "header", "Custom Header")
header.rows="20"
function header.cfgvalue(self, section)
cs=fs.readfile("/lib/uci/upload/custom_header.htm")
if cs == nil then
return ""
else
return cs
end
end
function header.write(self, section, value)
fs.writefile("/lib/uci/upload/custom_header.htm",value)
end
----------------
footer=d:option(TextValue, "footer", "Custom Footer")
footer.rows="20"
function footer.cfgvalue(self, section)
cs=fs.readfile("/lib/uci/upload/custom_footer.htm")
if cs == nil then
return ""
else
return cs
end
end
function footer.write(self, section, value)
fs.writefile("/lib/uci/upload/custom_footer.htm",value)
end
return m
| 1,750
|
alxhh/piratenluci
|
return {'amnesie','amnestie','amnestiemaatregel','amnestieregeling','amnestieverlening','amnestiewet','amnioscoop','amnioscopie','amnestieen','amnioscopen','amnioscopieen'}
| 172
|
terrabythia/alfabeter
|
blocFunctions = {}
function function_binding(toBind)
for k, v in pairs(toBind) do
blocFunctions[k] = function(position)
local newObjs = {};
for i in string.gmatch(v, "%S+") do
table.insert(newObjs, Engine.Scene:createGameObject(i)({position = position}));
end
return newObjs
end
end
end
function Object:uninit()
Object.initialized = false;
end
function Object:init(path)
print("Init terrain", path)
if not Object.initialized and file_exists(path) then
This:initialize();
print("Terrain initialized");
local lines = lines_from(path)
local maxY;
local maxX;
local sprSize;
local load_table = {};
print("Lines", inspect(lines));
for i, str in pairs(lines) do
if maxY == nil or i>maxY then
maxY = i;
end
load_table[i] = {}
for j = 1, #str do
if maxX == nil or j>maxX then
maxX = j;
end
local char = str:sub(j,j);
load_table[i][j] = char;
end
end
print("Loadtable", inspect(load_table));
local offset = {x = (maxX/2), y = (maxY/2)};
for i, v in pairs(load_table) do
Object.elements[i] = {}
for j, v2 in pairs(v) do
if v2 ~= " " then
local position = { x = j-1, y = i-1 };
print("Loading element", v2);
Object.elements[i][j] = blocFunctions[v2](position);
if sprSize == nil then
sprSize = Object.elements[i][j][1].getSprSize();
end
end
end
end
print("Setting camera");
local pVec = obe.Transform.UnitVector(
offset.x * sprSize.x,
offset.y * sprSize.y
);
local ySize = maxY/Engine.Scene:getCamera():getSize().y;
local xSize = maxX/Engine.Scene:getCamera():getSize().x;
local pSize = sprSize.x * (ySize > xSize and ySize or xSize);
local camera = Engine.Scene:getCamera();
camera:setPosition(pVec, obe.Transform.Referential.Center);
camera:scale(pSize, obe.Transform.Referential.Center);
print("Terrain done :)");
Object.initialized = true;
end
end
function Local.Init(toBind)
function_binding(toBind);
Object.elements = {};
end
function file_exists(path)
local f = io.open(path, "r")
if f then f:close() end
return f ~= nil
end
function lines_from(path)
lines = {}
for line in io.lines(path) do
lines[#lines + 1] = line
end
return lines
end
| 2,748
|
Alaznist/Examples
|
End of preview. Expand
in Data Studio
README.md exists but content is empty.
- Downloads last month
- -