repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
badboyam/crazy_bot | plugins/stats.lua | 458 | 4098 | -- Saves the number of messages from a user
-- Can check the number of messages with !stats
do
local NUM_MSG_MAX = 5
local TIME_CHECK = 4 -- seconds
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end | gpl-2.0 |
emadni/launcherlord | plugins/stats.lua | 458 | 4098 | -- Saves the number of messages from a user
-- Can check the number of messages with !stats
do
local NUM_MSG_MAX = 5
local TIME_CHECK = 4 -- seconds
local function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end | gpl-2.0 |
pirate/snabbswitch | src/core/timer.lua | 14 | 2701 | module(...,package.seeall)
local ffi = require("ffi")
local C = ffi.C
local lib = require("core.lib")
debug = _G.developer_debug
ticks = false -- current time, in ticks
ns_per_tick = 1e6 -- tick resolution (millisecond)
timers = {} -- table of {tick->timerlist}
-- This function can be removed in the future.
-- For now it exists to help people understand why their code now
-- breaks if it calls timer.init().
function init ()
error("timer.init() function is gone (timer module auto-initializes)")
end
-- Run all timers that have expired.
function run ()
if ticks then run_to_time(tonumber(C.get_time_ns())) end
end
-- Run all timers up to the given new time.
local function call_timers (l)
for i=1,#l do
local timer = l[i]
if debug then
print(string.format("running timer %s at tick %s", timer.name, ticks))
end
timer.fn(timer)
if timer.repeating then activate(timer) end
end
end
function run_to_time (ns)
local new_ticks = math.floor(tonumber(ns) / ns_per_tick)
for tick = ticks, new_ticks do
ticks = tick
if timers[ticks] then
call_timers(timers[ticks])
timers[ticks] = nil
end
end
end
function activate (t)
-- Initialize time
if not ticks then
ticks = math.floor(tonumber(C.get_time_ns() / ns_per_tick))
end
local tick = ticks + t.ticks
if timers[tick] then
table.insert(timers[tick], t)
else
timers[tick] = {t}
end
end
function new (name, fn, nanos, mode)
return { name = name,
fn = fn,
ticks = math.ceil(nanos / ns_per_tick),
repeating = (mode == 'repeating') }
end
function selftest ()
print("selftest: timer")
ticks = 0
local ntimers, runtime = 10000, 100000
local count, expected_count = 0, 0
local fn = function (t) count = count + 1 end
local start = C.get_monotonic_time()
-- Start timers, each counting at a different frequency
for freq = 1, ntimers do
local t = new("timer"..freq, fn, ns_per_tick * freq, 'repeating')
activate(t)
expected_count = expected_count + math.floor(runtime / freq)
end
-- Run timers for 'runtime' in random sized time steps
local now_ticks = 0
while now_ticks < runtime do
now_ticks = math.min(runtime, now_ticks + math.random(5))
local old_count = count
run_to_time(now_ticks * ns_per_tick)
assert(count > old_count, "count increasing")
end
assert(count == expected_count, "final count correct")
local finish = C.get_monotonic_time()
local elapsed_time = finish - start
print(("ok (%s callbacks in %.4f seconds)"):format(
lib.comma_value(count), elapsed_time))
end
| apache-2.0 |
ahuraa/trinityadmin | Commands/Commands_Server.lua | 2 | 1845 | -------------------------------------------------------------------------------------------------------------
--
-- TrinityAdmin Version 3.x
-- TrinityAdmin is a derivative of MangAdmin.
--
-- Copyright (C) 2007 Free Software Foundation, Inc.
-- License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
-- This is free software: you are free to change and redistribute it.
-- There is NO WARRANTY, to the extent permitted by law.
--
-- 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
--
-- Official Forums: http://groups.google.com/group/trinityadmin
-- GoogleCode Website: http://code.google.com/p/trinityadmin/
-- Subversion Repository: http://trinityadmin.googlecode.com/svn/
-- Dev Blog: http://trinityadmin.blogspot.com/
-------------------------------------------------------------------------------------------------------------
function Announce(value)
MangAdmin:ChatMsg(".announce "..value)
MangAdmin:LogAction("Announced message: "..value)
end
function Shutdown(value)
if value == "" then
MangAdmin:ChatMsg(".server shutdown 0")
MangAdmin:LogAction("Shut down server instantly.")
else
MangAdmin:ChatMsg(".server shutdown "..value)
MangAdmin:LogAction("Shut down server in "..value.." seconds.")
end
end
function ReloadTable(tablename)
if not (tablename == "") then
MangAdmin:ChatMsg(".reload "..tablename)
if tablename == "all" then
MangAdmin:LogAction("Reloaded all reloadable Trinity database tables.")
else
MangAdmin:LogAction("Reloaded the table "..tablename..".")
end
end
end
function ReloadScripts()
MangAdmin:ChatMsg(".loadscripts")
MangAdmin:LogAction("(Re-)Loaded scripts.")
end
| gpl-2.0 |
salorium/awesome | spec/wibox/widget/base_spec.lua | 14 | 3351 | ---------------------------------------------------------------------------
-- @author Uli Schlachter
-- @copyright 2016 Uli Schlachter
---------------------------------------------------------------------------
local base = require("wibox.widget.base")
local no_parent = base.no_parent_I_know_what_I_am_doing
describe("wibox.widget.base", function()
local widget1, widget2
before_each(function()
widget1 = base.make_widget()
widget2 = base.make_widget()
widget1.layout = function()
return { base.place_widget_at(widget2, 0, 0, 1, 1) }
end
end)
describe("caches", function()
it("garbage collectable", function()
local alive = setmetatable({ widget1, widget2 }, { __mode = "kv" })
assert.is.equal(2, #alive)
widget1, widget2 = nil, nil
collectgarbage("collect")
assert.is.equal(0, #alive)
end)
it("simple cache clear", function()
local alive = setmetatable({ widget1, widget2 }, { __mode = "kv" })
base.layout_widget(no_parent, { "fake context" }, widget1, 20, 20)
assert.is.equal(2, #alive)
widget1, widget2 = nil, nil
collectgarbage("collect")
assert.is.equal(0, #alive)
end)
it("self-reference cache clear", function()
widget2.widget = widget1
local alive = setmetatable({ widget1, widget2 }, { __mode = "kv" })
base.layout_widget(no_parent, { "fake context" }, widget1, 20, 20)
assert.is.equal(2, #alive)
widget1, widget2 = nil, nil
collectgarbage("collect")
assert.is.equal(0, #alive)
end)
end)
describe("setup", function()
it("Filters out 'false'", function()
-- Regression test: There was a bug where "nil"s where correctly
-- skipped, but "false" entries survived
local layout1, layout2 = base.make_widget(), base.make_widget()
local called = false
function layout1:set_widget(w)
called = true
assert.equals(w, layout2)
end
function layout2:set_children(children)
assert.is_same({nil, widget1, nil, widget2}, children)
end
layout2.allow_empty_widget = true
layout1:setup{ layout = layout2, false, widget1, nil, widget2 }
assert.is_true(called)
end)
it("Attribute 'false' works", function()
-- Regression test: I introduced a bug with the above fix
local layout1, layout2 = base.make_widget(), base.make_widget()
local called1, called2 = false, false
function layout1:set_widget(w)
called1 = true
assert.equals(w, layout2)
end
function layout2:set_children(children)
assert.is_same({}, children)
end
function layout2:set_foo(foo)
called2 = true
assert.is_false(foo)
end
layout1:setup{ layout = layout2, foo = false }
assert.is_true(called1)
assert.is_true(called2)
end)
end)
end)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
judos/robotMiningSite | source/libs/control/gui.lua | 1 | 4872 |
-- Constants:
local guiUpdateEveryTicks = 5
--------------------------------------------------
-- API
--------------------------------------------------
-- Requried:
-- modName - prefix which your ui components have. e.g. "hc.belt-sorter.1.1" (modName = "hc")
-- Usage:
-- each known gui defines these functions:
gui = {} -- [$entityName] = { open = $function(player,entity),
-- close = $function(player),
-- click = $function(nameArr, player, entity) }
-- Required Calls from control.lua:
-- gui_tick()
-- gui_init()
-- Helper functions:
-- gui_playersWithOpenGuiOf(entity) : {x:LuaPlayer, ...}
-- gui_scheduleEvent($uiComponentIdentifier,$player)
--------------------------------------------------
-- Global data
--------------------------------------------------
-- This helper file uses the following global data variables:
-- global.gui.playerData[$playerName].openGui = $(name of opened entity)
-- .openEntity = $(reference of LuaEntity)
-- " events[$tick] = { {$uiComponentIdentifier, $player}, ... }
-- " version = $number
--------------------------------------------------
-- Implementation
--------------------------------------------------
function gui_init()
if global.gui == nil then
global.gui = {
playerData = {},
events = {},
version = 1
}
end
local prevGui = global.gui.version
if not global.gui.version then
global.gui.version = 1
global.itemSelection = nil
end
if global.gui.version ~= prevGui then
info("Migrated gui version to "..tostring(global.gui.version))
end
end
local function handleEvent(uiComponentIdentifier,player)
local guiEvent = split(uiComponentIdentifier,".")
local eventIsForMod = table.remove(guiEvent,1)
if eventIsForMod == modName then
local entityName = global.gui.playerData[player.name].openGui
if entityName and gui[entityName] then
if gui[entityName].click ~= nil then
local entity = global.gui.playerData[player.name].openEntity
gui[entityName].click(guiEvent,player,entity)
end
elseif entityName == nil then
warn("No entityName found for player "..player.name)
warn(global.gui.playerData[player.name])
else
warn("No gui registered for "..entityName)
end
return true
else
-- gui event might be from other mods
info("unknown gui event occured: "..serpent.block(uiComponentIdentifier))
end
end
function gui_scheduleEvent(uiComponentIdentifier,player)
global.gui.events = global.gui.events or {}
table.insert(global.gui.events,{uiComponentIdentifier=uiComponentIdentifier,player=player})
end
local function playerCloseGui(player,playerData,openGui)
if gui[openGui] ~= nil and gui[openGui].close ~= nil then
gui[openGui].close(player)
end
playerData.openGui = nil
playerData.openEntity = nil
end
local function playerOpenGui(player,playerData,openEntity)
local openGui = openEntity.name
playerData.openGui = openGui
playerData.openEntity = openEntity
if gui[openGui] ~= nil and gui[openGui].open ~= nil then
gui[openGui].open(player,openEntity)
end
end
function gui_tick()
if game.tick % guiUpdateEveryTicks ~= 0 then return end
if global.gui.events ~= nil then
local events = global.gui.events
global.gui.events = nil
if #events > 0 then
for _,event in pairs(events) do
handleEvent(event.uiComponentIdentifier, event.player)
end
end
end
for _,player in pairs(game.players) do
if player.connected then
local openEntity = player.opened
local playerName = player.name
if global.gui.playerData[playerName] == nil then global.gui.playerData[playerName] = {} end
local playerData = global.gui.playerData[playerName]
local openGui = playerData.openGui
if openGui ~= nil and playerData.openEntity ~= openEntity then
playerCloseGui(player,playerData,openGui)
end
if openGui == nil and openEntity ~= nil then
playerOpenGui(player,playerData,openEntity)
end
end
end
end
--------------------------------------------------
-- Event registration
--------------------------------------------------
local function handleGuiEvent(event)
local player = game.players[event.player_index]
local uiComponentIdentifier = event.element.name
return handleEvent(uiComponentIdentifier,player)
end
script.on_event(defines.events.on_gui_click,handleGuiEvent)
script.on_event(defines.events.on_gui_text_changed,handleGuiEvent)
script.on_event(defines.events.on_gui_elem_changed,handleGuiEvent)
--------------------------------------------------
-- Helper functions
--------------------------------------------------
function gui_playersWithOpenGuiOf(entity)
local result = {}
for _,player in pairs(game.players) do
if player.connected then
local openEntity = player.opened
if openEntity == entity then
table.insert(result,player)
end
end
end
return result
end
| gpl-3.0 |
payday-restoration/restoration-mod | lua/sc/core/coreenvironmentcontrollermanager.lua | 1 | 1855 | local init_orig = CoreEnvironmentControllerManager.init
function CoreEnvironmentControllerManager:init()
init_orig(self)
self._GAME_DEFAULT_COLOR_GRADING = "color_payday"
end
local set_post_composite_orig = CoreEnvironmentControllerManager.set_post_composite
local ids_LUT_post = Idstring("color_grading_post")
local ids_LUT_settings = Idstring("lut_settings")
local ids_LUT_settings_a = Idstring("LUT_settings_a")
local ids_LUT_settings_b = Idstring("LUT_settings_b")
local ids_LUT_contrast = Idstring("contrast")
function CoreEnvironmentControllerManager:set_post_composite(t, dt)
set_post_composite_orig(self, t, dt)
if not restoration.Options:GetValue("OTHER/AltLastDownColor") then
return set_post_composite_orig(self, t, dt)
end
local vp = managers.viewport:first_active_viewport()
if not vp then
return
end
if not alive(self._vp) then
return
end
local last_life = 0
if self._last_life then
last_life = 0 and self._vp:vp():set_post_processor_effect("World", Idstring("color_grading_post"), Idstring("color_sin_classic"))
self._ignore_user_color_grading = true
else
local color_grading = self._default_color_grading
if not self._ignore_user_color_grading then
color_grading = managers.user:get_setting("video_color_grading") or self._default_color_grading
end
self._vp:vp():set_post_processor_effect("World", Idstring("color_grading_post"), Idstring(color_grading))
end
end
--[[function CoreEnvironmentControllerManager:set_chromatic_enabled(enabled)
self._chromatic_enabled = enabled
if self._material then
if self._chromatic_enabled then
self._material:set_variable(Idstring("chromatic_amount"), self._base_chromatic_amount)
else
self._material:set_variable(Idstring("chromatic_amount"), 0)
end
end
end]]--
| agpl-3.0 |
MrCerealGuy/Stonecraft | games/stonecraft_game/mods/technic/technic/crafts.lua | 1 | 6336 | -- check if we have the necessary dependencies to allow actually using these materials in the crafts
local mesecons_materials
if minetest.get_modpath("mesecons_materials") and not core.skip_mod("mesecons") then
mesecons_materials = minetest.get_modpath("mesecons_materials")
end
-- Remove some recipes
-- Bronze
minetest.clear_craft({
type = "shapeless",
output = "default:bronze_ingot"
})
-- Restore recipe for bronze block to ingots
minetest.register_craft({
output = "default:bronze_ingot 9",
recipe = {
{"default:bronzeblock"}
}
})
-- Accelerator tube
if pipeworks.enable_accelerator_tube then
minetest.clear_craft({
output = "pipeworks:accelerator_tube_1",
})
minetest.register_craft({
output = 'pipeworks:accelerator_tube_1',
recipe = {
{'technic:copper_coil', 'pipeworks:tube_1', 'technic:copper_coil'},
}
})
end
-- Teleport tube
if pipeworks.enable_teleport_tube then
minetest.clear_craft({
output = "pipeworks:teleport_tube_1",
})
minetest.register_craft({
output = 'pipeworks:teleport_tube_1',
recipe = {
{'default:mese_crystal', 'technic:copper_coil', 'default:mese_crystal'},
{'pipeworks:tube_1', 'technic:control_logic_unit', 'pipeworks:tube_1'},
{'default:mese_crystal', 'technic:copper_coil', 'default:mese_crystal'},
}
})
end
-- basic materials' brass ingot
minetest.clear_craft({
output = "basic_materials:brass_ingot",
})
minetest.register_craft( {
type = "shapeless",
output = "basic_materials:brass_ingot 9",
recipe = { "basic_materials:brass_block" },
})
-- tubes crafting recipes
minetest.register_craft({
output = 'technic:diamond_drill_head',
recipe = {
{'technic:stainless_steel_ingot', 'default:diamond', 'technic:stainless_steel_ingot'},
{'default:diamond', '', 'default:diamond'},
{'technic:stainless_steel_ingot', 'default:diamond', 'technic:stainless_steel_ingot'},
}
})
minetest.register_craft({
output = 'technic:green_energy_crystal',
recipe = {
{'default:gold_ingot', 'technic:battery', 'dye:green'},
{'technic:battery', 'technic:red_energy_crystal', 'technic:battery'},
{'dye:green', 'technic:battery', 'default:gold_ingot'},
}
})
minetest.register_craft({
output = 'technic:blue_energy_crystal',
recipe = {
{'moreores:mithril_ingot', 'technic:battery', 'dye:blue'},
{'technic:battery', 'technic:green_energy_crystal', 'technic:battery'},
{'dye:blue', 'technic:battery', 'moreores:mithril_ingot'},
}
})
minetest.register_craft({
output = 'technic:red_energy_crystal',
recipe = {
{'moreores:silver_ingot', 'technic:battery', 'dye:red'},
{'technic:battery', 'basic_materials:energy_crystal_simple', 'technic:battery'},
{'dye:red', 'technic:battery', 'moreores:silver_ingot'},
}
})
minetest.register_craft({
output = 'technic:copper_coil 1',
recipe = {
{'basic_materials:copper_wire', 'technic:wrought_iron_ingot', 'basic_materials:copper_wire'},
{'technic:wrought_iron_ingot', '', 'technic:wrought_iron_ingot'},
{'basic_materials:copper_wire', 'technic:wrought_iron_ingot', 'basic_materials:copper_wire'},
},
replacements = {
{"basic_materials:copper_wire", "basic_materials:empty_spool"},
{"basic_materials:copper_wire", "basic_materials:empty_spool"},
{"basic_materials:copper_wire", "basic_materials:empty_spool"},
{"basic_materials:copper_wire", "basic_materials:empty_spool"}
},
})
local isolation = mesecons_materials and "mesecons_materials:fiber" or "technic:rubber"
minetest.register_craft({
output = 'technic:lv_transformer',
recipe = {
{isolation, 'technic:wrought_iron_ingot', isolation},
{'technic:copper_coil', 'technic:wrought_iron_ingot', 'technic:copper_coil'},
{'technic:wrought_iron_ingot', 'technic:wrought_iron_ingot', 'technic:wrought_iron_ingot'},
}
})
minetest.register_craft({
output = 'technic:mv_transformer',
recipe = {
{isolation, 'technic:carbon_steel_ingot', isolation},
{'technic:copper_coil', 'technic:carbon_steel_ingot', 'technic:copper_coil'},
{'technic:carbon_steel_ingot', 'technic:carbon_steel_ingot', 'technic:carbon_steel_ingot'},
}
})
minetest.register_craft({
output = 'technic:hv_transformer',
recipe = {
{isolation, 'technic:stainless_steel_ingot', isolation},
{'technic:copper_coil', 'technic:stainless_steel_ingot', 'technic:copper_coil'},
{'technic:stainless_steel_ingot', 'technic:stainless_steel_ingot', 'technic:stainless_steel_ingot'},
}
})
minetest.register_craft({
output = 'technic:control_logic_unit',
recipe = {
{'', 'basic_materials:gold_wire', ''},
{'default:copper_ingot', 'technic:silicon_wafer', 'default:copper_ingot'},
{'', 'technic:chromium_ingot', ''},
},
replacements = { {"basic_materials:gold_wire", "basic_materials:empty_spool"}, },
})
minetest.register_craft({
output = 'technic:mixed_metal_ingot 9',
recipe = {
{'technic:stainless_steel_ingot', 'technic:stainless_steel_ingot', 'technic:stainless_steel_ingot'},
{'default:bronze_ingot', 'default:bronze_ingot', 'default:bronze_ingot'},
{'default:tin_ingot', 'default:tin_ingot', 'default:tin_ingot'},
}
})
minetest.register_craft({
output = 'technic:carbon_cloth',
recipe = {
{'technic:graphite', 'technic:graphite', 'technic:graphite'}
}
})
minetest.register_craft({
output = "technic:machine_casing",
recipe = {
{ "technic:cast_iron_ingot", "technic:cast_iron_ingot", "technic:cast_iron_ingot" },
{ "technic:cast_iron_ingot", "basic_materials:brass_ingot", "technic:cast_iron_ingot" },
{ "technic:cast_iron_ingot", "technic:cast_iron_ingot", "technic:cast_iron_ingot" },
},
})
minetest.register_craft({
output = "default:dirt 2",
type = "shapeless",
replacements = {{"bucket:bucket_water","bucket:bucket_empty"}},
recipe = {
"technic:stone_dust",
"group:leaves",
"bucket:bucket_water",
"group:sand",
},
})
minetest.register_craft({
output = "technic:rubber_goo",
type = "shapeless",
recipe = {
"technic:raw_latex",
"default:coal_lump",
"default:coal_lump",
"default:coal_lump",
"default:coal_lump",
"default:coal_lump",
"default:coal_lump",
"default:coal_lump",
"default:coal_lump",
},
})
minetest.register_craft({
output = "technic:rubber",
type = "cooking",
recipe = "technic:rubber_goo",
})
| gpl-3.0 |
rgujju/NexIDE | firmware/app/cjson/lua/cjson/util.lua | 170 | 6837 | local json = require "cjson"
-- Various common routines used by the Lua CJSON package
--
-- Mark Pulford <mark@kyne.com.au>
-- Determine with a Lua table can be treated as an array.
-- Explicitly returns "not an array" for very sparse arrays.
-- Returns:
-- -1 Not an array
-- 0 Empty table
-- >0 Highest index in the array
local function is_array(table)
local max = 0
local count = 0
for k, v in pairs(table) do
if type(k) == "number" then
if k > max then max = k end
count = count + 1
else
return -1
end
end
if max > count * 2 then
return -1
end
return max
end
local serialise_value
local function serialise_table(value, indent, depth)
local spacing, spacing2, indent2
if indent then
spacing = "\n" .. indent
spacing2 = spacing .. " "
indent2 = indent .. " "
else
spacing, spacing2, indent2 = " ", " ", false
end
depth = depth + 1
if depth > 50 then
return "Cannot serialise any further: too many nested tables"
end
local max = is_array(value)
local comma = false
local fragment = { "{" .. spacing2 }
if max > 0 then
-- Serialise array
for i = 1, max do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment, serialise_value(value[i], indent2, depth))
comma = true
end
elseif max < 0 then
-- Serialise table
for k, v in pairs(value) do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment,
("[%s] = %s"):format(serialise_value(k, indent2, depth),
serialise_value(v, indent2, depth)))
comma = true
end
end
table.insert(fragment, spacing .. "}")
return table.concat(fragment)
end
function serialise_value(value, indent, depth)
if indent == nil then indent = "" end
if depth == nil then depth = 0 end
if value == json.null then
return "json.null"
elseif type(value) == "string" then
return ("%q"):format(value)
elseif type(value) == "nil" or type(value) == "number" or
type(value) == "boolean" then
return tostring(value)
elseif type(value) == "table" then
return serialise_table(value, indent, depth)
else
return "\"<" .. type(value) .. ">\""
end
end
local function file_load(filename)
local file
if filename == nil then
file = io.stdin
else
local err
file, err = io.open(filename, "rb")
if file == nil then
error(("Unable to read '%s': %s"):format(filename, err))
end
end
local data = file:read("*a")
if filename ~= nil then
file:close()
end
if data == nil then
error("Failed to read " .. filename)
end
return data
end
local function file_save(filename, data)
local file
if filename == nil then
file = io.stdout
else
local err
file, err = io.open(filename, "wb")
if file == nil then
error(("Unable to write '%s': %s"):format(filename, err))
end
end
file:write(data)
if filename ~= nil then
file:close()
end
end
local function compare_values(val1, val2)
local type1 = type(val1)
local type2 = type(val2)
if type1 ~= type2 then
return false
end
-- Check for NaN
if type1 == "number" and val1 ~= val1 and val2 ~= val2 then
return true
end
if type1 ~= "table" then
return val1 == val2
end
-- check_keys stores all the keys that must be checked in val2
local check_keys = {}
for k, _ in pairs(val1) do
check_keys[k] = true
end
for k, v in pairs(val2) do
if not check_keys[k] then
return false
end
if not compare_values(val1[k], val2[k]) then
return false
end
check_keys[k] = nil
end
for k, _ in pairs(check_keys) do
-- Not the same if any keys from val1 were not found in val2
return false
end
return true
end
local test_count_pass = 0
local test_count_total = 0
local function run_test_summary()
return test_count_pass, test_count_total
end
local function run_test(testname, func, input, should_work, output)
local function status_line(name, status, value)
local statusmap = { [true] = ":success", [false] = ":error" }
if status ~= nil then
name = name .. statusmap[status]
end
print(("[%s] %s"):format(name, serialise_value(value, false)))
end
local result = { pcall(func, unpack(input)) }
local success = table.remove(result, 1)
local correct = false
if success == should_work and compare_values(result, output) then
correct = true
test_count_pass = test_count_pass + 1
end
test_count_total = test_count_total + 1
local teststatus = { [true] = "PASS", [false] = "FAIL" }
print(("==> Test [%d] %s: %s"):format(test_count_total, testname,
teststatus[correct]))
status_line("Input", nil, input)
if not correct then
status_line("Expected", should_work, output)
end
status_line("Received", success, result)
print()
return correct, result
end
local function run_test_group(tests)
local function run_helper(name, func, input)
if type(name) == "string" and #name > 0 then
print("==> " .. name)
end
-- Not a protected call, these functions should never generate errors.
func(unpack(input or {}))
print()
end
for _, v in ipairs(tests) do
-- Run the helper if "should_work" is missing
if v[4] == nil then
run_helper(unpack(v))
else
run_test(unpack(v))
end
end
end
-- Run a Lua script in a separate environment
local function run_script(script, env)
local env = env or {}
local func
-- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists
if _G.setfenv then
func = loadstring(script)
if func then
setfenv(func, env)
end
else
func = load(script, nil, nil, env)
end
if func == nil then
error("Invalid syntax.")
end
func()
return env
end
-- Export functions
return {
serialise_value = serialise_value,
file_load = file_load,
file_save = file_save,
compare_values = compare_values,
run_test_summary = run_test_summary,
run_test = run_test,
run_test_group = run_test_group,
run_script = run_script
}
-- vi:ai et sw=4 ts=4:
| gpl-3.0 |
rgujju/NexIDE | firmware/lua_examples/irsend.lua | 88 | 1803 | ------------------------------------------------------------------------------
-- IR send module
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <dronnikov@gmail.com>
--
-- Example:
-- dofile("irsend.lua").nec(4, 0x00ff00ff)
------------------------------------------------------------------------------
local M
do
-- const
local NEC_PULSE_US = 1000000 / 38000
local NEC_HDR_MARK = 9000
local NEC_HDR_SPACE = 4500
local NEC_BIT_MARK = 560
local NEC_ONE_SPACE = 1600
local NEC_ZERO_SPACE = 560
local NEC_RPT_SPACE = 2250
-- cache
local gpio, bit = gpio, bit
local mode, write = gpio.mode, gpio.write
local waitus = tmr.delay
local isset = bit.isset
-- NB: poorman 38kHz PWM with 1/3 duty. Touch with care! )
local carrier = function(pin, c)
c = c / NEC_PULSE_US
while c > 0 do
write(pin, 1)
write(pin, 0)
c = c + 0
c = c + 0
c = c + 0
c = c + 0
c = c + 0
c = c + 0
c = c * 1
c = c * 1
c = c * 1
c = c - 1
end
end
-- tsop signal simulator
local pull = function(pin, c)
write(pin, 0)
waitus(c)
write(pin, 1)
end
-- NB: tsop mode allows to directly connect pin
-- inplace of TSOP input
local nec = function(pin, code, tsop)
local pulse = tsop and pull or carrier
-- setup transmitter
mode(pin, 1)
write(pin, tsop and 1 or 0)
-- header
pulse(pin, NEC_HDR_MARK)
waitus(NEC_HDR_SPACE)
-- sequence, lsb first
for i = 31, 0, -1 do
pulse(pin, NEC_BIT_MARK)
waitus(isset(code, i) and NEC_ONE_SPACE or NEC_ZERO_SPACE)
end
-- trailer
pulse(pin, NEC_BIT_MARK)
-- done transmitter
--mode(pin, 0, tsop and 1 or 0)
end
-- expose
M = {
nec = nec,
}
end
return M
| gpl-3.0 |
wcjscm/JackGame | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ControlColourPicker.lua | 11 | 3144 |
--------------------------------
-- @module ControlColourPicker
-- @extend Control
-- @parent_module cc
--------------------------------
--
-- @function [parent=#ControlColourPicker] hueSliderValueChanged
-- @param self
-- @param #cc.Ref sender
-- @param #int controlEvent
-- @return ControlColourPicker#ControlColourPicker self (return value: cc.ControlColourPicker)
--------------------------------
--
-- @function [parent=#ControlColourPicker] getHuePicker
-- @param self
-- @return ControlHuePicker#ControlHuePicker ret (return value: cc.ControlHuePicker)
--------------------------------
--
-- @function [parent=#ControlColourPicker] getcolourPicker
-- @param self
-- @return ControlSaturationBrightnessPicker#ControlSaturationBrightnessPicker ret (return value: cc.ControlSaturationBrightnessPicker)
--------------------------------
--
-- @function [parent=#ControlColourPicker] setBackground
-- @param self
-- @param #cc.Sprite var
-- @return ControlColourPicker#ControlColourPicker self (return value: cc.ControlColourPicker)
--------------------------------
--
-- @function [parent=#ControlColourPicker] setcolourPicker
-- @param self
-- @param #cc.ControlSaturationBrightnessPicker var
-- @return ControlColourPicker#ControlColourPicker self (return value: cc.ControlColourPicker)
--------------------------------
--
-- @function [parent=#ControlColourPicker] colourSliderValueChanged
-- @param self
-- @param #cc.Ref sender
-- @param #int controlEvent
-- @return ControlColourPicker#ControlColourPicker self (return value: cc.ControlColourPicker)
--------------------------------
--
-- @function [parent=#ControlColourPicker] setHuePicker
-- @param self
-- @param #cc.ControlHuePicker var
-- @return ControlColourPicker#ControlColourPicker self (return value: cc.ControlColourPicker)
--------------------------------
--
-- @function [parent=#ControlColourPicker] getBackground
-- @param self
-- @return Sprite#Sprite ret (return value: cc.Sprite)
--------------------------------
--
-- @function [parent=#ControlColourPicker] create
-- @param self
-- @return ControlColourPicker#ControlColourPicker ret (return value: cc.ControlColourPicker)
--------------------------------
--
-- @function [parent=#ControlColourPicker] setEnabled
-- @param self
-- @param #bool bEnabled
-- @return ControlColourPicker#ControlColourPicker self (return value: cc.ControlColourPicker)
--------------------------------
--
-- @function [parent=#ControlColourPicker] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ControlColourPicker] setColor
-- @param self
-- @param #color3b_table colorValue
-- @return ControlColourPicker#ControlColourPicker self (return value: cc.ControlColourPicker)
--------------------------------
-- js ctor<br>
-- lua new
-- @function [parent=#ControlColourPicker] ControlColourPicker
-- @param self
-- @return ControlColourPicker#ControlColourPicker self (return value: cc.ControlColourPicker)
return nil
| gpl-3.0 |
Djabbz/nn | Parallel.lua | 39 | 3780 | local Parallel, parent = torch.class('nn.Parallel', 'nn.Container')
function Parallel:__init(inputDimension,outputDimension)
parent.__init(self)
self.modules = {}
self.size = torch.LongStorage()
self.inputDimension = inputDimension
self.outputDimension = outputDimension
end
function Parallel:updateOutput(input)
local nModule=input:size(self.inputDimension)
local outputs = {}
for i=1,nModule do
local currentInput = input:select(self.inputDimension,i)
local currentOutput = self.modules[i]:updateOutput(currentInput)
table.insert(outputs, currentOutput)
local outputSize = currentOutput:size(self.outputDimension)
if i == 1 then
self.size:resize(currentOutput:dim()):copy(currentOutput:size())
else
self.size[self.outputDimension] = self.size[self.outputDimension] + outputSize
end
end
self.output:resize(self.size)
local offset = 1
for i=1,nModule do
local currentOutput = outputs[i]
local outputSize = currentOutput:size(self.outputDimension)
self.output:narrow(self.outputDimension, offset, outputSize):copy(currentOutput)
offset = offset + currentOutput:size(self.outputDimension)
end
return self.output
end
function Parallel:updateGradInput(input, gradOutput)
local nModule=input:size(self.inputDimension)
self.gradInput:resizeAs(input)
local offset = 1
for i=1,nModule do
local module=self.modules[i]
local currentInput = input:select(self.inputDimension,i)
local currentOutput = module.output
local outputSize = currentOutput:size(self.outputDimension)
local currentGradOutput = gradOutput:narrow(self.outputDimension, offset, outputSize)
local currentGradInput = module:updateGradInput(currentInput, currentGradOutput)
self.gradInput:select(self.inputDimension,i):copy(currentGradInput)
offset = offset + outputSize
end
return self.gradInput
end
function Parallel:accGradParameters(input, gradOutput, scale)
local nModule=input:size(self.inputDimension)
local offset = 1
for i=1,nModule do
local module = self.modules[i]
local currentOutput = module.output
local outputSize = currentOutput:size(self.outputDimension)
module:accGradParameters(
input:select(self.inputDimension,i),
gradOutput:narrow(self.outputDimension, offset,outputSize),
scale
)
offset = offset + outputSize
end
end
function Parallel:accUpdateGradParameters(input, gradOutput, lr)
local nModule=input:size(self.inputDimension)
local offset = 1
for i=1,nModule do
local module = self.modules[i];
local currentOutput = module.output
module:accUpdateGradParameters(
input:select(self.inputDimension,i),
gradOutput:narrow(self.outputDimension, offset,
currentOutput:size(self.outputDimension)),
lr)
offset = offset + currentOutput:size(self.outputDimension)
end
end
function Parallel:__tostring__()
local tab = ' '
local line = '\n'
local next = ' |`-> '
local ext = ' | '
local extlast = ' '
local last = ' ... -> '
local str = torch.type(self)
str = str .. ' {' .. line .. tab .. 'input'
for i=1,#self.modules do
if i == self.modules then
str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. extlast)
else
str = str .. line .. tab .. next .. '(' .. i .. '): ' .. tostring(self.modules[i]):gsub(line, line .. tab .. ext)
end
end
str = str .. line .. tab .. last .. 'output'
str = str .. line .. '}'
return str
end
| bsd-3-clause |
Hello23-Ygopro/ygopro-kaijudo | expansions/script/c25003027.lua | 1 | 1052 | --Starlight Strategist
local ka=require "expansions.utility_ktcg"
local scard,sid=ka.GetID()
function scard.initial_effect(c)
ka.EnableCreatureAttribute(c)
--double breaker
ka.EnableBreaker(c,KA_ABILITY_DOUBLE_BREAKER)
--tap
ka.AddSingleComeIntoPlayAbility(c,0,nil,scard.postg,scard.posop1,EFFECT_FLAG_CARD_TARGET)
ka.AddComeIntoPlayAbility(c,0,nil,scard.postg,scard.posop2,EFFECT_FLAG_CARD_TARGET,scard.poscon)
end
scard.kaijudo_card=true
scard.postg=ka.TargetCardFunction(PLAYER_PLAYER,Card.IsUntapped,0,KA_LOCATION_BATTLE,1,1,KA_HINTMSG_TAP)
scard.posop1=ka.TargetTapUntapOperation(POS_FACEUP_TAPPED)
function scard.cfilter(c,tp)
return c:IsFaceup() and c:IsCreatureType(KA_CREATURE_SKYFORCE_CHAMPION) and c:IsControler(tp)
end
function scard.poscon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(scard.cfilter,1,e:GetHandler(),tp)
end
function scard.posop2(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToAbility(e) or e:GetHandler():IsFacedown() then return end
ka.TargetTapUntapOperation(POS_FACEUP_TAPPED)(e,tp,eg,ep,ev,re,r,rp)
end
| gpl-3.0 |
heysion/prosody-modules | mod_sift/mod_sift.lua | 32 | 6448 |
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
-- advertise disco features
module:add_feature("urn:xmpp:sift:1");
-- supported features
module:add_feature("urn:xmpp:sift:stanzas:iq");
module:add_feature("urn:xmpp:sift:stanzas:message");
module:add_feature("urn:xmpp:sift:stanzas:presence");
module:add_feature("urn:xmpp:sift:recipients:all");
module:add_feature("urn:xmpp:sift:senders:all");
-- allowed values of 'sender' and 'recipient' attributes
local senders = {
["all"] = true;
["local"] = true;
["others"] = true;
["remote"] = true;
["self"] = true;
};
local recipients = {
["all"] = true;
["bare"] = true;
["full"] = true;
};
-- this function converts a <message/>, <presence/> or <iq/> element in
-- the SIFT namespace into a hashtable, for easy lookup
local function to_hashtable(element)
if element ~= nil then
local hash = {};
-- make sure the sender and recipient attributes has a valid value
hash.sender = element.attr.sender or "all";
if not senders[hash.sender] then return false; end -- bad value, returning false
hash.recipient = element.attr.recipient or "all";
if not recipients[hash.recipient] then return false; end -- bad value, returning false
-- next we loop over all <allow/> elements
for _, tag in ipairs(element) do
if tag.name == "allow" and tag.attr.xmlns == "urn:xmpp:sift:1" then
-- make sure the element is valid
if not tag.attr.name or not tag.attr.ns then return false; end -- missing required attributes, returning false
hash[tag.attr.ns.."|"..tag.attr.name] = true;
hash.allowed = true; -- just a flag indicating we have some elements allowed
end
end
return hash;
end
end
local data = {}; -- table with all our data
-- handle SIFT set
module:hook("iq/self/urn:xmpp:sift:1:sift", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local sifttag = stanza.tags[1]; -- <sift/>
-- first, get the elements we are interested in
local message = sifttag:get_child("message");
local presence = sifttag:get_child("presence");
local iq = sifttag:get_child("iq");
-- for quick lookup, convert the elements into hashtables
message = to_hashtable(message);
presence = to_hashtable(presence);
iq = to_hashtable(iq);
-- make sure elements were valid
if message == false or presence == false or iq == false then
origin.send(st.error_reply(stanza, "modify", "bad-request"));
return true;
end
local existing = data[origin.full_jid] or {}; -- get existing data, if any
data[origin.full_jid] = { presence = presence, message = message, iq = iq }; -- store new data
origin.send(st.reply(stanza)); -- send back IQ result
if not existing.presence and not origin.presence and presence then
-- TODO send probes
end
return true;
end
end);
-- handle user disconnect
module:hook("resource-unbind", function(event)
data[event.session.full_jid] = nil; -- discard data
end);
-- IQ handler
module:hook("iq/full", function(event)
local origin, stanza = event.origin, event.stanza;
local siftdata = data[stanza.attr.to];
if stanza.attr.type == "get" or stanza.attr.type == "set" then
if siftdata and siftdata.iq then -- we seem to have an IQ filter
local tag = stanza.tags[1]; -- the IQ child
if not siftdata.iq[(tag.attr.xmlns or "jabber:client").."|"..tag.name] then
-- element not allowed; sending back generic error
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
return true;
end
end
end
end, 50);
-- Message to full JID handler
module:hook("message/full", function(event)
local origin, stanza = event.origin, event.stanza;
local siftdata = data[stanza.attr.to];
if siftdata and siftdata.message then -- we seem to have an message filter
local allowed = false;
for _, childtag in ipairs(stanza.tags) do
if siftdata.message[(childtag.attr.xmlns or "jabber:client").."|"..childtag.name] then
allowed = true;
end
end
if not allowed then
-- element not allowed; sending back generic error
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
-- FIXME maybe send to offline storage
return true;
end
end
end, 50);
-- Message to bare JID handler
module:hook("message/bare", function(event)
local origin, stanza = event.origin, event.stanza;
local user = bare_sessions[jid_bare(stanza.attr.to)];
local allowed = false;
for _, session in pairs(user and user.sessions or {}) do
local siftdata = data[session.full_jid];
if siftdata and siftdata.message then -- we seem to have an message filter
for _, childtag in ipairs(stanza.tags) do
if siftdata.message[(childtag.attr.xmlns or "jabber:client").."|"..childtag.name] then
allowed = true;
end
end
else
allowed = true;
end
end
if user and not allowed then
-- element not allowed; sending back generic error
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
-- FIXME maybe send to offline storage
return true;
end
end, 50);
-- Presence to full JID handler
module:hook("presence/full", function(event)
local origin, stanza = event.origin, event.stanza;
local siftdata = data[stanza.attr.to];
if siftdata and siftdata.presence then -- we seem to have an presence filter
local allowed = false;
for _, childtag in ipairs(stanza.tags) do
if siftdata.presence[(childtag.attr.xmlns or "jabber:client").."|"..childtag.name] then
allowed = true;
end
end
if not allowed then
-- element not allowed; sending back generic error
--origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
return true;
end
end
end, 50);
-- Presence to bare JID handler
module:hook("presence/bare", function(event)
local origin, stanza = event.origin, event.stanza;
local user = bare_sessions[jid_bare(stanza.attr.to)];
local allowed = false;
for _, session in pairs(user and user.sessions or {}) do
local siftdata = data[session.full_jid];
if siftdata and siftdata.presence then -- we seem to have an presence filter
for _, childtag in ipairs(stanza.tags) do
if siftdata.presence[(childtag.attr.xmlns or "jabber:client").."|"..childtag.name] then
allowed = true;
end
end
else
allowed = true;
end
end
if user and not allowed then
-- element not allowed; sending back generic error
--origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
return true;
end
end, 50);
| mit |
hfjgjfg/persianguard75 | plugins/chat.lua | 7 | 1391 | local function run(msg)
if msg.text == "سلام" then
return "سلام علیکم"
end
if msg.text == "Hi" then
return "Hello honey"
end
if msg.text == "Hello" then
return "Hi bb"
end
if msg.text == "hello" then
return "Hi honey"
end
if msg.text == "Salam" then
return "Salam aleykom"
end
if msg.text == "salam" then
return "va aleykol asalam"
end
if msg.text == "zac" then
return "Barash bezan sak"
end
if msg.text == "Mamad" then
return "کارتو بگو من به بابایی خودم میگم"
end
if msg.text == "mamad" then
return "کارتو بگو من به بابایی خودم میگم"
end
if msg.text == "محمد" then
return "کارتو بگو من به بابایی خودم میگم"
end
if msg.text == "mohammad" then
return "کارتو بگو من به بابایی خودم میگم"
end
if msg.text == "bot" then
return "hum?"
end
if msg.text == "Bot" then
return "Huuuum?"
end
if msg.text == "?" then
return "Hum??"
end
if msg.text == "بای" then
return "بسلامت"
end
if msg.text == "بای" then
return "بای بای"
end
end
return {
description = "Chat With Robot Server",
usage = "chat with robot",
patterns = {
"^سلام",
"^[Hh]ello$",
"^[Mm]ohammad$",
"^mamad$",
"^[Bb]ot$",
"^محمد$",
"^بای$",
"^?$",
"^[Ss]alam$",
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
xdel/snabbswitch | src/lib/checksum.lua | 8 | 8063 | module(...,package.seeall)
-- This module exposes the interface:
-- checksum.ipsum(pointer, length, initial) => checksum
--
-- pointer is a pointer to an array of data to be checksummed. initial
-- is an unsigned 16-bit number in host byte order which is used as
-- the starting value of the accumulator. The result is the IP
-- checksum over the data in host byte order.
--
-- The initial argument can be used to verify a checksum or to
-- calculate the checksum in an incremental manner over chunks of
-- memory. The synopsis to check whether the checksum over a block of
-- data is equal to a given value is the following
--
-- if ipsum(pointer, length, value) == 0 then
-- -- checksum correct
-- else
-- -- checksum incorrect
-- end
--
-- To chain the calculation of checksums over multiple blocks of data
-- together to obtain the overall checksum, one needs to pass the
-- one's complement of the checksum of one block as initial value to
-- the call of ipsum() for the following block, e.g.
--
-- local sum1 = ipsum(data1, length1, 0)
-- local total_sum = ipsum(data2, length2, bit.bnot(sum1))
--
-- The actual implementation is chosen based on running CPU.
require("lib.checksum_h")
local lib = require("core.lib")
local ffi = require("ffi")
local C = ffi.C
local band = bit.band
-- Select ipsum(pointer, len, initial) function based on hardware
-- capability.
local cpuinfo = lib.readfile("/proc/cpuinfo", "*a")
assert(cpuinfo, "failed to read /proc/cpuinfo for hardware check")
local have_avx2 = cpuinfo:match("avx2")
local have_sse2 = cpuinfo:match("sse2")
if have_avx2 then ipsum = C.cksum_avx2
elseif have_sse2 then ipsum = C.cksum_sse2
else ipsum = C.cksum_generic end
function finish_packet (buf, len, offset)
ffi.cast('uint16_t *', buf+offset)[0] = lib.htons(ipsum(buf, len, 0))
end
function verify_packet (buf, len)
local initial = C.pseudo_header_initial(buf, len)
if initial == 0xFFFF0001 then return nil
elseif initial == 0xFFFF0002 then return false
end
local headersize = 0
local ipv = band(buf[0], 0xF0)
if ipv == 0x60 then
headersize = 40
elseif ipv == 0x40 then
headersize = band(buf[0], 0x0F) * 4;
end
return ipsum(buf+headersize, len-headersize, initial) == 0
end
-- See checksum.h for more utility functions that can be added.
function selftest ()
print("selftest: checksum")
local tests = 1000
local n = 1000000
local array = ffi.new("char[?]", n)
for i = 0, n-1 do array[i] = i end
local avx2ok, sse2ok = 0, 0
for i = 1, tests do
local initial = math.random(0, 0xFFFF)
local ref = C.cksum_generic(array+i*2, i*10+i, initial)
if have_avx2 and C.cksum_avx2(array+i*2, i*10+i, initial) == ref then
avx2ok = avx2ok + 1
end
if have_sse2 and C.cksum_sse2(array+i*2, i*10+i, initial) == ref then
sse2ok = sse2ok + 1
end
assert(ipsum(array+i*2, i*10+i, initial) == ref, "API function check")
end
if have_avx2 then print("avx2: "..avx2ok.."/"..tests) else print("no avx2") end
if have_sse2 then print("sse2: "..sse2ok.."/"..tests) else print("no sse2") end
selftest_ipv4_tcp()
assert(not have_avx2 or avx2ok == tests, "AVX2 test failed")
assert(not have_sse2 or sse2ok == tests, "SSE2 test failed")
print("selftest: ok")
end
function selftest_ipv4_tcp ()
print("selftest: tcp/ipv4")
local s = "45 00 05 DC 00 26 40 00 40 06 20 F4 0A 00 00 01 0A 00 00 02 8A DE 13 89 6C 27 3B 04 1C E9 F9 C6 80 10 00 E5 5E 47 00 00 01 01 08 0A 01 0F 3A CA 01 0B 32 A9 00 00 00 00 00 00 00 01 00 00 13 89 00 00 00 00 00 00 00 00 FF FF E8 90 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36 37"
local data = lib.hexundump(s, 1500)
assert(verify_packet(ffi.cast("char*",data), #data), "TCP/IPv4 checksum validation failed")
end
| apache-2.0 |
Happy-Neko/xupnpd | src/plugins/xupnpd_vimeo.lua | 1 | 2513 | -- Copyright (C) 2011 Anton Burdinuk
-- clark15b@gmail.com
-- https://tsdemuxer.googlecode.com/svn/trunk/xupnpd
-- username, channel/channelname, group/groupname, album/album_id
function vimeo_updatefeed(feed,friendly_name)
local rc=false
local feed_url='http://vimeo.com/api/v2/'..feed..'/videos.json'
local feed_name='vimeo_'..string.gsub(feed,'/','_')
local feed_m3u_path=cfg.feeds_path..feed_name..'.m3u'
local tmp_m3u_path=cfg.tmp_path..feed_name..'.m3u'
local feed_data=http.download(feed_url)
if feed_data then
local x=json.decode(feed_data)
feed_data=nil
if x then
local dfd=io.open(tmp_m3u_path,'w+')
if dfd then
dfd:write('#EXTM3U name=\"',friendly_name or feed_name,'\" type=mp4 plugin=vimeo\n')
for i,j in ipairs(x) do
dfd:write('#EXTINF:0 logo=',j.thumbnail_medium,' ,',j.title,'\n',j.url,'\n')
end
dfd:close()
if util.md5(tmp_m3u_path)~=util.md5(feed_m3u_path) then
if os.execute(string.format('mv %s %s',tmp_m3u_path,feed_m3u_path))==0 then
if cfg.debug>0 then print('Vimeo feed \''..feed_name..'\' updated') end
rc=true
end
else
util.unlink(tmp_m3u_path)
end
end
end
end
return rc
end
-- send '\r\n' before data
function vimeo_sendurl(vimeo_url,range)
local url=nil
if plugin_sendurl_from_cache(vimeo_url,range) then return end
local vimeo_id=string.match(vimeo_url,'.+/(%w+)$')
local clip_page=plugin_download(vimeo_url)
if clip_page then
local sig,ts=string.match(clip_page,'"signature":"(%w+)","timestamp":(%w+),')
clip_page=nil
if sig and ts then
url=string.format('http://player.vimeo.com/play_redirect?clip_id=%s&sig=%s&time=%s&quality=hd&codecs=H264&type=moogaloop_local&embed_location=',vimeo_id,sig,ts)
end
else
if cfg.debug>0 then print('Vimeo clip '..vimeo_id..' is not found') end
end
if url then
if cfg.debug>0 then print('Vimeo Real URL: '..url) end
plugin_sendurl(vimeo_url,url,range)
else
if cfg.debug>0 then print('Vimeo Real URL is not found') end
plugin_sendfile('www/corrupted.mp4')
end
end
plugins['vimeo']={}
plugins.vimeo.sendurl=vimeo_sendurl
plugins.vimeo.updatefeed=vimeo_updatefeed
| gpl-2.0 |
Djabbz/nn | View.lua | 41 | 2232 | local View, parent = torch.class('nn.View', 'nn.Module')
function View:__init(...)
parent.__init(self)
if select('#', ...) == 1 and torch.typename(select(1, ...)) == 'torch.LongStorage' then
self.size = select(1, ...)
else
self.size = torch.LongStorage({...})
end
self.numElements = 1
local inferdim = false
for i = 1,#self.size do
local szi = self.size[i]
if szi >= 0 then
self.numElements = self.numElements * self.size[i]
else
assert(szi == -1, 'size should be positive or -1')
assert(not inferdim, 'only one dimension can be at -1')
inferdim = true
end
end
self.output = nil
self.gradInput = nil
self.numInputDims = nil
end
function View:setNumInputDims(numInputDims)
self.numInputDims = numInputDims
return self
end
local function batchsize(input, size, numInputDims, numElements)
local ind = input:nDimension()
local isz = input:size()
local maxdim = numInputDims and numInputDims or ind
local ine = 1
for i=ind,ind-maxdim+1,-1 do
ine = ine * isz[i]
end
if ine % numElements ~= 0 then
error(string.format(
'input view (%s) and desired view (%s) do not match',
table.concat(input:size():totable(), 'x'),
table.concat(size:totable(), 'x')))
end
-- the remainder is either the batch...
local bsz = ine / numElements
-- ... or the missing size dim
for i=1,size:size() do
if size[i] == -1 then
bsz = 1
break
end
end
-- for dim over maxdim, it is definitively the batch
for i=ind-maxdim,1,-1 do
bsz = bsz * isz[i]
end
-- special card
if bsz == 1 and (not numInputDims or input:nDimension() <= numInputDims) then
return
end
return bsz
end
function View:updateOutput(input)
local bsz = batchsize(input, self.size, self.numInputDims, self.numElements)
if bsz then
self.output = input:view(bsz, table.unpack(self.size:totable()))
else
self.output = input:view(self.size)
end
return self.output
end
function View:updateGradInput(input, gradOutput)
self.gradInput = gradOutput:view(input:size())
return self.gradInput
end
| bsd-3-clause |
T3hArco/skeyler-gamemodes | Sassilization/entities/entities/building_tower/init.lua | 1 | 3969 | --------------------
-- Sassilization
-- By Sassafrass / Spacetech / LuaPineapple
--------------------
AddCSLuaFile("shared.lua")
include("shared.lua")
util.PrecacheSound("sassilization/units/arrowfire01.wav")
util.PrecacheSound("sassilization/units/arrowfire02.wav")
AccessorFunc( ENT, "next_attack", "NextAttack" )
function ENT:Initialize()
self:SetLevel(1)
self:Setup("tower", false)
self.View = {}
self.next_attack = 0
self.Gib = GIB_WOOD
self.NextCheck = CurTime() + 1
local VECTOR_TOWERTOP = Vector(0, 0, 26)
self.UpPos = self:GetPos() + VECTOR_TOWERTOP
end
function ENT:OnDestroy(Info, Empire, Attacker)
if(Empire) then
if(Info ~= building.BUILDING_SELL) then
if self.level == 1 then
self:SpawnUnits("archer", 1)
elseif self.level == 2 then
self:SpawnUnits("archer", math.random(1, 2))
else
self:SpawnUnits("archer", 2)
end
end
end
self:UpdateControl()
end
function ENT:OnLevel(Level)
if(Level > 1) then
self.Gib = GIB_ALL
end
self.level = Level
self.AttackSpeed = building.GetBuildingKey("tower", "AttackSpeed")[Level]
self.AttackRange = building.GetBuildingKey("tower", "AttackRange")[Level]
self.AttackDamage = building.GetBuildingKey("tower", "AttackDamage")[Level]
end
function ENT:CanAttack()
if( not self:IsBuilt() ) then return end
return CurTime() > self:GetNextAttack()
end
local targetTrace = {}
targetTrace.mask = MASK_SOLID_BRUSHONLY
local targetTraceRes
function ENT:UpdateView()
self.View = {}
for _, ent in pairs( ents.FindInSphere( self:GetPos(), self.AttackRange ) ) do
if( ent.Attackable ) then
targetTrace.start = self.UpPos
targetTrace.endpos = ent:GetPos()
targetTraceRes = util.TraceLine(targetTrace)
--Only allow targetting this unit if it's actually visible through a direct line of sight
if targetTraceRes.Fraction == 1 then
if( ent.Unit ) then
if( ent.Unit:GetEmpire() ~= self:GetEmpire() and !Allied(self:GetEmpire(), ent.Unit:GetEmpire())) then
table.insert( self.View, ent.Unit )
end
elseif( ent.Building and ent:GetEmpire() ~= self:GetEmpire() and !Allied(self:GetEmpire(), ent:GetEmpire())) then
table.insert( self.View, ent )
end
end
end
end
end
function ENT:GetPriorityEnemy()
local pos = self:GetPos()
local min_dist, closest_target = self.AttackRange
for _, target in pairs(self.View) do
if(IsValid(target)) then
local dist = target:NearestAttackPoint(pos):Distance(pos)
if(dist < min_dist) then
closest_target = target
min_dist = dist
end
end
end
return closest_target
end
function ENT:OnThink()
if( not self:CanAttack() ) then return end
self:UpdateView()
local target = self:GetPriorityEnemy()
if(target) then
self.Enemy = target
else
self.Enemy = nil
end
if(self.Enemy) then
if(Unit:ValidUnit(self.Enemy) or ValidBuilding(self.Enemy)) then
self:ShootArrow(self.Enemy)
else
self.Enemy = nil
end
end
return self.AttackSpeed * 0.9
end
local arrowspeed = 120
function ENT:ShootArrow( target )
self:SetNextAttack( CurTime() + self.AttackSpeed )
local attackPoint = target:NearestAttackPoint( self.UpPos )
local arrowTime = attackPoint:Distance( self.UpPos ) / arrowspeed
local targetEnt = target.NWEnt and target.NWEnt or target
local dmginfo = {}
dmginfo.damage = self.AttackDamage
dmginfo.dmgtype = DMG_BULLET
dmginfo.dmgpos = targetEnt:WorldToLocal(attackPoint)
dmginfo.attacker = self
self:EmitSound( SA.Sounds.GetArrowFireSound() )
local ed = EffectData()
ed:SetOrigin( self.UpPos )
ed:SetScale( arrowTime )
ed:SetEntity( targetEnt )
ed:SetStart( dmginfo.dmgpos )
util.Effect( "arrow", ed, true, true )
timer.Simple( arrowTime, function()
if( IsValid( target ) ) then
target:Damage( dmginfo )
end
end )
end | bsd-3-clause |
MrCerealGuy/Stonecraft | games/stonecraft_game/mods/carts/cart_entity.lua | 1 | 11669 | -- carts/cart_entity.lua
-- support for MT game translation.
local S = carts.get_translator
local cart_entity = {
initial_properties = {
physical = false, -- otherwise going uphill breaks
collisionbox = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},
visual = "mesh",
mesh = "carts_cart.b3d",
visual_size = {x=1, y=1},
textures = {"carts_cart.png"},
},
driver = nil,
punched = false, -- used to re-send velocity and position
velocity = {x=0, y=0, z=0}, -- only used on punch
old_dir = {x=1, y=0, z=0}, -- random value to start the cart on punch
old_pos = nil,
old_switch = 0,
railtype = nil,
attached_items = {}
}
function cart_entity:on_rightclick(clicker)
if not clicker or not clicker:is_player() then
return
end
local player_name = clicker:get_player_name()
if self.driver and player_name == self.driver then
self.driver = nil
carts:manage_attachment(clicker, nil)
elseif not self.driver then
self.driver = player_name
carts:manage_attachment(clicker, self.object)
-- player_api does not update the animation
-- when the player is attached, reset to default animation
player_api.set_animation(clicker, "stand")
end
end
function cart_entity:on_activate(staticdata, dtime_s)
self.object:set_armor_groups({immortal=1})
if string.sub(staticdata, 1, string.len("return")) ~= "return" then
return
end
local data = minetest.deserialize(staticdata)
if type(data) ~= "table" then
return
end
self.railtype = data.railtype
if data.old_dir then
self.old_dir = data.old_dir
end
end
function cart_entity:get_staticdata()
return minetest.serialize({
railtype = self.railtype,
old_dir = self.old_dir
})
end
-- 0.5.x and later: When the driver leaves
function cart_entity:on_detach_child(child)
if child and child:get_player_name() == self.driver then
self.driver = nil
carts:manage_attachment(child, nil)
end
end
function cart_entity:on_punch(puncher, time_from_last_punch, tool_capabilities, direction)
local pos = self.object:get_pos()
local vel = self.object:get_velocity()
if not self.railtype or vector.equals(vel, {x=0, y=0, z=0}) then
local node = minetest.get_node(pos).name
self.railtype = minetest.get_item_group(node, "connect_to_raillike")
end
-- Punched by non-player
if not puncher or not puncher:is_player() then
local cart_dir = carts:get_rail_direction(pos, self.old_dir, nil, nil, self.railtype)
if vector.equals(cart_dir, {x=0, y=0, z=0}) then
return
end
self.velocity = vector.multiply(cart_dir, 2)
self.punched = true
return
end
-- Player digs cart by sneak-punch
if puncher:get_player_control().sneak then
if self.sound_handle then
minetest.sound_stop(self.sound_handle)
end
-- Detach driver and items
if self.driver then
if self.old_pos then
self.object:set_pos(self.old_pos)
end
local player = minetest.get_player_by_name(self.driver)
carts:manage_attachment(player, nil)
end
for _, obj_ in ipairs(self.attached_items) do
if obj_ then
obj_:set_detach()
end
end
-- Pick up cart
local inv = puncher:get_inventory()
if not minetest.is_creative_enabled(puncher:get_player_name())
or not inv:contains_item("main", "carts:cart") then
local leftover = inv:add_item("main", "carts:cart")
-- If no room in inventory add a replacement cart to the world
if not leftover:is_empty() then
minetest.add_item(self.object:get_pos(), leftover)
end
end
self.object:remove()
return
end
-- Player punches cart to alter velocity
if puncher:get_player_name() == self.driver then
if math.abs(vel.x + vel.z) > carts.punch_speed_max then
return
end
end
local punch_dir = carts:velocity_to_dir(puncher:get_look_dir())
punch_dir.y = 0
local cart_dir = carts:get_rail_direction(pos, punch_dir, nil, nil, self.railtype)
if vector.equals(cart_dir, {x=0, y=0, z=0}) then
return
end
local punch_interval = 1
if tool_capabilities and tool_capabilities.full_punch_interval then
punch_interval = tool_capabilities.full_punch_interval
end
time_from_last_punch = math.min(time_from_last_punch or punch_interval, punch_interval)
local f = 2 * (time_from_last_punch / punch_interval)
self.velocity = vector.multiply(cart_dir, f)
self.old_dir = cart_dir
self.punched = true
end
local function rail_on_step_event(handler, obj, dtime)
if handler then
handler(obj, dtime)
end
end
-- sound refresh interval = 1.0sec
local function rail_sound(self, dtime)
if not self.sound_ttl then
self.sound_ttl = 1.0
return
elseif self.sound_ttl > 0 then
self.sound_ttl = self.sound_ttl - dtime
return
end
self.sound_ttl = 1.0
if self.sound_handle then
local handle = self.sound_handle
self.sound_handle = nil
minetest.after(0.2, minetest.sound_stop, handle)
end
local vel = self.object:get_velocity()
local speed = vector.length(vel)
if speed > 0 then
self.sound_handle = minetest.sound_play(
"carts_cart_moving", {
object = self.object,
gain = (speed / carts.speed_max) / 2,
loop = true,
})
end
end
local function get_railparams(pos)
local node = minetest.get_node(pos)
return carts.railparams[node.name] or {}
end
local v3_len = vector.length
local function rail_on_step(self, dtime)
local vel = self.object:get_velocity()
if self.punched then
vel = vector.add(vel, self.velocity)
self.object:set_velocity(vel)
self.old_dir.y = 0
elseif vector.equals(vel, {x=0, y=0, z=0}) then
return
end
local pos = self.object:get_pos()
local cart_dir = carts:velocity_to_dir(vel)
local same_dir = vector.equals(cart_dir, self.old_dir)
local update = {}
if self.old_pos and not self.punched and same_dir then
local flo_pos = vector.round(pos)
local flo_old = vector.round(self.old_pos)
if vector.equals(flo_pos, flo_old) then
-- Do not check one node multiple times
return
end
end
local ctrl, player
-- Get player controls
if self.driver then
player = minetest.get_player_by_name(self.driver)
if player then
ctrl = player:get_player_control()
end
end
local stop_wiggle = false
if self.old_pos and same_dir then
-- Detection for "skipping" nodes (perhaps use average dtime?)
-- It's sophisticated enough to take the acceleration in account
local acc = self.object:get_acceleration()
local distance = dtime * (v3_len(vel) + 0.5 * dtime * v3_len(acc))
local new_pos, new_dir = carts:pathfinder(
pos, self.old_pos, self.old_dir, distance, ctrl,
self.old_switch, self.railtype
)
if new_pos then
-- No rail found: set to the expected position
pos = new_pos
update.pos = true
cart_dir = new_dir
end
elseif self.old_pos and self.old_dir.y ~= 1 and not self.punched then
-- Stop wiggle
stop_wiggle = true
end
local railparams
-- dir: New moving direction of the cart
-- switch_keys: Currently pressed L/R key, used to ignore the key on the next rail node
local dir, switch_keys = carts:get_rail_direction(
pos, cart_dir, ctrl, self.old_switch, self.railtype
)
local dir_changed = not vector.equals(dir, self.old_dir)
local new_acc = {x=0, y=0, z=0}
if stop_wiggle or vector.equals(dir, {x=0, y=0, z=0}) then
vel = {x = 0, y = 0, z = 0}
local pos_r = vector.round(pos)
if not carts:is_rail(pos_r, self.railtype)
and self.old_pos then
pos = self.old_pos
elseif not stop_wiggle then
pos = pos_r
else
pos.y = math.floor(pos.y + 0.5)
end
update.pos = true
update.vel = true
else
-- Direction change detected
if dir_changed then
vel = vector.multiply(dir, math.abs(vel.x + vel.z))
update.vel = true
if dir.y ~= self.old_dir.y then
pos = vector.round(pos)
update.pos = true
end
end
-- Center on the rail
if dir.z ~= 0 and math.floor(pos.x + 0.5) ~= pos.x then
pos.x = math.floor(pos.x + 0.5)
update.pos = true
end
if dir.x ~= 0 and math.floor(pos.z + 0.5) ~= pos.z then
pos.z = math.floor(pos.z + 0.5)
update.pos = true
end
-- Slow down or speed up..
local acc = dir.y * -4.0
-- Get rail for corrected position
railparams = get_railparams(pos)
-- no need to check for railparams == nil since we always make it exist.
local speed_mod = railparams.acceleration
if speed_mod and speed_mod ~= 0 then
-- Try to make it similar to the original carts mod
acc = acc + speed_mod
else
-- Handbrake or coast
if ctrl and ctrl.down then
acc = acc - 3
else
acc = acc - 0.4
end
end
new_acc = vector.multiply(dir, acc)
end
-- Limits
local max_vel = carts.speed_max
for _, v in pairs({"x","y","z"}) do
if math.abs(vel[v]) > max_vel then
vel[v] = carts:get_sign(vel[v]) * max_vel
new_acc[v] = 0
update.vel = true
end
end
self.object:set_acceleration(new_acc)
self.old_pos = vector.round(pos)
if not vector.equals(dir, {x=0, y=0, z=0}) and not stop_wiggle then
self.old_dir = vector.new(dir)
end
self.old_switch = switch_keys
if self.punched then
-- Collect dropped items
for _, obj_ in pairs(minetest.get_objects_inside_radius(pos, 1)) do
local ent = obj_:get_luaentity()
-- Careful here: physical_state and disable_physics are item-internal APIs
if ent and ent.name == "__builtin:item" and ent.physical_state then
ent:disable_physics()
obj_:set_attach(self.object, "", {x=0, y=0, z=0}, {x=0, y=0, z=0})
self.attached_items[#self.attached_items + 1] = obj_
end
end
self.punched = false
update.vel = true
end
railparams = railparams or get_railparams(pos)
if not (update.vel or update.pos) then
rail_on_step_event(railparams.on_step, self, dtime)
return
end
local yaw = 0
if self.old_dir.x < 0 then
yaw = 0.5
elseif self.old_dir.x > 0 then
yaw = 1.5
elseif self.old_dir.z < 0 then
yaw = 1
end
self.object:set_yaw(yaw * math.pi)
local anim = {x=0, y=0}
if dir.y == -1 then
anim = {x=1, y=1}
elseif dir.y == 1 then
anim = {x=2, y=2}
end
self.object:set_animation(anim, 1, 0)
if update.vel then
self.object:set_velocity(vel)
end
if update.pos then
if dir_changed then
self.object:set_pos(pos)
else
self.object:move_to(pos)
end
end
-- call event handler
rail_on_step_event(railparams.on_step, self, dtime)
end
function cart_entity:on_step(dtime)
rail_on_step(self, dtime)
rail_sound(self, dtime)
end
minetest.register_entity("carts:cart", cart_entity)
minetest.register_craftitem("carts:cart", {
description = S("Cart") .. "\n" .. S("(Sneak+Click to pick up)"),
inventory_image = minetest.inventorycube("carts_cart_top.png", "carts_cart_front.png", "carts_cart_side.png"),
wield_image = "carts_cart_front.png",
on_place = function(itemstack, placer, pointed_thing)
local under = pointed_thing.under
local node = minetest.get_node(under)
local udef = minetest.registered_nodes[node.name]
if udef and udef.on_rightclick and
not (placer and placer:is_player() and
placer:get_player_control().sneak) then
return udef.on_rightclick(under, node, placer, itemstack,
pointed_thing) or itemstack
end
if not pointed_thing.type == "node" then
return
end
if carts:is_rail(pointed_thing.under) then
minetest.add_entity(pointed_thing.under, "carts:cart")
elseif carts:is_rail(pointed_thing.above) then
minetest.add_entity(pointed_thing.above, "carts:cart")
else
return
end
minetest.sound_play({name = "default_place_node_metal", gain = 0.5},
{pos = pointed_thing.above}, true)
if not minetest.is_creative_enabled(placer:get_player_name()) then
itemstack:take_item()
end
return itemstack
end,
})
minetest.register_craft({
output = "carts:cart",
recipe = {
{"default:steel_ingot", "", "default:steel_ingot"},
{"default:steel_ingot", "default:steel_ingot", "default:steel_ingot"},
},
})
| gpl-3.0 |
spixi/wesnoth | data/ai/micro_ais/cas/ca_recruit_random.lua | 4 | 4685 | local H = wesnoth.require "helper"
local AH = wesnoth.require("ai/lua/ai_helper.lua")
local LS = wesnoth.require "location_set"
local recruit_type
local ca_recruit_random = {}
function ca_recruit_random:evaluation(cfg)
-- Random recruiting from all the units the side has
-- Check if leader is on keep
local leader = wesnoth.get_units { side = wesnoth.current.side, canrecruit = 'yes' }[1]
if (not leader) or (not wesnoth.get_terrain_info(wesnoth.get_terrain(leader.x, leader.y)).keep) then
return 0
end
-- Find all connected castle hexes
local castle_map = LS.of_pairs({ { leader.x, leader.y } })
local width, height, border = wesnoth.get_map_size()
local new_castle_hex_found = true
while new_castle_hex_found do
new_castle_hex_found = false
local new_hexes = {}
castle_map:iter(function(x, y)
for xa,ya in H.adjacent_tiles(x, y) do
if (not castle_map:get(xa, ya))
and (xa >= 1) and (xa <= width)
and (ya >= 1) and (ya <= height)
then
local is_castle = wesnoth.get_terrain_info(wesnoth.get_terrain(xa, ya)).castle
if is_castle then
table.insert(new_hexes, { xa, ya })
new_castle_hex_found = true
end
end
end
end)
for _,hex in ipairs(new_hexes) do
castle_map:insert(hex[1], hex[2])
end
end
-- Check if there is space left for recruiting
local no_space = true
castle_map:iter(function(x, y)
local unit = wesnoth.get_unit(x, y)
if (not unit) then
no_space = false
end
end)
if no_space then return 0 end
-- Set up the probability array
local probabilities, probability_sum = {}, 0
-- Go through all the types listed in [probability] tags (which can be comma-separated lists)
for prob in wml.child_range(cfg, "probability") do
types = AH.split(prob.type, ",")
for _,typ in ipairs(types) do -- 'type' is a reserved keyword in Lua
-- If this type is in the recruit list, add it
for _,recruit in ipairs(wesnoth.sides[wesnoth.current.side].recruit) do
if (recruit == typ) then
probabilities[typ] = { value = prob.probability }
probability_sum = probability_sum + prob.probability
break
end
end
end
end
-- Now we add in all the unit types not listed in [probability] tags
for _,recruit in ipairs(wesnoth.sides[wesnoth.current.side].recruit) do
if (not probabilities[recruit]) then
probabilities[recruit] = { value = 1 }
probability_sum = probability_sum + 1
end
end
-- Now eliminate all those that are too expensive (unless cfg.skip_low_gold_recruiting is set)
if cfg.skip_low_gold_recruiting then
for typ,probability in pairs(probabilities) do -- 'type' is a reserved keyword in Lua
if (wesnoth.unit_types[typ].cost > wesnoth.sides[wesnoth.current.side].gold) then
probability_sum = probability_sum - probability.value
probabilities[typ] = nil
end
end
end
-- Now set up the cumulative probability values for each type
-- Both min and max need to be set as the order of pairs() is not guaranteed
local cum_prob = 0
for typ,probability in pairs(probabilities) do
probabilities[typ].p_i = cum_prob
cum_prob = cum_prob + probability.value
probabilities[typ].p_f = cum_prob
end
-- We always call the exec function, no matter if the selected unit is affordable
-- The point is that this will blacklist the CA if an unaffordable recruit was
-- chosen -> no cheaper recruits will be selected in subsequent calls
if (cum_prob > 0) then
local rand_prob = math.random(cum_prob)
for typ,probability in pairs(probabilities) do
if (probability.p_i < rand_prob) and (rand_prob <= probability.p_f) then
recruit_type = typ
break
end
end
else
recruit_type = wesnoth.sides[wesnoth.current.side].recruit[1]
end
return cfg.ca_score
end
function ca_recruit_random:execution(cfg)
-- Let this function blacklist itself if the chosen recruit is too expensive
if wesnoth.unit_types[recruit_type].cost <= wesnoth.sides[wesnoth.current.side].gold then
AH.checked_recruit(ai, recruit_type)
end
end
return ca_recruit_random
| gpl-2.0 |
rbavishi/vlc-2.2.1 | share/lua/playlist/vimeo.lua | 65 | 3213 | --[[
$Id$
Copyright © 2009-2013 the VideoLAN team
Authors: Konstantin Pavlov (thresh@videolan.org)
François Revol (revol@free.fr)
Pierre Ynard
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.
--]]
function get_prefres()
local prefres = -1
if vlc.var and vlc.var.inherit then
prefres = vlc.var.inherit(nil, "preferred-resolution")
if prefres == nil then
prefres = -1
end
end
return prefres
end
-- Probe function.
function probe()
return ( vlc.access == "http" or vlc.access == "https" )
and ( string.match( vlc.path, "vimeo%.com/%d+$" )
or string.match( vlc.path, "player%.vimeo%.com" ) )
-- do not match other addresses,
-- else we'll also try to decode the actual video url
end
-- Parse function.
function parse()
if not string.match( vlc.path, "player%.vimeo%.com" ) then -- Web page URL
while true do
local line = vlc.readline()
if not line then break end
path = string.match( line, "data%-config%-url=\"(.-)\"" )
if path then
path = vlc.strings.resolve_xml_special_chars( path )
return { { path = path } }
end
end
vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" )
return { }
else -- API URL
local prefres = get_prefres()
local line = vlc.readline() -- data is on one line only
for stream in string.gmatch( line, "{([^}]*\"profile\":[^}]*)}" ) do
local url = string.match( stream, "\"url\":\"(.-)\"" )
if url then
path = url
if prefres < 0 then
break
end
local height = string.match( stream, "\"height\":(%d+)[,}]" )
if not height or tonumber(height) <= prefres then
break
end
end
end
if not path then
vlc.msg.err( "Couldn't extract vimeo video URL, please check for updates to this script" )
return { }
end
local name = string.match( line, "\"title\":\"(.-)\"" )
local artist = string.match( line, "\"owner\":{[^}]-\"name\":\"(.-)\"" )
local arturl = string.match( line, "\"thumbs\":{\"[^\"]+\":\"(.-)\"" )
local duration = string.match( line, "\"duration\":(%d+)[,}]" )
return { { path = path; name = name; artist = artist; arturl = arturl; duration = duration } }
end
end
| lgpl-2.1 |
ahmadreza5251/terojanbot | plugins/face.lua | 641 | 3073 | local https = require("ssl.https")
local ltn12 = require "ltn12"
-- Edit data/mashape.lua with your Mashape API key
-- http://docs.mashape.com/api-keys
local mashape = load_from_file('data/mashape.lua', {
api_key = ''
})
local function request(imageUrl)
local api_key = mashape.api_key
if api_key:isempty() then
return nil, 'Configure your Mashape API Key'
end
local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?"
local parameters = "attribute=gender%2Cage%2Crace"
parameters = parameters .. "&url="..(URL.escape(imageUrl) or "")
local url = api..parameters
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "Accept: application/json"
}
print(url)
local respbody = {}
local body, code = https.request{
url = url,
method = "GET",
headers = headers,
sink = ltn12.sink.table(respbody),
protocol = "tlsv1"
}
if code ~= 200 then return "", code end
local body = table.concat(respbody)
return body, code
end
local function parseData(data)
local jsonBody = json:decode(data)
local response = ""
if jsonBody.error ~= nil then
if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then
response = response .. "The image is too big. Provide a smaller image."
elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then
response = response .. "Is that a valid url for an image?"
else
response = response .. jsonBody.error
end
elseif jsonBody.face == nil or #jsonBody.face == 0 then
response = response .. "No faces found"
else
response = response .. #jsonBody.face .." face(s) found:\n\n"
for k,face in pairs(jsonBody.face) do
local raceP = ""
if face.attribute.race.confidence > 85.0 then
raceP = face.attribute.race.value:lower()
elseif face.attribute.race.confidence > 50.0 then
raceP = "(probably "..face.attribute.race.value:lower()..")"
else
raceP = "(posibly "..face.attribute.race.value:lower()..")"
end
if face.attribute.gender.confidence > 85.0 then
response = response .. "There is a "
else
response = response .. "There may be a "
end
response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " "
response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n"
end
end
return response
end
local function run(msg, matches)
--return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg')
local data, code = request(matches[1])
if code ~= 200 then return "There was an error. "..code end
return parseData(data)
end
return {
description = "Who is in that photo?",
usage = {
"!face [url]",
"!recognise [url]"
},
patterns = {
"^!face (.*)$",
"^!recognise (.*)$"
},
run = run
}
| gpl-2.0 |
nimaghorbani/dozdi5 | libs/mimetype.lua | 28 | 2924 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end
| gpl-2.0 |
patsoffice/dotfiles | .hammerspoon/Spoons/SpoonInstall.spoon/init.lua | 8 | 17398 | --- === SpoonInstall ===
---
--- Install and manage Spoons and Spoon repositories
---
--- Download: [https://github.com/Hammerspoon/Spoons/raw/master/Spoons/SpoonInstall.spoon.zip](https://github.com/Hammerspoon/Spoons/raw/master/Spoons/SpoonInstall.spoon.zip)
local obj={}
obj.__index = obj
-- Metadata
obj.name = "SpoonInstall"
obj.version = "0.1"
obj.author = "Diego Zamboni <diego@zzamboni.org>"
obj.homepage = "https://github.com/Hammerspoon/Spoons"
obj.license = "MIT - https://opensource.org/licenses/MIT"
--- SpoonInstall.logger
--- Variable
--- Logger object used within the Spoon. Can be accessed to set the default log level for the messages coming from the Spoon.
obj.logger = hs.logger.new('SpoonInstall')
--- SpoonInstall.repos
--- Variable
--- Table containing the list of available Spoon repositories. The key
--- of each entry is an identifier for the repository, and its value
--- is a table with the following entries:
--- * desc - Human-readable description for the repository
--- * url - Base URL for the repository. For now the repository is assumed to be hosted in GitHub, and the URL should be the main base URL of the repository. Repository metadata needs to be stored under `docs/docs.json`, and the Spoon zip files need to be stored under `Spoons/`.
---
--- Default value:
--- ```
--- {
--- default = {
--- url = "https://github.com/Hammerspoon/Spoons",
--- desc = "Main Hammerspoon Spoon repository",
--- }
--- }
--- ```
obj.repos = {
default = {
url = "https://github.com/Hammerspoon/Spoons",
desc = "Main Hammerspoon Spoon repository",
}
}
--- SpoonInstall.use_syncinstall
--- Variable
--- If `true`, `andUse()` will update repos and install packages synchronously. Defaults to `false`.
---
--- Keep in mind that if you set this to `true`, Hammerspoon will
--- block until all missing Spoons are installed, but the notifications
--- will happen at a more "human readable" rate.
obj.use_syncinstall = false
-- Execute a command and return its output with trailing EOLs trimmed. If the command fails, an error message is logged.
local function _x(cmd, errfmt, ...)
local output, status = hs.execute(cmd)
if status then
local trimstr = string.gsub(output, "\n*$", "")
return trimstr
else
obj.logger.ef(errfmt, ...)
return nil
end
end
-- --------------------------------------------------------------------
-- Spoon repository management
-- Internal callback to process and store the data from docs.json about a repository
-- callback is called with repo as arguments, only if the call is successful
function obj:_storeRepoJSON(repo, callback, status, body, hdrs)
local success=nil
if (status < 100) or (status >= 400) then
self.logger.ef("Error fetching JSON data for repository '%s'. Error code %d: %s", repo, status, body or "<no error message>")
else
local json = hs.json.decode(body)
if json then
self.repos[repo].data = {}
for i,v in ipairs(json) do
v.download_url = self.repos[repo].download_base_url .. v.name .. ".spoon.zip"
self.repos[repo].data[v.name] = v
end
self.logger.df("Updated JSON data for repository '%s'", repo)
success=true
else
self.logger.ef("Invalid JSON received for repository '%s': %s", repo, body)
end
end
if callback then
callback(repo, success)
end
return success
end
-- Internal function to return the URL of the docs.json file based on the URL of a GitHub repo
function obj:_build_repo_json_url(repo)
if self.repos[repo] and self.repos[repo].url then
self.repos[repo].json_url = string.gsub(self.repos[repo].url, "/$", "") .. "/raw/master/docs/docs.json"
self.repos[repo].download_base_url = string.gsub(self.repos[repo].url, "/$", "") .. "/raw/master/Spoons/"
return true
else
self.logger.ef("Invalid or unknown repository '%s'", repo)
return nil
end
end
--- SpoonInstall:asyncUpdateRepo(repo, callback)
--- Method
--- Asynchronously fetch the information about the contents of a Spoon repository
---
--- Parameters:
--- * repo - name of the repository to update. Defaults to `"default"`.
--- * callback - if given, a function to be called after the update finishes (also if it fails). The function will receive the following arguments:
--- * repo - name of the repository
--- * success - boolean indicating whether the update succeeded
---
--- Returns:
--- * `true` if the update was correctly initiated (i.e. the repo name is valid), `nil` otherwise
---
--- Notes:
--- * For now, the repository data is not persisted, so you need to update it after every restart if you want to use any of the install functions.
function obj:asyncUpdateRepo(repo, callback)
if not repo then repo = 'default' end
if self:_build_repo_json_url(repo) then
hs.http.asyncGet(self.repos[repo].json_url, nil, hs.fnutils.partial(self._storeRepoJSON, self, repo, callback))
return true
else
return nil
end
end
--- SpoonInstall:updateRepo(repo)
--- Method
--- Synchronously fetch the information about the contents of a Spoon repository
---
--- Parameters:
--- * repo - name of the repository to update. Defaults to `"default"`.
---
--- Returns:
--- * `true` if the update was successful, `nil` otherwise
---
--- Notes:
--- * This is a synchronous call, which means Hammerspoon will be blocked until it finishes. For use in your configuration files, it's advisable to use `SpoonInstall.asyncUpdateRepo()` instead.
--- * For now, the repository data is not persisted, so you need to update it after every restart if you want to use any of the install functions.
function obj:updateRepo(repo)
if not repo then repo = 'default' end
if self:_build_repo_json_url(repo) then
local a,b,c = hs.http.get(self.repos[repo].json_url)
return self:_storeRepoJSON(repo, nil, a, b, c)
else
return nil
end
end
--- SpoonInstall:updateAllRepos()
--- Method
--- Synchronously fetch the information about the contents of all Spoon repositories registered in `SpoonInstall.repos`
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
---
--- Notes:
--- * This is a synchronous call, which means Hammerspoon will be blocked until it finishes.
--- * For now, the repository data is not persisted, so you need to update it after every restart if you want to use any of the install functions.
function obj:updateAllRepos()
for k,v in pairs(self.repos) do
self:updateRepo(k)
end
end
--- SpoonInstall:repolist()
--- Method
--- Return a sorted list of registered Spoon repositories
---
--- Parameters:
--- * None
---
--- Returns:
--- * Table containing a list of strings with the repository identifiers
function obj:repolist()
local keys={}
-- Create sorted list of keys
for k,v in pairs(self.repos) do table.insert(keys, k) end
table.sort(keys)
return keys
end
--- SpoonInstall:search(pat)
--- Method
--- Search repositories for a pattern
---
--- Parameters:
--- * pat - Lua pattern that will be matched against the name and description of each spoon in the registered repositories. All text is converted to lowercase before searching it, so you can use all-lowercase in your pattern.
---
--- Returns:
--- * Table containing a list of matching entries. Each entry is a table with the following keys:
--- * name - Spoon name
--- * desc - description of the spoon
--- * repo - identifier in the repository where the match was found
function obj:search(pat)
local res={}
for repo,v in pairs(self.repos) do
if v.data then
for spoon,rec in pairs(v.data) do
if string.find(string.lower(rec.name .. "\n" .. rec.desc), pat) then
table.insert(res, { name = rec.name, desc = rec.desc, repo = repo })
end
end
else
self.logger.ef("Repository data for '%s' not available - call spoon.SpoonInstall:updateRepo('%s'), then try again.", repo, repo)
end
end
return res
end
-- --------------------------------------------------------------------
-- Spoon installation
-- Internal callback function to finalize the installation of a spoon after the zip file has been downloaded.
-- callback, if given, is called with (urlparts, success) as arguments
function obj:_installSpoonFromZipURLgetCallback(urlparts, callback, status, body, headers)
local success=nil
if (status < 100) or (status >= 400) then
self.logger.ef("Error downloading %s. Error code %d: %s", urlparts.absoluteString, status, body or "<none>")
else
-- Write the zip file to disk in a temporary directory
local tmpdir=_x("/usr/bin/mktemp -d", "Error creating temporary directory to download new spoon.")
if tmpdir then
local outfile = string.format("%s/%s", tmpdir, urlparts.lastPathComponent)
local f=assert(io.open(outfile, "w"))
f:write(body)
f:close()
-- Check its contents - only one *.spoon directory should be in there
output = _x(string.format("/usr/bin/unzip -l %s '*.spoon/' | /usr/bin/awk '$NF ~ /\\.spoon\\/$/ { print $NF }' | /usr/bin/wc -l", outfile),
"Error examining downloaded zip file %s, leaving it in place for your examination.", outfile)
if output then
if (tonumber(output) or 0) == 1 then
-- Uncompress the zip file
local outdir = string.format("%s/Spoons", hs.configdir)
if _x(string.format("/usr/bin/unzip -o %s -d %s 2>&1", outfile, outdir),
"Error uncompressing file %s, leaving it in place for your examination.", outfile) then
-- And finally, install it using Hammerspoon itself
self.logger.f("Downloaded and installed %s", urlparts.absoluteString)
_x(string.format("/bin/rm -rf '%s'", tmpdir), "Error removing directory %s", tmpdir)
success=true
end
else
self.logger.ef("The downloaded zip file %s is invalid - it should contain exactly one spoon. Leaving it in place for your examination.", outfile)
end
end
end
end
if callback then
callback(urlparts, success)
end
return success
end
--- SpoonInstall:asyncInstallSpoonFromZipURL(url, callback)
--- Method
--- Asynchronously download a Spoon zip file and install it.
---
--- Parameters:
--- * url - URL of the zip file to install.
--- * callback - if given, a function to call after the installation finishes (also if it fails). The function receives the following arguments:
--- * urlparts - Result of calling `hs.http.urlParts` on the URL of the Spoon zip file
--- * success - boolean indicating whether the installation was successful
---
--- Returns:
--- * `true` if the installation was correctly initiated (i.e. the URL is valid), `false` otherwise
function obj:asyncInstallSpoonFromZipURL(url, callback)
local urlparts = hs.http.urlParts(url)
local dlfile = urlparts.lastPathComponent
if dlfile and dlfile ~= "" and urlparts.pathExtension == "zip" then
hs.http.asyncGet(url, nil, hs.fnutils.partial(self._installSpoonFromZipURLgetCallback, self, urlparts, callback))
return true
else
self.logger.ef("Invalid URL %s, must point to a zip file", url)
return nil
end
end
--- SpoonInstall:installSpoonFromZipURL(url)
--- Method
--- Synchronously download a Spoon zip file and install it.
---
--- Parameters:
--- * url - URL of the zip file to install.
---
--- Returns:
--- * `true` if the installation was successful, `nil` otherwise
function obj:installSpoonFromZipURL(url)
local urlparts = hs.http.urlParts(url)
local dlfile = urlparts.lastPathComponent
if dlfile and dlfile ~= "" and urlparts.pathExtension == "zip" then
a,b,c=hs.http.get(url)
return self:_installSpoonFromZipURLgetCallback(urlparts, nil, a, b, c)
else
self.logger.ef("Invalid URL %s, must point to a zip file", url)
return nil
end
end
-- Internal function to check if a Spoon/Repo combination is valid
function obj:_is_valid_spoon(name, repo)
if self.repos[repo] then
if self.repos[repo].data then
if self.repos[repo].data[name] then
return true
else
self.logger.ef("Spoon '%s' does not exist in repository '%s'. Please check and try again.", name, repo)
end
else
self.logger.ef("Repository data for '%s' not available - call spoon.SpoonInstall:updateRepo('%s'), then try again.", repo, repo)
end
else
self.logger.ef("Invalid or unknown repository '%s'", repo)
end
return nil
end
--- SpoonInstall:asyncInstallSpoonFromRepo(name, repo, callback)
--- Method
--- Asynchronously install a Spoon from a registered repository
---
--- Parameters:
--- * name - Name of the Spoon to install.
--- * repo - Name of the repository to use. Defaults to `"default"`
--- * callback - if given, a function to call after the installation finishes (also if it fails). The function receives the following arguments:
--- * urlparts - Result of calling `hs.http.urlParts` on the URL of the Spoon zip file
--- * success - boolean indicating whether the installation was successful
---
--- Returns:
--- * `true` if the installation was correctly initiated (i.e. the repo and spoon name were correct), `false` otherwise.
function obj:asyncInstallSpoonFromRepo(name, repo, callback)
if not repo then repo = 'default' end
if self:_is_valid_spoon(name, repo) then
self:asyncInstallSpoonFromZipURL(self.repos[repo].data[name].download_url, callback)
end
return nil
end
--- SpoonInstall:installSpoonFromRepo(name, repo)
--- Method
--- Synchronously install a Spoon from a registered repository
---
--- Parameters:
--- * name = Name of the Spoon to install.
--- * repo - Name of the repository to use. Defaults to `"default"`
---
--- Returns:
--- * `true` if the installation was successful, `nil` otherwise.
function obj:installSpoonFromRepo(name, repo, callback)
if not repo then repo = 'default' end
if self:_is_valid_spoon(name, repo) then
return self:installSpoonFromZipURL(self.repos[repo].data[name].download_url)
end
return nil
end
--- SpoonInstall:andUse(name, arg)
--- Method
--- Declaratively install, load and configure a Spoon
---
--- Parameters:
--- * name - the name of the Spoon to install (without the `.spoon` extension). If the Spoon is already installed, it will be loaded using `hs.loadSpoon()`. If it is not installed, it will be installed using `SpoonInstall:asyncInstallSpoonFromRepo()` and then loaded.
--- * arg - if provided, can be used to specify the configuration of the Spoon. The following keys are recognized (all are optional):
--- * repo - repository from where the Spoon should be installed if not present in the system, as defined in `SpoonInstall.repos`. Defaults to `"default"`.
--- * config - a table containing variables to be stored in the Spoon object to configure it. For example, `config = { answer = 42 }` will result in `spoon.<LoadedSpoon>.answer` being set to 42.
--- * hotkeys - a table containing hotkey bindings. If provided, will be passed as-is to the Spoon's `bindHotkeys()` method. The special string `"default"` can be given to use the Spoons `defaultHotkeys` variable, if it exists.
--- * fn - a function which will be called with the freshly-loaded Spoon object as its first argument.
--- * loglevel - if the Spoon has a variable called `logger`, its `setLogLevel()` method will be called with this value.
--- * start - if `true`, call the Spoon's `start()` method after configuring everything else.
--- * disable - if `true`, do nothing. Easier than commenting it out when you want to temporarily disable a spoon.
---
--- Returns:
--- * None
function obj:andUse(name, arg)
if not arg then arg = {} end
if arg.disable then return true end
if hs.spoons.use(name, arg, true) then
return true
else
local repo = arg.repo or "default"
if self.repos[repo] then
if self.repos[repo].data then
local load_and_config = function(_, success)
if success then
hs.notify.show("Spoon installed by SpoonInstall", name .. ".spoon is now available", "")
hs.spoons.use(name, arg)
else
obj.logger.ef("Error installing Spoon '%s' from repo '%s'", name, repo)
end
end
if self.use_syncinstall then
return load_and_config(nil, self:installSpoonFromRepo(name, repo))
else
self:asyncInstallSpoonFromRepo(name, repo, load_and_config)
end
else
local update_repo_and_continue = function(_, success)
if success then
obj:andUse(name, arg)
else
obj.logger.ef("Error updating repository '%s'", repo)
end
end
if self.use_syncinstall then
return update_repo_and_continue(nil, self:updateRepo(repo))
else
self:asyncUpdateRepo(repo, update_repo_and_continue)
end
end
else
obj.logger.ef("Unknown repository '%s' for Spoon", repo, name)
end
end
end
return obj
| mit |
wcjscm/JackGame | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/DisplayManager.lua | 19 | 4990 |
--------------------------------
-- @module DisplayManager
-- @extend Ref
-- @parent_module ccs
--------------------------------
--
-- @function [parent=#DisplayManager] getDisplayRenderNode
-- @param self
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- @function [parent=#DisplayManager] getAnchorPointInPoints
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
--
-- @function [parent=#DisplayManager] getDisplayRenderNodeType
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
--
-- @function [parent=#DisplayManager] removeDisplay
-- @param self
-- @param #int index
-- @return DisplayManager#DisplayManager self (return value: ccs.DisplayManager)
--------------------------------
--
-- @function [parent=#DisplayManager] setForceChangeDisplay
-- @param self
-- @param #bool force
-- @return DisplayManager#DisplayManager self (return value: ccs.DisplayManager)
--------------------------------
--
-- @function [parent=#DisplayManager] init
-- @param self
-- @param #ccs.Bone bone
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#DisplayManager] getContentSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
--
-- @function [parent=#DisplayManager] getBoundingBox
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)
--------------------------------
-- @overload self, cc.Node, int
-- @overload self, ccs.DisplayData, int
-- @function [parent=#DisplayManager] addDisplay
-- @param self
-- @param #ccs.DisplayData displayData
-- @param #int index
-- @return DisplayManager#DisplayManager self (return value: ccs.DisplayManager)
--------------------------------
-- @overload self, float, float
-- @overload self, vec2_table
-- @function [parent=#DisplayManager] containPoint
-- @param self
-- @param #float x
-- @param #float y
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Change display by index. You can just use this method to change display in the display list.<br>
-- The display list is just used for this bone, and it is the displays you may use in every frame.<br>
-- Note : if index is the same with prev index, the method will not effect<br>
-- param index The index of the display you want to change<br>
-- param force If true, then force change display to specified display, or current display will set to display index edit in the flash every key frame.
-- @function [parent=#DisplayManager] changeDisplayWithIndex
-- @param self
-- @param #int index
-- @param #bool force
-- @return DisplayManager#DisplayManager self (return value: ccs.DisplayManager)
--------------------------------
--
-- @function [parent=#DisplayManager] changeDisplayWithName
-- @param self
-- @param #string name
-- @param #bool force
-- @return DisplayManager#DisplayManager self (return value: ccs.DisplayManager)
--------------------------------
--
-- @function [parent=#DisplayManager] isForceChangeDisplay
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#DisplayManager] getCurrentDisplayIndex
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
--
-- @function [parent=#DisplayManager] getAnchorPoint
-- @param self
-- @return vec2_table#vec2_table ret (return value: vec2_table)
--------------------------------
--
-- @function [parent=#DisplayManager] getDecorativeDisplayList
-- @param self
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
-- Determines if the display is visible<br>
-- see setVisible(bool)<br>
-- return true if the node is visible, false if the node is hidden.
-- @function [parent=#DisplayManager] isVisible
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Sets whether the display is visible<br>
-- The default value is true, a node is default to visible<br>
-- param visible true if the node is visible, false if the node is hidden.
-- @function [parent=#DisplayManager] setVisible
-- @param self
-- @param #bool visible
-- @return DisplayManager#DisplayManager self (return value: ccs.DisplayManager)
--------------------------------
--
-- @function [parent=#DisplayManager] create
-- @param self
-- @param #ccs.Bone bone
-- @return DisplayManager#DisplayManager ret (return value: ccs.DisplayManager)
--------------------------------
--
-- @function [parent=#DisplayManager] DisplayManager
-- @param self
-- @return DisplayManager#DisplayManager self (return value: ccs.DisplayManager)
return nil
| gpl-3.0 |
kjoenth/naev | dat/factions/spawn/pirate.lua | 4 | 3512 | include("dat/factions/spawn/common.lua")
-- @brief Spawns a small patrol fleet.
function spawn_patrol ()
local pilots = {}
local r = rnd.rnd()
if r < 0.3 then
scom.addPilot( pilots, "Pirate Hyena", 15 );
elseif r < 0.5 then
scom.addPilot( pilots, "Pirate Shark", 20 );
elseif r < 0.8 then
scom.addPilot( pilots, "Pirate Hyena", 15 );
scom.addPilot( pilots, "Pirate Shark", 20 );
else
scom.addPilot( pilots, "Pirate Hyena", 15 );
scom.addPilot( pilots, "Pirate Shark", 20 );
scom.addPilot( pilots, "Pirate Vendetta", 25 );
end
return pilots
end
-- @brief Spawns a medium sized squadron.
function spawn_squad ()
local pilots = {}
local r = rnd.rnd()
if r < 0.4 then
scom.addPilot( pilots, "Pirate Hyena", 15 );
scom.addPilot( pilots, "Pirate Vendetta", 25 );
scom.addPilot( pilots, "Pirate Ancestor", 20 );
scom.addPilot( pilots, "Pirate Ancestor", 20 );
elseif r < 0.6 then
scom.addPilot( pilots, "Pirate Hyena", 15 );
scom.addPilot( pilots, "Pirate Shark", 20 );
scom.addPilot( pilots, "Pirate Vendetta", 25 );
scom.addPilot( pilots, "Pirate Ancestor", 20 );
elseif r < 0.8 then
scom.addPilot( pilots, "Pirate Shark", 20 );
scom.addPilot( pilots, "Pirate Rhino", 35 );
scom.addPilot( pilots, "Pirate Phalanx", 45 );
else
scom.addPilot( pilots, "Pirate Hyena", 15 );
scom.addPilot( pilots, "Pirate Shark", 20 );
scom.addPilot( pilots, "Pirate Vendetta", 25 );
scom.addPilot( pilots, "Pirate Admonisher", 45 );
end
return pilots
end
-- @brief Spawns a capship with escorts.
function spawn_capship ()
local pilots = {}
local r = rnd.rnd()
-- Generate the capship
scom.addPilot( pilots, "Pirate Kestrel", 125 )
-- Generate the escorts
if r < 0.5 then
scom.addPilot( pilots, "Pirate Vendetta", 25 );
scom.addPilot( pilots, "Pirate Vendetta", 25 );
scom.addPilot( pilots, "Pirate Admonisher", 45 );
elseif r < 0.8 then
scom.addPilot( pilots, "Pirate Shark", 20 );
scom.addPilot( pilots, "Pirate Vendetta", 25 );
scom.addPilot( pilots, "Pirate Ancestor", 20 );
scom.addPilot( pilots, "Pirate Phalanx", 45 );
else
scom.addPilot( pilots, "Pirate Shark", 20 );
scom.addPilot( pilots, "Pirate Vendetta", 25 );
scom.addPilot( pilots, "Pirate Ancestor", 20 );
scom.addPilot( pilots, "Pirate Rhino", 35 );
scom.addPilot( pilots, "Pirate Admonisher", 45 );
end
return pilots
end
-- @brief Creation hook.
function create ( max )
local weights = {}
-- Create weights for spawn table
weights[ spawn_patrol ] = 100
weights[ spawn_squad ] = math.max(1, -80 + 0.80 * max)
weights[ spawn_capship ] = math.max(1, -500 + 1.70 * max)
-- Create spawn table base on weights
spawn_table = scom.createSpawnTable( weights )
-- Calculate spawn data
spawn_data = scom.choose( spawn_table )
return scom.calcNextSpawn( 0, scom.presence(spawn_data), max )
end
-- @brief Spawning hook
function spawn ( presence, max )
local pilots
-- Over limit
if presence > max then
return 5
end
-- Actually spawn the pilots
pilots = scom.spawn( spawn_data )
-- Calculate spawn data
spawn_data = scom.choose( spawn_table )
return scom.calcNextSpawn( presence, scom.presence(spawn_data), max ), pilots
end
| gpl-3.0 |
xingshuo/frame_sync_model | skynet/test/testmongodb.lua | 4 | 2949 | local skynet = require "skynet"
local mongo = require "mongo"
local bson = require "bson"
local host, db_name = ...
function test_insert_without_index()
local db = mongo.client({host = host})
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
local ret = db[db_name].testdb:safe_insert({test_key = 1});
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:safe_insert({test_key = 1});
assert(ret and ret.n == 1)
end
function test_insert_with_index()
local db = mongo.client({host = host})
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index"})
local ret = db[db_name].testdb:safe_insert({test_key = 1})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:safe_insert({test_key = 1})
assert(ret and ret.n == 0)
end
function test_find_and_remove()
local db = mongo.client({host = host})
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
db[db_name].testdb:ensureIndex({test_key = 1}, {test_key2 = -1}, {unique = true, name = "test_index"})
local ret = db[db_name].testdb:safe_insert({test_key = 1, test_key2 = 1})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:safe_insert({test_key = 1, test_key2 = 2})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:safe_insert({test_key = 2, test_key2 = 3})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:findOne({test_key2 = 1})
assert(ret and ret.test_key2 == 1)
local ret = db[db_name].testdb:find({test_key2 = {['$gt'] = 0}}):sort({test_key = 1}, {test_key2 = -1}):skip(1):limit(1)
assert(ret:count() == 3)
assert(ret:count(true) == 1)
if ret:hasNext() then
ret = ret:next()
end
assert(ret and ret.test_key2 == 1)
db[db_name].testdb:delete({test_key = 1})
db[db_name].testdb:delete({test_key = 2})
local ret = db[db_name].testdb:findOne({test_key = 1})
assert(ret == nil)
end
function test_expire_index()
local db = mongo.client({host = host})
db[db_name].testdb:dropIndex("*")
db[db_name].testdb:drop()
db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index", expireAfterSeconds = 1, })
db[db_name].testdb:ensureIndex({test_date = 1}, {expireAfterSeconds = 1, })
local ret = db[db_name].testdb:safe_insert({test_key = 1, test_date = bson.date(os.time())})
assert(ret and ret.n == 1)
local ret = db[db_name].testdb:findOne({test_key = 1})
assert(ret and ret.test_key == 1)
for i = 1, 1000 do
skynet.sleep(1);
local ret = db[db_name].testdb:findOne({test_key = 1})
if ret == nil then
return
end
end
assert(false, "test expire index failed");
end
skynet.start(function()
print("Test insert without index")
test_insert_without_index()
print("Test insert index")
test_insert_with_index()
print("Test find and remove")
test_find_and_remove()
print("Test expire index")
test_expire_index()
print("mongodb test finish.");
end)
| mit |
salorium/awesome | lib/awful/widget/launcher.lua | 4 | 1410 | ---------------------------------------------------------------------------
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008-2009 Julien Danjou
-- @release @AWESOME_VERSION@
-- @classmod awful.widget.launcher
---------------------------------------------------------------------------
local setmetatable = setmetatable
local util = require("awful.util")
local spawn = require("awful.spawn")
local wbutton = require("awful.widget.button")
local button = require("awful.button")
local launcher = { mt = {} }
--- Create a button widget which will launch a command.
-- @param args Standard widget table arguments, plus image for the image path
-- and command for the command to run on click, or either menu to create menu.
-- @return A launcher widget.
function launcher.new(args)
if not args.command and not args.menu then return end
local w = wbutton(args)
if not w then return end
local b
if args.command then
b = util.table.join(w:buttons(), button({}, 1, nil, function () spawn(args.command) end))
elseif args.menu then
b = util.table.join(w:buttons(), button({}, 1, nil, function () args.menu:toggle() end))
end
w:buttons(b)
return w
end
function launcher.mt:__call(...)
return launcher.new(...)
end
return setmetatable(launcher, launcher.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
McGlaspie/mvm | lua/mvm/bots/MarineCommanderBrain_Data.lua | 1 | 4775 |
Script.Load("lua/mvm/bots/CommonActions.lua")
Script.Load("lua/bots/BrainSenses.lua")
local kStationBuildDist = 15.0
local function CreateBuildNearStationAction( techId, className, numToBuild, weightIfNotEnough )
return CreateBuildStructureAction(
techId, className,
{
{-1.0, weightIfNotEnough},
{numToBuild-1, weightIfNotEnough},
{numToBuild, 0.0}
},
"CommandStation",
kStationBuildDist )
end
//----------------------------------------
//
//----------------------------------------
kMarineComBrainActions =
{
CreateBuildNearStationAction( kTechId.Armory , "Armory" , 1 , 1.1 ) ,
CreateBuildNearStationAction( kTechId.InfantryPortal , "InfantryPortal" , 2 , 1+math.random() ) ,
CreateBuildNearStationAction( kTechId.Observatory , "Observatory" , 1 , 1+math.random() ) ,
CreateBuildNearStationAction( kTechId.PhaseGate , "PhaseGate" , 1 , 1+math.random() ) ,
CreateBuildNearStationAction( kTechId.ArmsLab , "ArmsLab" , 1 , 1+math.random() ) ,
CreateBuildNearStationAction( kTechId.PrototypeLab , "PrototypeLab" , 1 , 1+math.random() ) ,
// Upgrades from structures
CreateUpgradeStructureAction( kTechId.ShotgunTech , 1.0 ) ,
CreateUpgradeStructureAction( kTechId.MinesTech , 1.0+math.random() ) ,
CreateUpgradeStructureAction( kTechId.WelderTech , 1.0+math.random() ) ,
CreateUpgradeStructureAction( kTechId.AdvancedArmoryUpgrade , 1.0+math.random() ) ,
// TODO
CreateUpgradeStructureAction( kTechId.PhaseTech , 1.0+math.random() ),
CreateUpgradeStructureAction( kTechId.Weapons1 , 1.0+math.random() ) ,
CreateUpgradeStructureAction( kTechId.Weapons2 , 1.0+math.random() ) ,
CreateUpgradeStructureAction( kTechId.Weapons3 , 1.0+math.random() ) ,
CreateUpgradeStructureAction( kTechId.Weapons4 , 1.0+math.random() ) ,
CreateUpgradeStructureAction( kTechId.Armor1 , 1.0+math.random() ) ,
CreateUpgradeStructureAction( kTechId.Armor2 , 1.0+math.random() ) ,
CreateUpgradeStructureAction( kTechId.Armor3 , 1.0+math.random() ) ,
CreateUpgradeStructureAction( kTechId.Armor4 , 1.0+math.random() ) ,
function(bot, brain)
local name = "extractor"
local com = bot:GetPlayer()
local sdb = brain:GetSenses()
local doables = sdb:Get("doableTechIds")
local weight = 0.0
local targetRP = nil
if doables[kTechId.Extractor] ~= nil then
targetRP = sdb:Get("resPointToTake")
if targetRP ~= nil then
weight = EvalLPF( sdb:Get("numExtractors"),
{
{0, 2},
{1, 1.5},
{2, 1.1},
{3, 1.0}
})
end
end
return { name = name, weight = weight,
perform = function(move)
if targetRP ~= nil then
local success = brain:ExecuteTechId( com, kTechId.Extractor, targetRP:GetOrigin(), com )
end
end}
end,
function(bot, brain)
return { name = "idle", weight = 1e-5,
perform = function(move)
if brain.debug then
DebugPrint("idling..")
end
end}
end
}
//----------------------------------------
// Build the senses database
//----------------------------------------
function CreateMarineComSenses()
local s = BrainSenses()
s:Initialize()
s:Add("gameMinutes", function(db)
return (Shared.GetTime() - GetGamerules():GetGameStartTime()) / 60.0
end)
s:Add("doableTechIds", function(db)
return db.bot.brain:GetDoableTechIds( db.bot:GetPlayer() )
end)
s:Add("stations", function(db)
return GetEntitiesForTeam("CommandStation", kMarineTeamType)
end)
s:Add("availResPoints", function(db)
return GetAvailableResourcePoints()
end)
s:Add("numExtractors", function(db)
return GetNumEntitiesOfType("Extractor", kMarineTeamType)
end)
s:Add("resPointToTake", function(db)
local rps = db:Get("availResPoints")
local stations = db:Get("stations")
local dist, rp = GetMinTableEntry( rps, function(rp)
return GetMinDistToEntities( rp, stations )
end)
return rp
end)
return s
//TODO Add TeampSupply sense
end
//----------------------------------------
//
//----------------------------------------
| gpl-3.0 |
xing634325131/Luci-0.11.1 | applications/luci-asterisk/luasrc/model/cbi/asterisk/voicemail.lua | 11 | 1730 | --[[
LuCI - Lua Configuration Interface
Copyright 2009 Jo-Philipp Wich <xm@subsignal.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: voicemail.lua 4397 2009-03-30 19:29:37Z jow $
]]--
local ast = require "luci.asterisk"
cbimap = Map("asterisk", "Voicemail - Mailboxes")
voicemail = cbimap:section(TypedSection, "voicemail", "Voicemail Boxes")
voicemail.addremove = true
voicemail.anonymous = true
voicemail.template = "cbi/tblsection"
context = voicemail:option(ListValue, "context", "Context")
context:value("default")
number = voicemail:option(Value, "number",
"Mailbox Number", "Unique mailbox identifier")
function number.write(self, s, val)
if val and #val > 0 then
local old = self:cfgvalue(s)
self.map.uci:foreach("asterisk", "dialplanvoice",
function(v)
if v.voicebox == old then
self.map:set(v['.name'], "voicebox", val)
end
end)
Value.write(self, s, val)
end
end
voicemail:option(Value, "name", "Ownername", "Human readable display name")
voicemail:option(Value, "password", "Password", "Access protection")
voicemail:option(Value, "email", "eMail", "Where to send voice messages")
voicemail:option(Value, "page", "Pager", "Pager number")
zone = voicemail:option(ListValue, "zone", "Timezone", "Used time format")
zone.titleref = luci.dispatcher.build_url("admin/asterisk/voicemail/settings")
cbimap.uci:foreach("asterisk", "voicezone",
function(s) zone:value(s['.name']) end)
function voicemail.remove(self, s)
return ast.voicemail.remove(self.map:get(s, "number"), self.map.uci)
end
return cbimap
| apache-2.0 |
payday-restoration/restoration-mod | lua/sc/managers/firemanager.lua | 1 | 16875 | local mvec3_set = mvector3.set
local mvec3_dir = mvector3.direction
local mvec3_dis_sq = mvector3.distance_sq
local mvec3_add = mvector3.add
local mvec3_copy = mvector3.copy
local tmp_pos = Vector3()
local math_min = math.min
local math_max = math.max
local math_round = math.round
local math_ceil = math.ceil
local table_insert = table.insert
local table_remove = table.remove
local world_g = World
local draw_explosion_sphere = nil
local draw_sync_explosion_sphere = nil
local draw_splinters = nil
local draw_obstructed_splinters = nil
local draw_splinter_hits = nil
local debug_draw_duration = 3
function FireManager:update(t, dt)
for index = #self._doted_enemies, 1, -1 do
local dot_info = self._doted_enemies[index]
--no grace period means that DoT ticks will consistently trigger as long as the enemy is "doted"
--instead of resetting the timer each time a new DoT instance is applied, correctly allowing players
--to dose enemies continuously to maximize damage, as the latest update to flamethrower stats intended
--Molotovs/ground fires are the exception, as otherwise they'd just melt anything caught by them
--instead of continuosly dealing damage at a steady pace to whoever stands on them
if dot_info.fire_dot_counter >= 0.5 then
self:_damage_fire_dot(dot_info)
dot_info.fire_dot_counter = 0
end
if t > dot_info.fire_damage_received_time + dot_info.dot_length then
if dot_info.fire_effects then
for _, fire_effect_id in ipairs(dot_info.fire_effects) do
world_g:effect_manager():fade_kill(fire_effect_id)
end
end
--unless intended for optimization, this just ends up confusing people as ALL fire effects are removed
--if it was done for that reason, please consider another method, having fire vanish for no reason
--is bad, as you won't know if the enemy you just flamed will keep taking fire DoT damage or not
--self:_remove_flame_effects_from_doted_unit(dot_info.enemy_unit)
if dot_info.sound_source then
self:_stop_burn_body_sound(dot_info.sound_source)
end
table_remove(self._doted_enemies, index)
if dot_info.enemy_unit and alive(dot_info.enemy_unit) then
self._dozers_on_fire[dot_info.enemy_unit:id()] = nil
end
else
dot_info.fire_dot_counter = dot_info.fire_dot_counter + dt
end
end
end
function FireManager:check_achievemnts(unit, t)
if not unit and not alive(unit) then
return
end
if not unit:base() or not unit:base()._tweak_table then
return
end
if CopDamage.is_civilian(unit:base()._tweak_table) then
return
end
--grant achievements only for the local player when they're the attackers
if self._doted_enemies then
for _, dot_info in ipairs(self._doted_enemies) do
if not dot_info.user_unit or dot_info.user_unit ~= managers.player:player_unit() then
return
end
end
else
return
end
for i = #self._enemies_on_fire, 1, -1 do
local data = self._enemies_on_fire[i]
if t - data.t > 5 or data.unit == unit then
table_remove(self._enemies_on_fire, i)
end
end
table_insert(self._enemies_on_fire, {
unit = unit,
t = t
})
if tweak_data.achievement.disco_inferno then
local count = #self._enemies_on_fire
if count >= 10 then
managers.achievment:award(tweak_data.achievement.disco_inferno)
end
end
--proper Dozer check
if unit:base().has_tag and unit:base():has_tag("tank") then
local unit_id = unit:id()
self._dozers_on_fire[unit_id] = self._dozers_on_fire[unit_id] or {
t = t,
unit = unit
}
end
if tweak_data.achievement.overgrill then
for dozer_id, dozer_info in pairs(self._dozers_on_fire) do
if t - dozer_info.t >= 10 then
managers.achievment:award(tweak_data.achievement.overgrill)
end
end
end
end
function FireManager:add_doted_enemy(enemy_unit, fire_damage_received_time, weapon_unit, dot_length, dot_damage, user_unit, is_molotov)
local dot_info = self:_add_doted_enemy(enemy_unit, fire_damage_received_time, weapon_unit, dot_length, dot_damage, user_unit, is_molotov)
managers.network:session():send_to_peers_synched("sync_add_doted_enemy", enemy_unit, 0, weapon_unit, dot_length, dot_damage, user_unit, is_molotov)
end
function FireManager:_add_doted_enemy(enemy_unit, fire_damage_received_time, weapon_unit, dot_length, dot_damage, user_unit, is_molotov)
if not self._doted_enemies then
return
end
local dot_info = nil
for _, cur_dot_info in ipairs(self._doted_enemies) do
if cur_dot_info.enemy_unit == enemy_unit then
--instead of always updating fire_damage_received_time, only do so (plus update the dot length) if the new length
--is longer than the remaining DoT time (DoT damage also gets replaced as it's pretty much a new DoT instance)
if cur_dot_info.fire_damage_received_time + cur_dot_info.dot_length < fire_damage_received_time + dot_length then
cur_dot_info.fire_damage_received_time = fire_damage_received_time
cur_dot_info.dot_length = dot_length
cur_dot_info.dot_damage = dot_damage
else
--to avoid a higher damage DoT from not applying, or applying with a longer timer
if cur_dot_info.dot_damage < dot_damage then
cur_dot_info.fire_damage_received_time = fire_damage_received_time
cur_dot_info.dot_length = dot_length
cur_dot_info.dot_damage = dot_damage
end
end
--always override the attacker and weapons used so that the latest attacker gets credited properly
cur_dot_info.weapon_unit = weapon_unit
cur_dot_info.user_unit = user_unit
cur_dot_info.is_molotov = is_molotov
dot_info = cur_dot_info
break
end
end
if dot_info then
dot_info.fire_damage_received_time = fire_damage_received_time
dot_info.weapon_unit = weapon_unit
dot_info.user_unit = user_unit
dot_info.is_molotov = is_molotov
dot_info.dot_damage = dot_damage
dot_info.dot_length = dot_length
else
dot_info = {
fire_dot_counter = 0,
enemy_unit = enemy_unit,
fire_damage_received_time = fire_damage_received_time,
weapon_unit = weapon_unit,
dot_length = dot_length,
dot_damage = dot_damage,
user_unit = user_unit,
is_molotov = is_molotov
}
table.insert(self._doted_enemies, dot_info)
local has_delayed_info = false
for index, delayed_dot in pairs(self.predicted_dot_info) do
if enemy_unit == delayed_dot.enemy_unit then
dot_info.sound_source = delayed_dot.sound_source
dot_info.fire_effects = delayed_dot.fire_effects
table.remove(self.predicted_dot_info, index)
has_delayed_info = true
end
end
if not has_delayed_info then
self:_start_enemy_fire_effect(dot_info)
self:start_burn_body_sound(dot_info)
end
end
self:check_achievemnts(enemy_unit, fire_damage_received_time)
end
function FireManager:detect_and_give_dmg(params)
local hit_pos = params.hit_pos
local slotmask = params.collision_slotmask
local user_unit = params.user
local dmg = params.damage
local player_dmg = params.player_damage or dmg
local range = params.range
local ignore_unit = params.ignore_unit
local curve_pow = params.curve_pow
local col_ray = params.col_ray
local owner = params.owner
local fire_dot_data = params.fire_dot_data
local is_molotov = params.is_molotov
local push_units = true
if params.push_units ~= nil then
push_units = params.push_units
end
if draw_explosion_sphere or draw_splinters or draw_obstructed_splinters or draw_splinter_hits then
if owner and owner:base() and owner:base().get_name_id and owner:base():get_name_id() == "environment_fire" then
debug_draw_duration = 0.1
end
end
if player_dmg ~= 0 then
local player = managers.player:player_unit()
if player then
player:character_damage():damage_fire({
variant = "fire",
position = hit_pos,
range = range,
damage = player_dmg,
ignite_character = params.ignite_character
})
end
end
if draw_explosion_sphere then
local new_brush = Draw:brush(Color.red:with_alpha(0.5), debug_draw_duration)
new_brush:sphere(hit_pos, range)
end
local bodies = nil
if ignore_unit then
bodies = world_g:find_bodies(ignore_unit, "intersect", "sphere", hit_pos, range, slotmask)
else
bodies = world_g:find_bodies("intersect", "sphere", hit_pos, range, slotmask)
end
local splinters = {
mvec3_copy(hit_pos)
}
local dirs = {
Vector3(range, 0, 0),
Vector3(-range, 0, 0),
Vector3(0, range, 0),
Vector3(0, -range, 0),
Vector3(0, 0, range),
Vector3(0, 0, -range)
}
local geometry_mask = managers.slot:get_mask("world_geometry")
for _, dir in ipairs(dirs) do
mvec3_set(tmp_pos, dir)
mvec3_add(tmp_pos, hit_pos)
local splinter_ray = world_g:raycast("ray", hit_pos, tmp_pos, "slot_mask", geometry_mask)
if splinter_ray then
tmp_pos = splinter_ray.position - dir:normalized() * math_min(splinter_ray.distance, 10)
end
if draw_splinters then
local new_brush = Draw:brush(Color.white:with_alpha(0.5), debug_draw_duration)
new_brush:cylinder(hit_pos, tmp_pos, 0.5)
end
local near_splinter = false
for _, s_pos in ipairs(splinters) do
if mvec3_dis_sq(tmp_pos, s_pos) < 900 then
near_splinter = true
break
end
end
if not near_splinter then
table_insert(splinters, mvec3_copy(tmp_pos))
end
end
local count_cops, count_gangsters, count_civilians, count_cop_kills, count_gangster_kills, count_civilian_kills = 0, 0, 0, 0, 0, 0
local units_to_hit, hit_units = {}, {}
local units_to_push, tweak_name = nil
if push_units and push_units == true then
units_to_push = {}
end
for _, hit_body in ipairs(bodies) do
if alive(hit_body) then
local hit_unit = hit_body:unit()
local hit_unit_key = hit_unit:key()
if units_to_push then
units_to_push[hit_unit_key] = hit_unit
end
local character = hit_unit:character_damage() and hit_unit:character_damage().damage_fire and not hit_unit:character_damage():dead()
local apply_dmg = hit_body:extension() and hit_body:extension().damage
local dir, damage, ray_hit, damage_character = nil
if character then
if not units_to_hit[hit_unit_key] then
if params.no_raycast_check_characters then
ray_hit = true
units_to_hit[hit_unit_key] = true
damage_character = true
else
for i_splinter, s_pos in ipairs(splinters) do
ray_hit = not world_g:raycast("ray", s_pos, hit_body:center_of_mass(), "slot_mask", geometry_mask, "report")
if ray_hit then
units_to_hit[hit_unit_key] = true
damage_character = true
if draw_splinter_hits then
local new_brush = Draw:brush(Color.green:with_alpha(0.5), debug_draw_duration)
new_brush:cylinder(s_pos, hit_body:center_of_mass(), 0.5)
end
break
else
if draw_obstructed_splinters then
local new_brush = Draw:brush(Color.yellow:with_alpha(0.5), debug_draw_duration)
new_brush:cylinder(s_pos, hit_body:center_of_mass(), 0.5)
end
end
end
end
if owner and ray_hit then
if hit_unit:base() and hit_unit:base()._tweak_table and not hit_unit:character_damage():dead() then
tweak_name = hit_unit:base()._tweak_table
if CopDamage.is_civilian(tweak_name) then
count_civilians = count_civilians + 1
elseif CopDamage.is_gangster(tweak_name) then
count_gangsters = count_gangsters + 1
elseif hit_unit:base().has_tag and hit_unit:base():has_tag("law") then
count_cops = count_cops + 1
end
end
end
end
elseif apply_dmg or hit_body:dynamic() then
if not units_to_hit[hit_unit_key] then
ray_hit = true
units_to_hit[hit_unit_key] = true
end
end
if not ray_hit and units_to_hit[hit_unit_key] and apply_dmg and hit_unit:character_damage() and hit_unit:character_damage().damage_fire then
if params.no_raycast_check_characters then
ray_hit = true
else
for i_splinter, s_pos in ipairs(splinters) do
ray_hit = not world_g:raycast("ray", s_pos, hit_body:center_of_mass(), "slot_mask", geometry_mask, "report")
if ray_hit then
break
end
end
end
end
if ray_hit then
hit_units[hit_unit_key] = hit_unit
dir = hit_body:center_of_mass()
mvec3_dir(dir, hit_pos, dir)
damage = dmg
if apply_dmg then
self:_apply_body_damage(true, hit_body, user_unit, dir, damage)
end
damage = math_max(damage, 1)
if character and damage_character then
local dead_before = hit_unit:character_damage():dead()
local action_data = {
variant = "fire",
damage = damage,
attacker_unit = user_unit,
weapon_unit = owner,
ignite_character = params.ignite_character,
col_ray = self._col_ray or {
position = hit_body:position(),
ray = dir
},
is_fire_dot_damage = false,
fire_dot_data = fire_dot_data,
is_molotov = is_molotov
}
hit_unit:character_damage():damage_fire(action_data)
if owner and not dead_before and hit_unit:base() and hit_unit:base()._tweak_table and hit_unit:character_damage():dead() then
tweak_name = hit_unit:base()._tweak_table
if CopDamage.is_civilian(tweak_name) then
count_civilian_kills = count_civilian_kills + 1
elseif CopDamage.is_gangster(tweak_name) then
count_gangster_kills = count_gangster_kills + 1
elseif hit_unit:base().has_tag and hit_unit:base():has_tag("law") then
count_cop_kills = count_cop_kills + 1
end
end
end
end
end
end
if units_to_push then
managers.explosion:units_to_push(units_to_push, params.hit_pos, params.range)
end
local alert_radius = params.alert_radius or 3000
local alert_filter = params.alert_filter or managers.groupai:state():get_unit_type_filter("civilians_enemies")
local alert_unit = user_unit
if alive(alert_unit) and alert_unit:base() and alert_unit:base().thrower_unit then
alert_unit = alert_unit:base():thrower_unit()
end
managers.groupai:state():propagate_alert({
"fire",
params.hit_pos,
alert_radius,
alert_filter,
alert_unit
})
local results = {}
if owner then
results.count_cops = count_cops
results.count_gangsters = count_gangsters
results.count_civilians = count_civilians
results.count_cop_kills = count_cop_kills
results.count_gangster_kills = count_gangster_kills
results.count_civilian_kills = count_civilian_kills
end
return hit_units, splinters, results
end
function FireManager:_apply_body_damage(is_server, hit_body, user_unit, dir, damage)
local hit_unit = hit_body:unit()
local local_damage = is_server or hit_unit:id() == -1
local sync_damage = is_server and hit_unit:id() ~= -1
if not local_damage and not sync_damage then
return
end
local normal = dir
local prop_damage = math_min(damage, 200)
if prop_damage < 0.25 then
prop_damage = math_round(prop_damage, 0.25)
end
if prop_damage > 0 then
local network_damage = math_ceil(prop_damage * 163.84)
prop_damage = network_damage / 163.84
if local_damage then
hit_body:extension().damage:damage_fire(user_unit, normal, hit_body:position(), dir, prop_damage)
hit_body:extension().damage:damage_damage(user_unit, normal, hit_body:position(), dir, prop_damage)
end
if sync_damage and managers.network:session() then
if alive(user_unit) then
managers.network:session():send_to_peers_synched("sync_body_damage_fire", hit_body, user_unit, normal, hit_body:position(), dir, math_min(32768, network_damage))
else
managers.network:session():send_to_peers_synched("sync_body_damage_fire_no_attacker", hit_body, normal, hit_body:position(), dir, math_min(32768, network_damage))
end
end
end
end
function FireManager:client_damage_and_push(from_pos, normal, user_unit, dmg, range, curve_pow)
if draw_sync_explosion_sphere then
local draw_duration = 3
local new_brush = Draw:brush(Color.red:with_alpha(0.5), draw_duration)
new_brush:sphere(from_pos, range)
end
local bodies = world_g:find_bodies("intersect", "sphere", from_pos, range, managers.slot:get_mask("explosion_targets"))
local units_to_push = {}
for _, hit_body in ipairs(bodies) do
if alive(hit_body) then
local hit_unit = hit_body:unit()
units_to_push[hit_unit:key()] = hit_unit
local apply_dmg = hit_body:extension() and hit_body:extension().damage and hit_unit:id() == -1
local dir, damage = nil
if apply_dmg then
dir = hit_body:center_of_mass()
mvec3_dir(dir, from_pos, dir)
damage = dmg
self:_apply_body_damage(false, hit_body, user_unit, dir, damage)
end
end
end
managers.explosion:units_to_push(units_to_push, from_pos, range)
end
function FireManager:give_local_player_dmg(pos, range, damage, user_unit)
local player = managers.player:player_unit()
if player then
player:character_damage():damage_fire({
variant = "fire",
position = pos,
range = range,
damage = damage,
attacker_unit = user_unit,
ignite_character = ignite_character
})
end
end | agpl-3.0 |
QuiQiJingFeng/skynet | lualib/http/internal.lua | 95 | 2613 | local table = table
local type = type
local M = {}
local LIMIT = 8192
local function chunksize(readbytes, body)
while true do
local f,e = body:find("\r\n",1,true)
if f then
return tonumber(body:sub(1,f-1),16), body:sub(e+1)
end
if #body > 128 then
-- pervent the attacker send very long stream without \r\n
return
end
body = body .. readbytes()
end
end
local function readcrln(readbytes, body)
if #body >= 2 then
if body:sub(1,2) ~= "\r\n" then
return
end
return body:sub(3)
else
body = body .. readbytes(2-#body)
if body ~= "\r\n" then
return
end
return ""
end
end
function M.recvheader(readbytes, lines, header)
if #header >= 2 then
if header:find "^\r\n" then
return header:sub(3)
end
end
local result
local e = header:find("\r\n\r\n", 1, true)
if e then
result = header:sub(e+4)
else
while true do
local bytes = readbytes()
header = header .. bytes
if #header > LIMIT then
return
end
e = header:find("\r\n\r\n", -#bytes-3, true)
if e then
result = header:sub(e+4)
break
end
if header:find "^\r\n" then
return header:sub(3)
end
end
end
for v in header:gmatch("(.-)\r\n") do
if v == "" then
break
end
table.insert(lines, v)
end
return result
end
function M.parseheader(lines, from, header)
local name, value
for i=from,#lines do
local line = lines[i]
if line:byte(1) == 9 then -- tab, append last line
if name == nil then
return
end
header[name] = header[name] .. line:sub(2)
else
name, value = line:match "^(.-):%s*(.*)"
if name == nil or value == nil then
return
end
name = name:lower()
if header[name] then
local v = header[name]
if type(v) == "table" then
table.insert(v, value)
else
header[name] = { v , value }
end
else
header[name] = value
end
end
end
return header
end
function M.recvchunkedbody(readbytes, bodylimit, header, body)
local result = ""
local size = 0
while true do
local sz
sz , body = chunksize(readbytes, body)
if not sz then
return
end
if sz == 0 then
break
end
size = size + sz
if bodylimit and size > bodylimit then
return
end
if #body >= sz then
result = result .. body:sub(1,sz)
body = body:sub(sz+1)
else
result = result .. body .. readbytes(sz - #body)
body = ""
end
body = readcrln(readbytes, body)
if not body then
return
end
end
local tmpline = {}
body = M.recvheader(readbytes, tmpline, body)
if not body then
return
end
header = M.parseheader(tmpline,1,header)
return result, header
end
return M
| mit |
devaloosh/VIPTEAM | plugins/banhammer.lua | 2 | 13163 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Team name : ( 🌐 VIP_TEAM 🌐 )▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ File name : ( اسم الملف ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Guenat team: ( @VIP_TEAM1 ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄
—]]
local function pre_process(msg)
local data = load_data(_config.moderation.data)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned and not is_momod2(msg.from.id, msg.to.id) or is_gbanned(user_id) and not is_admin2(msg.from.id) then -- Check it with redis
print('User is banned!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) >= 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) >= 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' or msg.to.type == 'channel' then
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
local chat_id = extra.chat_id
local chat_type = extra.chat_type
if chat_type == "chat" then
receiver = 'chat#id'..chat_id
else
receiver = 'channel#id'..chat_id
end
if success == 0 then
return send_large_msg(receiver, "Cannot find user by that username!")
end
local member_id = result.peer_id
local user_id = member_id
local member = result.username
local from_id = extra.from_id
local get_cmd = extra.get_cmd
if get_cmd == 'dee' then
if member_id == from_id then
send_large_msg(receiver, "You can't kick yourself")
return
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
send_large_msg(receiver, "You can't kick mods/owner/admins")
return
end
kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
send_large_msg(receiver, "You can't ban mods/owner/admins")
return
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
ban_user(member_id, chat_id)
elseif get_cmd == 'uban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
banall_user(member_id)
elseif get_cmd == 'nbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally unbanned')
unbanall_user(member_id)
end
end
local function run(msg, matches)
local support_id = msg.from.id
if matches[1]:lower() == 'id' and msg.to.type == "chat" or msg.to.type == "user" then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' and msg.to.type == "chat" then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "gbans" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin1(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin1(msg) then
msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
local receiver = get_receiver(msg)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(matches[2], msg.to.id)
send_large_msg(receiver, 'User ['..matches[2]..'] banned')
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'uban' then -- /uban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' nbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'uban',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'dee' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin1(msg) then
msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'dee',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if not is_admin1(msg) and not is_support(support_id) then
return
end
if matches[1]:lower() == 'banall' and is_admin1(msg) then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin1(msg) then
banall = get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'nbanall' then -- Global nban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] globally unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'nbanall',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbans" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^([Bb]anall) (.*)$",
"^([Bb]anall)$",
"^(gbans) (.*)$",
"^([Bb]anlist)$",
"^(gbans)$",
"^([Kk]ickme)",
"^(dee)$",
"^([Bb]an)$",
"^([Bb]an) (.*)$",
"^(uban) (.*)$",
"^(nbanall) (.*)$",
"^(nbanall)$",
"^(dee) (.*)$",
"^(uban)$",
"^([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| agpl-3.0 |
luvit/luvit | tests/test-pipe.lua | 11 | 1411 | --[[
Copyright 201202015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
require('tap')(function (test)
local path = require('path')
local fs = require('fs')
local __dirname = module.dir
local name = 'test-pipe'
local tmp_file = path.join(__dirname, 'tmp', name)
fs.writeFileSync(tmp_file, "")
local streamEventClosed = false
local streamEventAlreadyClosed = false
local file_path = path.join(__dirname, name..'.lua')
test("pipe", function()
local fp = fs.createReadStream(file_path)
local null = fs.createWriteStream(tmp_file)
null:on('error', function(err)
p(err)
if err.message:find('write after end') then
streamEventAlreadyClosed = true
end
end)
null:on('closed', function()
p('closed')
streamEventClosed = true
null:write('after closed')
end)
fp:pipe(null)
assert(true)
end)
end) | apache-2.0 |
ominux/nn | SpatialContrastiveNormalization.lua | 63 | 1444 | local SpatialContrastiveNormalization, parent = torch.class('nn.SpatialContrastiveNormalization','nn.Module')
function SpatialContrastiveNormalization:__init(nInputPlane, kernel, threshold, thresval)
parent.__init(self)
-- get args
self.nInputPlane = nInputPlane or 1
self.kernel = kernel or torch.Tensor(9,9):fill(1)
self.threshold = threshold or 1e-4
self.thresval = thresval or threshold or 1e-4
local kdim = self.kernel:nDimension()
-- check args
if kdim ~= 2 and kdim ~= 1 then
error('<SpatialContrastiveNormalization> averaging kernel must be 2D or 1D')
end
if (self.kernel:size(1) % 2) == 0 or (kdim == 2 and (self.kernel:size(2) % 2) == 0) then
error('<SpatialContrastiveNormalization> averaging kernel must have ODD dimensions')
end
-- instantiate sub+div normalization
self.normalizer = nn.Sequential()
self.normalizer:add(nn.SpatialSubtractiveNormalization(self.nInputPlane, self.kernel))
self.normalizer:add(nn.SpatialDivisiveNormalization(self.nInputPlane, self.kernel,
self.threshold, self.thresval))
end
function SpatialContrastiveNormalization:updateOutput(input)
self.output = self.normalizer:forward(input)
return self.output
end
function SpatialContrastiveNormalization:updateGradInput(input, gradOutput)
self.gradInput = self.normalizer:backward(input, gradOutput)
return self.gradInput
end
| bsd-3-clause |
payday-restoration/restoration-mod | lua/sc/managers/menumanager.lua | 1 | 13265 | restoration._cop_comment_cooldown_t = {}
--Fix for Grenade Cases on Pro Jobs
function MenuPrePlanningInitiator:set_locks_to_param(params, key, index)
local data = tweak_data:get_raw_value("preplanning", key, index) or {}
local enabled = params.enabled ~= false
params.tooltip = params.tooltip or {}
params.tooltip.errors = params.tooltip.errors or {}
if data.dlc_lock and not Global.game_settings and Global.game_settings.one_down then
local dlc_unlocked = managers.dlc:is_dlc_unlocked(data.dlc_lock)
if not dlc_unlocked then
local error_text_id = tweak_data:get_raw_value("lootdrop", "global_values", data.dlc_lock, "unlock_id")
table.insert(params.tooltip.errors, managers.localization:to_upper_text(error_text_id))
enabled = false
end
elseif data.upgrade_lock then
local upgrade_unlocked = managers.player:has_category_upgrade(data.upgrade_lock.category, data.upgrade_lock.upgrade)
if not upgrade_unlocked then
table.insert(params.tooltip.errors, managers.localization:to_upper_text("menu_asset_lock_" .. data.upgrade_lock.upgrade))
enabled = false
end
end
params.enabled = enabled
params.ignore_disabled = true
end
--Allow Chat in Crime.net Offline
function MenuManager:toggle_chatinput()
if Application:editor() or SystemInfo:platform() ~= Idstring("WIN32") or self:active_menu() or not managers.network:session() then
return
end
if managers.hud then
managers.hud:toggle_chatinput()
return true
end
end
function MenuJukeboxHeistTracks:modify_node(node, data)
managers.menu_component:show_contract_character(false)
node:clean_items()
local track_list, track_locked = managers.music:jukebox_music_tracks()
local option_data = {
type = "MenuItemMultiChoiceWithIcon"
}
table.insert(option_data, {
value = "all",
text_id = "menu_jukebox_playlist_all",
_meta = "option"
})
table.insert(option_data, {
value = "playlist",
text_id = "menu_jukebox_random_heist_playlist",
_meta = "option"
})
for _, track_name in pairs(track_list) do
if not track_locked[track_name] then
table.insert(option_data, {
_meta = "option",
text_id = "menu_jukebox_" .. track_name,
value = track_name
})
end
end
local track_list = {}
local unique_jobs = {}
for _, job_id in ipairs(tweak_data.narrative:get_jobs_index()) do
local job_tweak = tweak_data.narrative:job_data(job_id)
if self:_have_music(job_id) and not table.contains(unique_jobs, job_tweak.name_id) then
local text_id, color_ranges = tweak_data.narrative:create_job_name(job_id, true)
local days = #tweak_data.narrative:job_chain(job_id)
table.insert(unique_jobs, job_tweak.name_id)
if days > 1 then
for i = 1, days, 1 do
table.insert(track_list, {
job_id = job_id,
name_id = job_tweak.name_id,
day = i,
sort_id = text_id,
text_id = text_id .. " - " .. managers.localization:text("menu_jukebox_heist_day", {
day = i
}),
color_ranges = color_ranges
})
end
else
table.insert(track_list, {
job_id = job_id,
name_id = job_tweak.name_id,
sort_id = text_id,
text_id = text_id,
color_ranges = color_ranges
})
end
end
end
table.sort(track_list, function (x, y)
return x.sort_id == y.sort_id and x.text_id < y.text_id or x.sort_id < y.sort_id
end)
table.insert(track_list, {
name_id = "escape",
job_id = "escape",
text_id = managers.localization:text("menu_jukebox_heist_escape")
})
table.insert(track_list, {
name_id = "ponr",
job_id = "ponr",
text_id = managers.localization:text("menu_jukebox_heist_ponr")
})
for _, track_data in pairs(track_list) do
local heist_name = track_data.name_id .. (track_data.day and track_data.day or "")
local params = {
localize = "false",
align = "left",
callback = "jukebox_option_heist_tracks",
text_offset = 100,
name = heist_name,
text_id = track_data.text_id,
color_ranges = track_data.color_ranges,
heist_job = track_data.job_id,
heist_days = track_data.day,
icon = tweak_data.hud_icons:get_icon_data("jukebox_playing_icon")
}
local item = node:create_item(option_data, params)
item:set_value(managers.music:track_attachment(heist_name) or "all")
node:add_item(item)
end
managers.menu:add_back_button(node)
return node
end
function MenuCallbackHandler:jukebox_option_heist_tracks(item)
local track = item:value()
local job = item:parameters().heist_job
if job == "escape" or job == "ponr" then
managers.music:track_attachment_add(job, track)
else
local job_tweak = tweak_data.narrative.jobs[job]
if not job_tweak then
return
end
local day = item:parameters().heist_days and item:parameters().heist_days or ""
managers.music:track_attachment_add(job_tweak.name_id .. day, track)
end
local item_list = managers.menu:active_menu().logic:selected_node():items()
for _, item_data in ipairs(item_list) do
if item_data.set_icon_visible then
item_data:set_icon_visible(false)
end
end
if track ~= "all" and track ~= "playlist" then
managers.music:track_listen_start("music_heist_assault", track)
item:set_icon_visible(true)
else
managers.music:track_listen_stop()
end
managers.savefile:setting_changed()
end
function restoration:_game_t()
return TimerManager:game():time()
end
function restoration:start_inform_ene_cooldown(cooldown_t, msg_type)
local t = self:_game_t()
self._cop_comment_cooldown_t[msg_type] = self._cop_comment_cooldown_t[msg_type] or {}
self._cop_comment_cooldown_t[msg_type]._cooldown_t = cooldown_t + t
self._cooldown_delay_t = t + 5
end
function restoration:ene_inform_has_cooldown_met(msg_type)
local t = TimerManager:game():time()
if not self._cop_comment_cooldown_t[msg_type] then
return true
end
if self._cooldown_delay_t and self._cooldown_delay_t > t then
return false
end
if self._cop_comment_cooldown_t[msg_type]._cooldown_t < t then
return true
end
return false
end
function restoration:_has_deployable_type(unit, deployable)
local peer_id = managers.criminals:character_peer_id_by_unit(unit)
if not peer_id then
return false
end
local synced_deployable_equipment = managers.player:get_synced_deployable_equipment(peer_id)
if synced_deployable_equipment then
if not synced_deployable_equipment.deployable or synced_deployable_equipment.deployable ~= deployable then
return false
end
--[[if synced_deployable_equipment.amount and synced_deployable_equipment.amount <= 0 then
return false
end]]--
return true
end
return false
end
function restoration:_next_to_cops(data, amount)
local close_peers = {}
local range = 5000
amount = amount or 4
for u_key, u_data in pairs(managers.enemy:all_enemies()) do
if data.key ~= u_key then
if u_data.unit and alive(u_data.unit) and not u_data.unit:character_damage():dead() then
local anim_data = u_data.unit:anim_data()
if not anim_data.surrender and not anim_data.hands_tied and not anim_data.hands_back then
if mvector3.distance_sq(data.m_pos, u_data.m_pos) < range * range then
table.insert(close_peers, u_data.unit)
end
end
end
end
end
return #close_peers >= amount
end
function restoration:inform_law_enforcements(data, debug_enemy)
if managers.groupai:state()._special_unit_types[data.unit:base()._tweak_table] then
return
end
if data.unit:in_slot(16) or not data.char_tweak.chatter then
return
end
local sound_name, cooldown_t, msg_type
local enemy_target = data.attention_obj
if debug_enemy then
enemy_target = {
unit = debug_enemy,
dis = 0,
is_deployable = false
}
end
if enemy_target then
if enemy_target.is_deployable then
msg_type = "sentry_detected"
sound_name = "ch2"
cooldown_t = 30
elseif enemy_target.unit:in_slot(managers.slot:get_mask("all_criminals")) then
local weapon = enemy_target.unit.inventory and enemy_target.unit:inventory():equipped_unit()
if weapon and weapon:base():is_category("saw") then
msg_type = "saw_maniac"
sound_name = "ch4"
cooldown_t = 30
elseif self:_has_deployable_type(enemy_target.unit, "doctor_bag") then
msg_type = "doc_bag"
sound_name = "med"
cooldown_t = 30
--log("they have a medic >:c")
elseif self:_has_deployable_type(enemy_target.unit, "first_aid_kit") then
msg_type = "first_aid_kit"
sound_name = "med"
cooldown_t = 30
--log("they have a medic >:c")
elseif self:_has_deployable_type(enemy_target.unit, "ammo_bag") then
msg_type = "ammo_bag"
sound_name = "amm"
cooldown_t = 30
--log("they have an ammy bag")
elseif self:_has_deployable_type(enemy_target.unit, "trip_mine") then
msg_type = "trip_mine"
sound_name = "ch1"
cooldown_t = 30
--log("watch out for the trip mines")
end
end
end
if self:_next_to_cops(data) then
return
end
if not enemy_target or enemy_target.dis > 100000 then
return
end
if not msg_type or not self:ene_inform_has_cooldown_met(msg_type) then
return
end
if data.unit then
data.unit:sound():say(sound_name, true)
self:start_inform_ene_cooldown(cooldown_t, msg_type)
end
end
--[[
Hooks:Add("radialmenu_released_resutilitymenu","resmod_utility_menu_on_selected",function(item)
if item == 1 then
local loss_rate = 0.0
local placement_cost = 0.3
local ammo_ratio_taken = 0
local player = managers.player:local_player()
if player and alive(player) then
for index, weapon in pairs(player:inventory():available_selections()) do
local ammo_taken = weapon.unit:base():remove_ammo(1 - placement_cost)
ammo_ratio_taken = ammo_ratio_taken + (ammo_taken / weapon.unit:base():get_ammo_max())
-- Log("ammo_ratio_taken: " .. ammo_ratio_taken)
managers.hud:set_ammo_amount(index, weapon.unit:base():ammo_info())
end
local pos = player:position()
local angle = player:movement():m_head_rot():y()
local rot = Rotation(angle, angle, 0)
local ammo_upgrade_lvl = 0 --managers.player:upgrade_level("ammo_bag", "ammo_increase")
local bullet_storm_level = 0 -- managers.player:upgrade_level("player", "no_ammo_cost")
local function concat(div,...) --yeah that's right i'm too good for table.concat
local result
for _,value in pairs({...}) do
if result then
result = result .. div .. tostring(value)
else
result = tostring(value)
end
end
return result
end
if Network:is_client() then
-- managers.network:session():send_to_host("place_ammo_bag", pos, rot, ammo_upgrade_lvl, bullet_storm_level)
--use networking instead
LuaNetworking:SendToPeer(1,"restoration_drop_ammo",concat(":",pos.x,pos.y,pos.z,rot:x(),rot:y(),rot:z(),ammo_ratio_taken))
else
local unit = AmmoBagBase.spawn(pos, rot, ammo_upgrade_lvl, managers.network:session():local_peer():id(), bullet_storm_level)
unit:base()._ammo_amount = math.floor(math.min(ammo_ratio_taken,placement_cost) * (1 - loss_rate) * 100) / 100
local current_amount = unit:base()._ammo_amount
unit:base():_set_visual_stage()
managers.network:session():send_to_peers_synched("sync_ammo_bag_ammo_taken", unit, current_amount - ammo_ratio_taken)
-- Log("amount: " .. tostring(unit:base()._ammo_amount))
-- LuaNetworking:SendToPeer(1,"restoration_drop_ammo",concat(":",pos.x,pos.y,pos.z,rot:yaw(),rot:pitch(),rot:roll(),ammo_ratio_taken))
end
elseif item == 2 or item == 3 then
local equipped_deployable = managers.blackmarket:equipped_deployable()
if equipped_deployable == "tripmines" then
-- Log("Equipped tripmines")
elseif equipped_deployable == "sentry_gun" then
-- Log("Equipped sentrygun")
end
end
end
end)
]]
-- if restoration.Options:GetValue("OTHER/PDTHChallenges") then
Hooks:PostHook(MenuManager, "do_clear_progress", "pdth_hud_reset_challenges", function(ply)
managers.challenges_res:reset_challenges()
end)
-- end
function MenuCallbackHandler:accept_skirmish_contract(item)
local node = item:parameters().gui_node.node
managers.menu:active_menu().logic:navigate_back(true)
managers.menu:active_menu().logic:navigate_back(true)
local job_id = (node:parameters().menu_component_data or {}).job_id
local job_data = {
difficulty = "overkill_290",
customize_contract = true,
job_id = job_id or managers.skirmish:random_skirmish_job_id(),
difficulty_id = tweak_data:difficulty_to_index("overkill_290")
}
managers.job:on_buy_job(job_data.job_id, job_data.difficulty_id)
if Global.game_settings.single_player then
MenuCallbackHandler:start_single_player_job(job_data)
else
MenuCallbackHandler:start_job(job_data)
end
end
function MenuCallbackHandler:accept_skirmish_weekly_contract(item)
managers.menu:active_menu().logic:navigate_back(true)
managers.menu:active_menu().logic:navigate_back(true)
local weekly_skirmish = managers.skirmish:active_weekly()
local job_data = {
difficulty = "overkill_290",
weekly_skirmish = true,
job_id = weekly_skirmish.id
}
if Global.game_settings.single_player then
MenuCallbackHandler:start_single_player_job(job_data)
else
MenuCallbackHandler:start_job(job_data)
end
end | agpl-3.0 |
khanasbot/Avatar_Bot | plugins/bugzilla.lua | 611 | 3983 | do
local BASE_URL = "https://bugzilla.mozilla.org/rest/"
local function bugzilla_login()
local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password
print("accessing " .. url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_check(id)
-- data = bugzilla_login()
local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey
-- print(url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_listopened(email)
local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey
local res,code = https.request( url )
print(res)
local data = json:decode(res)
return data
end
local function run(msg, matches)
local response = ""
if matches[1] == "status" then
local data = bugzilla_check(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
response = response .. "\n Last update: "..data.bugs[1].last_change_time
response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
print(response)
end
elseif matches[1] == "list" then
local data = bugzilla_listopened(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
-- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
-- response = response .. "\n Last update: "..data.bugs[1].last_change_time
-- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
-- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
-- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
local total = table.map_length(data.bugs)
print("total bugs: " .. total)
local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2]
if total > 0 then
response = response .. ": "
for tableKey, bug in pairs(data.bugs) do
response = response .. "\n #" .. bug.id
response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution
response = response .. "\n Whiteboard: " .. bug.whiteboard
response = response .. "\n Summary: " .. bug.summary
end
end
end
end
return response
end
-- (table)
-- [bugs] = (table)
-- [1] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 927704
-- [whiteboard] = (string) [approved][full processed]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/
-- [2] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 1049337
-- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/
-- total bugs: 2
return {
description = "Lookup bugzilla status update",
usage = "/bot bugzilla [bug number]",
patterns = {
"^/bugzilla (status) (.*)$",
"^/bugzilla (list) (.*)$"
},
run = run
}
end | gpl-2.0 |
amirkingred/telejian | plugins/bugzilla.lua | 611 | 3983 | do
local BASE_URL = "https://bugzilla.mozilla.org/rest/"
local function bugzilla_login()
local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password
print("accessing " .. url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_check(id)
-- data = bugzilla_login()
local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey
-- print(url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_listopened(email)
local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey
local res,code = https.request( url )
print(res)
local data = json:decode(res)
return data
end
local function run(msg, matches)
local response = ""
if matches[1] == "status" then
local data = bugzilla_check(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
response = response .. "\n Last update: "..data.bugs[1].last_change_time
response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
print(response)
end
elseif matches[1] == "list" then
local data = bugzilla_listopened(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
-- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
-- response = response .. "\n Last update: "..data.bugs[1].last_change_time
-- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
-- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
-- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
local total = table.map_length(data.bugs)
print("total bugs: " .. total)
local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2]
if total > 0 then
response = response .. ": "
for tableKey, bug in pairs(data.bugs) do
response = response .. "\n #" .. bug.id
response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution
response = response .. "\n Whiteboard: " .. bug.whiteboard
response = response .. "\n Summary: " .. bug.summary
end
end
end
end
return response
end
-- (table)
-- [bugs] = (table)
-- [1] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 927704
-- [whiteboard] = (string) [approved][full processed]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/
-- [2] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 1049337
-- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/
-- total bugs: 2
return {
description = "Lookup bugzilla status update",
usage = "/bot bugzilla [bug number]",
patterns = {
"^/bugzilla (status) (.*)$",
"^/bugzilla (list) (.*)$"
},
run = run
}
end | gpl-2.0 |
haider1984/-1 | plugins/en-onservice.lua | 6 | 1369 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ BY SAJAD NOORI (@SAJJADNOORI) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ KICK BOT : طرد البوت ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local function run(msg, matches)
local bot_id = our_id
local receiver = get_receiver(msg)
if matches[1] == 'leave' and is_admin1(msg) then
chat_del_user("chat#id"..msg.to.id, 'user#id'..bot_id, ok_cb, false)
leave_channel(receiver, ok_cb, false)
elseif msg.service and msg.action.type == "chat_add_user" and msg.action.user.id == tonumber(bot_id) and not is_admin1(msg) then
send_large_msg(receiver, 'This is not one of my groups.', ok_cb, false)
chat_del_user(receiver, 'user#id'..bot_id, ok_cb, false)
leave_channel(receiver, ok_cb, false)
end
end
return {
patterns = {
"^(leave)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
ominux/nn | WeightedEuclidean.lua | 17 | 8147 | local WeightedEuclidean, parent = torch.class('nn.WeightedEuclidean', 'nn.Module')
function WeightedEuclidean:__init(inputSize,outputSize)
parent.__init(self)
self.weight = torch.Tensor(inputSize,outputSize)
self.gradWeight = torch.Tensor(inputSize,outputSize)
-- each template (output dim) has its own diagonal covariance matrix
self.diagCov = torch.Tensor(inputSize,outputSize)
self.gradDiagCov = torch.Tensor(inputSize,outputSize)
self:reset()
end
function WeightedEuclidean:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.weight:size(1))
end
self.weight:uniform(-stdv, stdv)
self.diagCov:fill(1)
end
local function view(res, src, ...)
local args = {...}
if src:isContiguous() then
res:view(src, table.unpack(args))
else
res:reshape(src, table.unpack(args))
end
end
function WeightedEuclidean:updateOutput(input)
-- lazy-initialize
self._diagCov = self._diagCov or self.output.new()
self._input = self._input or input.new()
self._weight = self._weight or self.weight.new()
self._expand = self._expand or self.output.new()
self._expand2 = self._expand or self.output.new()
self._expand3 = self._expand3 or self.output.new()
self._repeat = self._repeat or self.output.new()
self._repeat2 = self._repeat2 or self.output.new()
self._repeat3 = self._repeat3 or self.output.new()
local inputSize, outputSize = self.weight:size(1), self.weight:size(2)
-- y_j = || c_j * (w_j - x) ||
if input:dim() == 1 then
view(self._input, input, inputSize, 1)
self._expand:expandAs(self._input, self.weight)
self._repeat:resizeAs(self._expand):copy(self._expand)
self._repeat:add(-1, self.weight)
self._repeat:cmul(self.diagCov)
self.output:norm(self._repeat, 2, 1)
self.output:resize(outputSize)
elseif input:dim() == 2 then
local batchSize = input:size(1)
view(self._input, input, batchSize, inputSize, 1)
self._expand:expand(self._input, batchSize, inputSize, outputSize)
-- make the expanded tensor contiguous (requires lots of memory)
self._repeat:resizeAs(self._expand):copy(self._expand)
self._weight:view(self.weight, 1, inputSize, outputSize)
self._expand2:expandAs(self._weight, self._repeat)
self._diagCov:view(self.diagCov, 1, inputSize, outputSize)
self._expand3:expandAs(self._diagCov, self._repeat)
if torch.type(input) == 'torch.CudaTensor' then
-- requires lots of memory, but minimizes cudaMallocs and loops
self._repeat2:resizeAs(self._expand2):copy(self._expand2)
self._repeat:add(-1, self._repeat2)
self._repeat3:resizeAs(self._expand3):copy(self._expand3)
self._repeat:cmul(self._repeat3)
else
self._repeat:add(-1, self._expand2)
self._repeat:cmul(self._expand3)
end
self.output:norm(self._repeat, 2, 2)
self.output:resize(batchSize, outputSize)
else
error"1D or 2D input expected"
end
return self.output
end
function WeightedEuclidean:updateGradInput(input, gradOutput)
if not self.gradInput then
return
end
self._div = self._div or input.new()
self._output = self._output or self.output.new()
self._expand4 = self._expand4 or input.new()
self._gradOutput = self._gradOutput or input.new()
if not self.fastBackward then
self:updateOutput(input)
end
local inputSize, outputSize = self.weight:size(1), self.weight:size(2)
--[[
dy_j -2 * c_j * c_j * (w_j - x) c_j * c_j * (x - w_j)
---- = -------------------------- = ---------------------
dx 2 || c_j * (w_j - x) || y_j
--]]
-- to prevent div by zero (NaN) bugs
self._output:resizeAs(self.output):copy(self.output):add(0.0000001)
view(self._gradOutput, gradOutput, gradOutput:size())
self._div:cdiv(gradOutput, self._output)
if input:dim() == 1 then
self._div:resize(1, outputSize)
self._expand4:expandAs(self._div, self.weight)
if torch.type(input) == 'torch.CudaTensor' then
self._repeat2:resizeAs(self._expand4):copy(self._expand4)
self._repeat2:cmul(self._repeat)
else
self._repeat2:cmul(self._repeat, self._expand4)
end
self._repeat2:cmul(self.diagCov)
self.gradInput:sum(self._repeat2, 2)
self.gradInput:resizeAs(input)
elseif input:dim() == 2 then
local batchSize = input:size(1)
self._div:resize(batchSize, 1, outputSize)
self._expand4:expand(self._div, batchSize, inputSize, outputSize)
if torch.type(input) == 'torch.CudaTensor' then
self._repeat2:resizeAs(self._expand4):copy(self._expand4)
self._repeat2:cmul(self._repeat)
self._repeat2:cmul(self._repeat3)
else
self._repeat2:cmul(self._repeat, self._expand4)
self._repeat2:cmul(self._expand3)
end
self.gradInput:sum(self._repeat2, 3)
self.gradInput:resizeAs(input)
else
error"1D or 2D input expected"
end
return self.gradInput
end
function WeightedEuclidean:accGradParameters(input, gradOutput, scale)
local inputSize, outputSize = self.weight:size(1), self.weight:size(2)
scale = scale or 1
--[[
dy_j 2 * c_j * c_j * (w_j - x) c_j * c_j * (w_j - x)
---- = ------------------------- = ---------------------
dw_j 2 || c_j * (w_j - x) || y_j
dy_j 2 * c_j * (w_j - x)^2 c_j * (w_j - x)^2
---- = ----------------------- = -----------------
dc_j 2 || c_j * (w_j - x) || y_j
--]]
-- assumes a preceding call to updateGradInput
if input:dim() == 1 then
self.gradWeight:add(-scale, self._repeat2)
self._repeat:cdiv(self.diagCov)
self._repeat:cmul(self._repeat)
self._repeat:cmul(self.diagCov)
if torch.type(input) == 'torch.CudaTensor' then
self._repeat2:resizeAs(self._expand4):copy(self._expand4)
self._repeat2:cmul(self._repeat)
else
self._repeat2:cmul(self._repeat, self._expand4)
end
self.gradDiagCov:add(self._repeat2)
elseif input:dim() == 2 then
self._sum = self._sum or input.new()
self._sum:sum(self._repeat2, 1)
self._sum:resize(inputSize, outputSize)
self.gradWeight:add(-scale, self._sum)
if torch.type(input) == 'torch.CudaTensor' then
-- requires lots of memory, but minimizes cudaMallocs and loops
self._repeat:cdiv(self._repeat3)
self._repeat:cmul(self._repeat)
self._repeat:cmul(self._repeat3)
self._repeat2:resizeAs(self._expand4):copy(self._expand4)
self._repeat:cmul(self._repeat2)
else
self._repeat:cdiv(self._expand3)
self._repeat:cmul(self._repeat)
self._repeat:cmul(self._expand3)
self._repeat:cmul(self._expand4)
end
self._sum:sum(self._repeat, 1)
self._sum:resize(inputSize, outputSize)
self.gradDiagCov:add(scale, self._sum)
else
error"1D or 2D input expected"
end
end
function WeightedEuclidean:type(type)
if type then
-- prevent premature memory allocations
self._input = nil
self._output = nil
self._gradOutput = nil
self._weight = nil
self._div = nil
self._sum = nil
self._expand = nil
self._expand2 = nil
self._expand3 = nil
self._expand4 = nil
self._repeat = nil
self._repeat2 = nil
self._repeat3 = nil
end
return parent.type(self, type)
end
function WeightedEuclidean:parameters()
return {self.weight, self.diagCov}, {self.gradWeight, self.gradDiagCov}
end
function WeightedEuclidean:accUpdateGradParameters(input, gradOutput, lr)
local gradWeight = self.gradWeight
local gradDiagCov = self.gradDiagCov
self.gradWeight = self.weight
self.gradDiagCov = self.diagCov
self:accGradParameters(input, gradOutput, -lr)
self.gradWeight = gradWeight
self.gradDiagCov = gradDiagCov
end
| bsd-3-clause |
OpenRA/OpenRA | mods/cnc/maps/gdi05c/gdi05c.lua | 1 | 5578 | --[[
Copyright 2007-2022 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
RepairThreshold = { easy = 0.3, normal = 0.6, hard = 0.9 }
ActorRemovals =
{
easy = { Actor197, Actor198, Actor199, Actor162, Actor178, Actor181, Actor171, Actor163 },
normal = { Actor197, Actor162 },
hard = { },
}
AllToHuntTrigger = { Silo1, Proc1, Silo2, Radar1, Afld1, Hand1, Nuke1, Nuke2, Nuke3, Fact1 }
AtkRoute1 = { waypoint0, waypoint1, waypoint2, waypoint3, waypoint4 }
AtkRoute2 = { waypoint0, waypoint8, waypoint4 }
AtkRoute3 = { waypoint0, waypoint1, waypoint2, waypoint5, waypoint6, waypoint7 }
AtkRoute4 = { waypoint0, waypoint8, waypoint9, waypoint10, waypoint11 }
AutoCreateTeams =
{
{ types = { e1 = 2, e3 = 2 }, route = AtkRoute1 },
{ types = { e1 = 1, e3 = 2 }, route = AtkRoute2 },
{ types = { ltnk = 1 } , route = AtkRoute2 },
{ types = { bggy = 1 } , route = AtkRoute2 },
{ types = { bggy = 1 } , route = AtkRoute1 },
{ types = { ltnk = 1 } , route = AtkRoute3 },
{ types = { bggy = 1 } , route = AtkRoute4 }
}
Atk1Delay = { easy = DateTime.Seconds(60), normal = DateTime.Seconds(50), hard = DateTime.Seconds(40) }
Atk2Delay = { easy = DateTime.Seconds(90), normal = DateTime.Seconds(70), hard = DateTime.Seconds(50) }
Atk3Delay = { easy = DateTime.Seconds(120), normal = DateTime.Seconds(90), hard = DateTime.Seconds(70) }
Atk4Delay = { easy = DateTime.Seconds(150), normal = DateTime.Seconds(110), hard = DateTime.Seconds(90) }
AutoAtkStartDelay = { easy = DateTime.Seconds(150), normal = DateTime.Seconds(120), hard = DateTime.Seconds(90) }
AutoAtkMinDelay = { easy = DateTime.Minutes(1), normal = DateTime.Seconds(45), hard = DateTime.Seconds(30) }
AutoAtkMaxDelay = { easy = DateTime.Minutes(2), normal = DateTime.Seconds(90), hard = DateTime.Minutes(1) }
GDIBase = { GdiNuke1, GdiProc1, GdiWeap1, GdiNuke2, GdiNuke3, GdiPyle1, GdiSilo1, GdiRadar1 }
GDIUnits = { "e2", "e2", "e2", "e2", "e1", "e1", "e1", "e1", "mtnk", "mtnk", "jeep", "apc", "apc" }
GDIHarvester = { "harv" }
NodSams = { Sam1, Sam2, Sam3 }
AutoCreateTeam = function()
local team = Utils.Random(AutoCreateTeams)
for type, count in pairs(team.types) do
MoveAndHunt(Utils.Take(count, Nod.GetActorsByType(type)), team.route)
end
Trigger.AfterDelay(Utils.RandomInteger(AutoAtkMinDelay[Difficulty], AutoAtkMaxDelay[Difficulty]), AutoCreateTeam)
end
DiscoverGDIBase = function(actor, discoverer)
if BaseDiscovered or not discoverer == GDI then
return
end
--Spawn harv only when base is discovered, otherwise it will waste tiberium and might get killed before the player arrives
if not GdiProc1.IsDead then
Reinforcements.Reinforce(GDI, GDIHarvester, { GdiProc1.Location + CVec.New(0, 2), GdiProc1.Location + CVec.New(-1, 3) }, 1)
end
Utils.Do(GDIBase, function(actor)
actor.Owner = GDI
end)
BaseDiscovered = true
EliminateNod = AddPrimaryObjective(GDI, "eliminate-nod")
GDI.MarkCompletedObjective(FindBase)
end
Atk1TriggerFunction = function()
MoveAndHunt(Utils.Take(2, Nod.GetActorsByType('e1')), AtkRoute1)
MoveAndHunt(Utils.Take(2, Nod.GetActorsByType('e3')), AtkRoute1)
end
Atk2TriggerFunction = function()
MoveAndHunt(Utils.Take(4, Nod.GetActorsByType('e3')), AtkRoute2)
end
Atk3TriggerFunction = function()
MoveAndHunt(Utils.Take(1, Nod.GetActorsByType('bggy')), AtkRoute2)
end
Atk4TriggerFunction = function()
MoveAndHunt(Utils.Take(2, Nod.GetActorsByType('e1')), AtkRoute1)
MoveAndHunt(Utils.Take(1, Nod.GetActorsByType('ltnk')), AtkRoute1)
end
InsertGDIUnits = function()
Media.PlaySpeechNotification(GDI, "Reinforce")
Reinforcements.Reinforce(GDI, GDIUnits, { UnitsEntry.Location, UnitsRally.Location }, 15)
end
WorldLoaded = function()
GDI = Player.GetPlayer("GDI")
AbandonedBase = Player.GetPlayer("AbandonedBase")
Nod = Player.GetPlayer("Nod")
InitObjectives(GDI)
RepairNamedActors(Nod, RepairThreshold[Difficulty])
FindBase = AddPrimaryObjective(GDI, "find-gdi-base")
DestroySAMs = AddSecondaryObjective(GDI, "destroy-sams")
NodObjective = AddPrimaryObjective(Nod, "destroy-gdi")
Utils.Do(ActorRemovals[Difficulty], function(unit)
unit.Destroy()
end)
Trigger.AfterDelay(Atk1Delay[Difficulty], Atk1TriggerFunction)
Trigger.AfterDelay(Atk2Delay[Difficulty], Atk2TriggerFunction)
Trigger.AfterDelay(Atk3Delay[Difficulty], Atk3TriggerFunction)
Trigger.AfterDelay(Atk4Delay[Difficulty], Atk4TriggerFunction)
Trigger.AfterDelay(AutoAtkStartDelay[Difficulty], AutoCreateTeam)
Trigger.OnAllKilledOrCaptured(AllToHuntTrigger, function()
Utils.Do(Nod.GetGroundAttackers(), IdleHunt)
end)
Trigger.AfterDelay(DateTime.Seconds(40), function()
local delay = function() return DateTime.Seconds(30) end
local toBuild = function() return { "e1" } end
ProduceUnits(Nod, Hand1, delay, toBuild)
end)
Trigger.OnPlayerDiscovered(AbandonedBase, DiscoverGDIBase)
Trigger.OnAllKilled(NodSams, function()
GDI.MarkCompletedObjective(DestroySAMs)
Actor.Create("airstrike.proxy", true, { Owner = GDI })
end)
Camera.Position = UnitsRally.CenterPosition
InsertGDIUnits()
end
Tick = function()
if DateTime.GameTime > 2 and GDI.HasNoRequiredUnits() then
Nod.MarkCompletedObjective(NodObjective)
end
if BaseDiscovered and Nod.HasNoRequiredUnits() then
GDI.MarkCompletedObjective(EliminateNod)
end
end
| gpl-3.0 |
salorium/awesome | lib/menubar/init.lua | 1 | 12721 | ---------------------------------------------------------------------------
--- Menubar module, which aims to provide a freedesktop menu alternative
--
-- List of menubar keybindings:
-- ---
--
-- * "Left" | "C-j" select an item on the left
-- * "Right" | "C-k" select an item on the right
-- * "Backspace" exit the current category if we are in any
-- * "Escape" exit the current directory or exit menubar
-- * "Home" select the first item
-- * "End" select the last
-- * "Return" execute the entry
-- * "C-Return" execute the command with awful.spawn
-- * "C-M-Return" execute the command in a terminal
--
-- @author Alexander Yakushev <yakushev.alex@gmail.com>
-- @copyright 2011-2012 Alexander Yakushev
-- @release @AWESOME_VERSION@
-- @module menubar
---------------------------------------------------------------------------
-- Grab environment we need
local capi = {
client = client,
mouse = mouse,
screen = screen
}
local awful = require("awful")
local common = require("awful.widget.common")
local theme = require("beautiful")
local wibox = require("wibox")
local function get_screen(s)
return s and capi.screen[s]
end
-- menubar
local menubar = { mt = {}, menu_entries = {} }
menubar.menu_gen = require("menubar.menu_gen")
menubar.utils = require("menubar.utils")
local compute_text_width = menubar.utils.compute_text_width
-- Options section
--- When true the .desktop files will be reparsed only when the
-- extension is initialized. Use this if menubar takes much time to
-- open.
menubar.cache_entries = true
--- When true the categories will be shown alongside application
-- entries.
menubar.show_categories = true
--- Specifies the geometry of the menubar. This is a table with the keys
-- x, y, width and height. Missing values are replaced via the screen's
-- geometry. However, missing height is replaced by the font size.
menubar.geometry = { width = nil,
height = nil,
x = nil,
y = nil }
--- Width of blank space left in the right side.
menubar.right_margin = theme.xresources.apply_dpi(8)
--- Label used for "Next page", default "▶▶".
menubar.right_label = "▶▶"
--- Label used for "Previous page", default "◀◀".
menubar.left_label = "◀◀"
-- awful.widget.common.list_update adds three times a margin of dpi(4)
-- for each item:
local list_interspace = theme.xresources.apply_dpi(4) * 3
--- Allows user to specify custom parameters for prompt.run function
-- (like colors).
menubar.prompt_args = {}
-- Private section
local current_item = 1
local previous_item = nil
local current_category = nil
local shownitems = nil
local instance = { prompt = nil,
widget = nil,
wibox = nil }
local common_args = { w = wibox.layout.fixed.horizontal(),
data = setmetatable({}, { __mode = 'kv' }) }
--- Wrap the text with the color span tag.
-- @param s The text.
-- @param c The desired text color.
-- @return the text wrapped in a span tag.
local function colortext(s, c)
return "<span color='" .. awful.util.ensure_pango_color(c) .. "'>" .. s .. "</span>"
end
--- Get how the menu item should be displayed.
-- @param o The menu item.
-- @return item name, item background color, background image, item icon.
local function label(o)
if o.focused then
return colortext(o.name, (theme.menu_fg_focus or theme.fg_focus)), (theme.menu_bg_focus or theme.bg_focus), nil, o.icon
else
return o.name, (theme.menu_bg_normal or theme.bg_normal), nil, o.icon
end
end
--- Perform an action for the given menu item.
-- @param o The menu item.
-- @return if the function processed the callback, new awful.prompt command, new awful.prompt prompt text.
local function perform_action(o)
if not o then return end
if o.key then
current_category = o.key
local new_prompt = shownitems[current_item].name .. ": "
previous_item = current_item
current_item = 1
return true, "", new_prompt
elseif shownitems[current_item].cmdline then
awful.spawn(shownitems[current_item].cmdline)
-- Let awful.prompt execute dummy exec_callback and
-- done_callback to stop the keygrabber properly.
return false
end
end
--- Cut item list to return only current page.
-- @tparam table all_items All items list.
-- @tparam str query Search query.
-- @tparam number|screen scr Screen
-- @return table List of items for current page.
local function get_current_page(all_items, query, scr)
scr = get_screen(scr)
if not instance.prompt.width then
instance.prompt.width = compute_text_width(instance.prompt.prompt, scr)
end
if not menubar.left_label_width then
menubar.left_label_width = compute_text_width(menubar.left_label, scr)
end
if not menubar.right_label_width then
menubar.right_label_width = compute_text_width(menubar.right_label, scr)
end
local available_space = instance.geometry.width - menubar.right_margin -
menubar.right_label_width - menubar.left_label_width -
compute_text_width(query, scr) - instance.prompt.width
local width_sum = 0
local current_page = {}
for i, item in ipairs(all_items) do
item.width = item.width or
compute_text_width(item.name, scr) +
(item.icon and instance.geometry.height or 0) + list_interspace
if width_sum + item.width > available_space then
if current_item < i then
table.insert(current_page, { name = menubar.right_label, icon = nil })
break
end
current_page = { { name = menubar.left_label, icon = nil }, item, }
width_sum = item.width
else
table.insert(current_page, item)
width_sum = width_sum + item.width
end
end
return current_page
end
--- Update the menubar according to the command entered by user.
-- @tparam str query Search query.
-- @tparam number|screen scr Screen
local function menulist_update(query, scr)
query = query or ""
shownitems = {}
local pattern = awful.util.query_to_pattern(query)
local match_inside = {}
-- First we add entries which names match the command from the
-- beginning to the table shownitems, and the ones that contain
-- command in the middle to the table match_inside.
-- Add the categories
if menubar.show_categories then
for _, v in pairs(menubar.menu_gen.all_categories) do
v.focused = false
if not current_category and v.use then
if string.match(v.name, pattern) then
if string.match(v.name, "^" .. pattern) then
table.insert(shownitems, v)
else
table.insert(match_inside, v)
end
end
end
end
end
-- Add the applications according to their name and cmdline
for _, v in ipairs(menubar.menu_entries) do
v.focused = false
if not current_category or v.category == current_category then
if string.match(v.name, pattern)
or string.match(v.cmdline, pattern) then
if string.match(v.name, "^" .. pattern)
or string.match(v.cmdline, "^" .. pattern) then
table.insert(shownitems, v)
else
table.insert(match_inside, v)
end
end
end
end
-- Now add items from match_inside to shownitems
for _, v in ipairs(match_inside) do
table.insert(shownitems, v)
end
if #shownitems > 0 then
-- Insert a run item value as the last choice
table.insert(shownitems, { name = "Exec: " .. query, cmdline = query, icon = nil })
if current_item > #shownitems then
current_item = #shownitems
end
shownitems[current_item].focused = true
else
table.insert(shownitems, { name = "", cmdline = query, icon = nil })
end
common.list_update(common_args.w, nil, label,
common_args.data,
get_current_page(shownitems, query, scr))
end
--- Create the menubar wibox and widgets.
-- @tparam[opt] screen scr Screen.
local function initialize(scr)
instance.wibox = wibox({})
instance.widget = menubar.get(scr)
instance.wibox.ontop = true
instance.prompt = awful.widget.prompt()
local layout = wibox.layout.fixed.horizontal()
layout:add(instance.prompt)
layout:add(instance.widget)
instance.wibox:set_widget(layout)
end
--- Refresh menubar's cache by reloading .desktop files.
-- @tparam[opt] screen scr Screen.
function menubar.refresh(scr)
menubar.menu_gen.generate(function(entries)
menubar.menu_entries = entries
menulist_update(nil, scr)
end)
end
--- Awful.prompt keypressed callback to be used when the user presses a key.
-- @param mod Table of key combination modifiers (Control, Shift).
-- @param key The key that was pressed.
-- @param comm The current command in the prompt.
-- @return if the function processed the callback, new awful.prompt command, new awful.prompt prompt text.
local function prompt_keypressed_callback(mod, key, comm)
if key == "Left" or (mod.Control and key == "j") then
current_item = math.max(current_item - 1, 1)
return true
elseif key == "Right" or (mod.Control and key == "k") then
current_item = current_item + 1
return true
elseif key == "BackSpace" then
if comm == "" and current_category then
current_category = nil
current_item = previous_item
return true, nil, "Run: "
end
elseif key == "Escape" then
if current_category then
current_category = nil
current_item = previous_item
return true, nil, "Run: "
end
elseif key == "Home" then
current_item = 1
return true
elseif key == "End" then
current_item = #shownitems
return true
elseif key == "Return" or key == "KP_Enter" then
if mod.Control then
current_item = #shownitems
if mod.Mod1 then
-- add a terminal to the cmdline
shownitems[current_item].cmdline = menubar.utils.terminal
.. " -e " .. shownitems[current_item].cmdline
end
end
return perform_action(shownitems[current_item])
end
return false
end
--- Show the menubar on the given screen.
-- @param scr Screen.
function menubar.show(scr)
if not instance.wibox then
initialize(scr)
elseif instance.wibox.visible then -- Menu already shown, exit
return
elseif not menubar.cache_entries then
menubar.refresh(scr)
end
-- Set position and size
scr = scr or awful.screen.focused() or 1
scr = get_screen(scr)
local scrgeom = capi.screen[scr].workarea
local geometry = menubar.geometry
instance.geometry = {x = geometry.x or scrgeom.x,
y = geometry.y or scrgeom.y,
height = geometry.height or awful.util.round(theme.get_font_height() * 1.5),
width = geometry.width or scrgeom.width}
instance.wibox:geometry(instance.geometry)
current_item = 1
current_category = nil
menulist_update(nil, scr)
local prompt_args = menubar.prompt_args or {}
prompt_args.prompt = "Run: "
awful.prompt.run(prompt_args, instance.prompt.widget,
function() end, -- exe_callback function set to do nothing
awful.completion.shell, -- completion_callback
awful.util.get_cache_dir() .. "/history_menu",
nil,
menubar.hide, function(query) menulist_update(query, scr) end,
prompt_keypressed_callback
)
instance.wibox.visible = true
end
--- Hide the menubar.
function menubar.hide()
instance.wibox.visible = false
end
--- Get a menubar wibox.
-- @tparam[opt] screen scr Screen.
-- @return menubar wibox.
function menubar.get(scr)
menubar.refresh(scr)
-- Add to each category the name of its key in all_categories
for k, v in pairs(menubar.menu_gen.all_categories) do
v.key = k
end
return common_args.w
end
function menubar.mt.__call(_, ...)
return menubar.get(...)
end
return setmetatable(menubar, menubar.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
Emberwalker/Observatory | Observatory.lua | 1 | 5236 | -----------------------------------------------------------------------------------------------
-- Client Lua Script for Observatory
-- Arkan 2014; MIT License.
-- Base file template provided by Gemini:Addon
-----------------------------------------------------------------------------------------------
require "GameLib"
local Observatory = Apollo.GetPackage("Gemini:Addon-1.1").tPackage:NewAddon("Observatory", false)
local RPCore = Apollo.GetPackage("RPCore").tPackage
local Utils = Apollo.GetPackage("Arkan:Utils-1.0").tPackage
-----------------------------------------------------------------------------------------------
-- Constants
-----------------------------------------------------------------------------------------------
local MAJOR, MINOR = "Observatory", 1
local RENDER_TRAITS = { -- f = field, hr = human-readable
{f = "title", hr = "Full name/title"},
{f = "shortdesc", hr = "Description"},
{f = "bio", hr = "Biography"},
{f = "rpstate", hr = "RP status"}
}
-----------------------------------------------------------------------------------------------
-- Initialisers
-----------------------------------------------------------------------------------------------
-- Called at init
function Observatory:OnInitialize()
-- TODO: Event registration, hooks, frames, load XML, etc.
RPCore:SetDebugLevel(3) -- Temporary, REMOVE ME
self:GenerateProfileMeta()
end
-- Called after player enters game world.
function Observatory:OnEnable()
-- TODO: Finalise init cycle.
Apollo.RegisterSlashCommand("obs", "OnObsCommand", self)
end
-----------------------------------------------------------------------------------------------
-- Setup agents
-----------------------------------------------------------------------------------------------
function Observatory:GenerateProfileMeta()
local player = GameLib.GetPlayerUnit()
self.playerProfile = { -- TODO: Save flags as well.
fullname = player:GetName(),
title = "",
shortdesc = "",
bio = ""
}
self:SyncProfileToRPC()
end
-----------------------------------------------------------------------------------------------
-- Handlers
-----------------------------------------------------------------------------------------------
function Observatory:OnObsCommand(...)
local exp = Utils.Explode(" ", arg[2])
if exp[1] and exp[1] == "set" then
self:OnObsSetCommand(exp)
elseif exp[1] and exp[1] == "get" then
self:OnObsGetCommand(exp)
elseif exp[1] and exp[1] == "help" then
Utils.Log(MAJOR, "Observatory - RP profile manager/viewer.")
Utils.Log(MAJOR, "/obs get [name] -- Get a summary of PC by name.")
Utils.Log(MAJOR, "/obs set [var] [...] -- Set a variable. Valid vars:")
Utils.Log(MAJOR, "fullname, title, shortdesc, bio")
else
Utils.Log(MAJOR, "No subcommand provided. Try /obs help")
end
end
function Observatory:OnObsSetCommand(tExploded)
local var = tExploded[2]
local data = table.concat(tExploded, " ", 3)
if var == nil then
Utils.Log(MAJOR, "No variable specified. See /obs help")
return
end
if not self:IsValidTrait(var) then
Utils.Log(MAJOR, "Invalid variable, see /obs help: "..var)
return
end
if data == nil then
Utils.Log(MAJOR, "Something went horribly wrong, data is nil.")
return
end
Utils.Log(MAJOR, "Updating "..var.." to: "..data)
self:SetTrait(var, data)
end
function Observatory:OnObsGetCommand(tExploded)
local name = tExploded[2]
if name == nil then
Utils.Log(MAJOR, "No name provided.")
return
end
for _, r in pairs(RENDER_TRAITS) do
local v = RPCore:GetTrait(name, r.f)
if v ~= nil then
Utils.Log(MAJOR, r.hr..": "..v)
end
end
end
-----------------------------------------------------------------------------------------------
-- Helpers
-----------------------------------------------------------------------------------------------
function Observatory:SyncProfileToRPC()
RPCore:SetLocalTrait(RPCore.Trait_Name, self.playerProfile.fullname)
RPCore:SetLocalTrait(RPCore.Trait_NameAndTitle, self.playerProfile.title)
--RPCore:SetLocalTrait(RPCore.Trait_RPState, self.playerProfile.rpstate) -- TODO: Find a better way to represent/do this.
RPCore:SetLocalTrait(RPCore.Trait_Description, self.playerProfile.shortdesc)
RPCore:SetLocalTrait(RPCore.Trait_Biography, self.playerProfile.bio)
end
function Observatory:SetTrait(sTrait, data)
if sTrait == "rpstate" then
Utils.Log(MAJOR, "Cannot set rpstate at this time. This will be fixed later in GUI form.") -- TODO: Find way to do this
return
end
self.playerProfile[sTrait] = data
self:SyncProfileToRPC()
end
function Observatory:IsValidTrait(sTrait)
for k, _ in pairs(self.playerProfile) do
if k == sTrait then return true end
end
return false
end
-----------------------------------------------------------------------------------------------
-- Persistence
-----------------------------------------------------------------------------------------------
function Observatory:OnSave(eLevel)
if eLevel ~= GameLib.CodeEnumAddonSaveLevel.Character then return nil end
return self.playerProfile
end
function Observatory:OnRestore(eLevel, tData)
if eLevel ~= GameLib.CodeEnumAddonSaveLevel.Character or not tData then return nil end
self.playerProfile = tData
self:SyncProfileToRPC()
end
| mit |
ak40u/OsEngine | project/OsEngine/bin/Debug/lua/socket.lua | 146 | 4061 | -----------------------------------------------------------------------------
-- LuaSocket helper module
-- Author: Diego Nehab
-- RCS ID: $Id: socket.lua,v 1.22 2005/11/22 08:33:29 diego Exp $
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local string = require("string")
local math = require("math")
local socket = require("socket.core")
module("socket")
-----------------------------------------------------------------------------
-- Exported auxiliar functions
-----------------------------------------------------------------------------
function connect(address, port, laddress, lport)
local sock, err = socket.tcp()
if not sock then return nil, err end
if laddress then
local res, err = sock:bind(laddress, lport, -1)
if not res then return nil, err end
end
local res, err = sock:connect(address, port)
if not res then return nil, err end
return sock
end
function bind(host, port, backlog)
local sock, err = socket.tcp()
if not sock then return nil, err end
sock:setoption("reuseaddr", true)
local res, err = sock:bind(host, port)
if not res then return nil, err end
res, err = sock:listen(backlog)
if not res then return nil, err end
return sock
end
try = newtry()
function choose(table)
return function(name, opt1, opt2)
if base.type(name) ~= "string" then
name, opt1, opt2 = "default", name, opt1
end
local f = table[name or "nil"]
if not f then base.error("unknown key (".. base.tostring(name) ..")", 3)
else return f(opt1, opt2) end
end
end
-----------------------------------------------------------------------------
-- Socket sources and sinks, conforming to LTN12
-----------------------------------------------------------------------------
-- create namespaces inside LuaSocket namespace
sourcet = {}
sinkt = {}
BLOCKSIZE = 2048
sinkt["close-when-done"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if not chunk then
sock:close()
return 1
else return sock:send(chunk) end
end
})
end
sinkt["keep-open"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if chunk then return sock:send(chunk)
else return 1 end
end
})
end
sinkt["default"] = sinkt["keep-open"]
sink = choose(sinkt)
sourcet["by-length"] = function(sock, length)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if length <= 0 then return nil end
local size = math.min(socket.BLOCKSIZE, length)
local chunk, err = sock:receive(size)
if err then return nil, err end
length = length - string.len(chunk)
return chunk
end
})
end
sourcet["until-closed"] = function(sock)
local done
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if done then return nil end
local chunk, err, partial = sock:receive(socket.BLOCKSIZE)
if not err then return chunk
elseif err == "closed" then
sock:close()
done = 1
return partial
else return nil, err end
end
})
end
sourcet["default"] = sourcet["until-closed"]
source = choose(sourcet)
| apache-2.0 |
MrCerealGuy/Stonecraft | games/stonecraft_game/mods/cottages/nodes_fences.lua | 1 | 4047 | -- 22.01.13 Changed texture to that of the wood from the minimal development game
local S = cottages.S
minetest.register_node("cottages:fence_small", {
description = S("Small fence"),
drawtype = "nodebox",
-- top, bottom, side1, side2, inner, outer
tiles = {"cottages_minimal_wood.png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2},
node_box = {
type = "fixed",
fixed = {
{ -0.45, -0.35, 0.46, 0.45, -0.20, 0.50},
{ -0.45, 0.00, 0.46, 0.45, 0.15, 0.50},
{ -0.45, 0.35, 0.46, 0.45, 0.50, 0.50},
{ -0.50, -0.50, 0.46, -0.45, 0.50, 0.50},
{ 0.45, -0.50, 0.46, 0.50, 0.50, 0.50},
},
},
selection_box = {
type = "fixed",
fixed = {
{ -0.50, -0.50, 0.4, 0.50, 0.50, 0.5},
},
},
is_ground_content = false,
})
minetest.register_node("cottages:fence_corner", {
description = S("Small fence corner"),
drawtype = "nodebox",
-- top, bottom, side1, side2, inner, outer
tiles = {"cottages_minimal_wood.png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2},
node_box = {
type = "fixed",
fixed = {
{ -0.45, -0.35, 0.46, 0.45, -0.20, 0.50},
{ -0.45, 0.00, 0.46, 0.45, 0.15, 0.50},
{ -0.45, 0.35, 0.46, 0.45, 0.50, 0.50},
{ -0.50, -0.50, 0.46, -0.45, 0.50, 0.50},
{ 0.45, -0.50, 0.46, 0.50, 0.50, 0.50},
{ 0.46, -0.35, -0.45, 0.50, -0.20, 0.45},
{ 0.46, 0.00, -0.45, 0.50, 0.15, 0.45},
{ 0.46, 0.35, -0.45, 0.50, 0.50, 0.45},
{ 0.46, -0.50, -0.50, 0.50, 0.50, -0.45},
{ 0.46, -0.50, 0.45, 0.50, 0.50, 0.50},
},
},
selection_box = {
type = "fixed",
fixed = {
{ -0.50, -0.50,-0.5, 0.50, 0.50, 0.5},
},
},
is_ground_content = false,
})
minetest.register_node("cottages:fence_end", {
description = S("Small fence end"),
drawtype = "nodebox",
-- top, bottom, side1, side2, inner, outer
tiles = {"cottages_minimal_wood.png"},
paramtype = "light",
paramtype2 = "facedir",
groups = {snappy=2,choppy=2,oddly_breakable_by_hand=2},
node_box = {
type = "fixed",
fixed = {
{ -0.45, -0.35, 0.46, 0.45, -0.20, 0.50},
{ -0.45, 0.00, 0.46, 0.45, 0.15, 0.50},
{ -0.45, 0.35, 0.46, 0.45, 0.50, 0.50},
{ -0.50, -0.50, 0.46, -0.45, 0.50, 0.50},
{ 0.45, -0.50, 0.46, 0.50, 0.50, 0.50},
{ 0.46, -0.35, -0.45, 0.50, -0.20, 0.45},
{ 0.46, 0.00, -0.45, 0.50, 0.15, 0.45},
{ 0.46, 0.35, -0.45, 0.50, 0.50, 0.45},
{ 0.46, -0.50, -0.50, 0.50, 0.50, -0.45},
{ 0.46, -0.50, 0.45, 0.50, 0.50, 0.50},
{ -0.50, -0.35, -0.45, -0.46, -0.20, 0.45},
{ -0.50, 0.00, -0.45, -0.46, 0.15, 0.45},
{ -0.50, 0.35, -0.45, -0.46, 0.50, 0.45},
{ -0.50, -0.50, -0.50, -0.46, 0.50, -0.45},
{ -0.50, -0.50, 0.45, -0.46, 0.50, 0.50},
},
},
selection_box = {
type = "fixed",
fixed = {
{ -0.50, -0.50,-0.5, 0.50, 0.50, 0.5},
},
},
is_ground_content = false,
})
minetest.register_craft({
output = "cottages:fence_small 3",
recipe = {
{cottages.craftitem_fence, cottages.craftitem_fence},
}
})
-- xfences can be configured to replace normal fences - which makes them uncraftable
if ( minetest.get_modpath("xfences") ~= nil ) then
minetest.register_craft({
output = "cottages:fence_small 3",
recipe = {
{"xfences:fence","xfences:fence" },
}
})
end
minetest.register_craft({
output = "cottages:fence_corner",
recipe = {
{"cottages:fence_small","cottages:fence_small" },
}
})
minetest.register_craft({
output = "cottages:fence_small 2",
recipe = {
{"cottages:fence_corner" },
}
})
minetest.register_craft({
output = "cottages:fence_end",
recipe = {
{"cottages:fence_small","cottages:fence_small", "cottages:fence_small" },
}
})
minetest.register_craft({
output = "cottages:fence_small 3",
recipe = {
{"cottages:fence_end" },
}
})
| gpl-3.0 |
devaloosh/VIPTEAM | plugins/onservice.lua | 2 | 1476 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Team name : ( 🌐 VIP_TEAM 🌐 )▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ File name : ( اسم الملف ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Guenat team: ( @VIP_TEAM1 ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄
—]]
do
-- Will leave the group if be added
local function run(msg, matches)
local bot_id = our_id
local receiver = get_receiver(msg)
if matches[1] == 'leave' and is_admin1(msg) then
chat_del_user("chat#id"..msg.to.id, 'user#id'..bot_id, ok_cb, false)
leave_channel(receiver, ok_cb, false)
elseif msg.service and msg.action.type == "chat_add_user" and msg.action.user.id == tonumber(bot_id) and not is_admin1(msg) then
send_large_msg(receiver, 'This is not one of my groups.', ok_cb, false)
chat_del_user(receiver, 'user#id'..bot_id, ok_cb, false)
leave_channel(receiver, ok_cb, false)
end
end
return {
patterns = {
"^[#!/](leave)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| agpl-3.0 |
salorium/awesome | lib/awful/util.lua | 3 | 17974 | ---------------------------------------------------------------------------
--- Utility module for awful
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008 Julien Danjou
-- @release @AWESOME_VERSION@
-- @module awful.util
---------------------------------------------------------------------------
-- Grab environment we need
local os = os
local io = io
local assert = assert
local load = loadstring or load -- luacheck: globals loadstring (compatibility with Lua 5.1)
local loadfile = loadfile
local debug = debug
local pairs = pairs
local ipairs = ipairs
local type = type
local rtable = table
local string = string
local lgi = require("lgi")
local grect = require("gears.geometry").rectangle
local Gio = require("lgi").Gio
local Pango = lgi.Pango
local capi =
{
awesome = awesome,
mouse = mouse
}
local gears_debug = require("gears.debug")
local floor = math.floor
local util = {}
util.table = {}
util.shell = os.getenv("SHELL") or "/bin/sh"
local displayed_deprecations = {}
--- Display a deprecation notice, but only once per traceback.
-- @param[opt] see The message to a new method / function to use.
function util.deprecate(see)
local tb = debug.traceback()
if displayed_deprecations[tb] then
return
end
displayed_deprecations[tb] = true
-- Get function name/desc from caller.
local info = debug.getinfo(2, "n")
local funcname = info.name or "?"
local msg = "awful: function " .. funcname .. " is deprecated"
if see then
if string.sub(see, 1, 3) == 'Use' then
msg = msg .. ". " .. see
else
msg = msg .. ", see " .. see
end
end
gears_debug.print_warning(msg .. ".\n" .. tb)
end
--- Create a class proxy with deprecation messages.
-- This is useful when a class has moved somewhere else.
-- @tparam table fallback The new class
-- @tparam string old_name The old class name
-- @tparam string new_name The new class name
-- @treturn table A proxy class.
function util.deprecate_class(fallback, old_name, new_name)
local message = old_name.." has been renamed to "..new_name
local function call(_,...)
util.deprecate(message)
return fallback(...)
end
local function index(_, k)
util.deprecate(message)
return fallback[k]
end
local function newindex(_, k, v)
util.deprecate(message)
fallback[k] = v
end
return setmetatable({}, {__call = call, __index = index, __newindex = newindex})
end
--- Get a valid color for Pango markup
-- @param color The color.
-- @tparam string fallback The color to return if the first is invalid. (default: black)
-- @treturn string color if it is valid, else fallback.
function util.ensure_pango_color(color, fallback)
color = tostring(color)
return Pango.Color.parse(Pango.Color(), color) and color or fallback or "black"
end
--- Make i cycle.
-- @param t A length. Must be greater than zero.
-- @param i An absolute index to fit into #t.
-- @return An integer in (1, t) or nil if t is less than or equal to zero.
function util.cycle(t, i)
if t < 1 then return end
i = i % t
if i == 0 then
i = t
end
return i
end
--- Create a directory
-- @param dir The directory.
-- @return mkdir return code
function util.mkdir(dir)
return os.execute("mkdir -p " .. dir)
end
--- Eval Lua code.
-- @return The return value of Lua code.
function util.eval(s)
return assert(load(s))()
end
local xml_entity_names = { ["'"] = "'", ["\""] = """, ["<"] = "<", [">"] = ">", ["&"] = "&" };
--- Escape a string from XML char.
-- Useful to set raw text in textbox.
-- @param text Text to escape.
-- @return Escape text.
function util.escape(text)
return text and text:gsub("['&<>\"]", xml_entity_names) or nil
end
local xml_entity_chars = { lt = "<", gt = ">", nbsp = " ", quot = "\"", apos = "'", ndash = "-", mdash = "-", amp = "&" };
--- Unescape a string from entities.
-- @param text Text to unescape.
-- @return Unescaped text.
function util.unescape(text)
return text and text:gsub("&(%a+);", xml_entity_chars) or nil
end
--- Check if a file is a Lua valid file.
-- This is done by loading the content and compiling it with loadfile().
-- @param path The file path.
-- @return A function if everything is alright, a string with the error
-- otherwise.
function util.checkfile(path)
local f, e = loadfile(path)
-- Return function if function, otherwise return error.
if f then return f end
return e
end
--- Try to restart awesome.
-- It checks if the configuration file is valid, and then restart if it's ok.
-- If it's not ok, the error will be returned.
-- @return Never return if awesome restart, or return a string error.
function util.restart()
local c = util.checkfile(capi.awesome.conffile)
if type(c) ~= "function" then
return c
end
capi.awesome.restart()
end
--- Get the config home according to the XDG basedir specification.
-- @return the config home (XDG_CONFIG_HOME) with a slash at the end.
function util.get_xdg_config_home()
return (os.getenv("XDG_CONFIG_HOME") or os.getenv("HOME") .. "/.config") .. "/"
end
--- Get the cache home according to the XDG basedir specification.
-- @return the cache home (XDG_CACHE_HOME) with a slash at the end.
function util.get_xdg_cache_home()
return (os.getenv("XDG_CACHE_HOME") or os.getenv("HOME") .. "/.cache") .. "/"
end
--- Get the path to the user's config dir.
-- This is the directory containing the configuration file ("rc.lua").
-- @return A string with the requested path with a slash at the end.
function util.get_configuration_dir()
return capi.awesome.conffile:match(".*/") or "./"
end
--- Get the path to a directory that should be used for caching data.
-- @return A string with the requested path with a slash at the end.
function util.get_cache_dir()
return util.get_xdg_cache_home() .. "awesome/"
end
--- Get the path to the directory where themes are installed.
-- @return A string with the requested path with a slash at the end.
function util.get_themes_dir()
return "@AWESOME_THEMES_PATH@" .. "/"
end
--- Get the path to the directory where our icons are installed.
-- @return A string with the requested path with a slash at the end.
function util.get_awesome_icon_dir()
return "@AWESOME_ICON_PATH@" .. "/"
end
--- Get the user's config or cache dir.
-- It first checks XDG_CONFIG_HOME / XDG_CACHE_HOME, but then goes with the
-- default paths.
-- @param d The directory to get (either "config" or "cache").
-- @return A string containing the requested path.
function util.getdir(d)
if d == "config" then
-- No idea why this is what is returned, I recommend everyone to use
-- get_configuration_dir() instead
return util.get_xdg_config_home() .. "awesome/"
elseif d == "cache" then
return util.get_cache_dir()
end
end
--- Search for an icon and return the full path.
-- It searches for the icon path under the given directories with respect to the
-- given extensions for the icon filename.
-- @param iconname The name of the icon to search for.
-- @param exts Table of image extensions allowed, otherwise { 'png', gif' }
-- @param dirs Table of dirs to search, otherwise { '/usr/share/pixmaps/' }
-- @tparam[opt] string size The size. If this is specified, subdirectories `x`
-- of the dirs are searched first.
function util.geticonpath(iconname, exts, dirs, size)
exts = exts or { 'png', 'gif' }
dirs = dirs or { '/usr/share/pixmaps/', '/usr/share/icons/hicolor/' }
local icontypes = { 'apps', 'actions', 'categories', 'emblems',
'mimetypes', 'status', 'devices', 'extras', 'places', 'stock' }
for _, d in pairs(dirs) do
local icon
for _, e in pairs(exts) do
icon = d .. iconname .. '.' .. e
if util.file_readable(icon) then
return icon
end
if size then
for _, t in pairs(icontypes) do
icon = string.format("%s%ux%u/%s/%s.%s", d, size, size, t, iconname, e)
if util.file_readable(icon) then
return icon
end
end
end
end
end
end
--- Check if a file exists, is not readable and not a directory.
-- @param filename The file path.
-- @return True if file exists and is readable.
function util.file_readable(filename)
local file = io.open(filename)
if file then
local _, _, code = file:read(1)
io.close(file)
if code == 21 then
-- "Is a directory".
return false
end
return true
end
return false
end
--- Check if a path exists, is readable and is a directory.
-- @tparam string path The directory path.
-- @treturn boolean True if dir exists and is readable.
function util.dir_readable(path)
local gfile = Gio.File.new_for_path(path)
local gfileinfo = gfile:query_info("standard::type,access::can-read",
Gio.FileQueryInfoFlags.NONE)
return gfileinfo and gfileinfo:get_file_type() == "DIRECTORY" and
gfileinfo:get_attribute_boolean("access::can-read")
end
--- Check if a path is a directory.
-- @tparam string path
-- @treturn bool True if path exists and is a directory.
function util.is_dir(path)
return Gio.File.new_for_path(path):query_file_type({}) == "DIRECTORY"
end
local function subset_mask_apply(mask, set)
local ret = {}
for i = 1, #set do
if mask[i] then
rtable.insert(ret, set[i])
end
end
return ret
end
local function subset_next(mask)
local i = 1
while i <= #mask and mask[i] do
mask[i] = false
i = i + 1
end
if i <= #mask then
mask[i] = 1
return true
end
return false
end
--- Return all subsets of a specific set.
-- This function, giving a set, will return all subset it.
-- For example, if we consider a set with value { 10, 15, 34 },
-- it will return a table containing 2^n set:
-- { }, { 10 }, { 15 }, { 34 }, { 10, 15 }, { 10, 34 }, etc.
-- @param set A set.
-- @return A table with all subset.
function util.subsets(set)
local mask = {}
local ret = {}
for i = 1, #set do mask[i] = false end
-- Insert the empty one
rtable.insert(ret, {})
while subset_next(mask) do
rtable.insert(ret, subset_mask_apply(mask, set))
end
return ret
end
--- Get the nearest rectangle in the given direction. Every rectangle is specified as a table
-- with 'x', 'y', 'width', 'height' keys, the same as client or screen geometries.
-- @deprecated awful.util.get_rectangle_in_direction
-- @param dir The direction, can be either "up", "down", "left" or "right".
-- @param recttbl A table of rectangle specifications.
-- @param cur The current rectangle.
-- @return The index for the rectangle in recttbl closer to cur in the given direction. nil if none found.
-- @see gears.geometry
function util.get_rectangle_in_direction(dir, recttbl, cur)
util.deprecate("gears.geometry.rectangle.get_in_direction")
return grect.get_in_direction(dir, recttbl, cur)
end
--- Join all tables given as parameters.
-- This will iterate all tables and insert all their keys into a new table.
-- @param args A list of tables to join
-- @return A new table containing all keys from the arguments.
function util.table.join(...)
local ret = {}
for _, t in pairs({...}) do
if t then
for k, v in pairs(t) do
if type(k) == "number" then
rtable.insert(ret, v)
else
ret[k] = v
end
end
end
end
return ret
end
--- Override elements in the first table by the one in the second.
--
-- Note that this method doesn't copy entries found in `__index`.
-- @tparam table t the table to be overriden
-- @tparam table set the table used to override members of `t`
-- @tparam[opt=false] boolean raw Use rawset (avoid the metatable)
-- @treturn table t (for convenience)
function util.table.crush(t, set, raw)
if raw then
for k, v in pairs(set) do
rawset(t, k, v)
end
else
for k, v in pairs(set) do
t[k] = v
end
end
return t
end
--- Pack all elements with an integer key into a new table
-- While both lua and luajit implement __len over sparse
-- table, the standard define it as an implementation
-- detail.
--
-- This function remove any non numeric keys from the value set
--
-- @tparam table t A potentially sparse table
-- @treturn table A packed table with all numeric keys
function util.table.from_sparse(t)
local keys= {}
for k in pairs(t) do
if type(k) == "number" then
keys[#keys+1] = k
end
end
table.sort(keys)
local ret = {}
for _,v in ipairs(keys) do
ret[#ret+1] = t[v]
end
return ret
end
--- Check if a table has an item and return its key.
-- @param t The table.
-- @param item The item to look for in values of the table.
-- @return The key were the item is found, or nil if not found.
function util.table.hasitem(t, item)
for k, v in pairs(t) do
if v == item then
return k
end
end
end
--- Split a string into multiple lines
-- @param text String to wrap.
-- @param width Maximum length of each line. Default: 72.
-- @param indent Number of spaces added before each wrapped line. Default: 0.
-- @return The string with lines wrapped to width.
function util.linewrap(text, width, indent)
text = text or ""
width = width or 72
indent = indent or 0
local pos = 1
return text:gsub("(%s+)()(%S+)()",
function(_, st, word, fi)
if fi - pos > width then
pos = st
return "\n" .. string.rep(" ", indent) .. word
end
end)
end
--- Count number of lines in a string
-- @tparam string text Input string.
-- @treturn int Number of lines.
function util.linecount(text)
return select(2, text:gsub('\n', '\n')) + 1
end
--- Get a sorted table with all integer keys from a table
-- @param t the table for which the keys to get
-- @return A table with keys
function util.table.keys(t)
local keys = { }
for k, _ in pairs(t) do
rtable.insert(keys, k)
end
rtable.sort(keys, function (a, b)
return type(a) == type(b) and a < b or false
end)
return keys
end
--- Filter a tables keys for certain content types
-- @param t The table to retrieve the keys for
-- @param ... the types to look for
-- @return A filtered table with keys
function util.table.keys_filter(t, ...)
local keys = util.table.keys(t)
local keys_filtered = { }
for _, k in pairs(keys) do
for _, et in pairs({...}) do
if type(t[k]) == et then
rtable.insert(keys_filtered, k)
break
end
end
end
return keys_filtered
end
--- Reverse a table
-- @param t the table to reverse
-- @return the reversed table
function util.table.reverse(t)
local tr = { }
-- reverse all elements with integer keys
for _, v in ipairs(t) do
rtable.insert(tr, 1, v)
end
-- add the remaining elements
for k, v in pairs(t) do
if type(k) ~= "number" then
tr[k] = v
end
end
return tr
end
--- Clone a table
-- @param t the table to clone
-- @param deep Create a deep clone? (default: true)
-- @return a clone of t
function util.table.clone(t, deep)
deep = deep == nil and true or deep
local c = { }
for k, v in pairs(t) do
if deep and type(v) == "table" then
c[k] = util.table.clone(v)
else
c[k] = v
end
end
return c
end
---
-- Returns an iterator to cycle through, starting from the first element or the
-- given index, all elements of a table that match a given criteria.
--
-- @param t the table to iterate
-- @param filter a function that returns true to indicate a positive match
-- @param start what index to start iterating from. Default is 1 (=> start of
-- the table)
function util.table.iterate(t, filter, start)
local count = 0
local index = start or 1
local length = #t
return function ()
while count < length do
local item = t[index]
index = util.cycle(#t, index + 1)
count = count + 1
if filter(item) then return item end
end
end
end
--- Merge items from the one table to another one
-- @tparam table t the container table
-- @tparam table set the mixin table
-- @treturn table Return `t` for convenience
function util.table.merge(t, set)
for _, v in ipairs(set) do
table.insert(t, v)
end
return t
end
-- Escape all special pattern-matching characters so that lua interprets them
-- literally instead of as a character class.
-- Source: http://stackoverflow.com/a/20778724/15690
function util.quote_pattern(s)
-- All special characters escaped in a string: %%, %^, %$, ...
local patternchars = '['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..']'
return string.gsub(s, patternchars, "%%%1")
end
-- Generate a pattern matching expression that ignores case.
-- @param s Original pattern matching expression.
function util.query_to_pattern(q)
local s = util.quote_pattern(q)
-- Poor man's case-insensitive character matching.
s = string.gsub(s, "%a",
function (c)
return string.format("[%s%s]", string.lower(c),
string.upper(c))
end)
return s
end
--- Round a number to an integer.
-- @tparam number x
-- @treturn integer
function util.round(x)
return floor(x + 0.5)
end
return util
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
MrCerealGuy/Stonecraft | games/stonecraft_game/mods/farming/utensils.lua | 1 | 3505 |
local S = farming.intllib
-- wooden bowl
minetest.register_craftitem("farming:bowl", {
description = S("Wooden Bowl"),
inventory_image = "farming_bowl.png",
groups = {food_bowl = 1, flammable = 2}
})
minetest.register_craft({
output = "farming:bowl 4",
recipe = {
{"group:wood", "", "group:wood"},
{"", "group:wood", ""}
}
})
minetest.register_craft({
type = "fuel",
recipe = "farming:bowl",
burntime = 10,
})
-- saucepan
minetest.register_craftitem("farming:saucepan", {
description = S("Saucepan"),
inventory_image = "farming_saucepan.png",
groups = {food_saucepan = 1, flammable = 2}
})
minetest.register_craft({
output = "farming:saucepan",
recipe = {
{"default:steel_ingot", "", ""},
{"", "group:stick", ""}
}
})
-- cooking pot
minetest.register_craftitem("farming:pot", {
description = S("Cooking Pot"),
inventory_image = "farming_pot.png",
groups = {food_pot = 1, flammable = 2}
})
minetest.register_craft({
output = "farming:pot",
recipe = {
{"group:stick", "default:steel_ingot", "default:steel_ingot"},
{"", "default:steel_ingot", "default:steel_ingot"}
}
})
-- baking tray
minetest.register_craftitem("farming:baking_tray", {
description = S("Baking Tray"),
inventory_image = "farming_baking_tray.png",
groups = {food_baking_tray = 1, flammable = 2}
})
minetest.register_craft({
output = "farming:baking_tray",
recipe = {
{"default:clay_brick", "default:clay_brick", "default:clay_brick"},
{"default:clay_brick", "", "default:clay_brick"},
{"default:clay_brick", "default:clay_brick", "default:clay_brick"}
}
})
-- skillet
minetest.register_craftitem("farming:skillet", {
description = S("Skillet"),
inventory_image = "farming_skillet.png",
groups = {food_skillet = 1, flammable = 2}
})
minetest.register_craft({
output = "farming:skillet",
recipe = {
{"default:steel_ingot", "", ""},
{"", "default:steel_ingot", ""},
{"", "", "group:stick"}
}
})
-- mortar and pestle
minetest.register_craftitem("farming:mortar_pestle", {
description = S("Mortar and Pestle"),
inventory_image = "farming_mortar_pestle.png",
groups = {food_mortar_pestle = 1, flammable = 2}
})
minetest.register_craft({
output = "farming:mortar_pestle",
recipe = {
{"default:stone", "group:stick", "default:stone"},
{"", "default:stone", ""}
}
})
-- cutting board
minetest.register_craftitem("farming:cutting_board", {
description = S("Cutting Board"),
inventory_image = "farming_cutting_board.png",
groups = {food_cutting_board = 1, flammable = 2}
})
minetest.register_craft({
output = "farming:cutting_board",
recipe = {
{"default:steel_ingot", "", ""},
{"", "group:stick", ""},
{"", "", "group:wood"}
}
})
-- juicer
minetest.register_craftitem("farming:juicer", {
description = S("Juicer"),
inventory_image = "farming_juicer.png",
groups = {food_juicer = 1, flammable = 2}
})
minetest.register_craft({
output = "farming:juicer",
recipe = {
{"", "default:stone", ""},
{"default:stone", "", "default:stone"}
}
})
-- glass mixing bowl
minetest.register_craftitem("farming:mixing_bowl", {
description = S("Glass Mixing Bowl"),
inventory_image = "farming_mixing_bowl.png",
groups = {food_mixing_bowl = 1, flammable = 2}
})
minetest.register_craft({
output = "farming:mixing_bowl",
recipe = {
{"default:glass", "group:stick", "default:glass"},
{"", "default:glass", ""}
}
})
minetest.register_craft( {
type = "shapeless",
output = "vessels:glass_fragments",
recipe = {
"farming:mixing_bowl"
}
})
| gpl-3.0 |
xing634325131/Luci-0.11.1 | applications/luci-statistics/luasrc/statistics/rrdtool/definitions/cpu.lua | 76 | 1096 | --[[
Luci statistics - cpu plugin diagram definition
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
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: cpu.lua 2274 2008-06-03 23:15:16Z jow $
]]--
module("luci.statistics.rrdtool.definitions.cpu",package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
return {
title = "%H: Processor usage on core #%pi",
y_min = "0",
vlabel = "Percent",
number_format = "%5.1lf%%",
data = {
instances = {
cpu = { "idle", "user", "system", "nice" }
},
options = {
cpu_idle = { color = "ffffff" },
cpu_nice = { color = "00e000" },
cpu_user = { color = "0000ff" },
cpu_wait = { color = "ffb000" },
cpu_system = { color = "ff0000" },
cpu_softirq = { color = "ff00ff" },
cpu_interrupt = { color = "a000a0" },
cpu_steal = { color = "000000" }
}
}
}
end
| apache-2.0 |
zloster/FrameworkBenchmarks | frameworks/Lua/octopus/config.lua | 25 | 1033 | return {
extensions = {
{octopusExtensionsDir, "core"},
{octopusExtensionsDir, "baseline"},
{octopusExtensionsDir, "orm"},
{octopusExtensionsDir, "app"},
},
octopusExtensionsDir = octopusExtensionsDir,
octopusHostDir = octopusHostDir,
port = 8080,
securePort = 38080,
luaCodeCache = "on",
serverName = "tfb-server",
errorLog = "error_log logs/error.log;",
accessLog = "access_log logs/access.log;",
includeDrop = [[#include drop.conf;]],
maxBodySize = "50k",
minifyJavaScript = false,
minifyCommand = [[java -jar ../yuicompressor-2.4.8.jar %s -o %s]],
databaseConnection = {
rdbms = "mysql",
host = "DBHOSTNAME",
port = 3306,
database = "hello_world",
user = "benchmarkdbuser",
password = "benchmarkdbpass",
compact = false
},
globalParameters = {
octopusHostDir = octopusHostDir,
sourceCtxPath = "",
requireSecurity = false,
sessionTimeout = 3600,
usePreparedStatement = false,
},
}
| bsd-3-clause |
MrCerealGuy/Stonecraft | games/stonecraft_game/mods/default/furnace.lua | 1 | 10735 | -- default/furnace.lua
-- support for MT game translation.
local S = default.get_translator
--
-- Formspecs
--
function default.get_furnace_active_formspec(fuel_percent, item_percent)
return "size[8,8.5]"..
"list[context;src;2.75,0.5;1,1;]"..
"list[context;fuel;2.75,2.5;1,1;]"..
"image[2.75,1.5;1,1;default_furnace_fire_bg.png^[lowpart:"..
(fuel_percent)..":default_furnace_fire_fg.png]"..
"image[3.75,1.5;1,1;gui_furnace_arrow_bg.png^[lowpart:"..
(item_percent)..":gui_furnace_arrow_fg.png^[transformR270]"..
"list[context;dst;4.75,0.96;2,2;]"..
"list[current_player;main;0,4.25;8,1;]"..
"list[current_player;main;0,5.5;8,3;8]"..
"listring[context;dst]"..
"listring[current_player;main]"..
"listring[context;src]"..
"listring[current_player;main]"..
"listring[context;fuel]"..
"listring[current_player;main]"..
default.get_hotbar_bg(0, 4.25)
end
function default.get_furnace_inactive_formspec()
return "size[8,8.5]"..
"list[context;src;2.75,0.5;1,1;]"..
"list[context;fuel;2.75,2.5;1,1;]"..
"image[2.75,1.5;1,1;default_furnace_fire_bg.png]"..
"image[3.75,1.5;1,1;gui_furnace_arrow_bg.png^[transformR270]"..
"list[context;dst;4.75,0.96;2,2;]"..
"list[current_player;main;0,4.25;8,1;]"..
"list[current_player;main;0,5.5;8,3;8]"..
"listring[context;dst]"..
"listring[current_player;main]"..
"listring[context;src]"..
"listring[current_player;main]"..
"listring[context;fuel]"..
"listring[current_player;main]"..
default.get_hotbar_bg(0, 4.25)
end
--
-- Node callback functions that are the same for active and inactive furnace
--
local function can_dig(pos, player)
local meta = minetest.get_meta(pos);
local inv = meta:get_inventory()
return inv:is_empty("fuel") and inv:is_empty("dst") and inv:is_empty("src")
end
local function allow_metadata_inventory_put(pos, listname, index, stack, player)
if minetest.is_protected(pos, player:get_player_name()) then
return 0
end
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
if listname == "fuel" then
if minetest.get_craft_result({method="fuel", width=1, items={stack}}).time ~= 0 then
if inv:is_empty("src") then
meta:set_string("infotext", S("Furnace is empty"))
end
return stack:get_count()
else
return 0
end
elseif listname == "src" then
return stack:get_count()
elseif listname == "dst" then
return 0
end
end
local function allow_metadata_inventory_move(pos, from_list, from_index, to_list, to_index, count, player)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
local stack = inv:get_stack(from_list, from_index)
return allow_metadata_inventory_put(pos, to_list, to_index, stack, player)
end
local function allow_metadata_inventory_take(pos, listname, index, stack, player)
if minetest.is_protected(pos, player:get_player_name()) then
return 0
end
return stack:get_count()
end
local function swap_node(pos, name)
local node = minetest.get_node(pos)
if node.name == name then
return
end
node.name = name
minetest.swap_node(pos, node)
end
local function furnace_node_timer(pos, elapsed)
--
-- Initialize metadata
--
local meta = minetest.get_meta(pos)
local fuel_time = meta:get_float("fuel_time") or 0
local src_time = meta:get_float("src_time") or 0
local fuel_totaltime = meta:get_float("fuel_totaltime") or 0
local inv = meta:get_inventory()
local srclist, fuellist
local dst_full = false
local timer_elapsed = meta:get_int("timer_elapsed") or 0
meta:set_int("timer_elapsed", timer_elapsed + 1)
local cookable, cooked
local fuel
local update = true
while elapsed > 0 and update do
update = false
srclist = inv:get_list("src")
fuellist = inv:get_list("fuel")
--
-- Cooking
--
-- Check if we have cookable content
local aftercooked
cooked, aftercooked = minetest.get_craft_result({method = "cooking", width = 1, items = srclist})
cookable = cooked.time ~= 0
local el = math.min(elapsed, fuel_totaltime - fuel_time)
if cookable then -- fuel lasts long enough, adjust el to cooking duration
el = math.min(el, cooked.time - src_time)
end
-- Check if we have enough fuel to burn
if fuel_time < fuel_totaltime then
-- The furnace is currently active and has enough fuel
fuel_time = fuel_time + el
-- If there is a cookable item then check if it is ready yet
if cookable then
src_time = src_time + el
if src_time >= cooked.time then
-- Place result in dst list if possible
if inv:room_for_item("dst", cooked.item) then
inv:add_item("dst", cooked.item)
inv:set_stack("src", 1, aftercooked.items[1])
src_time = src_time - cooked.time
update = true
else
dst_full = true
end
-- Play cooling sound
minetest.sound_play("default_cool_lava",
{pos = pos, max_hear_distance = 16, gain = 0.1}, true)
else
-- Item could not be cooked: probably missing fuel
update = true
end
end
else
-- Furnace ran out of fuel
if cookable then
-- We need to get new fuel
local afterfuel
fuel, afterfuel = minetest.get_craft_result({method = "fuel", width = 1, items = fuellist})
if fuel.time == 0 then
-- No valid fuel in fuel list
fuel_totaltime = 0
src_time = 0
else
-- Take fuel from fuel list
inv:set_stack("fuel", 1, afterfuel.items[1])
-- Put replacements in dst list or drop them on the furnace.
local replacements = fuel.replacements
if replacements[1] then
local leftover = inv:add_item("dst", replacements[1])
if not leftover:is_empty() then
local above = vector.new(pos.x, pos.y + 1, pos.z)
local drop_pos = minetest.find_node_near(above, 1, {"air"}) or above
minetest.item_drop(replacements[1], nil, drop_pos)
end
end
update = true
fuel_totaltime = fuel.time + (fuel_totaltime - fuel_time)
end
else
-- We don't need to get new fuel since there is no cookable item
fuel_totaltime = 0
src_time = 0
end
fuel_time = 0
end
elapsed = elapsed - el
end
if fuel and fuel_totaltime > fuel.time then
fuel_totaltime = fuel.time
end
if srclist and srclist[1]:is_empty() then
src_time = 0
end
--
-- Update formspec, infotext and node
--
local formspec
local item_state
local item_percent = 0
if cookable then
item_percent = math.floor(src_time / cooked.time * 100)
if dst_full then
item_state = S("100% (output full)")
else
item_state = S("@1%", item_percent)
end
else
if srclist and not srclist[1]:is_empty() then
item_state = S("Not cookable")
else
item_state = S("Empty")
end
end
local fuel_state = S("Empty")
local active = false
local result = false
if fuel_totaltime ~= 0 then
active = true
local fuel_percent = 100 - math.floor(fuel_time / fuel_totaltime * 100)
fuel_state = S("@1%", fuel_percent)
formspec = default.get_furnace_active_formspec(fuel_percent, item_percent)
swap_node(pos, "default:furnace_active")
-- make sure timer restarts automatically
result = true
-- Play sound every 5 seconds while the furnace is active
if timer_elapsed == 0 or (timer_elapsed+1) % 5 == 0 then
minetest.sound_play("default_furnace_active",
{pos = pos, max_hear_distance = 16, gain = 0.5}, true)
end
else
if fuellist and not fuellist[1]:is_empty() then
fuel_state = S("@1%", 0)
end
formspec = default.get_furnace_inactive_formspec()
swap_node(pos, "default:furnace")
-- stop timer on the inactive furnace
minetest.get_node_timer(pos):stop()
meta:set_int("timer_elapsed", 0)
end
local infotext
if active then
infotext = S("Furnace active")
else
infotext = S("Furnace inactive")
end
infotext = infotext .. "\n" .. S("(Item: @1; Fuel: @2)", item_state, fuel_state)
--
-- Set meta values
--
meta:set_float("fuel_totaltime", fuel_totaltime)
meta:set_float("fuel_time", fuel_time)
meta:set_float("src_time", src_time)
meta:set_string("formspec", formspec)
meta:set_string("infotext", infotext)
return result
end
--
-- Node definitions
--
minetest.register_node("default:furnace", {
description = S("Furnace"),
tiles = {
"default_furnace_top.png", "default_furnace_bottom.png",
"default_furnace_side.png", "default_furnace_side.png",
"default_furnace_side.png", "default_furnace_front.png"
},
paramtype2 = "facedir",
groups = {cracky=2},
legacy_facedir_simple = true,
is_ground_content = false,
sounds = default.node_sound_stone_defaults(),
can_dig = can_dig,
on_timer = furnace_node_timer,
on_construct = function(pos)
local meta = minetest.get_meta(pos)
local inv = meta:get_inventory()
inv:set_size('src', 1)
inv:set_size('fuel', 1)
inv:set_size('dst', 4)
furnace_node_timer(pos, 0)
end,
on_metadata_inventory_move = function(pos)
minetest.get_node_timer(pos):start(1.0)
end,
on_metadata_inventory_put = function(pos)
-- start timer function, it will sort out whether furnace can burn or not.
minetest.get_node_timer(pos):start(1.0)
end,
on_metadata_inventory_take = function(pos)
-- check whether the furnace is empty or not.
minetest.get_node_timer(pos):start(1.0)
end,
on_blast = function(pos)
local drops = {}
default.get_inventory_drops(pos, "src", drops)
default.get_inventory_drops(pos, "fuel", drops)
default.get_inventory_drops(pos, "dst", drops)
drops[#drops+1] = "default:furnace"
minetest.remove_node(pos)
return drops
end,
allow_metadata_inventory_put = allow_metadata_inventory_put,
allow_metadata_inventory_move = allow_metadata_inventory_move,
allow_metadata_inventory_take = allow_metadata_inventory_take,
})
minetest.register_node("default:furnace_active", {
description = S("Furnace"),
tiles = {
"default_furnace_top.png", "default_furnace_bottom.png",
"default_furnace_side.png", "default_furnace_side.png",
"default_furnace_side.png",
{
image = "default_furnace_front_active.png",
backface_culling = false,
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1.5
},
}
},
paramtype2 = "facedir",
light_source = 8,
drop = "default:furnace",
groups = {cracky=2, not_in_creative_inventory=1},
legacy_facedir_simple = true,
is_ground_content = false,
sounds = default.node_sound_stone_defaults(),
on_timer = furnace_node_timer,
can_dig = can_dig,
allow_metadata_inventory_put = allow_metadata_inventory_put,
allow_metadata_inventory_move = allow_metadata_inventory_move,
allow_metadata_inventory_take = allow_metadata_inventory_take,
})
minetest.register_craft({
output = "default:furnace",
recipe = {
{"group:stone", "group:stone", "group:stone"},
{"group:stone", "", "group:stone"},
{"group:stone", "group:stone", "group:stone"},
}
})
| gpl-3.0 |
xing634325131/Luci-0.11.1 | modules/admin-full/luasrc/model/cbi/admin_network/vlan.lua | 21 | 8152 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.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
]]--
m = Map("network", translate("Switch"), translate("The network ports on this device can be combined to several <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s in which computers can communicate directly with each other. <abbr title=\"Virtual Local Area Network\">VLAN</abbr>s are often used to separate different network segments. Often there is by default one Uplink port for a connection to the next greater network like the internet and other ports for a local network."))
local switches = { }
m.uci:foreach("network", "switch",
function(x)
local sid = x['.name']
local switch_name = x.name or sid
local has_vlan = nil
local has_learn = nil
local has_vlan4k = nil
local has_jumbo3 = nil
local min_vid = 0
local max_vid = 16
local num_vlans = 16
local num_ports = 6
local cpu_port = 5
local switch_title
local enable_vlan4k = false
-- Parse some common switch properties from swconfig help output.
local swc = io.popen("swconfig dev %q help 2>/dev/null" % switch_name)
if swc then
local is_port_attr = false
local is_vlan_attr = false
while true do
local line = swc:read("*l")
if not line then break end
if line:match("^%s+%-%-vlan") then
is_vlan_attr = true
elseif line:match("^%s+%-%-port") then
is_vlan_attr = false
is_port_attr = true
elseif line:match("cpu @") then
switch_title = line:match("^switch%d: %w+%((.-)%)")
num_ports, cpu_port, num_vlans =
line:match("ports: (%d+) %(cpu @ (%d+)%), vlans: (%d+)")
num_ports = tonumber(num_ports) or 6
num_vlans = tonumber(num_vlans) or 16
cpu_port = tonumber(cpu_port) or 5
min_vid = 1
elseif line:match(": pvid") or line:match(": tag") or line:match(": vid") then
if is_vlan_attr then has_vlan4k = line:match(": (%w+)") end
elseif line:match(": enable_vlan4k") then
enable_vlan4k = true
elseif line:match(": enable_vlan") then
has_vlan = "enable_vlan"
elseif line:match(": enable_learning") then
has_learn = "enable_learning"
elseif line:match(": max_length") then
has_jumbo3 = "max_length"
end
end
swc:close()
end
-- Switch properties
s = m:section(NamedSection, x['.name'], "switch",
switch_title and translatef("Switch %q (%s)", switch_name, switch_title)
or translatef("Switch %q", switch_name))
s.addremove = false
if has_vlan then
s:option(Flag, has_vlan, translate("Enable VLAN functionality"))
end
if has_learn then
x = s:option(Flag, has_learn, translate("Enable learning and aging"))
x.default = x.enabled
end
if has_jumbo3 then
x = s:option(Flag, has_jumbo3, translate("Enable Jumbo Frame passthrough"))
x.enabled = "3"
x.rmempty = true
end
-- VLAN table
s = m:section(TypedSection, "switch_vlan",
switch_title and translatef("VLANs on %q (%s)", switch_name, switch_title)
or translatef("VLANs on %q", switch_name))
s.template = "cbi/tblsection"
s.addremove = true
s.anonymous = true
-- Filter by switch
s.filter = function(self, section)
local device = m:get(section, "device")
return (device and device == switch_name)
end
-- Override cfgsections callback to enforce row ordering by vlan id.
s.cfgsections = function(self)
local osections = TypedSection.cfgsections(self)
local sections = { }
local section
for _, section in luci.util.spairs(
osections,
function(a, b)
return (tonumber(m:get(osections[a], has_vlan4k or "vlan")) or 9999)
< (tonumber(m:get(osections[b], has_vlan4k or "vlan")) or 9999)
end
) do
sections[#sections+1] = section
end
return sections
end
-- When creating a new vlan, preset it with the highest found vid + 1.
s.create = function(self, section, origin)
-- Filter by switch
if m:get(origin, "device") ~= switch_name then
return
end
local sid = TypedSection.create(self, section)
local max_nr = 0
local max_id = 0
m.uci:foreach("network", "switch_vlan",
function(s)
if s.device == switch_name then
local nr = tonumber(s.vlan)
local id = has_vlan4k and tonumber(s[has_vlan4k])
if nr ~= nil and nr > max_nr then max_nr = nr end
if id ~= nil and id > max_id then max_id = id end
end
end)
m:set(sid, "device", switch_name)
m:set(sid, "vlan", max_nr + 1)
if has_vlan4k then
m:set(sid, has_vlan4k, max_id + 1)
end
return sid
end
local port_opts = { }
local untagged = { }
-- Parse current tagging state from the "ports" option.
local portvalue = function(self, section)
local pt
for pt in (m:get(section, "ports") or ""):gmatch("%w+") do
local pc, tu = pt:match("^(%d+)([tu]*)")
if pc == self.option then return (#tu > 0) and tu or "u" end
end
return ""
end
-- Validate port tagging. Ensure that a port is only untagged once,
-- bail out if not.
local portvalidate = function(self, value, section)
-- ensure that the ports appears untagged only once
if value == "u" then
if not untagged[self.option] then
untagged[self.option] = true
elseif min_vid > 0 or tonumber(self.option) ~= cpu_port then -- enable multiple untagged cpu ports due to weird broadcom default setup
return nil,
translatef("Port %d is untagged in multiple VLANs!", tonumber(self.option) + 1)
end
end
return value
end
local vid = s:option(Value, has_vlan4k or "vlan", "VLAN ID", "<div id='portstatus-%s'></div>" % switch_name)
local mx_vid = has_vlan4k and 4094 or (num_vlans - 1)
vid.rmempty = false
vid.forcewrite = true
vid.vlan_used = { }
vid.datatype = "and(uinteger,range("..min_vid..","..mx_vid.."))"
-- Validate user provided VLAN ID, make sure its within the bounds
-- allowed by the switch.
vid.validate = function(self, value, section)
local v = tonumber(value)
local m = has_vlan4k and 4094 or (num_vlans - 1)
if v ~= nil and v >= min_vid and v <= m then
if not self.vlan_used[v] then
self.vlan_used[v] = true
return value
else
return nil,
translatef("Invalid VLAN ID given! Only unique IDs are allowed")
end
else
return nil,
translatef("Invalid VLAN ID given! Only IDs between %d and %d are allowed.", min_vid, m)
end
end
-- When writing the "vid" or "vlan" option, serialize the port states
-- as well and write them as "ports" option to uci.
vid.write = function(self, section, value)
local o
local p = { }
for _, o in ipairs(port_opts) do
local v = o:formvalue(section)
if v == "t" then
p[#p+1] = o.option .. v
elseif v == "u" then
p[#p+1] = o.option
end
end
if enable_vlan4k then
m:set(sid, "enable_vlan4k", "1")
end
m:set(section, "ports", table.concat(p, " "))
return Value.write(self, section, value)
end
-- Fallback to "vlan" option if "vid" option is supported but unset.
vid.cfgvalue = function(self, section)
return m:get(section, has_vlan4k or "vlan")
or m:get(section, "vlan")
end
-- Build per-port off/untagged/tagged choice lists.
local pt
for pt = 0, num_ports - 1 do
local title
if pt == cpu_port then
title = translate("CPU")
else
title = translatef("Port %d", pt)
end
local po = s:option(ListValue, tostring(pt), title)
po:value("", translate("off"))
po:value("u", translate("untagged"))
po:value("t", translate("tagged"))
po.cfgvalue = portvalue
po.validate = portvalidate
po.write = function() end
port_opts[#port_opts+1] = po
end
switches[#switches+1] = switch_name
end
)
-- Switch status template
s = m:section(SimpleSection)
s.template = "admin_network/switch_status"
s.switches = switches
return m
| apache-2.0 |
LuaDist2/lua-rote | spec/boxshell_spec.lua | 3 | 1622 | -- This file is part of lua-rote, Lua binding to ROTE
-- Terminal Emulation library
-- Copyright (C) 2015 Boris Nagaev
-- See the LICENSE file for terms of use.
-- test RoteTerm:draw() and script demo/boxshell.lua
-- FIXME RoteTerm:draw() draws wrong things on Travis
-- https://travis-ci.org/starius/lua-rote/jobs/54479120#L1160
local function sleep()
local duration = os.getenv('TEST_SLEEP') or 5
os.execute('sleep ' .. duration)
end
describe("rote.RoteTerm.draw", function()
it("draws the terminal to the #curses window", function()
-- create file with secret text
local secret = 'secret'
local filename = os.tmpname()
local f = io.open(filename, 'w')
f:write(secret)
f:close()
-- create RoteTerm, run boxshell.lua in RoteTerm
local rote = assert(require "rote")
local rt = rote.RoteTerm(24, 80)
rt:forkPty('lua -lluacov demo/boxshell.lua vi')
sleep()
rt:update()
assert.truthy(rt:termText():match('Term In a Box'))
-- cell (0, 0) must have blue background
local attr = rt:cellAttr(0, 0)
local fg, bg = rote.fromAttr(attr)
assert.equal(rote.name2color.blue, bg)
-- open file
local cmd = ':e %s\n'
rt:write(cmd:format(filename))
sleep()
rt:update()
-- FIXME RoteTerm:draw() draws wrong things on Travis
--assert.truthy(rt:termText():match(secret))
-- quit
rt:write(':q\n')
sleep()
rt:update()
rt:forsakeChild()
-- cleanup
os.remove(filename)
end)
end)
| lgpl-2.1 |
T3hArco/skeyler-gamemodes | ssbase/entities/weapons/weapon_mac10/shared.lua | 1 | 1161 |
if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
end
if ( CLIENT ) then
SWEP.PrintName = "mac10"
SWEP.Author = "Counter-Strike"
SWEP.Slot = 2
SWEP.SlotPos = 0
SWEP.IconLetter = "l"
killicon.AddFont( "weapon_mac10", "CSKillIcons", SWEP.IconLetter, Color( 255, 80, 0, 255 ) )
end
SWEP.HoldType = "ar2"
SWEP.Base = "weapon_cs_base"
SWEP.Category = "Counter-Strike"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.ViewModel = "models/weapons/v_smg_mac10.mdl"
SWEP.WorldModel = "models/weapons/w_smg_mac10.mdl"
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Sound = Sound( "Weapon_mac10.Single" )
SWEP.Primary.Recoil = 0.7
SWEP.Primary.Damage = 30
SWEP.Primary.NumShots = 1
SWEP.Primary.Cone = 0.03
SWEP.Primary.ClipSize = 25
SWEP.Primary.Delay = 0.09
SWEP.Primary.DefaultClip = 75
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "smg1"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.IronSightsPos = Vector( 6.7, -3, 3 )
SWEP.IronSightsAng = Vector( 0, 5, 5 )
| bsd-3-clause |
kjoenth/naev | dat/factions/spawn/common.lua | 5 | 2958 |
scom = {}
-- @brief Calculates when next spawn should occur
scom.calcNextSpawn = function( cur, new, max )
if cur == 0 then return rnd.rnd(0, 10) end -- Kickstart spawning.
local stddelay = 10 -- seconds
local maxdelay = 60 -- seconds. No fleet can ever take more than this to show up.
local stdfleetsize = 1/4 -- The fraction of "max" that gets the full standard delay. Fleets bigger than this portion of max will have longer delays, fleets smaller, shorter.
local delayweight = 1. -- A scalar for tweaking the delay differences. A bigger number means bigger differences.
local percent = (cur + new) / max
local penaltyweight = 1. -- Further delays fleets that go over the presence limit.
if percent > 1. then
penaltyweight = 1. + 10. * (percent - 1.)
end
local fleetratio = (new/max)/stdfleetsize -- This turns into the base delay multiplier for the next fleet.
return math.min(stddelay * fleetratio * delayweight * penaltyweight, maxdelay)
end
--[[
@brief Creates the spawn table based on a weighted spawn function table.
@param weights Weighted spawn function table to use to generate the spawn table.
@return The matching spawn table.
--]]
scom.createSpawnTable = function( weights )
local spawn_table = {}
local max = 0
-- Create spawn table
for k,v in pairs(weights) do
max = max + v
spawn_table[ #spawn_table+1 ] = { chance = max, func = k }
end
-- Sanity check
if max == 0 then
error("No weight specified")
end
-- Normalize
for k,v in ipairs(spawn_table) do
v["chance"] = v["chance"] / max
end
-- Job done
return spawn_table
end
-- @brief Chooses what to spawn
scom.choose = function( stable )
local r = rnd.rnd()
for k,v in ipairs( stable ) do
if r < v["chance"] then
return v["func"]()
end
end
error("No spawn function found")
end
-- @brief Actually spawns the pilots
scom.spawn = function( pilots )
local spawned = {}
for k,v in ipairs(pilots) do
local p = pilot.add( v["pilot"] )
if #p == 0 then
error("No pilots added")
end
local presence = v["presence"] / #p
for _,vv in ipairs(p) do
spawned[ #spawned+1 ] = { pilot = vv, presence = presence }
end
end
return spawned
end
-- @brief adds a pilot to the table
scom.addPilot = function( pilots, name, presence )
pilots[ #pilots+1 ] = { pilot = name, presence = presence }
if pilots[ "__presence" ] then
pilots[ "__presence" ] = pilots[ "__presence" ] + presence
else
pilots[ "__presence" ] = presence
end
end
-- @brief Gets the presence value of a group of pilots
scom.presence = function( pilots )
if pilots[ "__presence" ] then
return pilots[ "__presence" ]
else
return 0
end
end
-- @brief Default decrease function
scom.decrease = function( cur, max, timer )
return timer
end
| gpl-3.0 |
shahabsaf1/copy | plugins/Add_Bot.lua | 29 | 1484 | --[[
Bot can join into a group by replying a message contain an invite link or by
typing !join [invite link].
URL.parse cannot parsing complicated message. So, this plugin only works for
single [invite link] in a post.
[invite link] may be preceeded but must not followed by another characters.
--]]
do
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
i = 0
for k,segment in pairs(parsed_path) do
i = i + 1
if segment == 'joinchat' then
invite_link = string.gsub(parsed_path[i+1], '[ %c].+$', '')
break
end
end
return invite_link
end
local function action_by_reply(extra, success, result)
local hash = parsed_url(result.text)
join = import_chat_link(hash, ok_cb, false)
end
function run(msg, matches)
if is_sudo(msg) then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
elseif matches[1] then
local hash = parsed_url(matches[1])
join = import_chat_link(hash, ok_cb, false)
end
end
end
return {
description = 'Invite the bot into a group chat via its invite link.',
usage = {
'!AddBot : Join a group by replying a message containing invite link.',
'!AddBot [invite_link] : Join into a group by providing their [invite_link].'
},
patterns = {
'^!AddBot$',
'^!AddBot (.*)$'
},
run = run
}
end
| gpl-2.0 |
HydraTeamBot/EchoSpamer | plugins/ingroup.lua | 371 | 44212 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
local user_info = redis:hgetall('user:'..group_owner)
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
if user_info.username then
return "Group onwer is @"..user_info.username.." ["..group_owner.."]"
else
return "Group owner is ["..group_owner..']'
end
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
kroepke/luna | luna-tests/src/test/resources/benchmarksgame/pidigits.lua-7.lua | 1 | 1784 | -- The Computer Language Benchmarks Game
-- http://benchmarksgame.alioth.debian.org/
-- contributed by Wim Couwenberg
--
-- requires LGMP "A GMP package for Lua 5.1"
--
-- 21 September 2008
local gmp, aux = {}, {}
require "c-gmp"(gmp, aux)
local add, mul, div = gmp.mpz_add, gmp.mpz_mul_ui, gmp.mpz_fdiv_q
local addmul, submul = gmp.mpz_addmul_ui, gmp.mpz_submul_ui
local init, get, set = gmp.mpz_init_set_d, gmp.mpz_get_d, gmp.mpz_set
--
-- Production:
--
-- [m11 m12] [m11 m12][k 4*k+2]
-- [ 0 m22] <-- [ 0 m22][0 2*k+1]
--
local function produce(m11, m12, m22, k)
local p = 2 * k + 1
mul(m12, p, m12)
addmul(m12, m11, 2 * p)
mul(m11, k, m11)
mul(m22, p, m22)
end
--
-- Extraction:
--
-- [m11 m12] [10 -10*d][m11 m12]
-- [ 0 m22] <-- [ 0 1 ][ 0 m22]
--
local function extract(m11, m12, m22, d)
submul(m12, m22, d)
mul(m11, 10, m11)
mul(m12, 10, m12)
end
--
-- Get integral part of p/q where
--
-- [p] [m11 m12][d]
-- [q] = [ 0 m22][1]
--
local function digit(m11, m12, m22, d, tmp)
set(tmp, m12)
addmul(tmp, m11, d)
div(tmp, m22, tmp)
return get(tmp)
end
-- Generate successive digits of PI.
local function pidigits(N)
local write = io.write
local m11, m12, m22, tmp = init(1), init(0), init(1), init(0)
local k, i = 1, 0
while i < N do
local d = digit(m11, m12, m22, 3, tmp)
if d == digit(m11, m12, m22, 4, tmp) then
write(d)
extract(m11, m12, m22, d)
i = i + 1; if i % 10 == 0 then write("\t:", i, "\n") end
else
produce(m11, m12, m22, k)
k = k + 1
end
end
if i % 10 ~= 0 then write(string.rep(" ", 10 - N % 10), "\t:", N, "\n") end
end
local N = tonumber(arg and arg[1]) or 27
pidigits(N)
| apache-2.0 |
salorium/awesome | lib/awful/mouse/resize.lua | 1 | 6641 | ---------------------------------------------------------------------------
--- An extandable mouse resizing handler.
--
-- This module offer a resizing and moving mechanism for drawable such as
-- clients and wiboxes.
--
-- @author Emmanuel Lepage Vallee <elv1313@gmail.com>
-- @copyright 2016 Emmanuel Lepage Vallee
-- @release @AWESOME_VERSION@
-- @submodule mouse
---------------------------------------------------------------------------
local aplace = require("awful.placement")
local capi = {mousegrabber = mousegrabber}
local beautiful = require("beautiful")
local module = {}
local mode = "live"
local req = "request::geometry"
local callbacks = {enter={}, move={}, leave={}}
local cursors = {
["mouse.resize"] = "fleur",
["mouse.move" ] = "cross"
}
--- The resize cursor name.
-- @beautiful beautiful.cursor_mouse_resize
-- @tparam[opt=fleur] string cursor
--- The move cursor name.
-- @beautiful beautiful.cursor_mouse_move
-- @tparam[opt=cross] string cursor
--- Set the resize mode.
-- The available modes are:
--
-- * **live**: Resize the layout everytime the mouse move
-- * **after**: Resize the layout only when the mouse is released
--
-- Some clients, such as XTerm, may lose information if resized too often.
--
-- @function awful.mouse.resize.set_mode
-- @tparam string m The mode
function module.set_mode(m)
assert(m == "live" or m == "after")
mode = m
end
--- Add a initialization callback.
-- This callback will be executed before the mouse grabbing start
-- @function awful.mouse.resize.add_enter_callback
-- @tparam function cb The callback (or nil)
-- @tparam[default=other] string context The callback context
function module.add_enter_callback(cb, context)
context = context or "other"
callbacks.enter[context] = callbacks.enter[context] or {}
table.insert(callbacks.enter[context], cb)
end
--- Add a "move" callback.
-- This callback is executed in "after" mode (see `set_mode`) instead of
-- applying the operation.
-- @function awful.mouse.resize.add_move_callback
-- @tparam function cb The callback (or nil)
-- @tparam[default=other] string context The callback context
function module.add_move_callback(cb, context)
context = context or "other"
callbacks.move[context] = callbacks.move[context] or {}
table.insert(callbacks.move[context], cb)
end
--- Add a "leave" callback
-- This callback is executed just before the `mousegrabber` stop
-- @function awful.mouse.resize.add_leave_callback
-- @tparam function cb The callback (or nil)
-- @tparam[default=other] string context The callback context
function module.add_leave_callback(cb, context)
context = context or "other"
callbacks.leave[context] = callbacks.leave[context] or {}
table.insert(callbacks.leave[context], cb)
end
-- Resize, the drawable.
--
-- Valid `args` are:
--
-- * *enter_callback*: A function called before the `mousegrabber` start
-- * *move_callback*: A function called when the mouse move
-- * *leave_callback*: A function called before the `mousegrabber` is released
-- * *mode*: The resize mode
--
-- @function awful.mouse.resize
-- @tparam client client A client
-- @tparam[default=mouse.resize] string context The resizing context
-- @tparam[opt={}] table args A set of `awful.placement` arguments
local function handler(_, client, context, args) --luacheck: no unused_args
args = args or {}
context = context or "mouse.resize"
local placement = args.placement
if type(placement) == "string" and aplace[placement] then
placement = aplace[placement]
end
-- Extend the table with the default arguments
args = setmetatable(
{
placement = placement or aplace.resize_to_mouse,
mode = args.mode or mode,
pretend = true,
},
{__index = args or {}}
)
local geo
for _, cb in ipairs(callbacks.enter[context] or {}) do
geo = cb(client, args)
if geo == false then
return false
end
end
if args.enter_callback then
geo = args.enter_callback(client, args)
if geo == false then
return false
end
end
geo = nil
-- Select the cursor
local tcontext = context:gsub('[.]', '_')
local cursor = beautiful["cursor_"..tcontext] or cursors[context] or "cross"
-- Execute the placement function and use request::geometry
capi.mousegrabber.run(function (_mouse)
if not client.valid then return end
-- Resize everytime the mouse move (default behavior)
if args.mode == "live" then
-- Get the new geometry
geo = setmetatable(args.placement(client, args),{__index=args})
end
-- Execute the move callbacks. This can be used to add features such as
-- snap or adding fancy graphical effects.
for _, cb in ipairs(callbacks.move[context] or {}) do
-- If something is returned, assume it is a modified geometry
geo = cb(client, geo, args) or geo
if geo == false then
return false
end
end
if args.move_callback then
geo = args.move_callback(client, geo, args)
if geo == false then
return false
end
end
-- In case it was modified
setmetatable(geo,{__index=args})
if args.mode == "live" then
-- Ask the resizing handler to resize the client
client:emit_signal( req, context, geo)
end
-- Quit when the button is released
for _,v in pairs(_mouse.buttons) do
if v then return true end
end
-- Only resize after the mouse is released, this avoid losing content
-- in resize sensitive apps such as XTerm or allow external modules
-- to implement custom resizing
if args.mode == "after" then
-- Get the new geometry
geo = args.placement(client, args)
-- Ask the resizing handler to resize the client
client:emit_signal( req, context, geo)
end
geo = nil
for _, cb in ipairs(callbacks.leave[context] or {}) do
geo = cb(client, geo, args)
end
if args.leave_callback then
geo = args.leave_callback(client, geo, args)
end
if not geo then return false end
-- In case it was modified
setmetatable(geo,{__index=args})
client:emit_signal( req, context, geo)
return false
end, cursor)
end
return setmetatable(module, {__call=handler})
| gpl-2.0 |
eloicaso/bird-openwrt | packages/bird-openwrt/bird6-openwrt/src/model/overview.lua | 2 | 3152 | --[[
Copyright (C) 2014-2017 - Eloi Carbo
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 3 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, see <http://www.gnu.org/licenses/>.
]]--
require("luci.sys")
local http = require "luci.http"
local uci = require "luci.model.uci"
local uciout = uci.cursor()
m=Map("bird6", "Bird6 UCI configuration helper", "")
-- Named section: "bird"
s_bird_uci = m:section(NamedSection, "bird", "bird", "Bird6 file settings", "")
s_bird_uci.addremove = False
uuc = s_bird_uci:option(Flag, "use_UCI_config", "Use UCI configuration", "Use UCI configuration instead of the /etc/bird6.conf file")
ucf = s_bird_uci:option(Value, "UCI_config_file", "UCI File", "Specify the file to place the UCI-translated configuration")
ucf.default = "/tmp/bird6.conf"
-- Named Section: "table"
s_bird_table = m:section(TypedSection, "table", "Tables configuration", "Configuration of the tables used in the protocols")
s_bird_table.addremove = true
s_bird_table.anonymous = true
name = s_bird_table:option(Value, "name", "Table name", "Descriptor ID of the table")
-- Named section: "global"
s_bird_global = m:section(NamedSection, "global", "global", "Global options", "Basic Bird6 settings")
s_bird_global.addremove = False
id = s_bird_global:option(Value, "router_id", "Router ID", "Identification number of the router. By default, is the router's IP.")
lf = s_bird_global:option(Value, "log_file", "Log File", "File used to store log related data.")
l = s_bird_global:option(MultiValue, "log", "Log", "Set which elements do you want to log.")
l:value("all", "All")
l:value("info", "Info")
l:value("warning","Warning")
l:value("error","Error")
l:value("fatal","Fatal")
l:value("debug","Debug")
l:value("trace","Trace")
l:value("remote","Remote")
l:value("auth","Auth")
d = s_bird_global:option(MultiValue, "debug", "Debug", "Set which elements do you want to debug.")
d:value("all", "All")
d:value("states","States")
d:value("routes","Routes")
d:value("filters","Filters")
d:value("interfaces","Interfaces")
d:value("events","Events")
d:value("packets","Packets")
listen_addr = s_bird_global:option(Value, "listen_bgp_addr", "BGP Address", "Set the Addres that BGP will listen to.")
listen_addr.optional = true
listen_port = s_bird_global:option(Value, "listen_bgp_port", "BGP Port", "Set the port that BGP will listen to.")
listen_port.optional = true
listen_dual = s_bird_global:option(Flag, "listen_bgp_dual", "BGP Dual/ipv6", "Set if BGP connections will listen ipv6 only 'ipv6only' or both ipv4/6 'dual' routes")
listen_dual.optional = true
function m.on_commit(self,map)
luci.sys.exec('/etc/init.d/bird6 restart')
end
return m
| gpl-3.0 |
T3hArco/skeyler-gamemodes | ssbase/entities/weapons/weapon_p90/shared.lua | 1 | 1658 | if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
end
if ( CLIENT ) then
SWEP.PrintName = "P90"
SWEP.Author = "Counter-Strike"
SWEP.Slot = 0
SWEP.SlotPos = 0
SWEP.IconLetter = "m"
killicon.AddFont( "weapon_p90", "CSKillIcons", SWEP.IconLetter, Color( 255, 80, 0, 255 ) )
end
SWEP.HoldType = "smg"
SWEP.Base = "weapon_cs_base"
SWEP.Category = "Counter-Strike"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.ViewModel = "models/weapons/v_smg_p90.mdl"
SWEP.WorldModel = "models/weapons/w_smg_p90.mdl"
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.Primary.Sound = Sound( "Weapon_P90.Single" )
SWEP.Primary.Recoil = 0.2
SWEP.Primary.Damage = 20
SWEP.Primary.NumShots = 1
SWEP.Primary.Cone = 0.025
SWEP.Primary.ClipSize = 50
SWEP.Primary.Delay = 0.066
SWEP.Primary.DefaultClip = 32
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "smg1"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.IronSightsPos = Vector( 4.7, -4, 2 ) | bsd-3-clause |
kjoenth/naev | dat/missions/neutral/runaway/runaway_cynthia.lua | 11 | 2972 | --[[
This is the "The Runaway" mission as described on the wiki.
There will be more missions to detail how you are percieved as the kidnapper of "Cynthia"
--]]
lang = naev.lang()
if lang == "es" then -- Spanish version of the texts would follow
elseif lang == "de" then -- German version of the texts would follow
else -- default English text
npc_name = "Young Teenager"
bar_desc = "A pretty teenager sits alone at a table."
title = "The Runaway"
cargoname = "Person"
misn_desc_pre_accept = [[She looks out of place in the bar. As you approach, she seems to stiffen.
"H..H..Hi", she stutters. "My name is Cynthia. Could you give me a lift? I really need to get out of here.
I can't pay you much, just what I have on me, %s credits." You wonder who she must be to have this many credits on her person. "I need you to take me to Zhiru."
You wonder who she is, but you dare not ask. Do you accept?]]
not_enough_cargospace = "Your cargo hold doesn't have enough free space."
misn_desc = "Deliver Cynthia safely to %s in the %s system."
reward_desc = "%s credits on delivery."
post_accept = {}
post_accept[1] = [["Thank you. But we must leave now, before anyone sees me."]]
misn_accomplished = [[As you walk into the docking bay, she warns you to look out behind yourself.
When you look back to where she was, nothing remains but a tidy pile of credit chips and a worthless pendant.]]
osd_text = {}
osd_text[1] = "Deliver Cynthia to Zhiru in the Goddard system"
end
function create ()
startworld, startworld_sys = planet.cur()
targetworld_sys = system.get("Goddard")
targetworld = planet.get("Zhiru")
--if not misn.claim ( {targetworld_sys} ) then
-- abort()
--end
reward = 75000
misn.setNPC( npc_name, "neutral/miner2" )
misn.setDesc( bar_desc )
end
function accept ()
--This mission does not make any system claims
if not tk.yesno( title, string.format( misn_desc_pre_accept, reward, targetworld:name() ) ) then
misn.finish()
end
--Our *cargo* weighs nothing
--This will probably cause a mess if this fails
if player.pilot():cargoFree() < 0 then
tk.msg( title, not_enough_cargospace )
misn.finish()
end
misn.accept()
misn.osdCreate(title,osd_text)
misn.osdActive(1)
cargoID = misn.cargoAdd( cargoname, 0 )
misn.setTitle( title )
misn.setReward( string.format( reward_desc, reward ) )
misn.setDesc( string.format( misn_desc, targetworld:name(), targetworld_sys:name() ) )
misn.markerAdd( targetworld_sys, "high")
tk.msg( title, post_accept[1] )
hook.land("land")
end
function land ()
--If we land, check if we're at our destination
if planet.cur() == targetworld then
misn.cargoRm( cargoID )
player.pay( reward )
tk.msg( title, string.format(misn_accomplished, reward) )
misn.finish(true)
end
end
function abort ()
--Clean up
misn.cargoRm( cargoID )
misn.osdDestroy()
misn.finish( false )
end
| gpl-3.0 |
McGlaspie/mvm | lua/mvm/Hud/GUIResourceDisplay.lua | 1 | 10179 |
// ======= Copyright (c) 2003-2011, Unknown Worlds Entertainment, Inc. All rights reserved. =======
//
// lua\GUIResourceDisplay.lua
//
// Created by: Brian Cronin (brianc@unknownworlds.com)
//
// Manages displaying resources and number of resource towers.
//
// ========= For more information, visit us at http://www.unknownworlds.com =====================
Script.Load("lua/mvm/GUIColorGlobals.lua")
Script.Load("lua/GUIScript.lua")
class 'GUIResourceDisplay' (GUIScript)
//GUIResourceDisplay.kBackgroundTextureMarine = "ui/marine_commander_textures.dds"
GUIResourceDisplay.kBackgroundTextureMarine = "ui/marine_commander_resources_icons.dds"
GUIResourceDisplay.kBackgroundTextureCoords = { X1 = 0, Y1 = 0, X2 = 256, Y2 = 64 }
GUIResourceDisplay.kBackgroundWidth = GUIScale(128)
GUIResourceDisplay.kBackgroundHeight = GUIScale(64)
GUIResourceDisplay.kBackgroundYOffset = 0
GUIResourceDisplay.kPersonalResourceIcon = { Width = 0, Height = 0, X = 0, Y = 0, Coords = { X1 = 0, Y1 = 0, X2 = 64, Y2 = 64} }
GUIResourceDisplay.kPersonalResourceIcon.Width = GUIScale(48)
GUIResourceDisplay.kPersonalResourceIcon.Height = GUIScale(48)
GUIResourceDisplay.kTeamResourceIcon = { Width = 0, Height = 0, X = 0, Y = 0, Coords = { X1 = 64, Y1 = 0, X2 = 128, Y2 = 64} }
GUIResourceDisplay.kTeamResourceIcon.Width = GUIScale(48)
GUIResourceDisplay.kTeamResourceIcon.Height = GUIScale(48)
GUIResourceDisplay.kResourceTowerIcon = { Width = 0, Height = 0, X = 0, Y = 0, Coords = { X1 = 128, Y1 = 0, X2 = 192, Y2 = 64} }
GUIResourceDisplay.kResourceTowerIcon.Width = GUIScale(48)
GUIResourceDisplay.kResourceTowerIcon.Height = GUIScale(48)
GUIResourceDisplay.kWorkerIcon = { Width = 0, Height = 0, X = 0, Y = 0, Coords = { X1 = 192, Y1 = 0, X2 = 256, Y2 = 64} }
GUIResourceDisplay.kWorkerIcon.Width = GUIScale(48)
GUIResourceDisplay.kWorkerIcon.Height = GUIScale(48)
GUIResourceDisplay.kIconTextXOffset = 5
GUIResourceDisplay.kIconXOffset = 30
local kFontName = "fonts/AgencyFB_small.fnt"
local kFontScale = GUIScale(Vector(1,1,1))
local kColorWhite = Color(1, 1, 1, 1)
local kColorRed = Color(1, 0, 0, 1)
function GUIResourceDisplay:Initialize(settingsTable)
self.textureName = GUIResourceDisplay.kBackgroundTextureMarine
local playerTeam = PlayerUI_GetTeamNumber()
local ui_baseColor = ConditionalValue(
playerTeam == kTeam1Index,
kGUI_Team1_BaseColor,
kGUI_Team2_BaseColor
)
// Background, only used for positioning
self.background = GUIManager:CreateGraphicItem()
self.background:SetSize(Vector(GUIResourceDisplay.kBackgroundWidth, GUIResourceDisplay.kBackgroundHeight, 0))
self.background:SetAnchor(GUIItem.Middle, GUIItem.Top)
self.background:SetPosition(Vector(-GUIResourceDisplay.kBackgroundWidth / 2, GUIResourceDisplay.kBackgroundYOffset, 0))
self.background:SetColor(Color(1, 1, 1, 0))
// Team display.
self.teamIcon = GUIManager:CreateGraphicItem()
self.teamIcon:SetSize(Vector(GUIResourceDisplay.kTeamResourceIcon.Width, GUIResourceDisplay.kTeamResourceIcon.Height, 0))
self.teamIcon:SetAnchor(GUIItem.Left, GUIItem.Center)
local teamIconX = GUIResourceDisplay.kTeamResourceIcon.X + -GUIResourceDisplay.kTeamResourceIcon.Width - GUIResourceDisplay.kIconXOffset
local teamIconY = GUIResourceDisplay.kTeamResourceIcon.Y + -GUIResourceDisplay.kPersonalResourceIcon.Height / 2
self.teamIcon:SetPosition(Vector(teamIconX, teamIconY, 0))
self.teamIcon:SetTexture(self.textureName)
self.teamIcon:SetShader( "shaders/GUI_TeamThemed.surface_shader" )
self.teamIcon:SetFloatParameter( "teamBaseColorR", ui_baseColor.r )
self.teamIcon:SetFloatParameter( "teamBaseColorG", ui_baseColor.g )
self.teamIcon:SetFloatParameter( "teamBaseColorB", ui_baseColor.b )
GUISetTextureCoordinatesTable(self.teamIcon, GUIResourceDisplay.kTeamResourceIcon.Coords)
self.background:AddChild(self.teamIcon)
self.teamText = GUIManager:CreateTextItem()
self.teamText:SetAnchor(GUIItem.Right, GUIItem.Center)
self.teamText:SetTextAlignmentX(GUIItem.Align_Min)
self.teamText:SetTextAlignmentY(GUIItem.Align_Center)
self.teamText:SetPosition(Vector(GUIResourceDisplay.kIconTextXOffset, 0, 0))
self.teamText:SetColor( Color(1, 1, 1, 1) ) //?????
self.teamText:SetFontName(kFontName)
self.teamText:SetScale(kFontScale)
self.teamIcon:AddChild(self.teamText)
// Tower display.
self.towerIcon = GUIManager:CreateGraphicItem()
self.towerIcon:SetSize(Vector(GUIResourceDisplay.kResourceTowerIcon.Width, GUIResourceDisplay.kResourceTowerIcon.Height, 0))
self.towerIcon:SetAnchor(GUIItem.Middle, GUIItem.Center)
local towerIconX = GUIResourceDisplay.kResourceTowerIcon.X + -GUIResourceDisplay.kResourceTowerIcon.Width
local towerIconY = GUIResourceDisplay.kResourceTowerIcon.Y + -GUIResourceDisplay.kResourceTowerIcon.Height / 2
self.towerIcon:SetPosition(Vector(towerIconX, towerIconY, 0))
self.towerIcon:SetTexture(self.textureName)
self.towerIcon:SetShader( "shaders/GUI_TeamThemed.surface_shader" )
self.towerIcon:SetFloatParameter( "teamBaseColorR", ui_baseColor.r )
self.towerIcon:SetFloatParameter( "teamBaseColorG", ui_baseColor.g )
self.towerIcon:SetFloatParameter( "teamBaseColorB", ui_baseColor.b )
GUISetTextureCoordinatesTable(self.towerIcon, GUIResourceDisplay.kResourceTowerIcon.Coords)
self.background:AddChild(self.towerIcon)
self.towerText = GUIManager:CreateTextItem()
self.towerText:SetAnchor(GUIItem.Right, GUIItem.Center)
self.towerText:SetTextAlignmentX(GUIItem.Align_Min)
self.towerText:SetTextAlignmentY(GUIItem.Align_Center)
self.towerText:SetPosition(Vector(GUIResourceDisplay.kIconTextXOffset, 0, 0))
self.towerText:SetColor(Color(1, 1, 1, 1)) //??????
self.towerText:SetFontName(kFontName)
self.towerText:SetScale(kFontScale)
self.towerIcon:AddChild(self.towerText)
// worker display.
self.workerIcon = GUIManager:CreateGraphicItem()
self.workerIcon:SetSize(Vector(GUIResourceDisplay.kResourceTowerIcon.Width, GUIResourceDisplay.kResourceTowerIcon.Height, 0))
self.workerIcon:SetAnchor(GUIItem.Right, GUIItem.Center)
local workerIconX = GUIResourceDisplay.kWorkerIcon.X + -GUIResourceDisplay.kWorkerIcon.Width + GUIResourceDisplay.kIconXOffset
local workerIconY = GUIResourceDisplay.kWorkerIcon.Y + -GUIResourceDisplay.kWorkerIcon.Height / 2
self.workerIcon:SetPosition(Vector(workerIconX, workerIconY, 0))
self.workerIcon:SetTexture(self.textureName)
self.workerIcon:SetShader( "shaders/GUI_TeamThemed.surface_shader" )
self.workerIcon:SetFloatParameter( "teamBaseColorR", ui_baseColor.r )
self.workerIcon:SetFloatParameter( "teamBaseColorG", ui_baseColor.g )
self.workerIcon:SetFloatParameter( "teamBaseColorB", ui_baseColor.b )
GUISetTextureCoordinatesTable(self.workerIcon, GUIResourceDisplay.kWorkerIcon.Coords)
self.background:AddChild(self.workerIcon)
self.workerText = GUIManager:CreateTextItem()
self.workerText:SetAnchor(GUIItem.Right, GUIItem.Center)
self.workerText:SetTextAlignmentX(GUIItem.Align_Min)
self.workerText:SetTextAlignmentY(GUIItem.Align_Center)
self.workerText:SetPosition(Vector(GUIResourceDisplay.kIconTextXOffset, 0, 0))
self.workerText:SetColor(Color(1, 1, 1, 1)) //?????
self.workerText:SetFontName(kFontName)
self.workerText:SetScale(kFontScale)
self.workerIcon:AddChild(self.workerText)
end
function GUIResourceDisplay:Uninitialize()
if self.background then
GUI.DestroyItem(self.background)
end
self.background = nil
end
local kWhite = Color(1,1,1,1)
local kRed = Color(1,0,0,1)
function GUIResourceDisplay:UpdateTeamColors()
local playerTeam = PlayerUI_GetTeamNumber()
local ui_baseColor = ConditionalValue(
playerTeam == kTeam1Index,
kGUI_Team1_BaseColor,
kGUI_Team2_BaseColor
)
self.teamIcon:SetFloatParameter( "teamBaseColorR", ui_baseColor.r )
self.teamIcon:SetFloatParameter( "teamBaseColorG", ui_baseColor.g )
self.teamIcon:SetFloatParameter( "teamBaseColorB", ui_baseColor.b )
self.towerIcon:SetFloatParameter( "teamBaseColorR", ui_baseColor.r )
self.towerIcon:SetFloatParameter( "teamBaseColorG", ui_baseColor.g )
self.towerIcon:SetFloatParameter( "teamBaseColorB", ui_baseColor.b )
self.workerIcon:SetFloatParameter( "teamBaseColorR", ui_baseColor.r )
self.workerIcon:SetFloatParameter( "teamBaseColorG", ui_baseColor.g )
self.workerIcon:SetFloatParameter( "teamBaseColorB", ui_baseColor.b )
end
local supplyWarningLimit = 10
local function PulseRed()
local anim = (math.cos(Shared.GetTime() * 5) + 1) * 0.5
local color = Color()
color.r = 1
color.g = anim
color.b = anim
return color
end
function GUIResourceDisplay:Update(deltaTime)
PROFILE("GUIResourceDisplay:Update")
self:UpdateTeamColors()
local currentTeamRes = PlayerUI_GetTeamResources()
if not self.displayedTeamRes then
self.displayedTeamRes = currentTeamRes
else
if self.displayedTeamRes > currentTeamRes then
self.displayedTeamRes = currentTeamRes
else
self.displayedTeamRes = Slerp(self.displayedTeamRes, currentTeamRes, deltaTime * 40)
end
end
self.teamText:SetText(ToString(math.round(self.displayedTeamRes)))
local numHarvesters = CommanderUI_GetTeamHarvesterCount()
self.towerText:SetText(ToString(numHarvesters))
local supplyUsed = MvM_GetSupplyUsedByTeam( Client.GetLocalPlayer():GetTeamNumber() )
local maxSupply = MvM_GetMaxSupplyForTeam( Client.GetLocalPlayer():GetTeamNumber() )
local targetColor = ConditionalValue( supplyUsed < maxSupply, kWhite, kRed)
if maxSupply - supplyUsed <= supplyWarningLimit and maxSupply ~= supplyUsed then
currentSupplyColor = PulseRed()
else
currentSupplyColor = targetColor
end
self.workerText:SetColor( currentSupplyColor )
self.workerIcon:SetColor( currentSupplyColor )
self.workerText:SetText(string.format("%d / %d", supplyUsed, maxSupply))
end
| gpl-3.0 |
mathiasbynens/otclient | modules/game_textmessage/textmessage.lua | 2 | 5062 | MessageSettings = {
none = {},
consoleRed = { color = TextColors.red, consoleTab='Default' },
consoleOrange = { color = TextColors.orange, consoleTab='Default' },
consoleBlue = { color = TextColors.blue, consoleTab='Default' },
centerRed = { color = TextColors.red, consoleTab='Server Log', screenTarget='lowCenterLabel' },
centerGreen = { color = TextColors.green, consoleTab='Server Log', screenTarget='highCenterLabel', consoleOption='showInfoMessagesInConsole' },
centerWhite = { color = TextColors.white, consoleTab='Server Log', screenTarget='middleCenterLabel', consoleOption='showEventMessagesInConsole' },
bottomWhite = { color = TextColors.white, consoleTab='Server Log', screenTarget='statusLabel', consoleOption='showEventMessagesInConsole' },
status = { color = TextColors.white, consoleTab='Server Log', screenTarget='statusLabel', consoleOption='showStatusMessagesInConsole' },
statusSmall = { color = TextColors.white, screenTarget='statusLabel' },
private = { color = TextColors.lightblue, screenTarget='privateLabel' }
}
MessageTypes = {
[MessageModes.MonsterSay] = MessageSettings.consoleOrange,
[MessageModes.MonsterYell] = MessageSettings.consoleOrange,
[MessageModes.BarkLow] = MessageSettings.consoleOrange,
[MessageModes.BarkLoud] = MessageSettings.consoleOrange,
[MessageModes.Failure] = MessageSettings.statusSmall,
[MessageModes.Login] = MessageSettings.bottomWhite,
[MessageModes.Game] = MessageSettings.centerWhite,
[MessageModes.Status] = MessageSettings.status,
[MessageModes.Warning] = MessageSettings.centerRed,
[MessageModes.Look] = MessageSettings.centerGreen,
[MessageModes.Loot] = MessageSettings.centerGreen,
[MessageModes.Red] = MessageSettings.consoleRed,
[MessageModes.Blue] = MessageSettings.consoleBlue,
[MessageModes.PrivateFrom] = MessageSettings.consoleBlue,
[MessageModes.GamemasterBroadcast] = MessageSettings.consoleRed,
[MessageModes.DamageDealed] = MessageSettings.status,
[MessageModes.DamageReceived] = MessageSettings.status,
[MessageModes.Heal] = MessageSettings.status,
[MessageModes.Exp] = MessageSettings.status,
[MessageModes.DamageOthers] = MessageSettings.none,
[MessageModes.HealOthers] = MessageSettings.none,
[MessageModes.ExpOthers] = MessageSettings.none,
[MessageModes.TradeNpc] = MessageSettings.centerWhite,
[MessageModes.Guild] = MessageSettings.centerWhite,
[MessageModes.Party] = MessageSettings.centerGreen,
[MessageModes.PartyManagement] = MessageSettings.centerWhite,
[MessageModes.TutorialHint] = MessageSettings.centerWhite,
[MessageModes.Market] = MessageSettings.centerWhite,
[MessageModes.BeyondLast] = MessageSettings.centerWhite,
[MessageModes.Report] = MessageSettings.consoleRed,
[MessageModes.HotkeyUse] = MessageSettings.centerGreen,
[254] = MessageSettings.private
}
messagesPanel = nil
function init()
connect(g_game, 'onTextMessage', displayMessage)
connect(g_game, 'onGameEnd', clearMessages)
messagesPanel = g_ui.loadUI('textmessage', modules.game_interface.getRootPanel())
end
function terminate()
disconnect(g_game, 'onTextMessage', displayMessage)
disconnect(g_game, 'onGameEnd', clearMessages)
clearMessages()
messagesPanel:destroy()
end
function calculateVisibleTime(text)
return math.max(#text * 100, 4000)
end
function displayMessage(mode, text)
if not g_game.isOnline() then return end
local msgtype = MessageTypes[mode]
if not msgtype then
perror('unhandled onTextMessage message mode ' .. mode .. ': ' .. text)
return
end
if msgtype == MessageSettings.none then return end
if msgtype.consoleTab ~= nil and (msgtype.consoleOption == nil or modules.client_options.getOption(msgtype.consoleOption)) then
modules.game_console.addText(text, msgtype, tr(msgtype.consoleTab))
--TODO move to game_console
end
if msgtype.screenTarget then
local label = messagesPanel:recursiveGetChildById(msgtype.screenTarget)
label:setText(text)
label:setColor(msgtype.color)
label:setVisible(true)
removeEvent(label.hideEvent)
label.hideEvent = scheduleEvent(function() label:setVisible(false) end, calculateVisibleTime(text))
end
end
function displayPrivateMessage(text)
displayMessage(254, text)
end
function displayStatusMessage(text)
displayMessage(MessageModes.Status, text)
end
function displayFailureMessage(text)
displayMessage(MessageModes.Failure, text)
end
function displayGameMessage(text)
displayMessage(MessageModes.Game, text)
end
function displayBroadcastMessage(text)
displayMessage(MessageModes.Warning, text)
end
function clearMessages()
for _i,child in pairs(messagesPanel:recursiveGetChildren()) do
if child:getId():match('Label') then
child:hide()
removeEvent(child.hideEvent)
end
end
end
function LocalPlayer:onAutoWalkFail(player)
modules.game_textmessage.displayFailureMessage(tr('There is no way.'))
end
| mit |
mathiasbynens/otclient | modules/corelib/ui/uitable.lua | 1 | 5427 | -- @docclass
--[[
TODO:
* Make table headers more robust.
* Get dynamic row heights working with text wrapping.
* Every second row different background color applied.
]]
UITable = extends(UIWidget, "UITable")
local HEADER_ID = 'row0'
function UITable.create()
local table = UITable.internalCreate()
table.headerRow = nil
table.dataSpace = nil
table.rows = {}
table.rowBaseStyle = nil
table.columns = {}
table.columBaseStyle = nil
table.headerRowBaseStyle = nil
table.headerColumnBaseStyle = nil
table.selectedRow = nil
return table
end
function UITable:onDestroy()
for k,row in pairs(self.rows) do
row.onClick = nil
end
self.rows = {}
self.columns = {}
self.headerRow = {}
self.selectedRow = nil
if self.dataSpace then
self.dataSpace:destroyChildren()
self.dataSpace = nil
end
end
function UITable:onStyleApply(styleName, styleNode)
for name, value in pairs(styleNode) do
if name == 'table-data' then
addEvent(function()
self:setTableData(self:getParent():getChildById(value))
end)
elseif name == 'column-style' then
addEvent(function()
self:setColumnStyle(value)
end)
elseif name == 'row-style' then
addEvent(function()
self:setRowStyle(value)
end)
elseif name == 'header-column-style' then
addEvent(function()
self:setHeaderColumnStyle(value)
end)
elseif name == 'header-row-style' then
addEvent(function()
self:setHeaderRowStyle(value)
end)
end
end
end
function UITable:hasHeader()
return self.headerRow ~= nil
end
function UITable:clearData()
if not self.dataSpace then
return
end
self.dataSpace:destroyChildren()
self.selectedRow = nil
self.columns = {}
self.rows = {}
end
function UITable:addHeaderRow(data)
if not data or type(data) ~= 'table' then
g_logger.error('UITable:addHeaderRow - table columns must be provided in a table')
return
end
-- build header columns
local columns = {}
for _, column in pairs(data) do
local col = g_ui.createWidget(self.headerColumnBaseStyle)
for type, value in pairs(column) do
if type == 'width' then
col:setWidth(value)
elseif type == 'height' then
col:setHeight(value)
elseif type == 'text' then
col:setText(value)
elseif type == 'onClick' then
col.onClick = value
end
end
table.insert(columns, col)
end
-- create a new header
local headerRow = g_ui.createWidget(self.headerRowBaseStyle, self)
local newHeight = (self.dataSpace:getHeight()-headerRow:getHeight())-self.dataSpace:getMarginTop()
self.dataSpace:applyStyle({ height = newHeight })
headerRow:setId(HEADER_ID)
for _, column in pairs(columns) do
headerRow:addChild(column)
self.columns[HEADER_ID] = column
end
headerRow.onClick = function(headerRow) self:selectRow(headerRow) end
self.headerRow = headerRow
return headerRow
end
function UITable:removeHeaderRow()
self.headerRow:destroy()
self.headerRow = nil
end
function UITable:addRow(data, ref, height)
if not self.dataSpace then
g_logger.error('UITable:addRow - table data space has not been set, cannot add rows.')
return
end
if not data or type(data) ~= 'table' then
g_logger.error('UITable:addRow - table columns must be provided in a table.')
return
end
local row = g_ui.createWidget(self.rowBaseStyle)
if ref then row.ref = ref end
if height then row:setHeight(height) end
local rowId = #self.rows
row:setId('row'..(rowId < 1 and 1 or rowId))
for _, column in pairs(data) do
local col = g_ui.createWidget(self.columBaseStyle, row)
for type, value in pairs(column) do
if type == 'width' then
col:setWidth(value)
elseif type == 'height' then
col:setHeight(value)
elseif type == 'text' then
col:setText(value)
end
end
self.columns[rowId] = col
end
row.onFocusChange = function(row, focused)
if focused then self:selectRow(row) end
end
self.dataSpace:addChild(row)
table.insert(self.rows, row)
return row
end
function UITable:removeRow(row)
if self.selectedRow == row then
self:selectRow(nil)
end
row.onClick = nil
table.removevalue(self.rows, row)
end
function UITable:selectRow(selectedRow)
if selectedRow == self.selectedRow then return end
local previousSelectedRow = self.selectedRow
self.selectedRow = selectedRow
if previousSelectedRow then
previousSelectedRow:setChecked(false)
end
if selectedRow then
selectedRow:setChecked(true)
end
signalcall(self.onSelectionChange, self, selectedRow, previousSelectedRow)
end
function UITable:setTableData(tableData)
self.dataSpace = tableData
self.dataSpace:applyStyle({ height = self:getHeight() })
end
function UITable:setRowStyle(style)
self.rowBaseStyle = style
for _, row in pairs(self.rows) do
row:setStyle(style)
end
end
function UITable:setColumnStyle(style)
self.columBaseStyle = style
for _, col in pairs(self.columns) do
col:setStyle(style)
end
end
function UITable:setHeaderRowStyle(style)
self.headerRowBaseStyle = style
if self.headerRow then
self.headerRow:setStyle(style)
end
end
function UITable:setHeaderColumnStyle(style)
self.headerColumnBaseStyle = style
if table.haskey(HEADER_ID) then
self.columns[HEADER_ID]:setStyle(style)
end
end
| mit |
heysion/prosody-modules | mod_mam_muc/mod_mam_muc.lua | 20 | 11013 | -- XEP-0313: Message Archive Management for Prosody MUC
-- Copyright (C) 2011-2014 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local xmlns_mam = "urn:xmpp:mam:0";
local xmlns_delay = "urn:xmpp:delay";
local xmlns_forward = "urn:xmpp:forward:0";
local muc_form_enable_logging = "muc#roomconfig_enablelogging"
local st = require "util.stanza";
local rsm = module:require "mod_mam/rsm";
local jid_bare = require "util.jid".bare;
local jid_split = require "util.jid".split;
local dataform = require "util.dataforms".new;
local it = require"util.iterators";
-- Support both old and new MUC code
local mod_muc = module:depends"muc";
local rooms = rawget(mod_muc, "rooms");
local each_room = rawget(mod_muc, "each_room") or function() return it.values(rooms); end;
local new_muc = not rooms;
if new_muc then
rooms = module:shared"muc/rooms";
end
local get_room_from_jid = rawget(mod_muc, "get_room_from_jid") or
function (jid)
return rooms[jid];
end
local getmetatable = getmetatable;
local function is_stanza(x)
return getmetatable(x) == st.stanza_mt;
end
local tostring = tostring;
local time_now = os.time;
local m_min = math.min;
local timestamp, timestamp_parse = require "util.datetime".datetime, require "util.datetime".parse;
local max_history_length = module:get_option_number("max_history_messages", 1000);
local default_max_items, max_max_items = 20, module:get_option_number("max_archive_query_results", max_history_length);
local log_all_rooms = module:get_option_boolean("muc_log_all_rooms", false);
local log_by_default = module:get_option_boolean("muc_log_by_default", true);
local archive_store = "muc_log";
local archive = module:open_store(archive_store, "archive");
if not archive or archive.name == "null" then
module:log("error", "Could not open archive storage");
return
elseif not archive.find then
module:log("error", "mod_%s does not support archiving, switch to mod_storage_sql2", archive._provided_by);
return
end
local function logging_enabled(room)
if log_all_rooms then
return true;
end
local enabled = room._data.logging;
if enabled == nil then
return log_by_default;
end
return enabled;
end
local send_history, save_to_history;
-- Override history methods for all rooms.
if not new_muc then -- 0.10 or older
module:hook("muc-room-created", function (event)
local room = event.room;
if logging_enabled(room) then
room.send_history = send_history;
room.save_to_history = save_to_history;
end
end);
function module.load()
for room in each_room() do
if logging_enabled(room) then
room.send_history = send_history;
room.save_to_history = save_to_history;
end
end
end
function module.unload()
for room in each_room() do
if room.send_history == send_history then
room.send_history = nil;
room.save_to_history = nil;
end
end
end
end
if not log_all_rooms then
module:hook("muc-config-form", function(event)
local room, form = event.room, event.form;
table.insert(form,
{
name = muc_form_enable_logging,
type = "boolean",
label = "Enable Logging?",
value = logging_enabled(room),
}
);
end);
module:hook("muc-config-submitted", function(event)
local room, fields, changed = event.room, event.fields, event.changed;
local new = fields[muc_form_enable_logging];
if new ~= room._data.logging then
room._data.logging = new;
if type(changed) == "table" then
changed[muc_form_enable_logging] = true;
else
event.changed = true;
end
if new then
room.send_history = send_history;
room.save_to_history = save_to_history;
else
room.send_history = nil;
room.save_to_history = nil;
end
end
end);
end
-- Note: We ignore the 'with' field as this is internally used for stanza types
local query_form = dataform {
{ name = "FORM_TYPE"; type = "hidden"; value = xmlns_mam; };
{ name = "with"; type = "jid-single"; };
{ name = "start"; type = "text-single" };
{ name = "end"; type = "text-single"; };
};
-- Serve form
module:hook("iq-get/bare/"..xmlns_mam..":query", function(event)
local origin, stanza = event.origin, event.stanza;
origin.send(st.reply(stanza):add_child(query_form:form()));
return true;
end);
-- Handle archive queries
module:hook("iq-set/bare/"..xmlns_mam..":query", function(event)
local origin, stanza = event.origin, event.stanza;
local room = stanza.attr.to;
local room_node = jid_split(room);
local orig_from = stanza.attr.from;
local query = stanza.tags[1];
local room_obj = get_room_from_jid(room);
if not room_obj then
return origin.send(st.error_reply(stanza, "cancel", "item-not-found"))
end
local from = jid_bare(orig_from);
-- Banned or not a member of a members-only room?
local from_affiliation = room_obj:get_affiliation(from);
if from_affiliation == "outcast" -- banned
or room_obj:get_members_only() and not from_affiliation then -- members-only, not a member
return origin.send(st.error_reply(stanza, "auth", "forbidden"))
end
local qid = query.attr.queryid;
-- Search query parameters
local qstart, qend;
local form = query:get_child("x", "jabber:x:data");
if form then
local err;
form, err = query_form:data(form);
if err then
origin.send(st.error_reply(stanza, "modify", "bad-request", select(2, next(err))));
return true;
end
qstart, qend = form["start"], form["end"];
end
if qstart or qend then -- Validate timestamps
local vstart, vend = (qstart and timestamp_parse(qstart)), (qend and timestamp_parse(qend))
if (qstart and not vstart) or (qend and not vend) then
origin.send(st.error_reply(stanza, "modify", "bad-request", "Invalid timestamp"))
return true
end
qstart, qend = vstart, vend;
end
-- RSM stuff
local qset = rsm.get(query);
local qmax = m_min(qset and qset.max or default_max_items, max_max_items);
local reverse = qset and qset.before or false;
local before, after = qset and qset.before, qset and qset.after;
if type(before) ~= "string" then before = nil; end
-- Load all the data!
local data, err = archive:find(room_node, {
start = qstart; ["end"] = qend; -- Time range
limit = qmax + 1;
before = before; after = after;
reverse = reverse;
total = true;
with = "message<groupchat";
});
if not data then
return origin.send(st.error_reply(stanza, "cancel", "internal-server-error"));
end
local total = err;
origin.send(st.reply(stanza))
local msg_reply_attr = { to = stanza.attr.from, from = stanza.attr.to };
local results = {};
-- Wrap it in stuff and deliver
local first, last;
local count = 0;
local complete = "true";
for id, item, when in data do
count = count + 1;
if count > qmax then
complete = nil;
break;
end
local fwd_st = st.message(msg_reply_attr)
:tag("result", { xmlns = xmlns_mam, queryid = qid, id = id })
:tag("forwarded", { xmlns = xmlns_forward })
:tag("delay", { xmlns = xmlns_delay, stamp = timestamp(when) }):up();
if not is_stanza(item) then
item = st.deserialize(item);
end
item.attr.xmlns = "jabber:client";
fwd_st:add_child(item);
if not first then first = id; end
last = id;
if reverse then
results[count] = fwd_st;
else
origin.send(fwd_st);
end
end
if reverse then
for i = #results, 1, -1 do
origin.send(results[i]);
end
end
-- That's all folks!
module:log("debug", "Archive query %s completed", tostring(qid));
if reverse then first, last = last, first; end
origin.send(st.message(msg_reply_attr)
:tag("fin", { xmlns = xmlns_mam, queryid = qid, complete = complete })
:add_child(rsm.generate {
first = first, last = last, count = total }));
return true;
end);
module:hook("muc-get-history", function (event)
local room = event.room;
if not logging_enabled(room) then return end
local room_jid = room.jid;
local maxstanzas = event.maxstanzas;
local maxchars = event.maxchars;
local since = event.since;
local to = event.to;
-- Load all the data!
local query = {
limit = m_min(maxstanzas or 20, max_history_length);
start = since;
reverse = true;
with = "message<groupchat";
}
module:log("debug", require"util.serialization".serialize(query))
local data, err = archive:find(jid_split(room_jid), query);
if not data then
module:log("error", "Could not fetch history: %s", tostring(err));
return
end
local history, i = {}, 1;
for _, item, when in data do
item.attr.to = to;
item:tag("delay", { xmlns = "urn:xmpp:delay", from = room_jid, stamp = timestamp(when) }):up(); -- XEP-0203
if maxchars then
local chars = #tostring(item);
if maxchars - chars < 0 then
break
end
maxchars = maxchars - chars;
end
history[i], i = item, i+1;
-- module:log("debug", tostring(item));
end
function event.next_stanza()
i = i - 1;
return history[i];
end
return true;
end, 1);
function send_history(self, to, stanza)
local maxchars, maxstanzas, seconds, since;
local history_tag = stanza:find("{http://jabber.org/protocol/muc}x/history")
if history_tag then
module:log("debug", tostring(history_tag));
local history_attr = history_tag.attr;
maxchars = tonumber(history_attr.maxchars);
maxstanzas = tonumber(history_attr.maxstanzas);
seconds = tonumber(history_attr.seconds);
since = history_attr.since;
if since then
since = timestamp_parse(since);
end
if seconds then
since = math.max(os.time() - seconds, since or 0);
end
end
local event = {
room = self;
to = to; -- `to` is required to calculate the character count for `maxchars`
maxchars = maxchars, maxstanzas = maxstanzas, since = since;
next_stanza = function() end; -- events should define this iterator
};
module:fire_event("muc-get-history", event);
for msg in event.next_stanza, event do
self:_route_stanza(msg);
end
end
-- Handle messages
function save_to_history(self, stanza)
local room = jid_split(self.jid);
-- Policy check
if not logging_enabled(self) then return end -- Don't log
module:log("debug", "We're logging this")
-- And stash it
local with = stanza.name
if stanza.attr.type then
with = with .. "<" .. stanza.attr.type
end
archive:append(room, nil, time_now(), with, stanza);
end
module:hook("muc-broadcast-message", function (event)
local room, stanza = event.room, event.stanza;
if stanza:get_child("body") then
save_to_history(room, stanza);
end
end);
if module:get_option_boolean("muc_log_presences", true) then
module:hook("muc-occupant-joined", function (event)
save_to_history(event.room, st.stanza("presence", { from = event.nick }));
end);
module:hook("muc-occupant-left", function (event)
save_to_history(event.room, st.stanza("presence", { type = "unavailable", from = event.nick }));
end);
end
module:hook("muc-room-destroyed", function(event)
local username = jid_split(event.room.jid);
archive:delete(username);
end);
-- TODO should we perhaps log presence as well?
-- And role/affiliation changes?
module:add_feature(xmlns_mam);
module:hook("muc-disco#info", function(event)
event.reply:tag("feature", {var=xmlns_mam}):up();
end);
| mit |
haider1984/-1 | plugins/ar-robot.lua | 6 | 2573 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀ BY SAJAD NOORI (@SAJJADNOORI) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY SAJJAD NOORI ▀▄ ▄▀
▀▄ ▄▀disable chat: تعطيل تفعيل دردشه محدد ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
local function is_channel_disabled( receiver )
if not _config.disabled_channels then
return false
end
if _config.disabled_channels[receiver] == nil then
return false
end
return _config.disabled_channels[receiver]
end
local function enable_channel(receiver)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
if _config.disabled_channels[receiver] == nil then
return '😊 اَلـبـِوتَ بأَلتأكيَدَ تمَ تشَغيِلهَ ب أَلمجموعـهِ ✔️👍🏻'
end
_config.disabled_channels[receiver] = false
save_config()
return "تَمِ ✔️ تشغـيَل البوَتَ في المَجمَوعـهَ 👍"
end
local function disable_channel( receiver )
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return "تَمِ ✔️ أطـفأءَ الـبوَتَ فـي أَلمجـموَعـهَ 👍🏻❌"
end
local function pre_process(msg)
local receiver = get_receiver(msg)
-- If sender is moderator then re-enable the channel
--if is_sudo(msg) then
if is_momod(msg) then
if msg.text == "تشغيل البوت" then
enable_channel(receiver)
end
end
if is_channel_disabled(receiver) then
msg.text = ""
end
return msg
end
local function run(msg, matches)
local receiver = get_receiver(msg)
-- Enable a channel
if matches[1] == 'تشغيل البوت' then
return enable_channel(receiver)
end
-- Disable a channel
if matches[1] == 'اطفاء البوت' then
return disable_channel(receiver)
end
end
return {
description = "Plugin to manage Bot.",
usage = {
"Bot on: enable BOT In a Group",
"Bot off: disable Bot In a Group" },
patterns = {
"^(تشغيل البوت)",
"^(اطفاء البوت)" },
run = run,
privileged = true,
--moderated = true,
pre_process = pre_process
} | gpl-2.0 |
QuiQiJingFeng/skynet | lualib/skynet/socket.lua | 6 | 9294 | local driver = require "skynet.socketdriver"
local skynet = require "skynet"
local skynet_core = require "skynet.core"
local assert = assert
local socket = {} -- api
local buffer_pool = {} -- store all message buffer object
local socket_pool = setmetatable( -- store all socket object
{},
{ __gc = function(p)
for id,v in pairs(p) do
driver.close(id)
-- don't need clear v.buffer, because buffer pool will be free at the end
p[id] = nil
end
end
}
)
local socket_message = {}
local function wakeup(s)
local co = s.co
if co then
s.co = nil
skynet.wakeup(co)
end
end
local function suspend(s)
assert(not s.co)
s.co = coroutine.running()
skynet.wait(s.co)
-- wakeup closing corouting every time suspend,
-- because socket.close() will wait last socket buffer operation before clear the buffer.
if s.closing then
skynet.wakeup(s.closing)
end
end
-- read skynet_socket.h for these macro
-- SKYNET_SOCKET_TYPE_DATA = 1
socket_message[1] = function(id, size, data)
local s = socket_pool[id]
if s == nil then
skynet.error("socket: drop package from " .. id)
driver.drop(data, size)
return
end
local sz = driver.push(s.buffer, buffer_pool, data, size)
local rr = s.read_required
local rrt = type(rr)
if rrt == "number" then
-- read size
if sz >= rr then
s.read_required = nil
wakeup(s)
end
else
if s.buffer_limit and sz > s.buffer_limit then
skynet.error(string.format("socket buffer overflow: fd=%d size=%d", id , sz))
driver.clear(s.buffer,buffer_pool)
driver.close(id)
return
end
if rrt == "string" then
-- read line
if driver.readline(s.buffer,nil,rr) then
s.read_required = nil
wakeup(s)
end
end
end
end
-- SKYNET_SOCKET_TYPE_CONNECT = 2
socket_message[2] = function(id, _ , addr)
local s = socket_pool[id]
if s == nil then
return
end
-- log remote addr
s.connected = true
wakeup(s)
end
-- SKYNET_SOCKET_TYPE_CLOSE = 3
socket_message[3] = function(id)
local s = socket_pool[id]
if s == nil then
return
end
s.connected = false
wakeup(s)
end
-- SKYNET_SOCKET_TYPE_ACCEPT = 4
socket_message[4] = function(id, newid, addr)
local s = socket_pool[id]
if s == nil then
driver.close(newid)
return
end
s.callback(newid, addr)
end
-- SKYNET_SOCKET_TYPE_ERROR = 5
socket_message[5] = function(id, _, err)
local s = socket_pool[id]
if s == nil then
skynet.error("socket: error on unknown", id, err)
return
end
if s.connected then
skynet.error("socket: error on", id, err)
elseif s.connecting then
s.connecting = err
end
s.connected = false
driver.shutdown(id)
wakeup(s)
end
-- SKYNET_SOCKET_TYPE_UDP = 6
socket_message[6] = function(id, size, data, address)
local s = socket_pool[id]
if s == nil or s.callback == nil then
skynet.error("socket: drop udp package from " .. id)
driver.drop(data, size)
return
end
local str = skynet.tostring(data, size)
skynet_core.trash(data, size)
s.callback(str, address)
end
local function default_warning(id, size)
local s = socket_pool[id]
if not s then
return
end
skynet.error(string.format("WARNING: %d K bytes need to send out (fd = %d)", size, id))
end
-- SKYNET_SOCKET_TYPE_WARNING
socket_message[7] = function(id, size)
local s = socket_pool[id]
if s then
local warning = s.on_warning or default_warning
warning(id, size)
end
end
skynet.register_protocol {
name = "socket",
id = skynet.PTYPE_SOCKET, -- PTYPE_SOCKET = 6
unpack = driver.unpack,
dispatch = function (_, _, t, ...)
socket_message[t](...)
end
}
local function connect(id, func)
local newbuffer
if func == nil then
newbuffer = driver.buffer()
end
local s = {
id = id,
buffer = newbuffer,
connected = false,
connecting = true,
read_required = false,
co = false,
callback = func,
protocol = "TCP",
}
assert(not socket_pool[id], "socket is not closed")
socket_pool[id] = s
suspend(s)
local err = s.connecting
s.connecting = nil
if s.connected then
return id
else
socket_pool[id] = nil
return nil, err
end
end
function socket.open(addr, port)
local id = driver.connect(addr,port)
return connect(id)
end
function socket.bind(os_fd)
local id = driver.bind(os_fd)
return connect(id)
end
function socket.stdin()
return socket.bind(0)
end
function socket.start(id, func)
driver.start(id)
return connect(id, func)
end
function socket.shutdown(id)
local s = socket_pool[id]
if s then
driver.clear(s.buffer,buffer_pool)
-- the framework would send SKYNET_SOCKET_TYPE_CLOSE , need close(id) later
driver.shutdown(id)
end
end
function socket.close_fd(id)
assert(socket_pool[id] == nil,"Use socket.close instead")
driver.close(id)
end
function socket.close(id)
local s = socket_pool[id]
if s == nil then
return
end
if s.connected then
driver.close(id)
-- notice: call socket.close in __gc should be carefully,
-- because skynet.wait never return in __gc, so driver.clear may not be called
if s.co then
-- reading this socket on another coroutine, so don't shutdown (clear the buffer) immediately
-- wait reading coroutine read the buffer.
assert(not s.closing)
s.closing = coroutine.running()
skynet.wait(s.closing)
else
suspend(s)
end
s.connected = false
end
driver.clear(s.buffer,buffer_pool)
assert(s.lock == nil or next(s.lock) == nil)
socket_pool[id] = nil
end
function socket.read(id, sz)
local s = socket_pool[id]
assert(s)
if sz == nil then
-- read some bytes
local ret = driver.readall(s.buffer, buffer_pool)
if ret ~= "" then
return ret
end
if not s.connected then
return false, ret
end
assert(not s.read_required)
s.read_required = 0
suspend(s)
ret = driver.readall(s.buffer, buffer_pool)
if ret ~= "" then
return ret
else
return false, ret
end
end
local ret = driver.pop(s.buffer, buffer_pool, sz)
if ret then
return ret
end
if not s.connected then
return false, driver.readall(s.buffer, buffer_pool)
end
assert(not s.read_required)
s.read_required = sz
suspend(s)
ret = driver.pop(s.buffer, buffer_pool, sz)
if ret then
return ret
else
return false, driver.readall(s.buffer, buffer_pool)
end
end
function socket.readall(id)
local s = socket_pool[id]
assert(s)
if not s.connected then
local r = driver.readall(s.buffer, buffer_pool)
return r ~= "" and r
end
assert(not s.read_required)
s.read_required = true
suspend(s)
assert(s.connected == false)
return driver.readall(s.buffer, buffer_pool)
end
function socket.readline(id, sep)
sep = sep or "\n"
local s = socket_pool[id]
assert(s)
local ret = driver.readline(s.buffer, buffer_pool, sep)
if ret then
return ret
end
if not s.connected then
return false, driver.readall(s.buffer, buffer_pool)
end
assert(not s.read_required)
s.read_required = sep
suspend(s)
if s.connected then
return driver.readline(s.buffer, buffer_pool, sep)
else
return false, driver.readall(s.buffer, buffer_pool)
end
end
function socket.block(id)
local s = socket_pool[id]
if not s or not s.connected then
return false
end
assert(not s.read_required)
s.read_required = 0
suspend(s)
return s.connected
end
socket.write = assert(driver.send)
socket.lwrite = assert(driver.lsend)
socket.header = assert(driver.header)
function socket.invalid(id)
return socket_pool[id] == nil
end
function socket.disconnected(id)
local s = socket_pool[id]
if s then
return not(s.connected or s.connecting)
end
end
function socket.listen(host, port, backlog)
if port == nil then
host, port = string.match(host, "([^:]+):(.+)$")
port = tonumber(port)
end
return driver.listen(host, port, backlog)
end
function socket.lock(id)
local s = socket_pool[id]
assert(s)
local lock_set = s.lock
if not lock_set then
lock_set = {}
s.lock = lock_set
end
if #lock_set == 0 then
lock_set[1] = true
else
local co = coroutine.running()
table.insert(lock_set, co)
skynet.wait(co)
end
end
function socket.unlock(id)
local s = socket_pool[id]
assert(s)
local lock_set = assert(s.lock)
table.remove(lock_set,1)
local co = lock_set[1]
if co then
skynet.wakeup(co)
end
end
-- abandon use to forward socket id to other service
-- you must call socket.start(id) later in other service
function socket.abandon(id)
local s = socket_pool[id]
if s then
driver.clear(s.buffer,buffer_pool)
s.connected = false
wakeup(s)
socket_pool[id] = nil
end
end
function socket.limit(id, limit)
local s = assert(socket_pool[id])
s.buffer_limit = limit
end
---------------------- UDP
local function create_udp_object(id, cb)
assert(not socket_pool[id], "socket is not closed")
socket_pool[id] = {
id = id,
connected = true,
protocol = "UDP",
callback = cb,
}
end
function socket.udp(callback, host, port)
local id = driver.udp(host, port)
create_udp_object(id, callback)
return id
end
function socket.udp_connect(id, addr, port, callback)
local obj = socket_pool[id]
if obj then
assert(obj.protocol == "UDP")
if callback then
obj.callback = callback
end
else
create_udp_object(id, callback)
end
driver.udp_connect(id, addr, port)
end
socket.sendto = assert(driver.udp_send)
socket.udp_address = assert(driver.udp_address)
function socket.warning(id, callback)
local obj = socket_pool[id]
assert(obj)
obj.on_warning = callback
end
return socket
| mit |
bertptrs/vimconfig | awesome/.config/awesome/battery.lua | 1 | 1893 | local naughty = require("naughty")
local beautiful = require("beautiful")
local vicious = require("vicious")
local wibox = require("wibox")
local pairs = pairs
module("battery")
-- Battery (based on http://awesome.naquadah.org/wiki/Gigamo_Battery_Widget)
-- Edited by TobiasKappe
local limits = { {25, 5},
{12, 3},
{ 7, 1},
{0}}
local function getnextlim (num)
for ind, pair in pairs(limits) do
lim = pair[1]; step = pair[2]; nextlim = limits[ind+1][1] or 0
if num > nextlim then
repeat
lim = lim - step
until num > lim
if lim < nextlim then
lim = nextlim
end
return lim
end
end
end
function batclosure ()
local nextlim = limits[1][1]
return function (_, args)
local prefix = "⚡"
local state, charge = args[1], args[2]
if not charge then return end
if state == "−" then
dirsign = "↓"
prefix = "Bat:"
if charge <= nextlim then
naughty.notify({
title = "⚡ Waarschuwing! ⚡",
text = "Accu bijna leeg ( ⚡ " ..charge.."%)!",
timeout = 7,
position = "bottom_right",
fg = beautiful.fg_focus,
bg = beautiful.bg_focus
})
nextlim = getnextlim(charge)
end
elseif state == "+" then
dirsign = "↑"
nextlim = limits[1][1]
else
return " ⚡ "
end
if dir ~= 0 then charge = charge.."%" end
return " "..prefix.." "..dirsign..charge..dirsign.." "
end
end
local widget = wibox.widget.textbox()
vicious.register(widget, vicious.widgets.bat, batclosure(), 31, "BAT0")
return widget
| gpl-2.0 |
dmccuskey/dmc-gestures | examples/gesture-pan-move/dmc_corona/dmc_gestures/tap_gesture.lua | 10 | 7687 | --====================================================================--
-- dmc_corona/dmc_gesture/tap_gesture.lua
--
-- Documentation: http://docs.davidmccuskey.com/dmc-gestures
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2015 David McCuskey
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.
--]]
--====================================================================--
--== DMC Corona Library : Tap Gesture
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--====================================================================--
--== DMC Tap Gesture
--====================================================================--
--====================================================================--
--== Imports
local Objects = require 'dmc_objects'
local Utils = require 'dmc_utils'
local Gesture = require 'dmc_gestures.core.gesture'
local Constants = require 'dmc_gestures.gesture_constants'
--====================================================================--
--== Setup, Constants
local newClass = Objects.newClass
local mabs = math.abs
--====================================================================--
--== Tap Gesture Class
--====================================================================--
--- Tap Gesture Recognizer Class.
-- gestures to recognize tap motions
--
-- **Inherits from:**
--
-- * @{Gesture.Gesture}
--
-- @classmod Gesture.Tap
--
-- @usage local Gesture = require 'dmc_gestures'
-- local view = display.newRect( 100, 100, 200, 200 )
-- local g = Gesture.newTapGesture( view )
-- g:addEventListener( g.EVENT, gHandler )
local TapGesture = newClass( Gesture, { name="Tap Gesture" } )
--- Class Constants.
-- @section
--== Class Constants
TapGesture.TYPE = Constants.TYPE_TAP
--- Event name constant.
-- @field EVENT
-- @usage gesture:addEventListener( gesture.EVENT, handler )
-- @usage gesture:removeEventListener( gesture.EVENT, handler )
--- Event type constant, gesture recognized.
-- this type of event is sent out when a Gesture Recognizer has recognized the gesture
-- @field GESTURE
-- @usage
-- local function handler( event )
-- local gesture = event.target
-- if event.type == gesture.GESTURE then
-- -- we have our event !
-- end
-- end
--======================================================--
-- Start: Setup DMC Objects
function TapGesture:__init__( params )
-- print( "TapGesture:__init__", params )
params = params or {}
if params.accuracy==nil then params.accuracy=Constants.TAP_ACCURACY end
if params.taps==nil then params.taps=Constants.TAP_TAPS end
if params.touches==nil then params.touches=Constants.TAP_TOUCHES end
self:superCall( '__init__', params )
--==--
--== Create Properties ==--
self._min_accuracy = params.accuracy
self._req_taps = params.taps
self._req_touches = params.touches
self._tap_count = 0 -- how many taps
end
function TapGesture:__initComplete__()
-- print( "TapGesture:__initComplete__" )
self:superCall( '__initComplete__' )
--==--
--== use setters
self.accuracy = self._min_accuracy
self.taps = self._req_taps
self.touches = self._req_touches
end
--[[
function TapGesture:__undoInitComplete__()
-- print( "TapGesture:__undoInitComplete__" )
--==--
self:superCall( '__undoInitComplete__' )
end
--]]
-- END: Setup DMC Objects
--======================================================--
--====================================================================--
--== Public Methods
--======================================================--
-- Getters/Setters
--- Getters and Setters
-- @section getters-setters
--- the maximum movement allowed between taps, radius (number).
--
-- @function .accuracy
-- @usage print( gesture.accuracy )
-- @usage gesture.accuracy = 10
--
function TapGesture.__getters:accuracy()
return self._min_accuracy
end
function TapGesture.__setters:accuracy( value )
assert( type(value)=='number' and value>0 )
--==--
self._min_accuracy = value
end
--- the minimum number of taps required to recognize (number).
-- this specifies the minimum number of taps required to succeed.
--
-- @function .taps
-- @usage print( gesture.taps )
-- @usage gesture.taps = 2
--
function TapGesture.__getters:taps()
return self._req_taps
end
function TapGesture.__setters:taps( value )
assert( type(value)=='number' and ( value>0 and value<6 ) )
--==--
self._req_taps = value
end
--- the minimum number of touches required to recognize (number).
-- this is used to specify the number of fingers required for each tap, eg a two-fingered single-tap, three-fingered double-tap.
--
-- @function .touches
-- @usage print( gesture.touches )
-- @usage gesture.touches = 2
--
function TapGesture.__getters:touches()
return self._req_touches
end
function TapGesture.__setters:touches( value )
assert( type(value)=='number' and ( value>0 and value<5 ) )
--==--
self._req_touches = value
end
--====================================================================--
--== Private Methods
function TapGesture:_do_reset()
-- print( "TapGesture:_do_reset" )
Gesture._do_reset( self )
self._tap_count=0
end
--====================================================================--
--== Event Handlers
-- event is Corona Touch Event
--
function TapGesture:touch( event )
-- print("TapGesture:touch", event.phase, self )
Gesture.touch( self, event )
local phase = event.phase
if phase=='began' then
local r_touches = self._req_touches
local touch_count = self._touch_count
self:_startFailTimer()
self._gesture_attempt=true
if touch_count==r_touches then
self:_startGestureTimer()
elseif touch_count>r_touches then
self:gotoState( TapGesture.STATE_FAILED )
end
elseif phase=='moved' then
local _mabs = mabs
local accuracy = self._min_accuracy
if _mabs(event.xStart-event.x)>accuracy or _mabs(event.yStart-event.y)>accuracy then
self:gotoState( TapGesture.STATE_FAILED )
end
elseif phase=='cancelled' then
self:gotoState( TapGesture.STATE_FAILED )
else -- ended
local touch_count = self._touch_count
local r_taps = self._req_taps
local taps = self._tap_count
if self._gesture_timer and touch_count==0 then
taps = taps + 1
self:_stopGestureTimer()
end
if taps==r_taps then
self:gotoState( TapGesture.STATE_RECOGNIZED )
elseif taps>r_taps then
self:gotoState( TapGesture.STATE_FAILED )
else
self:_startFailTimer()
end
self._tap_count = taps
end
end
--====================================================================--
--== State Machine
-- none
return TapGesture
| mit |
dmccuskey/dmc-gestures | examples/gesture-multigesture-basic/dmc_corona/dmc_gestures/tap_gesture.lua | 10 | 7687 | --====================================================================--
-- dmc_corona/dmc_gesture/tap_gesture.lua
--
-- Documentation: http://docs.davidmccuskey.com/dmc-gestures
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2015 David McCuskey
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.
--]]
--====================================================================--
--== DMC Corona Library : Tap Gesture
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--====================================================================--
--== DMC Tap Gesture
--====================================================================--
--====================================================================--
--== Imports
local Objects = require 'dmc_objects'
local Utils = require 'dmc_utils'
local Gesture = require 'dmc_gestures.core.gesture'
local Constants = require 'dmc_gestures.gesture_constants'
--====================================================================--
--== Setup, Constants
local newClass = Objects.newClass
local mabs = math.abs
--====================================================================--
--== Tap Gesture Class
--====================================================================--
--- Tap Gesture Recognizer Class.
-- gestures to recognize tap motions
--
-- **Inherits from:**
--
-- * @{Gesture.Gesture}
--
-- @classmod Gesture.Tap
--
-- @usage local Gesture = require 'dmc_gestures'
-- local view = display.newRect( 100, 100, 200, 200 )
-- local g = Gesture.newTapGesture( view )
-- g:addEventListener( g.EVENT, gHandler )
local TapGesture = newClass( Gesture, { name="Tap Gesture" } )
--- Class Constants.
-- @section
--== Class Constants
TapGesture.TYPE = Constants.TYPE_TAP
--- Event name constant.
-- @field EVENT
-- @usage gesture:addEventListener( gesture.EVENT, handler )
-- @usage gesture:removeEventListener( gesture.EVENT, handler )
--- Event type constant, gesture recognized.
-- this type of event is sent out when a Gesture Recognizer has recognized the gesture
-- @field GESTURE
-- @usage
-- local function handler( event )
-- local gesture = event.target
-- if event.type == gesture.GESTURE then
-- -- we have our event !
-- end
-- end
--======================================================--
-- Start: Setup DMC Objects
function TapGesture:__init__( params )
-- print( "TapGesture:__init__", params )
params = params or {}
if params.accuracy==nil then params.accuracy=Constants.TAP_ACCURACY end
if params.taps==nil then params.taps=Constants.TAP_TAPS end
if params.touches==nil then params.touches=Constants.TAP_TOUCHES end
self:superCall( '__init__', params )
--==--
--== Create Properties ==--
self._min_accuracy = params.accuracy
self._req_taps = params.taps
self._req_touches = params.touches
self._tap_count = 0 -- how many taps
end
function TapGesture:__initComplete__()
-- print( "TapGesture:__initComplete__" )
self:superCall( '__initComplete__' )
--==--
--== use setters
self.accuracy = self._min_accuracy
self.taps = self._req_taps
self.touches = self._req_touches
end
--[[
function TapGesture:__undoInitComplete__()
-- print( "TapGesture:__undoInitComplete__" )
--==--
self:superCall( '__undoInitComplete__' )
end
--]]
-- END: Setup DMC Objects
--======================================================--
--====================================================================--
--== Public Methods
--======================================================--
-- Getters/Setters
--- Getters and Setters
-- @section getters-setters
--- the maximum movement allowed between taps, radius (number).
--
-- @function .accuracy
-- @usage print( gesture.accuracy )
-- @usage gesture.accuracy = 10
--
function TapGesture.__getters:accuracy()
return self._min_accuracy
end
function TapGesture.__setters:accuracy( value )
assert( type(value)=='number' and value>0 )
--==--
self._min_accuracy = value
end
--- the minimum number of taps required to recognize (number).
-- this specifies the minimum number of taps required to succeed.
--
-- @function .taps
-- @usage print( gesture.taps )
-- @usage gesture.taps = 2
--
function TapGesture.__getters:taps()
return self._req_taps
end
function TapGesture.__setters:taps( value )
assert( type(value)=='number' and ( value>0 and value<6 ) )
--==--
self._req_taps = value
end
--- the minimum number of touches required to recognize (number).
-- this is used to specify the number of fingers required for each tap, eg a two-fingered single-tap, three-fingered double-tap.
--
-- @function .touches
-- @usage print( gesture.touches )
-- @usage gesture.touches = 2
--
function TapGesture.__getters:touches()
return self._req_touches
end
function TapGesture.__setters:touches( value )
assert( type(value)=='number' and ( value>0 and value<5 ) )
--==--
self._req_touches = value
end
--====================================================================--
--== Private Methods
function TapGesture:_do_reset()
-- print( "TapGesture:_do_reset" )
Gesture._do_reset( self )
self._tap_count=0
end
--====================================================================--
--== Event Handlers
-- event is Corona Touch Event
--
function TapGesture:touch( event )
-- print("TapGesture:touch", event.phase, self )
Gesture.touch( self, event )
local phase = event.phase
if phase=='began' then
local r_touches = self._req_touches
local touch_count = self._touch_count
self:_startFailTimer()
self._gesture_attempt=true
if touch_count==r_touches then
self:_startGestureTimer()
elseif touch_count>r_touches then
self:gotoState( TapGesture.STATE_FAILED )
end
elseif phase=='moved' then
local _mabs = mabs
local accuracy = self._min_accuracy
if _mabs(event.xStart-event.x)>accuracy or _mabs(event.yStart-event.y)>accuracy then
self:gotoState( TapGesture.STATE_FAILED )
end
elseif phase=='cancelled' then
self:gotoState( TapGesture.STATE_FAILED )
else -- ended
local touch_count = self._touch_count
local r_taps = self._req_taps
local taps = self._tap_count
if self._gesture_timer and touch_count==0 then
taps = taps + 1
self:_stopGestureTimer()
end
if taps==r_taps then
self:gotoState( TapGesture.STATE_RECOGNIZED )
elseif taps>r_taps then
self:gotoState( TapGesture.STATE_FAILED )
else
self:_startFailTimer()
end
self._tap_count = taps
end
end
--====================================================================--
--== State Machine
-- none
return TapGesture
| mit |
pirate/snabbswitch | src/lib/hardware/pci.lua | 2 | 5264 | module(...,package.seeall)
local ffi = require("ffi")
local C = ffi.C
local lib = require("core.lib")
require("lib.hardware.pci_h")
--- ### Hardware device information
devices = {}
--- Array of all supported hardware devices.
---
--- Each entry is a "device info" table with these attributes:
---
--- * `pciaddress` e.g. `"0000:83:00.1"`
--- * `vendor` id hex string e.g. `"0x8086"` for Intel.
--- * `device` id hex string e.g. `"0x10fb"` for 82599 chip.
--- * `interface` name of Linux interface using this device e.g. `"eth0"`.
--- * `status` string Linux operational status, or `nil` if not known.
--- * `driver` Lua module that supports this hardware e.g. `"intel10g"`.
--- * `usable` device was suitable to use when scanned? `yes` or `no`
--- Initialize (or re-initialize) the `devices` table.
function scan_devices ()
for _,device in ipairs(lib.files_in_directory("/sys/bus/pci/devices")) do
local info = device_info(device)
if info.driver then table.insert(devices, info) end
end
end
function device_info (pciaddress)
local info = {}
local p = path(pciaddress)
info.pciaddress = pciaddress
info.vendor = lib.firstline(p.."/vendor")
info.device = lib.firstline(p.."/device")
info.model = which_model(info.vendor, info.device)
info.driver = which_driver(info.vendor, info.device)
if info.driver then
info.interface = lib.firstfile(p.."/net")
if info.interface then
info.status = lib.firstline(p.."/net/"..info.interface.."/operstate")
end
end
info.usable = lib.yesno(is_usable(info))
return info
end
--- Return the path to the sysfs directory for `pcidev`.
function path(pcidev) return "/sys/bus/pci/devices/"..pcidev end
model = {
["82599_SFP"] = 'Intel 82599 SFP',
["82574L"] = 'Intel 82574L',
["82571"] = 'Intel 82571',
["82599_T3"] = 'Intel 82599 T3',
["X540"] = 'Intel X540',
}
-- Supported cards indexed by vendor and device id.
local cards = {
["0x8086"] = {
["0x10fb"] = {model = model["82599_SFP"], driver = 'apps.intel.intel_app'},
["0x10d3"] = {model = model["82574L"], driver = 'apps.intel.intel_app'},
["0x105e"] = {model = model["82571"], driver = 'apps.intel.intel_app'},
["0x151c"] = {model = model["82599_T3"], driver = 'apps.intel.intel_app'},
["0x1528"] = {model = model["X540"], driver = 'apps.intel.intel_app'},
},
["0x1924"] = {
["0x0903"] = {model = 'SFN7122F', driver = 'apps.solarflare.solarflare'}
},
}
-- Return the name of the Lua module that implements support for this device.
function which_driver (vendor, device)
local card = cards[vendor] and cards[vendor][device]
return card and card.driver
end
function which_model (vendor, device)
local card = cards[vendor] and cards[vendor][device]
return card and card.model
end
--- ### Device manipulation.
--- Return true if `device` is safely available for use, or false if
--- the operating systems to be using it.
function is_usable (info)
return info.driver and (info.interface == nil or info.status == 'down')
end
--- Force Linux to release the device with `pciaddress`.
--- The corresponding network interface (e.g. `eth0`) will disappear.
function unbind_device_from_linux (pciaddress)
root_check()
local p = path(pciaddress).."/driver/unbind"
if lib.can_write(p) then
lib.writefile(path(pciaddress).."/driver/unbind", pciaddress)
end
end
-- Memory map PCI device configuration space.
-- Return two values:
-- Pointer for memory-mapped access.
-- File descriptor for the open sysfs resource file.
function map_pci_memory (device, n)
root_check()
local filepath = path(device).."/resource"..n
local fd = C.open_pci_resource(filepath)
assert(fd >= 0)
local addr = C.map_pci_resource(fd)
assert( addr ~= 0 )
return addr, fd
end
-- Close a file descriptor opened by map_pci_memory().
function close_pci_resource (fd, base)
C.close_pci_resource(fd, base)
end
--- Enable or disable PCI bus mastering. DMA only works when bus
--- mastering is enabled.
function set_bus_master (device, enable)
root_check()
local fd = C.open_pcie_config(path(device).."/config")
local value = ffi.new("uint16_t[1]")
assert(C.pread(fd, value, 2, 0x4) == 2)
if enable then
value[0] = bit.bor(value[0], lib.bits({Master=2}))
else
value[0] = bit.band(value[0], bit.bnot(lib.bits({Master=2})))
end
assert(C.pwrite(fd, value, 2, 0x4) == 2)
C.close(fd)
end
function root_check ()
lib.root_check("error: must run as root to access PCI devices")
end
--- ### Selftest
---
--- PCI selftest scans for available devices and performs our driver's
--- self-test on each of them.
function selftest ()
print("selftest: pci")
scan_devices()
print_device_summary()
end
function print_device_summary ()
local attrs = {"pciaddress", "vendor", "device", "interface", "status",
"driver", "usable"}
local fmt = "%-13s %-7s %-7s %-10s %-9s %-11s %s"
print(fmt:format(unpack(attrs)))
for _,info in ipairs(devices) do
local values = {}
for _,attr in ipairs(attrs) do
table.insert(values, info[attr] or "-")
end
print(fmt:format(unpack(values)))
end
end
| apache-2.0 |
zturtleman/quakeconstruct | code/debug/lua/levelup/cl_init.lua | 2 | 1986 | print("OPENED CLINIT\n")
local mfuncs = {}
LVcurrentMoney = 0
LVcurrentXP = 0
LVtargetXP = 0
LVlevel = 0
LVweapons = {}
local levelUp = 0
mfuncs[LVMSG_XP_ADDED] = function()
local xp = message.ReadShort()
local money = message.ReadShort()
local source = message.ReadVector()
--print("CL_XP_ADDED: " .. xp .. " : " .. tostring(source) .. "\n")
FX_XPText(xp - LVcurrentXP,source)
LVcurrentXP = xp
LVcurrentMoney = money
end
mfuncs[LVMSG_LEVELUP] = function()
local tXP = message.ReadShort()
local lvl = message.ReadShort()
print("CL_LEVELUP: " .. lvl .. " : " .. tXP .. "\n")
LVtargetXP = tXP
LVlevel = lvl
levelUp = LevelTime()
end
mfuncs[LVMSG_GAMESTATE] = function()
local xp = message.ReadShort()
local tXP = message.ReadShort()
local lvl = message.ReadShort()
local money = message.ReadShort()
local weaps = message.ReadString()
LVweapons = LVDecodeWeapons(weaps)
print("CL_GAMESTATE: " .. xp .. " : " .. tXP .. " : " .. lvl .. "\n")
LVcurrentXP = xp
LVtargetXP = tXP
LVlevel = lvl
LVcurrentMoney = money
end
function requestGameState()
print("CL_RequestingGameState\n")
SendString("lvl_gamestate")
end
local function HandleMessage(msgid)
if(msgid == "levt") then
local t = message.ReadShort()
local b,e = pcall(mfuncs[t])
if(!b) then
print("^1LVERROR: " .. tostring(e) .. "\n")
end
end
end
hook.add("HandleMessage","levelup",HandleMessage)
local function d2d()
draw.SetColor(1,1,1,1)
local wp = ""
for i=WP_GAUNTLET, WP_BFG do
wp = wp .. (LVweapons[i] or "0")
wp = wp .. "|"
end
draw.Text(10,280,"WEAPONS: |" .. wp,15,20)
draw.Text(10,300,"LEVEL-" .. LVlevel,15,20)
draw.Text(10,320,"XP: " .. LVcurrentXP .. "/" .. LVtargetXP .. " | $" .. LVcurrentMoney,15,20)
local lt = (LevelTime() - levelUp) / 8000
if(lt < 1) then
draw.SetColor(0,1,0,1 - lt)
draw.Text(10,340,"LEVEL UP!",10,16)
end
end
hook.add("Draw2D","levelup",d2d)
requestGameState() | gpl-2.0 |
Shayan123456/shayanhhallaji | plugins/Boobs.lua | 150 | 1613 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. ًں”",
"!butts: Get a butts NSFW image. ًں”"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
| gpl-2.0 |
dmccuskey/dmc-gestures | examples/gesture-multigesture-basic/dmc_corona/dmc_gestures/delegate_gesture.lua | 10 | 2729 | --====================================================================--
-- dmc_corona/dmc_gestures/delegate_gesture.lua
--
-- Documentation: http://docs.davidmccuskey.com/
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2015 David McCuskey
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.
--]]
--====================================================================--
--== DMC Corona UI : Gesture Recognizer Delegate
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.1.0"
--- Gesture Recognizer Delegate Interface.
-- the interface for controlling a Gesture Recognizer via a delegate. currently all methods are optional, only implement if needed.
--
-- @classmod Delegate.GestureRecognizer
-- @usage
-- local Gesture = require 'dmc_corona.dmc_gestures'
--
-- -- setup delegate object
-- local delegate = {
-- shouldRecognizeWith=function(self, did_recognize, to_fail )
-- return true
-- end,
-- }
-- @usage
-- local widget = dUI.newPanGesture()
-- widget.delegate = <delgate object>
-- @usage
-- local Gesture = require 'dmc_corona.dmc_gestures'
-- local widget = dUI.newPanGesture{
-- delegate=<delegate object>
-- }
--- (optional) asks delegate if Gesture Recognizer should remain active.
-- return true if Gesture Recognizer should remain, the default return value is `false`.
--
-- @within Methods
-- @function :shouldRecognizeWith
-- @tparam object did_recognize Gesture Recognizer which has Recognized its gesture
-- @tparam object to_fail Gesture Recognizer which is about to be Failed
-- @treturn bool true if Gesture Recognizer `to_fail` should remain.
| mit |
xuqiongkai/GraphBasedRNN | util/util.lua | 1 | 7318 | --------------------------------------------------------------------------------
--
-- Graph-Based Recursive Neural Network for Vertex Classification
-- Copyright (C) 2016-2017 Qiongkai Xu, Chenchen Xu
--
-- 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 3 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, see <http://www.gnu.org/licenses/>.
--
--------------------------------------------------------------------------------
function util.extract_content(content_path, feature_path, label_path, meta_path)
--printf("%s, %s, %s.\n", feature_path, label_path, meta_path)
local content_file = io.open(content_path, 'r')
local line, tokens
local dataset = {}
local sample_num, feature_num = 0, 0
-- write label and calculate sample number
local label_file = io.open(label_path, 'w')
local meta_file = io.open(meta_path, 'w')
local label_set = {}
while true do
line = content_file:read()
if line == nil then break end
tokens = stringx.split(line, "\t")
sample_num = sample_num + 1
feature_num = #tokens - 2
label_file:write(tokens[1].."\t"..tokens[#tokens].."\n")
label_set[tokens[#tokens]] = 1
end
content_file:close()
label_file:close()
--write to meta data
for k, _ in pairs(label_set) do
meta_file:write(k.."\n")
end
meta_file:close()
-- extract features
local features = torch.Tensor(sample_num, feature_num)
sample_num = 0
content_file = io.open(content_path, 'r')
while true do
line = content_file:read()
if line == nil then break end
tokens = stringx.split(line, "\t")
sample_num = sample_num + 1
for i = 2, #tokens - 1 do
features[sample_num][i-1] = tonumber(tokens[i])
end
end
content_file:close()
torch.save(feature_path, features)
end
function util.read_features(feature_path)
return torch.load(feature_path)
end
function util.read_mat_features(feature_path)
local sample_num, feature_num = 0, 0
local feature_file = io.open(feature_path, 'r')
local line, tokens
while true do
line = feature_file:read()
if line == nil then break end
tokens = stringx.split(line, ",")
feature_num = #tokens
sample_num = sample_num + 1
end
feature_file:close()
local features = torch.DoubleTensor(sample_num, feature_num)
sample_num = 0
feature_file = io.open(feature_path, 'r')
while true do
line = feature_file:read()
if line == nil then break end
tokens = stringx.split(line, ",")
sample_num = sample_num + 1
for i = 1, #tokens do
features[sample_num][i] = tonumber(tokens[i])
end
end
return features
end
function util.read_features_text(feature_path, to_feature_path)
local sample_num, feature_num = 0, 0
local feature_file = io.open(feature_path, 'r')
local line, tokens
while true do
line = feature_file:read()
if line == nil then break end
tokens = stringx.split(line, "\t")
feature_num = #tokens
sample_num = sample_num + 1
end
feature_file:close()
local features = torch.DoubleTensor(sample_num, feature_num)
sample_num = 0
feature_file = io.open(feature_path, 'r')
while true do
line = feature_file:read()
if line == nil then break end
tokens = stringx.split(line, "\t")
sample_num = sample_num + 1
for i = 1, #tokens do
features[sample_num][i] = tonumber(tokens[i])
end
end
torch.save(to_feature_path, features)
end
function util.read_labels(label_path)
local label_file = io.open(label_path, 'r')
local i2s, s2i = {}, {}
local labels = {}
local line, tokens
local count = 0
while true do
line = label_file:read()
if line == nil then break end
count = count + 1
tokens = stringx.split(line, "\t")
i2s[count] = tokens[1]
s2i[tokens[1]] = count
labels[tokens[1]] = tokens[2]
end
label_file:close()
return i2s, s2i, labels
end
function util.read_scores(label_path)
local label_file = io.open(label_path, 'r')
local i2s, s2i = {}, {}
local labels = {}
local line, tokens
local count = 0
while true do
line = label_file:read()
if line == nil then break end
count = count + 1
tokens = stringx.split(line, "\t")
i2s[count] = tokens[1]
s2i[tokens[1]] = count
labels[tokens[1]] = torch.Tensor(1):fill(tonumber(tokens[2]))
end
label_file:close()
return i2s, s2i, labels
end
function util.read_meta(meta_path)
local meta_file = io.open(meta_path, 'r')
local map = {}
local count = 0
local line
while true do
line = meta_file:read()
if line == nil then break end
count = count + 1
map[line] = count
end
meta_file:close()
return map, count
end
function util.read_cites(cites_path)
local cites_file = io.open(cites_path, 'r')
local line, tokens
local dataset = {}
local data
while true do
line = cites_file:read()
if line == nil then break end
tokens = stringx.split(line, "\t")
data = dataset[tokens[1]]
if data == nil then data = {} end
data[#data + 1] = tokens[2]
dataset[tokens[1]] = data
end
return dataset
end
function util.generate_indices(sample_num, alpha)
local indices = torch.randperm(sample_num)
--local indices = torch.range(1, sample_num)
local train_num = torch.floor(sample_num * alpha)
local train_indices = torch.range(1, train_num)
local test_indices = torch.range(train_num + 1, sample_num)
local train_indices_set = {}
local test_indices_set = {}
for i = 1,train_indices:size()[1] do
train_indices[i] = indices[train_indices[i]]
train_indices_set[train_indices[i]] = true
end
for i = 1,test_indices:size()[1] do
test_indices[i] = indices[test_indices[i]]
test_indices_set[test_indices[i]] = true
end
return train_indices, test_indices, train_indices_set, test_indices_set
end
function util.best_label(output, label_num)
local prediction = 1
local best_score = -1000
for i = 1, label_num do
if output[i] > best_score then
best_score = output[i]
prediction = i
end
end
return prediction
end
function util.split_string(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={} ; i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end | gpl-3.0 |
Talyrius/Squire3 | Localization.lua | 2 | 14527 | --[[
Squire3 - One-click smart mounting.
(c) 2014 Adirelle (adirelle@gmail.com)
This file is part of Squire3.
Squire3 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 3 of the License, or
(at your option) any later version.
Squire3 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 Squire3. If not, see <http://www.gnu.org/licenses/>.
--]]
local addonName, addon = ...
local L = setmetatable({}, {
__index = function(self, key)
if key ~= nil then
--@debug@
addon.Debug('Missing locale', tostring(key))
--@end-debug@
rawset(self, key, tostring(key))
end
return tostring(key)
end,
})
addon.L = L
--------------------------------------------------------------------------------
-- Locales from localization system
--------------------------------------------------------------------------------
-- %Localization: squire3
-- THE END OF THE FILE IS UPDATED BY https://github.com/Adirelle/wowaceTools/#updatelocalizationphp.
-- ANY CHANGE BELOW THESES LINES WILL BE LOST.
-- UPDATE THE TRANSLATIONS AT http://www.wowace.com/addons/squire3/localization/
-- AND ASK THE AUTHOR TO UPDATE THIS FILE.
-- @noloc[[
------------------------ enUS ------------------------
-- Config.lua
L["Alt"] = true
L["Any"] = true
L["Automatically ..."] = true
L["Blizzard settings"] = true
L["Built-in settings that interacts with shapeshift forms and mounts."] = true
L["Cancel %s"] = true
L["Control"] = true
L["Create and pickup a macro to put in an action slot."] = true
L["Dismount while flying"] = true
L["Dismount"] = true
L["Enforce ground mount modifier"] = true
L["Leave vehicle"] = true
L["Macro"] = true
L["None"] = true
L["Note: these are console variables. They are not affected by profile changes."] = true
L["Options"] = true
L["Select a modifier to enforce a unsafe behavior (like dismount mid-air)."] = true
L["Select a modifier to select a ground mount even in flyable area."] = true
L["Select which action Squire3 should automatically take."] = true
L["Select which spells Squire3 should use."] = true
L["Shift"] = true
L["Two-step mode"] = true
L["Unsafe modifier"] = true
L["Use spells"] = true
L["When enabled, Squire3 will either dismount or mount each click, not both at the same time."] = true
L["When enabled, automatically dismount when you cast a spell mid-air. When disabled, you have to dismount first."] = true
L["When enabled, automatically dismount when you cast a spell. When disabled, you have to dismount first."] = true
L["When enabled, trying to cast a spell normally unavailable to your current shapeshift form automatically cancels it beforehands. When disabled, you have to unshift first."] = true
-- Squire3.lua
L["Use Squire3"] = true
------------------------ frFR ------------------------
local locale = GetLocale()
if locale == 'frFR' then
L["Alt"] = "Alt" -- Needs review
L["Any"] = "N'importe lequel" -- Needs review
L["Automatically ..."] = "Automatiquement ..." -- Needs review
L["Blizzard settings"] = "Réglages Blizzard" -- Needs review
L["Built-in settings that interacts with shapeshift forms and mounts."] = "Réglages intégrés qui interagissent avec les transformations et les montures." -- Needs review
L["Cancel %s"] = "Annuler %s" -- Needs review
L["Control"] = "Ctrl" -- Needs review
L["Create and pickup a macro to put in an action slot."] = "Créer et prend une macro à mettre dans une barre d'action." -- Needs review
L["Dismount"] = "Démonter" -- Needs review
L["Dismount while flying"] = "Démonter en vol" -- Needs review
L["Enforce ground mount modifier"] = "Modificateur pour forcer une monture terrestre" -- Needs review
L["Leave vehicle"] = "Quitter le véhicule" -- Needs review
L["Macro"] = "Macro" -- Needs review
L["None"] = "Aucun" -- Needs review
L["Note: these are console variables. They are not affected by profile changes."] = "Note : ce sont des variables de consoles. Elles ne sont pas affectées par les changements de profil." -- Needs review
L["Options"] = "Options" -- Needs review
L["Select a modifier to enforce a unsafe behavior (like dismount mid-air)."] = "Sélectionner un modificateur pour outrepasser les sécurites (pour démonter en vol par exemple)." -- Needs review
L["Select a modifier to select a ground mount even in flyable area."] = "Sélectionner une modificateur pour sélectionner une monture terrestre dans les zones où le vol est possible." -- Needs review
L["Select which action Squire3 should automatically take."] = "Sélectionner quelles actions Squire3 doit automatiquement entreprendre." -- Needs review
L["Select which spells Squire3 should use."] = "Sélectionenr quels sorts Squire3 peut utiliser." -- Needs review
L["Shift"] = "Maj" -- Needs review
L["Unsafe modifier"] = "Modificateur \"forcer\"" -- Needs review
L["Use spells"] = "Utiliser les sorts" -- Needs review
L["Use Squire3"] = "Utiliser Squire3" -- Needs review
L["When enabled, automatically dismount when you cast a spell mid-air. When disabled, you have to dismount first."] = "Quand actif, démonte automatiquement en vol pour lancer un sort. Quand inactif, il faut démonter d'abord." -- Needs review
L["When enabled, automatically dismount when you cast a spell. When disabled, you have to dismount first."] = "Quand actif, démonte automatiquement pour lancer un sort. Quand inactif, il faut démonter d'abord." -- Needs review
L["When enabled, trying to cast a spell normally unavailable to your current shapeshift form automatically cancels it beforehands. When disabled, you have to unshift first."] = "Quand actif, lancer un sort normalement interdit pour la transformation courante l'annule. Quand inactif, il faut d'abord annuler la transformation." -- Needs review
------------------------ deDE ------------------------
elseif locale == 'deDE' then
L["Alt"] = "ALT"
L["Any"] = "Jeder"
L["Automatically ..."] = "Automatisch..."
L["Blizzard settings"] = "Blizzard-Einstellungen"
L["Cancel %s"] = "%s abbrechen"
L["Control"] = "STRG"
L["Dismount"] = "Absitzen"
L["Dismount while flying"] = "Abzitzen im Flug"
L["Leave vehicle"] = "Fahrzeug verlassen"
L["Macro"] = "Makro"
L["None"] = "Keiner"
L["Options"] = "Einstellungen"
L["Shift"] = "SHIFT"
------------------------ esMX ------------------------
elseif locale == 'esMX' then
L["Alt"] = "Alt"
L["Any"] = "Cualquier"
L["Automatically ..."] = "Automáticamente..."
L["Blizzard settings"] = "Opciones de Blizzard"
L["Built-in settings that interacts with shapeshift forms and mounts."] = "Opciones que se incluyen en el juego y se afectan el comportamiento de formas y monturas."
L["Cancel %s"] = "Cancelar %s"
L["Control"] = "Ctrl"
L["Create and pickup a macro to put in an action slot."] = "Crea y recoge un macro para poner en un botón de acción."
L["Dismount"] = "Desmontar"
L["Dismount while flying"] = "Desmontar en vuelo"
L["Enforce ground mount modifier"] = "Modificador para usar montura de tierra"
L["Leave vehicle"] = "Salir del vehículo"
L["Macro"] = "Macro"
L["None"] = "Ningún"
L["Note: these are console variables. They are not affected by profile changes."] = "Notas: Estos son variables de la consola. Ellas no se ven afectadas por los cambios del perfíl."
L["Options"] = "Opciones"
L["Select a modifier to enforce a unsafe behavior (like dismount mid-air)."] = "Seleccione un modificador para ejecutar un acción inseguro, como desmontar en vuelo."
L["Select a modifier to select a ground mount even in flyable area."] = "Seleccione un modificador para usar una montura de tierra en una zona donde puedes volar."
L["Select which action Squire3 should automatically take."] = "Seleccione el acción que Squire3 debe hacer automáticamente."
L["Select which spells Squire3 should use."] = "Seleccione los hechizos que Squire3 debe usar."
L["Shift"] = "Mayús"
L["Unsafe modifier"] = "Modificador inseguro"
L["Use spells"] = "Usar hechizos"
L["Use Squire3"] = "Usar Squire3"
L["When enabled, automatically dismount when you cast a spell mid-air. When disabled, you have to dismount first."] = "Cuando se activa, desmontas automáticamente al lanzar un hechizo en vuelo. Cuando no se activa, primero debes desmontar."
L["When enabled, automatically dismount when you cast a spell. When disabled, you have to dismount first."] = "Cuando se activa, desmontas automáticamente al lanzar un hechizo. Cuando no se activa, primero debes desmontar."
L["When enabled, trying to cast a spell normally unavailable to your current shapeshift form automatically cancels it beforehands. When disabled, you have to unshift first."] = "Cuando se activa, cancelas automáticamente el cambio de forma al lanzar un hechizo que no puede ser lanzado en tu forma actuál. Cuando no se activa, primero debes cancelar la forma."
------------------------ ruRU ------------------------
-- no translation
------------------------ esES ------------------------
elseif locale == 'esES' then
L["Alt"] = "Alt"
L["Any"] = "Cualquier"
L["Automatically ..."] = "Automáticamente..."
L["Blizzard settings"] = "Opciones de Blizzard"
L["Built-in settings that interacts with shapeshift forms and mounts."] = "Opciones que se incluyen en el juego y se afectan el comportamiento de formas y monturas."
L["Cancel %s"] = "Cancelar %s"
L["Control"] = "Ctrl"
L["Create and pickup a macro to put in an action slot."] = "Crea y recoge un macro para poner en un botón de acción."
L["Dismount"] = "Desmontar"
L["Dismount while flying"] = "Desmontar en vuelo"
L["Enforce ground mount modifier"] = "Modificador para usar montura de tierra"
L["Leave vehicle"] = "Salir del vehículo"
L["Macro"] = "Macro"
L["None"] = "Ningún"
L["Note: these are console variables. They are not affected by profile changes."] = "Notas: Estos son variables de la consola. Ellas no se ven afectadas por los cambios del perfíl."
L["Options"] = "Opciones"
L["Select a modifier to enforce a unsafe behavior (like dismount mid-air)."] = "Seleccione un modificador para ejecutar un acción inseguro, como desmontar en vuelo."
L["Select a modifier to select a ground mount even in flyable area."] = "Seleccione un modificador para usar una montura de tierra en una zona donde puedes volar."
L["Select which action Squire3 should automatically take."] = "Seleccione el acción que Squire3 debe hacer automáticamente."
L["Select which spells Squire3 should use."] = "Seleccione los hechizos que Squire3 debe usar."
L["Shift"] = "Mayús"
L["Unsafe modifier"] = "Modificador inseguro"
L["Use spells"] = "Usar hechizos"
L["Use Squire3"] = "Usar Squire3"
L["When enabled, automatically dismount when you cast a spell mid-air. When disabled, you have to dismount first."] = "Cuando se activa, desmontas automáticamente al lanzar un hechizo en vuelo. Cuando no se activa, primero debes desmontar."
L["When enabled, automatically dismount when you cast a spell. When disabled, you have to dismount first."] = "Cuando se activa, desmontas automáticamente al lanzar un hechizo. Cuando no se activa, primero debes desmontar."
L["When enabled, trying to cast a spell normally unavailable to your current shapeshift form automatically cancels it beforehands. When disabled, you have to unshift first."] = "Cuando se activa, cancelas automáticamente el cambio de forma al lanzar un hechizo que no puede ser lanzado en tu forma actuál. Cuando no se activa, primero debes cancelar la forma."
------------------------ zhTW ------------------------
-- no translation
------------------------ zhCN ------------------------
-- no translation
------------------------ koKR ------------------------
elseif locale == 'koKR' then
L["Alt"] = "Alt"
L["Any"] = "Any"
L["Automatically ..."] = "자동화"
L["Blizzard settings"] = "블리자드 설정"
L["Built-in settings that interacts with shapeshift forms and mounts."] = "태세 변환과 탈것에 대한 행동을 변경하는 설정입니다."
L["Cancel %s"] = "취소 %s"
L["Control"] = "Ctrl"
L["Create and pickup a macro to put in an action slot."] = "매크로를 생성하여 행동 바에 넣습니다."
L["Dismount"] = "해제"
L["Dismount while flying"] = "비행시 해제"
L["Enforce ground mount modifier"] = "지상 탈것 강제 기능키"
L["Leave vehicle"] = "탈것 내리기"
L["Macro"] = "매크로"
L["None"] = "None"
L["Note: these are console variables. They are not affected by profile changes."] = "중요: 이것은 콘솔의 변수입니다. 프로필 변경이 적용되지 않습니다."
L["Options"] = "설정"
L["Select a modifier to enforce a unsafe behavior (like dismount mid-air)."] = "불완전한 행동을 할 수 있는 기능키를 선택합니다. (이를테면 하늘에서 내리기)"
L["Select a modifier to select a ground mount even in flyable area."] = "비행가능 지역에서 지상 탈것으로 선택할 때 기능키를 선택합니다."
L["Select which action Squire3 should automatically take."] = "비행하는 동안 Squire3가 자동으로 진행해야 하는 것을 선택합니다."
L["Select which spells Squire3 should use."] = "Squire3가 사용하는 주문을 선택합니다."
L["Shift"] = "Shift"
L["Unsafe modifier"] = "불완전한 행동 기능키"
L["Use spells"] = "주문 사용"
L["Use Squire3"] = "Squire3 사용"
L["When enabled, automatically dismount when you cast a spell mid-air. When disabled, you have to dismount first."] = "선택하면 하늘에서 주문을 시전하면 자동으로 탈것에서 내립니다. 탈것에서 먼저 내리면 불가능합니다."
L["When enabled, automatically dismount when you cast a spell. When disabled, you have to dismount first."] = "선택하면 주문을 시전할 때 탈것에서 내립니다. 탈것에서 먼저 내리면 불가능합니다."
L["When enabled, trying to cast a spell normally unavailable to your current shapeshift form automatically cancels it beforehands. When disabled, you have to unshift first."] = "선택하면 태세 또는 변신시 사용할 수 없는 주문을 시전할 때 자동으로 먼저 취소합니다. 반드시 변신전에 시전해야 합니다."
------------------------ ptBR ------------------------
-- no translation
end
-- @noloc]]
-- Replace remaining true values by their key
for k,v in pairs(L) do if v == true then L[k] = k end end
| gpl-3.0 |
xing634325131/Luci-0.11.1 | applications/luci-minidlna/luasrc/controller/minidlna.lua | 73 | 1448 | --[[
LuCI - Lua Configuration Interface - miniDLNA support
Copyright 2012 Gabor Juhos <juhosg@openwrt.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$
]]--
module("luci.controller.minidlna", package.seeall)
function index()
if not nixio.fs.access("/etc/config/minidlna") then
return
end
local page
page = entry({"admin", "services", "minidlna"}, cbi("minidlna"), _("miniDLNA"))
page.dependent = true
entry({"admin", "services", "minidlna_status"}, call("minidlna_status"))
end
function minidlna_status()
local sys = require "luci.sys"
local uci = require "luci.model.uci".cursor()
local port = tonumber(uci:get_first("minidlna", "minidlna", "port"))
local status = {
running = (sys.call("pidof minidlna >/dev/null") == 0),
audio = 0,
video = 0,
image = 0
}
if status.running then
local fd = sys.httpget("http://127.0.0.1:%d/" % (port or 8200), true)
if fd then
local html = fd:read("*a")
if html then
status.audio = (tonumber(html:match("Audio files: (%d+)")) or 0)
status.video = (tonumber(html:match("Video files: (%d+)")) or 0)
status.image = (tonumber(html:match("Image files: (%d+)")) or 0)
end
fd:close()
end
end
luci.http.prepare_content("application/json")
luci.http.write_json(status)
end
| apache-2.0 |
zturtleman/quakeconstruct | code/debug/lua/includes/tools.lua | 2 | 12430 | QLUA_DEBUG = false
if(SERVER) then QLUA_DEBUG = false end
--QLUA_DEBUG = true
local logfile = nil
if(SERVER) then
logfile = io.output("sv_lualog.txt", rw)
else
logfile = io.output("cl_lualog.txt", rw)
end
function LOG(str)
logfile:write(tostring(str))
end
LOG("\n\n----LOGGING: " .. os.date("%c") .. "----\n\n")
function CLAMP(v,low,high)
return math.min(high,math.max(low,v))
end
function killGaps(line)
line = string.Replace(line," ","")
line = string.Replace(line,"\t","")
return line
end
function argPack(...)
return arg
end
function boolToInt(b)
if(b == true) then return 1 end
return 0
end
function intToBool(i)
if(i == 0) then return false end
return true
end
function gOR(...)
if(#arg < 2) then return arg[1] or 0 end
local v = arg[1]
for i=2, #arg do
v = bitOr(v,arg[i])
end
return v
end
function gAND(...)
if(#arg < 2) then return arg[1] or 0 end
local v = arg[1]
for i=2, #arg do
v = bitAnd(v,arg[i])
end
return v
end
function entityWaterLevel(pl)
local wtype = 0
local level = 0
local viewHeight = 0
local minZ = -24
local isPL = pl:IsPlayer()
if(isPL) then
if(SERVER) then
viewHeight = util.GetViewHeight(pl)
else
viewHeight = util.GetViewHeight()
end
end
local pos = pl:GetPos()
local o = pos.z
if(isPL) then
pos.z = o + minZ + 1;
end
local cont = util.GetPointContents(pos,pl:EntIndex())
local sample2 = viewHeight - minZ
local sample1 = sample2 / 2
if(isPL) then
if(bitAnd(cont,MASK_WATER) ~= 0) then
wtype = cont
level = 1
pos.z = o + minZ + sample1
cont = util.GetPointContents(pos,pl:EntIndex())
if(bitAnd(cont,MASK_WATER) ~= 0) then
level = 2
pos.z = o + minZ + sample2
cont = util.GetPointContents(pos,pl:EntIndex())
if(bitAnd(cont,MASK_WATER) ~= 0) then
level = 3
end
end
end
end
return level,wtype
--[[ local level = 0
local pos = pl:GetPos()
local mask = gOR(CONTENTS_WATER,CONTENTS_LAVA,CONTENTS_SLIME)
local res = TraceLine(pos + Vector(0,0,28),pos - Vector(0,0,65),pl,mask)
if(res.fraction < .5) then level = 1 end
if(res.fraction < .35) then level = 2 end
if(res.fraction <= 0) then level = 3 end
print(res.fraction .. "\n")
print(bitAnd(res.contents,CONTENTS_LAVA) .. "\n")
return level,res.contents]]
end
function ColorToLong(r,g,b,a)
if (a == nil) then a = 0 end
r = r * 255
g = g * 255
b = b * 255
a = a * 255
if(r > 255) then r = 255 end
if(g > 255) then g = 255 end
if(b > 255) then b = 255 end
if(a > 255) then a = 255 end
if(r < 0) then r = 0 end
if(g < 0) then g = 0 end
if(b < 0) then b = 0 end
if(a < 0) then a = 0 end
local out = 0
g = bitShift(g,-8)
b = bitShift(b,-16)
a = bitShift(a,-24)
return gOR(out,r,g,b,a)
end
function LongToColor(long)
local r = gAND(long,255)/255
local g = gAND(bitShift(long,8),255)/255
local b = gAND(bitShift(long,16),255)/255
local a = gAND(bitShift(long,24),255)/255
return r,g,b,a
end
function lastChar(v)
return string.sub(v,string.len(v),string.len(v))
end
function firstChar(v)
return string.sub(v,1,1)
end
function ProfileFunction(func,...)
local tps = ticksPerSecond()
local s = (ticks() / tps)
pcall(func,arg)
local e = (ticks() / tps)
return (e - s) * 1000
end
function fixcolorstring(s)
while true do
local pos = string.find(s, '^', 0, true)
if (pos == nil) then
break
end
local left = string.sub(s, 1, pos-1)
local right = string.sub(s, pos + 2)
s = left .. right
end
return s
end
function includesimple(s)
include("lua/" .. s .. ".lua")
end
function CurTime()
return LevelTime()/1000
end
function debugprint(msg)
if(QLUA_DEBUG) then
if(SERVER) then
print("SV: " .. msg)
else
print("CL: " .. msg)
end
end
end
function hexFormat(k)
return string.gsub(k, ".", function (c)
return string.format("%02x", string.byte(c))
end)
end
function purgeTable(tab,param,val)
for i=1, #tab do
if(type(tab[i]) == "table") then
if(tab[i][param] == val) then
tab[i][param] = 1
else
tab[i][param] = 0
end
else
local prev = tab[i]
tab[i] = {}
tab[i][param] = 0
tab[i].__prev = prev
end
end
--tab = table.sort(tab,function(a,b) return a[param] > b[param] end)
table.sort(tab,function(a,b) return a[param] > b[param] end)
while(tab[1] != nil and tab[1][param] == 1) do
table.remove(tab,1)
end
for i=1, #tab do
if(tab[i].__prev) then
tab[i] = tab[i].__prev
end
end
return tab
end
function PlayerTrace(...)
local forward = nil
local startpos = nil
local pl = nil
if(SERVER) then
pl = arg[1]
forward = VectorForward(pl:GetAimAngles())
startpos = pl:GetMuzzlePos()
else
pl = LocalPlayer()
forward = _CG.refdef.forward
startpos = _CG.refdef.origin
end
local mask = 1 or arg[2] --Solid
if(CLIENT) then mask = 1 or arg[1] end
local endpos = vAdd(startpos,vMul(forward,16000))
return TraceLine(startpos,endpos,pl,mask)
end
function MethodOfDeathToWeapon(dtype)
local mods = {
[MOD_SHOTGUN] = WP_SHOTGUN,
[MOD_GAUNTLET] = WP_GAUNTLET,
[MOD_MACHINEGUN] = WP_MACHINEGUN,
[MOD_GRENADE] = WP_GRENADE_LAUNCHER,
[MOD_GRENADE_SPLASH] = WP_GRENADE_LAUNCHER,
[MOD_ROCKET] = WP_ROCKET_LAUNCHER,
[MOD_ROCKET_SPLASH] = WP_ROCKET_LAUNCHER,
[MOD_PLASMA] = WP_PLASMAGUN,
[MOD_PLASMA_SPLASH] = WP_PLASMAGUN,
[MOD_RAILGUN] = WP_RAILGUN,
[MOD_LIGHTNING] = WP_LIGHTNING,
[MOD_BFG] = WP_BFG,
[MOD_BFG_SPLASH] = WP_BFG,
[MOD_GRAPPLE] = WP_GRAPPLING_HOOK,
}
return mods[dtype] or WP_NONE
end
if(CLIENT) then
function drawNSBox(x,y,w,h,v,shader,nocenter)
local d = 1/3
draw.Rect(x,y,v,v,shader,0,0,d,d)
draw.Rect(x+v,y,v+(w-v*3),v,shader,d,0,d*2,d)
draw.Rect(x+(w-v),y,v,v,shader,d*2,0,d*3,d)
draw.Rect(x,y+v,v,v+(h-v*3),shader,0,d,d,d*2)
if(!nocenter) then draw.Rect(x+v,y+v,v+(w-v*3),v+(h-(v*3)),shader,d,d,d*2,d*2) end
draw.Rect(x+(w-v),y+v,v,v+(h-(v*3)),shader,d*2,d,d*3,d*2)
draw.Rect(x,y+(h-v),v,v,shader,0,d*2,d,d*3)
draw.Rect(x+v,y+(h-v),v+(w-v*3),v,shader,d,d*2,d*2,d*3)
draw.Rect(x+(w-v),y+(h-v),v,v,shader,d*2,d*2,d*3,d*3)
end
function LoadPlayerModels(pl)
local legs = RefEntity()
local torso = RefEntity()
local head = RefEntity()
local info = pl:GetInfo()
local ghead = info.headModel
local gtorso = info.torsoModel
local glegs = info.legsModel
local headskin = info.headSkin
local torsoskin = info.torsoSkin
local legsskin = info.legsSkin
legs:SetModel(glegs)
legs:SetSkin(legsskin)
torso:SetModel(gtorso)
torso:SetSkin(torsoskin)
head:SetModel(ghead)
head:SetSkin(headskin)
return legs,torso,head
end
function LoadCharacter(char,skin)
local legs = RefEntity()
local torso = RefEntity()
local head = RefEntity()
local info = LocalPlayer():GetInfo()
local ghead = info.headModel
local gtorso = info.torsoModel
local glegs = info.legsModel
local headskin = info.headSkin
local torsoskin = info.torsoSkin
local legsskin = info.legsSkin
if(char != nil) then
skin = skin or "default"
ghead = LoadModel("models/players/" .. char .. "/head.md3")
gtorso = LoadModel("models/players/" .. char .. "/upper.md3")
glegs = LoadModel("models/players/" .. char .. "/lower.md3")
headskin = util.LoadSkin("models/players/" .. char .. "/head_" .. skin .. ".skin")
torsoskin = util.LoadSkin("models/players/" .. char .. "/upper_" .. skin .. ".skin")
legsskin = util.LoadSkin("models/players/" .. char .. "/lower_" .. skin .. ".skin")
end
legs:SetModel(glegs)
legs:SetSkin(legsskin)
torso:SetModel(gtorso)
torso:SetSkin(torsoskin)
head:SetModel(ghead)
head:SetSkin(headskin)
return legs,torso,head
end
function GetMuzzleLocation()
local hand = util.Hand()
local pl = LocalPlayer()
local id = pl:GetInfo().weapon
if(id == WP_NONE) then return Vector() end
local inf = util.WeaponInfo(id)
local ref = RefEntity()
ref:SetModel(inf.weaponModel)
ref:PositionOnTag(hand,"tag_weapon")
local flash = RefEntity()
flash:PositionOnTag(ref,"tag_flash")
return flash:GetPos()
end
function GetTag(ref,tag)
local r = RefEntity()
r:PositionOnTag(ref,tag)
return r:GetPos(),r:GetAxis()
end
function hsv(h,s,v,...)
h = h % 360
local h1 = math.floor((h/60) % 6)
local f = (h / 60) - math.floor(h / 60)
local p = v * (1 - s)
local q = v * (1 - (f * s) )
local t = v * (1 - (1 - f) * s)
local values = {
{v,t,p},
{q,v,p},
{p,v,t},
{p,q,v},
{t,p,v},
{v,p,q}
}
local out = values[h1+1]
if(arg != nil) then
for k,v in pairs(arg) do
table.insert(out,v)
end
end
return unpack(out)
end
local hsvtemp = {}
for i=0,360 do
local r,g,b = hsv(i,1,1)
hsvtemp[i+1] = {r,g,b}
end
function fasthue(h,v,...)
h = h % 360
if(h < 1) then h = 1 end
if(h > 360) then h = 360 end
h = math.ceil(h)
local out = table.Copy(hsvtemp[h])
out[1] = out[1] * v
out[2] = out[2] * v
out[3] = out[3] * v
if(arg != nil) then
for k,v in pairs(arg) do
table.insert(out,v)
end
end
return unpack(out)
end
end
function SetOrigin( ent, origin )
local tr = ent:GetTrajectory()
tr:SetBase(origin)
tr:SetType(TR_STATIONARY)
tr:SetTime(0)
tr:SetDuration(0)
tr:SetDelta(Vector(0,0,0))
ent:SetTrajectory(tr)
end
function BounceEntity(ent,trace,amt)
local tr = ent:GetTrajectory()
local hitTime = LastTime() + ( LevelTime() - LastTime() ) * trace.fraction;
local vel = tr:EvaluateDelta(hitTime)
local dot = DotProduct( vel, trace.normal );
local delta = vAdd(vel,vMul(trace.normal,-2*dot))
delta = vMul(delta,amt or .5)
tr:SetBase(ent:GetPos())
tr:SetDelta(delta)
ent:SetTrajectory(tr)
if ( trace.normal.z > 0 and delta.z < 40 ) then
trace.endpos.z = trace.endpos.z + 1.0
SetOrigin( ent, trace.endpos );
ent:SetGroundEntity(trace.entitynum);
return;
end
ent:SetPos(vAdd(ent:GetPos(),trace.normal))
end
local function MirrorPoint (vec, surface, camera)
local lv = Vector()
local transformed = Vector()
lv = vec - surface.origin
for i=1, 3 do
local d = DotProduct(lv, surface.axis[i]);
transformed = transformed + (camera.axis[i] * d)
end
return transformed + camera.origin
end
local function MirrorVector (vec, surface, camera)
local out = Vector()
for i=1, 3 do
local d = DotProduct(vec, surface.axis[i]);
out = out + (camera.axis[i] * d)
end
return out
end
function LerpReach(lr,id,v,t,thr,s,r)
if(lr == nil or type(lr) != "table") then error("No LerpReach for you :(\n") end
lr[id] = lr[id] or {}
local l = lr[id]
l.t = l.t or t
l.v = l.v or v
l.v = l.v + (l.t - l.v)*s
if(math.abs(l.t-l.v) < thr) then
pcall(r,l)
end
return l.v
end
function DamageInfo(self,inflictor,attacker,damage,meansOfDeath,killed)
local m = "Damaged"
if(killed) then m = "Killed" end
print("A Player Was " .. m .. "\n")
print("INFLICTOR: " .. GetClassname(inflictor) .. "\n")
if(GetClassname(attacker) == "player") then
print("ATTACKER: " .. GetPlayerInfo(attacker)["name"] .. "\n")
else
print("ATTACKER: " .. GetClassname(attacker) .. "\n")
end
print("DAMAGE: " .. damage .. "\n")
print("MOD: " .. meansOfDeath .. "\n")
print("The Target's Name Is: " .. GetPlayerInfo(self)["name"] .. "\n")
end
function QuickParticle(pos,duration,shader,model,angle,scale)
local ref = RefEntity()
ref:SetColor(1,1,1,1)
ref:SetAngles(angle or Vector(0))
ref:Scale(scale or Vector(1,1,1))
ref:SetType(RT_SPRITE)
if(model != nil) then ref:SetType(RT_MODEL) end
if(model != nil) then ref:SetModel(model) end
ref:SetShader(shader)
ref:SetRadius(5)
ref:SetPos(pos)
local le = LocalEntity()
le:SetPos(pos)
le:SetAngles(angle or Vector(0))
le:SetRadius(5)
le:SetRefEntity(ref)
le:SetStartTime(LevelTime())
le:SetEndTime(LevelTime() + duration)
le:SetType(LE_FADE_RGB)
le:SetColor(1,1,1,1)
le:SetTrType(TR_LINEAR)
return le,ref
end
POWERUP_FOREVER = 10000*10000
debugprint("^3Tools loaded.\n") | gpl-2.0 |
McGlaspie/mvm | lua/mvm/PrototypeLab.lua | 1 | 6362 |
Script.Load("lua/mvm/LOSMixin.lua")
Script.Load("lua/mvm/LiveMixin.lua")
Script.Load("lua/mvm/TeamMixin.lua")
Script.Load("lua/mvm/ConstructMixin.lua")
Script.Load("lua/mvm/SelectableMixin.lua")
Script.Load("lua/mvm/GhostStructureMixin.lua")
Script.Load("lua/mvm/DetectableMixin.lua")
Script.Load("lua/mvm/FireMixin.lua")
Script.Load("lua/mvm/WeldableMixin.lua")
Script.Load("lua/mvm/DissolveMixin.lua")
Script.Load("lua/mvm/PowerConsumerMixin.lua")
Script.Load("lua/mvm/SupplyUserMixin.lua")
Script.Load("lua/mvm/NanoshieldMixin.lua")
Script.Load("lua/mvm/ElectroMagneticMixin.lua")
Script.Load("lua/mvm/RagdollMixin.lua")
if Client then
Script.Load("lua/mvm/ColoredSkinsMixin.lua")
Script.Load("lua/mvm/CommanderGlowMixin.lua")
end
local newNetworkVars = {}
AddMixinNetworkVars(FireMixin, newNetworkVars)
AddMixinNetworkVars(DetectableMixin, newNetworkVars)
AddMixinNetworkVars(ElectroMagneticMixin, newNetworkVars)
local kUpdateLoginTime = 0.3
local kAnimationGraph = PrecacheAsset("models/marine/prototype_lab/prototype_lab.animation_graph")
//-----------------------------------------------------------------------------
function PrototypeLab:OnCreate() //OVERRIDES
ScriptActor.OnCreate(self)
InitMixin(self, BaseModelMixin)
InitMixin(self, ModelMixin)
InitMixin(self, LiveMixin)
InitMixin(self, GameEffectsMixin)
InitMixin(self, FlinchMixin)
InitMixin(self, TeamMixin)
InitMixin(self, PointGiverMixin)
InitMixin(self, SelectableMixin)
InitMixin(self, EntityChangeMixin)
InitMixin(self, LOSMixin)
InitMixin(self, CorrodeMixin)
InitMixin(self, ConstructMixin)
InitMixin(self, ResearchMixin)
InitMixin(self, RecycleMixin)
InitMixin(self, RagdollMixin)
InitMixin(self, ObstacleMixin)
InitMixin(self, DissolveMixin)
InitMixin(self, GhostStructureMixin)
InitMixin(self, VortexAbleMixin)
InitMixin(self, PowerConsumerMixin)
InitMixin(self, ParasiteMixin)
InitMixin(self, FireMixin)
InitMixin(self, DetectableMixin)
InitMixin(self, ElectroMagneticMixin)
if Client then
InitMixin(self, CommanderGlowMixin)
InitMixin(self, ColoredSkinsMixin)
end
self:SetLagCompensated(false)
self:SetPhysicsType(PhysicsType.Kinematic)
self:SetPhysicsGroup(PhysicsGroup.BigStructuresGroup)
self.loginEastAmount = 0
self.loginNorthAmount = 0
self.loginWestAmount = 0
self.loginSouthAmount = 0
self.timeScannedEast = 0
self.timeScannedNorth = 0
self.timeScannedWest = 0
self.timeScannedSouth = 0
self.loginNorthAmount = 0
self.loginEastAmount = 0
self.loginSouthAmount = 0
self.loginWestAmount = 0
self.deployed = false
end
/*
function PrototypeLab:OnInitialized() //OVERRIDES
ScriptActor.OnInitialized(self)
self:SetModel(PrototypeLab.kModelName, kAnimationGraph)
InitMixin(self, WeldableMixin)
InitMixin(self, NanoShieldMixin)
if Server then
self.loggedInArray = {false, false, false, false}
self:AddTimedCallback(PrototypeLab.UpdateLoggedIn, kUpdateLoginTime)
// This Mixin must be inited inside this OnInitialized() function.
if not HasMixin(self, "MapBlip") then
InitMixin(self, MapBlipMixin)
end
InitMixin(self, StaticTargetMixin)
//InitMixin(self, InfestationTrackerMixin)
InitMixin(self, SupplyUserMixin)
elseif Client then
InitMixin(self, UnitStatusMixin)
InitMixin(self, HiveVisionMixin)
self:InitializeSkin()
end
end
*/
local orgProtoInit = PrototypeLab.OnInitialized
function PrototypeLab:OnInitialized()
orgProtoInit(self)
if Client then
self:InitializeSkin()
end
end
function PrototypeLab:OverrideVisionRadius()
return 3
end
function PrototypeLab:GetIsVulnerableToEMP()
return false
end
function PrototypeLab:GetTechButtons(techId)
return {
kTechId.JetpackTech, kTechId.None, kTechId.None, kTechId.None,
kTechId.ExosuitTech, kTechId.DualMinigunTech, kTechId.None, kTechId.None
} // kTechId.DualRailgunTech
end
function PrototypeLab:GetItemList(forPlayer)
if forPlayer:isa("Exo") then
if forPlayer:GetHasDualGuns() then
return {}
elseif forPlayer:GetHasRailgun() then
return { kTechId.UpgradeToDualRailgun }
elseif forPlayer:GetHasMinigun() then
return { kTechId.UpgradeToDualMinigun }
end
end
return { kTechId.Jetpack, kTechId.Exosuit, kTechId.ClawRailgunExosuit, }
end
if Client then
function PrototypeLab:InitializeSkin()
self.skinBaseColor = self:GetBaseSkinColor()
self.skinAccentColor = self:GetAccentSkinColor()
self.skinTrimColor = self:GetTrimSkinColor()
self.skinAtlasIndex = 0
end
function PrototypeLab:GetBaseSkinColor()
return ConditionalValue( self:GetTeamNumber() == kTeam2Index, kTeam2_BaseColor, kTeam1_BaseColor )
end
function PrototypeLab:GetAccentSkinColor()
if self:GetIsBuilt() then
return ConditionalValue( self:GetTeamNumber() == kTeam2Index, kTeam2_AccentColor, kTeam1_AccentColor )
else
return Color( 0,0,0 )
end
end
function PrototypeLab:GetTrimSkinColor()
return ConditionalValue( self:GetTeamNumber() == kTeam2Index, kTeam2_TrimColor, kTeam1_TrimColor )
end
function PrototypeLab:OnUse(player, elapsedTime, useSuccessTable)
self:UpdatePrototypeLabWarmUp()
if GetIsUnitActive(self) and not Shared.GetIsRunningPrediction() and not player.buyMenu and self:GetWarmupCompleted() then
if Client.GetLocalPlayer() == player then
Client.SetCursor("ui/Cursor_MarineCommanderDefault.dds", 0, 0)
// Play looping "active" sound while logged in
// Shared.PlayPrivateSound(player, Armory.kResupplySound, player, 1.0, Vector(0, 0, 0))
if player:GetTeamNumber() == kTeam2Index then
MouseTracker_SetIsVisible(true, "ui/Cursor_MenuDefault.dds", true)
else
MouseTracker_SetIsVisible(true, "ui/Cursor_MarineCommanderDefault.dds", true)
end
// tell the player to show the lua menu
player:BuyMenu(self)
end
end
end
end //End Client
//-----------------------------------------------------------------------------
Class_Reload("PrototypeLab", newNetworkVars)
| gpl-3.0 |
szym/turbo | turbo/util.lua | 7 | 10367 | -- Turbo.lua Utilities module.
--
-- Copyright 2011, 2012, 2013, 2014 John Abrahamsen
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local ffi = require "ffi"
local buffer = require "turbo.structs.buffer"
local platform = require "turbo.platform"
local luasocket
if not platform.__LINUX__ or _G.__TURBO_USE_LUASOCKET__ then
luasocket = require "socket"
end
require "turbo.cdef"
local C = ffi.C
local g_time_str_buf, g_time_t, g_timeval
if platform.__LINUX__ and not _G.__TURBO_USE_LUASOCKET__ then
g_time_str_buf = ffi.new("char[1024]")
g_time_t = ffi.new("time_t[1]")
g_timeval = ffi.new("struct timeval")
end
local util = {}
--*************** String library extensions ***************
--- Extends the standard string library with a split method.
function string:split(sep, max, pattern)
assert(sep ~= '', "Separator is not a string or a empty string.")
assert(max == nil or max >= 1, "Max is 0 or a negative number.")
local record = {}
if self:len() > 0 then
local plain = not pattern
max = max or -1
local field=1 start=1
local first, last = self:find(sep, start, plain)
while first and max ~= 0 do
record[field] = self:sub(start, first-1)
field = field+1
start = last+1
first, last = self:find(sep, start, plain)
max = max-1
end
record[field] = self:sub(start)
end
return record
end
-- strip white space from sides of a string
function string:strip()
return self:match("^%s*(.-)%s*$")
end
--- Create substring from.
-- Beware that index starts at 0.
-- @param from From index, can be nil to indicate start.
-- @param to To index, can be nil to indicate end.
-- @return string
function string:substr(from, to)
local len = self:len()
from = from or 0
to = to or len
assert(from < len, "From out of range.")
assert(to <= len, "To out of range.")
assert(from < to, "From greater than to.")
local ptr = ffi.cast("char *", self)
return ffi.string(ptr + from, to - from)
end
--- Create a random string.
function util.rand_str(len)
math.randomseed(util.gettimeofday()+math.random(0x0,0xffffffff))
len = len or 64
local bytes = buffer(len)
for i = 1, len do
bytes:append_char_right(ffi.cast("char", math.random(0x0, 0x80)))
end
bytes = tostring(bytes)
return bytes
end
--*************** Table utilites ***************
--- Merge two tables to one.
function util.tablemerge(t1, t2)
for k, v in pairs(t2) do
if (type(v) == "table") and (type(t1[k] or false) == "table") then
util.tablemerge(t1[k], t2[k])
else
t1[k] = v
end
end
return t1
end
--- Join a list into a string with given delimiter.
function util.join(delimiter, list)
local len = #list
if len == 0 then
return ""
end
local string = list[1]
for i = 2, len do
string = string .. delimiter .. list[i]
end
return string
end
--- Returns true if value exists in table.
function util.is_in(needle, haystack)
if not needle or not haystack then
return nil
end
local i
for i = 1, #haystack, 1 do
if needle == haystack[i] then
return true
end
end
return
end
--- unpack that does not cause trace abort.
-- May not be very fast if large tables are unpacked.
function util.funpack(t, i)
i = i or 1
if t[i] ~= nil then
return t[i], util.funpack(t, i + 1)
end
end
--*************** Time and date ***************
--- Current msecs since epoch. Better granularity than Lua builtin.
-- @return Number
if platform.__LINUX__ and not _G.__TURBO_USE_LUASOCKET__ then
function util.gettimeofday()
C.gettimeofday(g_timeval, nil)
return (tonumber((g_timeval.tv_sec * 1000)+
(g_timeval.tv_usec / 1000)))
end
else
function util.gettimeofday()
return math.ceil(luasocket.gettime() * 1000)
end
end
do
local rt_support, rt = pcall(ffi.load, "rt")
if not rt_support or _G.__TURBO_USE_LUASOCKET__ then
util.gettimemonotonic = util.gettimeofday
else
local ts = ffi.new("struct timespec")
-- Current msecs since arbitrary start point, doesn't jump due to
-- time changes
-- @return Number
function util.gettimemonotonic()
rt.clock_gettime(rt.CLOCK_MONOTONIC, ts)
return (tonumber((ts.tv_sec*1000)+(ts.tv_nsec/1000000)))
end
end
end
--- Create a time string used in HTTP cookies.
-- "Sun, 04-Sep-2033 16:49:21 GMT"
if platform.__LINUX__ and not _G.__TURBO_USE_LUASOCKET__ then
function util.time_format_cookie(epoch)
g_time_t[0] = epoch
local tm = C.gmtime(g_time_t)
local sz = C.strftime(
g_time_str_buf,
1024,
"%a, %d-%b-%Y %H:%M:%S GMT",
tm)
return ffi.string(g_time_str_buf, sz)
end
else
function util.time_format_cookie(time)
return os.date(
"%a, %d-%b-%Y %H:%M:%S GMT",
time)
end
end
if platform.__LINUX__ and not _G.__TURBO_USE_LUASOCKET__ then
--- Create a time string used in HTTP header fields.
-- "Sun, 04 Sep 2033 16:49:21 GMT"
function util.time_format_http_header(time_t)
g_time_t[0] = time_t
local tm = C.gmtime(g_time_t)
local sz = C.strftime(
g_time_str_buf,
1024,
"%a, %d %b %Y %H:%M:%S GMT",
tm)
return ffi.string(g_time_str_buf, sz)
end
else
function util.time_format_http_header(time)
return os.date(
"%a, %d %b %Y %H:%M:%S GMT",
time / 1000)
end
end
--*************** File ***************
--- Check if file exists on local filesystem.
-- @param path Full path to file
-- @return True or false.
function util.file_exists(path)
local f = io.open(path, "r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
function util.read_all(file)
local f = io.open(file, "rb")
assert(f, "Could not open file " .. file .. " for reading.")
local content = f:read("*all")
f:close()
return content
end
--******** Low-level buffer search *********
-- Fast string case agnostic comparison
function util.strcasecmp(str1, str2)
return tonumber(ffi.C.strcasecmp(str1, str2))
end
--- Find substring in memory string.
-- Based on lj_str_find in lj_str.c in LuaJIT by Mike Pall.
function util.str_find(s, p, slen, plen)
if plen <= slen then
if plen == 0 then
return s
else
local c = ffi.cast("int", p[0])
p = p + 1
plen = plen - 1
slen = slen - plen
local q
while slen > 0 do
q = ffi.cast("char*", C.memchr(s, c, slen))
if q == nil then
break
end
if C.memcmp(q + 1, p, plen) == 0 then
return q
end
q = q + 1
slen = slen - (q - s)
s = q
end
end
end
end
--- Turbo Booyer-Moore memory search algorithm.
-- DEPRECATED as of v.1.1.
-- @param x char* Needle memory pointer
-- @param m int Needle size
-- @param y char* Haystack memory pointer
-- @param n int Haystack size.
function util.TBM(x, m, y, n)
log.warning("turbo.util.TBM is deprecated.")
return util.str_find(y, x, n, m)
end
--- Convert number value to hexadecimal string format.
-- @param num The number to convert.
-- @return String
function util.hex(num)
local hexstr = '0123456789abcdef'
local s = ''
while num > 0 do
local mod = math.fmod(num, 16)
s = string.sub(hexstr, mod+1, mod+1) .. s
num = math.floor(num / 16)
end
if s == '' then
s = '0'
end
return s
end
local hex = util.hex
--- Dump memory region to stdout, from ptr to given size. Usefull for
-- debugging Luajit FFI. Notice! This can and will cause a SIGSEGV if
-- not being used on valid pointers.
-- @param ptr A cdata pointer (from FFI)
-- @param sz (Number) Length to dump contents for.
function util.mem_dump(ptr, sz)
local voidptr = ffi.cast("unsigned char *", ptr)
if not voidptr then
error("Trying to dump null ptr")
end
io.write(string.format("Pointer type: %s\
From memory location: 0x%s dumping %d bytes\n",
ffi.typeof(ptr),
hex(tonumber(ffi.cast("intptr_t", voidptr))),
sz))
local p = 0;
local sz_base_1 = sz - 1
for i = 0, sz_base_1 do
if (p == 10) then
p = 0
io.write("\n")
end
local hex_string
if (voidptr[i] < 0xf) then
hex_string = string.format("0x0%s ", hex(voidptr[i]))
else
hex_string = string.format("0x%s ", hex(voidptr[i]))
end
io.write(hex_string)
p = p + 1
end
io.write("\n")
end
--- Loads dynamic library with helper functions or bails out with error.
-- @param name Custom library name or path
function util.load_libtffi(name)
local have_name = name and true or false
name = name or os.getenv("TURBO_LIBTFFI") or "libtffi_wrap"
local ok, lib = pcall(ffi.load, name)
if not ok then
-- Try the old loading method which works for some Linux distros.
-- But only if name is not given as argument.
if not have_name then
ok, lib = pcall(ffi.load, "/usr/local/lib/libtffi_wrap.so")
end
if not ok then
-- Still not OK...
error("Could not load " .. name .. " \
Please run makefile and ensure that installation is done correct.")
end
end
return lib
end
return util
| apache-2.0 |
helkarakse/Miscellaneous | src/upload/upload.lua | 1 | 1984 | --[[
TickDump Version 0.1 Dev
Do not modify, copy or distribute without permission of author
Helkarakse, 20131210
]]
-- Libraries
os.loadAPI("functions")
os.loadAPI("json")
-- Variables
local fileName = "profile.txt"
local dimension = string.sub(os.getComputerLabel(), 1, 1)
local server = string.lower(string.sub(os.getComputerLabel(), 2))
local outputText, map = "", nil
local currentFileSize = 0
local uploadDelay = 30
local urlPush = "http://dev.otegamers.com/api/v1/tps/put/" .. server .. "/" .. dimension
-- Functions
local uploadLoop = function()
while true do
-- only push the document if it changes
if (fs.getSize(fileName) ~= currentFileSize) then
-- check if the file exists
if (fs.exists(fileName)) then
-- file exists, store in outputText in preparation to send
local file = fs.open(fileName, "r")
outputText = file.readAll()
file.close()
end
-- update the file size to the new one
currentFileSize = fs.getSize(fileName)
-- -- get the current array of players ingame
-- local playerArray = map.getPlayerUsernames()
-- local response = http.post(urlPush, "json=" .. textutils.urlEncode(outputText) .. "&players=" .. textutils.urlEncode(json.encode(playerArray)))
local response = http.post(urlPush, "json=" .. textutils.urlEncode(outputText))
if (response) then
local responseText = response.readAll()
functions.debug(responseText)
response.close()
else
functions.debug("Warning: Failed to retrieve response from server")
end
end
sleep(uploadDelay)
end
end
local function init()
-- functions.debug("URL is: " .. urlPush);
--
-- local hasMap, mapDir = functions.locatePeripheral("adventure map interface")
-- if (hasMap) then
-- map = peripheral.wrap(mapDir)
-- functions.debug("Map peripheral detected and wrapped.")
-- else
-- functions.debug("No map peripheral detected.")
-- return;
-- end
if (fs.exists(fileName)) then
parallel.waitForAll(uploadLoop)
end
end
init() | gpl-2.0 |
MrCerealGuy/Stonecraft | clientmods/preview/init.lua | 1 | 5946 | local modname = assert(core.get_current_modname())
local modstorage = core.get_mod_storage()
local mod_channel
dofile(core.get_modpath(modname) .. "example.lua")
core.register_on_shutdown(function()
print("[PREVIEW] shutdown client")
end)
local id = nil
do
local server_info = core.get_server_info()
print("Server version: " .. server_info.protocol_version)
print("Server ip: " .. server_info.ip)
print("Server address: " .. server_info.address)
print("Server port: " .. server_info.port)
print("CSM restrictions: " .. dump(core.get_csm_restrictions()))
local l1, l2 = core.get_language()
print("Configured language: " .. l1 .. " / " .. l2)
end
mod_channel = core.mod_channel_join("experimental_preview")
core.after(4, function()
if mod_channel:is_writeable() then
mod_channel:send_all("preview talk to experimental")
end
end)
core.after(1, function()
print("armor: " .. dump(core.localplayer:get_armor_groups()))
id = core.localplayer:hud_add({
hud_elem_type = "text",
name = "example",
number = 0xff0000,
position = {x=0, y=1},
offset = {x=8, y=-8},
text = "You are using the preview mod",
scale = {x=200, y=60},
alignment = {x=1, y=-1},
})
end)
core.register_on_modchannel_message(function(channel, sender, message)
print("[PREVIEW][modchannels] Received message `" .. message .. "` on channel `"
.. channel .. "` from sender `" .. sender .. "`")
core.after(1, function()
mod_channel:send_all("CSM preview received " .. message)
end)
end)
core.register_on_modchannel_signal(function(channel, signal)
print("[PREVIEW][modchannels] Received signal id `" .. signal .. "` on channel `"
.. channel)
end)
core.register_on_inventory_open(function(inventory)
print("INVENTORY OPEN")
print(dump(inventory))
return false
end)
core.register_on_placenode(function(pointed_thing, node)
print("The local player place a node!")
print("pointed_thing :" .. dump(pointed_thing))
print("node placed :" .. dump(node))
return false
end)
core.register_on_item_use(function(itemstack, pointed_thing)
print("The local player used an item!")
print("pointed_thing :" .. dump(pointed_thing))
print("item = " .. itemstack:get_name())
if not itemstack:is_empty() then
return false
end
local pos = core.camera:get_pos()
local pos2 = vector.add(pos, vector.multiply(core.camera:get_look_dir(), 100))
local rc = core.raycast(pos, pos2)
local i = rc:next()
print("[PREVIEW] raycast next: " .. dump(i))
if i then
print("[PREVIEW] line of sight: " .. (core.line_of_sight(pos, i.above) and "yes" or "no"))
local n1 = core.find_nodes_in_area(pos, i.under, {"default:stone"})
local n2 = core.find_nodes_in_area_under_air(pos, i.under, {"default:stone"})
print(("[PREVIEW] found %s nodes, %s nodes under air"):format(
n1 and #n1 or "?", n2 and #n2 or "?"))
end
return false
end)
-- This is an example function to ensure it's working properly, should be removed before merge
core.register_on_receiving_chat_message(function(message)
print("[PREVIEW] Received message " .. message)
return false
end)
-- This is an example function to ensure it's working properly, should be removed before merge
core.register_on_sending_chat_message(function(message)
print("[PREVIEW] Sending message " .. message)
return false
end)
core.register_on_chatcommand(function(command, params)
print("[PREVIEW] caught command '"..command.."'. Parameters: '"..params.."'")
end)
-- This is an example function to ensure it's working properly, should be removed before merge
core.register_on_hp_modification(function(hp)
print("[PREVIEW] HP modified " .. hp)
end)
-- This is an example function to ensure it's working properly, should be removed before merge
core.register_on_damage_taken(function(hp)
print("[PREVIEW] Damage taken " .. hp)
end)
-- This is an example function to ensure it's working properly, should be removed before merge
core.register_chatcommand("dump", {
func = function(param)
return true, dump(_G)
end,
})
local function preview_minimap()
local minimap = core.ui.minimap
if not minimap then
print("[PREVIEW] Minimap is disabled. Skipping.")
return
end
minimap:set_mode(4)
minimap:show()
minimap:set_pos({x=5, y=50, z=5})
minimap:set_shape(math.random(0, 1))
print("[PREVIEW] Minimap: mode => " .. dump(minimap:get_mode()) ..
" position => " .. dump(minimap:get_pos()) ..
" angle => " .. dump(minimap:get_angle()))
end
core.after(2, function()
print("[PREVIEW] loaded " .. modname .. " mod")
modstorage:set_string("current_mod", modname)
assert(modstorage:get_string("current_mod") == modname)
preview_minimap()
end)
core.after(5, function()
if core.ui.minimap then
core.ui.minimap:show()
end
print("[PREVIEW] Time of day " .. core.get_timeofday())
print("[PREVIEW] Node level: " .. core.get_node_level({x=0, y=20, z=0}) ..
" max level " .. core.get_node_max_level({x=0, y=20, z=0}))
print("[PREVIEW] Find node near: " .. dump(core.find_node_near({x=0, y=20, z=0}, 10,
{"group:tree", "default:dirt", "default:stone"})))
end)
core.register_on_dignode(function(pos, node)
print("The local player dug a node!")
print("pos:" .. dump(pos))
print("node:" .. dump(node))
return false
end)
core.register_on_punchnode(function(pos, node)
print("The local player punched a node!")
local itemstack = core.localplayer:get_wielded_item()
print(dump(itemstack:to_table()))
print("pos:" .. dump(pos))
print("node:" .. dump(node))
local meta = core.get_meta(pos)
print("punched meta: " .. (meta and dump(meta:to_table()) or "(missing)"))
return false
end)
core.register_chatcommand("privs", {
func = function(param)
return true, core.privs_to_string(minetest.get_privilege_list())
end,
})
core.register_chatcommand("text", {
func = function(param)
return core.localplayer:hud_change(id, "text", param)
end,
})
core.register_on_mods_loaded(function()
core.log("Yeah preview mod is loaded with other CSM mods.")
end)
| gpl-3.0 |
Happy-Neko/xupnpd | src/xupnpd_http.lua | 1 | 14519 | -- Copyright (C) 2011 Anton Burdinuk
-- clark15b@gmail.com
-- https://tsdemuxer.googlecode.com/svn/trunk/xupnpd
http_mime={}
http_err={}
http_vars={}
-- http_mime types
http_mime['html']='text/html'
http_mime['htm']='text/html'
http_mime['xml']='text/xml; charset="UTF-8"'
http_mime['txt']='text/plain'
http_mime['cpp']='text/plain'
http_mime['h']='text/plain'
http_mime['lua']='text/plain'
http_mime['jpg']='image/jpeg'
http_mime['png']='image/png'
http_mime['ico']='image/vnd.microsoft.icon'
http_mime['mpeg']='video/mpeg'
http_mime['css']='text/css'
http_mime['json']='application/json'
http_mime['js']='application/javascript'
http_mime['m3u']='audio/x-mpegurl'
-- http http_error list
http_err[100]='Continue'
http_err[101]='Switching Protocols'
http_err[200]='OK'
http_err[201]='Created'
http_err[202]='Accepted'
http_err[203]='Non-Authoritative Information'
http_err[204]='No Content'
http_err[205]='Reset Content'
http_err[206]='Partial Content'
http_err[300]='Multiple Choices'
http_err[301]='Moved Permanently'
http_err[302]='Moved Temporarily'
http_err[303]='See Other'
http_err[304]='Not Modified'
http_err[305]='Use Proxy'
http_err[400]='Bad Request'
http_err[401]='Unauthorized'
http_err[402]='Payment Required'
http_err[403]='Forbidden'
http_err[404]='Not Found'
http_err[405]='Method Not Allowed'
http_err[406]='Not Acceptable'
http_err[407]='Proxy Authentication Required'
http_err[408]='Request Time-Out'
http_err[409]='Conflict'
http_err[410]='Gone'
http_err[411]='Length Required'
http_err[412]='Precondition Failed'
http_err[413]='Request Entity Too Large'
http_err[414]='Request-URL Too Large'
http_err[415]='Unsupported Media Type'
http_err[416]='Requested range not satisfiable'
http_err[500]='Internal Server http_error'
http_err[501]='Not Implemented'
http_err[502]='Bad Gateway'
http_err[503]='Out of Resources'
http_err[504]='Gateway Time-Out'
http_err[505]='HTTP Version not supported'
http_vars['fname']=cfg.name
http_vars['manufacturer']=util.xmlencode('Anton Burdinuk <clark15b@gmail.com>')
http_vars['manufacturer_url']=''
http_vars['description']=ssdp_server
http_vars['name']='xupnpd'
http_vars['version']=cfg.version
http_vars['url']='http://xupnpd.org'
http_vars['uuid']=ssdp_uuid
http_vars['interface']=ssdp.interface()
http_vars['port']=cfg.http_port
http_templ=
{
'/dev.xml',
'/wmc.xml',
'/index.html'
}
dofile('xupnpd_soap.lua')
function http_send_headers(err,ext,len)
http.send(
string.format(
'HTTP/1.1 %i %s\r\nPragma: no-cache\r\nCache-control: no-cache\r\nDate: %s\r\nServer: %s\r\nAccept-Ranges: none\r\n'..
'Connection: close\r\nContent-Type: %s\r\nEXT:\r\n',
err,http_err[err] or 'Unknown',os.date('!%a, %d %b %Y %H:%M:%S GMT'),ssdp_server,http_mime[ext] or 'application/x-octet-stream')
)
if len then http.send(string.format("Content-Length: %s\r\n",len)) end
http.send("\r\n")
if cfg.debug>0 and err~=200 then print('http error '..err) end
end
function get_soap_method(s)
local i=string.find(s,'#',1)
if not i then return s end
return string.sub(s,i+1)
end
function plugin_sendurl_from_cache(url,range)
local c=cache[url]
if c and c.value then
if cfg.debug>0 then print('Cache URL: '..c.value) end
if http.sendurl(c.value,1,range)==0 then return false end
return true
end
return false
end
function plugin_sendurl(url,real_url,range)
local rc,location
location=real_url
for i=1,5,1 do
core.sendevent('store',url,location)
rc,location=http.sendurl(location,1,range)
if not location then
break
else
if cfg.debug>0 then print('Redirect #'..i..' to: '..location) end
end
end
end
function plugin_sendfile(path)
local len=util.getflen(path)
if len then
http.send(string.format('Content-Length: %s\r\n\r\n',len))
http.sendfile(path)
else
http.send('\r\n')
end
end
function plugin_download(url)
local data,location
location=url
for i=1,5,1 do
data,location=http.download(location)
if not location then
return data
else
if cfg.debug>0 then print('Redirect #'..i..' to: '..location) end
end
end
return nil
end
function http_handler(what,from,port,msg)
if not msg or not msg.reqline then return end
local ui_main=cfg.ui_path..'xupnpd_ui.lua'
if msg.reqline[2]=='/' then
if util.getflen(ui_main) then
msg.reqline[2]='/ui'
else
msg.reqline[2]='/index.html'
end
end
local head=false
local f=util.geturlinfo(cfg.www_root,msg.reqline[2])
if not f or (msg.reqline[3]~='HTTP/1.0' and msg.reqline[3]~='HTTP/1.1') then
http_send_headers(400)
return
end
if cfg.debug>0 then print(from..' '..msg.reqline[1]..' '..msg.reqline[2]..' \"'..(msg['user-agent'] or '')..'\"') end
local from_ip=string.match(from,'(.+):.+')
if string.find(f.url,'^/ui/?') then
if util.getflen(ui_main) then
dofile(ui_main)
ui_handler(f.args,msg.data or '',from_ip,f.url)
else
http_send_headers(404)
end
return
end
if msg.reqline[1]=='HEAD' then head=true msg.reqline[1]='GET' end
if msg.reqline[1]=='POST' then
if f.url=='/soap' then
if cfg.debug>0 then print(from..' SOAP '..(msg.soapaction or '')) end
http_send_headers(200,'xml')
local err=true
local s=services[ f.args['s'] ]
if s then
local func_name=get_soap_method(msg.soapaction or '')
local func=s[func_name]
if func then
if cfg.debug>1 then print(msg.data) end
local r=soap.find('Envelope/Body/'..func_name,soap.parse(msg.data))
r=func(r or {},from_ip)
if r then
local resp=
string.format(
'<?xml version=\"1.0\" encoding=\"utf-8\"?>'..
'<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">'..
'<s:Body><u:%sResponse xmlns:u=\"%s\">%s</u:%sResponse></s:Body></s:Envelope>',
func_name,s.schema,soap.serialize_vector(r),func_name)
http.send(resp)
if cfg.debug>2 then print(resp) end
err=false
end
end
end
if err==true then
http.send(
'<?xml version=\"1.0\" encoding=\"utf-8\"?>'..
'<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">'..
'<s:Body>'..
'<s:Fault>'..
'<faultcode>s:Client</faultcode>'..
'<faultstring>UPnPError</faultstring>'..
'<detail>'..
'<u:UPnPError xmlns:u=\"urn:schemas-upnp-org:control-1-0\">'..
'<u:errorCode>501</u:errorCode>'..
'<u:errorDescription>Action Failed</u:errorDescription>'..
'</u:UPnPError>'..
'</detail>'..
'</s:Fault>'..
'</s:Body>'..
'</s:Envelope>'
)
if cfg.debug>0 then print('upnp error 501') end
end
else
http_send_headers(404)
end
elseif msg.reqline[1]=='SUBSCRIBE' then
local ttl=1800
local sid=core.uuid()
if f.args.s then
core.sendevent('subscribe',f.args.s,sid,string.match(msg.callback,'<(.+)>'),ttl)
end
http.send(
string.format(
'HTTP/1.1 200 OK\r\nPragma: no-cache\r\nCache-control: no-cache\r\nDate: %s\r\nServer: %s\r\nAccept-Ranges: none\r\n'..
'Connection: close\r\nEXT:\r\nSID: uuid:%s\r\nTIMEOUT: Second-%d\r\n\r\n',
os.date('!%a, %d %b %Y %H:%M:%S GMT'),ssdp_server,sid,ttl))
elseif msg.reqline[1]=='UNSUBSCRIBE' then
core.sendevent('unsubscribe',string.match(msg.sid or '','uuid:(.+)'))
http.send(
string.format(
'HTTP/1.1 200 OK\r\nPragma: no-cache\r\nCache-control: no-cache\r\nDate: %s\r\nServer: %s\r\nAccept-Ranges: none\r\n'..
'Connection: close\r\nEXT:\r\n\r\n',
os.date('!%a, %d %b %Y %H:%M:%S GMT'),ssdp_server))
elseif msg.reqline[1]=='GET' then
if cfg.xbox360==true then
local t=split_string(f.url,'/')
if table.maxn(t)==2 then
if not f.args then f.args={} end
f.args['s']=util.urldecode(t[2])
if t[1]=='p' then f.url='/proxy' elseif t[1]=='s' then f.url='/stream' end
end
end
if f.url=='/proxy' then
local pls=find_playlist_object(f.args['s'] or '')
if not pls then http_send_headers(404) return end
http.send(string.format(
'HTTP/1.1 200 OK\r\nPragma: no-cache\r\nCache-control: no-cache\r\nDate: %s\r\nServer: %s\r\n'..
'Connection: close\r\nContent-Type: %s\r\nEXT:\r\nTransferMode.DLNA.ORG: Streaming\r\n',
os.date('!%a, %d %b %Y %H:%M:%S GMT'),ssdp_server,pls.mime[3]))
http.send('ContentFeatures.DLNA.ORG: '..pls.dlna_extras..'\r\n')
if cfg.wdtv==true then
http.send('Content-Size: 65535\r\n')
http.send('Content-Length: 65535\r\n')
end
if head==true then
http.send('\r\n')
http.flush()
else
if pls.event then core.sendevent(pls.event,pls.url) end
if cfg.debug>0 then print(from..' PROXY '..pls.url..' <'..pls.mime[3]..'>') end
core.sendevent('status',util.getpid(),from_ip..' '..pls.name)
if pls.plugin then
http.send('Accept-Ranges: bytes\r\n')
http.flush() -- PS3 YouTube network error fix?
plugins[pls.plugin].sendurl(pls.url,msg.range)
else
http.send('Accept-Ranges: none\r\n\r\n')
if string.find(pls.url,'^udp://@') then
http.sendmcasturl(string.sub(pls.url,8),cfg.mcast_interface,2048)
else
http.sendurl(pls.url)
end
end
end
elseif f.url=='/stream' then
local pls=find_playlist_object(f.args['s'] or '')
if not pls or not pls.path then http_send_headers(404) return end
local flen=pls.length
local ffrom=0
local flen_total=flen
if msg.range and flen and flen>0 then
local f,t=string.match(msg.range,'bytes=(.*)-(.*)')
f=tonumber(f)
t=tonumber(t)
if not f then f=0 end
if not t then t=flen-1 end
if f>t or t+1>flen then http_send_headers(416) return end
ffrom=f
flen=t-f+1
end
http.send(string.format(
'HTTP/1.1 200 OK\r\nPragma: no-cache\r\nCache-control: no-cache\r\nDate: %s\r\nServer: %s\r\n'..
'Connection: close\r\nContent-Type: %s\r\nEXT:\r\nTransferMode.DLNA.ORG: Streaming\r\n',
os.date('!%a, %d %b %Y %H:%M:%S GMT'),ssdp_server,pls.mime[3]))
if flen then
http.send(string.format('Accept-Ranges: bytes\r\nContent-Length: %s\r\n',flen))
else
http.send('Accept-Ranges: none\r\n')
end
local dlna_extras=pls.dlna_extras
if dlna_extras~='*' then
dlna_extras=string.gsub(dlna_extras,'DLNA.ORG_OP=%d%d','DLNA.ORG_OP=11')
end
http.send('ContentFeatures.DLNA.ORG: '..dlna_extras..'\r\n')
if msg.range and flen and flen>0 then
http.send(string.format('Content-Range: bytes %s-%s/%s\r\n',ffrom,ffrom+flen-1,flen_total))
end
http.send('\r\n')
http.flush()
if head~=true then
if pls.event then core.sendevent(pls.event,pls.path) end
if cfg.debug>0 then print(from..' STREAM '..pls.path..' <'..pls.mime[3]..'>') end
core.sendevent('status',util.getpid(),from_ip..' '..pls.name)
http.sendfile(pls.path,ffrom,flen)
end
elseif f.url=='/reload' then
http_send_headers(200,'txt')
if head~=true then
http.send('OK')
core.sendevent('reload')
end
else
if f.type=='none' then http_send_headers(404) return end
if f.type~='file' then http_send_headers(403) return end
local tmpl=false
for i,fname in ipairs(http_templ) do
if f.url==fname then tmpl=true break end
end
local len=nil
if not tmpl then len=f.length end
http.send(
string.format(
'HTTP/1.1 200 OK\r\nDate: %s\r\nServer: %s\r\nAccept-Ranges: none\r\nConnection: close\r\nContent-Type: %s\r\nEXT:\r\n',
os.date('!%a, %d %b %Y %H:%M:%S GMT'),ssdp_server,http_mime[f.ext] or 'application/x-octet-stream'))
if len then
http.send(string.format('Content-Length: %s\r\n',len))
end
if tmpl then
http.send('Pragma: no-cache\r\nCache-control: no-cache\r\n')
end
http.send('\r\n')
if head~=true then
if cfg.debug>0 then print(from..' FILE '..f.path) end
if tmpl then http.sendtfile(f.path,http_vars) else http.sendfile(f.path) end
end
end
else
http_send_headers(405)
end
http.flush()
end
events["http"]=http_handler
http.listen(cfg.http_port,"http")
| gpl-2.0 |
MrCerealGuy/Stonecraft | games/stonecraft_game/mods/skinsdb/skins_updater.lua | 1 | 4323 | -- Skins update script
local S = minetest.get_translator("skinsdb")
local _ID_ = "Lua Skins Updater"
local internal = {}
internal.errors = {}
-- Binary downloads are required
if not core.features.httpfetch_binary_data then
internal.errors[#internal.errors + 1] =
"Feature 'httpfetch_binary_data' is missing. Update Minetest."
end
-- Insecure environment for saving textures and meta
local ie, http = skins.ie, skins.http
if not ie or not http then
internal.errors[#internal.errors + 1] = "Insecure environment is required. " ..
"Please add skinsdb to `secure.trusted_mods` in minetest.conf"
end
minetest.register_chatcommand("skinsdb_download_skins", {
params = "<skindb start page> <amount of pages>",
description = S("Downloads the specified range of skins and shuts down the server"),
privs = {server=true},
func = function(name, param)
if #internal.errors > 0 then
return false, "Cannot run " .. _ID_ .. ":\n\t" ..
table.concat(internal.errors, "\n\t")
end
local parts = string.split(param, " ")
local start = tonumber(parts[1])
local len = tonumber(parts[2])
if not (start and len and len > 0) then
return false, "Invalid page number or amount of pages"
end
internal.get_pages_count(internal.fetch_function, start, len)
return true, "Started downloading..."
end,
})
if #internal.errors > 0 then
return -- Nonsense to load something that's not working
end
-- http://minetest.fensta.bplaced.net/api/apidoku.md
local root_url = "http://minetest.fensta.bplaced.net"
local page_url = root_url .. "/api/v2/get.json.php?getlist&page=%i&outformat=base64" -- [1] = Page#
local preview_url = root_url .. "/skins/1/%i.png" -- [1] = ID
local mod_path = skins.modpath
local meta_path = mod_path .. "/meta/"
local skins_path = mod_path .. "/textures/"
-- Fancy debug wrapper to download an URL
local function fetch_url(url, callback)
http.fetch({
url = url,
user_agent = _ID_
}, function(result)
if result.succeeded then
if result.code ~= 200 then
core.log("warning", ("%s: STATUS=%i URL=%s"):format(
_ID_, result.code, url))
end
return callback(result.data)
end
core.log("warning", ("%s: Failed to download URL=%s"):format(
_ID_, url))
end)
end
-- Insecure workaround since meta/ and textures/ cannot be written to
local function unsafe_file_write(path, contents)
local f = ie.io.open(path, "wb")
f:write(contents)
f:close()
end
-- Takes a valid skin table from the Skins Database and saves it
local function safe_single_skin(skin)
local meta = {
skin.name,
skin.author,
skin.license
}
local name = "character_" .. skin.id
-- core.safe_file_write does not work here
unsafe_file_write(
meta_path .. name .. ".txt",
table.concat(meta, "\n")
)
unsafe_file_write(
skins_path .. name .. ".png",
core.decode_base64(skin.img)
)
fetch_url(preview_url:format(skin.id), function(preview)
unsafe_file_write(skins_path .. name .. "_preview.png", preview)
end)
core.log("action", ("%s: Completed skin %s"):format(_ID_, name))
end
-- Get total pages since it'll just return the last page all over again
internal.get_pages_count = function(callback, ...)
local vars = {...}
fetch_url(page_url:format(1) .. "&per_page=1", function(data)
local list = core.parse_json(data)
-- "per_page" defaults to 20 if left away (docs say something else, though)
callback(math.ceil(list.pages / 20), unpack(vars))
end)
end
-- Function to fetch a range of pages
internal.fetch_function = function(pages_total, start_page, len)
start_page = math.max(start_page, 1)
local end_page = math.min(start_page + len - 1, pages_total)
for page_n = start_page, end_page do
local page_cpy = page_n
fetch_url(page_url:format(page_n), function(data)
core.log("action", ("%s: Page %i"):format(_ID_, page_cpy))
local list = core.parse_json(data)
for i, skin in pairs(list.skins) do
assert(skin.type == "image/png")
assert(skin.id ~= "")
if skin.id ~= 1 then -- Skin 1 is bundled with skinsdb
safe_single_skin(skin)
end
end
if page_cpy == end_page then
local log = _ID_ .. " finished downloading all skins. " ..
"Shutting down server to reload media cache"
core.log("action", log)
core.request_shutdown(log, true, 3 --[[give some time for pending requests]])
end
end)
end
end
| gpl-3.0 |
xing634325131/Luci-0.11.1 | libs/web/luasrc/http/protocol/date.lua | 13 | 2801 | --[[
HTTP protocol implementation for LuCI - date handling
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
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: date.lua 3860 2008-12-06 03:18:14Z jow $
]]--
--- LuCI http protocol implementation - date helper class.
-- This class contains functions to parse, compare and format http dates.
module("luci.http.protocol.date", package.seeall)
require("luci.sys.zoneinfo")
MONTHS = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"
}
--- Return the time offset in seconds between the UTC and given time zone.
-- @param tz Symbolic or numeric timezone specifier
-- @return Time offset to UTC in seconds
function tz_offset(tz)
if type(tz) == "string" then
-- check for a numeric identifier
local s, v = tz:match("([%+%-])([0-9]+)")
if s == '+' then s = 1 else s = -1 end
if v then v = tonumber(v) end
if s and v then
return s * 60 * ( math.floor( v / 100 ) * 60 + ( v % 100 ) )
-- lookup symbolic tz
elseif luci.sys.zoneinfo.OFFSET[tz:lower()] then
return luci.sys.zoneinfo.OFFSET[tz:lower()]
end
end
-- bad luck
return 0
end
--- Parse given HTTP date string and convert it to unix epoch time.
-- @param data String containing the date
-- @return Unix epoch time
function to_unix(date)
local wd, day, mon, yr, hr, min, sec, tz = date:match(
"([A-Z][a-z][a-z]), ([0-9]+) " ..
"([A-Z][a-z][a-z]) ([0-9]+) " ..
"([0-9]+):([0-9]+):([0-9]+) " ..
"([A-Z0-9%+%-]+)"
)
if day and mon and yr and hr and min and sec then
-- find month
local month = 1
for i = 1, 12 do
if MONTHS[i] == mon then
month = i
break
end
end
-- convert to epoch time
return tz_offset(tz) + os.time( {
year = yr,
month = month,
day = day,
hour = hr,
min = min,
sec = sec
} )
end
return 0
end
--- Convert the given unix epoch time to valid HTTP date string.
-- @param time Unix epoch time
-- @return String containing the formatted date
function to_http(time)
return os.date( "%a, %d %b %Y %H:%M:%S GMT", time )
end
--- Compare two dates which can either be unix epoch times or HTTP date strings.
-- @param d1 The first date or epoch time to compare
-- @param d2 The first date or epoch time to compare
-- @return -1 - if d1 is lower then d2
-- @return 0 - if both dates are equal
-- @return 1 - if d1 is higher then d2
function compare(d1, d2)
if d1:match("[^0-9]") then d1 = to_unix(d1) end
if d2:match("[^0-9]") then d2 = to_unix(d2) end
if d1 == d2 then
return 0
elseif d1 < d2 then
return -1
else
return 1
end
end
| apache-2.0 |
salorium/awesome | lib/awful/widget/watch.lua | 3 | 3492 | ---------------------------------------------------------------------------
--- Watch widget.
-- Here is an example of simple temperature widget which will update each 15
-- seconds implemented in two different ways.
-- The first, simpler one, will just display the return command output
-- (so output is stripped by shell commands).
-- In the other example `sensors` returns to the widget its full output
-- and it's trimmed in the widget callback function:
--
-- 211 mytextclock,
-- 212 wibox.widget.textbox(' | '),
-- 213 -- one way to do that:
-- 214 awful.widget.watch('bash -c "sensors | grep temp1"', 15),
-- 215 -- another way:
-- 216 awful.widget.watch('sensors', 15, function(widget, stdout)
-- 217 for line in stdout:gmatch("[^\r\n]+") do
-- 218 if line:match("temp1") then
-- 219 widget:set_text(line)
-- 220 return
-- 221 end
-- 222 end
-- 223 end),
-- 224 mylayoutbox[s],
--
-- 
--
-- @author Benjamin Petrenko
-- @author Yauheni Kirylau
-- @copyright 2015, 2016 Benjamin Petrenko, Yauheni Kirylau
-- @release @AWESOME_VERSION@
-- @classmod awful.widget.watch
---------------------------------------------------------------------------
local setmetatable = setmetatable
local textbox = require("wibox.widget.textbox")
local timer = require("gears.timer")
local spawn = require("awful.spawn")
local watch = { mt = {} }
--- Create a textbox that shows the output of a command
-- and updates it at a given time interval.
--
-- @tparam string|table command The command.
--
-- @tparam[opt=5] integer timeout The time interval at which the textbox
-- will be updated.
--
-- @tparam[opt] function callback The function that will be called after
-- the command output will be received. it is shown in the textbox.
-- Defaults to:
-- function(widget, stdout, stderr, exitreason, exitcode)
-- widget:set_text(stdout)
-- end
-- @param callback.widget Base widget instance.
-- @tparam string callback.stdout Output on stdout.
-- @tparam string callback.stderr Output on stderr.
-- @tparam string callback.exitreason Exit Reason.
-- The reason can be "exit" or "signal".
-- @tparam integer callback.exitcode Exit code.
-- For "exit" reason it's the exit code.
-- For "signal" reason — the signal causing process termination.
--
-- @param[opt=wibox.widget.textbox()] base_widget Base widget.
--
-- @return The widget used by this watch
function watch.new(command, timeout, callback, base_widget)
timeout = timeout or 5
base_widget = base_widget or textbox()
callback = callback or function(widget, stdout, stderr, exitreason, exitcode) -- luacheck: no unused args
widget:set_text(stdout)
end
local t = timer { timeout = timeout }
t:connect_signal("timeout", function()
t:stop()
spawn.easy_async(command, function(stdout, stderr, exitreason, exitcode)
callback(base_widget, stdout, stderr, exitreason, exitcode)
t:again()
end)
end)
t:start()
t:emit_signal("timeout")
return base_widget
end
function watch.mt.__call(_, ...)
return watch.new(...)
end
return setmetatable(watch, watch.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
wcjscm/JackGame | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/CCBReader.lua | 19 | 4473 |
--------------------------------
-- @module CCBReader
-- @extend Ref
-- @parent_module cc
--------------------------------
--
-- @function [parent=#CCBReader] addOwnerOutletName
-- @param self
-- @param #string name
-- @return CCBReader#CCBReader self (return value: cc.CCBReader)
--------------------------------
--
-- @function [parent=#CCBReader] getOwnerCallbackNames
-- @param self
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
--
-- @function [parent=#CCBReader] addDocumentCallbackControlEvents
-- @param self
-- @param #int eventType
-- @return CCBReader#CCBReader self (return value: cc.CCBReader)
--------------------------------
--
-- @function [parent=#CCBReader] setCCBRootPath
-- @param self
-- @param #char ccbRootPath
-- @return CCBReader#CCBReader self (return value: cc.CCBReader)
--------------------------------
--
-- @function [parent=#CCBReader] addOwnerOutletNode
-- @param self
-- @param #cc.Node node
-- @return CCBReader#CCBReader self (return value: cc.CCBReader)
--------------------------------
--
-- @function [parent=#CCBReader] getOwnerCallbackNodes
-- @param self
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
--
-- @function [parent=#CCBReader] readSoundKeyframesForSeq
-- @param self
-- @param #cc.CCBSequence seq
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#CCBReader] getCCBRootPath
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#CCBReader] getOwnerCallbackControlEvents
-- @param self
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
--
-- @function [parent=#CCBReader] getOwnerOutletNodes
-- @param self
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
--
-- @function [parent=#CCBReader] readUTF8
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#CCBReader] addOwnerCallbackControlEvents
-- @param self
-- @param #int type
-- @return CCBReader#CCBReader self (return value: cc.CCBReader)
--------------------------------
--
-- @function [parent=#CCBReader] getOwnerOutletNames
-- @param self
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
-- js setActionManager<br>
-- lua setActionManager
-- @function [parent=#CCBReader] setAnimationManager
-- @param self
-- @param #cc.CCBAnimationManager pAnimationManager
-- @return CCBReader#CCBReader self (return value: cc.CCBReader)
--------------------------------
--
-- @function [parent=#CCBReader] readCallbackKeyframesForSeq
-- @param self
-- @param #cc.CCBSequence seq
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#CCBReader] getAnimationManagersForNodes
-- @param self
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
--
-- @function [parent=#CCBReader] getNodesWithAnimationManagers
-- @param self
-- @return array_table#array_table ret (return value: array_table)
--------------------------------
-- js getActionManager<br>
-- lua getActionManager
-- @function [parent=#CCBReader] getAnimationManager
-- @param self
-- @return CCBAnimationManager#CCBAnimationManager ret (return value: cc.CCBAnimationManager)
--------------------------------
--
-- @function [parent=#CCBReader] setResolutionScale
-- @param self
-- @param #float scale
-- @return CCBReader#CCBReader self (return value: cc.CCBReader)
--------------------------------
-- @overload self, cc.CCBReader
-- @overload self, cc.NodeLoaderLibrary, cc.CCBMemberVariableAssigner, cc.CCBSelectorResolver, cc.NodeLoaderListener
-- @overload self
-- @function [parent=#CCBReader] CCBReader
-- @param self
-- @param #cc.NodeLoaderLibrary pNodeLoaderLibrary
-- @param #cc.CCBMemberVariableAssigner pCCBMemberVariableAssigner
-- @param #cc.CCBSelectorResolver pCCBSelectorResolver
-- @param #cc.NodeLoaderListener pNodeLoaderListener
-- @return CCBReader#CCBReader self (return value: cc.CCBReader)
return nil
| gpl-3.0 |
MrCerealGuy/Stonecraft | games/stonecraft_game/mods/ethereal/gates.lua | 1 | 4028 |
local S = ethereal.intllib
-- register Ethereal wood type gates
doors.register_fencegate("ethereal:fencegate_scorched", {
description = S("Scorched Wood Fence Gate"),
texture = "scorched_tree.png",
material = "ethereal:scorched_tree",
groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}
})
doors.register_fencegate("ethereal:fencegate_frostwood", {
description = S("Frost Wood Fence Gate"),
texture = "frost_wood.png",
material = "ethereal:frost_wood",
groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}
})
doors.register_fencegate("ethereal:fencegate_redwood", {
description = S("Redwood Fence Gate"),
texture = "redwood_wood.png",
material = "ethereal:redwood_wood",
groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}
})
doors.register_fencegate("ethereal:fencegate_willow", {
description = S("Willow Wood Fence Gate"),
texture = "willow_wood.png",
material = "ethereal:willow_wood",
groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}
})
doors.register_fencegate("ethereal:fencegate_yellowwood", {
description = S("Healing Wood Fence Gate"),
texture = "yellow_wood.png",
material = "ethereal:yellow_wood",
groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}
})
doors.register_fencegate("ethereal:fencegate_palm", {
description = S("Palm Wood Fence Gate"),
texture = "moretrees_palm_wood.png",
material = "ethereal:palm_wood",
groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}
})
doors.register_fencegate("ethereal:fencegate_banana", {
description = S("Banana Wood Fence Gate"),
texture = "banana_wood.png",
material = "ethereal:banana_wood",
groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}
})
doors.register_fencegate("ethereal:fencegate_mushroom", {
description = S("Mushroom Trunk Fence Gate"),
texture = "mushroom_trunk.png",
material = "ethereal:mushroom_trunk",
groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}
})
doors.register_fencegate("ethereal:fencegate_birch", {
description = S("Birch Wood Fence Gate"),
texture = "moretrees_birch_wood.png",
material = "ethereal:birch_wood",
groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}
})
doors.register_fencegate("ethereal:fencegate_sakura", {
description = S("Sakura Wood Fence Gate"),
texture = "ethereal_sakura_wood.png",
material = "ethereal:sakura_wood",
groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}
})
-- add compatibility for ethereal's to default wooden gates
minetest.register_alias("ethereal:fencegate_wood_open", "doors:gate_wood_open")
minetest.register_alias("ethereal:fencegate_wood_closed", "doors:gate_wood_closed")
minetest.register_alias("ethereal:fencegate_acacia_open", "doors:gate_acacia_wood_open")
minetest.register_alias("ethereal:fencegate_acacia_closed", "doors:gate_acacia_wood_closed")
minetest.register_alias("ethereal:fencegate_junglewood_open", "doors:gate_junglewood_open")
minetest.register_alias("ethereal:fencegate_junglewood_closed", "doors:gate_junglewood_closed")
minetest.register_alias("ethereal:fencegate_pine_open", "doors:gate_pine_wood_open")
minetest.register_alias("ethereal:fencegate_pine_closed", "doors:gate_pine_wood_closed")
-- sakura door
doors.register_door("ethereal:door_sakura", {
tiles = {
{name = "ethereal_sakura_door.png", backface_culling = true}
},
description = S("Sakura Wood Door"),
inventory_image = "ethereal_sakura_door_inv.png",
groups = {
snappy = 1, choppy = 2, oddly_breakable_by_hand = 2,
flammable = 2
},
sound_open = "doors_glass_door_open",
sound_close = "doors_glass_door_close",
recipe = {
{"group:stick", "default:paper"},
{"default:paper", "group:stick"},
{"ethereal:sakura_wood", "ethereal:sakura_wood"}
}
})
minetest.register_alias("ethereal:sakura_door", "ethereal:door_sakura")
minetest.register_alias("ethereal:sakura_door_a", "ethereal:door_sakura_a")
minetest.register_alias("ethereal:sakura_door_b", "ethereal:door_sakura_b")
| gpl-3.0 |
luvit/luvit | bench/http-cluster/worker.lua | 14 | 2257 | --[[
Copyright 2014 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local uv = require('uv')
local encoder = require('http-codec').encoder
local decoder = require('http-codec').decoder
local app = require('./app')
local server = uv.new_tcp()
local function httpDecoder(emit)
local decode = decoder()
local input
return function (err, chunk)
if err then return emit(err) end
input = (input and chunk) and (input .. chunk) or chunk
repeat
local event, extra = decode(input)
if event then
input = extra
emit(nil, event)
end
until not event
end
end
local function process(socket, app)
local req, res, body
local encode = encoder()
socket:read_start(httpDecoder(function (err, event)
if err then return end
assert(not err, err)
local typ = type(event)
if typ == "table" then
req = event
res, body = app(req)
socket:write(encode(res) .. encode(body))
if not req.keepAlive then
socket:close()
end
elseif typ == "string" and req.onbody then
req.onbody(event)
elseif not event then
socket:close()
end
end))
end
local function onconnection(err)
if err then return end
local client = uv.new_tcp()
server:accept(client)
process(client, app)
end
-- Get listening socket from master process
local pipe = uv.new_pipe(true)
uv.pipe_open(pipe, 3)
uv.read_start(pipe, function (err)
assert(not err, err)
if uv.pipe_pending_count(pipe) > 0 then
local pending_type = uv.pipe_pending_type(pipe)
assert(pending_type == "tcp")
assert(uv.accept(pipe, server))
assert(uv.listen(server, 256, onconnection))
uv.close(pipe)
print("Worker received server handle")
end
end)
| apache-2.0 |
oUF-wow/oUF | elements/tags.lua | 1 | 24569 | -- Credits: Vika, Cladhaire, Tekkub
--[[
# Element: Tags
Provides a system for text-based display of information by binding a tag string to a font string widget which in turn is
tied to a unit frame.
## Widget
A FontString to hold a tag string. Unlike other elements, this widget must not have a preset name.
## Notes
A `Tag` is a Lua string consisting of a function name surrounded by square brackets. The tag will be replaced by the
output of the function and displayed as text on the font string widget with that the tag has been registered.
A `Tag String` is a Lua string consisting of one or multiple tags with optional literals and parameters around them.
Each tag will be updated individually and the output will follow the tags order. Literals will be displayed in the
output string regardless of whether the surrounding tag functions return a value. I.e. `"[curhp]/[maxhp]"` will resolve
to something like `2453/5000`.
There's also an optional prefix and suffix that are separated from the tag name by `$>` and `<$` respectively,
for example, `"[==$>name<$==]"` will resolve to `==Thrall==`, and `"[perhp<$%]"` will resole to `100%`, however, said
affixes will only be added if the tag function returns a non-empty string, if it returns `nil` or `""` affixes will be
omitted.
Additionally, it's possible to pass optional arguments to a tag function to alter its behaviour. Optional arguments are
defined via `()` at the end of a tag and separated by commas (`,`). For example, `"[name(a,r,g,s)]"`, in this case 4
additional arguments, `"a"`, `"r"`, `"g"`, and `"s"` will be passed to the name tag function, what to do with them,
however, is up to a developer to decide.
The full tag syntax looks like this: `"[prefix$>tag<$suffix(a,r,g,s)]"`. The order of optional elements is important,
while they can be independently omitted, they can't be reordered.
A `Tag Function` is used to replace a single tag in a tag string by its output. A tag function receives only two
arguments - the unit and the realUnit of the unit frame used to register the tag (see Options for further details). The
tag function is called when the unit frame is shown or when a specified event has fired. It the tag is registered on an
eventless frame (i.e. one holding the unit "targettarget"), then the tag function is called in a set time interval.
A number of built-in tag functions exist. The layout can also define its own tag functions by adding them to the
`oUF.Tags.Methods` table. The events upon which the function will be called are specified in a white-space separated
list added to the `oUF.Tags.Events` table. Should an event fire without unit information, then it should also be listed
in the `oUF.Tags.SharedEvents` table as follows: `oUF.Tags.SharedEvents.EVENT_NAME = true`.
## Options
.overrideUnit - if specified on the font string widget, the frame's realUnit will be passed as the second argument to
every tag function whose name is contained in the relevant tag string. Otherwise the second argument
is always nil (boolean)
.frequentUpdates - defines how often the corresponding tag function(s) should be called. This will override the events
for the tag(s), if any. If the value is a number, it is taken as a time interval in seconds. If the
value is a boolean, the time interval is set to 0.5 seconds (number or boolean)
## Attributes
.parent - the unit frame on which the tag has been registered
## Examples
### Example 1
-- define the tag function
oUF.Tags.Methods['mylayout:threatname'] = function(unit, realUnit)
local color = _TAGS['threatcolor'](unit)
local name = _TAGS['name'](unit, realUnit)
return string.format('%s%s|r', color, name)
end
-- add the events
oUF.Tags.Events['mylayout:threatname'] = 'UNIT_NAME_UPDATE UNIT_THREAT_SITUATION_UPDATE'
-- create the text widget
local info = self.Health:CreateFontString(nil, 'OVERLAY', 'GameFontNormal')
info:SetPoint('LEFT')
-- register the tag on the text widget with oUF
self:Tag(info, '[mylayout:threatname]')
### Example 2
-- define the tag function that accepts optional arguments
oUF.Tags.Methods['mylayout:name'] = function(unit, realUnit, ...)
local name = _TAGS['name'](unit, realUnit)
local length = tonumber(...)
if(length) then
return name:sub(1, length) -- please note, this code doesn't support UTF-8 chars
else
return name
end
end
-- add the events
oUF.Tags.Events['mylayout:name'] = 'UNIT_NAME_UPDATE'
-- create the text widget
local info = self.Health:CreateFontString(nil, 'OVERLAY', 'GameFontNormal')
info:SetPoint('LEFT')
-- register the tag on the text widget with oUF
self:Tag(info, '[mylayout:name(5)]') -- the output will be shortened to 5 characters
-- self:Tag(info, '[mylayout:name]') -- alternative, the output won't be adjusted
-- self:Tag(info, '[mylayout:name(10)]') -- alternative, the output will be shortened to 10 characters
--]]
local _, ns = ...
local oUF = ns.oUF
local Private = oUF.Private
local nierror = Private.nierror
local unitExists = Private.unitExists
local xpcall = Private.xpcall
local _PATTERN = '%[..-%]+'
local _ENV = {
Hex = function(r, g, b)
if(type(r) == 'table') then
if(r.r) then
r, g, b = r.r, r.g, r.b
else
r, g, b = unpack(r)
end
end
return string.format('|cff%02x%02x%02x', r * 255, g * 255, b * 255)
end,
}
_ENV.ColorGradient = function(...)
return _ENV._FRAME:ColorGradient(...)
end
local _PROXY = setmetatable(_ENV, {__index = _G})
local tagStrings = {
['affix'] = [[function(u)
local c = UnitClassification(u)
if(c == 'minus') then
return 'Affix'
end
end]],
['arcanecharges'] = [[function()
if(GetSpecialization() == SPEC_MAGE_ARCANE) then
local num = UnitPower('player', Enum.PowerType.ArcaneCharges)
if(num > 0) then
return num
end
end
end]],
['arenaspec'] = [[function(u)
local id = u:match('arena(%d)$')
if(id) then
local specID = GetArenaOpponentSpec(tonumber(id))
if(specID and specID > 0) then
local _, specName = GetSpecializationInfoByID(specID)
return specName
end
end
end]],
['chi'] = [[function()
if(GetSpecialization() == SPEC_MONK_WINDWALKER) then
local num = UnitPower('player', Enum.PowerType.Chi)
if(num > 0) then
return num
end
end
end]],
['classification'] = [[function(u)
local c = UnitClassification(u)
if(c == 'rare') then
return 'Rare'
elseif(c == 'rareelite') then
return 'Rare Elite'
elseif(c == 'elite') then
return 'Elite'
elseif(c == 'worldboss') then
return 'Boss'
elseif(c == 'minus') then
return 'Affix'
end
end]],
['cpoints'] = [[function(u)
local cp = UnitPower(u, Enum.PowerType.ComboPoints)
if(cp > 0) then
return cp
end
end]],
['creature'] = [[function(u)
return UnitCreatureFamily(u) or UnitCreatureType(u)
end]],
['curmana'] = [[function(unit)
return UnitPower(unit, Enum.PowerType.Mana)
end]],
['dead'] = [[function(u)
if(UnitIsDead(u)) then
return 'Dead'
elseif(UnitIsGhost(u)) then
return 'Ghost'
end
end]],
['deficit:name'] = [[function(u)
local missinghp = _TAGS['missinghp'](u)
if(missinghp) then
return '-' .. missinghp
else
return _TAGS['name'](u)
end
end]],
['difficulty'] = [[function(u)
if UnitCanAttack('player', u) then
local l = UnitEffectiveLevel(u)
return Hex(GetCreatureDifficultyColor((l > 0) and l or 999))
end
end]],
['group'] = [[function(unit)
local name, server = UnitName(unit)
if(server and server ~= '') then
name = string.format('%s-%s', name, server)
end
for i=1, GetNumGroupMembers() do
local raidName, _, group = GetRaidRosterInfo(i)
if( raidName == name ) then
return group
end
end
end]],
['holypower'] = [[function()
if(GetSpecialization() == SPEC_PALADIN_RETRIBUTION) then
local num = UnitPower('player', Enum.PowerType.HolyPower)
if(num > 0) then
return num
end
end
end]],
['leader'] = [[function(u)
if(UnitIsGroupLeader(u)) then
return 'L'
end
end]],
['leaderlong'] = [[function(u)
if(UnitIsGroupLeader(u)) then
return 'Leader'
end
end]],
['level'] = [[function(u)
local l = UnitEffectiveLevel(u)
if(UnitIsWildBattlePet(u) or UnitIsBattlePetCompanion(u)) then
l = UnitBattlePetLevel(u)
end
if(l > 0) then
return l
else
return '??'
end
end]],
['maxmana'] = [[function(unit)
return UnitPowerMax(unit, Enum.PowerType.Mana)
end]],
['missinghp'] = [[function(u)
local current = UnitHealthMax(u) - UnitHealth(u)
if(current > 0) then
return current
end
end]],
['missingpp'] = [[function(u)
local current = UnitPowerMax(u) - UnitPower(u)
if(current > 0) then
return current
end
end]],
['name'] = [[function(u, r)
return UnitName(r or u)
end]],
['offline'] = [[function(u)
if(not UnitIsConnected(u)) then
return 'Offline'
end
end]],
['perhp'] = [[function(u)
local m = UnitHealthMax(u)
if(m == 0) then
return 0
else
return math.floor(UnitHealth(u) / m * 100 + .5)
end
end]],
['perpp'] = [[function(u)
local m = UnitPowerMax(u)
if(m == 0) then
return 0
else
return math.floor(UnitPower(u) / m * 100 + .5)
end
end]],
['plus'] = [[function(u)
local c = UnitClassification(u)
if(c == 'elite' or c == 'rareelite') then
return '+'
end
end]],
['powercolor'] = [[function(u)
local pType, pToken, altR, altG, altB = UnitPowerType(u)
local t = _COLORS.power[pToken]
if(not t) then
if(altR) then
if(altR > 1 or altG > 1 or altB > 1) then
return Hex(altR / 255, altG / 255, altB / 255)
else
return Hex(altR, altG, altB)
end
else
return Hex(_COLORS.power[pType] or _COLORS.power.MANA)
end
end
return Hex(t)
end]],
['pvp'] = [[function(u)
if(UnitIsPVP(u)) then
return 'PvP'
end
end]],
['raidcolor'] = [[function(u)
local _, class = UnitClass(u)
if(class) then
return Hex(_COLORS.class[class])
else
local id = u:match('arena(%d)$')
if(id) then
local specID = GetArenaOpponentSpec(tonumber(id))
if(specID and specID > 0) then
_, _, _, _, _, class = GetSpecializationInfoByID(specID)
return Hex(_COLORS.class[class])
end
end
end
end]],
['rare'] = [[function(u)
local c = UnitClassification(u)
if(c == 'rare' or c == 'rareelite') then
return 'Rare'
end
end]],
['resting'] = [[function(u)
if(u == 'player' and IsResting()) then
return 'zzz'
end
end]],
['runes'] = [[function()
local amount = 0
for i = 1, 6 do
local _, _, ready = GetRuneCooldown(i)
if(ready) then
amount = amount + 1
end
end
return amount
end]],
['sex'] = [[function(u)
local s = UnitSex(u)
if(s == 2) then
return 'Male'
elseif(s == 3) then
return 'Female'
end
end]],
['shortclassification'] = [[function(u)
local c = UnitClassification(u)
if(c == 'rare') then
return 'R'
elseif(c == 'rareelite') then
return 'R+'
elseif(c == 'elite') then
return '+'
elseif(c == 'worldboss') then
return 'B'
elseif(c == 'minus') then
return '-'
end
end]],
['smartclass'] = [[function(u)
if(UnitIsPlayer(u)) then
return _TAGS['class'](u)
end
return _TAGS['creature'](u)
end]],
['smartlevel'] = [[function(u)
local c = UnitClassification(u)
if(c == 'worldboss') then
return 'Boss'
else
local plus = _TAGS['plus'](u)
local level = _TAGS['level'](u)
if(plus) then
return level .. plus
else
return level
end
end
end]],
['soulshards'] = [[function()
local num = UnitPower('player', Enum.PowerType.SoulShards)
if(num > 0) then
return num
end
end]],
['status'] = [[function(u)
if(UnitIsDead(u)) then
return 'Dead'
elseif(UnitIsGhost(u)) then
return 'Ghost'
elseif(not UnitIsConnected(u)) then
return 'Offline'
else
return _TAGS['resting'](u)
end
end]],
['threat'] = [[function(u)
local s = UnitThreatSituation(u)
if(s == 1) then
return '++'
elseif(s == 2) then
return '--'
elseif(s == 3) then
return 'Aggro'
end
end]],
['threatcolor'] = [[function(u)
return Hex(GetThreatStatusColor(UnitThreatSituation(u)))
end]],
}
local tags = setmetatable(
{
curhp = UnitHealth,
curpp = UnitPower,
maxhp = UnitHealthMax,
maxpp = UnitPowerMax,
class = UnitClass,
faction = UnitFactionGroup,
race = UnitRace,
},
{
__index = function(self, key)
local tagString = tagStrings[key]
if(tagString) then
self[key] = tagString
tagStrings[key] = nil
end
return rawget(self, key)
end,
__newindex = function(self, key, val)
if(type(val) == 'string') then
local func, err = loadstring('return ' .. val)
if(func) then
val = func()
else
error(err, 3)
end
end
assert(type(val) == 'function', 'Tag function must be a function or a string that evaluates to a function.')
-- We don't want to clash with any custom envs
if(getfenv(val) == _G) then
-- pcall is needed for cases when Blizz functions are passed as
-- strings, for intance, 'UnitPowerMax', an attempt to set a
-- custom env will result in an error
pcall(setfenv, val, _PROXY)
end
rawset(self, key, val)
end,
}
)
_ENV._TAGS = tags
local vars = setmetatable({}, {
__newindex = function(self, key, val)
if(type(val) == 'string') then
local func = loadstring('return ' .. val)
if(func) then
val = func() or val
end
end
rawset(self, key, val)
end,
})
_ENV._VARS = vars
local tagEvents = {
['affix'] = 'UNIT_CLASSIFICATION_CHANGED',
['arcanecharges'] = 'UNIT_POWER_UPDATE PLAYER_TALENT_UPDATE',
['arenaspec'] = 'ARENA_PREP_OPPONENT_SPECIALIZATIONS',
['chi'] = 'UNIT_POWER_UPDATE PLAYER_TALENT_UPDATE',
['classification'] = 'UNIT_CLASSIFICATION_CHANGED',
['cpoints'] = 'UNIT_POWER_FREQUENT PLAYER_TARGET_CHANGED',
['curhp'] = 'UNIT_HEALTH UNIT_MAXHEALTH',
['curmana'] = 'UNIT_POWER_UPDATE UNIT_MAXPOWER',
['curpp'] = 'UNIT_POWER_UPDATE UNIT_MAXPOWER',
['dead'] = 'UNIT_HEALTH',
['deficit:name'] = 'UNIT_HEALTH UNIT_MAXHEALTH UNIT_NAME_UPDATE',
['difficulty'] = 'UNIT_FACTION',
['faction'] = 'NEUTRAL_FACTION_SELECT_RESULT',
['group'] = 'GROUP_ROSTER_UPDATE',
['holypower'] = 'UNIT_POWER_UPDATE PLAYER_TALENT_UPDATE',
['leader'] = 'PARTY_LEADER_CHANGED',
['leaderlong'] = 'PARTY_LEADER_CHANGED',
['level'] = 'UNIT_LEVEL PLAYER_LEVEL_UP',
['maxhp'] = 'UNIT_MAXHEALTH',
['maxmana'] = 'UNIT_POWER_UPDATE UNIT_MAXPOWER',
['maxpp'] = 'UNIT_MAXPOWER',
['missinghp'] = 'UNIT_HEALTH UNIT_MAXHEALTH',
['missingpp'] = 'UNIT_MAXPOWER UNIT_POWER_UPDATE',
['name'] = 'UNIT_NAME_UPDATE',
['offline'] = 'UNIT_HEALTH UNIT_CONNECTION',
['perhp'] = 'UNIT_HEALTH UNIT_MAXHEALTH',
['perpp'] = 'UNIT_MAXPOWER UNIT_POWER_UPDATE',
['plus'] = 'UNIT_CLASSIFICATION_CHANGED',
['powercolor'] = 'UNIT_DISPLAYPOWER',
['pvp'] = 'UNIT_FACTION',
['rare'] = 'UNIT_CLASSIFICATION_CHANGED',
['resting'] = 'PLAYER_UPDATE_RESTING',
['runes'] = 'RUNE_POWER_UPDATE',
['shortclassification'] = 'UNIT_CLASSIFICATION_CHANGED',
['smartlevel'] = 'UNIT_LEVEL PLAYER_LEVEL_UP UNIT_CLASSIFICATION_CHANGED',
['soulshards'] = 'UNIT_POWER_UPDATE',
['status'] = 'UNIT_HEALTH PLAYER_UPDATE_RESTING UNIT_CONNECTION',
['threat'] = 'UNIT_THREAT_SITUATION_UPDATE',
['threatcolor'] = 'UNIT_THREAT_SITUATION_UPDATE',
}
local unitlessEvents = {
ARENA_PREP_OPPONENT_SPECIALIZATIONS = true,
GROUP_ROSTER_UPDATE = true,
NEUTRAL_FACTION_SELECT_RESULT = true,
PARTY_LEADER_CHANGED = true,
PLAYER_LEVEL_UP = true,
PLAYER_TALENT_UPDATE = true,
PLAYER_TARGET_CHANGED = true,
PLAYER_UPDATE_RESTING = true,
RUNE_POWER_UPDATE = true,
}
local events = {}
local eventFrame = CreateFrame('Frame')
eventFrame:SetScript('OnEvent', function(self, event, unit)
local strings = events[event]
if(strings) then
for _, fs in next, strings do
if(fs:IsVisible() and (unitlessEvents[event] or fs.parent.unit == unit or (fs.extraUnits and fs.extraUnits[unit]))) then
fs:UpdateTag()
end
end
end
end)
local onUpdates = {}
local eventlessUnits = {}
local function createOnUpdate(timer)
if(not onUpdates[timer]) then
local total = timer
local frame = CreateFrame('Frame')
local strings = eventlessUnits[timer]
frame:SetScript('OnUpdate', function(self, elapsed)
if(total >= timer) then
for _, fs in next, strings do
if(fs.parent:IsShown() and unitExists(fs.parent.unit)) then
fs:UpdateTag()
end
end
total = 0
end
total = total + elapsed
end)
onUpdates[timer] = frame
end
end
--[[ Tags: frame:UpdateTags()
Used to update all tags on a frame.
* self - the unit frame from which to update the tags
--]]
local function Update(self)
if(self.__tags) then
for fs in next, self.__tags do
fs:UpdateTag()
end
end
end
local tagPool = {}
local funcPool = {}
local tmp = {}
-- full tag syntax: '[prefix$>tag-name<$suffix(a,r,g,s)]'
-- for a small test case see https://github.com/oUF-wow/oUF/pull/602
local function getBracketData(tag)
local prefixEnd, prefixOffset = tag:match('()$>'), 1
if(not prefixEnd) then
prefixEnd = 1
else
prefixEnd = prefixEnd - 1
prefixOffset = 3
end
local suffixEnd = (tag:match('()%(', prefixOffset + 1) or -1) - 1
local suffixStart, suffixOffset = tag:match('<$()', prefixEnd), 1
if(not suffixStart) then
suffixStart = suffixEnd + 1
else
suffixOffset = 3
end
return tag:sub(prefixEnd + prefixOffset, suffixStart - suffixOffset),
prefixEnd,
suffixStart,
suffixEnd,
tag:match('%((.-)%)', suffixOffset + 1)
end
local function getTagFunc(tagstr)
local func = tagPool[tagstr]
if(not func) then
local format, numTags = tagstr:gsub('%%', '%%%%'):gsub(_PATTERN, '%%s')
local args = {}
local idx = 1
local format_ = {}
for i = 1, numTags do
format_[i] = '%s'
end
for bracket in tagstr:gmatch(_PATTERN) do
local tagFunc = funcPool[bracket] or tags[bracket:sub(2, -2)]
if(not tagFunc) then
local tagName, prefixEnd, suffixStart, suffixEnd, customArgs = getBracketData(bracket)
local tag = tags[tagName]
if(tag) then
if(prefixEnd ~= 1 or suffixStart - suffixEnd ~= 1) then
local prefix = prefixEnd ~= 1 and bracket:sub(2, prefixEnd) or ''
local suffix = suffixStart - suffixEnd ~= 1 and bracket:sub(suffixStart, suffixEnd) or ''
tagFunc = function(unit, realUnit)
local str
if(customArgs) then
str = tag(unit, realUnit, string.split(',', customArgs))
else
str = tag(unit, realUnit)
end
if(str and str ~= '') then
return prefix .. str .. suffix
end
end
else
tagFunc = function(unit, realUnit)
local str
if(customArgs) then
str = tag(unit, realUnit, string.split(',', customArgs))
else
str = tag(unit, realUnit)
end
if(str and str ~= '') then
return str
end
end
end
funcPool[bracket] = tagFunc
end
end
if(tagFunc) then
table.insert(args, tagFunc)
idx = idx + 1
else
nierror(string.format('Attempted to use invalid tag %s.', bracket))
format_[idx] = bracket
format = format:format(unpack(format_, 1, numTags))
format_[idx] = '%s'
numTags = numTags - 1
end
end
func = function(self)
local parent = self.parent
local unit = parent.unit
local realUnit
if(self.overrideUnit) then
realUnit = parent.realUnit
end
_ENV._COLORS = parent.colors
_ENV._FRAME = parent
for i, f in next, args do
tmp[i] = f(unit, realUnit) or ''
end
-- We do 1, numTags because tmp can hold several unneeded variables.
return self:SetFormattedText(format, unpack(tmp, 1, numTags))
end
tagPool[tagstr] = func
end
return func
end
local function registerEvent(fontstr, event)
if(not events[event]) then events[event] = {} end
local isOK = xpcall(eventFrame.RegisterEvent, eventFrame, event)
if(isOK) then
table.insert(events[event], fontstr)
end
end
local function registerEvents(fontstr, tagstr)
for tag in tagstr:gmatch(_PATTERN) do
tag = getBracketData(tag)
local tagevents = tagEvents[tag]
if(tagevents) then
for event in tagevents:gmatch('%S+') do
registerEvent(fontstr, event)
end
end
end
end
local function unregisterEvents(fontstr)
for event, data in next, events do
local index = 1
local tagfsstr = data[index]
while tagfsstr do
if(tagfsstr == fontstr) then
if(#data == 1) then
eventFrame:UnregisterEvent(event)
end
table.remove(data, index)
else
index = index + 1
end
tagfsstr = data[index]
end
end
end
local taggedFS = {}
--[[ Tags: frame:Tag(fs, tagstr, ...)
Used to register a tag on a unit frame.
* self - the unit frame on which to register the tag
* fs - the font string to display the tag (FontString)
* tagstr - the tag string (string)
* ... - additional optional unitID(s) the tag should update for
--]]
local function Tag(self, fs, tagstr, ...)
if(not fs or not tagstr) then return end
if(not self.__tags) then
self.__tags = {}
table.insert(self.__elements, Update)
elseif(self.__tags[fs]) then
-- We don't need to remove it from the __tags table as Untag handles
-- that for us.
self:Untag(fs)
end
fs.parent = self
fs.UpdateTag = getTagFunc(tagstr)
if(self.__eventless or fs.frequentUpdates) then
local timer
if(type(fs.frequentUpdates) == 'number') then
timer = fs.frequentUpdates
else
timer = .5
end
if(not eventlessUnits[timer]) then eventlessUnits[timer] = {} end
table.insert(eventlessUnits[timer], fs)
createOnUpdate(timer)
else
registerEvents(fs, tagstr)
if(...) then
if(not fs.extraUnits) then
fs.extraUnits = {}
end
for index = 1, select('#', ...) do
fs.extraUnits[select(index, ...)] = true
end
end
end
taggedFS[fs] = tagstr
self.__tags[fs] = true
end
--[[ Tags: frame:Untag(fs)
Used to unregister a tag from a unit frame.
* self - the unit frame from which to unregister the tag
* fs - the font string holding the tag (FontString)
--]]
local function Untag(self, fs)
if(not fs or not self.__tags) then return end
unregisterEvents(fs)
for _, timers in next, eventlessUnits do
local index = 1
local fontstr = timers[index]
while fontstr do
if(fs == fontstr) then
table.remove(timers, index)
else
index = index + 1
end
fontstr = timers[index]
end
end
fs.UpdateTag = nil
taggedFS[fs] = nil
self.__tags[fs] = nil
end
local function strip(tag)
-- remove prefix, custom args, and suffix
return tag:gsub('%[.-$>', '['):gsub('%(.-%)%]', ']'):gsub('<$.-%]', ']')
end
oUF.Tags = {
Methods = tags,
Events = tagEvents,
SharedEvents = unitlessEvents,
Vars = vars,
RefreshMethods = function(self, tag)
if(not tag) then return end
-- If a tag's name contains magic chars, there's a chance that
-- string.match will fail to find the match.
tag = '%[' .. tag:gsub('[%^%$%(%)%%%.%*%+%-%?]', '%%%1') .. '%]'
for func in next, funcPool do
if(strip(func):match(tag)) then
funcPool[func] = nil
end
end
for tagstr, func in next, tagPool do
if(strip(tagstr):match(tag)) then
tagPool[tagstr] = nil
for fs in next, taggedFS do
if(fs.UpdateTag == func) then
fs.UpdateTag = getTagFunc(tagstr)
if(fs:IsVisible()) then
fs:UpdateTag()
end
end
end
end
end
end,
RefreshEvents = function(self, tag)
if(not tag) then return end
-- If a tag's name contains magic chars, there's a chance that
-- string.match will fail to find the match.
tag = '%[' .. tag:gsub('[%^%$%(%)%%%.%*%+%-%?]', '%%%1') .. '%]'
for tagstr in next, tagPool do
if(strip(tagstr):match(tag)) then
for fs, ts in next, taggedFS do
if(ts == tagstr) then
unregisterEvents(fs)
registerEvents(fs, tagstr)
end
end
end
end
end,
}
oUF:RegisterMetaFunction('Tag', Tag)
oUF:RegisterMetaFunction('Untag', Untag)
oUF:RegisterMetaFunction('UpdateTags', Update)
| mit |
Reborn-org/tablighchi | dkjson.lua | 1 | 26571 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
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.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
-->botreborn_ch
| gpl-3.0 |
prozacgod/ccmount | inspect.lua | 3 | 8091 | local inspect ={
_VERSION = 'inspect.lua 2.0.0',
_URL = 'http://github.com/kikito/inspect.lua',
_DESCRIPTION = 'human-readable representations of tables',
_LICENSE = [[
MIT LICENSE
Copyright (c) 2013 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.
]]
}
-- Apostrophizes the string if it has quotes, but not aphostrophes
-- Otherwise, it returns a regular quoted string
local function smartQuote(str)
if str:match('"') and not str:match("'") then
return "'" .. str .. "'"
end
return '"' .. str:gsub('"', '\\"') .. '"'
end
local controlCharsTranslation = {
["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n",
["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v"
}
local function escapeChar(c) return controlCharsTranslation[c] end
local function escape(str)
local result = str:gsub("\\", "\\\\"):gsub("(%c)", escapeChar)
return result
end
local function isIdentifier(str)
return type(str) == 'string' and str:match( "^[_%a][_%a%d]*$" )
end
local function isArrayKey(k, length)
return type(k) == 'number' and 1 <= k and k <= length
end
local function isDictionaryKey(k, length)
return not isArrayKey(k, length)
end
local defaultTypeOrders = {
['number'] = 1, ['boolean'] = 2, ['string'] = 3, ['table'] = 4,
['function'] = 5, ['userdata'] = 6, ['thread'] = 7
}
local function sortKeys(a, b)
local ta, tb = type(a), type(b)
-- strings and numbers are sorted numerically/alphabetically
if ta == tb and (ta == 'string' or ta == 'number') then return a < b end
local dta, dtb = defaultTypeOrders[ta], defaultTypeOrders[tb]
-- Two default types are compared according to the defaultTypeOrders table
if dta and dtb then return defaultTypeOrders[ta] < defaultTypeOrders[tb]
elseif dta then return true -- default types before custom ones
elseif dtb then return false -- custom types after default ones
end
-- custom types are sorted out alphabetically
return ta < tb
end
local function getDictionaryKeys(t)
local keys, length = {}, #t
for k,_ in pairs(t) do
if isDictionaryKey(k, length) then table.insert(keys, k) end
end
table.sort(keys, sortKeys)
return keys
end
local function getToStringResultSafely(t, mt)
local __tostring = type(mt) == 'table' and rawget(mt, '__tostring')
local str, ok
if type(__tostring) == 'function' then
ok, str = pcall(__tostring, t)
str = ok and str or 'error: ' .. tostring(str)
end
if type(str) == 'string' and #str > 0 then return str end
end
local maxIdsMetaTable = {
__index = function(self, typeName)
rawset(self, typeName, 0)
return 0
end
}
local idsMetaTable = {
__index = function (self, typeName)
local col = setmetatable({}, {__mode = "kv"})
rawset(self, typeName, col)
return col
end
}
local function countTableAppearances(t, tableAppearances)
tableAppearances = tableAppearances or setmetatable({}, {__mode = "k"})
if type(t) == 'table' then
if not tableAppearances[t] then
tableAppearances[t] = 1
for k,v in pairs(t) do
countTableAppearances(k, tableAppearances)
countTableAppearances(v, tableAppearances)
end
countTableAppearances(getmetatable(t), tableAppearances)
else
tableAppearances[t] = tableAppearances[t] + 1
end
end
return tableAppearances
end
local function parse_filter(filter)
if type(filter) == 'function' then return filter end
-- not a function, so it must be a table or table-like
filter = type(filter) == 'table' and filter or {filter}
local dictionary = {}
for _,v in pairs(filter) do dictionary[v] = true end
return function(x) return dictionary[x] end
end
-------------------------------------------------------------------
function inspect.inspect(rootObject, options)
options = options or {}
local depth = options.depth or math.huge
local filter = parse_filter(options.filter or {})
local tableAppearances = countTableAppearances(rootObject)
local buffer = {}
local maxIds = setmetatable({}, maxIdsMetaTable)
local ids = setmetatable({}, idsMetaTable)
local level = 0
local blen = 0 -- buffer length
local function puts(...)
local args = {...}
for i=1, #args do
blen = blen + 1
buffer[blen] = tostring(args[i])
end
end
local function down(f)
level = level + 1
f()
level = level - 1
end
local function tabify()
puts("\n", string.rep(" ", level))
end
local function commaControl(needsComma)
if needsComma then puts(',') end
return true
end
local function alreadyVisited(v)
return ids[type(v)][v] ~= nil
end
local function getId(v)
local tv = type(v)
local id = ids[tv][v]
if not id then
id = maxIds[tv] + 1
maxIds[tv] = id
ids[tv][v] = id
end
return id
end
local putValue -- forward declaration that needs to go before putTable & putKey
local function putKey(k)
if isIdentifier(k) then return puts(k) end
puts( "[" )
putValue(k)
puts("]")
end
local function putTable(t)
if alreadyVisited(t) then
puts('<table ', getId(t), '>')
elseif level >= depth then
puts('{...}')
else
if tableAppearances[t] > 1 then puts('<', getId(t), '>') end
local dictKeys = getDictionaryKeys(t)
local length = #t
local mt = getmetatable(t)
local to_string_result = getToStringResultSafely(t, mt)
puts('{')
down(function()
if to_string_result then
puts(' -- ', escape(to_string_result))
if length >= 1 then tabify() end -- tabify the array values
end
local needsComma = false
for i=1, length do
needsComma = commaControl(needsComma)
puts(' ')
putValue(t[i])
end
for _,k in ipairs(dictKeys) do
needsComma = commaControl(needsComma)
tabify()
putKey(k)
puts(' = ')
putValue(t[k])
end
if mt then
needsComma = commaControl(needsComma)
tabify()
puts('<metatable> = ')
putValue(mt)
end
end)
if #dictKeys > 0 or mt then -- dictionary table. Justify closing }
tabify()
elseif length > 0 then -- array tables have one extra space before closing }
puts(' ')
end
puts('}')
end
end
-- putvalue is forward-declared before putTable & putKey
putValue = function(v)
if filter(v) then
puts('<filtered>')
else
local tv = type(v)
if tv == 'string' then
puts(smartQuote(escape(v)))
elseif tv == 'number' or tv == 'boolean' or tv == 'nil' then
puts(tostring(v))
elseif tv == 'table' then
putTable(v)
else
puts('<',tv,' ',getId(v),'>')
end
end
end
putValue(rootObject)
return table.concat(buffer)
end
setmetatable(inspect, { __call = function(_, ...) return inspect.inspect(...) end })
return inspect
| mit |
T3hArco/skeyler-gamemodes | bhop/gamemode/sv_gatekeeper.lua | 1 | 1119 | ----------------------------
-- Bunny Hop --
-- Created by Skeyler.com --
----------------------------
GM.AllowedList = {}
GM.AllowedList["STEAM_0:0:25464234"]=true -- Aaron
GM.AllowedList["STEAM_0:1:19940367"]=true -- Ntag
GM.AllowedList["STEAM_0:1:9346397"]=true -- Snoipa
GM.AllowedList["STEAM_0:0:43691646"]=true -- knoxed
GM.AllowedList["STEAM_0:1:20059628"]=true -- George
GM.AllowedList["STEAM_0:0:17219175"]=true -- Knoxed main
GM.AllowedList["STEAM_0:0:8398971"]=true -- Giggles
GM.AllowedList["STEAM_0:0:14340930"]=true -- Arcky
GM.AllowedList["STEAM_0:0:13707575"]=true -- Stebbzor
GM.AllowedList["STEAM_0:1:22006069"]=true -- Arco
GM.AllowedList["STEAM_0:1:14671056"]=true -- Hateful
GM.AllowedList["STEAM_0:0:8232794"]=true -- Chewgum
--[[function GM:CheckPassword(steam, IP, sv_pass, cl_pass, name)
steam = util.SteamIDFrom64(steam)
if self.AllowedList[steam] then
return true
else
MsgN(name.."<"..steam..">("..IP..") tried to join the server.")
return false, "Skeyler Bhop is currently in Development, please try another day."
end
end]] | bsd-3-clause |
dmccuskey/dmc-gestures | dmc_corona/lib/dmc_lua/lib/bit/numberlua.lua | 115 | 13399 | --[[
LUA MODULE
bit.numberlua - Bitwise operations implemented in pure Lua as numbers,
with Lua 5.2 'bit32' and (LuaJIT) LuaBitOp 'bit' compatibility interfaces.
SYNOPSIS
local bit = require 'bit.numberlua'
print(bit.band(0xff00ff00, 0x00ff00ff)) --> 0xffffffff
-- Interface providing strong Lua 5.2 'bit32' compatibility
local bit32 = require 'bit.numberlua'.bit32
assert(bit32.band(-1) == 0xffffffff)
-- Interface providing strong (LuaJIT) LuaBitOp 'bit' compatibility
local bit = require 'bit.numberlua'.bit
assert(bit.tobit(0xffffffff) == -1)
DESCRIPTION
This library implements bitwise operations entirely in Lua.
This module is typically intended if for some reasons you don't want
to or cannot install a popular C based bit library like BitOp 'bit' [1]
(which comes pre-installed with LuaJIT) or 'bit32' (which comes
pre-installed with Lua 5.2) but want a similar interface.
This modules represents bit arrays as non-negative Lua numbers. [1]
It can represent 32-bit bit arrays when Lua is compiled
with lua_Number as double-precision IEEE 754 floating point.
The module is nearly the most efficient it can be but may be a few times
slower than the C based bit libraries and is orders or magnitude
slower than LuaJIT bit operations, which compile to native code. Therefore,
this library is inferior in performane to the other modules.
The `xor` function in this module is based partly on Roberto Ierusalimschy's
post in http://lua-users.org/lists/lua-l/2002-09/msg00134.html .
The included BIT.bit32 and BIT.bit sublibraries aims to provide 100%
compatibility with the Lua 5.2 "bit32" and (LuaJIT) LuaBitOp "bit" library.
This compatbility is at the cost of some efficiency since inputted
numbers are normalized and more general forms (e.g. multi-argument
bitwise operators) are supported.
STATUS
WARNING: Not all corner cases have been tested and documented.
Some attempt was made to make these similar to the Lua 5.2 [2]
and LuaJit BitOp [3] libraries, but this is not fully tested and there
are currently some differences. Addressing these differences may
be improved in the future but it is not yet fully determined how to
resolve these differences.
The BIT.bit32 library passes the Lua 5.2 test suite (bitwise.lua)
http://www.lua.org/tests/5.2/ . The BIT.bit library passes the LuaBitOp
test suite (bittest.lua). However, these have not been tested on
platforms with Lua compiled with 32-bit integer numbers.
API
BIT.tobit(x) --> z
Similar to function in BitOp.
BIT.tohex(x, n)
Similar to function in BitOp.
BIT.band(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bxor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bnot(x) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.rshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.extract(x, field [, width]) --> z
Similar to function in Lua 5.2.
BIT.replace(x, v, field, width) --> z
Similar to function in Lua 5.2.
BIT.bswap(x) --> z
Similar to function in Lua 5.2.
BIT.rrotate(x, disp) --> z
BIT.ror(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lrotate(x, disp) --> z
BIT.rol(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.arshift
Similar to function in Lua 5.2 and BitOp.
BIT.btest
Similar to function in Lua 5.2 with requires two arguments.
BIT.bit32
This table contains functions that aim to provide 100% compatibility
with the Lua 5.2 "bit32" library.
bit32.arshift (x, disp) --> z
bit32.band (...) --> z
bit32.bnot (x) --> z
bit32.bor (...) --> z
bit32.btest (...) --> true | false
bit32.bxor (...) --> z
bit32.extract (x, field [, width]) --> z
bit32.replace (x, v, field [, width]) --> z
bit32.lrotate (x, disp) --> z
bit32.lshift (x, disp) --> z
bit32.rrotate (x, disp) --> z
bit32.rshift (x, disp) --> z
BIT.bit
This table contains functions that aim to provide 100% compatibility
with the LuaBitOp "bit" library (from LuaJIT).
bit.tobit(x) --> y
bit.tohex(x [,n]) --> y
bit.bnot(x) --> y
bit.bor(x1 [,x2...]) --> y
bit.band(x1 [,x2...]) --> y
bit.bxor(x1 [,x2...]) --> y
bit.lshift(x, n) --> y
bit.rshift(x, n) --> y
bit.arshift(x, n) --> y
bit.rol(x, n) --> y
bit.ror(x, n) --> y
bit.bswap(x) --> y
DEPENDENCIES
None (other than Lua 5.1 or 5.2).
DOWNLOAD/INSTALLATION
If using LuaRocks:
luarocks install lua-bit-numberlua
Otherwise, download <https://github.com/davidm/lua-bit-numberlua/zipball/master>.
Alternately, if using git:
git clone git://github.com/davidm/lua-bit-numberlua.git
cd lua-bit-numberlua
Optionally unpack:
./util.mk
or unpack and install in LuaRocks:
./util.mk install
REFERENCES
[1] http://lua-users.org/wiki/FloatingPoint
[2] http://www.lua.org/manual/5.2/
[3] http://bitop.luajit.org/
LICENSE
(c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT).
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.
(end license)
--]]
local M = {_TYPE='module', _NAME='bit.numberlua', _VERSION='0.3.1.20120131'}
local floor = math.floor
local MOD = 2^32
local MODM = MOD-1
local function memoize(f)
local mt = {}
local t = setmetatable({}, mt)
function mt:__index(k)
local v = f(k); t[k] = v
return v
end
return t
end
local function make_bitop_uncached(t, m)
local function bitop(a, b)
local res,p = 0,1
while a ~= 0 and b ~= 0 do
local am, bm = a%m, b%m
res = res + t[am][bm]*p
a = (a - am) / m
b = (b - bm) / m
p = p*m
end
res = res + (a+b)*p
return res
end
return bitop
end
local function make_bitop(t)
local op1 = make_bitop_uncached(t,2^1)
local op2 = memoize(function(a)
return memoize(function(b)
return op1(a, b)
end)
end)
return make_bitop_uncached(op2, 2^(t.n or 1))
end
-- ok? probably not if running on a 32-bit int Lua number type platform
function M.tobit(x)
return x % 2^32
end
M.bxor = make_bitop {[0]={[0]=0,[1]=1},[1]={[0]=1,[1]=0}, n=4}
local bxor = M.bxor
function M.bnot(a) return MODM - a end
local bnot = M.bnot
function M.band(a,b) return ((a+b) - bxor(a,b))/2 end
local band = M.band
function M.bor(a,b) return MODM - band(MODM - a, MODM - b) end
local bor = M.bor
local lshift, rshift -- forward declare
function M.rshift(a,disp) -- Lua5.2 insipred
if disp < 0 then return lshift(a,-disp) end
return floor(a % 2^32 / 2^disp)
end
rshift = M.rshift
function M.lshift(a,disp) -- Lua5.2 inspired
if disp < 0 then return rshift(a,-disp) end
return (a * 2^disp) % 2^32
end
lshift = M.lshift
function M.tohex(x, n) -- BitOp style
n = n or 8
local up
if n <= 0 then
if n == 0 then return '' end
up = true
n = - n
end
x = band(x, 16^n-1)
return ('%0'..n..(up and 'X' or 'x')):format(x)
end
local tohex = M.tohex
function M.extract(n, field, width) -- Lua5.2 inspired
width = width or 1
return band(rshift(n, field), 2^width-1)
end
local extract = M.extract
function M.replace(n, v, field, width) -- Lua5.2 inspired
width = width or 1
local mask1 = 2^width-1
v = band(v, mask1) -- required by spec?
local mask = bnot(lshift(mask1, field))
return band(n, mask) + lshift(v, field)
end
local replace = M.replace
function M.bswap(x) -- BitOp style
local a = band(x, 0xff); x = rshift(x, 8)
local b = band(x, 0xff); x = rshift(x, 8)
local c = band(x, 0xff); x = rshift(x, 8)
local d = band(x, 0xff)
return lshift(lshift(lshift(a, 8) + b, 8) + c, 8) + d
end
local bswap = M.bswap
function M.rrotate(x, disp) -- Lua5.2 inspired
disp = disp % 32
local low = band(x, 2^disp-1)
return rshift(x, disp) + lshift(low, 32-disp)
end
local rrotate = M.rrotate
function M.lrotate(x, disp) -- Lua5.2 inspired
return rrotate(x, -disp)
end
local lrotate = M.lrotate
M.rol = M.lrotate -- LuaOp inspired
M.ror = M.rrotate -- LuaOp insipred
function M.arshift(x, disp) -- Lua5.2 inspired
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
local arshift = M.arshift
function M.btest(x, y) -- Lua5.2 inspired
return band(x, y) ~= 0
end
--
-- Start Lua 5.2 "bit32" compat section.
--
M.bit32 = {} -- Lua 5.2 'bit32' compatibility
local function bit32_bnot(x)
return (-1 - x) % MOD
end
M.bit32.bnot = bit32_bnot
local function bit32_bxor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = bxor(a, b)
if c then
z = bit32_bxor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bxor = bit32_bxor
local function bit32_band(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = ((a+b) - bxor(a,b)) / 2
if c then
z = bit32_band(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return MODM
end
end
M.bit32.band = bit32_band
local function bit32_bor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = MODM - band(MODM - a, MODM - b)
if c then
z = bit32_bor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bor = bit32_bor
function M.bit32.btest(...)
return bit32_band(...) ~= 0
end
function M.bit32.lrotate(x, disp)
return lrotate(x % MOD, disp)
end
function M.bit32.rrotate(x, disp)
return rrotate(x % MOD, disp)
end
function M.bit32.lshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return lshift(x % MOD, disp)
end
function M.bit32.rshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return rshift(x % MOD, disp)
end
function M.bit32.arshift(x,disp)
x = x % MOD
if disp >= 0 then
if disp > 31 then
return (x >= 0x80000000) and MODM or 0
else
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
else
return lshift(x, -disp)
end
end
function M.bit32.extract(x, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
return extract(x, field, ...)
end
function M.bit32.replace(x, v, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
v = v % MOD
return replace(x, v, field, ...)
end
--
-- Start LuaBitOp "bit" compat section.
--
M.bit = {} -- LuaBitOp "bit" compatibility
function M.bit.tobit(x)
x = x % MOD
if x >= 0x80000000 then x = x - MOD end
return x
end
local bit_tobit = M.bit.tobit
function M.bit.tohex(x, ...)
return tohex(x % MOD, ...)
end
function M.bit.bnot(x)
return bit_tobit(bnot(x % MOD))
end
local function bit_bor(a, b, c, ...)
if c then
return bit_bor(bit_bor(a, b), c, ...)
elseif b then
return bit_tobit(bor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bor = bit_bor
local function bit_band(a, b, c, ...)
if c then
return bit_band(bit_band(a, b), c, ...)
elseif b then
return bit_tobit(band(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.band = bit_band
local function bit_bxor(a, b, c, ...)
if c then
return bit_bxor(bit_bxor(a, b), c, ...)
elseif b then
return bit_tobit(bxor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bxor = bit_bxor
function M.bit.lshift(x, n)
return bit_tobit(lshift(x % MOD, n % 32))
end
function M.bit.rshift(x, n)
return bit_tobit(rshift(x % MOD, n % 32))
end
function M.bit.arshift(x, n)
return bit_tobit(arshift(x % MOD, n % 32))
end
function M.bit.rol(x, n)
return bit_tobit(lrotate(x % MOD, n % 32))
end
function M.bit.ror(x, n)
return bit_tobit(rrotate(x % MOD, n % 32))
end
function M.bit.bswap(x)
return bit_tobit(bswap(x % MOD))
end
return M
| mit |
dmccuskey/dmc-gestures | examples/gesture-pan-basic/dmc_corona/lib/dmc_lua/lib/bit/numberlua.lua | 115 | 13399 | --[[
LUA MODULE
bit.numberlua - Bitwise operations implemented in pure Lua as numbers,
with Lua 5.2 'bit32' and (LuaJIT) LuaBitOp 'bit' compatibility interfaces.
SYNOPSIS
local bit = require 'bit.numberlua'
print(bit.band(0xff00ff00, 0x00ff00ff)) --> 0xffffffff
-- Interface providing strong Lua 5.2 'bit32' compatibility
local bit32 = require 'bit.numberlua'.bit32
assert(bit32.band(-1) == 0xffffffff)
-- Interface providing strong (LuaJIT) LuaBitOp 'bit' compatibility
local bit = require 'bit.numberlua'.bit
assert(bit.tobit(0xffffffff) == -1)
DESCRIPTION
This library implements bitwise operations entirely in Lua.
This module is typically intended if for some reasons you don't want
to or cannot install a popular C based bit library like BitOp 'bit' [1]
(which comes pre-installed with LuaJIT) or 'bit32' (which comes
pre-installed with Lua 5.2) but want a similar interface.
This modules represents bit arrays as non-negative Lua numbers. [1]
It can represent 32-bit bit arrays when Lua is compiled
with lua_Number as double-precision IEEE 754 floating point.
The module is nearly the most efficient it can be but may be a few times
slower than the C based bit libraries and is orders or magnitude
slower than LuaJIT bit operations, which compile to native code. Therefore,
this library is inferior in performane to the other modules.
The `xor` function in this module is based partly on Roberto Ierusalimschy's
post in http://lua-users.org/lists/lua-l/2002-09/msg00134.html .
The included BIT.bit32 and BIT.bit sublibraries aims to provide 100%
compatibility with the Lua 5.2 "bit32" and (LuaJIT) LuaBitOp "bit" library.
This compatbility is at the cost of some efficiency since inputted
numbers are normalized and more general forms (e.g. multi-argument
bitwise operators) are supported.
STATUS
WARNING: Not all corner cases have been tested and documented.
Some attempt was made to make these similar to the Lua 5.2 [2]
and LuaJit BitOp [3] libraries, but this is not fully tested and there
are currently some differences. Addressing these differences may
be improved in the future but it is not yet fully determined how to
resolve these differences.
The BIT.bit32 library passes the Lua 5.2 test suite (bitwise.lua)
http://www.lua.org/tests/5.2/ . The BIT.bit library passes the LuaBitOp
test suite (bittest.lua). However, these have not been tested on
platforms with Lua compiled with 32-bit integer numbers.
API
BIT.tobit(x) --> z
Similar to function in BitOp.
BIT.tohex(x, n)
Similar to function in BitOp.
BIT.band(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bxor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bnot(x) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.rshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.extract(x, field [, width]) --> z
Similar to function in Lua 5.2.
BIT.replace(x, v, field, width) --> z
Similar to function in Lua 5.2.
BIT.bswap(x) --> z
Similar to function in Lua 5.2.
BIT.rrotate(x, disp) --> z
BIT.ror(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lrotate(x, disp) --> z
BIT.rol(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.arshift
Similar to function in Lua 5.2 and BitOp.
BIT.btest
Similar to function in Lua 5.2 with requires two arguments.
BIT.bit32
This table contains functions that aim to provide 100% compatibility
with the Lua 5.2 "bit32" library.
bit32.arshift (x, disp) --> z
bit32.band (...) --> z
bit32.bnot (x) --> z
bit32.bor (...) --> z
bit32.btest (...) --> true | false
bit32.bxor (...) --> z
bit32.extract (x, field [, width]) --> z
bit32.replace (x, v, field [, width]) --> z
bit32.lrotate (x, disp) --> z
bit32.lshift (x, disp) --> z
bit32.rrotate (x, disp) --> z
bit32.rshift (x, disp) --> z
BIT.bit
This table contains functions that aim to provide 100% compatibility
with the LuaBitOp "bit" library (from LuaJIT).
bit.tobit(x) --> y
bit.tohex(x [,n]) --> y
bit.bnot(x) --> y
bit.bor(x1 [,x2...]) --> y
bit.band(x1 [,x2...]) --> y
bit.bxor(x1 [,x2...]) --> y
bit.lshift(x, n) --> y
bit.rshift(x, n) --> y
bit.arshift(x, n) --> y
bit.rol(x, n) --> y
bit.ror(x, n) --> y
bit.bswap(x) --> y
DEPENDENCIES
None (other than Lua 5.1 or 5.2).
DOWNLOAD/INSTALLATION
If using LuaRocks:
luarocks install lua-bit-numberlua
Otherwise, download <https://github.com/davidm/lua-bit-numberlua/zipball/master>.
Alternately, if using git:
git clone git://github.com/davidm/lua-bit-numberlua.git
cd lua-bit-numberlua
Optionally unpack:
./util.mk
or unpack and install in LuaRocks:
./util.mk install
REFERENCES
[1] http://lua-users.org/wiki/FloatingPoint
[2] http://www.lua.org/manual/5.2/
[3] http://bitop.luajit.org/
LICENSE
(c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT).
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.
(end license)
--]]
local M = {_TYPE='module', _NAME='bit.numberlua', _VERSION='0.3.1.20120131'}
local floor = math.floor
local MOD = 2^32
local MODM = MOD-1
local function memoize(f)
local mt = {}
local t = setmetatable({}, mt)
function mt:__index(k)
local v = f(k); t[k] = v
return v
end
return t
end
local function make_bitop_uncached(t, m)
local function bitop(a, b)
local res,p = 0,1
while a ~= 0 and b ~= 0 do
local am, bm = a%m, b%m
res = res + t[am][bm]*p
a = (a - am) / m
b = (b - bm) / m
p = p*m
end
res = res + (a+b)*p
return res
end
return bitop
end
local function make_bitop(t)
local op1 = make_bitop_uncached(t,2^1)
local op2 = memoize(function(a)
return memoize(function(b)
return op1(a, b)
end)
end)
return make_bitop_uncached(op2, 2^(t.n or 1))
end
-- ok? probably not if running on a 32-bit int Lua number type platform
function M.tobit(x)
return x % 2^32
end
M.bxor = make_bitop {[0]={[0]=0,[1]=1},[1]={[0]=1,[1]=0}, n=4}
local bxor = M.bxor
function M.bnot(a) return MODM - a end
local bnot = M.bnot
function M.band(a,b) return ((a+b) - bxor(a,b))/2 end
local band = M.band
function M.bor(a,b) return MODM - band(MODM - a, MODM - b) end
local bor = M.bor
local lshift, rshift -- forward declare
function M.rshift(a,disp) -- Lua5.2 insipred
if disp < 0 then return lshift(a,-disp) end
return floor(a % 2^32 / 2^disp)
end
rshift = M.rshift
function M.lshift(a,disp) -- Lua5.2 inspired
if disp < 0 then return rshift(a,-disp) end
return (a * 2^disp) % 2^32
end
lshift = M.lshift
function M.tohex(x, n) -- BitOp style
n = n or 8
local up
if n <= 0 then
if n == 0 then return '' end
up = true
n = - n
end
x = band(x, 16^n-1)
return ('%0'..n..(up and 'X' or 'x')):format(x)
end
local tohex = M.tohex
function M.extract(n, field, width) -- Lua5.2 inspired
width = width or 1
return band(rshift(n, field), 2^width-1)
end
local extract = M.extract
function M.replace(n, v, field, width) -- Lua5.2 inspired
width = width or 1
local mask1 = 2^width-1
v = band(v, mask1) -- required by spec?
local mask = bnot(lshift(mask1, field))
return band(n, mask) + lshift(v, field)
end
local replace = M.replace
function M.bswap(x) -- BitOp style
local a = band(x, 0xff); x = rshift(x, 8)
local b = band(x, 0xff); x = rshift(x, 8)
local c = band(x, 0xff); x = rshift(x, 8)
local d = band(x, 0xff)
return lshift(lshift(lshift(a, 8) + b, 8) + c, 8) + d
end
local bswap = M.bswap
function M.rrotate(x, disp) -- Lua5.2 inspired
disp = disp % 32
local low = band(x, 2^disp-1)
return rshift(x, disp) + lshift(low, 32-disp)
end
local rrotate = M.rrotate
function M.lrotate(x, disp) -- Lua5.2 inspired
return rrotate(x, -disp)
end
local lrotate = M.lrotate
M.rol = M.lrotate -- LuaOp inspired
M.ror = M.rrotate -- LuaOp insipred
function M.arshift(x, disp) -- Lua5.2 inspired
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
local arshift = M.arshift
function M.btest(x, y) -- Lua5.2 inspired
return band(x, y) ~= 0
end
--
-- Start Lua 5.2 "bit32" compat section.
--
M.bit32 = {} -- Lua 5.2 'bit32' compatibility
local function bit32_bnot(x)
return (-1 - x) % MOD
end
M.bit32.bnot = bit32_bnot
local function bit32_bxor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = bxor(a, b)
if c then
z = bit32_bxor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bxor = bit32_bxor
local function bit32_band(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = ((a+b) - bxor(a,b)) / 2
if c then
z = bit32_band(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return MODM
end
end
M.bit32.band = bit32_band
local function bit32_bor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = MODM - band(MODM - a, MODM - b)
if c then
z = bit32_bor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bor = bit32_bor
function M.bit32.btest(...)
return bit32_band(...) ~= 0
end
function M.bit32.lrotate(x, disp)
return lrotate(x % MOD, disp)
end
function M.bit32.rrotate(x, disp)
return rrotate(x % MOD, disp)
end
function M.bit32.lshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return lshift(x % MOD, disp)
end
function M.bit32.rshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return rshift(x % MOD, disp)
end
function M.bit32.arshift(x,disp)
x = x % MOD
if disp >= 0 then
if disp > 31 then
return (x >= 0x80000000) and MODM or 0
else
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
else
return lshift(x, -disp)
end
end
function M.bit32.extract(x, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
return extract(x, field, ...)
end
function M.bit32.replace(x, v, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
v = v % MOD
return replace(x, v, field, ...)
end
--
-- Start LuaBitOp "bit" compat section.
--
M.bit = {} -- LuaBitOp "bit" compatibility
function M.bit.tobit(x)
x = x % MOD
if x >= 0x80000000 then x = x - MOD end
return x
end
local bit_tobit = M.bit.tobit
function M.bit.tohex(x, ...)
return tohex(x % MOD, ...)
end
function M.bit.bnot(x)
return bit_tobit(bnot(x % MOD))
end
local function bit_bor(a, b, c, ...)
if c then
return bit_bor(bit_bor(a, b), c, ...)
elseif b then
return bit_tobit(bor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bor = bit_bor
local function bit_band(a, b, c, ...)
if c then
return bit_band(bit_band(a, b), c, ...)
elseif b then
return bit_tobit(band(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.band = bit_band
local function bit_bxor(a, b, c, ...)
if c then
return bit_bxor(bit_bxor(a, b), c, ...)
elseif b then
return bit_tobit(bxor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bxor = bit_bxor
function M.bit.lshift(x, n)
return bit_tobit(lshift(x % MOD, n % 32))
end
function M.bit.rshift(x, n)
return bit_tobit(rshift(x % MOD, n % 32))
end
function M.bit.arshift(x, n)
return bit_tobit(arshift(x % MOD, n % 32))
end
function M.bit.rol(x, n)
return bit_tobit(lrotate(x % MOD, n % 32))
end
function M.bit.ror(x, n)
return bit_tobit(rrotate(x % MOD, n % 32))
end
function M.bit.bswap(x)
return bit_tobit(bswap(x % MOD))
end
return M
| mit |
dmccuskey/dmc-gestures | examples/gesture-pinch-basic/dmc_corona/lib/dmc_lua/lib/bit/numberlua.lua | 115 | 13399 | --[[
LUA MODULE
bit.numberlua - Bitwise operations implemented in pure Lua as numbers,
with Lua 5.2 'bit32' and (LuaJIT) LuaBitOp 'bit' compatibility interfaces.
SYNOPSIS
local bit = require 'bit.numberlua'
print(bit.band(0xff00ff00, 0x00ff00ff)) --> 0xffffffff
-- Interface providing strong Lua 5.2 'bit32' compatibility
local bit32 = require 'bit.numberlua'.bit32
assert(bit32.band(-1) == 0xffffffff)
-- Interface providing strong (LuaJIT) LuaBitOp 'bit' compatibility
local bit = require 'bit.numberlua'.bit
assert(bit.tobit(0xffffffff) == -1)
DESCRIPTION
This library implements bitwise operations entirely in Lua.
This module is typically intended if for some reasons you don't want
to or cannot install a popular C based bit library like BitOp 'bit' [1]
(which comes pre-installed with LuaJIT) or 'bit32' (which comes
pre-installed with Lua 5.2) but want a similar interface.
This modules represents bit arrays as non-negative Lua numbers. [1]
It can represent 32-bit bit arrays when Lua is compiled
with lua_Number as double-precision IEEE 754 floating point.
The module is nearly the most efficient it can be but may be a few times
slower than the C based bit libraries and is orders or magnitude
slower than LuaJIT bit operations, which compile to native code. Therefore,
this library is inferior in performane to the other modules.
The `xor` function in this module is based partly on Roberto Ierusalimschy's
post in http://lua-users.org/lists/lua-l/2002-09/msg00134.html .
The included BIT.bit32 and BIT.bit sublibraries aims to provide 100%
compatibility with the Lua 5.2 "bit32" and (LuaJIT) LuaBitOp "bit" library.
This compatbility is at the cost of some efficiency since inputted
numbers are normalized and more general forms (e.g. multi-argument
bitwise operators) are supported.
STATUS
WARNING: Not all corner cases have been tested and documented.
Some attempt was made to make these similar to the Lua 5.2 [2]
and LuaJit BitOp [3] libraries, but this is not fully tested and there
are currently some differences. Addressing these differences may
be improved in the future but it is not yet fully determined how to
resolve these differences.
The BIT.bit32 library passes the Lua 5.2 test suite (bitwise.lua)
http://www.lua.org/tests/5.2/ . The BIT.bit library passes the LuaBitOp
test suite (bittest.lua). However, these have not been tested on
platforms with Lua compiled with 32-bit integer numbers.
API
BIT.tobit(x) --> z
Similar to function in BitOp.
BIT.tohex(x, n)
Similar to function in BitOp.
BIT.band(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bxor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bnot(x) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.rshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.extract(x, field [, width]) --> z
Similar to function in Lua 5.2.
BIT.replace(x, v, field, width) --> z
Similar to function in Lua 5.2.
BIT.bswap(x) --> z
Similar to function in Lua 5.2.
BIT.rrotate(x, disp) --> z
BIT.ror(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lrotate(x, disp) --> z
BIT.rol(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.arshift
Similar to function in Lua 5.2 and BitOp.
BIT.btest
Similar to function in Lua 5.2 with requires two arguments.
BIT.bit32
This table contains functions that aim to provide 100% compatibility
with the Lua 5.2 "bit32" library.
bit32.arshift (x, disp) --> z
bit32.band (...) --> z
bit32.bnot (x) --> z
bit32.bor (...) --> z
bit32.btest (...) --> true | false
bit32.bxor (...) --> z
bit32.extract (x, field [, width]) --> z
bit32.replace (x, v, field [, width]) --> z
bit32.lrotate (x, disp) --> z
bit32.lshift (x, disp) --> z
bit32.rrotate (x, disp) --> z
bit32.rshift (x, disp) --> z
BIT.bit
This table contains functions that aim to provide 100% compatibility
with the LuaBitOp "bit" library (from LuaJIT).
bit.tobit(x) --> y
bit.tohex(x [,n]) --> y
bit.bnot(x) --> y
bit.bor(x1 [,x2...]) --> y
bit.band(x1 [,x2...]) --> y
bit.bxor(x1 [,x2...]) --> y
bit.lshift(x, n) --> y
bit.rshift(x, n) --> y
bit.arshift(x, n) --> y
bit.rol(x, n) --> y
bit.ror(x, n) --> y
bit.bswap(x) --> y
DEPENDENCIES
None (other than Lua 5.1 or 5.2).
DOWNLOAD/INSTALLATION
If using LuaRocks:
luarocks install lua-bit-numberlua
Otherwise, download <https://github.com/davidm/lua-bit-numberlua/zipball/master>.
Alternately, if using git:
git clone git://github.com/davidm/lua-bit-numberlua.git
cd lua-bit-numberlua
Optionally unpack:
./util.mk
or unpack and install in LuaRocks:
./util.mk install
REFERENCES
[1] http://lua-users.org/wiki/FloatingPoint
[2] http://www.lua.org/manual/5.2/
[3] http://bitop.luajit.org/
LICENSE
(c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT).
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.
(end license)
--]]
local M = {_TYPE='module', _NAME='bit.numberlua', _VERSION='0.3.1.20120131'}
local floor = math.floor
local MOD = 2^32
local MODM = MOD-1
local function memoize(f)
local mt = {}
local t = setmetatable({}, mt)
function mt:__index(k)
local v = f(k); t[k] = v
return v
end
return t
end
local function make_bitop_uncached(t, m)
local function bitop(a, b)
local res,p = 0,1
while a ~= 0 and b ~= 0 do
local am, bm = a%m, b%m
res = res + t[am][bm]*p
a = (a - am) / m
b = (b - bm) / m
p = p*m
end
res = res + (a+b)*p
return res
end
return bitop
end
local function make_bitop(t)
local op1 = make_bitop_uncached(t,2^1)
local op2 = memoize(function(a)
return memoize(function(b)
return op1(a, b)
end)
end)
return make_bitop_uncached(op2, 2^(t.n or 1))
end
-- ok? probably not if running on a 32-bit int Lua number type platform
function M.tobit(x)
return x % 2^32
end
M.bxor = make_bitop {[0]={[0]=0,[1]=1},[1]={[0]=1,[1]=0}, n=4}
local bxor = M.bxor
function M.bnot(a) return MODM - a end
local bnot = M.bnot
function M.band(a,b) return ((a+b) - bxor(a,b))/2 end
local band = M.band
function M.bor(a,b) return MODM - band(MODM - a, MODM - b) end
local bor = M.bor
local lshift, rshift -- forward declare
function M.rshift(a,disp) -- Lua5.2 insipred
if disp < 0 then return lshift(a,-disp) end
return floor(a % 2^32 / 2^disp)
end
rshift = M.rshift
function M.lshift(a,disp) -- Lua5.2 inspired
if disp < 0 then return rshift(a,-disp) end
return (a * 2^disp) % 2^32
end
lshift = M.lshift
function M.tohex(x, n) -- BitOp style
n = n or 8
local up
if n <= 0 then
if n == 0 then return '' end
up = true
n = - n
end
x = band(x, 16^n-1)
return ('%0'..n..(up and 'X' or 'x')):format(x)
end
local tohex = M.tohex
function M.extract(n, field, width) -- Lua5.2 inspired
width = width or 1
return band(rshift(n, field), 2^width-1)
end
local extract = M.extract
function M.replace(n, v, field, width) -- Lua5.2 inspired
width = width or 1
local mask1 = 2^width-1
v = band(v, mask1) -- required by spec?
local mask = bnot(lshift(mask1, field))
return band(n, mask) + lshift(v, field)
end
local replace = M.replace
function M.bswap(x) -- BitOp style
local a = band(x, 0xff); x = rshift(x, 8)
local b = band(x, 0xff); x = rshift(x, 8)
local c = band(x, 0xff); x = rshift(x, 8)
local d = band(x, 0xff)
return lshift(lshift(lshift(a, 8) + b, 8) + c, 8) + d
end
local bswap = M.bswap
function M.rrotate(x, disp) -- Lua5.2 inspired
disp = disp % 32
local low = band(x, 2^disp-1)
return rshift(x, disp) + lshift(low, 32-disp)
end
local rrotate = M.rrotate
function M.lrotate(x, disp) -- Lua5.2 inspired
return rrotate(x, -disp)
end
local lrotate = M.lrotate
M.rol = M.lrotate -- LuaOp inspired
M.ror = M.rrotate -- LuaOp insipred
function M.arshift(x, disp) -- Lua5.2 inspired
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
local arshift = M.arshift
function M.btest(x, y) -- Lua5.2 inspired
return band(x, y) ~= 0
end
--
-- Start Lua 5.2 "bit32" compat section.
--
M.bit32 = {} -- Lua 5.2 'bit32' compatibility
local function bit32_bnot(x)
return (-1 - x) % MOD
end
M.bit32.bnot = bit32_bnot
local function bit32_bxor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = bxor(a, b)
if c then
z = bit32_bxor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bxor = bit32_bxor
local function bit32_band(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = ((a+b) - bxor(a,b)) / 2
if c then
z = bit32_band(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return MODM
end
end
M.bit32.band = bit32_band
local function bit32_bor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = MODM - band(MODM - a, MODM - b)
if c then
z = bit32_bor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bor = bit32_bor
function M.bit32.btest(...)
return bit32_band(...) ~= 0
end
function M.bit32.lrotate(x, disp)
return lrotate(x % MOD, disp)
end
function M.bit32.rrotate(x, disp)
return rrotate(x % MOD, disp)
end
function M.bit32.lshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return lshift(x % MOD, disp)
end
function M.bit32.rshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return rshift(x % MOD, disp)
end
function M.bit32.arshift(x,disp)
x = x % MOD
if disp >= 0 then
if disp > 31 then
return (x >= 0x80000000) and MODM or 0
else
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
else
return lshift(x, -disp)
end
end
function M.bit32.extract(x, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
return extract(x, field, ...)
end
function M.bit32.replace(x, v, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
v = v % MOD
return replace(x, v, field, ...)
end
--
-- Start LuaBitOp "bit" compat section.
--
M.bit = {} -- LuaBitOp "bit" compatibility
function M.bit.tobit(x)
x = x % MOD
if x >= 0x80000000 then x = x - MOD end
return x
end
local bit_tobit = M.bit.tobit
function M.bit.tohex(x, ...)
return tohex(x % MOD, ...)
end
function M.bit.bnot(x)
return bit_tobit(bnot(x % MOD))
end
local function bit_bor(a, b, c, ...)
if c then
return bit_bor(bit_bor(a, b), c, ...)
elseif b then
return bit_tobit(bor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bor = bit_bor
local function bit_band(a, b, c, ...)
if c then
return bit_band(bit_band(a, b), c, ...)
elseif b then
return bit_tobit(band(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.band = bit_band
local function bit_bxor(a, b, c, ...)
if c then
return bit_bxor(bit_bxor(a, b), c, ...)
elseif b then
return bit_tobit(bxor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bxor = bit_bxor
function M.bit.lshift(x, n)
return bit_tobit(lshift(x % MOD, n % 32))
end
function M.bit.rshift(x, n)
return bit_tobit(rshift(x % MOD, n % 32))
end
function M.bit.arshift(x, n)
return bit_tobit(arshift(x % MOD, n % 32))
end
function M.bit.rol(x, n)
return bit_tobit(lrotate(x % MOD, n % 32))
end
function M.bit.ror(x, n)
return bit_tobit(rrotate(x % MOD, n % 32))
end
function M.bit.bswap(x)
return bit_tobit(bswap(x % MOD))
end
return M
| mit |
pydsigner/naev | dat/missions/dvaered/dv_antiflf02.lua | 11 | 14334 | --[[
-- This is the second mission in the anti-FLF Dvaered campaign. The player is part of a Dvaered plot to smoke out the FLF base.
-- stack variable flfbase_intro:
-- 1 - The player has turned in the FLF agent or rescued the Dvaered crew. Conditional for dv_antiflf02
-- 2 - The player has rescued the FLF agent. Conditional for flf_pre02
-- 3 - The player has found the FLF base for the Dvaered, or has betrayed the FLF after rescuing the agent. Conditional for dv_antiflf03
--]]
-- localization stuff, translators would work here
include("fleethelper.lua")
lang = naev.lang()
if lang == "es" then
else -- default english
title = {}
text = {}
failtitle = {}
failtext = {}
osd_desc = {}
comm_msg = {}
title[1] = "House Dvaered needs YOU"
text[1] = [[You join the Dvaered official at his table. He greets you in a cordial fashion, at least by Dvaered standards. You explain to him that you wish to know more about the anti-FLF operation that House Dvaered is supposedly working on.
"Ah! It's good to see such righteous enthusiasm among our citizenry. Indeed, our forces have been preparing to deal a significant blow to the FLF terrorists. I can't disclose the details, of course - this is a military operation. However, if you have a combat-capable ship and enough sense of duty to assist us, there is an opportunity to serve alongside the real Dvaered warriors. How about it? Can we count on your support?"]]
title[2] = "A clever ruse"
text[2] = [["Splendid. You have the right mindset, citizen. If only all were like you! But that is neither here nor there. Come, I will take you to the local command bunker. The details of this operation will be explained to you there."
True to his word, the Dvaered liaison escorts you out of the spaceport bar, and within the hour you find yourself deep inside a highly secured Dvaered military complex. You are ushered into a room, in which you find a large table and several important-looking military men. At the head of the table sits a man whose name tag identifies him as Colonel Urnus. Evidently he's the man in charge.
A Dvaered soldier instructs you to take a seat.]]
text[3] = [[As you take the last empty seat at the table, Colonel Urnus starts the meeting. "Welcome, citizen. You know why you are here and you know what this meeting is about, so let me get right to the point. We have reason to believe the FLF terrorists are operating from a secret base of operations. We know this base is located somewhere in the nebula, and we have recently uncovered intel that indicates the base is likely to be in the %s system."
One of the walls lights up, showing part of the galaxy map. The %s system is colored red, and it's pulsating gently.
"Of course, we have conducted patrols in this system, but so far without result. Our sensors are severely impaired by the nebula in this system, so the chances of us finding the terrorist hive by our own devices are slim. Fortunately, our top strategists have come up with a ruse, one that will make the FLF come to us."
"We will use a civilian ship - your ship, naturally - as a decoy," Urnus continues. The image on the wall zooms up to the %s system, and a white blip representing your ship appears near the jump point. "Your ship will be equipped with an IFF transponder in use by the FLF, so to anyone who isn't looking too closely you will appear as an FLF ship. Of course, this alone is not enough. The FLF will assume you know where their base is, since you look like one of them."
The image on the wall updates again, this time showing several House Dvaered crests near your ship.
"Some time after you enter the system, several of our military assets will jump in and open fire. To the FLF, it will look like one of their own has come under attack! Since their base is nearby, they will undoubtably send reinforcements to help their 'comrade' out of a tight situation."]]
text[4] = [["As soon as the FLF ships join the battle, you and the Dvaered ships will disengage and target the FLF instead. Your mission is to render at least one of their ships incapable of fighting, and board it. You can then access the ship's computer and download the flight log, which will include the location of the FLF base. Take this information to a Dvaered base, and your mission will be complete."
The image on the wall updates one last time, simulating the battle as described by Colonel Urnus. Several FLF logos appear, which are promptly surrounded by the Dvaered ones. Then the logos turn gray, indicating that they've been disabled.
"Let me make one thing clear, citizen. You are allowed, even expected to fire on the Dvaered ships that are firing on you. However, you must make it look you're on the losing side, or the FLF will not come to your aid! So, do NOT disable or destroy any Dvaered ships, and make sure your own armor takes a bit of a beating. This is vital to the success of the mission. Do not fail."
Colonel Urnus to have concluded his explanation, so you, having spotted the obvious flaw in the Dvaereds' plan, pop the question of what happens if the FLF never show up.
"Well," the Colonel muses, "That will mean our intel was probably wrong. But don't worry, citizen, we'll get those terrorists eventually! Now, time is of the essence, so get to your ship and follow your orders. Dismissed!"]]
title[5] = "Take no prisoners - only their logs"
text[5] = [[You successfully board the FLF ship and secure its flight logs. This is what the Dvaered want - you should take it to a Dvaered planet immediately.]]
title[6] = "X marks the spot"
text[6] = [[As soon as you land, a Dvaered military operator contacts you and requests you turn over the flight log you procured from the FLF ship, so you do. The Dvaered are then silent for some twenty minutes, time you use to complete your post-landing routines. Then, you are summoned to the local Dvaered security station.
Colonel Urnus welcomes you. "Well met, citizen. I have received word of your accomplishment in our recent operation. It seems HQ is quite pleased with the result, and they have instructed me to reward you appropriately."
He hands you a credit chip that represents a decent sum of money, though you feel that a mere monetary reward doesn't begin to compensate for the insane plan the Dvaered made you part of. However, you wisely opt not to give voice to that thought.
"In addition," Urnus resumes, "Dvaered military command has decided that you may participate in the upcoming battle against the FLF stronghold, in recognition of your courage and your skill in battle. You may contact our liaison whenever you're ready."
That concludes the pleasantries, and you are unceremoniously deposited outside the security compound. But at least you earned some money - and a chance to see some real action.]]
refusetitle = "House Dvaered is out of luck"
refusetext = [["I see. In that case, I'm going to have to ask you to leave. My job is to recruit a civilian, but you're clearly not the man I'm looking for. You may excuse yourself, citizen."]]
failtitle[1] = "You ran away!"
failtext[1] = "You have left the system without first completing your mission. The operation ended in failure."
failtitle[2] = "You fought too hard!"
failtext[2] = "You have disabled a Dvaered ship, thereby violating your orders. The operation is canceled thanks to you. The Dvaered are less than pleased."
failtitle[3] = "All the FLF are dead!"
failtext[3] = "Unfortunately, all the FLF ships have been destroyed before you managed to board one of them. The operation ended in failure."
npc_desc = "This must be the Dvaered liaison you heard about. Allegedly, he may have a job for you that involves fighting the Frontier Liberation Front."
misn_title = "Lure out the FLF"
osd_desc[1] = "Fly to the %s system"
osd_desc[2] = "Wait for the Dvaered military to jump in and attack you"
osd_desc[3] = "Fight the Dvaered until the FLF step in"
osd_desc[4] = "Disable and board at least one FLF ship"
osd_desc[5] = "Return to any Dvaered world"
misn_desc = "You have been recruited to act as a red herring in a military operation of Dvaered design. Your chief purpose is to goad the FLF into showing themselves, then disabling and boarding one of their ships. You will fail this mission if you disable or destroy any Dvaered ship, or if you leave the system before the operation is complete."
comm_msg["enter"] = "Here come the FLF! All units, switch to EMPs and disable the terrorist ships!"
comm_msg["victory"] = "All targets neutralized. Download the flight log and let's get out of here!"
end
function create()
missys = {system.get(var.peek("flfbase_sysname"))}
if not misn.claim(missys) then
abort()
end
misn.setNPC("Dvaered liaison", "dvaered/dv_military_m1")
misn.setDesc(npc_desc)
end
function accept()
if tk.yesno(title[1], text[1]) then
destsysname = var.peek("flfbase_sysname")
tk.msg(title[2], text[2])
tk.msg(title[2], string.format(text[3], destsysname, destsysname, destsysname))
tk.msg(title[2], text[4])
misn.accept()
osd_desc[1] = string.format(osd_desc[1], destsysname)
misn.osdCreate(misn_title, osd_desc)
misn.setDesc(misn_desc)
misn.setTitle(misn_title)
marker = misn.markerAdd( system.get(destsysname), "low" )
missionstarted = false
DVdisablefail = true
logsfound = false
flfdead = 0
misn.cargoAdd("FLF IFF Transponder", 0)
hook.jumpout("jumpout")
hook.enter("enter")
hook.land("land")
else
tk.msg(refusetitle, refusetext)
misn.finish()
end
end
function jumpout()
last_sys = system.cur()
end
function enter()
if system.cur():name() == destsysname and not logsfound then
pilot.clear()
pilot.toggleSpawn(false)
misn.osdActive(2)
hook.timer(15000, "spawnDV")
elseif missionstarted then -- The player has jumped away from the mission theater, which instantly ends the mission.
tk.msg(failtitle[1], failtext[1])
faction.get("Dvaered"):modPlayerSingle(-10)
abort()
end
end
function land()
if logsfound and planet.cur():faction():name() == "Dvaered" then
tk.msg(title[6], text[6])
var.push("flfbase_intro", 3)
faction.get("Dvaered"):modPlayerSingle(5)
player.pay(70000) -- 70K
misn.finish(true)
end
end
function spawnDV()
misn.osdActive(3)
missionstarted = true
fleetDV = pilot.add("Dvaered Strike Force", "dvaered_norun", last_sys)
-- The Dvaered ships should attack the player, so set them hostile.
-- These are Vigilances, so we should tune them WAY down so the player doesn't insta-die.
for i, j in ipairs(fleetDV) do
j:setHostile()
j:setHilight(true)
j:setVisplayer(true)
j:rmOutfit("all")
j:addOutfit("Turreted Gauss Gun", 1)
j:addOutfit("Small Shield Booster", 1)
j:addOutfit("Steering Thrusters", 1)
j:addOutfit("Solar Panel", 1)
hook.pilot(j, "disable", "disableDV")
end
hook.timer(500, "pollHealth")
end
-- Polls the player's health and the Dvaereds' shields, and spawns the FLF fleet if shields and armor are below a certain value.
function pollHealth()
shieldDV = 0
parmor, pshield = player.pilot():health()
local maxshieldDV = 0
for i, j in ipairs(fleetDV) do
maxshieldDV = maxshieldDV + j:stats()["shield"]
armor, shield = j:health()
shieldDV = shieldDV + shield
end
if parmor <= 60 and pshield <= 10 and shieldDV <= (maxshieldDV - 50) then
spawnFLF()
else
hook.timer(500, "pollHealth")
end
end
-- Spawn the FLF ships, reset the Dvaered.
function spawnFLF()
DVdisablefail = false -- The player no longer fails the mission if a Dvaered ship is disabled
misn.osdActive(4)
for i, j in ipairs(fleetDV) do
j:setFriendly()
j:setHilight(false)
j:changeAI("dvaered_norun")
j:setInvincPlayer()
-- Re-outfit the ships to use disable weapons. Kind of ugly, should probably be handled via AI orders in the future.
j:addOutfit("EMP Grenade Launcher", 3)
end
angle = rnd.rnd() * 2 * math.pi
dist = 800
vecFLF = vec2.new(math.cos(angle) * dist, math.sin(angle) * dist)
fleetFLF = addShips( "FLF Vendetta", "flf_norun", player.pilot():pos() + vecFLF, 4 )
flfactive = #fleetFLF
fleetDV[1]:comm(comm_msg["enter"])
for i, j in ipairs(fleetFLF) do
j:setHilight(true)
j:setVisplayer()
hook.pilot(j, "disable", "disableFLF")
hook.pilot(j, "death", "deathFLF")
hook.pilot(j, "board", "boardFLF")
end
end
function disableDV()
if DVdisablefail then -- Only true as long as the FLF aren't there yet
tk.msg(failtitle[2], failtext[2])
faction.get("Dvaered"):modPlayerSingle(-10)
abort()
end
end
function disableFLF()
flfactive = flfactive - 1
-- Persuade the Dvaered to stop shooting at disabled FLF
for i, j in ipairs(fleetDV) do
if j:exists() then
if flfactive == 0 and not messaged then
fleetDV[i]:comm(comm_msg["victory"])
messaged = true
end
j:changeAI("dvaered_norun")
end
end
end
function deathFLF()
flfdead = flfdead + 1
if flfdead == 6 and not logsfound then
tk.msg(failtitle[3], failtext[3])
abort()
end
end
function boardFLF()
misn.osdActive(5)
tk.msg(title[5], text[5])
missionstarted = false
logsfound = true
player.unboard()
misn.markerRm(marker)
for i, j in ipairs(fleetDV) do
if j:exists() then
j:changeAI("flee") -- Make them jump out (if they're not dead!)
end
end
for _, j in ipairs(fleetFLF) do
if j:exists() then
j:setHilight(false)
j:setVisplayer(false)
j:setNoboard(true)
end
end
end
function abort()
misn.finish(false)
end
| gpl-3.0 |
parsa13881/serverbot | plugins/anti_chat.lua | 62 | 1069 |
antichat = {}-- An empty table for solving multiple kicking problem
do
local function run(msg, matches)
if is_momod(msg) then -- Ignore mods,owner,admins
return
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['lock_chat'] then
if data[tostring(msg.to.id)]['settings']['lock_chat'] == 'yes' then
if antichat[msg.from.id] == true then
return
end
send_large_msg("chat#id".. msg.to.id , "chat is not allowed here")
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked (chat was locked) ")
chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false)
antichat[msg.from.id] = true
return
end
end
return
end
local function cron()
antichat = {} -- Clear antichat table
end
return {
patterns = {
"([\216-\219][\128-\191])"
},
run = run,
cron = cron
}
end
--Copyright; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.