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 |
|---|---|---|---|---|---|
Mehranhpr/seed | plugins/owners.lua | 68 | 12477 |
local function lock_group_namemod(msg, data, target)
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)
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)
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)
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)
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)
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 unlock_group_photomod(msg, data, target)
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 show_group_settingsmod(msg, data, target)
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 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.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
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 set_description(target, about)
local data = load_data(_config.moderation.data)
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 run(msg, matches)
if msg.to.type ~= 'chat' then
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]..':'..user_id
redis:del(hash)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback (extra , success, result)
local receiver = 'chat#'..matches[1]
vardump(result)
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local receiver = 'chat#'..matches[1]
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ")
export_chat_link(receiver, callback, true)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "------")
send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^[!/]owners (%d+) ([^%s]+) (.*)$",
"^[!/]owners (%d+) ([^%s]+)$",
"^[!/](changeabout) (%d+) (.*)$",
"^[!/](changerules) (%d+) (.*)$",
"^[!/](changename) (%d+) (.*)$",
"^[!/](loggroup) (%d+)$"
},
run = run
}
| gpl-2.0 |
CaptainCN/QCEditor | cocos2d/cocos/scripting/lua-bindings/auto/api/AnimationData.lua | 2 | 1089 |
--------------------------------
-- @module AnimationData
-- @extend Ref
-- @parent_module ccs
--------------------------------
--
-- @function [parent=#AnimationData] getMovement
-- @param self
-- @param #string movementName
-- @return MovementData#MovementData ret (return value: ccs.MovementData)
--------------------------------
--
-- @function [parent=#AnimationData] getMovementCount
-- @param self
-- @return int#int ret (return value: int)
--------------------------------
--
-- @function [parent=#AnimationData] addMovement
-- @param self
-- @param #ccs.MovementData movData
-- @return AnimationData#AnimationData self (return value: ccs.AnimationData)
--------------------------------
--
-- @function [parent=#AnimationData] create
-- @param self
-- @return AnimationData#AnimationData ret (return value: ccs.AnimationData)
--------------------------------
-- js ctor
-- @function [parent=#AnimationData] AnimationData
-- @param self
-- @return AnimationData#AnimationData self (return value: ccs.AnimationData)
return nil
| mit |
Rydra/OpenRA | mods/ra/maps/desert-shellmap/desert-shellmap.lua | 4 | 5096 | local ants = Utils.RandomInteger(0, 51) == 0
if ants then
UnitTypes = { "ant", "ant", "ant" }
BeachUnitTypes = { "ant", "ant" }
ParadropUnitTypes = { "ant", "ant", "ant", "ant", "ant" }
ProducedUnitTypes =
{
{ AlliedBarracks1, { "e1", "e3" } },
{ AlliedBarracks2, { "e1", "e3" } },
{ SovietBarracks1, { "ant" } },
{ SovietBarracks2, { "ant" } },
{ SovietBarracks3, { "ant" } },
{ AlliedWarFactory1, { "jeep", "1tnk", "2tnk", "arty", "ctnk" } },
{ SovietWarFactory1, { "3tnk", "4tnk", "v2rl", "ttnk", "apc" } }
}
else
UnitTypes = { "3tnk", "ftrk", "ttnk", "apc" }
BeachUnitTypes = { "e1", "e2", "e3", "e4", "e1", "e2", "e3", "e4", "e1", "e2", "e3", "e4", "e1", "e2", "e3", "e4" }
ParadropUnitTypes = { "e1", "e1", "e2", "e3", "e4" }
ProducedUnitTypes =
{
{ AlliedBarracks1, { "e1", "e3" } },
{ AlliedBarracks2, { "e1", "e3" } },
{ SovietBarracks1, { "dog", "e1", "e2", "e3", "e4", "shok" } },
{ SovietBarracks2, { "dog", "e1", "e2", "e3", "e4", "shok" } },
{ SovietBarracks3, { "dog", "e1", "e2", "e3", "e4", "shok" } },
{ AlliedWarFactory1, { "jeep", "1tnk", "2tnk", "arty", "ctnk" } },
{ SovietWarFactory1, { "3tnk", "4tnk", "v2rl", "ttnk", "apc" } }
}
end
ParadropWaypoints = { Paradrop1, Paradrop2, Paradrop3, Paradrop4, Paradrop5, Paradrop6, Paradrop7, Paradrop8 }
BindActorTriggers = function(a)
if a.HasProperty("Hunt") then
if a.Owner == allies then
Trigger.OnIdle(a, a.Hunt)
else
Trigger.OnIdle(a, function(a) a.AttackMove(AlliedTechnologyCenter.Location) end)
end
end
if a.HasProperty("HasPassengers") then
Trigger.OnDamaged(a, function()
if a.HasPassengers then
a.Stop()
a.UnloadPassengers()
end
end)
end
end
SendSovietUnits = function(entryCell, unitTypes, interval)
local i = 0
team = {}
Utils.Do(unitTypes, function(type)
local a = Actor.Create(type, false, { Owner = soviets, Location = entryCell })
BindActorTriggers(a)
Trigger.AfterDelay(i * interval, function() a.IsInWorld = true end)
table.insert(team, a)
i = i + 1
end)
Trigger.OnAllKilled(team, function() SendSovietUnits(entryCell, unitTypes, interval) end)
end
ShipAlliedUnits = function()
local transport = Actor.Create("lst", true, { Location = LstEntry.Location, Owner = allies })
Utils.Do({ "1tnk", "1tnk", "jeep", "2tnk", "2tnk" }, function(type)
local a = Actor.Create(type, false, { Owner = allies })
BindActorTriggers(a)
transport.LoadPassenger(a)
end)
transport.Move(LstUnload.Location)
transport.UnloadPassengers()
transport.Wait(50)
transport.Move(LstEntry.Location)
transport.Destroy()
Trigger.AfterDelay(60 * 25, ShipAlliedUnits)
end
ParadropSovietUnits = function()
local lz = Utils.Random(ParadropWaypoints).Location
local start = Utils.CenterOfCell(Map.RandomEdgeCell()) + WVec.New(0, 0, Actor.CruiseAltitude("badr"))
local transport = Actor.Create("badr", true, { CenterPosition = start, Owner = soviets, Facing = (Utils.CenterOfCell(lz) - start).Facing })
Utils.Do(ParadropUnitTypes, function(type)
local a = Actor.Create(type, false, { Owner = soviets })
BindActorTriggers(a)
transport.LoadPassenger(a)
end)
transport.Paradrop(lz)
Trigger.AfterDelay(35 * 25, ParadropSovietUnits)
end
ProduceUnits = function(t)
local factory = t[1]
if not factory.IsDead then
local unitType = t[2][Utils.RandomInteger(1, #t[2] + 1)]
factory.Wait(Actor.BuildTime(unitType))
factory.Produce(unitType)
factory.CallFunc(function() ProduceUnits(t) end)
end
end
SetupAlliedUnits = function()
Utils.Do(Map.NamedActors, function(a)
if a.Owner == allies and a.HasProperty("Invulnerable") then
a.Invulnerable = true
a.Stance = "Defend"
end
end)
end
SetupFactories = function()
Utils.Do(ProducedUnitTypes, function(pair)
Trigger.OnProduction(pair[1], function(_, a) BindActorTriggers(a) end)
end)
end
ChronoshiftAlliedUnits = function()
local cells = Utils.ExpandFootprint({ ChronoshiftLocation.Location }, false)
local units = { }
for i = 1, #cells do
local unit = Actor.Create("2tnk", true, { Owner = allies, Facing = 0 })
BindActorTriggers(unit)
units[unit] = cells[i]
end
Chronosphere.Chronoshift(units)
Trigger.AfterDelay(60 * 25, ChronoshiftAlliedUnits)
end
ticks = 0
speed = 5
Tick = function()
ticks = ticks + 1
local t = (ticks + 45) % (360 * speed) * (math.pi / 180) / speed;
Camera.Position = viewportOrigin + WVec.New(19200 * math.sin(t), 20480 * math.cos(t), 0)
end
WorldLoaded = function()
allies = Player.GetPlayer("Allies")
soviets = Player.GetPlayer("Soviets")
viewportOrigin = Camera.Position
SetupAlliedUnits()
SetupFactories()
ShipAlliedUnits()
ParadropSovietUnits()
Trigger.AfterDelay(5 * 25, ChronoshiftAlliedUnits)
Utils.Do(ProducedUnitTypes, ProduceUnits)
SendSovietUnits(Entry1.Location, UnitTypes, 50)
SendSovietUnits(Entry2.Location, UnitTypes, 50)
SendSovietUnits(Entry3.Location, UnitTypes, 50)
SendSovietUnits(Entry4.Location, UnitTypes, 50)
SendSovietUnits(Entry5.Location, UnitTypes, 50)
SendSovietUnits(Entry6.Location, UnitTypes, 50)
SendSovietUnits(Entry7.Location, BeachUnitTypes, 15)
end | gpl-3.0 |
asamy45/forgottenmapeditor | modules/mapeditor_itempalette/itempalette.lua | 1 | 4786 | ItemPalette = {}
local paletteWindow
local paletteList
local comboBox
UIPaletteCreature = extends(UICreature)
function UIPaletteCreature:onMousePress(mousePos, button)
-- TODO: Could optimize this by outfit id?...
_G["currentThing"] = self:getCreature():getName()
ToolPalette.update()
end
UIPaletteItem = extends(UIItem)
function UIPaletteItem:onMousePress(mousePos, button)
_G["currentThing"] = self:getItemId()
ToolPalette.update()
end
local function onOptionChange(widget, optText, optData)
paletteList:destroyChildren()
if optData <= ItemCategoryLast then
local items = g_things.findItemTypeByCategory(optData)
for i = 1, #items do
local widget = g_ui.createWidget('PaletteItem', paletteList)
widget:setItemId(items[i]:getClientId())
end
elseif optData == ThingCategoryCreature then
local creatures = g_creatures.getCreatures()
for i = 1, #creatures do
local widget = g_ui.createWidget('PaletteCreature', paletteList)
widget:setCreature(creatures[i]:cast())
end
elseif optData >= ItemCategoryInterior then
for a, v in ipairs(extraItem[optText].from) do
for i = extraItem[optText].from[a], extraItem[optText].to[a] do
local widget = g_ui.createWidget('PaletteItem', paletteList)
local itemid = g_things.getItemType(i)
widget:setItemId(itemid:getClientId())
end
end
for a, v in ipairs(extraItem[optText].id) do
local widget = g_ui.createWidget('PaletteItem', paletteList)
local itemid = g_things.getItemType(v)
widget:setItemId(itemid:getClientId())
end
elseif optData == ItemCategoryInvalid then
local categoryItems = g_things.findItemTypeByCategory(ItemCategoryInvalid)
for idx = 1, #categoryItems do
local widget = g_ui.createWidget('PaletteItem', paletteList)
widget:setItemId(categoryItems[idx]:getClientId())
end
end
end
local function deselectChild(child)
paletteList:focusChild(nil)
if child then
child:setBorderWidth(0)
end
end
local function onMousePress(self, mousePos, button)
local previous = _G["currentWidget"]
local next = self:getChildByPos(mousePos)
if not next then
deselectChild(previous)
_G["currentWidget"] = nil
_G["currentThing"] = nil
elseif next ~= previous then
deselectChild(previous)
next:setBorderWidth(1)
paletteList:focusChild(next)
_G["currentWidget"] = next
else
deselectChild(previous)
end
if ToolPalette.getCurrentTool().drawTool == false then
ToolPalette.setTool(ToolPencil)
end
ToolPalette.update()
end
function ItemPalette.init()
comboBox = g_ui.createWidget("ComboBox", rootWidget:recursiveGetChildById('leftPanel'))
paletteWindow = g_ui.loadUI('itempalette.otui', rootWidget:recursiveGetChildById('leftPanel'))
paletteList = paletteWindow:recursiveGetChildById('paletteList')
paletteList.onMouseMove = function(self, mousePos, mouseMoved)
local thing = self:getChildByPos(mousePos)
if thing then
if comboBox:getCurrentOption().text == "Creatures" then
updateBottomCreature(thing:getCreature():getName())
else
updateBottomItem(thing:getItemId())
end
end
end
connect(paletteList, { onMousePress = onMousePress })
comboBox.onOptionChange = onOptionChange
_G["currentThing"] = 4526
_G["secondThing"] = 106
_G["currentWidget"] = nil
ToolPalette.update()
ItemPalette.initData()
end
function ItemPalette.initData()
paletteList:destroyChildren()
comboBox:clearOptions()
comboBox:addOption("Grounds", ItemCategoryGround)
comboBox:addOption("Containers", ItemCategoryContainer)
comboBox:addOption("Weapons", ItemCategoryWeapon)
comboBox:addOption("Ammunition", ItemCategoryAmmunition)
comboBox:addOption("Armor", ItemCategoryArmor)
comboBox:addOption("Charges", ItemCategoryCharges)
comboBox:addOption("Teleports", ItemCategoryTeleport)
comboBox:addOption("MagicFields", ItemCategoryMagicField)
comboBox:addOption("Keys", ItemCategoryKey)
comboBox:addOption("Splashs", ItemCategorySplash)
comboBox:addOption("Fluids", ItemCategoryFluid)
comboBox:addOption("Doors", ItemCategoryDoor)
if g_game.getProtocolVersion() >= 840 then
comboBox:addOption("Interior", ItemCategoryInterior)
comboBox:addOption("Exterior", ItemCategoryExterior)
comboBox:addOption("Stairs", ItemCategoryStairs)
end
comboBox:addOption("Creatures", ThingCategoryCreature)
comboBox:addOption("Others", ItemCategoryInvalid)
comboBox:setCurrentIndex(1)
end
function ItemPalette.terminate()
comboBox.onOptionChange = nil
disconnect(paletteList, { onMousePress = onMousePress })
paletteWindow:destroy()
paletteWindow = nil
end
| mit |
githubmereza/rezaj | bot/InfernalTG.lua | 1 | 8855 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '1.0'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
-- mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"Help_All",
"Auto_Leave",
"BLOCK",
"Feedback",
"Member_Manager",
"Group_Manager",
"S2A",
"SUDO",
"all",
"arabic_lock",
"Banhammer",
"download_media",
"get",
"inpm",
"invite",
"leaders",
"leave_ban",
"plugins",
"realmcommands",
"service_entergroup",
"set",
"anti_spam",
"stats",
"Version",
"close_group",
"toto",
"kickall",
"boobs",
"Maseage",
"tagall",
},
sudo_users = {170774776,194222290,111041070},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[infernalTG v2 - Open Source
An advance Administration bot based on yagop/telegram-bot
our official github :
https://github.com/INFERNALTEAM/InfernalTG.git
Antispambot : @InfernalTG
website ; https://arash-infernal.epage.ir
Admins
@Creed_is_dead [Founder]
@digitalboys [Developer]
@Arashinfernal [Developer]
@MustafFlux [Manager]
Special thanks to
Imandaneshi
thisisarman
yago perez ...
and more ...
Our channels
@Infernalteamch [English]
@infernalchannel [persian]
@Infernalteam [persian]
]],
help_text_realm = [[
group admin Commands:
!creategroup [Name]
!createrealm [Name]
!setname [Name]
!setabout [GroupID] [Text]
!setrules [GroupID] [Text]
!lock [GroupID] [setting]
!unlock [GroupID] [setting]
!wholist
!who
!type
!kill chat [GroupID]
!kill realm [RealmID]
!adminprom [id|username]
!admindem [id|username]
!list infernalgroups
!list infernalrealms
!log
!broadcast [text]
!broadcast InfernalTG !
!br [group_id] [text]
!br 123456789 Hello !
**U can use both "/" and "!"
*Only admins and sudo can add bots in group
*Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only admins and sudo can use res, setowner, commands
]],
help_text = [[
tools for tele85 :
>#1.Add_bot
>#2.Anti_Bot
>#3.Auto_Leave
>#4.BLOCK
>#5.Feedback
>#6.Member_Manager
>#7.S2A
>#8.SUDO
>#8.all
>#9.arabic_lock
>#10.banhammer
>#11.down_media
>#12.get
>#13.inpm
>#14.invite
>#15.leaders
>#16.leave_ban
>#17.pluglist
>#18.realmcommands
>#19.service_entergroup
>#20.set
>#21.anti_spam
>#22.stats
>#23.toengsupport
>#24.topersupport
>#25.spammer_a
>#26.Spammer_i
>#27.Version
>#28.close_group
>#29.kickall
>#30.SendPm
>#31.tagall
>#32.share
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
ETegro/OpenSAN | feeds/luci/applications/luci-asterisk/luasrc/model/cbi/asterisk/dialplan_out.lua | 11 | 3280 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 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: dialplan_out.lua 4385 2009-03-29 19:11:57Z jow $
]]--
local ast = require("luci.asterisk")
local function find_outgoing_contexts(uci)
local c = { }
local h = { }
-- uci:foreach("asterisk", "dialplan",
-- function(s)
-- if not h[s['.name']] then
-- c[#c+1] = { s['.name'], "Dialplan: %s" % s['.name'] }
-- h[s['.name']] = true
-- end
-- end)
uci:foreach("asterisk", "dialzone",
function(s)
if not h[s['.name']] then
c[#c+1] = { s['.name'], "Dialzone: %s" % s['.name'] }
h[s['.name']] = true
end
end)
return c
end
local function find_incoming_contexts(uci)
local c = { }
local h = { }
uci:foreach("asterisk", "sip",
function(s)
if s.context and not h[s.context] and
uci:get_bool("asterisk", s['.name'], "provider")
then
c[#c+1] = { s.context, "Incoming: %s" % s['.name'] or s.context }
h[s.context] = true
end
end)
return c
end
local function find_trunks(uci)
local t = { }
uci:foreach("asterisk", "sip",
function(s)
if uci:get_bool("asterisk", s['.name'], "provider") then
t[#t+1] = {
"SIP/%s" % s['.name'],
"SIP: %s" % s['.name']
}
end
end)
uci:foreach("asterisk", "iax",
function(s)
t[#t+1] = {
"IAX/%s" % s['.name'],
"IAX: %s" % s.extension or s['.name']
}
end)
return t
end
--[[
dialzone {name} - Outgoing zone.
uses - Outgoing line to use: TYPE/Name
match (list) - Number to match
countrycode - The effective country code of this dialzone
international (list) - International prefix to match
localzone - dialzone for local numbers
addprefix - Prexix required to dial out.
localprefix - Prefix for a local call
]]
--
-- SIP dialzone configuration
--
if arg[1] then
cbimap = Map("asterisk", "Edit Dialplan Entry")
entry = cbimap:section(NamedSection, arg[1])
back = entry:option(DummyValue, "_overview", "Back to dialplan overview")
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "asterisk", "dialplans")
desc = entry:option(Value, "description", "Description")
function desc.cfgvalue(self, s, ...)
return Value.cfgvalue(self, s, ...) or s
end
match = entry:option(DynamicList, "match", "Number matches")
intl = entry:option(DynamicList, "international", "Intl. prefix matches (optional)")
trunk = entry:option(MultiValue, "uses", "Used trunk")
for _, v in ipairs(find_trunks(cbimap.uci)) do
trunk:value(unpack(v))
end
aprefix = entry:option(Value, "addprefix", "Add prefix to dial out (optional)")
--ast.idd.cbifill(aprefix)
ccode = entry:option(Value, "countrycode", "Effective countrycode (optional)")
ast.cc.cbifill(ccode)
lzone = entry:option(ListValue, "localzone", "Dialzone for local numbers")
lzone:value("", "no special treatment of local numbers")
for _, v in ipairs(find_outgoing_contexts(cbimap.uci)) do
lzone:value(unpack(v))
end
lprefix = entry:option(Value, "localprefix", "Prefix for local calls (optional)")
return cbimap
end
| gpl-3.0 |
MNoya/DotaCraft | game/dota_addons/dotacraft/scripts/vscripts/heroes/alchemist/healing_spray.lua | 1 | 1790 | --[[
Author: Noya
Creates a dummy unit to apply the HealingSpray thinker modifier which does the waves
]]
function HealingSprayStart( event )
local caster = event.caster
local point = event.target_points[1]
local ability = event.ability
caster.healing_spray_dummy = CreateUnitByName("dummy_unit_vulnerable", point, false, caster, caster, caster:GetTeam())
event.ability:ApplyDataDrivenModifier(caster, caster.healing_spray_dummy, "modifier_healing_spray_thinker", nil)
end
function HealingSprayWave( event )
local caster = event.caster
local point = event.target:GetAbsOrigin()
local particleName = "particles/custom/alchemist_acid_spray_cast.vpcf"
local particle = ParticleManager:CreateParticle(particleName, PATTACH_CUSTOMORIGIN, caster)
ParticleManager:SetParticleControlEnt(particle, 0, caster, PATTACH_POINT_FOLLOW, "attach_hitloc", caster:GetAbsOrigin(), true)
ParticleManager:SetParticleControl(particle, 1, point)
ParticleManager:SetParticleControl(particle, 15, Vector(255,255,0))
ParticleManager:SetParticleControl(particle, 16, Vector(255,255,0))
local ability = event.ability
local radius = ability:GetLevelSpecialValueFor("radius",ability:GetLevel()-1)
local heal = ability:GetLevelSpecialValueFor("wave_heal",ability:GetLevel()-1)
local allies = FindAllUnitsInRadius(caster, radius, point)
for _,target in pairs(allies) do
if not IsCustomBuilding(target) and not target:IsMechanical() and not target:IsWard() then
local heal = math.min(heal, target:GetHealthDeficit())
if heal > 0 then
target:Heal(heal,ability)
PopupHealing(target, heal)
end
end
end
end
function HealingSprayEnd( event )
local caster = event.caster
if IsValidEntity(caster.healing_spray_dummy) then
caster.healing_spray_dummy:ForceKill(true)
end
end | gpl-3.0 |
nekrozar/ygopro-scripts | c65150219.lua | 2 | 1168 | --機甲忍法フリーズ・ロック
function c65150219.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_ATTACK_ANNOUNCE)
e1:SetCondition(c65150219.condition)
e1:SetOperation(c65150219.activate)
c:RegisterEffect(e1)
--pos limit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_CANNOT_CHANGE_POSITION)
e2:SetProperty(EFFECT_FLAG_SET_AVAILABLE)
e2:SetRange(LOCATION_SZONE)
e2:SetTargetRange(0,LOCATION_MZONE)
e2:SetCondition(c65150219.poscon)
c:RegisterEffect(e2)
end
function c65150219.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x2b)
end
function c65150219.condition(e,tp,eg,ep,ev,re,r,rp)
return tp~=Duel.GetTurnPlayer() and Duel.IsExistingMatchingCard(c65150219.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c65150219.activate(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
if Duel.NegateAttack() then
Duel.SkipPhase(1-tp,PHASE_BATTLE,RESET_PHASE+PHASE_BATTLE_STEP,1)
end
end
function c65150219.poscon(e)
return Duel.IsExistingMatchingCard(c65150219.cfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil)
end
| gpl-2.0 |
nekrozar/ygopro-scripts | c83102080.lua | 6 | 1639 | --パラレル・ツイスター
function c83102080.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c83102080.cost)
e1:SetTarget(c83102080.target)
e1:SetOperation(c83102080.activate)
c:RegisterEffect(e1)
end
function c83102080.filter(c,ec)
return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsAbleToGraveAsCost()
and Duel.IsExistingTarget(c83102080.tgfilter,0,LOCATION_ONFIELD,LOCATION_ONFIELD,1,ec,c)
end
function c83102080.tgfilter(c,tc)
return c~=tc
end
function c83102080.cost(e,tp,eg,ep,ev,re,r,rp,chk)
e:SetLabel(1)
return true
end
function c83102080.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local c=e:GetHandler()
if chkc then return chkc:IsOnField() and chkc~=c end
if chk==0 then
if e:GetLabel()~=0 then
e:SetLabel(0)
return Duel.IsExistingMatchingCard(c83102080.filter,tp,LOCATION_ONFIELD,0,1,c,c)
else
return Duel.IsExistingTarget(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,c)
end
end
if e:GetLabel()~=0 then
e:SetLabel(0)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c83102080.filter,tp,LOCATION_ONFIELD,0,1,1,c,c)
Duel.SendtoGrave(g,REASON_COST)
end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,c)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c83102080.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
nekrozar/ygopro-scripts | c65384188.lua | 2 | 3106 | --実力伯仲
function c65384188.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c65384188.target)
e1:SetOperation(c65384188.activate)
c:RegisterEffect(e1)
end
function c65384188.filter(c)
return c:IsPosition(POS_FACEUP_ATTACK) and c:IsType(TYPE_EFFECT) and not c:IsDisabled()
end
function c65384188.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
if chk==0 then return Duel.IsExistingTarget(c65384188.filter,tp,LOCATION_MZONE,0,1,nil)
and Duel.IsExistingTarget(c65384188.filter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUPATTACK)
Duel.SelectTarget(tp,c65384188.filter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUPATTACK)
Duel.SelectTarget(tp,c65384188.filter,tp,0,LOCATION_MZONE,1,1,nil)
end
function c65384188.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc1,tc2=Duel.GetFirstTarget()
if tc1:IsRelateToEffect(e) and tc1:IsFaceup() and tc2:IsRelateToEffect(e) and tc2:IsFaceup() then
local a=0
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetReset(RESET_EVENT+RESETS_STANDARD)
if not tc1:IsDisabled() then
tc1:RegisterEffect(e1)
tc1:RegisterEffect(e2)
a=a+1
end
if not tc2:IsDisabled() then
local e3=e1:Clone()
local e4=e2:Clone()
tc2:RegisterEffect(e3)
tc2:RegisterEffect(e4)
a=a+1
end
if tc1:IsDefensePos() or tc2:IsDefensePos() or a~=2 then return end
Duel.BreakEffect()
c65384188.reg(c,tc1,tc2)
c65384188.reg(c,tc2,tc1)
end
end
function c65384188.reg(c,tc1,tc2)
tc1:RegisterFlagEffect(65384188,RESET_EVENT+RESETS_STANDARD,0,0)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_CHANGE_POS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetOperation(c65384188.posop)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc1:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e2:SetCondition(c65384188.effcon)
e2:SetValue(1)
e2:SetReset(RESET_EVENT+RESETS_STANDARD)
e2:SetLabelObject(tc2)
tc1:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_CANNOT_CHANGE_POSITION)
tc1:RegisterEffect(e3)
local e4=e2:Clone()
e4:SetCode(EFFECT_CANNOT_ATTACK)
tc1:RegisterEffect(e4)
local e5=e2:Clone()
e5:SetCode(EFFECT_IMMUNE_EFFECT)
e5:SetValue(c65384188.efilter)
tc1:RegisterEffect(e5)
end
function c65384188.posop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:GetFlagEffect(65384188)~=0 and not c:IsPosition(POS_FACEUP_ATTACK) then
c:ResetFlagEffect(65384188)
end
end
function c65384188.effcon(e)
return e:GetHandler():GetFlagEffect(65384188)~=0 and e:GetLabelObject():GetFlagEffect(65384188)~=0
end
function c65384188.efilter(e,te)
return te:GetOwner()~=e:GetOwner()
end
| gpl-2.0 |
vasili-v/themis | vendor/github.com/apache/thrift/lib/lua/TSocket.lua | 113 | 2996 | ---- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
require 'TTransport'
require 'libluasocket'
-- TSocketBase
TSocketBase = TTransportBase:new{
__type = 'TSocketBase',
timeout = 1000,
host = 'localhost',
port = 9090,
handle
}
function TSocketBase:close()
if self.handle then
self.handle:destroy()
self.handle = nil
end
end
-- Returns a table with the fields host and port
function TSocketBase:getSocketInfo()
if self.handle then
return self.handle:getsockinfo()
end
terror(TTransportException:new{errorCode = TTransportException.NOT_OPEN})
end
function TSocketBase:setTimeout(timeout)
if timeout and ttype(timeout) == 'number' then
if self.handle then
self.handle:settimeout(timeout)
end
self.timeout = timeout
end
end
-- TSocket
TSocket = TSocketBase:new{
__type = 'TSocket',
host = 'localhost',
port = 9090
}
function TSocket:isOpen()
if self.handle then
return true
end
return false
end
function TSocket:open()
if self.handle then
self:close()
end
-- Create local handle
local sock, err = luasocket.create_and_connect(
self.host, self.port, self.timeout)
if err == nil then
self.handle = sock
end
if err then
terror(TTransportException:new{
message = 'Could not connect to ' .. self.host .. ':' .. self.port
.. ' (' .. err .. ')'
})
end
end
function TSocket:read(len)
local buf = self.handle:receive(self.handle, len)
if not buf or string.len(buf) ~= len then
terror(TTransportException:new{errorCode = TTransportException.UNKNOWN})
end
return buf
end
function TSocket:write(buf)
self.handle:send(self.handle, buf)
end
function TSocket:flush()
end
-- TServerSocket
TServerSocket = TSocketBase:new{
__type = 'TServerSocket',
host = 'localhost',
port = 9090
}
function TServerSocket:listen()
if self.handle then
self:close()
end
local sock, err = luasocket.create(self.host, self.port)
if not err then
self.handle = sock
else
terror(err)
end
self.handle:settimeout(self.timeout)
self.handle:listen()
end
function TServerSocket:accept()
local client, err = self.handle:accept()
if err then
terror(err)
end
return TSocket:new({handle = client})
end
| apache-2.0 |
kingbuffalo/prototype_code | cpp/ejoy2d_note/examples/ex04.lua | 21 | 1146 | local ej = require "ejoy2d"
local fw = require "ejoy2d.framework"
local pack = require "ejoy2d.simplepackage"
local sprite = require "ejoy2d.sprite"
pack.load {
pattern = fw.WorkDir..[[examples/asset/?]],
"sample",
}
local scissor = false
local obj = ej.sprite("sample","mine")
obj.resource.frame = 70
obj.label.text = "The #[red]quick#[green] brown #[blue]fox jumps#[stop] over the lazy dog"
obj:ps(400,300)
local screencoord = { scale = 1.2 }
local game = {}
function game.update()
obj.frame = obj.frame + 1
end
function game.drawframe()
ej.clear()
obj:draw(screencoord)
end
function game.touch(what, x, y)
if what == "END" then
local touched = obj:test(x,y,screencoord)
if touched then
if touched.name == "label" then
touched.text = "label touched"
end
if touched.name == "panel" then
scissor = not scissor
touched.scissor = scissor
obj.label.text = scissor and "Set scissor" or "Clear scissor"
end
else
obj.label.text = "Not Hit"
end
end
end
function game.message(...)
end
function game.handle_error(...)
end
function game.on_resume()
end
function game.on_pause()
end
ej.start(game)
| mit |
Domderon/spice-minions | hymn/spawnportal.lua | 1 | 1779 | local Entity = require "smee.game_core.entity"
local Building = require "shared.building"
local LogicCore = require "hymn.logiccore"
local EntityStatics = require "hymn.staticdata.entitystatics"
local SpawnPortal = Building:subclass("SpawnPortal")
function SpawnPortal:initialize(entityStatic, playerId)
Building.initialize(self, entityStatic, playerId)
self:setPlayer(playerId)
self:setAnimation("images/buildings/constructionsite.png", 1)
self.timeSinceLastSpawn = 0
self.path = {}
end
function SpawnPortal:setPlayer(playerId)
self.playerId = playerId
local player = LogicCore.players[playerId]
self.theme = player:theme()
-- self:setAnimation("images/buildings/" .. self.theme .. "/portal.png", 0.1)
end
function SpawnPortal:addPathPoint(position)
self.path[#self.path + 1] = position
end
function SpawnPortal:spawnInterval()
local player = LogicCore.players[self.playerId]
return 800/player.resource
end
function SpawnPortal:update(dt)
Building.update(self, dt)
if not self.constructing then
local entityManager = LogicCore.entityManager
self.timeSinceLastSpawn = self.timeSinceLastSpawn + dt
local spawnInterval = self:spawnInterval()
if self.timeSinceLastSpawn >= spawnInterval then --not self.hasSpawned and
-- SPAWN
local spawn = Entity.createFromEStat(self.spawnEntityStatics, self.playerId)
entityManager:add(spawn, LogicCore.layerId.units)
spawn:setPosition(self.position.x, self.position.y)
spawn.userPath = {}
for k, v in pairs(self.path) do
spawn.userPath[k] = v:copy()
end
self.timeSinceLastSpawn = self.timeSinceLastSpawn - spawnInterval
self.hasSpawned = true
end
end
end
function SpawnPortal:clearPath()
self.path = {}
end
return SpawnPortal | mit |
andreaskoepf/nn | WeightedEuclidean.lua | 43 | 8173 | 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, tensorCache)
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, tensorCache)
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 |
nekrozar/ygopro-scripts | c59687381.lua | 4 | 1140 | --ディフェンスゾーン
function c59687381.initial_effect(c)
--Activate
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_ACTIVATE)
e0:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e0)
--cannot be target/indestructable
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e1:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE+EFFECT_FLAG_SET_AVAILABLE)
e1:SetRange(LOCATION_FZONE)
e1:SetTargetRange(LOCATION_SZONE,0)
e1:SetTarget(c59687381.tgtg)
e1:SetValue(aux.tgoval)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e2:SetValue(aux.indoval)
c:RegisterEffect(e2)
local e3=e1:Clone()
e3:SetTargetRange(0,LOCATION_SZONE)
e3:SetValue(aux.tgsval)
c:RegisterEffect(e3)
local e4=e3:Clone()
e4:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e4:SetValue(aux.indsval)
c:RegisterEffect(e4)
end
function c59687381.tgfilter(c,tp)
return c:IsControler(tp) and c:IsLocation(LOCATION_MZONE) and c:GetSequence()<5
end
function c59687381.tgtg(e,c)
return c:GetSequence()<5 and c:GetColumnGroup():FilterCount(c59687381.tgfilter,nil,c:GetControler())>0
end
| gpl-2.0 |
MNoya/DotaCraft | game/dota_addons/dotacraft/scripts/vscripts/heroes/beastmaster/summon_bear.lua | 1 | 1619 | local bearNames = {
[1] = "neutral_beastmaster_bear",
[2] = "neutral_beastmaster_raging_bear",
[3] = "neutral_beastmaster_spirit_bear",
}
function SpawnBear(event)
local caster = event.caster
local ability = event.ability
local duration = ability:GetLevelSpecialValueFor("duration", ability:GetLevel()-1)
local fv = caster:GetForwardVector()
local position = caster:GetAbsOrigin() + fv * 200
local playerID = caster:GetPlayerOwnerID()
local hero = PlayerResource:GetSelectedHeroEntity(playerID)
local bear = caster:CreateSummon(bearNames[ability:GetLevel()], position, duration)
ability:ApplyDataDrivenModifier(caster, bear, "modifier_beastmaster_bear", {})
end
--------------------------------------------------------------------------------
--[[Author: Amused/D3luxe
Used by: Noya
Blinks the target to the target point, if the point is beyond max blink range then blink the maximum range]]
function Blink(keys)
local point = keys.target_points[1]
local caster = keys.caster
local casterPos = caster:GetAbsOrigin()
local difference = point - casterPos
local ability = keys.ability
local range = ability:GetLevelSpecialValueFor("blink_range", (ability:GetLevel() - 1))
if difference:Length2D() > range then
point = casterPos + (point - casterPos):Normalized() * range
end
FindClearSpaceForUnit(caster, point, false)
Timers:CreateTimer(0.15, function()
ParticleManager:CreateParticle("particles/units/heroes/hero_lone_druid/lone_druid_bear_blink_end.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster)
end)
end | gpl-3.0 |
theonlywild/otouto | plugins/imdb.lua | 16 | 1101 | local command = 'imdb <query>'
local doc = [[```
/imdb <query>
Returns an IMDb entry.
```]]
local triggers = {
'^/imdb[@'..bot.username..']*'
}
local action = function(msg)
local input = msg.text:input()
if not input then
if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text
else
sendMessage(msg.chat.id, doc, true, msg.message_id, true)
return
end
end
local url = 'http://www.omdbapi.com/?t=' .. URL.escape(input)
local jstr, res = HTTP.request(url)
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
end
local jdat = JSON.decode(jstr)
if jdat.Response ~= 'True' then
sendReply(msg, config.errors.results)
return
end
local output = '[' .. jdat.Title .. '](http://imdb.com/title/'
output = output .. jdat.imdbID .. ') ('.. jdat.Year ..')\n'
output = output .. jdat.imdbRating ..'/10 | '.. jdat.Runtime ..' | '.. jdat.Genre ..'\n'
output = output .. jdat.Plot
sendMessage(msg.chat.id, output, true, nil, true)
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}
| gpl-2.0 |
finalsliver/supervillain-ui | SVUI_Skins/components/addons/TradeSkillDW.lua | 2 | 5779 | --[[
##########################################################
S V U I By: Failcoder
##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
local pairs = _G.pairs;
local string = _G.string;
--[[ STRING METHODS ]]--
local format = string.format;
--[[
##########################################################
GET ADDON DATA
##########################################################
]]--
local SV = _G['SVUI'];
local L = SV.L;
local MOD = SV.Skins;
local Schema = MOD.Schema;
--[[
##########################################################
TSDW
##########################################################
]]--
local function StyleTradeSkillDW()
assert(TradeSkillDW_QueueFrame, "AddOn Not Loaded")
TradeSkillFrame:SetStyle("Frame", "Window2")
TradeSkillListScrollFrameScrollBar:RemoveTextures(true)
TradeSkillDetailScrollFrameScrollBar:RemoveTextures(true)
TradeSkillFrameInset:RemoveTextures(true)
TradeSkillExpandButtonFrame:RemoveTextures(true)
TradeSkillDetailScrollChildFrame:RemoveTextures(true)
TradeSkillListScrollFrameScrollBar:RemoveTextures(true)
SV.API:Set("Frame", TradeSkillGuildFrame,"Transparent")
SV.API:Set("Frame", TradeSkillGuildFrameContainer,"Transparent")
TradeSkillGuildFrame:SetPoint("BOTTOMLEFT", TradeSkillFrame, "BOTTOMRIGHT", 3, 19)
SV.API:Set("CloseButton", TradeSkillGuildFrameCloseButton)
TradeSkillFrame:HookScript("OnShow", function()
SV.API:Set("Frame", TradeSkillFrame)
TradeSkillListScrollFrameScrollBar:RemoveTextures()
if not TradeSkillDWExpandButton then return end
if not TradeSkillDWExpandButton.styled then
SV.API:Set("PageButton", TradeSkillDWExpandButton)
TradeSkillDWExpandButton.styled = true
end
end)
TradeSkillFrame:SetHeight(TradeSkillFrame:GetHeight() + 12)
TradeSkillRankFrame:SetStyle("Frame", 'Transparent')
TradeSkillRankFrame:SetStatusBarTexture(SV.media.statusbar.default)
TradeSkillCreateButton:SetStyle("Button")
TradeSkillCancelButton:SetStyle("Button")
TradeSkillFilterButton:SetStyle("Button")
TradeSkillCreateAllButton:SetStyle("Button")
TradeSkillViewGuildCraftersButton:SetStyle("Button")
TradeSkillLinkButton:GetNormalTexture():SetTexCoord(0.25, 0.7, 0.37, 0.75)
TradeSkillLinkButton:GetPushedTexture():SetTexCoord(0.25, 0.7, 0.45, 0.8)
TradeSkillLinkButton:GetHighlightTexture():Die()
SV.API:Set("Frame", TradeSkillLinkButton,"Transparent")
TradeSkillLinkButton:SetSize(17, 14)
TradeSkillLinkButton:SetPoint("LEFT", TradeSkillLinkFrame, "LEFT", 5, -1)
TradeSkillFrameSearchBox:SetStyle("Editbox")
TradeSkillInputBox:SetStyle("Editbox")
TradeSkillIncrementButton:SetPoint("RIGHT", TradeSkillCreateButton, "LEFT", -13, 0)
SV.API:Set("CloseButton", TradeSkillFrameCloseButton)
SV.API:Set("ScrollBar", TradeSkillDetailScrollFrameScrollBar)
local once = false
hooksecurefunc("TradeSkillFrame_SetSelection", function(id)
TradeSkillSkillIcon:SetStyle("Button")
if TradeSkillSkillIcon:GetNormalTexture() then
TradeSkillSkillIcon:GetNormalTexture():SetTexCoord(0.1,0.9,0.1,0.9)
TradeSkillSkillIcon:GetNormalTexture():ClearAllPoints()
TradeSkillSkillIcon:GetNormalTexture():SetPoint("TOPLEFT", 2, -2)
TradeSkillSkillIcon:GetNormalTexture():SetPoint("BOTTOMRIGHT", -2, 2)
end
for i = 1, MAX_TRADE_SKILL_REAGENTS do
local button = _G["TradeSkillReagent"..i]
local icon = _G["TradeSkillReagent"..i.."IconTexture"]
local count = _G["TradeSkillReagent"..i.."Count"]
icon:SetTexCoord(0.1,0.9,0.1,0.9)
icon:SetDrawLayer("OVERLAY")
if not icon.backdrop then
icon.backdrop = CreateFrame("Frame", nil, button)
icon.backdrop:SetFrameLevel(button:GetFrameLevel() - 1)
SV.API:Set("Frame", icon.backdrop,"Transparent")
icon.backdrop:SetPoint("TOPLEFT", icon, "TOPLEFT", -2, 2)
icon.backdrop:SetPoint("BOTTOMRIGHT", icon, "BOTTOMRIGHT", 2, -2)
end
icon:SetParent(icon.backdrop)
count:SetParent(icon.backdrop)
count:SetDrawLayer("OVERLAY")
if i > 2 and once == false then
local point, anchoredto, point2, x, y = button:GetPoint()
button:ClearAllPoints()
button:SetPoint(point, anchoredto, point2, x, y - 3)
once = true
end
_G["TradeSkillReagent"..i.."NameFrame"]:Die()
end
end)
TradeSkillDW_QueueFrame:HookScript("OnShow", function() SV.API:Set("Frame", TradeSkillDW_QueueFrame,"Transparent") end)
SV.API:Set("CloseButton", TradeSkillDW_QueueFrameCloseButton)
TradeSkillDW_QueueFrameInset:RemoveTextures()
TradeSkillDW_QueueFrameClear:SetStyle("Button")
TradeSkillDW_QueueFrameDown:SetStyle("Button")
TradeSkillDW_QueueFrameUp:SetStyle("Button")
TradeSkillDW_QueueFrameDo:SetStyle("Button")
TradeSkillDW_QueueFrameDetailScrollFrameScrollBar:RemoveTextures()
TradeSkillDW_QueueFrameDetailScrollFrameChildFrame:RemoveTextures()
TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent1:RemoveTextures()
TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent2:RemoveTextures()
TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent3:RemoveTextures()
TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent4:RemoveTextures()
TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent5:RemoveTextures()
TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent6:RemoveTextures()
TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent7:RemoveTextures()
TradeSkillDW_QueueFrameDetailScrollFrameChildFrameReagent8:RemoveTextures()
SV.API:Set("ScrollBar", TradeSkillDW_QueueFrameDetailScrollFrameScrollBar)
TradeSkillListScrollFrameScrollBar:RemoveTextures()
end
--[[#################################################]]--
MOD:SaveAddonStyle("TradeSkillDW", StyleTradeSkillDW)
| mit |
finalsliver/supervillain-ui | SVUI_UnitFrames/libs/oUF_1.6.9/elements/combat.lua | 7 | 1931 | --[[ Element: Combat Icon
Toggles the visibility of `self.Combat` based on the player's combat status.
Widget
Combat - Any UI widget.
Notes
The default assistant icon will be applied if the UI widget is a texture and
doesn't have a texture or color defined.
Examples
-- Position and size
local Combat = self:CreateTexture(nil, "OVERLAY")
Combat:SetSize(16, 16)
Combat:SetPoint('TOP', self)
-- Register it with oUF
self.Combat = Combat
Hooks
Override(self) - Used to completely override the internal update function.
Removing the table key entry will make the element fall-back
to its internal function again.
]]
local parent, ns = ...
local oUF = ns.oUF
local Update = function(self, event)
local combat = self.Combat
if(combat.PreUpdate) then
combat:PreUpdate()
end
local inCombat = UnitAffectingCombat('player')
if(inCombat) then
combat:Show()
else
combat:Hide()
end
if(combat.PostUpdate) then
return combat:PostUpdate(inCombat)
end
end
local Path = function(self, ...)
return (self.Combat.Override or Update) (self, ...)
end
local ForceUpdate = function(element)
return Path(element.__owner, 'ForceUpdate')
end
local Enable = function(self, unit)
local combat = self.Combat
if(combat and unit == 'player') then
combat.__owner = self
combat.ForceUpdate = ForceUpdate
self:RegisterEvent("PLAYER_REGEN_DISABLED", Path, true)
self:RegisterEvent("PLAYER_REGEN_ENABLED", Path, true)
if(combat:IsObjectType"Texture" and not combat:GetTexture()) then
combat:SetTexture[[Interface\CharacterFrame\UI-StateIcon]]
combat:SetTexCoord(.5, 1, 0, .49)
end
return true
end
end
local Disable = function(self)
if(self.Combat) then
self.Combat:Hide()
self:UnregisterEvent("PLAYER_REGEN_DISABLED", Path)
self:UnregisterEvent("PLAYER_REGEN_ENABLED", Path)
end
end
oUF:AddElement('Combat', Path, Enable, Disable)
| mit |
nekrozar/ygopro-scripts | c87931906.lua | 1 | 4008 | --月光融合
function c87931906.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_FUSION_SUMMON+CATEGORY_DECKDES)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,87931906+EFFECT_COUNT_CODE_OATH)
e1:SetTarget(c87931906.target)
e1:SetOperation(c87931906.activate)
c:RegisterEffect(e1)
end
function c87931906.filter0(c)
return c:IsSetCard(0xdf) and c:IsType(TYPE_MONSTER) and c:IsCanBeFusionMaterial() and c:IsAbleToGrave()
end
function c87931906.filter1(c,e)
return not c:IsImmuneToEffect(e)
end
function c87931906.filter2(c,e,tp,m,f,chkf)
return c:IsType(TYPE_FUSION) and c:IsSetCard(0xdf) and (not f or f(c))
and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_FUSION,tp,false,false) and c:CheckFusionMaterial(m,nil,chkf)
end
function c87931906.cfilter(c)
return c:GetSummonLocation()==LOCATION_EXTRA
end
function c87931906.fcheck(tp,sg,fc)
return sg:FilterCount(Card.IsLocation,nil,LOCATION_DECK+LOCATION_EXTRA)<=1
end
function c87931906.gcheck(sg)
return sg:FilterCount(Card.IsLocation,nil,LOCATION_DECK+LOCATION_EXTRA)<=1
end
function c87931906.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local chkf=tp
local mg1=Duel.GetFusionMaterial(tp)
if Duel.IsExistingMatchingCard(c87931906.cfilter,tp,0,LOCATION_MZONE,1,nil) then
local mg2=Duel.GetMatchingGroup(c87931906.filter0,tp,LOCATION_DECK+LOCATION_EXTRA,0,nil)
if mg2:GetCount()>0 then
mg1:Merge(mg2)
Auxiliary.FCheckAdditional=c87931906.fcheck
Auxiliary.GCheckAdditional=c87931906.gcheck
end
end
local res=Duel.IsExistingMatchingCard(c87931906.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg1,nil,chkf)
Auxiliary.FCheckAdditional=nil
Auxiliary.GCheckAdditional=nil
if not res then
local ce=Duel.GetChainMaterial(tp)
if ce~=nil then
local fgroup=ce:GetTarget()
local mg3=fgroup(ce,e,tp)
local mf=ce:GetValue()
res=Duel.IsExistingMatchingCard(c87931906.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg3,mf,chkf)
end
end
return res
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c87931906.activate(e,tp,eg,ep,ev,re,r,rp)
local chkf=tp
local mg1=Duel.GetFusionMaterial(tp):Filter(c87931906.filter1,nil,e)
local exmat=false
if Duel.IsExistingMatchingCard(c87931906.cfilter,tp,0,LOCATION_MZONE,1,nil) then
local mg2=Duel.GetMatchingGroup(c87931906.filter0,tp,LOCATION_DECK+LOCATION_EXTRA,0,nil)
if mg2:GetCount()>0 then
mg1:Merge(mg2)
exmat=true
end
end
if exmat then
Auxiliary.FCheckAdditional=c87931906.fcheck
Auxiliary.GCheckAdditional=c87931906.gcheck
end
local sg1=Duel.GetMatchingGroup(c87931906.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg1,nil,chkf)
Auxiliary.FCheckAdditional=nil
Auxiliary.GCheckAdditional=nil
local mg3=nil
local sg2=nil
local ce=Duel.GetChainMaterial(tp)
if ce~=nil then
local fgroup=ce:GetTarget()
mg3=fgroup(ce,e,tp)
local mf=ce:GetValue()
sg2=Duel.GetMatchingGroup(c87931906.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg3,mf,chkf)
end
if sg1:GetCount()>0 or (sg2~=nil and sg2:GetCount()>0) then
local sg=sg1:Clone()
if sg2 then sg:Merge(sg2) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local tg=sg:Select(tp,1,1,nil)
local tc=tg:GetFirst()
mg1:RemoveCard(tc)
if sg1:IsContains(tc) and (sg2==nil or not sg2:IsContains(tc) or not Duel.SelectYesNo(tp,ce:GetDescription())) then
if exmat then
Auxiliary.FCheckAdditional=c87931906.fcheck
Auxiliary.GCheckAdditional=c87931906.gcheck
end
local mat1=Duel.SelectFusionMaterial(tp,tc,mg1,nil,chkf)
Auxiliary.FCheckAdditional=nil
Auxiliary.GCheckAdditional=nil
tc:SetMaterial(mat1)
Duel.SendtoGrave(mat1,REASON_EFFECT+REASON_MATERIAL+REASON_FUSION)
Duel.BreakEffect()
Duel.SpecialSummon(tc,SUMMON_TYPE_FUSION,tp,tp,false,false,POS_FACEUP)
else
local mat2=Duel.SelectFusionMaterial(tp,tc,mg3,nil,chkf)
local fop=ce:GetOperation()
fop(ce,e,tp,tc,mat2)
end
tc:CompleteProcedure()
end
end
| gpl-2.0 |
Pandafuchs/iLife | server/Classes/Shop/cWellStackedPizza.lua | 2 | 6351 | CWellStackedPizza = inherit(CShop)
function CWellStackedPizza:constructor(dim)
self.Dim = dim
self.Ped = createPed ( 155, 376.6845703125, -117.2783203125, 1001.4921875, 180, false)
setElementInterior(self.Ped, 5)
setElementDimension(self.Ped, self.Dim)
setElementData(self.Ped, "EastereggPed", true)
new(CShopRob, dim, self.Ped)
self.Marker = createMarker(376.681640625,-118.94140625,1001.4995117188, "corona", 1, 255, 255, 255, 125, getRootElement())
setElementInterior(self.Marker, 5)
setElementDimension(self.Marker, self.Dim)
self.Ped2 = createPed ( 155, 372.91796875, -117.27734375, 1001.4921875, 180, false)
setElementInterior(self.Ped2, 5)
setElementDimension(self.Ped2, self.Dim)
setElementData(self.Ped2, "EastereggPed", true)
ItemShops[7].addMarker(ItemShops[7], 5, dim, 373.1552734375, -118.8056640625, 1001.4921875)
self.Menus = {
[1] = createObject(2218, 377.79998779297, -118.09999847412, 1001.5999755859, 336, 21, 72.25),
[2] = createObject(2219, 378.70001220703, -118.09999847412, 1001.5992431641, 336, 21, 72.25),
[3] = createObject(2220, 379.60000610352, -118.09999847412, 1001.5999755859, 336, 21, 72.25)
}
self.Names = {
[1] = "Menu Small",
[2] = "Menu Medium",
[3] = "Menu Large"
}
self.Prices = {
[1] = 5,
[2] = 10,
[3] = 15
}
self.Hunger = {
[1] = 30,
[2] = 60,
[3] = 100
}
for k,v in ipairs(self.Menus) do
setElementInterior(v, 5)
setElementDimension(v, self.Dim)
end
self.eOnMarkerHit = bind(self.onMarkerHit, self)
addEventHandler("onMarkerHit", self.Marker, self.eOnMarkerHit)
self.bStop = bind(self.stop, self)
self.bNext = bind(self.next, self)
self.bBack = bind(self.back, self)
self.bBuy = bind(self.buy, self)
self.Display = {}
self.Texts = {}
self.State = {}
self.ID = dim-20000
CShop.constructor(self, "WellStackedPizza", self.ID)
end
function CWellStackedPizza:destructor()
end
function CWellStackedPizza:onMarkerHit(theElement, matchDimension)
if (matchDimension) then
if (getElementType(theElement) == "player") then
self:start(theElement)
end
end
end
function CWellStackedPizza:start(thePlayer)
self.Display[getPlayerName(thePlayer)] = textCreateDisplay()
self.Texts[getPlayerName(thePlayer)] = {}
self.State[getPlayerName(thePlayer)] = 1
self.Texts[getPlayerName(thePlayer)]["Menu"] = textCreateTextItem(self.Names[self.State[getPlayerName(thePlayer)]].." - "..self.Prices[self.State[getPlayerName(thePlayer)]].."$", 0.05, 0.8)
textItemSetScale ( self.Texts[getPlayerName(thePlayer)]["Menu"], 2 )
textDisplayAddText (self.Display[getPlayerName(thePlayer)], self.Texts[getPlayerName(thePlayer)]["Menu"])
self.Texts[getPlayerName(thePlayer)]["Control1"] = textCreateTextItem("Links/Rechts - Vor/Zurück", 0.05, 0.85)
textItemSetScale ( self.Texts[getPlayerName(thePlayer)]["Control1"], 2 )
textDisplayAddText (self.Display[getPlayerName(thePlayer)], self.Texts[getPlayerName(thePlayer)]["Control1"])
self.Texts[getPlayerName(thePlayer)]["Control2"] = textCreateTextItem("Leertaste - Kaufen", 0.05, 0.9)
textItemSetScale ( self.Texts[getPlayerName(thePlayer)]["Control2"], 2 )
textDisplayAddText (self.Display[getPlayerName(thePlayer)], self.Texts[getPlayerName(thePlayer)]["Control2"])
self.Texts[getPlayerName(thePlayer)]["Control3"] = textCreateTextItem("Enter - Verlassen", 0.05, 0.95)
textItemSetScale ( self.Texts[getPlayerName(thePlayer)]["Control3"], 2 )
textDisplayAddText (self.Display[getPlayerName(thePlayer)], self.Texts[getPlayerName(thePlayer)]["Control3"])
textDisplayAddObserver(self.Display[getPlayerName(thePlayer)], thePlayer)
local lx,ly,lz = getElementPosition(self.Menus[self.State[getPlayerName(thePlayer)]])
setCameraMatrix(thePlayer, lx-0.2, ly-0.5, lz+0.5, lx-0.2, ly, lz)
toggleAllControls(thePlayer, false)
bindKey(thePlayer, "enter", "down", self.bStop)
bindKey(thePlayer, "space", "down", self.bBuy)
bindKey(thePlayer, "left", "down", self.bBack)
bindKey(thePlayer, "right", "down", self.bNext)
end
function CWellStackedPizza:stop(thePlayer)
textDestroyDisplay(self.Display[getPlayerName(thePlayer)])
self.Display[getPlayerName(thePlayer)] = nil
textDestroyTextItem(self.Texts[getPlayerName(thePlayer)]["Menu"])
self.Texts[getPlayerName(thePlayer)]["Menu"] = nil
textDestroyTextItem(self.Texts[getPlayerName(thePlayer)]["Control1"])
self.Texts[getPlayerName(thePlayer)]["Control1"] = nil
textDestroyTextItem(self.Texts[getPlayerName(thePlayer)]["Control2"])
self.Texts[getPlayerName(thePlayer)]["Control2"] = nil
textDestroyTextItem(self.Texts[getPlayerName(thePlayer)]["Control3"])
self.Texts[getPlayerName(thePlayer)]["Control3"] = nil
self.State[getPlayerName(thePlayer)] = nil
unbindKey(thePlayer, "enter", "down", self.bStop)
unbindKey(thePlayer, "space", "down", self.bBuy)
unbindKey(thePlayer, "left", "down", self.bBack)
unbindKey(thePlayer, "right", "down", self.bNext)
toggleAllControls(thePlayer, true)
setCameraTarget(thePlayer, thePlayer)
end
function CWellStackedPizza:next(thePlayer)
if (self.State[getPlayerName(thePlayer)] >= #self.Menus) then
self.State[getPlayerName(thePlayer)] = 1
else
self.State[getPlayerName(thePlayer)] = self.State[getPlayerName(thePlayer)]+1
end
textItemSetText(self.Texts[getPlayerName(thePlayer)]["Menu"], self.Names[self.State[getPlayerName(thePlayer)]].." - "..self.Prices[self.State[getPlayerName(thePlayer)]].."$")
local lx,ly,lz = getElementPosition(self.Menus[self.State[getPlayerName(thePlayer)]])
setCameraMatrix(thePlayer, lx-0.2, ly-0.5, lz+0.5, lx-0.2, ly, lz)
end
function CWellStackedPizza:back(thePlayer)
if (self.State[getPlayerName(thePlayer)] <= 1) then
self.State[getPlayerName(thePlayer)] = #self.Menus
else
self.State[getPlayerName(thePlayer)] = self.State[getPlayerName(thePlayer)]-1
end
textItemSetText(self.Texts[getPlayerName(thePlayer)]["Menu"], self.Names[self.State[getPlayerName(thePlayer)]].." - "..self.Prices[self.State[getPlayerName(thePlayer)]].."$")
local lx,ly,lz = getElementPosition(self.Menus[self.State[getPlayerName(thePlayer)]])
setCameraMatrix(thePlayer, lx-0.2, ly-0.5, lz+0.5, lx-0.2, ly, lz)
end
function CWellStackedPizza:buy(thePlayer)
local choose = self.State[getPlayerName(thePlayer)]
if (thePlayer:payMoney(self.Prices[choose])) then
thePlayer:eat(self.Hunger[self.State[getPlayerName(thePlayer)]])
end
end
| mit |
NijigenDevs/QSanguosha-For-Saimoe | extension-doc/2-SkillGeneral.lua | 15 | 8474 | --1.技能
--要说三国杀武将DIY,不得不说的就是技能。
--神杀给技能留的接口,与平时我们所说的技能分类有点区别。
--基本上来讲,技能分为以下几种:
--视为技:
--龙胆、武圣等等
--特点:可以将某牌当作另一种牌使用
--触发技:
--奸雄、反馈等等
--特点:在某个时机,可以执行某某效果
--距离技:
--马术、飞影
--特点:不用说大家都明白
--手牌上限技
--横江(后续效果)
--特点:还能是什么
--克己不是手牌上限技,是触发技
--目标修改技
--咆哮、集智、天义(后续效果)
--特点:修改某张牌在出牌阶段内的使用次数、修改某张牌可以选择的目标人数、修改某张牌可以选择的距离限制
--技能共通:
--所有的技能都通过sgs.CreateXXXSkill这个函数来实现,比如触发技:
thetrigger = sgs.CreateTriggerSkill{
name = "thetrigger" ,
events = {sgs.EventPhaseStart} ,
can_trigger = function(self, event, room, player, data)
blablabla
end ,
on_cost = function(self, event, room, player, data)
blablabla
end ,
on_effect = function(self, evnet, room, player, data)
blablabla
end ,
}
--所有技能共通的属性放在这里,在技能讲解时将不再仔细讲它们的作用。
--name:
--字符串类型,表示技能的名字
--没有默认值,不能为空。
--relate_to_place:
--字符串类型,但是除了默认值之外,只能取两个值。
--"head":表示该技能是主将技。
--"deputy":表示该技能是副将技。
--不写取值或者取值为nil,则为主副将皆有的技能。
--除了技能之外,还要讲一下的就是技能卡。
--类似仁德、制衡等等这种出牌阶段空闲时间的技能,没有固定的时机。
--他们的效果也不是普通的游戏牌里所拥有的。
--这时就需要技能卡来解决这个问题了
--技能卡其实是个虚拟的牌,用于解决这类技能问题,有些触发技也需要用到技能卡来实现技能。
--说白了就是技能卡就是被神杀当作牌,而这类的牌的效果就是技能的效果。
--技能卡需要使用视为技才能使用,也就是将某牌(甚至没有牌)当技能卡这种牌来使用。
--仁德、制衡、离间、驱虎等等,为出牌阶段使用的技能卡
--流离(TargetConfirming)、天香(DamageInflicted)、突袭(EventPhaseStart)、巧变(EventPhaseChanging)等等,为响应时使用的技能卡
--触发技的触发时机
TriggerEvent = {
NonTrigger, --没有时机,不能触发技能
GameStart, --游戏开始时:化身
TurnStart, --回合开始前:争功(倚天)
EventPhaseStart, --阶段开始时(包括回合开始时,各个阶段的开始时,回合结束时和结束后):突袭等等,这类技能很多
EventPhaseProceeding, --阶段进行时:无技能
EventPhaseEnd, --阶段结束时:生息
EventPhaseChanging, --阶段转换时(也就是两个阶段中间的时间点):巧变、克己, data:toPhaseChange()
EventPhaseSkipping, --阶段被跳过时:无技能
DrawNCards, --摸排阶段摸牌时(英姿、好施前半部分), data:toInt()
AfterDrawNCards, --摸牌阶段摸牌后(好施后半部分), data:toInt()
PreHpRecover, --回复体力前:无技能, data:toRecover()
HpRecover, --回复体力时:恩怨, data:toRecover()
PreHpLost, --体力流失前:弘法, data:toInt()
HpChanged, --体力变化时:无技能
MaxHpChanged, --体力上限变化时:无技能
PostHpReduced, --体力变化后:规则里最重要的濒死结算在此时机0优先级, data:toInt()(用于流失体力)/data:toDamage()(用于伤害)
EventLoseSkill, --失去技能时:不屈, data:toString()
EventAcquireSkill, --获得技能时:有技能,但是举不出来例子, data:toString()
StartJudge, --判定开始时:咒缚, data:toJudge()
AskForRetrial, --改判时:鬼才、鬼道, data:toJudge()
FinishRetrial, --改判后:无技能, data:toJudge()
FinishJudge, --判定生效时:天妒、屯田后续效果, data:toJudge()
PindianVerifying, --拼点检查时:鹰扬, data:toPindian()
Pindian, --拼点生效时:制霸收拼点牌等等, data:toPindian()
TurnedOver, --武将牌被翻面时(对于国战来讲是叠置):解围
ChainStateChanged, --武将牌被横置或重置时:无技能
ConfirmDamage, --计算伤害点数:酒, data:toDamage()
Predamage, --造成伤害前:绝情, data:toDamage()
DamageForseen, --受到伤害前:狂风大雾, data:toDamage()
DamageCaused, --造成伤害时:装备寒冰剑、潜袭(旧), data:toDamage()
DamageInflicted, --受到伤害时:天香,装备藤甲伤害+1的效果, data:toDamage()
PreDamageDone, --造成伤害扣减体力时:武魂加标记, data:toDamage()
DamageDone, --造成伤害扣减体力后:无技能, data:toDamage()
Damage, --造成伤害后:烈刃,胆守, data:toDamage()
Damaged, --受到伤害后:奸雄反馈遗计等等,技能非常多, data:toDamage()
DamageComplete, --铁索,天香誓仇摸牌, data:toDamage()
Dying, --进入濒死状态时:补益, data:toDying()
QuitDying, --濒死结算后:黩武失去体力的效果, data:toDying()
AskForPeaches, --处于濒死状态时:涅槃, data:toDying()
AskForPeachesDone, --处于濒死状态时(求桃结束):不屈防止死亡的效果, data:toDying()
Death, --死亡时:断肠挥泪, data:toDeath()
BuryVictim, --死亡后(注意优先级为负):飞龙夺凤复活, data:toDeath()
BeforeGameOverJudge, --死亡前:焚心, data:toDeath()
GameOverJudge, --判断是否游戏结束时:狱刎(智), data:toDeath()
GameFinished, --游戏结束时:无技能
SlashEffected, --杀生效时(防止杀的效果专用):享乐等等,技能非常多, data:toSlashEffect()
SlashProceed, --杀求闪时:旧版烈弓、旧版铁骑, data:toSlashEffect()
SlashHit, --杀击中时:无技能, data:toSlashEffect()
SlashMissed, --杀被闪避时:武器青龙刀,虎啸, data:toSlashEffect()
JinkEffect, --闪生效时(防止闪的效果专用):大喝后续效果, data:toCard()
CardAsked, --求响应牌时:护驾、激将、八阵, data:toStringList()
CardResponded, --响应牌时:雷击, data:toCardResponse()
BeforeCardsMove, --卡牌移动时(注意此时卡牌还未移动):落英、礼让、巨象, data:toMoveOneTime()
CardsMoveOneTime, --卡牌移动后:惜粮(倚天), data:toMoveOneTime()
PreCardUsed, --卡牌使用前(用于限次数的视为普通牌的技能), data:toCardUse()
CardUsed, --卡牌使用时(不包括使用闪):集智, data:toCardUse()
TargetConfirming, --指定/成为目标时:享乐、流离, data:toCardUse()
TargetConfirmed, --指定/成为目标后:铁骑、烈弓, data:toCardUse()
CardEffect, --卡牌生效前(不要触发技能!!!), data:toCardEffect()
CardEffected, --卡牌生效时(防止除了杀之外的其他牌效果使用,注意杀也会经历此时机,不要无效!!会导致残留qinggang tag造成防具一直无效问题!!!), data:toCardEffect()
PostCardEffected, --卡牌生效后:无技能, data:toCardEffect()
CardFinished, --卡牌结算完毕, data:toCardEffect()
TrickCardCanceling, --锦囊牌询问无懈可击时:探虎拼点之后的效果, data:toCardEffect()
ChoiceMade, --做出选择后,用于战功包, data:toString()
--这4个时机用于其他游戏模式,国战没用
StageChange, --虎牢关专用,神吕布变身为第二形态,注意此时机是用来throw的而不是用来触发的
FetchDrawPileCard, --小型场景用,摸牌堆牌
ActionedReset, --武将牌重置时,用于3v3
Debut, --登场时,用于1v1和血战到底
TurnBroken, --结算终止回合结束,用于胆守和翩仪,注意此时机是用来throw的而不是用来触发的
--这3个时机用于官方国战
GeneralShown, --武将牌明置时:闺秀, data:toBool()
GeneralHidden, --武将牌暗置时:不屈进入濒死状态的时机, data:toBool()
GeneralRemoved, --武将牌被移除时:闺秀, data:toString()
NumOfEvents --时机总数(不能触发技能)
}
| gpl-3.0 |
nekrozar/ygopro-scripts | c43661068.lua | 3 | 1554 | --星に願いを
function c43661068.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c43661068.target)
e1:SetOperation(c43661068.activate)
c:RegisterEffect(e1)
end
function c43661068.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c43661068.tfilter(chkc,tp) end
if chk==0 then return Duel.IsExistingTarget(c43661068.tfilter,tp,LOCATION_MZONE,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c43661068.tfilter,tp,LOCATION_MZONE,0,1,1,nil,tp)
end
function c43661068.filter(c,atk,def)
return c:IsFaceup() and c:GetLevel()>0 and (c:IsAttack(atk) or c:IsDefense(def))
end
function c43661068.tfilter(c,tp)
return c:IsFaceup() and c:GetLevel()>0
and Duel.IsExistingMatchingCard(c43661068.filter,tp,LOCATION_MZONE,0,1,c,c:GetAttack(),c:GetDefense())
end
function c43661068.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
local g=Duel.GetMatchingGroup(c43661068.filter,tp,LOCATION_MZONE,0,tc,tc:GetAttack(),tc:GetDefense())
local lv=tc:GetLevel()
local lc=g:GetFirst()
while lc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetValue(lv)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
lc:RegisterEffect(e1)
lc=g:GetNext()
end
end
end
| gpl-2.0 |
nekrozar/ygopro-scripts | c64437633.lua | 3 | 1758 | --儀水鏡の幻影術
function c64437633.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c64437633.target)
e1:SetOperation(c64437633.activate)
c:RegisterEffect(e1)
end
function c64437633.filter(c,e,tp)
return c:IsSetCard(0x3a) and bit.band(c:GetType(),0x81)==0x81 and c:IsCanBeSpecialSummoned(e,0,tp,false,true)
end
function c64437633.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c64437633.filter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,LOCATION_HAND)
end
function c64437633.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c64437633.filter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
local tc=g:GetFirst()
if tc then
Duel.SpecialSummon(tc,0,tp,tp,false,true,POS_FACEUP)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_ATTACK)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1,true)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetOperation(c64437633.retop)
e2:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
e2:SetCountLimit(1)
tc:RegisterEffect(e2,true)
end
end
function c64437633.retop(e,tp,eg,ep,ev,re,r,rp)
Duel.SendtoHand(e:GetHandler(),nil,REASON_EFFECT)
end
| gpl-2.0 |
nekrozar/ygopro-scripts | c14541657.lua | 4 | 2021 | --黄昏の忍者-シンゲツ
function c14541657.initial_effect(c)
--untargetable
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SELECT_BATTLE_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(0,LOCATION_MZONE)
e1:SetValue(c14541657.atlimit)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e2:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e2:SetRange(LOCATION_MZONE)
e2:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e2:SetTarget(c14541657.tglimit)
e2:SetValue(aux.tgoval)
c:RegisterEffect(e2)
--tohand
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e3:SetCountLimit(1,14541657)
e3:SetCondition(c14541657.thcon)
e3:SetTarget(c14541657.thtg)
e3:SetOperation(c14541657.thop)
c:RegisterEffect(e3)
end
function c14541657.atlimit(e,c)
return c:IsFaceup() and c:IsSetCard(0x2b) and c~=e:GetHandler()
end
function c14541657.tglimit(e,c)
return c:IsSetCard(0x2b) and c~=e:GetHandler()
end
function c14541657.thcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsReason(REASON_BATTLE)
or (rp==1-tp and c:IsReason(REASON_DESTROY) and c:GetPreviousControler()==tp)
end
function c14541657.thfilter(c)
return c:IsSetCard(0x2b) and c:IsType(TYPE_MONSTER) and not c:IsCode(14541657) and c:IsAbleToHand()
end
function c14541657.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c14541657.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c14541657.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c14541657.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
venkatarajasekhar/bee | test/db/ipc.test.lua | 1 | 3402 | fiber = require('fiber')
ch = fiber.channel()
ch:size()
ch:count()
ch:is_full()
ch:is_empty()
ch:get(.1)
ch:put()
ch:count()
ch:put('test')
ch:get()
ch:get('wrong timeout')
ch:get(-10)
ch:put(234)
ch:put(345, .5)
ch:count()
ch:is_full()
ch:is_empty()
buffer = {}
--# setopt delimiter ';'
tfbr = fiber.create(
function()
while true do
table.insert(buffer, ch:get())
end
end
);
t = {};
for i = 1, 10 do
table.insert(t, {i, ch:put(i, 0.1)})
end;
--# setopt delimiter ''
t
ch:has_readers()
ch:has_writers()
fiber.cancel(tfbr)
ch:has_readers()
ch:has_writers()
ch:count()
ch:put(db.info.pid)
ch:count()
ch:is_full()
ch:is_empty()
ch:get(db.info.pid) == db.info.pid
buffer
ch:is_empty()
ch:broadcast()
ch:broadcast(123)
ch:get()
ch:is_full()
ch:is_empty()
--# setopt delimiter ';'
tfbr = fiber.create(
function()
while true do
local v = ch:get()
table.insert(buffer, {'tfbr', tostring(v)})
end
end
);
tfbr2 = fiber.create(
function()
while true do
local v = ch:get()
table.insert(buffer, {'tfbr2', tostring(v)})
end
end
);
--# setopt delimiter ''
buffer = {}
buffer
ch:is_full()
ch:is_empty()
ch:put(1)
ch:put(2)
ch:put(3)
ch:put(4)
ch:put(5)
ch:broadcast('broadcast message!')
t = {}
for i = 35, 45 do table.insert(t, ch:put(i)) end
t
buffer
ch = fiber.channel(1)
ch:is_closed()
passed = false
type(fiber.create(function() if ch:get() == nil then passed = true end end))
ch:close()
passed
ch:get()
ch:get()
ch:put(10)
ch:is_closed()
ch = fiber.channel(1)
ch:put(true)
ch:is_closed()
passed = false
type(fiber.create(function() if ch:put(true) == false then passed = true end end))
ch:close()
passed
ch:get()
ch:get()
ch:put(10)
ch:is_closed()
-- race conditions
chs= {}
count= 0
res= { }
--# setopt delimiter ';'
for i = 1, 10 do table.insert(chs, fiber.channel()) end;
for i = 1, 10 do
local no = i fiber.create(
function()
fiber.self():name('pusher')
while true do
chs[no]:put({no})
fiber.sleep(0.001 * math.random())
end
end
)
end;
for i = 1, 10 do
local no = i fiber.create(
function()
fiber.self():name('receiver')
while true do
local r = chs[no]:get(math.random() * .001)
if r ~= nil and r[1] == no then
res[no] = true
elseif r ~= nil then
break
end
fiber.sleep(0.001 * math.random())
count = count + 1
end
res[no] = false
end
)
end;
for i = 1, 100 do fiber.sleep(0.01) if count > 2000 then break end end;
count > 2000, #res, res;
--# setopt delimiter ''
--
-- gh-756: channel:close() leaks memory
--
ffi = require('ffi')
ffi.cdef[[ struct gh756 { int k; }; ]]
ct = ffi.metatype('struct gh756', { __gc = function() refs = refs - 1; end })
-- create 10 objects and put they to a channel
refs = 10
ch = fiber.channel(refs)
for i=1,refs do ch:put(ffi.new(ct, i)) end
-- get an object from the channel, run GC and check the number of objects
ch:get().k == 1
collectgarbage('collect')
refs
ch:get().k == 2
collectgarbage('collect')
refs
-- close the channel and check the number of objects
ch:close()
collectgarbage('collect')
refs -- must be zero
| bsd-2-clause |
venkatarajasekhar/bee | third_party/luafun/tests/operators.lua | 5 | 4619 | --
-- All these functions are fully covered by Lua tests.
-- This test just checks that all functions were defined correctly.
--
print(op == operator) -- an alias
--[[test
true
--test]]
--------------------------------------------------------------------------------
-- Comparison operators
--------------------------------------------------------------------------------
local comparators = { 'le', 'lt', 'eq', 'ne', 'ge', 'gt' }
for _k, op in iter(comparators) do
print('op', op)
print('==')
print('num:')
print(operator[op](0, 1))
print(operator[op](1, 0))
print(operator[op](0, 0))
print('str:')
print(operator[op]("abc", "cde"))
print(operator[op]("cde", "abc"))
print(operator[op]("abc", "abc"))
print('')
end
--[[test
op le
==
num:
true
false
true
str:
true
false
true
op lt
==
num:
true
false
false
str:
true
false
false
op eq
==
num:
false
false
true
str:
false
false
true
op ne
==
num:
true
true
false
str:
true
true
false
op ge
==
num:
false
true
true
str:
false
true
true
op gt
==
num:
false
true
false
str:
false
true
false
--test]]
--------------------------------------------------------------------------------
-- Arithmetic operators
--------------------------------------------------------------------------------
print(operator.add(-1.0, 1.0))
print(operator.add(0, 0))
print(operator.add(12, 2))
--[[test
0
0
14
--test]]
print(operator.div(10, 2))
print(operator.div(10, 3))
print(operator.div(-10, 3))
--[[test
5
3.3333333333333
-3.3333333333333
--test]]
print(operator.floordiv(10, 3))
print(operator.floordiv(11, 3))
print(operator.floordiv(12, 3))
print(operator.floordiv(-10, 3))
print(operator.floordiv(-11, 3))
print(operator.floordiv(-12, 3))
--[[test
3
3
4
-4
-4
-4
--test]]
print(operator.intdiv(10, 3))
print(operator.intdiv(11, 3))
print(operator.intdiv(12, 3))
print(operator.intdiv(-10, 3))
print(operator.intdiv(-11, 3))
print(operator.intdiv(-12, 3))
--[[test
3
3
4
-3
-3
-4
--test]]
print(operator.truediv(10, 3))
print(operator.truediv(11, 3))
print(operator.truediv(12, 3))
print(operator.truediv(-10, 3))
print(operator.truediv(-11, 3))
print(operator.truediv(-12, 3))
--[[test
3.3333333333333
3.6666666666667
4
-3.3333333333333
-3.6666666666667
-4
--test]]
print(operator.mod(10, 2))
print(operator.mod(10, 3))
print(operator.mod(-10, 3))
--[[test
0
1
2
--test]]
print(operator.mul(10, 0.1))
print(operator.mul(0, 0))
print(operator.mul(-1, -1))
--[[test
1
0
1
--test]]
print(operator.neq(1))
print(operator.neq(0) == 0)
print(operator.neq(-0) == 0)
print(operator.neq(-1))
--[[test
-1
true
true
1
--test]]
print(operator.unm(1))
print(operator.unm(0) == 0)
print(operator.unm(-0) == 0)
print(operator.unm(-1))
--[[test
-1
true
true
1
--test]]
print(operator.pow(2, 3))
print(operator.pow(0, 10))
print(operator.pow(2, 0))
--[[test
8
0
1
--test]]
print(operator.sub(2, 3))
print(operator.sub(0, 10))
print(operator.sub(2, 2))
--[[test
-1
-10
0
--test]]
--------------------------------------------------------------------------------
-- String operators
--------------------------------------------------------------------------------
print(operator.concat("aa", "bb"))
print(operator.concat("aa", ""))
print(operator.concat("", "bb"))
--[[test
aabb
aa
bb
--test]]
print(operator.len(""))
print(operator.len("ab"))
print(operator.len("abcd"))
--[[test
0
2
4
--test]]
print(operator.length(""))
print(operator.length("ab"))
print(operator.length("abcd"))
--[[test
0
2
4
--test]]
----------------------------------------------------------------------------
-- Logical operators
----------------------------------------------------------------------------
print(operator.land(true, true))
print(operator.land(true, false))
print(operator.land(false, true))
print(operator.land(false, false))
print(operator.land(1, 0))
print(operator.land(0, 1))
print(operator.land(1, 1))
print(operator.land(0, 0))
--[[test
true
false
false
false
0
1
1
0
--test]]
print(operator.lor(true, true))
print(operator.lor(true, false))
print(operator.lor(false, true))
print(operator.lor(false, false))
print(operator.lor(1, 0))
print(operator.lor(0, 1))
print(operator.lor(1, 1))
print(operator.lor(0, 0))
--[[test
true
true
true
false
1
0
1
0
--test]]
print(operator.lnot(true))
print(operator.lnot(false))
print(operator.lor(1))
print(operator.lor(0))
--[[test
false
true
1
0
--test]]
print(operator.truth(true))
print(operator.truth(false))
print(operator.truth(1))
print(operator.truth(0))
print(operator.truth(nil))
print(operator.truth(""))
print(operator.truth({}))
--[[test
true
false
true
true
false
true
true
--test]]
| bsd-2-clause |
ev1l0rd/yalnpv | dfhack/hack/scripts/modtools/equip-item.lua | 1 | 2559 | -- modtools/equip-item.lua
-- equip an item on a unit with a particular body part
--[[=begin
modtools/equip-item
===================
Force a unit to equip an item with a particular body part; useful in
conjunction with the ``create`` scripts above. See also `forceequip`.
=end]]
local utils = require 'utils'
function equipItem(unit, item, bodyPart, mode)
--it is assumed that the item is on the ground
item.flags.on_ground = false
item.flags.in_inventory = true
local block = dfhack.maps.getTileBlock(item.pos)
local occupancy = block.occupancy[item.pos.x%16][item.pos.y%16]
for k,v in ipairs(block.items) do
--local blockItem = df.item.find(v)
if v == item.id then
block.items:erase(k)
break
end
end
local foundItem = false
for k,v in ipairs(block.items) do
local blockItem = df.item.find(v)
if blockItem.pos.x == item.pos.x and blockItem.pos.y == item.pos.y then
foundItem = true
break
end
end
if not foundItem then
occupancy.item = false
end
local inventoryItem = df.unit_inventory_item:new()
inventoryItem.item = item
inventoryItem.mode = mode
inventoryItem.body_part_id = bodyPart
unit.inventory:insert(#unit.inventory,inventoryItem)
end
validArgs = --[[validArgs or--]] utils.invert({
'help',
'unit',
'item',
'bodyPart',
'mode'
})
if moduleMode then
return
end
local args = utils.processArgs({...}, validArgs)
if args.help then
print(
[[scripts/modtools/equip-item.lua
arguments:
-help
print this help message
]])
return
end
local unitId = tonumber(args.unit) or ((args.unit == '\\LAST') and (df.global.unit_next_id-1))
local unit = df.unit.find(unitId)
if not unit then
error('invalid unit!', args.unit)
end
local itemId = tonumber(args.item) or ((args.item == '\\LAST') and (df.global.item_next_id-1))
local item = df.item.find(itemId)
if not item then
error('invalid item!', args.item)
end
local bodyPartName = args.bodyPart
local creature_raw = df.global.world.raws.creatures.all[unit.race]
local caste_raw = creature_raw.caste[unit.caste]
local body_info = caste_raw.body_info
local partId
local part
for k,v in ipairs(body_info.body_parts) do
if v.token == bodyPartName then
partId = k
part = v
break
end
end
if not part then
error('invalid body part name: ', bodyPartName)
end
local mode = args.mode
mode = df.unit_inventory_item.T_mode[mode]
equipItem(unit, item, partId, mode)
| mit |
nekrozar/ygopro-scripts | c96915510.lua | 1 | 3427 | --魔神儀の創造主-クリオルター
function c96915510.initial_effect(c)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_HANDES+CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,96915510)
e1:SetCondition(c96915510.spcon)
e1:SetCost(c96915510.spcost)
e1:SetTarget(c96915510.sptg)
e1:SetOperation(c96915510.spop)
c:RegisterEffect(e1)
--disable
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetRange(LOCATION_MZONE)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetTarget(c96915510.atktg)
e2:SetCode(EFFECT_DISABLE)
c:RegisterEffect(e2)
--attack
local e3=e2:Clone()
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetValue(2000)
c:RegisterEffect(e3)
end
function c96915510.spcon(e,tp,eg,ep,ev,re,r,rp)
local ph=Duel.GetCurrentPhase()
return ph==PHASE_MAIN1 or ph==PHASE_MAIN2
end
function c96915510.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return not e:GetHandler():IsPublic() end
end
function c96915510.spfilter(c,e,tp)
return c:IsSetCard(0x117) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c96915510.spcheck(g)
return g:GetSum(Card.GetLevel)==10
end
function c96915510.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<=0 or Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)<1 then return false end
if ft>1 and Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end
local g=Duel.GetMatchingGroup(c96915510.spfilter,tp,LOCATION_GRAVE,0,nil,e,tp)
return g:CheckSubGroup(c96915510.spcheck,1,ft)
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE)
end
function c96915510.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.DiscardHand(tp,nil,1,1,REASON_EFFECT+REASON_DISCARD)>0 then
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<=0 then return end
if ft>1 and Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end
local g=Duel.GetMatchingGroup(c96915510.spfilter,tp,LOCATION_GRAVE,0,nil,e,tp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:SelectSubGroup(tp,c96915510.spcheck,false,1,ft)
if sg then
local c=e:GetHandler()
local fid=c:GetFieldID()
local tc=sg:GetFirst()
while tc do
Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP)
tc:RegisterFlagEffect(96915510,RESET_EVENT+RESETS_STANDARD,0,1,fid)
tc=sg:GetNext()
end
Duel.SpecialSummonComplete()
sg:KeepAlive()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetCountLimit(1)
e1:SetLabel(fid)
e1:SetLabelObject(sg)
e1:SetCondition(c96915510.retcon)
e1:SetOperation(c96915510.retop)
Duel.RegisterEffect(e1,tp)
end
end
end
function c96915510.retfilter(c,fid)
return c:GetFlagEffectLabel(96915510)==fid
end
function c96915510.retcon(e,tp,eg,ep,ev,re,r,rp)
local g=e:GetLabelObject()
if not g:IsExists(c96915510.retfilter,1,nil,e:GetLabel()) then
g:DeleteGroup()
e:Reset()
return false
else return true end
end
function c96915510.retop(e,tp,eg,ep,ev,re,r,rp)
local g=e:GetLabelObject()
local tg=g:Filter(c96915510.retfilter,nil,e:GetLabel())
Duel.SendtoDeck(tg,nil,2,REASON_EFFECT)
end
function c96915510.atktg(e,c)
return c:IsSetCard(0x117) and not c:IsType(TYPE_RITUAL)
end
| gpl-2.0 |
FailcoderAddons/SVUI | SVUI_!Core/system/api.lua | 1 | 75489 | --[[
##########################################################
S V U I By: Munglunch
##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
local pairs = _G.pairs;
local ipairs = _G.ipairs;
local type = _G.type;
local error = _G.error;
local pcall = _G.pcall;
local tostring = _G.tostring;
local tonumber = _G.tonumber;
local getmetatable = _G.getmetatable;
local setmetatable = _G.setmetatable;
local collectgarbage = _G.collectgarbage;
local table = _G.table;
local string = _G.string;
local math = _G.math;
local wipe = _G.wipe;
local tinsert = _G.tinsert;
local tremove = _G.tremove;
--[[ MATH METHODS ]]--
local floor, abs, min, max = math.floor, math.abs, math.min, math.max;
local parsefloat, ceil = math.parsefloat, math.ceil;
--[[ STRING METHODS ]]--
local lower, upper = string.lower, string.upper;
--[[ TABLE METHODS ]]--
local tremove, tcopy, twipe, tsort, tconcat = table.remove, table.copy, table.wipe, table.sort, table.concat;
--BLIZZARD API
local CreateFrame = _G.CreateFrame;
local InCombatLockdown = _G.InCombatLockdown;
local GameTooltip = _G.GameTooltip;
local ReloadUI = _G.ReloadUI;
local GetTime = _G.GetTime;
local hooksecurefunc = _G.hooksecurefunc;
local IsAltKeyDown = _G.IsAltKeyDown;
local IsShiftKeyDown = _G.IsShiftKeyDown;
local IsControlKeyDown = _G.IsControlKeyDown;
local IsModifiedClick = _G.IsModifiedClick;
local PlaySound = _G.PlaySound;
local PlaySoundFile = _G.PlaySoundFile;
local SetCVar = _G.SetCVar;
local GetCVar = _G.GetCVar;
local GetCVarBool = _G.GetCVarBool;
local SquareButton_SetIcon = _G.SquareButton_SetIcon;
local RAID_CLASS_COLORS = _G.RAID_CLASS_COLORS;
local CUSTOM_CLASS_COLORS = _G.CUSTOM_CLASS_COLORS;
--[[
##########################################################
GET ADDON DATA
##########################################################
]]--
local SV = select(2, ...)
local L = SV.L;
local SVUILib = Librarian("Registry");
local MOD = SV:NewPackage("API", L["API"]);
--[[
##########################################################
LOCALS
##########################################################
]]--
local MAC_DISPLAY;
local BASE_MOD = 0.64;
local LIVE_UPDATE_FRAMES = {};
--[[
##########################################################
LOOKUP TABLE
##########################################################
]]--
MOD.Templates = {
["Default"] = "SVUI_CoreStyle_Default",
["Transparent"] = "SVUI_CoreStyle_Transparent",
["Button"] = "SVUI_CoreStyle_Button",
["CheckButton"] = "SVUI_CoreStyle_CheckButton",
["DockButton"] = "SVUI_CoreStyle_DockButton",
["ActionSlot"] = "SVUI_CoreStyle_ActionSlot",
["Lite"] = "SVUI_CoreStyle_Lite",
["Icon"] = "SVUI_CoreStyle_Icon",
["Bar"] = "SVUI_CoreStyle_Bar",
["Inset"] = "SVUI_CoreStyle_Inset",
["Blackout"] = "SVUI_CoreStyle_Blackout",
["Component"] = "SVUI_CoreStyle_Component",
["Paper"] = "SVUI_CoreStyle_Paper",
["Container"] = "SVUI_CoreStyle_Container",
["Pattern"] = "SVUI_CoreStyle_Pattern",
["Premium"] = "SVUI_CoreStyle_Premium",
["Model"] = "SVUI_CoreStyle_Model",
["UnitLarge"] = "SVUI_CoreStyle_UnitLarge",
["UnitSmall"] = "SVUI_CoreStyle_UnitSmall",
["Window"] = "SVUI_CoreStyle_Window",
["Window2"] = "SVUI_CoreStyle_Window2",
};
MOD.Methods = {};
MOD.Concepts = {};
--[[
##########################################################
UI SCALING
##########################################################
]]--
local function ScreenUpdate()
local rez = GetCVar("gxResolution")
local height = rez:match("%d+x(%d+)")
local width = rez:match("(%d+)x%d+")
local gxHeight = tonumber(height)
local gxWidth = tonumber(width)
local gxMod = (768 / gxHeight)
local customScale = false;
if(IsMacClient()) then
if(not MAC_DISPLAY) then
MAC_DISPLAY = SVUILib:NewGlobal("Display");
if(not MAC_DISPLAY.Y or (MAC_DISPLAY.Y and type(MAC_DISPLAY.Y) ~= "number")) then
MAC_DISPLAY.Y = gxHeight;
end
if(not MAC_DISPLAY.X or (MAC_DISPLAY.X and type(MAC_DISPLAY.X) ~= "number")) then
MAC_DISPLAY.X = gxWidth;
end
end
if(MAC_DISPLAY and MAC_DISPLAY.Y and MAC_DISPLAY.X) then
if(gxHeight ~= MAC_DISPLAY.Y or gxWidth ~= MAC_DISPLAY.X) then
gxHeight = MAC_DISPLAY.Y;
gxWidth = MAC_DISPLAY.X;
end
end
end
local gxScale;
if(SV.db.screen.advanced) then
BASE_MOD = 0.64
local ADJUSTED_SCALE = SV.db.screen.scaleAdjust;
if(ADJUSTED_SCALE) then
if(type(ADJUSTED_SCALE) ~= "number") then
ADJUSTED_SCALE = tonumber(ADJUSTED_SCALE);
end
if(ADJUSTED_SCALE and ADJUSTED_SCALE ~= BASE_MOD) then
BASE_MOD = ADJUSTED_SCALE;
customScale = true;
end
end
gxScale = BASE_MOD;
else
-- local default_autoscale = true;
-- if(BlizzardOptionsPanel_GetCVarSafe("useUiScale") ~= 0) then
-- default_autoscale = false;
-- end
if(SV.db.screen.autoScale) then
gxScale = max(0.64, min(1.15, gxMod));
else
gxScale = max(0.64, min(1.15, GetCVar("uiScale") or UIParent:GetScale() or gxMod));
end
end
return gxWidth, gxHeight, gxScale, customScale
end
--[[
##########################################################
APPENDED POSITIONING METHODS
##########################################################
]]--
local ModSize = function(self, width, height)
if(type(width) == "number") then
local h = (height and type(height) == "number") and height or width
self:SetSize(width, h)
end
end
local WrapPoints = function(self, parent, x, y)
x = type(x) == "number" and x or 1
y = y or x
parent = parent or self:GetParent()
if self:GetPoint() then
self:ClearAllPoints()
end
self:SetPoint("TOPLEFT", parent, "TOPLEFT", -x, y)
self:SetPoint("BOTTOMRIGHT", parent, "BOTTOMRIGHT", x, -y)
end
local InsetPoints = function(self, parent, x, y)
x = type(x) == "number" and x or 1
y = y or x
parent = parent or self:GetParent()
if self:GetPoint() then
self:ClearAllPoints()
end
self:SetPoint("TOPLEFT", parent, "TOPLEFT", x, -y)
self:SetPoint("BOTTOMRIGHT", parent, "BOTTOMRIGHT", -x, y)
end
--[[
##########################################################
APPENDED DESTROY METHODS
##########################################################
]]--
local _purgatory = CreateFrame("Frame", nil)
_purgatory:Hide()
local Die = function(self)
if(self.UnregisterAllEvents) then
self:UnregisterAllEvents()
self:SetParent(_purgatory)
else
self:Hide()
self.Show = SV.fubar
end
end
local RemoveTextures = function(self, option)
if((not self.GetNumRegions) or (self.Panel and (not self.Panel.CanBeRemoved))) then return end
local region, layer, texture
for i = 1, self:GetNumRegions()do
region = select(i, self:GetRegions())
if(region and (region:GetObjectType() == "Texture")) then
layer = region:GetDrawLayer()
texture = region:GetTexture()
if(option) then
if(type(option) == "boolean") then
if region.UnregisterAllEvents then
region:UnregisterAllEvents()
region:SetParent(_purgatory)
else
region.Show = region.Hide
end
region:Hide()
elseif(type(option) == "string" and ((layer == option) or (texture ~= option))) then
region:SetTexture("")
end
else
region:SetTexture("")
end
end
end
end
--[[
##########################################################
SECURE FADING
##########################################################
]]--
local FRAMES_TO_HIDE = {};
local FRAMES_TO_SHOW = {};
local FadeEventManager_OnEvent = function(self, event)
if(event == 'PLAYER_REGEN_ENABLED') then
self:UnregisterEvent("PLAYER_REGEN_ENABLED")
for frame in pairs(FRAMES_TO_HIDE) do
frame:Hide()
end
wipe(FRAMES_TO_HIDE)
for frame in pairs(FRAMES_TO_SHOW) do
frame:Show()
end
wipe(FRAMES_TO_SHOW)
end
end
local FadeEventManager = CreateFrame('Frame')
FadeEventManager:SetScript("OnEvent", FadeEventManager_OnEvent)
local SecureFade_OnUpdate = function(self, elasped)
local frame = self.owner;
if(frame) then
local state = frame.___fadeset;
state[4] = (state[4] or 0) + elasped;
if(state[4] < state[3]) then
if(frame.___fademode == "IN") then
frame:SetAlpha((state[4] / state[3]) * (state[2] - state[1]) + state[1])
elseif(frame.___fademode == "OUT") then
frame:SetAlpha(((state[3] - state[4]) / state[3]) * (state[1] - state[2]) + state[2])
end
else
state[4] = 0
frame:SetAlpha(state[2])
local canfade = (not InCombatLockdown()) or (InCombatLockdown() and (not frame:IsProtected()))
if(frame.___fadehide) then
if(canfade) then
frame:Hide()
if(frame.___fadefunc) then
local _, catch = pcall(frame.___fadefunc, frame)
if(not catch) then
frame.___fadefunc = nil
end
end
else
frame:SetAlpha(state[2])
FRAMES_TO_HIDE[frame] = true;
FadeEventManager:RegisterEvent("PLAYER_REGEN_ENABLED");
end
else
if(frame.___fadefunc) then
local _, catch = pcall(frame.___fadefunc, frame)
if(not catch) then
frame.___fadefunc = nil
end
end
end
self.Running = false;
self:SetScript("OnUpdate", nil);
end
end
end
local SecureFadeIn = function(self, duration, alphaStart, alphaEnd)
if(self.___visibilityLocked) then return end
local alpha1 = alphaStart or 0;
local alpha2 = alphaEnd or 1;
local timer = duration or 0.1;
local canfade = (not InCombatLockdown()) or (InCombatLockdown() and (not self:IsProtected()))
if((not self:IsShown()) and canfade) then
self:Show()
end
if((not self:IsShown()) and (not canfade)) then
FRAMES_TO_SHOW[self] = true
end
if(self:IsShown() and self:GetAlpha() == alpha2) then return end
if(not self.___fadehandler) then
self.___fadehandler = CreateFrame("Frame", nil)
self.___fadehandler.owner = self;
end
if(not self.___fademode or (self.___fademode and self.___fademode ~= "IN")) then
if(FRAMES_TO_HIDE[self]) then
FRAMES_TO_HIDE[self] = nil
end
self.___fademode = "IN";
self.___fadehide = nil;
self.___fadefunc = self.___fadeshowfunc;
if(not self.___fadeset) then
self.___fadeset = {};
end
self.___fadeset[1] = alpha1;
self.___fadeset[2] = alpha2;
self.___fadeset[3] = timer;
self:SetAlpha(alpha1)
end
if(not self.___fadehandler.Running) then
self.___fadehandler.Running = true;
self.___fadehandler:SetScript("OnUpdate", SecureFade_OnUpdate)
end
end
local SecureFadeOut = function(self, duration, alphaStart, alphaEnd, hideOnFinished)
if(self.___visibilityLocked) then return end
local alpha1 = alphaStart or 1;
local alpha2 = alphaEnd or 0;
local timer = duration or 0.1;
if((not self:IsShown()) or self:GetAlpha() == alpha2) then return end
if(not self.___fadehandler) then
self.___fadehandler = CreateFrame("Frame", nil)
self.___fadehandler.owner = self;
end
if(not self.___fademode or (self.___fademode and self.___fademode ~= "OUT")) then
if(FRAMES_TO_SHOW[self]) then
FRAMES_TO_SHOW[self] = nil
end
self.___fademode = "OUT";
self.___fadehide = hideOnFinished;
self.___fadefunc = self.___fadehidefunc;
if(not self.___fadeset) then
self.___fadeset = {};
end
self.___fadeset[1] = alpha1;
self.___fadeset[2] = alpha2;
self.___fadeset[3] = timer;
self:SetAlpha(alpha1)
end
if(not self.___fadehandler.Running) then
self.___fadehandler.Running = true;
self.___fadehandler:SetScript("OnUpdate", SecureFade_OnUpdate)
end
end
local SecureFadeCallback = function(self, callback, alwaysOnHide, alwaysOnShow)
if(alwaysOnHide) then
self.___fadehidefunc = callback;
elseif(alwaysOnShow) then
self.___fadeshowfunc = callback;
end
self.___fadefunc = callback;
end
--[[
##########################################################
TEMPLATE INTERNAL HANDLERS
##########################################################
]]--
local HookPanelBorderColor = function(self,r,g,b,a)
if self.BorderLeft then
self.BorderLeft:SetVertexColor(r,g,b,a)
self.BorderRight:SetVertexColor(r,g,b,a)
self.BorderTop:SetVertexColor(r,g,b,a)
self.BorderBottom:SetVertexColor(r,g,b,a)
end
if self.Shadow then
local alpha = self.Shadow:GetAttribute("shadowAlpha") or 0.5
self.Shadow:SetBackdropBorderColor(r,g,b,alpha)
end
end
local HookBackdrop = function(self,...)
if(self.Panel) then
self.Panel:SetBackdrop(...)
end
end
local HookBackdropColor = function(self,...)
if(self.Panel) then
self.Panel:SetBackdropColor(...)
end
end
local HookBackdropBorderColor = function(self,...)
if(self.Panel) then
self.Panel:SetBackdropBorderColor(...)
end
end
local HookVertexColor = function(self,...)
if(self.Panel) then
self.Panel.Skin:SetVertexColor(...)
end
end
local HookCustomBackdrop = function(self)
if(self.Panel) then
local bgid = self.Panel:GetAttribute("panelID")
local bdSet = SV.media.backdrop[bgid]
if(bdSet) then
if(not self.Panel:GetAttribute("panelLocked")) then
local edgeSize = bdSet.edgeSize;
if(edgeSize and type(edgeSize) == 'number') then
local offset = ceil(edgeSize * 0.2);
self.Panel:ClearAllPoints()
self.Panel:SetPoint("TOPLEFT", self, "TOPLEFT", -offset, offset)
self.Panel:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", offset, -offset)
end
end
self.Panel:SetBackdrop(bdSet)
self.Panel:SetBackdropBorderColor(0,0,0,1)
else
local newBgFile = SV.media.background[bgid]
local newBorderFile = SV.media.border[bgid]
if(newBgFile and newBorderFile) then
local w,h = self:GetSize()
local sizeMod = max(w,h)
local edgeSize = self.Panel:GetAttribute("panelPadding") or 1
local offset = ceil(edgeSize * 0.2)
self.Panel:SetBackdrop({
bgFile = newBgFile,
edgeFile = newBorderFile,
tile = true,
tileSize = sizeMod,
edgeSize = edgeSize,
insets =
{
left = offset,
right = offset,
top = offset,
bottom = offset,
},
})
self.Panel:SetBackdropBorderColor(0,0,0,1)
if(not self.Panel:GetAttribute("panelLocked")) then
self.Panel:ClearAllPoints()
self.Panel:SetPoint("TOPLEFT", self, "TOPLEFT", -offset, offset)
self.Panel:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", offset, -offset)
end
end
end
local colorID = self.Panel:GetAttribute("panelColor")
local panelColor = SV.media.color[colorID];
if(panelColor) then
self.Panel:SetBackdropColor(panelColor[1], panelColor[2], panelColor[3], panelColor[4] or 1)
end
end
end
local HookFrameLevel = function(self, level)
if(self.Panel) then
local adjustment = level - 1;
if(adjustment < 0) then adjustment = 0 end
self.Panel:SetFrameLevel(adjustment)
end
end
local Cooldown_ForceUpdate = function(self)
self.nextUpdate = 0;
self:Show()
end
local Cooldown_StopTimer = function(self)
self.enable = nil;
if(self.parent and self.parent.HideAfterCooldown) then
self.parent:Hide();
else
self:Hide();
end
end
local Cooldown_OnUpdate = function(self, elapsed)
if self.nextUpdate > 0 then
self.nextUpdate = self.nextUpdate - elapsed;
return
end
local now = GetTime();
local start = self.start;
local remaining = now - start;
local expires = (self.duration - remaining);
if expires > 0.05 then
if (self.fontScale * self:GetEffectiveScale() / UIParent:GetScale()) < 0.5 then
self.text:SetText('')
self.nextUpdate = 500
else
local timeLeft = 0;
local calc = 0;
if expires < 4 then
self.nextUpdate = 0.051
self.text:SetFormattedText("|cffff0000%.1f|r", expires)
elseif expires < 60 then
self.nextUpdate = 0.51
self.text:SetFormattedText("|cffffff00%d|r", floor(expires))
elseif expires < 3600 then
timeLeft = ceil(expires / 60);
calc = floor((expires / 60) + .5);
self.nextUpdate = calc > 1 and ((expires - calc) * 29.5) or (expires - 59.5);
self.text:SetFormattedText("|cffffffff%dm|r", timeLeft)
elseif expires < 86400 then
timeLeft = ceil(expires / 3600);
calc = floor((expires / 3600) + .5);
self.nextUpdate = calc > 1 and ((expires - calc) * 1799.5) or (expires - 3570);
self.text:SetFormattedText("|cff66ffff%dh|r", timeLeft)
else
timeLeft = ceil(expires / 86400);
calc = floor((expires / 86400) + .5);
self.nextUpdate = calc > 1 and ((expires - calc) * 43199.5) or (expires - 85680);
if(timeLeft > 7) then
self.text:SetFormattedText("|cff6666ff%s|r", "long")
else
self.text:SetFormattedText("|cff6666ff%dd|r", timeLeft)
end
end
end
else
Cooldown_StopTimer(self)
end
end
local Cooldown_OnSizeChanged = function(self, width, height)
local frame = self.timer
local override = self.SizeOverride
local newSize = floor(width + .5) / 36;
override = override or frame:GetParent():GetParent().SizeOverride;
if override then
newSize = override / 20
end
if newSize == frame.fontScale then
return
end
frame.fontScale = newSize;
if newSize < 0.5 and not override then
frame:Hide()
else
frame:Show()
frame.text:SetFont(SV.media.font.number, newSize * 15, 'OUTLINE')
if frame.enable then
Cooldown_ForceUpdate(frame)
end
end
end
local CreateCooldownTimer = function(self)
local timer = CreateFrame('Frame', nil, self)
timer.parent = self:GetParent()
timer:SetAllPoints()
timer:SetScript('OnUpdate', Cooldown_OnUpdate)
local timeText = timer:CreateFontString(nil,'OVERLAY')
timeText:SetPoint('CENTER',1,1)
timeText:SetJustifyH("CENTER")
timer.text = timeText;
timer:Hide()
self.timer = timer;
local width, height = self:GetSize()
Cooldown_OnSizeChanged(self, width, height)
self:SetScript('OnSizeChanged', Cooldown_OnSizeChanged)
return self.timer
end
local _hook_Cooldown_SetCooldown = function(self, start, duration, elapsed)
if start > 0 and duration > 2.5 then
local timer = self.timer or CreateCooldownTimer(self)
timer.start = start;
timer.duration = duration;
timer.enable = true;
timer.nextUpdate = 0;
if timer.fontScale >= 0.5 then
timer:Show()
end
else
local timer = self.timer;
if timer then
Cooldown_StopTimer(timer)
end
end
if self.timer then
if elapsed and elapsed > 0 then
self.timer:SetAlpha(0)
else
self.timer:SetAlpha(0.8)
end
end
end
local SetFrameBorderColor = function(self, r, g, b, setPrevious, reset)
if(setPrevious) then
self.Panel.__previous = setPrevious
elseif(reset) then
r,g,b = unpack(SV.media.color[self.Panel.__previous])
end
self.Panel.Shadow:SetBackdropBorderColor(r, g, b)
end
local ShowAlertFlash = function(self)
self:ColorBorder(1,0.9,0)
SV.Animate:Flash(self.Panel.Shadow, 0.75, true)
end
local HideAlertFlash = function(self)
SV.Animate:StopFlash(self.Panel.Shadow)
self:ColorBorder(1,0.9,0, nil, true)
end
--[[
##########################################################
TEMPLATE HELPERS
##########################################################
]]--
local function SetCD(button, noSwipe)
local bn = button:GetName()
if(bn) then
local cooldown = _G[bn.."Cooldown"];
if(cooldown) then
if(not SV.db.general or (SV.db.general and (not SV.db.general.cooldown))) then return end
cooldown:ClearAllPoints()
cooldown:InsetPoints()
cooldown:SetDrawEdge(false)
cooldown:SetDrawBling(false)
if(not noSwipe) then
cooldown:SetSwipeColor(0, 0, 0, 1)
end
if(not cooldown.HookedCooldown) then
hooksecurefunc(cooldown, "SetCooldown", _hook_Cooldown_SetCooldown)
cooldown.HookedCooldown = true
end
end
return cooldown
end
return false
end
function MOD:FLASH(frame)
if(frame.Panel.Shadow) then
frame.Panel.__previous = 'darkest';
frame.ColorBorder = SetFrameBorderColor
frame.StartAlert = ShowAlertFlash
frame.StopAlert = HideAlertFlash
end
end
function MOD:CD(frame, noSwipe)
local cooldown = SetCD(frame, noSwipe)
if(not cooldown) then
cooldown = CreateFrame("Cooldown", nil, frame)
cooldown:ClearAllPoints()
cooldown:InsetPoints(frame, 1, 1)
cooldown:SetDrawEdge(false)
cooldown:SetDrawBling(false)
if(not noSwipe) then
cooldown:SetSwipeColor(0, 0, 0, 1)
end
if(not cooldown.HookedCooldown) then
hooksecurefunc(cooldown, "SetCooldown", _hook_Cooldown_SetCooldown)
cooldown.HookedCooldown = true
end
end
return cooldown
end
function MOD:APPLY(frame, templateName, underlay, padding, xOffset, yOffset, defaultColor)
local xmlTemplate = self.Templates[templateName] or self.Templates.Default;
local borderColor = {0,0,0,1}
local panel = CreateFrame('Frame', nil, frame, xmlTemplate)
local level = frame:GetFrameLevel()
if(level == 0 and not InCombatLockdown()) then
frame:SetFrameLevel(1)
level = 1
end
local adjustment = level - 1;
if(adjustment < 0) then adjustment = 0 end
panel:SetFrameLevel(adjustment)
hooksecurefunc(frame, "SetFrameLevel", HookFrameLevel)
if(defaultColor) then
panel:SetAttribute("panelColor", defaultColor)
end
local panelID = panel:GetAttribute("panelID")
local colorName = panel:GetAttribute("panelColor")
local gradientName = panel:GetAttribute("panelGradient")
local forcedOffset = panel:GetAttribute("panelOffset")
if(forcedOffset or xOffset or yOffset) then
panel:SetAttribute("panelLocked", true)
end
if(frame.noStyleUpdate) then
panel:SetAttribute("panelSkipUpdate", true)
end
padding = padding or panel:GetAttribute("panelPadding")
if(forcedOffset) then
xOffset = xOffset or forcedOffset
yOffset = yOffset or forcedOffset
else
xOffset = xOffset or padding
yOffset = yOffset or padding
end
--panel:WrapPoints(frame, xOffset, yOffset)
panel:SetPoint("TOPLEFT", frame, "TOPLEFT", -xOffset, yOffset)
panel:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", xOffset, -yOffset)
local bgColor = SV.media.color[colorName] or SV.media.color.default;
local borderColor = SV.media.bordercolor[panelID] or SV.media.bordercolor.default;
if(panel:GetBackdrop()) then
if(underlay) then
panel:SetBackdropColor(bgColor[1],bgColor[2],bgColor[3],bgColor[4] or 1)
panel:SetBackdropBorderColor(borderColor[1],borderColor[2],borderColor[3],borderColor[4] or 1)
else
local bd = panel:GetBackdrop()
frame:SetBackdrop(bd)
frame:SetBackdropColor(bgColor[1],bgColor[2],bgColor[3],bgColor[4] or 1)
frame:SetBackdropBorderColor(borderColor[1],borderColor[2],borderColor[3],borderColor[4] or 1)
panel:SetBackdrop(nil)
end
if(templateName ~= 'Transparent') then
hooksecurefunc(panel, "SetBackdropBorderColor", HookPanelBorderColor)
hooksecurefunc(frame, "SetBackdropBorderColor", HookBackdropBorderColor)
if(underlay) then
frame:SetBackdrop(nil)
frame.SetBackdrop = panel.SetBackdrop
--hooksecurefunc(frame, "SetBackdrop", HookBackdrop)
hooksecurefunc(frame, "SetBackdropColor", HookBackdropColor)
end
frame.UpdateBackdrop = HookCustomBackdrop
frame.BackdropNeedsUpdate = true
end
end
if(padding and panel.BorderLeft) then
panel.BorderLeft:SetWidth(padding)
panel.BorderRight:SetWidth(padding)
panel.BorderTop:SetHeight(padding)
panel.BorderBottom:SetHeight(padding)
end
if(panel.Shadow) then
--panel.Shadow:SetAllPoints(panel)
panel.Shadow:SetPoint('TOPLEFT', panel, 'TOPLEFT', -2, 2)
panel.Shadow:SetPoint('BOTTOMRIGHT', panel, 'BOTTOMRIGHT', 2, -2)
local alpha = panel.Shadow:GetAttribute("shadowAlpha") or 0.5
panel.Shadow:SetBackdropBorderColor(0,0,0,alpha)
local level = panel.Shadow:GetFrameLevel() - 1
if(level >= 0) then
panel.Shadow:SetFrameLevel(level)
else
panel.Shadow:SetFrameLevel(0)
end
end
if(panel.Skin) then
panel.Skin:ClearAllPoints()
panel.Skin:SetAllPoints(panel)
if(not underlay) then
panel.Skin:SetParent(frame)
end
if(gradientName and SV.media.gradient[gradientName]) then
panel.Skin:SetGradient(unpack(SV.media.gradient[gradientName]))
else
panel.Skin:SetVertexColor(bgColor[1], bgColor[2], bgColor[3], bgColor[4] or 1)
end
if((not panel:GetAttribute("panelSkipUpdate")) and panel:GetAttribute("panelTexUpdate")) then
frame.TextureNeedsUpdate = true
if(panel:GetAttribute("panelHookVertex")) then
frame.UpdateColor = HookVertexColor
frame.NoColorUpdate = true
end
end
end
if(panel.TopLeft and (not underlay)) then
panel.TopLeft:SetParent(frame)
panel.TopRight:SetParent(frame)
panel.BottomLeft:SetParent(frame)
panel.BottomRight:SetParent(frame)
end
frame.Panel = panel;
end
--[[
##########################################################
UI ELEMENT METHODS
##########################################################
]]--
local function CommonButtonSettings(frame, addChecked, noSwipe)
if(frame.Left) then
frame.Left:SetAlpha(0)
end
if(frame.Middle) then
frame.Middle:SetAlpha(0)
end
if(frame.Right) then
frame.Right:SetAlpha(0)
end
if(frame.SetNormalTexture) then
frame:SetNormalTexture("")
end
if(frame.SetDisabledTexture) then
frame:SetDisabledTexture("")
end
if(frame.SetCheckedTexture) then
frame:SetCheckedTexture("")
end
if(frame.SetHighlightTexture) then
if(not frame.hover) then
local hover = frame:CreateTexture(nil, "HIGHLIGHT")
hover:InsetPoints(frame.Panel)
frame.hover = hover;
end
frame.hover:SetTexture(0.1, 0.8, 0.8, 0.5)
frame:SetHighlightTexture(frame.hover)
end
if(frame.SetPushedTexture) then
if(not frame.pushed) then
local pushed = frame:CreateTexture(nil, "OVERLAY")
pushed:InsetPoints(frame.Panel)
frame.pushed = pushed;
end
frame.pushed:SetTexture(0.1, 0.8, 0.1, 0.3)
frame:SetPushedTexture(frame.pushed)
end
if(frame.SetCheckedTexture and addChecked) then
if(not frame.checked) then
local checked = frame:CreateTexture(nil, "OVERLAY")
checked:InsetPoints(frame.Panel)
frame.checked = checked
end
frame.checked:SetTexture(0, 0.5, 0, 0.2)
frame:SetCheckedTexture(frame.checked)
end
SetCD(frame, noSwipe)
end
MOD.Methods["Button"] = function(self, frame, inverse, xOffset, yOffset, defaultColor)
if(not frame or (frame and frame.Panel)) then return end
local x,y = -1,-1
if(xOffset or yOffset) then
x = xOffset or -1
y = yOffset or -1
inverse = true
end
self:APPLY(frame, "Button", inverse, 1, x, y, defaultColor)
CommonButtonSettings(frame, true)
if(defaultColor) then
frame.Panel:SetAttribute("panelID", "button"..defaultColor)
tinsert(LIVE_UPDATE_FRAMES, frame);
end
end;
MOD.Methods["LiteButton"] = function(self, frame, inverse, xOffset, yOffset, defaultColor)
if(not frame or (frame and frame.Panel)) then return end
local x,y = 1,1
if(xOffset or yOffset) then
x = xOffset or 1
y = yOffset or 1
inverse = true
end
self:APPLY(frame, "Lite", inverse, 1, x, y)
--frame:SetBackdropColor(0,0,0,0)
--frame:SetBackdropBorderColor(0,0,0,0)
CommonButtonSettings(frame, true)
end;
MOD.Methods["ActionSlot"] = function(self, frame, inverse, addChecked)
if(not frame or (frame and frame.Panel)) then return end
addChecked = addChecked or false;
local underlay = (not inverse)
self:APPLY(frame, "ActionSlot", underlay)
CommonButtonSettings(frame, addChecked, true)
end;
MOD.Methods["CheckButton"] = function(self, frame, inverse, x, y)
if(not frame or (frame and frame.Panel)) then return end
local width, height = frame:GetSize()
width = width * 0.7
height = height * 0.7
frame:SetSize(width, height)
local underlay = (not inverse)
self:APPLY(frame, "CheckButton", inverse, 1, 1, 1)
if(frame.SetNormalTexture) then
frame:SetNormalTexture("")
end
if(frame.SetPushedTexture) then
frame:SetPushedTexture("")
end
if(frame.SetHighlightTexture) then
if(not frame.hover) then
local hover = frame:CreateTexture(nil, "OVERLAY")
hover:InsetPoints(frame.Panel)
frame.hover = hover;
end
local color = SV.media.color.highlight
frame.hover:SetTexture(color[1], color[2], color[3], 0.5)
frame:SetHighlightTexture(frame.hover)
end
if(frame.SetCheckedTexture) then
frame:SetCheckedTexture(SV.media.button.check)
local ct = frame:GetCheckedTexture()
ct:SetTexCoord(0, 1, 0, 1)
end
if(frame.SetDisabledCheckedTexture) then
frame:SetDisabledCheckedTexture(SV.media.button.uncheck)
local ct = frame:GetDisabledCheckedTexture()
ct:SetTexCoord(0, 1, 0, 1)
end
end;
MOD.Methods["Editbox"] = function(self, frame, inverse, x, y)
if(not frame or (frame and frame.Panel)) then return end
if frame.TopLeftTex then frame.TopLeftTex:Die() end
if frame.TopRightTex then frame.TopRightTex:Die() end
if frame.TopTex then frame.TopTex:Die() end
if frame.BottomLeftTex then frame.BottomLeftTex:Die() end
if frame.BottomRightTex then frame.BottomRightTex:Die() end
if frame.BottomTex then frame.BottomTex:Die() end
if frame.LeftTex then frame.LeftTex:Die() end
if frame.RightTex then frame.RightTex:Die() end
if frame.MiddleTex then frame.MiddleTex:Die() end
if frame.Left then frame.Left:Die() end
if frame.Right then frame.Right:Die() end
if frame.Middle then frame.Middle:Die() end
local underlay = (not inverse)
self:APPLY(frame, "Inset", underlay, 1, x, y)
local globalName = frame:GetName();
if globalName then
if _G[globalName.."Left"] then _G[globalName.."Left"]:Die() end
if _G[globalName.."Middle"] then _G[globalName.."Middle"]:Die() end
if _G[globalName.."Right"] then _G[globalName.."Right"]:Die() end
if _G[globalName.."Mid"] then _G[globalName.."Mid"]:Die() end
if globalName:find("Silver") or globalName:find("Copper") or globalName:find("Gold") then
frame.Panel:SetPoint("TOPLEFT", -3, 1)
if globalName:find("Silver") or globalName:find("Copper") then
frame.Panel:SetPoint("BOTTOMRIGHT", -12, -2)
else
frame.Panel:SetPoint("BOTTOMRIGHT", -2, -2)
end
end
end
end;
--[[
##########################################################
CUSTOM TEMPLATING METHODS
##########################################################
]]--
MOD.Methods["Icon"] = function(self, frame, inverse, ...)
if(not frame or (frame and frame.Panel)) then return end
local underlay = (not inverse)
self:APPLY(frame, "Icon", underlay, ...)
end;
MOD.Methods["DockButton"] = function(self, frame, inverse, template)
if(not frame or (frame and frame.Panel)) then return end
template = template or "DockButton"
self:APPLY(frame, template, inverse)
self:FLASH(frame)
if(frame.Left) then
frame.Left:SetAlpha(0)
end
if(frame.Middle) then
frame.Middle:SetAlpha(0)
end
if(frame.Right) then
frame.Right:SetAlpha(0)
end
if(frame.SetNormalTexture) then
frame:SetNormalTexture("")
end
if(frame.SetDisabledTexture) then
frame:SetDisabledTexture("")
end
if(frame.SetCheckedTexture) then
frame:SetCheckedTexture("")
end
if(frame.SetHighlightTexture) then
if(not frame.hover) then
local hover = frame:CreateTexture(nil, "HIGHLIGHT")
hover:InsetPoints(frame.Panel)
frame.hover = hover;
end
frame.hover:SetTexture(0.1, 0.8, 0.8, 0.5)
frame:SetHighlightTexture(frame.hover)
end
if(not frame.Panel:GetAttribute("panelSkipUpdate")) then
tinsert(LIVE_UPDATE_FRAMES, frame);
end
end;
MOD.Methods["Frame"] = function(self, frame, inverse, styleName, noupdate, overridePadding, xOffset, yOffset, defaultColor)
if(not frame or (frame and frame.Panel)) then return end
local padding = false;
if(overridePadding and type(overridePadding) == "number") then
padding = overridePadding
end
styleName = styleName or "Default";
local underlay = (not inverse)
if(noupdate) then
frame.noStyleUpdate = true
end
self:APPLY(frame, styleName, underlay, padding, xOffset, yOffset, defaultColor)
if(not noupdate) then
tinsert(LIVE_UPDATE_FRAMES, frame);
end
end;
--[[
##########################################################
TEMPLATE API
##########################################################
]]--
local SetPanelColor = function(self, ...)
local arg1,arg2,arg3,arg4,arg5,arg6,arg7 = select(1, ...)
if(not self.Panel or not arg1) then return; end
if(self.Panel.Skin and self.Panel:GetAttribute("panelGradient")) then
if(type(arg1) == "string") then
if(arg1 == "VERTICAL" or arg1 == "HORIZONTAL") then
self.Panel.Skin:SetGradient(...)
elseif(SV.media.gradient[arg1]) then
self.Panel:SetAttribute("panelColor", arg1)
self.Panel.Skin:SetGradient(unpack(SV.media.gradient[arg1]))
if(SV.media.color[arg1]) then
local t = SV.media.color[arg1]
self:SetBackdropColor(t[1], t[2], t[3], t[4])
end
end
end
elseif(type(arg1) == "string" and SV.media.color[arg1]) then
local t = SV.media.color[arg1]
self.Panel:SetAttribute("panelColor", arg1)
self:SetBackdropColor(t[1], t[2], t[3], t[4])
elseif(arg1 and type(arg1) == "number") then
self:SetBackdropColor(...)
end
end
local SetStyle = function(self, method, ...)
if(not self or (self and self.Panel)) then return end
method = method or "Frame";
local methodName, flags = method:gsub("!_", "");
local param = false;
if(flags and (flags > 0)) then
param = true;
end
local fn = MOD.Methods[methodName];
if(fn) then
local pass, catch = pcall(fn, MOD, self, param, ...)
if(catch) then
SV:HandleError("API", "SetStyle", catch);
return
end
end
end
--[[
##########################################################
HOOKED ATLAS HIJACKER
##########################################################
]]--
local ATLAS_THIEF = {} -- Wasn't this the name of a movie?
local ATLAS_HACKS = {} -- Couldn't think of anything clever honestly.
ATLAS_HACKS["default"] = function(self)
self:SetTexture("")
end
local StealAtlas = function(self, atlas)
if(not self or not atlas) then return end
--print(atlas)
local hack = ATLAS_THIEF[atlas];
if(hack) then
local fn = ATLAS_HACKS[hack] or ATLAS_HACKS["default"]
local pass, catch = pcall(fn, self, atlas)
if(catch) then
SV:HandleError("API", "SetStyle", catch);
return
end
end
end
--[[
##########################################################
UPDATE CALLBACKS
##########################################################
]]--
local function FrameTemplateUpdates()
for i=1, #LIVE_UPDATE_FRAMES do
local frame = LIVE_UPDATE_FRAMES[i]
if(frame) then
local panelID = frame.Panel:GetAttribute("panelID")
local colorID = frame.Panel:GetAttribute("panelColor")
local panelColor = SV.media.color[colorID];
if(frame.BackdropNeedsUpdate) then
if(frame.UpdateBackdrop) then
frame:UpdateBackdrop()
end
if(panelColor) then
frame:SetBackdropColor(panelColor[1], panelColor[2], panelColor[3], panelColor[4] or 1)
end
if(SV.media.bordercolor[panelID]) then
local borderColor = SV.media.bordercolor[panelID]
frame:SetBackdropBorderColor(borderColor[1], borderColor[2], borderColor[3], borderColor[4] or 1)
else
frame:SetBackdropBorderColor(0,0,0,1)
end
end
if(frame.TextureNeedsUpdate and frame.Panel.Skin) then
local tex = SV.media.background[panelID]
if(tex) then
frame.Panel.Skin:SetTexture(tex)
--if(panelID == 'unitlarge') then print(frame.Panel.Skin:GetTexture()) end
end
if(not frame.NoColorUpdate) then
local gradient = frame.Panel:GetAttribute("panelGradient")
if(gradient and SV.media.gradient[gradient]) then
local g = SV.media.gradient[gradient]
frame.Panel.Skin:SetGradient(g[1], g[2], g[3], g[4], g[5], g[6], g[7])
elseif(panelColor) then
frame.Panel.Skin:SetVertexColor(panelColor[1], panelColor[2], panelColor[3], panelColor[4] or 1)
end
end
end
end
end
end
SV.Events:On("SHARED_MEDIA_UPDATED", FrameTemplateUpdates, true);
SV.Events:On("REQUEST_TEMPLATE_UPDATED", FrameTemplateUpdates, true);
--[[
##########################################################
CORE FUNCTIONS
##########################################################
]]--
function SV:SetAtlasFunc(atlas, fn)
ATLAS_HACKS[atlas] = fn
end
function SV:SetAtlasFilter(atlas, fn)
if(not fn) then
fn = "default"
end
ATLAS_THIEF[atlas] = fn
end
--[[
##########################################################
SCREEN HANDLER (IN DEVELOPMENT)
##########################################################
]]--
function SV:UI_SCALE_CHANGED(event)
local managedScale = self.db.screen.autoScale;
local gxWidth, gxHeight, gxScale, customScale = ScreenUpdate();
if(managedScale) then
local needCalc = true;
if(self.db.screen.advanced) then
if(self.db.screen.forcedWidth ~= gxWidth) then
gxWidth = self.db.screen.forcedWidth
needCalc = false;
end
if(self.db.screen.forcedHeight ~= gxHeight) then
gxHeight = self.db.screen.forcedHeight
needCalc = false;
end
end
if(needCalc) then
if(gxWidth < 1600) then
self.LowRez = true;
elseif(gxWidth >= 3840) then
self.LowRez = nil
local evalwidth;
if(self.db.screen.multiMonitor) then
if(gxWidth < 4080) then
evalwidth = 1224;
elseif(gxWidth < 4320) then
evalwidth = 1360;
elseif(gxWidth < 4680) then
evalwidth = 1400;
elseif(gxWidth < 4800) then
evalwidth = 1440;
elseif(gxWidth < 5760) then
if(gxHeight == 900) then evalwidth = 1600 else evalwidth = 1680 end
elseif(gxWidth < 7680) then
evalwidth = 1920;
elseif(gxWidth < 9840) then
evalwidth = 2560;
elseif(gxWidth > 9839) then
evalwidth = 3280;
end
else
if(gxWidth < 4080) then
evalwidth = 3840;
elseif(gxWidth < 4320) then
evalwidth = 4080;
elseif(gxWidth < 4680) then
evalwidth = 4320;
elseif(gxWidth < 4800) then
evalwidth = 4680;
elseif(gxWidth < 5040) then
evalwidth = 4800;
elseif(gxWidth < 5760) then
evalwidth = 5040;
elseif(gxWidth < 7680) then
evalwidth = 5760;
elseif(gxWidth < 9840) then
evalwidth = 7680;
elseif(gxWidth > 9839) then
evalwidth = 9840;
end
end
gxWidth = evalwidth;
end
end
end
if(event == 'PLAYER_LOGIN' or event == 'UI_SCALE_CHANGED') then
self.Screen:ClearAllPoints()
self.Screen:SetPoint("CENTER")
local ignoreChange = false;
if(managedScale) then
local testScale1 = parsefloat(UIParent:GetScale(), 5);
local testScale2 = parsefloat(gxScale, 5);
if(event == "PLAYER_LOGIN" and (testScale1 ~= testScale2)) then
SetCVar("useUiScale", 1)
SetCVar("uiScale", gxScale)
WorldMapFrame.hasTaint = true;
ignoreChange = true;
_G.Advanced_UseUIScale:SetScale(0.0001)
_G.Advanced_UseUIScale:SetAlpha(0)
_G.Advanced_UIScaleSlider:SetScale(0.0001)
_G.Advanced_UIScaleSlider:SetAlpha(0)
end
if(gxWidth) then
local width = gxWidth
local height = gxHeight;
if(height > 1200) then
height = UIParent:GetHeight();
local ratio = gxHeight / height;
width = gxWidth / ratio;
end
self.Screen:SetSize(width, height);
else
self.Screen:SetSize(UIParent:GetSize());
end
else
self.Screen:SetSize(UIParent:GetSize());
end
if((not customScale) and (not ignoreChange) and (event == 'UI_SCALE_CHANGED')) then
local change = abs((testScale1 * 100) - (testScale2 * 100))
if(change > 1) then
if(managedScale) then
self:StaticPopup_Show('CHANGED_MANAGED_UISCALE')
elseif(BlizzardOptionsPanel_GetCVarSafe("useUiScale") ~= 0) then
self:StaticPopup_Show('RELOAD_UI')
end
end
end
end
end
--[[
##########################################################
API INJECTION
##########################################################
]]--
local MODIFIED_OBJECTS = {};
local CURRENT_OBJECT = CreateFrame("Frame");
local function AppendFrameMethods(OBJECT)
local objType = OBJECT:GetObjectType()
if(not MODIFIED_OBJECTS[objType]) then
local META = getmetatable(OBJECT).__index
if not OBJECT.SetStyle then META.SetStyle = SetStyle end
if not OBJECT.SetPanelColor then META.SetPanelColor = SetPanelColor end
if not OBJECT.ModSize then META.ModSize = ModSize end
if not OBJECT.ModWidth then META.ModWidth = META.SetWidth end
if not OBJECT.ModHeight then META.ModHeight = META.SetHeight end
if not OBJECT.ModPoint then META.ModPoint = META.SetPoint end
if not OBJECT.WrapPoints then META.WrapPoints = WrapPoints end
if not OBJECT.InsetPoints then META.InsetPoints = InsetPoints end
if not OBJECT.Die then META.Die = Die end
if not OBJECT.RemoveTextures then META.RemoveTextures = RemoveTextures end
if not OBJECT.FadeIn then META.FadeIn = SecureFadeIn end
if not OBJECT.FadeOut then META.FadeOut = SecureFadeOut end
if not OBJECT.FadeCallback then META.FadeCallback = SecureFadeCallback end
MODIFIED_OBJECTS[objType] = true
end
end
local function AppendTextureMethods(OBJECT)
local META = getmetatable(OBJECT).__index
if not OBJECT.ModSize then META.ModSize = ModSize end
if not OBJECT.ModWidth then META.ModWidth = META.SetWidth end
if not OBJECT.ModHeight then META.ModHeight = META.SetHeight end
if not OBJECT.ModPoint then META.ModPoint = META.SetPoint end
if not OBJECT.WrapPoints then META.WrapPoints = WrapPoints end
if not OBJECT.InsetPoints then META.InsetPoints = InsetPoints end
if not OBJECT.Die then META.Die = Die end
if(OBJECT.SetAtlas) then
hooksecurefunc(META, "SetAtlas", StealAtlas)
end
end
local function AppendFontStringMethods(OBJECT)
local META = getmetatable(OBJECT).__index
if not OBJECT.ModSize then META.ModSize = ModSize end
if not OBJECT.ModWidth then META.ModWidth = META.SetWidth end
if not OBJECT.ModHeight then META.ModHeight = META.SetHeight end
if not OBJECT.ModPoint then META.ModPoint = META.SetPoint end
if not OBJECT.WrapPoints then META.WrapPoints = WrapPoints end
if not OBJECT.InsetPoints then META.InsetPoints = InsetPoints end
end
AppendFrameMethods(CURRENT_OBJECT)
AppendTextureMethods(CURRENT_OBJECT:CreateTexture())
AppendFontStringMethods(CURRENT_OBJECT:CreateFontString())
CURRENT_OBJECT = EnumerateFrames()
while CURRENT_OBJECT do
AppendFrameMethods(CURRENT_OBJECT)
CURRENT_OBJECT = EnumerateFrames(CURRENT_OBJECT)
end
--[[
##########################################################
STYLING CONCEPTS
##########################################################
]]--
local Button_OnEnter = function(self)
self:SetBackdropColor(0.1, 0.8, 0.8)
end
local Button_OnLeave = function(self)
self:SetBackdropColor(unpack(SV.media.color.button))
end
local ConceptButton_OnEnter = function(self)
self:SetBackdropBorderColor(0.1, 0.8, 0.8)
end
local ConceptButton_OnLeave = function(self)
self:SetBackdropBorderColor(0,0,0,1)
end
local Tab_OnEnter = function(self)
self.backdrop:SetPanelColor("highlight")
self.backdrop:SetBackdropBorderColor(0.1, 0.8, 0.8)
end
local Tab_OnLeave = function(self)
self.backdrop:SetPanelColor("button")
self.backdrop:SetBackdropBorderColor(0,0,0,1)
end
local _hook_DropDownButton_SetPoint = function(self, _, _, _, _, _, breaker)
if not breaker then
self:SetPoint("RIGHT", self.AnchorParent, "RIGHT", -10, 3, true)
end
end
local _hook_Tooltip_OnShow = function(self)
self:SetBackdrop(SV.media.backdrop.tooltip)
end
MOD.Concepts["Frame"] = function(self, adjustable, frame, template, noStripping, padding, xOffset, yOffset)
if(not frame or (frame and frame.Panel)) then return end
template = template or "Transparent"
local baselevel = frame:GetFrameLevel()
if(baselevel < 1) then
frame:SetFrameLevel(1)
end
if(not noStripping) then
RemoveTextures(frame)
end
self.Methods["Frame"](self, frame, (not adjustable), template, true, padding, xOffset, yOffset)
end
MOD.Concepts["Window"] = function(self, adjustable, frame, altStyle, fullStrip, padding, xOffset, yOffset)
if(not frame or (frame and frame.Panel)) then return end
local template = altStyle and "Window2" or "Window"
local baselevel = frame:GetFrameLevel()
if(baselevel < 1) then
frame:SetFrameLevel(1)
end
RemoveTextures(frame, fullStrip)
local name = frame:GetName()
if(name and _G[name.."BtnCornerLeft"]) then
_G[name.."BtnCornerLeft"]:SetTexture("");
_G[name.."BtnCornerRight"]:SetTexture("");
_G[name.."ButtonBottomBorder"]:SetTexture("");
end
self.Methods["Frame"](self, frame, (not adjustable), template, false, padding, xOffset, yOffset)
if(frame.Inset) then
RemoveTextures(frame.Inset, fullStrip)
self.Methods["Frame"](self, frame.Inset, adjustable, "Inset", false, 3, 1, 1)
end
end
MOD.Concepts["Button"] = function(self, adjustable, frame)
if(not frame or (frame and frame.Panel)) then return end
RemoveTextures(frame)
self.Methods["Button"](self, frame, adjustable)
end
MOD.Concepts["CheckButton"] = function(self, adjustable, frame)
if(not frame or (frame and frame.Panel)) then return end
--RemoveTextures(frame)
self.Methods["CheckButton"](self, frame, adjustable)
end
MOD.Concepts["CloseButton"] = function(self, adjustable, frame, targetAnchor)
if(not frame or (frame and frame.Panel)) then return end
RemoveTextures(frame)
self.Methods["Button"](self, frame, adjustable, -6, -6, "red")
frame:SetFrameLevel(frame:GetFrameLevel() + 4)
frame:SetNormalTexture(SV.media.icon.close)
frame:HookScript("OnEnter", ConceptButton_OnEnter)
frame:HookScript("OnLeave", ConceptButton_OnLeave)
if(targetAnchor) then
frame:ClearAllPoints()
frame:SetPoint("TOPRIGHT", targetAnchor, "TOPRIGHT", 3, 3)
end
end
MOD.Concepts["InfoButton"] = function(self, adjustable, frame, targetAnchor, size)
if(not frame or (frame and frame.Panel)) then return end
RemoveTextures(frame)
size = size or 26
frame:SetSize(size, size)
--self.Methods["Button"](self, frame, false, -2, -2, "yellow")
frame:SetNormalTexture(SV.media.icon.info)
--frame:HookScript("OnEnter", ConceptButton_OnEnter)
--frame:HookScript("OnLeave", ConceptButton_OnLeave)
if(targetAnchor) then
frame:ClearAllPoints()
frame:SetPoint("TOPRIGHT", targetAnchor, "TOPRIGHT", 3, 3)
end
end
MOD.Concepts["ArrowButton"] = function(self, adjustable, frame, direction, targetAnchor)
if(not frame or (frame and frame.Panel)) then return end
local iconKey = "move_" .. direction:lower()
RemoveTextures(frame)
self.Methods["Button"](self, frame, adjustable, -7, -7, "green")
frame:SetFrameLevel(frame:GetFrameLevel() + 4)
frame:SetNormalTexture(SV.media.icon[iconKey])
frame:HookScript("OnEnter", ConceptButton_OnEnter)
frame:HookScript("OnLeave", ConceptButton_OnLeave)
if(targetAnchor) then
frame:ClearAllPoints()
frame:SetPoint("TOPRIGHT", targetAnchor, "TOPRIGHT", 0, 0)
end
end
MOD.Concepts["ItemButton"] = function(self, adjustable, frame, noScript)
if(not frame) then return end
RemoveTextures(frame)
if(not frame.Panel) then
if(not noScript) then
self.Methods["Frame"](self, frame, false, "Button", true, 1, -1, -1)
frame:HookScript("OnEnter", Button_OnEnter)
frame:HookScript("OnLeave", Button_OnLeave)
else
self.Methods["Frame"](self, frame, false, "Inset", true, 1, -1, -1)
-- frame:HookScript("OnEnter", ConceptButton_OnEnter)
-- frame:HookScript("OnLeave", ConceptButton_OnLeave)
end
end
local link = frame:GetName()
if(link) then
local nameObject = _G[("%sName"):format(link)]
local subNameObject = _G[("%sSubName"):format(link)]
local arrowObject = _G[("%sFlyoutArrow"):format(link)]
local levelObject = _G[("%sLevel"):format(link)]
local iconObject = _G[("%sIcon"):format(link)] or _G[("%sIconTexture"):format(link)] or frame.Icon or frame.icon
local countObject = _G[("%sCount"):format(link)]
if(not frame.Riser) then
local fg = CreateFrame("Frame", nil, frame)
fg:SetSize(120, 22)
fg:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT", 0, -11)
fg:SetFrameLevel(frame:GetFrameLevel() + 1)
frame.Riser = fg
end
if(iconObject) then
iconObject:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
if(not adjustable) then
iconObject:InsetPoints(frame, 2, 2)
end
if(not frame.IconShadow) then
frame.IconShadow = CreateFrame("Frame", nil, frame)
frame.IconShadow:WrapPoints(iconObject)
frame.IconShadow:SetStyle("Icon")
end
iconObject:SetParent(frame.Riser)
iconObject:SetDrawLayer("ARTWORK", -1)
end
if(countObject) then
countObject:SetParent(frame.Riser)
countObject:SetAllPoints(frame.Riser)
countObject:SetFontObject(SVUI_Font_Number)
countObject:SetDrawLayer("ARTWORK", 7)
end
if(nameObject) then nameObject:SetParent(frame.Riser) end
if(subNameObject) then subNameObject:SetParent(frame.Riser) end
if(arrowObject) then arrowObject:SetParent(frame.Riser) end
if(levelObject) then
levelObject:SetParent(frame.Riser)
levelObject:SetFontObject(SVUI_Font_Number)
levelObject:SetDrawLayer("ARTWORK", 7)
end
end
end
MOD.Concepts["PageButton"] = function(self, adjustable, frame, isVertical, isLeft)
if(not frame) then return end
local bName = frame:GetName()
local leftDown;
if(bName) then
local testName = bName:lower()
leftDown = ((bName and testName:find('left')) or testName:find('prev') or testName:find('decrement')) or false
else
leftDown = isLeft or false
end
frame:SetNormalTexture("")
frame:SetPushedTexture("")
frame:SetHighlightTexture("")
frame:SetDisabledTexture("")
if(not frame.Panel) then
RemoveTextures(frame)
self.Methods["Button"](self, frame, adjustable, -4, -4)
end
if not frame.icon then
frame.icon = frame:CreateTexture(nil,'ARTWORK')
frame.icon:SetSize(13, 13)
frame.icon:SetPoint('CENTER')
frame.icon:SetTexture(SV.media.button.radio)
frame.icon:SetTexCoord(0.02, 0.2, 0.02, 0.2)
frame:SetScript('OnMouseDown',function(self)
if self:IsEnabled() then
self.icon:SetPoint("CENTER",-1,-1)
end
end)
frame:SetScript('OnMouseUp',function(self)
self.icon:SetPoint("CENTER",0,0)
end)
frame:SetScript('OnDisable',function(self)
SetDesaturation(self.icon, true)
self.icon:SetAlpha(0.5)
end)
frame:SetScript('OnEnable',function(self)
SetDesaturation(self.icon, false)
self.icon:SetAlpha(1.0)
end)
if not frame:IsEnabled() then
frame:GetScript('OnDisable')(frame)
end
end
if isVertical then
if leftDown then SquareButton_SetIcon(frame,'UP') else SquareButton_SetIcon(frame,'DOWN')end
else
if leftDown then SquareButton_SetIcon(frame,'LEFT') else SquareButton_SetIcon(frame,'RIGHT')end
end
end
MOD.Concepts["ScrollBar"] = function(self, adjustable, frame, scale, yOffset)
if(not frame or (frame and frame.Panel)) then return end
scale = scale or 5
local scrollName = frame:GetName()
local testForBar = _G[("%sScrollBar"):format(scrollName)]
if(testForBar) then
scrollName = testForBar:GetName()
RemoveTextures(frame)
frame = testForBar
end
local bg, track, top, bottom, mid, upButton, downButton
bg = _G[("%sBG"):format(scrollName)]
if(bg) then bg:SetTexture("") end
track = _G[("%sTrack"):format(scrollName)]
if(track) then track:SetTexture("") end
top = _G[("%sTop"):format(scrollName)]
if(top) then top:SetTexture("") end
bottom = _G[("%sBottom"):format(scrollName)]
if(bottom) then bottom:SetTexture("") end
mid = _G[("%sMiddle"):format(scrollName)]
if(mid) then mid:SetTexture("") end
upButton = _G[("%sScrollUpButton"):format(scrollName)]
downButton = _G[("%sScrollDownButton"):format(scrollName)]
if(upButton and downButton) then
RemoveTextures(upButton)
if(not upButton.icon) then
local upW, upH = upButton:GetSize()
self.Concepts["PageButton"](self, false, upButton)
SquareButton_SetIcon(upButton, "UP")
upButton:SetSize(upW + scale, upH + scale)
if(yOffset) then
local anchor, parent, relative, xBase, yBase = upButton:GetPoint()
local yAdjust = (yOffset or 0) + yBase
upButton:ClearAllPoints()
upButton:SetPoint(anchor, parent, relative, xBase, yAdjust)
end
end
RemoveTextures(downButton)
if(not downButton.icon) then
local dnW, dnH = downButton:GetSize()
self.Concepts["PageButton"](self, false, downButton)
SquareButton_SetIcon(downButton, "DOWN")
downButton:SetSize(dnW + scale, dnH + scale)
if(yOffset) then
local anchor, parent, relative, xBase, yBase = downButton:GetPoint()
local yAdjust = ((yOffset or 0) * -1) + yBase
downButton:ClearAllPoints()
downButton:SetPoint(anchor, parent, relative, xBase, yAdjust)
end
end
if(not frame.BG) then
frame.BG = frame:CreateTexture(nil, "BACKGROUND")
frame.BG:SetPoint("TOPLEFT", upButton, "TOPLEFT", 1, -1)
frame.BG:SetPoint("BOTTOMRIGHT", downButton, "BOTTOMRIGHT", -1, 1)
frame.BG:SetTexture(SV.media.background.transparent)
local fg = CreateFrame("Frame", nil, frame)
fg:SetPoint("TOPLEFT", frame, "TOPLEFT", 18, -2)
fg:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -10, 6)
fg:SetBackdrop(SV.media.backdrop.outline)
frame.Brdr = fg
end
if(frame.SetThumbTexture) then
frame:SetThumbTexture(SV.media.button.knob)
end
elseif(frame.GetOrientation) then
if(frame:GetOrientation() == "VERTICAL") then
frame:SetWidth(12)
else
frame:SetHeight(12)
for i=1, frame:GetNumRegions() do
local child = select(i, frame:GetRegions())
if(child and child:GetObjectType() == "FontString") then
local anchor, parent, relative, x, y = child:GetPoint()
if relative:find("BOTTOM") then
child:SetPoint(anchor, parent, relative, x, y - 4)
end
end
end
end
RemoveTextures(frame)
frame:SetBackdrop(nil)
self.Methods["Frame"](self, frame, (not adjustable), "Transparent", true)
frame:SetBackdropBorderColor(0.2,0.2,0.2)
frame:SetThumbTexture(SV.media.button.knob)
end
end
MOD.Concepts["Tab"] = function(self, adjustable, frame, addBackground, xOffset, yOffset)
if(not frame or (frame and frame.Panel)) then return end
local tab = frame:GetName();
if _G[tab.."Left"] then _G[tab.."Left"]:SetTexture("") end
if _G[tab.."LeftDisabled"] then _G[tab.."LeftDisabled"]:SetTexture("") end
if _G[tab.."Right"] then _G[tab.."Right"]:SetTexture("") end
if _G[tab.."RightDisabled"] then _G[tab.."RightDisabled"]:SetTexture("") end
if _G[tab.."Middle"] then _G[tab.."Middle"]:SetTexture("") end
if _G[tab.."MiddleDisabled"] then _G[tab.."MiddleDisabled"]:SetTexture("") end
if(frame.GetHighlightTexture and frame:GetHighlightTexture()) then
frame:GetHighlightTexture():SetTexture("")
end
RemoveTextures(frame)
if(addBackground) then
local nTex = frame:GetNormalTexture()
if(nTex) then
nTex:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
InsetPoints(nTex, frame)
end
xOffset = xOffset or 1
yOffset = yOffset or 1
frame.pushed = true;
frame.backdrop = CreateFrame("Frame", nil, frame)
WrapPoints(frame.backdrop, frame, xOffset, yOffset)
frame.backdrop:SetFrameLevel(0)
self.Methods["Frame"](self, frame.backdrop, (not adjustable), "Button", false)
local initialAnchor, anchorParent, relativeAnchor, xPosition, yPosition = frame:GetPoint()
frame:SetPoint(initialAnchor, anchorParent, relativeAnchor, 1, yPosition)
else
xOffset = xOffset or 10
yOffset = yOffset or 3
frame.backdrop = CreateFrame("Frame", nil, frame)
InsetPoints(frame.backdrop, frame, xOffset, yOffset);
if(frame:GetFrameLevel() > 0) then
frame.backdrop:SetFrameLevel(frame:GetFrameLevel() - 1)
end
self.Methods["Frame"](self, frame.backdrop, (not adjustable), "Button", false)
end
frame:HookScript("OnEnter", Tab_OnEnter)
frame:HookScript("OnLeave", Tab_OnLeave)
-- if(frame.backdrop.UpdateBackdrop) then
-- frame.backdrop:UpdateBackdrop()
-- end
end
MOD.Concepts["DropDown"] = function(self, adjustable, frame, width)
if(not frame or (frame and frame.Panel)) then return end
local ddName = frame:GetName();
local ddText = _G[("%sText"):format(ddName)]
local ddButton = _G[("%sButton"):format(ddName)]
if not width then width = max(frame:GetWidth(), 128) end
RemoveTextures(frame)
frame:SetWidth(width)
if(ddButton) then
if(ddText) then
ddText:SetPoint("RIGHT", ddButton, "LEFT", 2, 0)
end
ddButton:ClearAllPoints()
ddButton:SetPoint("RIGHT", frame, "RIGHT", -10, 3)
ddButton.AnchorParent = frame
hooksecurefunc(ddButton, "SetPoint", _hook_DropDownButton_SetPoint)
self.Concepts["PageButton"](self, false, ddButton, true)
local currentLevel = frame:GetFrameLevel()
if(currentLevel == 0) then
currentLevel = 1
end
if(not frame.BG) then
frame.BG = frame:CreateTexture(nil, "BACKGROUND")
frame.BG:SetPoint("TOPLEFT", frame, "TOPLEFT", 18, -2)
frame.BG:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -10, 6)
frame.BG:SetTexture(SV.media.background.transparent)
local fg = CreateFrame("Frame", nil, frame)
fg:SetPoint("TOPLEFT", frame, "TOPLEFT", 18, -2)
fg:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -10, 6)
fg:SetBackdrop(SV.media.backdrop.outline)
frame.Brdr = fg
end
end
end
MOD.Concepts["Tooltip"] = function(self, adjustable, frame, useHook)
if(not frame or (frame and frame.Panel)) then return end
if frame.Background then
frame.Background:SetTexture("")
end
if frame.Delimiter1 then
frame.Delimiter1:SetTexture("")
frame.Delimiter2:SetTexture("")
end
if frame.BorderTop then
frame.BorderTop:SetTexture("")
end
if frame.BorderTopLeft then
frame.BorderTopLeft:SetTexture("")
end
if frame.BorderTopRight then
frame.BorderTopRight:SetTexture("")
end
if frame.BorderLeft then
frame.BorderLeft:SetTexture("")
end
if frame.BorderRight then
frame.BorderRight:SetTexture("")
end
if frame.BorderBottom then
frame.BorderBottom:SetTexture("")
end
if frame.BorderBottomRight then
frame.BorderBottomRight:SetTexture("")
end
if frame.BorderBottomLeft then
frame.BorderBottomLeft:SetTexture("")
end
frame:SetBackdrop(SV.media.backdrop.tooltip)
if(useHook) then
frame:HookScript('OnShow', _hook_Tooltip_OnShow)
end
end
MOD.Concepts["EditBox"] = function(self, adjustable, frame, width, height, x, y)
if(not frame or (frame and frame.Panel)) then return end
RemoveTextures(frame, true)
self.Methods["Editbox"](self, frame, adjustable, x, y)
if width then frame:SetWidth(width) end
if height then frame:SetHeight(height) end
end
MOD.Concepts["QuestItem"] = function(self, adjustable, frame)
if(not frame or (frame and frame.Panel)) then return end
local icon, oldIcon;
local name = frame:GetName();
if(name and _G[name.."IconTexture"]) then
icon = _G[name.."IconTexture"];
oldIcon = _G[name.."IconTexture"]:GetTexture();
elseif(frame.Icon) then
icon = frame.Icon;
oldIcon = frame.Icon:GetTexture();
end
RemoveTextures(frame)
self.Methods["Icon"](self, frame, adjustable)
local width,height = frame:GetSize()
local fittedWidth = (width - height) + 2
local insetFrame = CreateFrame("Frame", nil, frame.Panel)
insetFrame:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT")
insetFrame:SetWidth(fittedWidth)
insetFrame:SetHeight(height)
self.Methods["Frame"](self, insetFrame, false, "Inset")
if(icon) then
local size = height - 4
icon:ClearAllPoints()
icon:SetPoint("TOPLEFT", frame, "TOPLEFT", 2, -2)
icon:SetSize(size, size)
local iconFallback = frame.Panel:CreateTexture(nil, "BACKGROUND")
iconFallback:SetAllPoints(icon)
iconFallback:SetTexture([[Interface\ICONS\INV_Misc_Bag_10]])
iconFallback:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
if(oldIcon) then
icon:SetTexture(oldIcon)
end
icon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
end
end
MOD.Concepts["Skin"] = function(self, style, frame, topX, topY, bottomX, bottomY)
if(not frame or (frame and frame.Panel)) then return end
if(not style) then style = "model" end
local artname = style:lower()
local texture = SV.media.background[artname] or SV.media.background.model
RemoveTextures(frame, true)
local borderFrame = CreateFrame("Frame", nil, frame)
borderFrame:SetPoint("TOPLEFT", frame, "TOPLEFT", topX, topY)
borderFrame:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", bottomX, bottomY)
borderFrame:SetBackdrop(SV.media.backdrop.outline)
local skin = frame:CreateTexture(nil, "BACKGROUND", nil, -1)
skin:SetAllPoints(borderFrame)
skin:SetTexture(texture)
skin:SetGradient(unpack(SV.media.gradient.special))
end
local ALERT_TEMPLATE = {
["typeA"] = {
COLOR = {0.8, 0.2, 0.2},
BG = [[Interface\AddOns\SVUI_!Core\assets\textures\Alert\ALERT-BG]],
LEFT = [[Interface\AddOns\SVUI_!Core\assets\textures\Alert\ALERT-LEFT]],
RIGHT = [[Interface\AddOns\SVUI_!Core\assets\textures\Alert\ALERT-RIGHT]],
TOP = [[Interface\AddOns\SVUI_!Core\assets\textures\Alert\ALERT-TOP]],
BOTTOM = [[Interface\AddOns\SVUI_!Core\assets\textures\Alert\ALERT-BOTTOM]],
},
["typeB"] = {
COLOR = {0.08, 0.4, 0},
BG = [[Interface\AddOns\SVUI_!Core\assets\textures\Alert\ALERT-BG-2]],
LEFT = [[Interface\AddOns\SVUI_!Core\assets\textures\Alert\ALERT-LEFT-2]],
RIGHT = [[Interface\AddOns\SVUI_!Core\assets\textures\Alert\ALERT-RIGHT-2]],
TOP = [[Interface\AddOns\SVUI_!Core\assets\textures\Alert\ALERT-TOP]],
BOTTOM = [[Interface\AddOns\SVUI_!Core\assets\textures\Alert\ALERT-BOTTOM]],
},
};
local SetIconAlertColor = function(self, r, g, b)
self.AlertPanel.icon:SetGradient('VERTICAL', (r*0.5), (g*0.5), (b*0.5), r, g, b)
end;
local SetAlertColor = function(self, r, g, b)
self.AlertPanel:SetBackdropColor(r,g,b)
self.AlertPanel.left:SetVertexColor(r,g,b)
self.AlertPanel.right:SetVertexColor(r,g,b)
self.AlertPanel.top:SetVertexColor(r,g,b)
self.AlertPanel.bottom:SetVertexColor(r,g,b)
end;
MOD.Concepts["Alert"] = function(self, defaultStyle, frame, arg)
if(not frame or (frame and frame.AlertPanel)) then return end
if(not defaultStyle) then
local size = frame:GetWidth() * 0.5;
local lvl = frame:GetFrameLevel();
if lvl < 1 then lvl = 1 end
local alertpanel = CreateFrame("Frame", nil, frame)
alertpanel:SetPoint("TOPLEFT", frame, "TOPLEFT", -25, 10)
alertpanel:SetPoint("TOPRIGHT", frame, "TOPRIGHT", 10, 10)
alertpanel:SetHeight(size)
alertpanel:SetFrameLevel(lvl - 1)
--[[ FRAME BG ]]--
alertpanel.bg = alertpanel:CreateTexture(nil, "BACKGROUND", nil, -5)
alertpanel.bg:SetAllPoints()
alertpanel.bg:SetTexture([[Interface\AddOns\SVUI_!Core\assets\textures\Alert\ALERT-FULL]])
alertpanel.bg:SetGradient('VERTICAL', 0, 0, 0, .37, .32, .29)
--[[ ICON BG ]]--
alertpanel.icon = alertpanel:CreateTexture(nil, "BACKGROUND", nil, -2)
alertpanel.icon:SetTexture([[Interface\AddOns\SVUI_!Core\assets\textures\Alert\ALERT-ICON-BORDER]])
alertpanel.icon:SetGradient('VERTICAL', 1, 0.35, 0, 1, 1, 0)
alertpanel.icon:SetPoint("LEFT", alertpanel, "LEFT", -45, 20)
alertpanel.icon:SetSize(size, size)
frame.AlertPanel = alertpanel
frame.AlertColor = SetIconAlertColor
else
local alertType = arg and "typeB" or "typeA";
local TEMPLATE = ALERT_TEMPLATE[alertType];
local r,g,b = unpack(TEMPLATE.COLOR);
local size = frame:GetHeight();
local half = size * 0.5;
local offset = size * 0.1;
local lvl = frame:GetFrameLevel();
if lvl < 1 then lvl = 1 end
local alertpanel = CreateFrame("Frame", nil, frame)
alertpanel:SetPoint("TOPLEFT", frame, "TOPLEFT", offset, 0)
alertpanel:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -offset, 0)
alertpanel:SetFrameLevel(lvl - 1)
alertpanel:SetBackdrop({
bgFile = TEMPLATE.BG
})
alertpanel:SetBackdropColor(r,g,b)
--[[ LEFT ]]--
alertpanel.left = alertpanel:CreateTexture(nil, "BORDER")
alertpanel.left:SetTexture(TEMPLATE.LEFT)
alertpanel.left:SetVertexColor(r,g,b)
alertpanel.left:SetPoint("TOPRIGHT", alertpanel, "TOPLEFT", 0, 0)
alertpanel.left:SetPoint("BOTTOMRIGHT", alertpanel, "BOTTOMLEFT", 0, 0)
alertpanel.left:SetWidth(size)
--[[ RIGHT ]]--
alertpanel.right = alertpanel:CreateTexture(nil, "BORDER")
alertpanel.right:SetTexture(TEMPLATE.RIGHT)
alertpanel.right:SetVertexColor(r,g,b)
alertpanel.right:SetPoint("TOPLEFT", alertpanel, "TOPRIGHT", 0, 0)
alertpanel.right:SetPoint("BOTTOMLEFT", alertpanel, "BOTTOMRIGHT", 0, 0)
alertpanel.right:SetWidth(size * 2)
--[[ TOP ]]--
alertpanel.top = alertpanel:CreateTexture(nil, "BORDER")
alertpanel.top:SetTexture(TEMPLATE.TOP)
alertpanel.top:SetPoint("BOTTOMLEFT", alertpanel, "TOPLEFT", 0, 0)
alertpanel.top:SetPoint("BOTTOMRIGHT", alertpanel, "TOPRIGHT", 0, 0)
alertpanel.top:SetHeight(half)
--[[ BOTTOM ]]--
alertpanel.bottom = alertpanel:CreateTexture(nil, "BORDER")
alertpanel.bottom:SetTexture(TEMPLATE.BOTTOM)
alertpanel.bottom:SetPoint("TOPLEFT", alertpanel, "BOTTOMLEFT", 0, 0)
alertpanel.bottom:SetPoint("TOPRIGHT", alertpanel, "BOTTOMRIGHT", 0, 0)
alertpanel.bottom:SetWidth(half)
frame.AlertPanel = alertpanel
frame.AlertColor = SetAlertColor
end
end
function MOD:Set(concept, ...)
if(not concept) then return end
local fn;
local conceptString, flags = concept:gsub("!_", "");
local param = true;
if(flags and (flags > 0)) then
param = false;
end
local nameString, typeflags = conceptString:gsub("Skin", "");
if(typeflags and (typeflags > 0)) then
fn = self.Concepts["Skin"];
param = nameString
else
fn = self.Concepts[nameString];
end
if(fn) then
local pass, catch = pcall(fn, self, param, ...)
if(catch) then
SV:HandleError("API", "SetStyle", catch);
return
end
end
end
-- _G.Proxy_CreateFrame = CreateFrame;
-- _G.CreateFrame = function(frameType, frameName, parentFrame, template)
-- local f
-- if(template and template == "UIPanelButtonTemplate") then
-- f = Proxy_CreateFrame(frameType, frameName, parentFrame, template)
-- else
-- f = Proxy_CreateFrame(frameType, frameName, parentFrame, template)
-- end
-- return f
-- end
-- hooksecurefunc("CreateFrame", function(frameType, globalName, parent, template)
-- if(template and template:find("UIPanelButtonTemplate")) then
-- if(globalName) then
-- print(globalName .. ' -> ' .. template)
-- else
-- print(template)
-- end
-- end
-- end)
| mit |
mihailim/koreader | plugins/newsdownloader.koplugin/feed_config.lua | 1 | 1386 | return {--do NOT change this line
--HELP:
-- use syntax: {"http://your-url.com", limit=max_number_of_items_to_be_created, download_full_article=true/false},
-- remember to put coma at the end of each line!
-- you can also edit this file in external text editor. Config file is located under:
-- <your_download_directory>/feed_config.lua
-- default: <koreader_dir>/news/feed_config.lua
-- DETAILS:
-- set 'limit' to "0" means no limit.
-- 'download_full_article=true' - means download full article (may not always work correctly)
-- 'download_full_article=false' - means use only feed description to create feeds (usually only beginning of the article)
-- default value is 'true' (if no 'download_full_article' entry)
-- 'include_images=true' - means download any images on the page and inlude them in the article
-- 'include_images=false' - means ignore any images, only download the text (faster download, smaller file sizes)
-- default value is 'false' (if no 'include_images' entry)
-- comment out line ("--" at line start) to stop downloading source
-- LIST YOUR FEEDS HERE:
{ "http://feeds.reuters.com/Reuters/worldNews?format=xml", limit = 2, download_full_article=true},
{ "https://www.pcworld.com/index.rss", limit = 7 , download_full_article=false},
-- { "http://www.football.co.uk/international/rss.xml", limit = 2},
}--do NOT change this line
| agpl-3.0 |
nekrozar/ygopro-scripts | c62543393.lua | 7 | 1456 | --レクンガ
function c62543393.initial_effect(c)
--token
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(62543393,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c62543393.cost)
e1:SetTarget(c62543393.target)
e1:SetOperation(c62543393.operation)
c:RegisterEffect(e1)
end
function c62543393.cfilter(c)
return c:IsAttribute(ATTRIBUTE_WATER) and c:IsAbleToRemoveAsCost()
end
function c62543393.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c62543393.cfilter,tp,LOCATION_GRAVE,0,2,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c62543393.cfilter,tp,LOCATION_GRAVE,0,2,2,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c62543393.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsPlayerCanSpecialSummonMonster(tp,62543394,0,0x4011,700,700,2,RACE_PLANT,ATTRIBUTE_WATER) end
Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,0)
end
function c62543393.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsPlayerCanSpecialSummonMonster(tp,62543394,0,0x4011,700,700,2,RACE_PLANT,ATTRIBUTE_WATER) then
local token=Duel.CreateToken(tp,62543394)
Duel.SpecialSummon(token,0,tp,tp,false,false,POS_FACEUP_ATTACK)
end
end
| gpl-2.0 |
nekrozar/ygopro-scripts | c64442155.lua | 1 | 1819 | --慈悲深き機械天使
function c64442155.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,64442155+EFFECT_COUNT_CODE_OATH)
e1:SetCost(c64442155.cost)
e1:SetTarget(c64442155.target)
e1:SetOperation(c64442155.activate)
c:RegisterEffect(e1)
end
function c64442155.costfilter(c)
return c:IsSetCard(0x2093) and c:GetType()&0x81==0x81 and c:IsReleasable()
end
function c64442155.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroupEx(tp,c64442155.costfilter,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectReleaseGroupEx(tp,c64442155.costfilter,1,1,nil)
Duel.Release(g,REASON_COST)
end
function c64442155.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,2) end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(2)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,2)
end
function c64442155.activate(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
local g=Duel.GetMatchingGroup(Card.IsAbleToDeck,p,LOCATION_HAND,0,nil)
if g:GetCount()>0 then
Duel.Hint(HINT_SELECTMSG,p,HINTMSG_TODECK)
local sg=g:Select(p,1,1,nil)
Duel.SendtoDeck(sg,nil,1,REASON_EFFECT)
end
if not e:IsHasType(EFFECT_TYPE_ACTIVATE) then return end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetTarget(c64442155.splimit)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c64442155.splimit(e,c)
return c:GetType()&0x81~=0x81
end
| gpl-2.0 |
nekrozar/ygopro-scripts | c74298287.lua | 3 | 2719 | --水精鱗-アビスディーネ
function c74298287.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(74298287,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_TO_HAND)
e1:SetCountLimit(1,74298287)
e1:SetCondition(c74298287.spcon1)
e1:SetTarget(c74298287.sptg1)
e1:SetOperation(c74298287.spop1)
c:RegisterEffect(e1)
--
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(74298287,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetCountLimit(1,74298287)
e2:SetCondition(c74298287.spcon2)
e2:SetTarget(c74298287.sptg2)
e2:SetOperation(c74298287.spop2)
c:RegisterEffect(e2)
end
function c74298287.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x74)
end
function c74298287.spcon1(e,tp,eg,ep,ev,re,r,rp)
return bit.band(r,REASON_EFFECT)~=0 and e:GetHandler():IsPreviousLocation(LOCATION_DECK+LOCATION_GRAVE)
and Duel.IsExistingMatchingCard(c74298287.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c74298287.sptg1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsRelateToEffect(e) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c74298287.spop1(e,tp,eg,ep,ev,re,r,rp)
if not Duel.IsExistingMatchingCard(c74298287.cfilter,tp,LOCATION_MZONE,0,1,nil) then return end
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
function c74298287.spcon2(e,tp,eg,ep,ev,re,r,rp)
return re:IsActiveType(TYPE_MONSTER) and re:GetHandler():IsSetCard(0x74)
end
function c74298287.spfilter(c,e,tp)
return c:IsSetCard(0x74) and c:IsLevelBelow(3) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c74298287.sptg2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c74298287.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c74298287.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c74298287.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c74298287.spop2(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
chrisJohn404/ljswitchboard-module_manager | lib/switchboard_modules/lua_script_debugger/premade_scripts_addresses/counter_examples/23_counters.lua | 1 | 3048 | --This program demonstrates how to use digital lines as simple counters.
--Most commonly users should throttle their code execution using the functions:
--'LJ.IntervalConfig(0, 1000)', and 'if LJ.CheckInterval(0) then' ...
--Array indeces 1-23 correspond with DIO0-22 as the following:
--Index: 1 Channel: FIO0 (DIO0)
--Index: 2 Channel: FIO1 (DIO1)
--Index: 3 Channel: FIO2 (DIO2)
--Index: 4 Channel: FIO3 (DIO3)
--Index: 5 Channel: FIO4 (DIO4)
--Index: 6 Channel: FIO5 (DIO5)
--Index: 7 Channel: FIO6 (DIO6)
--Index: 8 Channel: FIO7 (DIO7)
--Index: 9 Channel: EIO0 (DIO8)
--Index: 10 Channel: EIO1 (DIO9)
--Index: 11 Channel: EIO2 (DIO10)
--Index: 12 Channel: EIO3 (DIO11)
--Index: 13 Channel: EIO4 (DIO12)
--Index: 14 Channel: EIO5 (DIO13)
--Index: 15 Channel: EIO6 (DIO14)
--Index: 16 Channel: EIO7 (DIO15)
--Index: 17 Channel: CIO0 (DIO16)
--Index: 18 Channel: CIO1 (DIO17)
--Index: 19 Channel: CIO2 (DIO18)
--Index: 20 Channel: CIO3 (DIO19)
--Index: 21 Channel: MIO0 (DIO20)
--Index: 22 Channel: MIO1 (DIO21)
--Index: 23 Channel: MIO2 (DIO22)
print("Create and read 23 counters.")
local mbRead=MB.R --Local functions for faster processing
local mbWrite=MB.W
if (mbRead(60000, 3) ~= 7) then
print("This example is only for the T7. Exiting Lua Script.")
mbWrite(6000, 1, 0)
end
--1 = Rising edge, 0 = falling
local edge = {}
for i = 1, 23 do
edge[i] = 0 --sets all 23 counters to increment on falling edges
end
local bits = {}
local bits_new = {}
local count = {}
--The throttle setting can correspond roughly with the length of the Lua
--script. A rule of thumb for deciding a throttle setting is
--throttle = (3*NumLinesCode) + 20
local throttleSetting = 100 --Default throttle setting is 10 instructions
LJ.setLuaThrottle(throttleSetting)
local throttleSetting = LJ.getLuaThrottle()
print ("Current Lua Throttle Setting: ", throttleSetting)
mbWrite(2600, 0, 0) --FIO to input
mbWrite(2601, 0, 0) --EIO to input
mbWrite(2602, 0, 0) --COI to input
mbWrite(2603, 0, 0) --MIO to input
for i=1, 23 do
bits[i] = 0
bits_new[i] = 99
count[i] = 0
end
while true do
for i=1, 23 do
bits_new[i] = mbRead((i-1)+2000, 0)
end
--Compare bits_new to bits
for i=1, 23 do
if bits[i] ~= bits_new[i] then
if edge[i] == 1 then
if bits[i] == 0 then
count[i] = count[i] + 1
print ("Counter: ", i, " Rising: ", count[i])
end
else
if bits[i] == 1 then
count[i] = count[i] + 1
print ("Counter: ", i, " Falling: ", count[i])
end
end
bits[i] = bits_new[i]
mbWrite(((i-1)*2)+46000, 3, count[i]) --Save in User RAM
end
end
end
| mit |
nekrozar/ygopro-scripts | c59951714.lua | 2 | 2446 | --アドバンス・ディボーター
function c59951714.initial_effect(c)
--cannot special summon
local e1=Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_BE_MATERIAL)
e2:SetOperation(c59951714.spr)
c:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(59951714,0))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetRange(LOCATION_GRAVE)
e3:SetCode(EVENT_PHASE+PHASE_STANDBY)
e3:SetCondition(c59951714.spcon)
e3:SetCost(c59951714.spcost)
e3:SetTarget(c59951714.sptg)
e3:SetOperation(c59951714.spop)
c:RegisterEffect(e3)
Duel.AddCustomActivityCounter(59951714,ACTIVITY_SPSUMMON,c59951714.counterfilter)
end
function c59951714.counterfilter(c)
return c:GetSummonLocation()~=LOCATION_EXTRA
end
function c59951714.spr(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if r==REASON_SUMMON then
c:RegisterFlagEffect(59951714,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,0,1)
end
end
function c59951714.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:GetTurnID()~=Duel.GetTurnCount() and tp==Duel.GetTurnPlayer() and c:GetFlagEffect(59951714)>0
end
function c59951714.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetCustomActivityCount(59951714,tp,ACTIVITY_SPSUMMON)==0 end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e1:SetTargetRange(1,0)
e1:SetTarget(c59951714.splimit)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c59951714.splimit(e,c,sump,sumtype,sumpos,targetp)
return c:IsLocation(LOCATION_EXTRA)
end
function c59951714.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,true,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
e:GetHandler():ResetFlagEffect(59951714)
end
function c59951714.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP)
end
end
| gpl-2.0 |
FailcoderAddons/SVUI | SVUI_!Core/system/_docklets/misc.lua | 1 | 7767 | --[[
##########################################################
S V U I By: Munglunch
##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
local assert = _G.assert;
local type = _G.type;
local error = _G.error;
local pcall = _G.pcall;
local print = _G.print;
local ipairs = _G.ipairs;
local pairs = _G.pairs;
local tostring = _G.tostring;
local tonumber = _G.tonumber;
--STRING
local string = _G.string;
local upper = string.upper;
local format = string.format;
local find = string.find;
local match = string.match;
local gsub = string.gsub;
--TABLE
local table = _G.table;
local tinsert = _G.tinsert;
local tremove = _G.tremove;
local twipe = _G.wipe;
--MATH
local math = _G.math;
local min = math.min;
local floor = math.floor
local ceil = math.ceil
--BLIZZARD API
local Quit = _G.Quit;
local Logout = _G.Logout;
local ReloadUI = _G.ReloadUI;
local GameTooltip = _G.GameTooltip;
local InCombatLockdown = _G.InCombatLockdown;
local CreateFrame = _G.CreateFrame;
local GetTime = _G.GetTime;
local GetItemCooldown = _G.GetItemCooldown;
local GetItemCount = _G.GetItemCount;
local GetItemInfo = _G.GetItemInfo;
local GetSpellInfo = _G.GetSpellInfo;
local IsSpellKnown = _G.IsSpellKnown;
local GetProfessions = _G.GetProfessions;
local GetProfessionInfo = _G.GetProfessionInfo;
local IsAltKeyDown = _G.IsAltKeyDown;
local IsShiftKeyDown = _G.IsShiftKeyDown;
local IsControlKeyDown = _G.IsControlKeyDown;
local IsModifiedClick = _G.IsModifiedClick;
local hooksecurefunc = _G.hooksecurefunc;
local GetSpecialization = _G.GetSpecialization;
local GetNumSpecGroups = _G.GetNumSpecGroups;
local GetActiveSpecGroup = _G.GetActiveSpecGroup;
local SetActiveSpecGroup = _G.SetActiveSpecGroup;
local GetSpecializationInfo = _G.GetSpecializationInfo;
--[[
##########################################################
ADDON
##########################################################
]]--
local SV = select(2, ...)
local L = SV.L
local MOD = SV.Dock;
--[[
##########################################################
LOCALS
##########################################################
]]--
local HEARTH_SPELLS = {556,50977,18960,126892}
local function GetMacroCooldown(itemID)
local start,duration = GetItemCooldown(itemID)
local expires = duration - (GetTime() - start)
if expires > 0.05 then
local timeLeft = 0;
local calc = 0;
if expires < 4 then
return format("|cffff0000%.1f|r", expires)
elseif expires < 60 then
return format("|cffffff00%d|r", floor(expires))
elseif expires < 3600 then
timeLeft = ceil(expires / 60);
calc = floor((expires / 60) + .5);
return format("|cffff9900%dm|r", timeLeft)
elseif expires < 86400 then
timeLeft = ceil(expires / 3600);
calc = floor((expires / 3600) + .5);
return format("|cff66ffff%dh|r", timeLeft)
else
timeLeft = ceil(expires / 86400);
calc = floor((expires / 86400) + .5);
return format("|cff6666ff%dd|r", timeLeft)
end
else
return "|cff6666ffReady|r"
end
end
local Hearth_OnEnter = function(self)
GameTooltip:AddLine(HELPFRAME_STUCK_HEARTHSTONE_HEADER, 1, 1, 0)
GameTooltip:AddLine(" ", 1, 1, 1)
local location = GetBindLocation()
GameTooltip:AddDoubleLine(LOCATION_COLON, location, 1, 0.5, 0, 1, 1, 1)
if InCombatLockdown() then return end
local remaining = GetMacroCooldown(6948)
GameTooltip:AddDoubleLine(L["Time Remaining"], remaining, 1, 0.5, 0, 1, 1, 1)
local text1 = self:GetAttribute("tipText")
local text2 = self:GetAttribute("tipExtraText")
GameTooltip:AddLine(" ", 1, 1, 1)
GameTooltip:AddDoubleLine("[Left-Click]", text1, 0, 1, 0, 1, 1, 1)
if(text2) then
GameTooltip:AddDoubleLine("[Right Click]", text2, 0, 1, 0, 1, 1, 1)
end
end
local SpecSwap_OnClick = function(self)
if InCombatLockdown() then return end
local current = GetActiveSpecGroup()
if(current == 2) then
SetActiveSpecGroup(1)
else
SetActiveSpecGroup(2)
end
end
local SpecSwap_OnEnter = function(self)
local currentGroup = GetActiveSpecGroup()
local currentSpec = GetSpecialization(false, false, currentGroup);
local text1 = currentSpec and select(2, GetSpecializationInfo(currentSpec)) or "None"
local otherGroup = 1;
local activeText = SPECIALIZATION_SECONDARY_ACTIVE;
local otherText = SPECIALIZATION_PRIMARY;
if(currentGroup == 1) then
otherGroup = 2
activeText = SPECIALIZATION_PRIMARY_ACTIVE;
otherText = SPECIALIZATION_SECONDARY;
end
local otherSpec = GetSpecialization(false, false, otherGroup);
local text2 = otherSpec and select(2, GetSpecializationInfo(otherSpec)) or "None"
GameTooltip:AddLine(GARRISON_SWITCH_SPECIALIZATIONS, 1, 1, 0)
GameTooltip:AddLine(" ", 1, 1, 1)
GameTooltip:AddDoubleLine(activeText, text1, 1, 0.5, 0, 1, 1, 1)
GameTooltip:AddDoubleLine(otherText, text2, 1, 0.5, 0, 1, 1, 1)
end
local PowerButton_OnClick = function(self, button)
if(button == "RightButton" and IsShiftKeyDown()) then
Quit()
elseif(IsShiftKeyDown()) then
ReloadUI()
else
Logout()
end
end
local PowerButton_OnEnter = function(self)
GameTooltip:AddLine(OTHER .. " " .. OPTIONS_MENU, 1, 1, 0)
GameTooltip:AddLine(" ", 1, 1, 1)
GameTooltip:AddDoubleLine("[Click]", LOGOUT, 0, 1, 0, 1, 1, 1)
GameTooltip:AddDoubleLine("[SHIFT + Left Click]", RELOADUI, 0, 1, 0, 1, 1, 1)
GameTooltip:AddDoubleLine("[SHIFT + Right Click]", EXIT_GAME, 0, 1, 0, 1, 1, 1)
end
local function LoadMiscTools()
if(MOD.MiscToolsLoaded) then return end
if(InCombatLockdown()) then
MOD.MiscNeedsUpdate = true;
MOD:RegisterEvent("PLAYER_REGEN_ENABLED");
return
end
-- HEARTH BUTTON
if(SV.db.Dock.dockTools.hearth) then
local hearthStone = GetItemInfo(6948);
if(hearthStone and type(hearthStone) == "string") then
local hearth = SV.Dock:SetDockButton("BottomLeft", L["Hearthstone"], "SVUI_Hearth", SV.media.dock.hearthIcon, false, Hearth_OnEnter, "SecureActionButtonTemplate")
hearth.Icon:SetTexCoord(0,0.5,0,1)
hearth:SetAttribute("type1", "macro")
hearth:SetAttribute("macrotext1", "/use [nomod]" .. hearthStone)
local hasRightClick = false;
for i = 1, #HEARTH_SPELLS do
if(IsSpellKnown(HEARTH_SPELLS[i])) then
local rightClickSpell = GetSpellInfo(HEARTH_SPELLS[i])
hearth:SetAttribute("tipExtraText", rightClickSpell)
hearth:SetAttribute("type2", "macro")
hearth:SetAttribute("macrotext2", "/use [nomod] " .. rightClickSpell)
hasRightClick = true;
end
end
end
end
-- SPEC BUTTON
if(SV.db.Dock.dockTools.specswap) then
local numSpecGroups = GetNumSpecGroups()
if(numSpecGroups and numSpecGroups == 2) then
local specSwap = SV.Dock:SetDockButton("BottomLeft", L["Spec Swap"], "SVUI_SpecSwap", SV.media.dock.specSwapIcon, SpecSwap_OnClick, SpecSwap_OnEnter)
end
end
-- POWER BUTTON
if(SV.db.Dock.dockTools.power) then
local power = SV.Dock:SetDockButton("BottomLeft", L["Power Button"], "SVUI_PowerButton", SV.media.dock.powerIcon, PowerButton_OnClick, PowerButton_OnEnter)
end
MOD.MiscToolsLoaded = true
end
--[[
##########################################################
BUILD/UPDATE
##########################################################
]]--
function MOD:UpdateMiscTools()
if(self.MiscToolsLoaded) then return end
LoadMiscTools()
end
function MOD:LoadAllMiscTools()
if(self.MiscToolsLoaded) then return end
SV.Timers:ExecuteTimer(LoadMiscTools, 5)
end
| mit |
nekrozar/ygopro-scripts | c30155789.lua | 3 | 3087 | --サディスティック・ポーション
function c30155789.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCost(c30155789.cost)
e1:SetTarget(c30155789.target)
e1:SetOperation(c30155789.operation)
c:RegisterEffect(e1)
end
function c30155789.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local c=e:GetHandler()
local cid=Duel.GetChainInfo(0,CHAININFO_CHAIN_ID)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_REMAIN_FIELD)
e1:SetProperty(EFFECT_FLAG_OATH)
e1:SetReset(RESET_CHAIN)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_CHAIN_DISABLED)
e2:SetOperation(c30155789.tgop)
e2:SetLabel(cid)
e2:SetReset(RESET_CHAIN)
Duel.RegisterEffect(e2,tp)
end
function c30155789.tgop(e,tp,eg,ep,ev,re,r,rp)
local cid=Duel.GetChainInfo(ev,CHAININFO_CHAIN_ID)
if cid~=e:GetLabel() then return end
if e:GetOwner():IsRelateToChain(ev) then
e:GetOwner():CancelToGrave(false)
end
end
function c30155789.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() end
if chk==0 then return e:IsHasType(EFFECT_TYPE_ACTIVATE)
and Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c30155789.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsLocation(LOCATION_SZONE) then return end
if not c:IsRelateToEffect(e) or c:IsStatus(STATUS_LEAVE_CONFIRMED) then return end
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,c,tc)
--draw
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_DAMAGE)
e1:SetRange(LOCATION_SZONE)
e1:SetCondition(c30155789.damcon)
e1:SetOperation(c30155789.damop)
e1:SetCountLimit(1)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
c:RegisterEffect(e1)
--Equip limit
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_EQUIP_LIMIT)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetValue(c30155789.eqlimit)
e3:SetLabelObject(tc)
e3:SetReset(RESET_EVENT+RESETS_STANDARD)
c:RegisterEffect(e3)
else
c:CancelToGrave(false)
end
end
function c30155789.eqlimit(e,c)
return c==e:GetLabelObject()
end
function c30155789.damcon(e,tp,eg,ep,ev,re,r,rp)
return bit.band(r,REASON_EFFECT)~=0 and ep~=tp and rp==tp
end
function c30155789.damop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=c:GetEquipTarget()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(1000)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
end
| gpl-2.0 |
hjsrzvpqma/test | plugins/plugins.lua | 19 | 6327 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '⛔️'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✅'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..status..' '..v..'\n'
end
end
local text = text..'\nدر مجموع '..nsum..' افزونه وجود دارد.\n'..nact..' افزونه فعال و '..nsum-nact..' افزونه غیر فعال.'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '⛔️'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✅'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..status..' '..v..'\n'
end
end
local text = text..'\n'..nact..' افزونه فعال میباشد\nاز '..nsum..' افزونه نصب شده.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return '✅ افزونه '..plugin_name..' فعال است.'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return '⛔️ افزونه '..plugin_name..' وجود ندارد.'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return '⛔️ افزونه '..name..' وجود ندارد.'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return '⛔️ افزونه '..name..' فعال نیست.'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "⛔️ این افزونه وجود ندارد."
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return '⛔️ افزونه '..plugin..' غیر فعال شد.'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return '✅ این افزونه فعال است.'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return '✅ افزونه '..plugin..' مجددا فعال شد.'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '/plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == '+' and matches[3] == 'group' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("✅ افزونه "..plugin..' فعال شد.')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == '-' and matches[3] == 'group' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("⛔️ افزونه "..plugin..' غیر فعال شد.')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return '⛔️ این افزونه نمیتواند غیر فعال شود.'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == '?' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin Manager",
usage = {
moderator = {
"/plugins - (name) group : disable item in group",
"/plugins + (name) group : enable item in group",
},
sudo = {
"/plugins : plugins list",
"/plugins + (name) : enable bot item",
"/plugins - (name) : disable bot item",
"/plugins ? : reloads plugins" },
},
patterns = {
"^[!/]plugins$",
"^[!/]plugins? (+) ([%w_%.%-]+)$",
"^[!/]plugins? (-) ([%w_%.%-]+)$",
"^[!/]plugins? (+) ([%w_%.%-]+) (group)",
"^[!/]plugins? (-) ([%w_%.%-]+) (group)",
"^[!/]plugins? (?)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end
| gpl-2.0 |
nekrozar/ygopro-scripts | c83326048.lua | 2 | 1619 | --次元障壁
function c83326048.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DISABLE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMINGS_CHECK_MONSTER)
e1:SetCountLimit(1,83326048+EFFECT_COUNT_CODE_OATH)
e1:SetTarget(c83326048.target)
e1:SetOperation(c83326048.operation)
c:RegisterEffect(e1)
end
function c83326048.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CARDTYPE)
Duel.SetTargetParam(Duel.SelectOption(tp,1057,1056,1063,1073,1074))
end
function c83326048.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local opt=Duel.GetChainInfo(0,CHAININFO_TARGET_PARAM)
local ct=nil
if opt==0 then ct=TYPE_RITUAL end
if opt==1 then ct=TYPE_FUSION end
if opt==2 then ct=TYPE_SYNCHRO end
if opt==3 then ct=TYPE_XYZ end
if opt==4 then ct=TYPE_PENDULUM end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetLabel(ct)
e1:SetTargetRange(1,1)
e1:SetTarget(c83326048.sumlimit)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_DISABLE)
e2:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e2:SetTarget(c83326048.distg)
e2:SetLabel(ct)
e2:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e2,tp)
end
function c83326048.sumlimit(e,c,sump,sumtype,sumpos,targetp)
return c:IsType(e:GetLabel())
end
function c83326048.distg(e,c)
return c:IsType(e:GetLabel())
end
| gpl-2.0 |
xuejian1354/attitude_adjustment | feeds/luci/modules/admin-full/luasrc/model/cbi/admin_network/ipv6.lua | 17 | 4011 | --[[
LuCI - Lua Configuration Interface
Copyright 2013 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local m, s, o
m = Map("6relayd", translate("IPv6 RA and DHCPv6"),
translate("6relayd is a daemon for serving and relaying IPv6 management protocols to "..
"configure clients and downstream routers. "..
"It provides server services for RA, stateless and stateful DHCPv6, "..
"prefix delegation and can be used to relay RA, DHCPv6 and NDP between routed "..
"(non-bridged) interfaces in case no delegated prefixes are available."))
s = m:section(TypedSection, "server", translate("Server Settings"))
s.addremove = false
s.anonymous = true
o = s:option(DynamicList, "network", translate("Service Interfaces"),
translate("Interfaces to provide services on or to relay services to."))
o.widget = "checkbox"
o.template = "cbi/network_netlist"
o.nocreate = true
o.nobridges = true
o.novirtual = true
o.optional = false
o = s:option(ListValue, "rd", translate("Router Advertisement-Service"))
o:value("", translate("disabled"))
o:value("server", translate("server mode"))
o:value("relay", translate("relay mode"))
o = s:option(ListValue, "dhcpv6", translate("DHCPv6-Service"))
o:value("", translate("disabled"))
o:value("server", translate("server mode"))
o:value("relay", translate("relay mode"))
o = s:option(ListValue, "management_level", translate("DHCPv6-Mode"))
o:value("", translate("stateless"))
o:value("1", translate("stateless + stateful"))
o:value("2", translate("stateful-only"))
o:depends("dhcpv6", "server")
o = s:option(ListValue, "ndp", translate("NDP-Proxy"))
o:value("", translate("disabled"))
o:value("relay", translate("relay mode"))
o = s:option(Flag, "fallback_relay", translate("Fallback to relay"),
translate("Relay services from master to server interfaces when there is no public prefix available."))
o.enabled = "rd dhcpv6 ndp"
o.disabled = ""
o = s:option(Value, "master", translate("Master Interface"),
translate("Specifies the master interface for services that are relayed."))
o.template = "cbi/network_netlist"
o.nocreate = true
o:depends("rd", "relay")
o:depends("dhcpv6", "relay")
o:depends("ndp", "relay")
o:depends("fallback_relay", "rd dhcpv6 ndp")
o = s:option(Flag, "always_rewrite_dns", translate("Always announce local DNS"),
translate("Announce the local router as DNS server even in relay mode."))
o:depends("rd", "relay")
o:depends("dhcpv6", "relay")
o:depends("fallback_relay", "rd dhcpv6 ndp")
o = s:option(Value, "rewrite_dns_addr", translate("Override announced DNS-server"),
translate("Announce a custom DNS-server instead of the local one."))
o = s:option(Flag, "always_assume_default", translate("Always announce default router"),
translate("Announce as default router even if no public prefix is available."))
o:depends("rd", "server")
o = s:option(Flag, "compat_ula", translate("ULA-preference compatibility"),
translate("Work around IPv6 address-selection issues of some devices."))
m:section(SimpleSection).template = "admin_network/lease_status"
s = m:section(TypedSection, "lease", translate("Static Leases"),
translate("Static leases are used to assign fixed IPv6 Interface-IDs to clients. Interface-IDs are appended to available prefixes to form IPv6-addresses. " ..
" (e.g. a prefix of 2001:db80::/64 combined with Interface-ID 123456 will form the address 2001:db80::12:3456)") .. "<br />" ..
translate("Use the <em>Add</em> Button to add a new lease entry. The <em>DUID</em> " ..
"indentifies the host, the <em>Interface-ID</em> specifies the ID to use in addresses."))
s.addremove = true
s.anonymous = true
s.template = "cbi/tblsection"
s:option(Value, "duid", translate("DUID")).optional = false
s:option(Value, "id", translate("Interface-ID")).optional = false
return m
| gpl-2.0 |
nekrozar/ygopro-scripts | c44686185.lua | 4 | 3381 | --影六武衆-ハツメ
function c44686185.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(44686185,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetCountLimit(1,44686185)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c44686185.cost)
e1:SetTarget(c44686185.target)
e1:SetOperation(c44686185.operation)
c:RegisterEffect(e1)
--destroy replace
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EFFECT_DESTROY_REPLACE)
e2:SetRange(LOCATION_GRAVE)
e2:SetTarget(c44686185.reptg)
e2:SetValue(c44686185.repval)
e2:SetOperation(c44686185.repop)
c:RegisterEffect(e2)
end
function c44686185.filter0(c)
return c:IsLocation(LOCATION_MZONE) and c:GetSequence()<5
end
function c44686185.filter1(c)
return c:IsSetCard(0x3d) and c:IsType(TYPE_MONSTER) and c:IsAbleToRemoveAsCost() and (c:IsLocation(LOCATION_GRAVE) or c:IsFaceup())
end
function c44686185.filter3(c,e,tp)
return c44686185.filter1(c)
and Duel.IsExistingMatchingCard(c44686185.filter4,tp,LOCATION_GRAVE+LOCATION_ONFIELD,0,1,c,e,tp,c)
end
function c44686185.filter4(c,e,tp,rc)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
local g=Group.FromCards(c,rc)
local ct=g:FilterCount(c44686185.filter0,nil)
return c44686185.filter1(c) and ft+ct>0
and Duel.IsExistingTarget(c44686185.filter2,tp,LOCATION_GRAVE,0,1,g,e,tp)
end
function c44686185.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c44686185.filter3,tp,LOCATION_GRAVE+LOCATION_ONFIELD,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g1=Duel.SelectMatchingCard(tp,c44686185.filter3,tp,LOCATION_GRAVE+LOCATION_ONFIELD,0,1,1,nil,e,tp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g2=Duel.SelectMatchingCard(tp,c44686185.filter4,tp,LOCATION_GRAVE+LOCATION_ONFIELD,0,1,1,g1:GetFirst(),e,tp,g1:GetFirst())
g1:Merge(g2)
Duel.Remove(g1,POS_FACEUP,REASON_COST)
end
function c44686185.filter2(c,e,tp)
return c:IsSetCard(0x3d) and not c:IsCode(44686185) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c44686185.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c44686185.filter2(chkc,e,tp) end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c44686185.filter2,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c44686185.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
function c44686185.repfilter(c,tp)
return c:IsFaceup() and c:IsSetCard(0x3d)
and c:IsLocation(LOCATION_MZONE) and c:IsControler(tp) and c:IsReason(REASON_EFFECT) and not c:IsReason(REASON_REPLACE)
end
function c44686185.reptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemove() and eg:IsExists(c44686185.repfilter,1,nil,tp)
and eg:GetCount()==1 end
return Duel.SelectEffectYesNo(tp,e:GetHandler(),96)
end
function c44686185.repval(e,c)
return c44686185.repfilter(c,e:GetHandlerPlayer())
end
function c44686185.repop(e,tp,eg,ep,ev,re,r,rp)
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_EFFECT)
end
| gpl-2.0 |
chrisjbray/hammerspoon | extensions/fnutils/init.lua | 11 | 20125 | --- === hs.fnutils ===
---
--- Functional programming utility functions
local fnutils = {}
local pairs,ipairs = pairs,ipairs
local floor = math.floor
--- hs.fnutils.imap(list, fn) -> list
--- Function
--- Execute a function across a list-like table in order, and collect the results
---
--- Parameters:
--- * list - A list-like table, i.e. one whose keys are sequential integers starting from 1
--- * fn - A function that accepts a single parameter (a table element). The values returned from this function
--- will be collected into the result list; when `nil` is returned the relevant element is discarded - the
--- result list won't have any "holes".
---
--- Returns:
--- * A list-like table containing the results of calling the function on every element in the table
---
--- Notes:
--- * If `list` has "holes", all elements after the first hole will be lost, as the table is iterated over with `ipairs`;
--- use `hs.fnutils.map()` if your table has holes
function fnutils.imap(t, fn)
local nt = {}
for _, v in ipairs(t) do
nt[#nt+1] = fn(v) -- or nil < removed, as this precludes inserting false!
end
return nt
end
local function isListIndex(k)
return type(k)=='number' and k>=1 and floor(k)==k -- not using 5.3 syntax (k//1==k), as you never know
end
--- hs.fnutils.map(table, fn) -> table
--- Function
--- Execute a function across a table (in arbitrary order) and collect the results
---
--- Parameters:
--- * table - A table; it can have both a list (or array) part and a hash (or dict) part
--- * fn - A function that accepts a single parameter (a table element). For the hash part, the values returned
--- from this function (if non-nil) will be assigned to the same key in the result list. For the array part, this function
--- behaves like `hs.fnutils.imap()` (i.e. `nil` results are discarded); however all keys, including integer keys after
--- a "hole" in `table`, will be iterated over.
---
--- Returns:
--- * A table containing the results of calling the function on every element in the table
---
--- Notes:
--- * If `table` is a pure array table (list-like) without "holes", use `hs.fnutils.imap()` if you need guaranteed in-order
--- processing and for better performance.
function fnutils.map(t, fn)
local nt = {}
for k, v in pairs(t) do -- they'll potentially be out of order, but they always were anyway
nt[isListIndex(k) and (#nt+1) or k] = fn(v) -- meh, but required for compatibility
end
return nt
end
--- hs.fnutils.ieach(list, fn)
--- Function
--- Execute a function across a list-like table in order, and discard the results
---
--- Parameters:
--- * list - A list-like table, i.e. one whose keys are sequential integers starting from 1
--- * fn - A function that accepts a single parameter (a table element)
---
--- Returns:
--- * None
function fnutils.ieach(t, fn)
for _, v in ipairs(t) do fn(v) end
end
--- hs.fnutils.each(table, fn)
--- Function
--- Execute a function across a table (in arbitrary order), and discard the results
---
--- Parameters:
--- * table - A table; it can have both a list (or array) part and a hash (or dict) part
--- * fn - A function that accepts a single parameter (a table element)
---
--- Returns:
--- * None
function fnutils.each(t, fn)
for _, v in pairs(t) do fn(v) end
end
--- hs.fnutils.ifilter(list, fn) -> list
--- Function
--- Filter a list-like table by running a predicate function on its elements in order
---
--- Parameters:
--- * list - A list-like table, i.e. one whose keys are sequential integers starting from 1
--- * fn - A function that accepts a single parameter (a table element) and returns a boolean
--- value: true if the parameter should be kept, false if it should be discarded
---
--- Returns:
--- * A list-like table containing the elements of the table for which fn(element) returns true
---
--- Notes:
--- * If `list` has "holes", all elements after the first hole will be lost, as the table is iterated over with `ipairs`;
--- use `hs.fnutils.map()` if your table has holes
function fnutils.ifilter(t, fn)
local nt = {}
for k, v in ipairs(t) do if fn(v) then nt[#nt+1] = v end end
return nt
end
--- hs.fnutils.filter(table, fn) -> table
--- Function
--- Filter a table by running a predicate function on its elements (in arbitrary order)
---
--- Parameters:
--- * table - A table; it can have both a list (or array) part and a hash (or dict) part
--- * fn - A function that accepts a single parameter (a table element) and returns a boolean
--- value: true if the parameter should be kept, false if it should be discarded
---
--- Returns:
--- * A table containing the elements of the table for which fn(element) returns true
---
--- Notes:
--- * If `table` is a pure array table (list-like) without "holes", use `hs.fnutils.ifilter()` if you need guaranteed in-order
--- processing and for better performance.
function fnutils.filter(t, fn)
local nt = {}
for k, v in pairs(t) do
if fn(v) then nt[isListIndex(k) and (#nt+1) or k] = v end -- meh etc.
end
return nt
end
--- hs.fnutils.copy(table) -> table
--- Function
--- Copy a table using `pairs()`
---
--- Parameters:
--- * table - A table containing some sort of data
---
--- Returns:
--- * A new table containing the same data as the input table
function fnutils.copy(t)
local nt = {}
for k, v in pairs(t) do
nt[k] = v
end
return nt
end
--- hs.fnutils.contains(table, element) -> bool
--- Function
--- Determine if a table contains a given object
---
--- Parameters:
--- * table - A table containing some sort of data
--- * element - An object to search the table for
---
--- Returns:
--- * A boolean, true if the element could be found in the table, otherwise false
function fnutils.contains(t, el)
for k, v in pairs(t) do
if v == el then
return true
end
end
return false
end
--- hs.fnutils.indexOf(table, element) -> number or nil
--- Function
--- Determine the location in a table of a given object
---
--- Parameters:
--- * table - A table containing some sort of data
--- * element - An object to search the table for
---
--- Returns:
--- * A number containing the index of the element in the table, or nil if it could not be found
function fnutils.indexOf(t, el)
for k, v in pairs(t) do
if v == el then
return k
end
end
return nil
end
--- hs.fnutils.concat(table1, table2)
--- Function
--- Join two tables together
---
--- Parameters:
--- * table1 - A table containing some sort of data
--- * table2 - A table containing some sort of data
---
--- Returns:
--- * table1, with all of table2's elements added to the end of it
---
--- Notes:
--- * table2 cannot be a sparse table, see [http://www.luafaq.org/gotchas.html#T6.4](http://www.luafaq.org/gotchas.html#T6.4)
function fnutils.concat(t1, t2)
for i = 1, #t2 do
t1[#t1 + 1] = t2[i]
end
return t1
end
--- hs.fnutils.mapCat(table, fn) -> table
--- Function
--- Execute, across a table, a function that outputs tables, and concatenate all of those tables together
---
--- Parameters:
--- * table - A table containing some sort of data
--- * fn - A function that takes a single parameter and returns a table
---
--- Returns:
--- * A table containing the concatenated results of calling fn(element) for every element in the supplied table
function fnutils.mapCat(t, fn)
local nt = {}
for k, v in pairs(t) do
fnutils.concat(nt, fn(v))
end
return nt
end
--- hs.fnutils.reduce(table, fn) -> table
--- Function
--- Reduce a table to a single element, using a function
---
--- Parameters:
--- * table - A table containing some sort of data
--- * fn - A function that takes two parameters, which will be elements of the supplied table. It should choose one of these elements and return it
---
--- Returns:
--- * The element of the supplied table that was chosen by the iterative reducer function
---
--- Notes:
--- * table cannot be a sparse table, see [http://www.luafaq.org/gotchas.html#T6.4](http://www.luafaq.org/gotchas.html#T6.4)
--- * The first iteration of the reducer will call fn with the first and second elements of the table. The second iteration will call fn with the result of the first iteration, and the third element. This repeats until there is only one element left
function fnutils.reduce(t, fn)
local len = #t
if len == 0 then return nil end
if len == 1 then return t[1] end
local result = t[1]
for i = 2, #t do
result = fn(result, t[i])
end
return result
end
--- hs.fnutils.find(table, fn) -> element
--- Function
--- Execute a function across a table and return the first element where that function returns true
---
--- Parameters:
--- * table - A table containing some sort of data
--- * fn - A function that takes one parameter and returns a boolean value
---
--- Returns:
--- * The element of the supplied table that first caused fn to return true
function fnutils.find(t, fn)
for _, v in pairs(t) do
if fn(v) then return v end
end
return nil
end
--- hs.fnutils.sequence(...) -> fn
--- Constructor
--- Creates a function that will collect the result of a series of functions into a table
---
--- Parameters:
--- * ... - A number of functions, passed as different arguments. They should accept zero parameters, and return something
---
--- Returns:
--- * A function that, when called, will call all of the functions passed to this constructor. The output of these functions will be collected together and returned.
function fnutils.sequence(...)
local arg = table.pack(...)
return function()
local results = {}
for _, fn in ipairs(arg) do
table.insert(results, fn())
end
return results
end
end
--- hs.fnutils.partial(fn, ...) -> fn'
--- Constructor
--- Returns a new function which takes the provided arguments and pre-applies them as the initial arguments to the provided function. When the new function is later invoked with additional arguments, they are appended to the end of the initial list given and the complete list of arguments is finally passed into the provided function and its result returned.
---
--- Parameters:
--- * fn - The function which will act on all of the arguments provided now and when the result is invoked later.
--- * ... - The initial arguments to pre-apply to the resulting new function.
---
--- Returns:
--- * A function
---
--- Notes:
--- * This is best understood with an example which you can test in the Hammerspoon console:
---
--- Create the function `a` which has it's initial arguments set to `1,2,3`:
--- a = hs.fnutils.partial(function(...) return table.pack(...) end, 1, 2, 3)
---
--- Now some examples of using the new function, `a(...)`:
--- hs.inspect(a("a","b","c")) will return: { 1, 2, 3, "a", "b", "c", n = 6 }
--- hs.inspect(a(4,5,6,7)) will return: { 1, 2, 3, 4, 5, 6, 7, n = 7 }
--- hs.inspect(a(1)) will return: { 1, 2, 3, 1, n = 4 }
function fnutils.partial(fn, ...)
local args = table.pack(...)
return function(...)
for idx = args.n+1,#args do args[idx] = nil end -- clear previous values
for idx, val in ipairs(table.pack(...)) do
args[args.n + idx] = val
end
return fn(table.unpack(args))
end
end
--- hs.fnutils.cycle(table) -> fn()
--- Constructor
--- Creates a function that repeatedly iterates a table
---
--- Parameters:
--- * table - A table containing some sort of data
---
--- Returns:
--- * A function that, when called repeatedly, will return all of the elements of the supplied table, repeating indefinitely
---
--- Notes:
--- * table cannot be a sparse table, see [http://www.luafaq.org/gotchas.html#T6.4](http://www.luafaq.org/gotchas.html#T6.4)
--- * An example usage:
--- ```lua
--- f = cycle({4, 5, 6})
--- {f(), f(), f(), f(), f(), f(), f()} == {4, 5, 6, 4, 5, 6, 4}
--- ```
function fnutils.cycle(t)
local i = 1
return function()
local x = t[i]
i = i % #t + 1
return x
end
end
--- hs.fnutils.every(table, fn) -> bool
--- Function
--- Returns true if the application of fn on every entry in table is true.
---
--- Parameters:
--- * table - A table containing some sort of data
--- * fn - A function that accepts a single parameter and returns a "true" value (any value except the boolean `false` or nil) if the parameter was accepted, or a "false" value (the boolean false or nil) if the parameter was rejected.
---
--- Returns:
--- * True if the application of fn on every element of the table is true
--- * False if the function returns `false` for any element of the table. Note that testing stops when the first false return is detected.
function fnutils.every(table, fn)
for k, v in pairs(table) do
if not fn(v, k) then return false end
end
return true
end
--- hs.fnutils.some(table, fn) -> bool
--- Function
--- Returns true if the application of fn on entries in table are true for at least one of the members.
---
--- Parameters:
--- * table - A table containing some sort of data
--- * fn - A function that accepts a single parameter and returns a "true" value (any value except the boolean `false` or nil) if the parameter was accepted, or a "false" value (the boolean false or nil) if the parameter was rejected.
---
--- Returns:
--- * True if the application of fn on any element of the table is true. Note that testing stops when the first true return is detected.
--- * False if the function returns `false` for all elements of the table.
function fnutils.some(table, fn)
local function is_invalid(v, k)
return not fn(v, k)
end
return not fnutils.every(table, is_invalid)
end
--- hs.fnutils.sortByKeys(table[ , function]) -> function
--- Constructor
--- Iterator for retrieving elements from a table of key-value pairs in the order of the keys.
---
--- Parameters:
--- * table - the table of key-value pairs to be iterated through
--- * fn - an optional function which will be passed to `table.sort` to determine how the keys are sorted. If it is not present, then keys will be sorted numerically/alphabetically.
---
--- Returns:
--- * function to be used as an iterator
---
--- Notes:
--- * Similar to Perl's `sort(keys %hash)`
--- * Iterators are used in looping constructs like `for`:
--- * `for i,v in hs.fnutils.sortByKeys(t[, f]) do ... end`
--- * A sort function should accept two arguments and return true if the first argument should appear before the second, or false otherwise.
--- * e.g. `function(m,n) return not (m < n) end` would result in reverse alphabetic order.
--- * See _Programming_In_Lua,_3rd_ed_, page 52 for a more complete discussion.
--- * The default sort is to compare keys directly, if they are of the same type, or as their tostring() versions, if the key types differ:
--- * function(m,n) if type(m) ~= type(n) then return tostring(m) < tostring(n) else return m < n end
fnutils.sortByKeys = function(t, f)
-- a default, simple comparison that treats keys as strings only if their types differ
f = f or function(m,n) if type(m) ~= type(n) then return tostring(m) < tostring(n) else return m < n end end
if t then
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
else
return function() return nil end
end
end
--- hs.fnutils.sortByKeyValues(table[ , function]) -> function
--- Constructor
--- Iterator for retrieving elements from a table of key-value pairs in the order of the values.
---
--- Parameters:
--- * table - the table of key-value pairs to be iterated through
--- * fn - an optional function which will be passed to `table.sort` to determine how the values are sorted. If it is not present, then values will be sorted numerically/alphabetically.
---
--- Returns:
--- * function to be used as an iterator
---
--- Notes:
--- * Similar to Perl's `sort { $hash{$a} <=> $hash{$b} } keys %hash`
--- * Iterators are used in looping constructs like `for`:
--- * `for i,v in hs.fnutils.sortByKeyValues(t[, f]) do ... end`
--- * A sort function should accept two arguments and return true if the first argument should appear before the second, or false otherwise.
--- * e.g. `function(m,n) return not (m < n) end` would result in reverse alphabetic order.
--- * See _Programming_In_Lua,_3rd_ed_, page 52 for a more complete discussion.
--- * The default sort is to compare values directly, if they are of the same type, or as their tostring() versions, if the value types differ:
--- * function(m,n) if type(m) ~= type(n) then return tostring(m) < tostring(n) else return m < n end
fnutils.sortByKeyValues = function(t, f)
-- a default, simple comparison that treats keys as strings only if their types differ
f = f or function(m,n) if type(m) ~= type(n) then return tostring(m) < tostring(n) else return m < n end end
if t then
local a = {}
for n in pairs(t) do table.insert(a, {n, t[n]}) end
table.sort(a, function(m,n) return f(m[2], n[2]) end)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i][1], a[i][2]
end
end
return iter
else
return function() return nil end
end
end
--- hs.fnutils.split(sString, sSeparator [, nMax] [, bPlain]) -> { array }
--- Function
--- Convert string to an array of strings, breaking at the specified separator.
---
--- Parameters:
--- * sString -- the string to split into substrings
--- * sSeparator -- the separator. If `bPlain` is false or not provided, this is treated as a Lua pattern.
--- * nMax -- optional parameter specifying the maximum number (or all if `nMax` is nil) of substrings to split from `sString`.
--- * bPlain -- optional boolean parameter, defaulting to false, specifying if `sSeparator` should be treated as plain text (true) or a Lua pattern (false)
---
--- Returns:
--- * An array of substrings. The last element of the array will be the remaining portion of `sString` that remains after `nMax` (or all, if `nMax` is not provided or is nil) substrings have been identified.
---
--- Notes:
--- * Similar to "split" in Perl or "string.split" in Python.
--- * Optional parameters `nMax` and `bPlain` are identified by their type -- if parameter 3 or 4 is a number or nil, it will be considered a value for `nMax`; if parameter 3 or 4 is a boolean value, it will be considered a value for `bPlain`.
--- * Lua patterns are more flexible for pattern matching, but can also be slower if the split point is simple. See §6.4.1 of the _Lua_Reference_Manual_ at http://www.lua.org/manual/5.3/manual.html#6.4.1 for more information on Lua patterns.
function fnutils.split(sString, sSeparator, nMax, bPlain)
if type(nMax) == "boolean" then
nMax, bPlain = bPlain, nMax
end
sSeparator = sSeparator or ""
if type(sString) ~= "string" then
error("sString parameter to hs.fnutils.split must be a string", 2) end
if type(sSeparator) ~= "string" then
error("sSeparator parameter to hs.fnutils.split must be a string", 2) end
if type(nMax) ~= "number" and type(nMax) ~= "nil" then
error("nMax parameter to hs.fnutils.split must be a number, if it is provided", 2) end
if type(bPlain) ~= "boolean" and type(bPlain) ~= "nil" then
error("bPlain parameter to hs.fnutils.split must be a boolean, if it is provided", 2) end
if sSeparator == "" or maxSubStrings == 0 then return { sString } end -- degenerate cases
local aRecord = {}
if sString:len() > 0 then
nMax = nMax or -1
local nField, nStart = 1, 1
local nFirst,nLast = sString:find(sSeparator, nStart, bPlain)
while nFirst and nMax ~= 0 do
aRecord[nField] = sString:sub(nStart, nFirst-1)
nField = nField+1
nStart = nLast+1
nFirst,nLast = sString:find(sSeparator, nStart, bPlain)
nMax = nMax-1
end
aRecord[nField] = sString:sub(nStart)
end
return aRecord
end
return fnutils
| mit |
vlc-mirror/vlc-2.1 | share/lua/meta/art/03_lastfm.lua | 3 | 1854 | --[[
Gets an artwork from last.fm
$Id$
Copyright © 2010 the VideoLAN team
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.
--]]
-- Return the artwork
function fetch_art()
if vlc.item == nil then return nil end
local meta = vlc.item:metas()
if meta["Listing Type"] == "radio"
or meta["Listing Type"] == "tv"
then return nil end
if meta["artist"] and meta["album"] then
title = meta["artist"].."/"..meta["album"]
else
return nil
end
-- remove -.* from string
title = string.gsub( title, " ?%-.*", "" )
-- remove (info..) from string
title = string.gsub( title, "%(.*%)", "" )
-- remove CD2 etc from string
title = string.gsub( title, "CD%d+", "" )
-- remove Disc \w+ from string
title = string.gsub( title, "Disc %w+", "" )
fd = vlc.stream( "http://www.last.fm/music/" .. title )
if not fd then return nil end
page = fd:read( 65653 )
fd = nil
_, _, arturl = string.find( page, "<meta property=\"og:image\" content=\"([^\"]+)\" />" )
-- Don't use default album-art (not found one)
if not arturl or string.find( arturl, "default_album_mega.png") then
return nil
end
return arturl
end
| lgpl-2.1 |
MidflightDigital/ddrsn3-theme | DDR SN3/BGAnimations/ScreenSelectMusic decorations/SNBPMDisplay.lua | 1 | 3520 | local LoadingScreen = Var "LoadingScreen"
--smcmd is "screen metrics command", gmcmd is "general metrics command"
--these make it require a little less typing to run useful BPMDisplay related commands
local smcmd, gmcmd
do
smcmd = function(s, name)
return (THEME:GetMetric(LoadingScreen, name))(s)
end
gmcmd = function(s, name)
return (THEME:GetMetric("BPMDisplay", name))(s)
end
end
local counter = 0
local targetDelta = 1/60
local timer = GetUpdateTimer(targetDelta)
--displays 3 digit numbers 000, 111, 222... 999, 000... every 1/60 of a second (about)
local function RandomBPM(self, _)
local s = self:GetChild"BPMDisplay"
if not timer() then return end
s:settext(string.rep(tostring(counter),3))
counter = (counter+1)%10
end
local function textBPM(dispBPM)
return string.format("%03d", math.round(dispBPM))
end
local goingUp = true
local startTime = GetTimeSinceStart()
local dispBPMs = {0,0}
--how long (in seconds) it should take to change from one BPM to the other
local length = 1
--how long to wait between reaching the target BPM and switching modes (in seconds)
local pause = 1
local function VariedBPM(self, _)
local s = self:GetChild"BPMDisplay"
local curTime = GetTimeSinceStart()
local base = dispBPMs[goingUp and 1 or 2]
local target = dispBPMs[goingUp and 2 or 1]
--clamp doesn't sort its operands so we have to make sure they are correct
local bpm = clamp(base+(target-base)*((curTime-startTime)/length),
goingUp and base or target,
goingUp and target or base)
--aux is used to store the current BPM in non-truncated numeric form for use by the BPM meter
s:aux(bpm):settext(textBPM(bpm))
if curTime >= startTime + length + pause then
goingUp = not goingUp
startTime = curTime
end
end
return Def.ActorFrame{
--only ActorFrames and classes based on ActorFrame have update functions, which we need
Name="SNBPMDisplayHost",
Def.BitmapText{
Font="BPMDisplay bpm",
Name="BPMDisplay",
InitCommand=function(s) s:aux(0):halign(0):settext "000":x(THEME:GetMetric(LoadingScreen,"BPMDisplayX"))
:y(THEME:GetMetric(LoadingScreen,"BPMDisplayY")); return gmcmd(s, "SetNoBpmCommand") end,
OnCommand=function(s) return smcmd(s, "BPMDisplayOnCommand") end,
OffCommand=function(s) return smcmd(s, "BPMDisplayOffCommand") end,
CurrentSongChangedMessageCommand = function(s, _)
local song = GAMESTATE:GetCurrentSong()
if song then
if song:IsDisplayBpmRandom() or song:IsDisplayBpmSecret() then
gmcmd(s, song:IsDisplayBpmRandom() and "SetRandomCommand" or "SetExtraCommand")
--I do not believe that it is necessary to reset this counter every time.
--It may even be incorrect.
counter = 0
timer = GetUpdateTimer(targetDelta)
--an aux value of -1 is intended as a special value but it is not used.
s:aux(-1):settext "999":GetParent():SetUpdateFunction(RandomBPM)
else
--if the display BPM is random, GetDisplayBpms returns nonsense, so only do it here.
dispBPMs = song:GetDisplayBpms()
s:aux(dispBPMs[1]):settext(textBPM(dispBPMs[1]))
if song:IsDisplayBpmConstant() then
gmcmd(s, "SetNormalCommand")
s:GetParent():SetUpdateFunction(nil)
else
gmcmd(s, "SetChangeCommand")
--These actually do need to be reset every time.
goingUp = true
startTime = GetTimeSinceStart()
s:GetParent():SetUpdateFunction(VariedBPM)
end
end
else
gmcmd(s, "SetNoBpmCommand")
s:aux(0):settext "000":GetParent():SetUpdateFunction(nil)
end
end
}
} | mit |
kuffz/ntopng-bk | scripts/lua/iface_ndpi_stats.lua | 2 | 3262 | --
-- (C) 2013-15 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
sendHTTPHeader('text/html; charset=iso-8859-1')
interface.select(ifname)
host_info = url2hostinfo(_GET)
if(_GET["breed"] == "true") then
show_breed = true
else
show_breed = false
end
if(_GET["mode"] == "sinceStartup") then
stats = interface.getStats()
elseif(_GET["mode"] == "count") then
stats = interface.getNdpiFlowsCount()
elseif(host_info["host"] == nil) then
stats = interface.getNdpiStats()
else
stats = interface.getHostInfo(host_info["host"], host_info["vlan"])
end
print "[\n"
if(stats ~= nil) then
tot = 0
_ifstats = {}
if(_GET["mode"] == "count") then
tot = 0
for k, v in pairs(stats) do
tot = tot + v
stats[k] = tonumber(v)
-- print(k.."="..v.."\n,")
end
threshold = (tot * 3) / 100
num = 0
for k, v in pairsByValues(stats, rev) do
if((num < 5) and (v > threshold)) then
if(num > 0) then print(", ") end
print("\t { \"label\": \"" .. k .."\", \"value\": ".. v .." }")
num = num + 1
tot = tot - v
else
break
end
end
if(tot > 0) then
if(num > 0) then print(", ") end
print("\t { \"label\": \"Other\", \"value\": ".. tot .." }")
end
print "]\n"
return
end
if(show_breed) then
__ifstats = {}
for key, value in pairs(stats["ndpi"]) do
b = stats["ndpi"][key]["breed"]
traffic = stats["ndpi"][key]["bytes.sent"] + stats["ndpi"][key]["bytes.rcvd"]
if(__ifstats[b] == nil) then
__ifstats[b] = traffic
else
__ifstats[b] = __ifstats[b] + traffic
end
end
for key, value in pairs(__ifstats) do
--print(key.."="..value.."<p>\n")
_ifstats[value] = key
tot = tot + value
end
else
for key, value in pairs(stats["ndpi"]) do
-- print("->"..key.."\n")
traffic = stats["ndpi"][key]["bytes.sent"] + stats["ndpi"][key]["bytes.rcvd"]
if(show_breed) then
_ifstats[traffic] = stats["ndpi"][key]["breed"]
else
_ifstats[traffic] = key
end
--print(key.."="..traffic)
tot = tot + traffic
end
end
-- Print up to this number of entries
max_num_entries = 5
-- Print entries whose value >= 3% of the total
threshold = (tot * 3) / 100
num = 0
accumulate = 0
for key, value in pairsByKeys(_ifstats, rev) do
if(key < threshold) then
break
end
if(num > 0) then
print ",\n"
end
if(host_info["host"] == nil) then
print("\t { \"label\": \"" .. value .."\", \"url\": \""..ntop.getHttpPrefix().."/lua/flows_stats.lua?application="..value.."\", \"value\": ".. key .." }")
else
print("\t { \"label\": \"" .. value .."\", \"value\": ".. key .." }")
end
accumulate = accumulate + key
num = num + 1
if(num == max_num_entries) then
break
end
end
if(tot == 0) then
tot = 1
end
-- In case there is some leftover do print it as "Other"
if(accumulate < tot) then
if(num > 0) then
print (",\n")
end
print("\t { \"label\": \"Other\", \"value\": ".. (tot-accumulate) .." }")
end
end
print "\n]"
| gpl-3.0 |
MaxyTibia/forgottenserver | data/npc/lib/npc.lua | 21 | 3182 | -- Including the Advanced NPC System
dofile('data/npc/lib/npcsystem/npcsystem.lua')
function msgcontains(message, keyword)
local message, keyword = message:lower(), keyword:lower()
if message == keyword then
return true
end
return message:find(keyword) and not message:find('(%w+)' .. keyword)
end
function doNpcSellItem(cid, itemid, amount, subType, ignoreCap, inBackpacks, backpack)
local amount = amount or 1
local subType = subType or 0
local item = 0
if isItemStackable(itemid) then
if inBackpacks then
stuff = doCreateItemEx(backpack, 1)
item = doAddContainerItem(stuff, itemid, math.min(100, amount))
else
stuff = doCreateItemEx(itemid, math.min(100, amount))
end
return doPlayerAddItemEx(cid, stuff, ignoreCap) ~= RETURNVALUE_NOERROR and 0 or amount, 0
end
local a = 0
if inBackpacks then
local container, b = doCreateItemEx(backpack, 1), 1
for i = 1, amount do
local item = doAddContainerItem(container, itemid, subType)
if isInArray({(getContainerCapById(backpack) * b), amount}, i) then
if doPlayerAddItemEx(cid, container, ignoreCap) ~= RETURNVALUE_NOERROR then
b = b - 1
break
end
a = i
if amount > i then
container = doCreateItemEx(backpack, 1)
b = b + 1
end
end
end
return a, b
end
for i = 1, amount do -- normal method for non-stackable items
local item = doCreateItemEx(itemid, subType)
if doPlayerAddItemEx(cid, item, ignoreCap) ~= RETURNVALUE_NOERROR then
break
end
a = i
end
return a, 0
end
local func = function(cid, text, type, e, pcid)
if isPlayer(pcid) then
doCreatureSay(cid, text, type, false, pcid, getCreaturePosition(cid))
e.done = TRUE
end
end
function doCreatureSayWithDelay(cid, text, type, delay, e, pcid)
if isPlayer(pcid) then
e.done = FALSE
e.event = addEvent(func, delay < 1 and 1000 or delay, cid, text, type, e, pcid)
end
end
function doPlayerTakeItem(cid, itemid, count)
if getPlayerItemCount(cid,itemid) < count then
return false
end
while count > 0 do
local tempcount = 0
if isItemStackable(itemid) then
tempcount = math.min (100, count)
else
tempcount = 1
end
local ret = doPlayerRemoveItem(cid, itemid, tempcount)
if ret ~= false then
count = count - tempcount
else
return false
end
end
if count ~= 0 then
return false
end
return true
end
function doPlayerSellItem(cid, itemid, count, cost)
if doPlayerTakeItem(cid, itemid, count) == true then
if not doPlayerAddMoney(cid, cost) then
error('Could not add money to ' .. getPlayerName(cid) .. '(' .. cost .. 'gp)')
end
return true
end
return false
end
function doPlayerBuyItemContainer(cid, containerid, itemid, count, cost, charges)
if not doPlayerRemoveMoney(cid, cost) then
return false
end
for i = 1, count do
local container = doCreateItemEx(containerid, 1)
for x = 1, getContainerCapById(containerid) do
doAddContainerItem(container, itemid, charges)
end
if doPlayerAddItemEx(cid, container, true) ~= RETURNVALUE_NOERROR then
return false
end
end
return true
end
function getCount(string)
local b, e = string:find("%d+")
return b and e and tonumber(string:sub(b, e)) or -1
end
| gpl-2.0 |
MaxyTibia/forgottenserver | data/talkactions/scripts/looktype.lua | 27 | 1088 | function onSay(player, words, param)
if not player:getGroup():getAccess() then
return true
end
local lookType = tonumber(param)
if lookType >= 0 and lookType ~= 1 and lookType ~= 135 and lookType ~= 411 and lookType ~= 415 and lookType ~= 424 and (lookType <= 160 or lookType >= 192) and lookType ~= 439 and lookType ~= 440 and lookType ~= 468 and lookType ~= 469 and (lookType < 474 or lookType > 485) and lookType ~= 501 and lookType ~= 518 and lookType ~= 519 and lookType ~= 520 and lookType ~= 524 and lookType ~= 525 and lookType ~= 536 and lookType ~= 543 and lookType ~= 549 and lookType ~= 576 and lookType ~= 581 and lookType ~= 582 and lookType ~= 597 and lookType ~= 616 and lookType ~= 623 and lookType ~= 625 and (lookType <= 637 or lookType >= 644) and (lookType <= 644 or lookType >= 647) and (lookType <= 651 or lookType >= 664) and lookType <= 699 then
local playerOutfit = player:getOutfit()
playerOutfit.lookType = lookType
player:setOutfit(playerOutfit)
else
player:sendCancelMessage("A look type with that id does not exist.")
end
return false
end
| gpl-2.0 |
adib1380/iranian_bot | plugins/modra.lua | 15 | 11324 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin!"
end
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.'
end
local function set_description(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = deskripsi
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..deskripsi
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 set_rules(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
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 = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules
return rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
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
-- show group settings
local function show_group_settings(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local settings = data[tostring(msg.to.id)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
function run(msg, matches)
--vardump(msg)
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
if not is_chat_msg(msg) then
return "This is not a group chat."
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if msg.media and is_chat_msg(msg) and is_momod(msg) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'setabout' and matches[2] then
deskripsi = matches[2]
return set_description(msg, data)
end
if matches[1] == 'about' then
return get_description(msg, data)
end
if matches[1] == 'setrules' then
rules = matches[2]
return set_rules(msg, data)
end
if matches[1] == 'rules' then
return get_rules(msg, data)
end
if matches[1] == 'group' and matches[2] == 'lock' then --group lock *
if matches[3] == 'name' then
return lock_group_name(msg, data)
end
if matches[3] == 'member' then
return lock_group_member(msg, data)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'unlock' then --group unlock *
if matches[3] == 'name' then
return unlock_group_name(msg, data)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'settings' then
return show_group_settings(msg, data)
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
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)
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] == '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' then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'no' then
return nil
end
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
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
chat_set_photo (receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
end
end
return {
description = "Plugin to manage group chat.",
usage = {
"!creategroup <group_name> : Create a new group (admin only)",
"!setabout <description> : Set group description",
"!about : Read group description",
"!setrules <rules> : Set group rules",
"!rules : Read group rules",
"!setname <new_name> : Set group name",
"!setphoto : Set group photo",
"!group <lock|unlock> name : Lock/unlock group name",
"!group <lock|unlock> photo : Lock/unlock group photo",
"!group <lock|unlock> member : Lock/unlock group member",
"!group settings : Show group settings"
},
patterns = {
"^!(creategroup) (.*)$",
"^!(setabout) (.*)$",
"^!(about)$",
"^!(setrules) (.*)$",
"^!(rules)$",
"^!(setname) (.*)$",
"^!(setphoto)$",
"^!(group) (lock) (.*)$",
"^!(group) (unlock) (.*)$",
"^!(group) (settings)$",
"^!!tgservice (.+)$",
"%[(photo)%]",
},
run = run,
}
end
| gpl-2.0 |
NoriSilverrage/Revamped-Factorio-Machines | RFM-tweaks_1.1.4/prototypes/nuclear.lua | 1 | 2207 | data.raw.item["steam-turbine"].stack_size = 20
data:extend({
{
type = "item",
name = "steam-turbine-2",
icon = "__Nucular__/graphics/icons/steam-turbine.png",
flags = {"goes-to-quickbar"},
subgroup = "nuclear-structure",
order = "b-a",
place_result = "steam-turbine-2",
enabled = false,
stack_size = 20
},
{
type = "item",
name = "steam-turbine-3",
icon = "__Nucular__/graphics/icons/steam-turbine.png",
flags = {"goes-to-quickbar"},
subgroup = "nuclear-structure",
order = "b-b",
place_result = "steam-turbine-3",
enabled = false,
stack_size = 20
},
{
type = "recipe",
name = "steam-turbine-2",
energy_required = 5,
enabled = "false",
ingredients =
{
{"steam-turbine", 1},
{"steel-pipe", 20},
{"electronic-circuit", 20},
{"steel-plate", 50}
},
result = "steam-turbine-2"
},
{
type = "recipe",
name = "steam-turbine-3",
energy_required = 5,
enabled = "false",
ingredients =
{
{"steam-turbine-2", 1},
{"plastic-pipe", 20},
{"advanced-circuit", 20},
{"steel-plate", 60}
},
result = "steam-turbine-3"
},
})
-- Steam Turbine Mk2 to Mk4 **************************************************************************
local turbine2 = table.deepcopy(data.raw["generator"]["steam-turbine"])
turbine2.name = "steam-turbine-2"
turbine2.effectivity = 2
turbine2.fluid_usage_per_tick = 0.75
turbine2.max_health = 400
turbine2.minable.result = "steam-turbine-2"
turbine2.fast_replaceable_group = "steam-engine"
data:extend({ turbine2 })
-- Mk 3
local turbine3 = table.deepcopy(data.raw["generator"]["steam-turbine"])
turbine3.name = "steam-turbine-3"
turbine3.effectivity = 4
turbine3.fluid_usage_per_tick = 0.5
turbine3.max_health = 500
turbine3.minable.result = "steam-turbine-3"
turbine3.fast_replaceable_group = "steam-engine"
data:extend({ turbine3 })
table.insert(data.raw["technology"]["steam-engine-generator-1"].effects,{type="unlock-recipe",recipe="steam-turbine-2"})
table.insert(data.raw["technology"]["steam-engine-generator-2"].effects,{type="unlock-recipe",recipe="steam-turbine-3"})
| mit |
nabilbendafi/haka | modules/protocol/tcp/tcp_connection.lua | 2 | 18812 | -- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
local class = require("class")
local check = require("check")
local ipv4 = require("protocol/ipv4")
local tcp = require("protocol/tcp")
local module = {}
local log = haka.log_section("tcp")
local tcp_connection_dissector = haka.dissector.new{
type = haka.helper.PacketDissector,
name = 'tcp_connection'
}
tcp_connection_dissector.cnx_table = ipv4.cnx_table()
tcp_connection_dissector:register_event('new_connection')
tcp_connection_dissector:register_event('receive_packet')
tcp_connection_dissector:register_streamed_event('receive_data')
tcp_connection_dissector:register_event('end_connection')
tcp_connection_dissector.policies.no_connection_found = haka.policy.new("no connection found for tcp packet")
tcp_connection_dissector.policies.unexpected_packet = haka.policy.new("unexpected tcp packet")
tcp_connection_dissector.policies.invalid_handshake = haka.policy.new("invalid tcp handshake")
tcp_connection_dissector.policies.new_connection = haka.policy.new("new connection")
haka.policy {
on = tcp_connection_dissector.policies.no_connection_found,
name = "default action",
action = {
haka.policy.alert{ severity = 'low' },
haka.policy.drop
}
}
local function tcp_get_key(pkt)
return pkt.src, pkt.dst, pkt.srcport, pkt.dstport
end
function tcp_connection_dissector:receive(pkt)
local connection, direction, dropped = tcp_connection_dissector.cnx_table:get(tcp_get_key(pkt))
if not connection then
if pkt.flags.syn and not pkt.flags.ack then
connection = tcp_connection_dissector.cnx_table:create(tcp_get_key(pkt))
connection.data = haka.context.newscope()
local self = tcp_connection_dissector:new(connection, pkt)
local ret, err = xpcall(function ()
haka.context:exec(connection.data, function ()
self:trigger('new_connection', pkt)
class.classof(self).policies.next_dissector:apply{
values = self:install_criterion(),
ctx = self,
}
self:activate_next_dissector()
end)
end, debug.format_error)
if err then
log.error("%s", err)
pkt:drop()
self:error()
haka.abort()
end
if not pkt:can_continue() then
self:drop()
haka.abort()
end
if not self._stream then
pkt:drop()
haka.abort()
end
connection.data:createnamespace('tcp_connection', self)
else
if not dropped then
tcp_connection_dissector.policies.no_connection_found:apply{
ctx = pkt,
values = {
srcip = pkt.src,
srcport = pkt.srcport,
dstip = pkt.dst,
dstport = pkt.dstport
},
desc = {
sources = {
haka.alert.address(pkt.src),
haka.alert.service(string.format("tcp/%d", pkt.srcport))
},
targets = {
haka.alert.address(pkt.dst),
haka.alert.service(string.format("tcp/%d", pkt.dstport))
}
}
}
if not pkt:can_continue() then
-- packet was dropped by policy
return
else
pkt:send()
end
else
return pkt:drop()
end
end
end
local dissector = connection.data:namespace('tcp_connection')
local ret, err = xpcall(function ()
haka.context:exec(connection.data, function ()
return dissector:emit(pkt, direction)
end)
if dissector._restart then
return tcp_connection_dissector:receive(pkt)
end
end, debug.format_error)
if not ret then
if err then
log.error("%s", err)
dissector:error()
end
end
end
function tcp_connection_dissector.method:install_criterion()
return { port = self.dstport }
end
haka.policy {
on = tcp_connection_dissector.policies.unexpected_packet,
name = "default action",
action = {
haka.policy.alert(),
haka.policy.drop
}
}
haka.policy {
on = tcp_connection_dissector.policies.invalid_handshake,
name = "default action",
action = {
haka.policy.alert(),
haka.policy.drop
}
}
tcp_connection_dissector.state_machine = haka.state_machine.new("tcp", function ()
state_type{
events = { 'input', 'output', 'reset' },
update = function (self, state_machine, direction, pkt)
if pkt.flags.rst then
state_machine.owner:_sendpkt(pkt, direction)
state_machine:trigger('reset', pkt)
return
end
if direction == state_machine.owner.input then
state_machine:trigger('input', pkt)
else
assert(direction == state_machine.owner.output)
state_machine:trigger('output', pkt)
end
end
}
reset = state()
syn = state()
syn_sent = state()
syn_received = state()
established = state()
fin_wait_1 = state()
fin_wait_2 = state()
closing = state()
timed_wait = state()
local function unexpected_packet(self, pkt)
tcp_connection_dissector.policies.unexpected_packet:apply{
ctx = pkt,
desc = {
sources = {
haka.alert.address(pkt.src),
haka.alert.service(string.format("tcp/%d", pkt.srcport))
},
targets = {
haka.alert.address(pkt.dst),
haka.alert.service(string.format("tcp/%d", pkt.dstport))
}
}
}
end
local function invalid_handshake(type)
return function (self, pkt)
tcp_connection_dissector.policies.unexpected_packet:apply{
ctx = pkt,
desc = {
description = string.format("invalid tcp %s handshake", type),
sources = {
haka.alert.address(pkt.src),
haka.alert.service(string.format("tcp/%d", pkt.srcport))
},
targets = {
haka.alert.address(pkt.dst),
haka.alert.service(string.format("tcp/%d", pkt.dstport))
}
}
}
end
end
local function send(dir)
return function(self, pkt)
self._stream[self[dir]]:init(pkt.seq+1)
pkt:send()
end
end
any:on{
events = { events.fail, events.reset },
jump = reset,
}
any:on{
events = { events.input, events.output },
execute = unexpected_packet,
jump = fail,
}
any:on{
event = events.finish,
execute = function (self)
self:trigger('end_connection')
self:_close()
end,
}
reset:on{
event = events.enter,
execute = function (self)
self:trigger('end_connection')
self:clearstream()
self._parent:drop()
end,
}
reset:on{
event = events.timeout(60),
jump = finish,
}
reset:on{
event = events.finish,
execute = function (self)
self:_close()
end,
}
syn:on{
event = events.init,
execute = function (self)
self.input = 'up'
self.output = 'down'
end,
}
syn:on{
event = events.input,
when = function (self, pkt) return pkt.flags.syn end,
execute = send('input'),
jump = syn_sent,
}
syn:on{
event = events.input,
execute = invalid_handshake('establishement'),
jump = fail,
}
syn_sent:on{
event = events.output,
when = function (self, pkt) return pkt.flags.syn and pkt.flags.ack end,
execute = send('output'),
jump = syn_received,
}
syn_sent:on{
event = events.input,
when = function (self, pkt) return pkt.flags.syn end,
execute = function (self, pkt)
pkt:send()
end,
}
syn_sent:on{
events = { events.output, events.input },
execute = invalid_handshake('establishement'),
jump = fail,
}
local function push(dir, finish)
return function (self, pkt)
self:push(pkt, self[dir], finish)
end
end
syn_received:on{
event = events.input,
when = function (self, pkt) return pkt.flags.ack end,
execute = push('input'),
jump = established,
}
syn_received:on{
event = events.input,
when = function (self, pkt) return pkt.flags.fin end,
execute = push('input'),
jump = fin_wait_1,
}
syn_received:on{
event = events.output,
when = function (self, pkt) return pkt.flags.syn and pkt.flags.ack end,
execute = push('output'),
}
syn_received:on{
events = { events.input, events.output },
execute = invalid_handshake('establishement'),
jump = fail,
}
established:on{
event = events.enter,
execute = function (self, pkt)
self._established = true
end
}
established:on{
event = events.input,
when = function (self, pkt) return pkt.flags.fin end,
execute = push('input', true),
jump = fin_wait_1,
}
established:on{
event = events.input,
execute = push('input'),
}
established:on{
event = events.output,
when = function (self, pkt) return pkt.flags.fin end,
execute = function (self, pkt)
self:push(pkt, self.output, true)
self.input, self.output = self.output, self.input
end,
jump = fin_wait_1,
}
established:on{
event = events.output,
execute = push('output'),
}
local function dofinish(self, pkt)
self:finish(self.output)
self:_sendpkt(pkt, self.output)
end
local function sendpkt(dir)
return function (self, pkt)
self:_sendpkt(pkt, self[dir])
end
end
fin_wait_1:on{
event = events.output,
when = function (self, pkt) return pkt.flags.fin and pkt.flags.ack end,
execute = dofinish,
jump = closing,
}
fin_wait_1:on{
event = events.output,
when = function (self, pkt) return pkt.flags.fin end,
execute = dofinish,
jump = timed_wait,
}
fin_wait_1:on{
event = events.output,
when = function (self, pkt) return pkt.flags.ack end,
execute = push('output', true),
jump = fin_wait_2,
}
fin_wait_1:on{
event = events.output,
execute = invalid_handshake('termination'),
jump = fail,
}
fin_wait_1:on{
event = events.input,
when = function (self, pkt) return pkt.flags.fin and pkt.flags.ack end,
execute = sendpkt('input'),
jump = closing,
}
fin_wait_1:on{
event = events.input,
execute = sendpkt('input'),
}
fin_wait_2:on{
event = events.output,
when = function (self, pkt) return pkt.flags.fin end,
execute = sendpkt('output'),
jump = timed_wait,
}
fin_wait_2:on{
event = events.output,
when = function (self, pkt) return pkt.flags.ack end,
execute = sendpkt('output'),
}
fin_wait_2:on{
event = events.input,
when = function (self, pkt) return pkt.flags.ack end,
execute = sendpkt('input'),
}
fin_wait_2:on{
events = { events.output, events.input },
execute = invalid_handshake('termination'),
jump = fail,
}
closing:on{
event = events.input,
when = function (self, pkt) return pkt.flags.ack end,
execute = sendpkt('input'),
jump = timed_wait,
}
closing:on{
event = events.input,
when = function (self, pkt) return not pkt.flags.fin end,
execute = invalid_handshake('termination'),
jump = fail,
}
closing:on{
event = events.input,
execute = sendpkt('input'),
}
closing:on{
event = events.output,
when = function (self, pkt) return not pkt.flags.ack end,
execute = invalid_handshake('termination'),
jump = fail,
}
closing:on{
event = events.output,
execute = sendpkt('output'),
}
timed_wait:on{
event = events.enter,
execute = function (self)
self:trigger('end_connection')
end,
}
timed_wait:on{
event = events.input,
when = function (self, pkt) return pkt.flags.syn end,
execute = function (self, pkt)
self:restart()
end,
jump = finish,
}
timed_wait:on{
events = { events.input, events.output },
when = function (self, pkt) return not pkt.flags.ack end,
execute = invalid_handshake('termination'),
jump = fail,
}
timed_wait:on{
event = events.input,
execute = sendpkt('input'),
}
timed_wait:on{
event = events.output,
execute = sendpkt('output'),
}
timed_wait:on{
event = events.timeout(60),
jump = finish,
}
timed_wait:on{
event = events.finish,
execute = function (self)
self:_close()
end,
}
initial(syn)
end)
tcp_connection_dissector.auto_state_machine = false
function tcp_connection_dissector.method:__init(connection, pkt)
class.super(tcp_connection_dissector).__init(self, connection)
self._stream = {}
self._restart = false
self.srcip = pkt.src
self.dstip = pkt.dst
self.srcport = pkt.srcport
self.dstport = pkt.dstport
self._stream['up'] = tcp.tcp_stream()
self._stream['down'] = tcp.tcp_stream()
self._state = tcp_connection_dissector.state_machine:instanciate(self)
end
function tcp_connection_dissector.method:clearstream()
if self._stream then
self._stream.up:clear()
self._stream.down:clear()
self._stream = nil
end
end
function tcp_connection_dissector.method:restart()
self._restart = true
end
function tcp_connection_dissector.method:emit(pkt, direction)
self._parent:update_stat(direction, pkt.len)
self:trigger('receive_packet', pkt, direction)
self._state:update(direction, pkt)
end
function tcp_connection_dissector.method:_close()
self:clearstream()
if self._parent then
self._parent:close()
self._parent = nil
end
self._state = nil
end
function tcp_connection_dissector.method:_trigger_receive(direction, stream, current)
self:trigger('receive_data', stream.stream, current, direction)
local next_dissector = self._next_dissector
if next_dissector then
return next_dissector:receive(stream.stream, current, direction)
else
return self:send(direction)
end
end
function tcp_connection_dissector.method:push(pkt, direction, finish)
local stream = self._stream[direction]
local current = stream:push(pkt)
if finish then stream.stream:finish() end
self:_trigger_receive(direction, stream, current)
end
function tcp_connection_dissector.method:finish(direction)
local stream = self._stream[direction]
stream.stream:finish()
self:_trigger_receive(direction, stream, nil)
end
function tcp_connection_dissector.method:can_continue()
return self._stream ~= nil
end
function tcp_connection_dissector.method:_sendpkt(pkt, direction)
self:send(direction)
if self._stream then
self._stream[direction]:seq(pkt)
self._stream[haka.dissector.opposite_direction(direction)]:ack(pkt)
pkt:send()
else
haka.log.warning("tcp_connection: invalid stream")
end
end
function tcp_connection_dissector.method:_send(direction)
if self._stream then
local stream = self._stream[direction]
local other_stream = self._stream[haka.dissector.opposite_direction(direction)]
local pkt = stream:pop()
while pkt do
other_stream:ack(pkt)
pkt:send()
pkt = stream:pop()
end
else
haka.log.warning("tcp_connection: invalid stream")
end
end
function tcp_connection_dissector.method:send(direction)
if not direction then
self:_send('up')
self:_send('down')
else
self:_send(direction)
end
end
function tcp_connection_dissector.method:error()
self:_close()
end
function tcp_connection_dissector.method:drop()
check.assert(self._state, "connection already dropped")
self._state:trigger('reset')
end
function tcp_connection_dissector.method:_forgereset(direction)
local tcprst = haka.dissectors.packet.create()
tcprst = haka.dissectors.ipv4.create(tcprst)
if direction == 'up' then
tcprst.src = self.srcip
tcprst.dst = self.dstip
else
tcprst.src = self.dstip
tcprst.dst = self.srcip
end
tcprst.ttl = 64
tcprst = haka.dissectors.tcp.create(tcprst)
if direction == 'up' then
tcprst.srcport = self.srcport
tcprst.dstport = self.dstport
else
tcprst.srcport = self.dstport
tcprst.dstport = self.srcport
end
tcprst.seq = self._stream[direction].lastseq
tcprst.flags.rst = true
return tcprst
end
function tcp_connection_dissector.method:reset()
check.assert(self._established, "cannot reset a non-established connection")
local rst
rst = self:_forgereset('down')
rst:send()
rst = self:_forgereset('up')
rst:send()
self:drop()
end
function tcp_connection_dissector.method:halfreset()
check.assert(self._established, "cannot reset a non-established connection")
local rst
rst = self:_forgereset('down')
rst:send()
self:drop()
end
haka.policy {
name = "tcp connection",
on = haka.dissectors.tcp.policies.next_dissector,
action = haka.dissectors.tcp_connection.install
}
haka.rule {
on = haka.dissectors.tcp_connection.events.new_connection,
eval = function (flow, pkt)
tcp_connection_dissector.policies.new_connection:apply{
ctx = flow,
values = {
srcip = pkt.src,
srcport = pkt.srcport,
dstip = pkt.dst,
dstport = pkt.dstport
},
desc = {
sources = {
haka.alert.address(pkt.src),
haka.alert.service(string.format("tcp/%d", pkt.srcport))
},
targets = {
haka.alert.address(pkt.dst),
haka.alert.service(string.format("tcp/%d", pkt.dstport))
}
}
}
end
}
--
-- Helpers
--
module.helper = {}
module.helper.TcpFlowDissector = class.class('TcpFlowDissector', haka.helper.FlowDissector)
function module.helper.TcpFlowDissector.method:__init(flow)
check.assert(class.isa(flow, tcp_connection_dissector), "invalid parent dissector, must be a tcp flow")
class.super(module.helper.TcpFlowDissector).__init(self, flow)
end
function module.helper.TcpFlowDissector.method:can_continue()
return self._parent ~= nil
end
function module.helper.TcpFlowDissector.method:drop()
if self._parent then
self._parent:drop()
self._parent = nil
end
end
function module.helper.TcpFlowDissector.method:reset()
if self._parent then
self._parent:reset()
self._parent = nil
end
end
function module.helper.TcpFlowDissector.method:receive(stream, current, direction)
return haka.dissector.pcall(self, function ()
self._parent:streamed(stream, self.receive_streamed, self, current, direction)
if self._parent then
self._parent:send(direction)
end
end)
end
function module.helper.TcpFlowDissector.method:receive_streamed(iter, direction)
assert(self._state, "no state machine defined")
while iter:wait() do
self._state:update(iter, direction)
self:continue()
end
end
--
-- Console utilities
--
module.console = {}
function module.console.list_connections(show_dropped)
local ret = {}
for _, cnx in ipairs(tcp_connection_dissector.cnx_table:all(show_dropped)) do
if cnx.data then
local tcp_data = cnx.data:namespace('tcp_connection')
table.insert(ret, {
_thread = haka.current_thread(),
_id = tcp_data.id,
id = string.format("%d-%d", haka.current_thread(), tcp_data.id),
srcip = tcp_data.srcip,
srcport = tcp_data.srcport,
dstip = tcp_data.dstip,
dstport = tcp_data.dstport,
state = tcp_data.state,
in_pkts = tcp_data.in_pkts,
in_bytes = tcp_data.in_bytes,
out_pkts = tcp_data.out_pkts,
out_bytes = tcp_data.out_bytes
})
end
end
return ret
end
function module.console.drop_connection(id)
local tcp_conn = tcp_connection_dissector.cnx_table:get_byid(id)
if not tcp_conn then
error("unknown tcp connection")
end
if tcp_conn.data then
local tcp_data = tcp_conn.data:namespace('tcp_connection')
tcp_data:drop()
end
end
function module.console.reset_connection(id)
local tcp_conn = tcp_connection_dissector.cnx_table:get_byid(id)
if not tcp_conn then
error("unknown tcp connection")
end
if tcp_conn.data then
local tcp_data = tcp_conn.data:namespace('tcp_connection')
tcp_data:reset()
end
end
return module
| mpl-2.0 |
eulerreich/nn | CosineDistance.lua | 26 | 2154 | local CosineDistance, parent = torch.class('nn.CosineDistance', 'nn.Module')
function CosineDistance:__init()
parent.__init(self)
self.gradInput = {torch.Tensor(), torch.Tensor()}
end
function CosineDistance:updateOutput(input)
local input1, input2 = input[1], input[2]
if input1:dim() == 1 then
input1 = input1:view(1,-1)
input2 = input2:view(1,-1)
end
if not self.buffer then
self.buffer = input1.new()
self.w1 = input1.new()
self.w22 = input1.new()
self.w = input1.new()
self.w32 = input1.new()
self.ones = input1.new()
end
self.buffer:cmul(input1,input2)
self.w1:sum(self.buffer,2)
local epsilon = 1e-12
self.buffer:cmul(input1,input1)
self.w22:sum(self.buffer,2):add(epsilon)
self.ones:resizeAs(self.w22):fill(1)
self.w22:cdiv(self.ones, self.w22)
self.w:resizeAs(self.w22):copy(self.w22)
self.buffer:cmul(input2,input2)
self.w32:sum(self.buffer,2):add(epsilon)
self.w32:cdiv(self.ones, self.w32)
self.w:cmul(self.w32)
self.w:sqrt()
self.output:cmul(self.w1,self.w)
self.output = self.output:select(2,1)
return self.output
end
function CosineDistance:updateGradInput(input, gradOutput)
local v1 = input[1]
local v2 = input[2]
local not_batch = false
if v1:dim() == 1 then
v1 = v1:view(1,-1)
v2 = v2:view(1,-1)
not_batch = true
end
local gw1 = self.gradInput[1]
local gw2 = self.gradInput[2]
gw1:resizeAs(v1):copy(v2)
gw2:resizeAs(v1):copy(v1)
self.w = self.w:expandAs(v1)
self.buffer:cmul(self.w1,self.w22)
self.buffer = self.buffer:expandAs(v1)
gw1:addcmul(-1,self.buffer,v1)
gw1:cmul(self.w)
self.buffer:cmul(self.w1,self.w32)
self.buffer = self.buffer:expandAs(v1)
gw2:addcmul(-1,self.buffer,v2)
gw2:cmul(self.w)
local go = gradOutput:view(-1,1):expandAs(v1)
gw1:cmul(go)
gw2:cmul(go)
if not_batch then
self.gradInput[1] = gw1:select(1,1)
self.gradInput[2] = gw2:select(1,1)
end
-- fix for torch bug
-- https://github.com/torch/torch7/issues/289
self.buffer:resize()
return self.gradInput
end
| bsd-3-clause |
LuaDist2/dromozoa-commons | dromozoa/commons/base16.lua | 3 | 3545 | -- Copyright (C) 2015 Tomoyuki Fujimori <moyu@dromozoa.com>
--
-- This file is part of dromozoa-commons.
--
-- dromozoa-commons 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.
--
-- dromozoa-commons 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 dromozoa-commons. If not, see <http://www.gnu.org/licenses/>.
local sequence_writer = require "dromozoa.commons.sequence_writer"
local translate_range = require "dromozoa.commons.translate_range"
local encoder_upper = {}
local encoder_lower = {}
local decoder = {}
local n = ("0"):byte()
for i = 0, 9 do
local byte = i + n
local char = string.char(byte)
encoder_upper[i] = char
encoder_lower[i] = char
decoder[byte] = i
end
local n = ("A"):byte() - 10
for i = 10, 15 do
local byte = i + n
local char = string.char(byte)
encoder_upper[i] = char
decoder[byte] = i
end
local n = ("a"):byte() - 10
for i = 10, 15 do
local byte = i + n
local char = string.char(byte)
encoder_lower[i] = char
decoder[byte] = i
end
local function encode_impl(encoder, out, v)
local b = v % 16
local a = (v - b) / 16
out:write(encoder[a], encoder[b])
end
local function encode(encoder, out, s, min, max)
for i = min + 3, max, 4 do
local p = i - 3
local a, b, c, d = s:byte(p, i)
encode_impl(encoder, out, a)
encode_impl(encoder, out, b)
encode_impl(encoder, out, c)
encode_impl(encoder, out, d)
end
local i = max + 1
local p = i - (i - min) % 4
if p < i then
local a, b, c = s:byte(p, max)
if c then
encode_impl(encoder, out, a)
encode_impl(encoder, out, b)
encode_impl(encoder, out, c)
elseif b then
encode_impl(encoder, out, a)
encode_impl(encoder, out, b)
else
encode_impl(encoder, out, a)
end
end
return out
end
local function decode(out, s, min, max)
local n = max - min + 1
if n == 0 then
return out
elseif n % 2 ~= 0 then
return nil, "length not divisible by 2"
end
for i = min + 3, max, 4 do
local p = i - 3
if s:find("^%x%x%x%x", p) == nil then
return nil, "decode error at position " .. p
end
local a, b, c, d = s:byte(p, i)
out:write(string.char(decoder[a] * 16 + decoder[b], decoder[c] * 16 + decoder[d]))
end
if n % 4 == 2 then
local p = max - 1
if s:find("^%x%x", p) == nil then
return nil, "decode error at position " .. p
end
local a, b = s:byte(p, max)
out:write(string.char(decoder[a] * 16 + decoder[b]))
end
return out
end
local class = {}
function class.encode_upper(s, i, j)
local s = tostring(s)
return encode(encoder_upper, sequence_writer(), s, translate_range(#s, i, j)):concat()
end
function class.encode_lower(s, i, j)
local s = tostring(s)
return encode(encoder_lower, sequence_writer(), s, translate_range(#s, i, j)):concat()
end
function class.decode(s, i, j)
local s = tostring(s)
local result, message = decode(sequence_writer(), s, translate_range(#s, i, j))
if result == nil then
return nil, message
else
return result:concat()
end
end
class.encode = class.encode_upper
return class
| gpl-3.0 |
csteddy/luasocket | test/urltest.lua | 30 | 17349 | local socket = require("socket")
socket.url = require("socket.url")
dofile("testsupport.lua")
local check_build_url = function(parsed)
local built = socket.url.build(parsed)
if built ~= parsed.url then
print("built is different from expected")
print(built)
print(expected)
os.exit()
end
end
local check_protect = function(parsed, path, unsafe)
local built = socket.url.build_path(parsed, unsafe)
if built ~= path then
print(built, path)
print("path composition failed.")
os.exit()
end
end
local check_invert = function(url)
local parsed = socket.url.parse(url)
parsed.path = socket.url.build_path(socket.url.parse_path(parsed.path))
local rebuilt = socket.url.build(parsed)
if rebuilt ~= url then
print(url, rebuilt)
print("original and rebuilt are different")
os.exit()
end
end
local check_parse_path = function(path, expect)
local parsed = socket.url.parse_path(path)
for i = 1, math.max(#parsed, #expect) do
if parsed[i] ~= expect[i] then
print(path)
os.exit()
end
end
if expect.is_directory ~= parsed.is_directory then
print(path)
print("is_directory mismatch")
os.exit()
end
if expect.is_absolute ~= parsed.is_absolute then
print(path)
print("is_absolute mismatch")
os.exit()
end
local built = socket.url.build_path(expect)
if built ~= path then
print(built, path)
print("path composition failed.")
os.exit()
end
end
local check_absolute_url = function(base, relative, absolute)
local res = socket.url.absolute(base, relative)
if res ~= absolute then
io.write("absolute: In test for '", relative, "' expected '",
absolute, "' but got '", res, "'\n")
os.exit()
end
end
local check_parse_url = function(gaba)
local url = gaba.url
gaba.url = nil
local parsed = socket.url.parse(url)
for i, v in pairs(gaba) do
if v ~= parsed[i] then
io.write("parse: In test for '", url, "' expected ", i, " = '",
v, "' but got '", tostring(parsed[i]), "'\n")
for i,v in pairs(parsed) do print(i,v) end
os.exit()
end
end
for i, v in pairs(parsed) do
if v ~= gaba[i] then
io.write("parse: In test for '", url, "' expected ", i, " = '",
tostring(gaba[i]), "' but got '", v, "'\n")
for i,v in pairs(parsed) do print(i,v) end
os.exit()
end
end
end
print("testing URL parsing")
check_parse_url{
url = "scheme://userinfo@host:port/path;params?query#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
authority = "user:password@host:port",
host = "host",
port = "port",
userinfo = "user:password",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment",
}
check_parse_url{
url = "scheme://userinfo@host:port/path;params?query#",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = ""
}
check_parse_url{
url = "scheme://userinfo@host:port/path;params?#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port/path;params#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port/path;?query#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port/path?query#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port/;params?query#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/",
params = "params",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
}
check_parse_url{
url = "//userinfo@host:port/path;params?query#fragment",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "//userinfo@host:port/path",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
}
check_parse_url{
url = "//userinfo@host/path",
authority = "userinfo@host",
host = "host",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
}
check_parse_url{
url = "//user:password@host/path",
authority = "user:password@host",
host = "host",
userinfo = "user:password",
password = "password",
user = "user",
path = "/path",
}
check_parse_url{
url = "//user:@host/path",
authority = "user:@host",
host = "host",
userinfo = "user:",
password = "",
user = "user",
path = "/path",
}
check_parse_url{
url = "//user@host:port/path",
authority = "user@host:port",
host = "host",
userinfo = "user",
user = "user",
port = "port",
path = "/path",
}
check_parse_url{
url = "//host:port/path",
authority = "host:port",
port = "port",
host = "host",
path = "/path",
}
check_parse_url{
url = "//host/path",
authority = "host",
host = "host",
path = "/path",
}
check_parse_url{
url = "//host",
authority = "host",
host = "host",
}
check_parse_url{
url = "/path",
path = "/path",
}
check_parse_url{
url = "path",
path = "path",
}
-- IPv6 tests
check_parse_url{
url = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html",
scheme = "http",
host = "FEDC:BA98:7654:3210:FEDC:BA98:7654:3210",
authority = "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80",
port = "80",
path = "/index.html"
}
check_parse_url{
url = "http://[1080:0:0:0:8:800:200C:417A]/index.html",
scheme = "http",
host = "1080:0:0:0:8:800:200C:417A",
authority = "[1080:0:0:0:8:800:200C:417A]",
path = "/index.html"
}
check_parse_url{
url = "http://[3ffe:2a00:100:7031::1]",
scheme = "http",
host = "3ffe:2a00:100:7031::1",
authority = "[3ffe:2a00:100:7031::1]",
}
check_parse_url{
url = "http://[1080::8:800:200C:417A]/foo",
scheme = "http",
host = "1080::8:800:200C:417A",
authority = "[1080::8:800:200C:417A]",
path = "/foo"
}
check_parse_url{
url = "http://[::192.9.5.5]/ipng",
scheme = "http",
host = "::192.9.5.5",
authority = "[::192.9.5.5]",
path = "/ipng"
}
check_parse_url{
url = "http://[::FFFF:129.144.52.38]:80/index.html",
scheme = "http",
host = "::FFFF:129.144.52.38",
port = "80",
authority = "[::FFFF:129.144.52.38]:80",
path = "/index.html"
}
check_parse_url{
url = "http://[2010:836B:4179::836B:4179]",
scheme = "http",
host = "2010:836B:4179::836B:4179",
authority = "[2010:836B:4179::836B:4179]",
}
check_parse_url{
url = "//userinfo@[::FFFF:129.144.52.38]:port/path;params?query#fragment",
authority = "userinfo@[::FFFF:129.144.52.38]:port",
host = "::FFFF:129.144.52.38",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://user:password@[::192.9.5.5]:port/path;params?query#fragment",
scheme = "scheme",
authority = "user:password@[::192.9.5.5]:port",
host = "::192.9.5.5",
port = "port",
userinfo = "user:password",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
print("testing URL building")
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
host = "host",
port = "port",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url{
url = "//userinfo@[::FFFF:129.144.52.38]:port/path;params?query#fragment",
host = "::FFFF:129.144.52.38",
port = "port",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url{
url = "scheme://user:password@[::192.9.5.5]:port/path;params?query#fragment",
scheme = "scheme",
host = "::192.9.5.5",
port = "port",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user:password@host/path;params?query#fragment",
scheme = "scheme",
host = "host",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user@host/path;params?query#fragment",
scheme = "scheme",
host = "host",
user = "user",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://host/path;params?query#fragment",
scheme = "scheme",
host = "host",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://host/path;params#fragment",
scheme = "scheme",
host = "host",
path = "/path",
params = "params",
fragment = "fragment"
}
check_build_url {
url = "scheme://host/path#fragment",
scheme = "scheme",
host = "host",
path = "/path",
fragment = "fragment"
}
check_build_url {
url = "scheme://host/path",
scheme = "scheme",
host = "host",
path = "/path",
}
check_build_url {
url = "//host/path",
host = "host",
path = "/path",
}
check_build_url {
url = "/path",
path = "/path",
}
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
host = "host",
port = "port",
user = "user",
userinfo = "not used",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
host = "host",
port = "port",
user = "user",
userinfo = "not used",
authority = "not used",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
host = "host",
port = "port",
userinfo = "user:password",
authority = "not used",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
authority = "user:password@host:port",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
-- standard RFC tests
print("testing absolute resolution")
check_absolute_url("http://a/b/c/d;p?q#f", "g:h", "g:h")
check_absolute_url("http://a/b/c/d;p?q#f", "g", "http://a/b/c/g")
check_absolute_url("http://a/b/c/d;p?q#f", "./g", "http://a/b/c/g")
check_absolute_url("http://a/b/c/d;p?q#f", "g/", "http://a/b/c/g/")
check_absolute_url("http://a/b/c/d;p?q#f", "/g", "http://a/g")
check_absolute_url("http://a/b/c/d;p?q#f", "//g", "http://g")
check_absolute_url("http://a/b/c/d;p?q#f", "?y", "http://a/b/c/d;p?y")
check_absolute_url("http://a/b/c/d;p?q#f", "g?y", "http://a/b/c/g?y")
check_absolute_url("http://a/b/c/d;p?q#f", "g?y/./x", "http://a/b/c/g?y/./x")
check_absolute_url("http://a/b/c/d;p?q#f", "#s", "http://a/b/c/d;p?q#s")
check_absolute_url("http://a/b/c/d;p?q#f", "g#s", "http://a/b/c/g#s")
check_absolute_url("http://a/b/c/d;p?q#f", "g#s/./x", "http://a/b/c/g#s/./x")
check_absolute_url("http://a/b/c/d;p?q#f", "g?y#s", "http://a/b/c/g?y#s")
check_absolute_url("http://a/b/c/d;p?q#f", ";x", "http://a/b/c/d;x")
check_absolute_url("http://a/b/c/d;p?q#f", "g;x", "http://a/b/c/g;x")
check_absolute_url("http://a/b/c/d;p?q#f", "g;x?y#s", "http://a/b/c/g;x?y#s")
check_absolute_url("http://a/b/c/d;p?q#f", ".", "http://a/b/c/")
check_absolute_url("http://a/b/c/d;p?q#f", "./", "http://a/b/c/")
check_absolute_url("http://a/b/c/d;p?q#f", "..", "http://a/b/")
check_absolute_url("http://a/b/c/d;p?q#f", "../", "http://a/b/")
check_absolute_url("http://a/b/c/d;p?q#f", "../g", "http://a/b/g")
check_absolute_url("http://a/b/c/d;p?q#f", "../..", "http://a/")
check_absolute_url("http://a/b/c/d;p?q#f", "../../", "http://a/")
check_absolute_url("http://a/b/c/d;p?q#f", "../../g", "http://a/g")
check_absolute_url("http://a/b/c/d;p?q#f", "", "http://a/b/c/d;p?q#f")
check_absolute_url("http://a/b/c/d;p?q#f", "/./g", "http://a/./g")
check_absolute_url("http://a/b/c/d;p?q#f", "/../g", "http://a/../g")
check_absolute_url("http://a/b/c/d;p?q#f", "g.", "http://a/b/c/g.")
check_absolute_url("http://a/b/c/d;p?q#f", ".g", "http://a/b/c/.g")
check_absolute_url("http://a/b/c/d;p?q#f", "g..", "http://a/b/c/g..")
check_absolute_url("http://a/b/c/d;p?q#f", "..g", "http://a/b/c/..g")
check_absolute_url("http://a/b/c/d;p?q#f", "./../g", "http://a/b/g")
check_absolute_url("http://a/b/c/d;p?q#f", "./g/.", "http://a/b/c/g/")
check_absolute_url("http://a/b/c/d;p?q#f", "g/./h", "http://a/b/c/g/h")
check_absolute_url("http://a/b/c/d;p?q#f", "g/../h", "http://a/b/c/h")
-- extra tests
check_absolute_url("//a/b/c/d;p?q#f", "d/e/f", "//a/b/c/d/e/f")
check_absolute_url("/a/b/c/d;p?q#f", "d/e/f", "/a/b/c/d/e/f")
check_absolute_url("a/b/c/d", "d/e/f", "a/b/c/d/e/f")
check_absolute_url("a/b/c/d/../", "d/e/f", "a/b/c/d/e/f")
check_absolute_url("http://velox.telemar.com.br", "/dashboard/index.html",
"http://velox.telemar.com.br/dashboard/index.html")
print("testing path parsing and composition")
check_parse_path("/eu/tu/ele", { "eu", "tu", "ele"; is_absolute = 1 })
check_parse_path("/eu/", { "eu"; is_absolute = 1, is_directory = 1 })
check_parse_path("eu/tu/ele/nos/vos/eles/",
{ "eu", "tu", "ele", "nos", "vos", "eles"; is_directory = 1})
check_parse_path("/", { is_absolute = 1, is_directory = 1})
check_parse_path("", { })
check_parse_path("eu%01/%02tu/e%03l%04e/nos/vos%05/e%12les/",
{ "eu\1", "\2tu", "e\3l\4e", "nos", "vos\5", "e\18les"; is_directory = 1})
check_parse_path("eu/tu", { "eu", "tu" })
print("testing path protection")
check_protect({ "eu", "-_.!~*'():@&=+$,", "tu" }, "eu/-_.!~*'():@&=+$,/tu")
check_protect({ "eu ", "~diego" }, "eu%20/~diego")
check_protect({ "/eu>", "<diego?" }, "%2feu%3e/%3cdiego%3f")
check_protect({ "\\eu]", "[diego`" }, "%5ceu%5d/%5bdiego%60")
check_protect({ "{eu}", "|diego\127" }, "%7beu%7d/%7cdiego%7f")
check_protect({ "eu ", "~diego" }, "eu /~diego", 1)
check_protect({ "/eu>", "<diego?" }, "/eu>/<diego?", 1)
check_protect({ "\\eu]", "[diego`" }, "\\eu]/[diego`", 1)
check_protect({ "{eu}", "|diego\127" }, "{eu}/|diego\127", 1)
print("testing inversion")
check_invert("http:")
check_invert("a/b/c/d.html")
check_invert("//net_loc")
check_invert("http:a/b/d/c.html")
check_invert("//net_loc/a/b/d/c.html")
check_invert("http://net_loc/a/b/d/c.html")
check_invert("//who:isit@net_loc")
check_invert("http://he:man@boo.bar/a/b/c/i.html;type=moo?this=that#mark")
check_invert("/b/c/d#fragment")
check_invert("/b/c/d;param#fragment")
check_invert("/b/c/d;param?query#fragment")
check_invert("/b/c/d?query")
check_invert("/b/c/d;param?query")
check_invert("http://he:man@[::192.168.1.1]/a/b/c/i.html;type=moo?this=that#mark")
print("the library passed all tests")
| mit |
mohammadgham/man | bot/sbssbot.lua | 1 | 10346 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '2'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"download_media",
"invite",
"all",
"leave_ban",
"admin",
"lock_badw",
"lock_link",
"tag",
"setrank",
"id",
"tagall",
"SUDO",
"feedback",
"getplug",
"echo",
"plugins",
"time",
"welcome"
sudo_users = {310896266},--Sudo users
sudo_users = {310896266},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[Sbss Bot V2 Beta
An Advanced Anti Spam Bot Forked On TeleSeed
Develpoed By:
@sina7sk
Manager:
@yellowhat
Founder:
@amirho3in
Special Thank To:
Mehr Pouya
Arman
IM/-\N
Creed Is Dead
]],
help_text_realm = [[
See Patterns In Github
]],
help_text = [[
لیست دستورات :
اخراج [آیدی،کد،ریپلای] 👤
شخص مورد نظر از گروه اخراج ميشود
_________________________________________
بن [آیدی،کد،ریپلای]😟
شخص مورد نظر از گروه تحریم میشود
_________________________________________
حذف بن[کد]😃
شخص مورد نظر از تحریم خارج ميشود
_________________________________________
لیست بن👥
لیست افرادی که از گروه تحریم شده اند
_________________________________________
خروج : ترک گروه 🔫
صاحب : نمایش آیدی مدیر گروه
_________________________________________
لیست : لیست کمک مدیرها😍
_________________________________________
ترفیع [ریپلای،یوزرنیم]
اضافه کردن کمک مدیر
_________________________________________
تنزل [ریپلای،یوزرنیم]
حذف کردن کمک مدیر
_________________________________________
قفل [اعضا|نام|ربات |تگ|عکس|خروج|فحش]🔒
_________________________________________
باز کردن [اعضا|نام|ربات |تگ|عکس|خروج|فحش]🔓
_________________________________________
تنظیم عکس : اضافه کردن وقفل عکس گروه🌅
_________________________________________
تنظیم نام [نام]⛩
عوض کردن نام گروه
_________________________________________
توضیحات: درباره گروه🏷
_________________________________________
قوانین: قوانین گروه⚖⚖
_________________________________________
تنظیم قانون<متن>⚖
_________________________________________
تنظیم توضیحات<متن>
تنظیمات: تنظیمات گروه🛠
_________________________________________
لینک جدید : تعویض لینک و ارسال درگروه🏵
_________________________________________
لینک خصوصی :ارسال در چت خصوصی 💷
_________________________________________
لینک : لینک گروه🔖
_________________________________________
حساسیت[تعداد]
محدودیت تعداد اسپم📯🔆
_________________________________________
پاک کردن
پاکسازی مدیرها/قوانین/موضوع✏️
_________________________________________
ایدی [یوزرنیم]
بازگرداندن کد آیدی🤖
_________________________________________
تگ : صدا کردن افراد گروه🗣🗣
⚠️نیاز نیست از '!' و '/' استفاده کنید*⚠️
_________________________________________
_________________________________________
_________________________________________
ليست سودوها :@Cia_00_07
@sina7sk
@amirho3in
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
Nether-Machine/NetherMachine | rotations/shared/Reel/Lures.lua | 1 | 3558 | --[[
Copyright (c) 2014, drizz
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
--]]
local CONTINENT_PANDARIA = 6
Reel.Enchantments = {
{ id = 4919, bonus = 150 }, -- +150 Temporary fishing lure
{ id = 265, bonus = 75 } -- +75 Temporary fishing lure
}
Reel.Lures = {
}
Reel.Hats = {
{ id = 88710, bonus = 5, enchantment = 4919 }, -- Nat's Hat
{ id = 117405, bonus = 10, enchantment = 4919 }, -- Nat's Drinking Hat
{ id = 33820, bonus = 5, enchantment = 265 }, -- Weather-Beaten Fishing Hat
{ id = 19972, bonus = 5 }, -- Lucky Fishing Hat
{ id = 93732, bonus = 5 }, -- Darkmoon Fishing Cap
{ id = 118380, bonus = 100 }, -- Hightfish Cap
{ id = 118393, bonus = 100 } -- Tentacled Hat
}
Reel.Rods = {
{ id = 46337, bonus = 3 }, -- Staats' Fishing Pole / +3
{ id = 120163, bonus = 3 }, -- Thruk's Fishing Rod / +3
{ id = 6365, bonus = 5 }, -- Strong Fishing Pole / +5
{ id = 84660, bonus = 10 }, -- Pandaren Fishing Pole / +10
{ id = 6366, bonus = 15 }, -- Darkwood Fishing Pole / +15
{ id = 6367, bonus = 20 }, -- Big Iron Fishing Pole / +20
{ id = 25978, bonus = 20 }, -- Seth's Graphite Fishing Pole / +20
{ id = 19022, bonus = 20 }, -- Nat Pagle's Extreme Angler FC-5000 / +20
{ id = 45858, bonus = 25 }, -- Nat's Lucky Fishing Pole / +25
{ id = 45991, bonus = 30 }, -- Bone Fishing Pole / +30
{ id = 44050, bonus = 30 }, -- Mastercraft Kalu'ak Fishing Pole / +30
{ id = 45992, bonus = 30 }, -- Jeweled Fishing Pole / +30
{ id = 84661, bonus = 30 }, -- Dragon Fishing Pole / +30
{ id = 116826, bonus = 30 }, -- Draenic Fishing Pole / +30
{ id = 116825, bonus = 30 }, -- Savage Fishing Pole / +30
{ id = 19970, bonus = 40 }, -- Arcanite Fishing Pole / +40
{ id = 118381, bonus = 100 } -- Ephemeral Fishing Pole / +100
}
Reel.Buffs = {
-- Ancient Pandaren Fishing Charm
{ id = 85973, buff = 125167, condition = function() return GetCurrentMapContinent() == CONTINENT_PANDARIA end },
}
-- Check whether an item is a fishing rod.
--
-- @returns True if the item is a fishing rod.
function Reel:IsFishingRod(itemID)
for i, rod in ipairs(self.Rods) do
if rod.id == itemID then
return true
end
end
end
-- Check whether an item is a lure item.
--
-- @returns True if the item is a lure item.
function Reel:IsLureItem(itemID)
for i, lure in ipairs(self.Lures) do
if lure.id == itemID then
return true
end
end
end
-- Check whether an item is a fishing buff item.
--
-- @returns True if the item is a fishing buff item.
function Reel:IsBuffItem(itemID)
for i, buff in ipairs(self.Buffs) do
if buff.id == itemID then
return true
end
end
end
-- Check whether an item is a fishing hat.
--
-- @returns True if the item is a fishing hat.
function Reel:IsFishingHat(itemID)
for i, hat in ipairs(self.Hats) do
if hat.id == itemID then
return true
end
end
end | agpl-3.0 |
Nether-Machine/NetherMachine | NetherMachine_MrTheSoulz/rotations/druid/balance.lua | 1 | 6723 | local fetch = NetherMachine.interface.fetchKey
local exeOnLoad = function()
mts.Splash("|cff9482C9[MTS]-|cffFFFFFF"..(select(2, GetSpecializationInfo(GetSpecialization())) or "Error").."-|cff9482C9Loaded", 5.0)
NetherMachine.toggle.create(
'dotEverything',
'Interface\\Icons\\Ability_creature_cursed_05.png',
'Dot All The Things!',
'Click here to dot all the things!\nSome Spells require Multitarget enabled also.\nOnly Works if using FireHack.')
end
local BoomkinForm = {
-- Interrupts
{ "78675", "target.interruptsAt(50)" }, -- Solar Beam
-- Items
{ "#5512", "player.health < 50" }, --Healthstone
-- Cooldowns
{ "112071", "modifier.cooldowns" }, --Celestial Alignment
{ "#trinket1", "modifier.cooldowns" }, --trinket 1
{ "#trinket2", "modifier.cooldowns" }, --trinket 2
{ "#57723", "player.hashero" }, -- Int Pot on lust
--Defensive
{ "Barkskin", "player.health <= 50", "player" },
{ "#5512", "player.health < 40"}, --Healthstone when less than 40% health
{ "108238", "player.health < 60", "player"}, --Instant renewal when less than 40% health
{{ -- Auto Dotting
{ "164812", "@mtsLib.mtsDot(164812, 2, 100)" }, -- moonfire
{ "164815", "@mtsLib.mtsDot(164815, 2, 100)" }, --SunFire
}, "toggle.dotEverything" },
-- AoE
{ "48505", "modifier.multitarget", "target" }, -- Starfall
{ "48505", "player.area(8).enemies >= 4", "target" }, -- Starfall // FH SMART AoE
-- Proc's
{ "78674", "player.buff(Shooting Stars)", "target" }, --Starsurge with Shooting Stars Proc
{ "164815", "player.buff(Solar Peak)", "target" }, --SunFire on proc
{ "164812", "player.buff(Lunar Peak)", "target" }, --MoonFire on proc
-- Rotation
{ "78674", "player.spell(78674).charges >= 2" }, --StarSurge with more then 2 charges
{ "78674", "player.buff(112071}" }, --StarSurge with Celestial Alignment buff
{ "164812", "target.debuff(Moonfire).duration <= 2"}, --MoonFire
{ "164815", "target.debuff(Sunfire).duration <= 2"}, --SunFire
{ "2912", "player.buff(Lunar Empowerment).count >= 1" }, --Starfire with Lunar Empowerment
{ "5176", "player.buff(Solar Empowerment).count >= 1" }, --Wrath with Solar Empowerment
{ "2912", "player.lunar"}, --StarFire
{ "5176", "player.solar"}, --Wrath
--{ "2912" }, --StarFire Filler
}
NetherMachine.rotation.register_custom(102, mts.Icon.."|r[|cff9482C9MTS|r][|cffFF7D0ADruid-Boomkin|r]",
{ ------------------------------------------------------------------------------------------------------------------ In Combat
{ "1126", { -- Mark of the Wild
"!player.buff(20217).any", -- kings
"!player.buff(115921).any", -- Legacy of the Emperor
"!player.buff(1126).any", -- Mark of the Wild
"!player.buff(90363).any", -- embrace of the Shale Spider
"!player.buff(69378).any", -- Blessing of Forgotten Kings
"!player.buff(5215)",-- Not in Stealth
"player.form = 0", -- Player not in form
(function() return fetch('mtsconfDruidBalance','Buffs') end),
}},
{ "20484", { -- Rebirth
"modifier.lshift",
"!mouseover.alive"
}, "mouseover" },
{ "/run CancelShapeshiftForm();", (function()
if mts.dynamicEval("player.form = 0") or fetch('mtsconfDruidBalance', 'Form') == 'MANUAL' then
return false
elseif mts.dynamicEval("player.form != 0") and fetch('mtsconfDruidBalance', 'Form') == '0' then
return true
else
return mts.dynamicEval("player.form != " .. fetch('mtsconfDruidBalance', 'Form'))
end
end) },
{ "768", { -- catform
"player.form != 2", -- Stop if cat
"!modifier.lalt", -- Stop if pressing left alt
"!player.buff(5215)", -- Not in Stealth
(function() return fetch('mtsconfDruidBalance','Form') == '2' end),
}},
{ "783", { -- Travel
"player.form != 3", -- Stop if cat
"!modifier.lalt", -- Stop if pressing left alt
"!player.buff(5215)", -- Not in Stealth
(function() return fetch('mtsconfDruidBalance','Form') == '3' end),
}},
{ "5487", { -- catform
"player.form != 1", -- Stop if cat
"!modifier.lalt", -- Stop if pressing left alt
"!player.buff(5215)", -- Not in Stealth
(function() return fetch('mtsconfDruidBalance','Form') == '1' end),
}},
{ "24858", { -- boomkin
"player.form != 4", -- Stop if boomkin
"!modifier.lalt", -- Stop if pressing left alt
"!player.buff(5215)", -- Not in Stealth
(function() return fetch('mtsconfDruidBalance','Form') == '4' end),
}},
{{ --------------------------------------------------------------------------------- Boomkin Form
{ BoomkinForm },
}, "player.form = 4" },
},
{ ------------------------------------------------------------------------------------------------------------------ Out Combat
{ "1126", { -- Mark of the Wild
"!player.buff(20217).any", -- kings
"!player.buff(115921).any", -- Legacy of the Emperor
"!player.buff(1126).any", -- Mark of the Wild
"!player.buff(90363).any", -- embrace of the Shale Spider
"!player.buff(69378).any", -- Blessing of Forgotten Kings
"!player.buff(5215)",-- Not in Stealth
"player.form = 0", -- Player not in form
(function() return fetch('mtsconfDruidBalance','Buffs') end),
}},
{ "20484", { -- Rebirth
"modifier.lshift",
"!mouseover.alive"
}, "mouseover" },
{ "/run CancelShapeshiftForm();", (function()
if mts.dynamicEval("player.form = 0") or fetch('mtsconfDruidBalance', 'FormOCC') == 'MANUAL' then
return false
elseif mts.dynamicEval("player.form != 0") and fetch('mtsconfDruidBalance', 'FormOCC') == '0' then
return true
else
return mts.dynamicEval("player.form != " .. fetch('mtsconfDruidBalance', 'FormOCC'))
end
end) },
{ "768", { -- catform
"player.form != 2", -- Stop if cat
"!modifier.lalt", -- Stop if pressing left alt
"!player.buff(5215)", -- Not in Stealth
(function() return fetch('mtsconfDruidBalance','FormOCC') == '2' end),
}},
{ "783", { -- Travel
"player.form != 3", -- Stop if cat
"!modifier.lalt", -- Stop if pressing left alt
"!player.buff(5215)", -- Not in Stealth
(function() return fetch('mtsconfDruidBalance','FormOCC') == '3' end),
}},
{ "5487", { -- catform
"player.form != 1", -- Stop if cat
"!modifier.lalt", -- Stop if pressing left alt
"!player.buff(5215)", -- Not in Stealth
(function() return fetch('mtsconfDruidBalance','FormOCC') == '1' end),
}},
{ "24858", { -- boomkin
"player.form != 4", -- Stop if boomkin
"!modifier.lalt", -- Stop if pressing left alt
"!player.buff(5215)", -- Not in Stealth
(function() return fetch('mtsconfDruidBalance','FormOCC') == '4' end),
}},
}, exeOnLoad) | agpl-3.0 |
tederis/mta-resources | xrloader/_compile.lua | 5 | 1459 | local _writeScript = function ( responseData, errno, filepath )
if errno > 0 then
outputDebugString ( "Произошла ошибка " .. errno, 2 )
return
end
local file = fileCreate ( filepath )
if file then
fileWrite ( file, responseData )
fileClose ( file )
else
outputDebugString ( "Файл не создается!", 2 )
end
end
function compileScript ( filepath )
local filename = gettok ( filepath, 1, 46 )
local file = fileOpen ( filepath, true )
if file then
local content = fileRead ( file, fileGetSize ( file ) )
fileClose ( file )
fetchRemote ( "http://luac.mtasa.com/?compile=1&debug=0&blockdecompile=1&encrypt=1", _writeScript, content, true, filename .. ".tct" )
end
end
function compileAllScripts ( )
local xml = xmlLoadFile ( "meta.xml" )
if xml == false then
outputDebugString ( "Meta.xml не был найден!", 2 )
return
end
local node
local index = 0
local _next = function ( )
node = xmlFindChild ( xml, "script", index )
index = index + 1
return node
end
local num = 0
while _next ( ) do
if xmlNodeGetAttribute ( node, "special" ) == false then
local filepath = xmlNodeGetAttribute ( node, "src" )
compileScript ( filepath )
num = num + 1
end
end
outputDebugString ( "Собрано " .. num .. " скриптов" )
end
addCommandHandler ( "compile",
function ( )
compileAllScripts ( )
end
) | gpl-3.0 |
tederis/mta-resources | wbo_modmanager/_compile.lua | 5 | 1459 | local _writeScript = function ( responseData, errno, filepath )
if errno > 0 then
outputDebugString ( "Произошла ошибка " .. errno, 2 )
return
end
local file = fileCreate ( filepath )
if file then
fileWrite ( file, responseData )
fileClose ( file )
else
outputDebugString ( "Файл не создается!", 2 )
end
end
function compileScript ( filepath )
local filename = gettok ( filepath, 1, 46 )
local file = fileOpen ( filepath, true )
if file then
local content = fileRead ( file, fileGetSize ( file ) )
fileClose ( file )
fetchRemote ( "http://luac.mtasa.com/?compile=1&debug=0&blockdecompile=1&encrypt=1", _writeScript, content, true, filename .. ".tct" )
end
end
function compileAllScripts ( )
local xml = xmlLoadFile ( "meta.xml" )
if xml == false then
outputDebugString ( "Meta.xml не был найден!", 2 )
return
end
local node
local index = 0
local _next = function ( )
node = xmlFindChild ( xml, "script", index )
index = index + 1
return node
end
local num = 0
while _next ( ) do
if xmlNodeGetAttribute ( node, "special" ) == false then
local filepath = xmlNodeGetAttribute ( node, "src" )
compileScript ( filepath )
num = num + 1
end
end
outputDebugString ( "Собрано " .. num .. " скриптов" )
end
addCommandHandler ( "compile",
function ( )
compileAllScripts ( )
end
) | gpl-3.0 |
tederis/mta-resources | sp_login/_compile.lua | 5 | 1459 | local _writeScript = function ( responseData, errno, filepath )
if errno > 0 then
outputDebugString ( "Произошла ошибка " .. errno, 2 )
return
end
local file = fileCreate ( filepath )
if file then
fileWrite ( file, responseData )
fileClose ( file )
else
outputDebugString ( "Файл не создается!", 2 )
end
end
function compileScript ( filepath )
local filename = gettok ( filepath, 1, 46 )
local file = fileOpen ( filepath, true )
if file then
local content = fileRead ( file, fileGetSize ( file ) )
fileClose ( file )
fetchRemote ( "http://luac.mtasa.com/?compile=1&debug=0&blockdecompile=1&encrypt=1", _writeScript, content, true, filename .. ".tct" )
end
end
function compileAllScripts ( )
local xml = xmlLoadFile ( "meta.xml" )
if xml == false then
outputDebugString ( "Meta.xml не был найден!", 2 )
return
end
local node
local index = 0
local _next = function ( )
node = xmlFindChild ( xml, "script", index )
index = index + 1
return node
end
local num = 0
while _next ( ) do
if xmlNodeGetAttribute ( node, "special" ) == false then
local filepath = xmlNodeGetAttribute ( node, "src" )
compileScript ( filepath )
num = num + 1
end
end
outputDebugString ( "Собрано " .. num .. " скриптов" )
end
addCommandHandler ( "compile",
function ( )
compileAllScripts ( )
end
) | gpl-3.0 |
suppayami/shoot-la-shoot | data/scripts/class/specific/bullet_enemy_d.lua | 1 | 1093 | BulletEnemyD = class(Bullet)
function BulletEnemyD:spriteClass()
return SpriteBulletEnemyD
end
function BulletEnemyD:spriteLayer()
return "scene"
end
function BulletEnemyD:spriteName()
return "bullet_enemy_d"
end
function BulletEnemyD:moveRateX()
if not self.moveY then return 0 end
if self.moveY > 0 then
return 6 * math.sin(self.flyAngle)
else
return -6 * math.sin(self.flyAngle)
end
end
function BulletEnemyD:moveRateY()
if not self.moveY then return 6 end
if self.moveY > 0 then
return 6 * math.cos(self.flyAngle)
else
return -6 * math.cos(self.flyAngle)
end
end
function BulletEnemyD:applyEffect(target)
local layer = self:spriteLayer()
local name = "sloweffect"
local class = SpriteSlow
local sprite = LayerManager:addSprite(layer, name, class)
sprite.x = target.x
sprite.y = target.y
sprite.ox = sprite:width() / 2
sprite.oy = sprite:width() / 2
sprite:autoDestroy(1)
target.slowRate = 0.5
target.slowDuration = 10 * 60
self:destroy()
end | mit |
teleoktan/teleoktan | plugins/banhammer.lua | 1 | 36752 | local function pre_process(msg)
chat = msg.chat_id_
user = msg.sender_user_id_
local function check_newmember(arg, data)
test = load_data(_config.moderation.data)
lock_bots = test[arg.chat_id]['settings']['lock_bots']
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
if data.type_.ID == "UserTypeBot" then
if not is_owner(arg.msg) and lock_bots == 'yes' then
kick_user(data.id_, arg.chat_id)
end
end
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if is_banned(data.id_, arg.chat_id) then
if not lang then
tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_User_ "..user_name.." *[ "..data.id_.." ]* _is banned_", 0, "md")
else
tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_کاربر_ "..user_name.." *[ "..data.id_.." ]* _از گروه محروم است_", 0, "md")
end
kick_user(data.id_, arg.chat_id)
end
if is_gbanned(data.id_) then
if not lang then
tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_User_ "..user_name.." *[ "..data.id_.." ]* _is globally banned_", 0, "md")
else
tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_کاربر_ "..user_name.." *[ "..data.id_.." ]* _از تمام گروه های ربات محروم است_", 0, "md")
end
kick_user(data.id_, arg.chat_id)
end
end
if msg.adduser then
tdcli_function ({
ID = "GetUser",
user_id_ = msg.adduser
}, check_newmember, {chat_id=chat,msg_id=msg.id_,user_id=user,msg=msg})
end
if msg.joinuser then
tdcli_function ({
ID = "GetUser",
user_id_ = msg.joinuser
}, check_newmember, {chat_id=chat,msg_id=msg.id_,user_id=user,msg=msg})
end
if is_silent_user(user, chat) then
del_msg(msg.chat_id_, msg.id_)
end
if is_banned(user, chat) then
del_msg(msg.chat_id_, tonumber(msg.id_))
kick_user(user, chat)
end
if is_gbanned(user) then
del_msg(msg.chat_id_, tonumber(msg.id_))
kick_user(user, chat)
end
end
local function action_by_reply(arg, data)
local hash = "gp_lang:"..data.chat_id_
local lang = redis:get(hash)
local cmd = arg.cmd
if not tonumber(data.sender_user_id_) then return false end
if data.sender_user_id_ then
if cmd == "ban" then
local function ban_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if is_mod1(arg.chat_id, data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't ban_ *mods,owners and bot admins*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه، و ادمین های ربات رو از گروه محروم کنید*", 0, "md")
end
end
if administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* * از گروه محروم بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
kick_user(data.id_, arg.chat_id)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, ban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "unban" then
local function unban_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *unbanned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه خارج شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, unban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "silent" then
local function silent_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if is_mod1(arg.chat_id, data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't silent_ *mods,owners and bot admins*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه، و ادمین های ربات بگیرید*", 0, "md")
end
end
if administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *silent*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن رو نداشت*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _added to_ *silent users list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو از دست داد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, silent_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "unsilent" then
local function unsilent_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *silent*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن را داشت*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _removed from_ *silent users list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو به دست آورد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, unsilent_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "banall" then
local function gban_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration['gban_users'] then
administration['gban_users'] = {}
save_data(_config.moderation.data, administration)
end
if is_admin1(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't_ *globally ban* _other admins_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید ادمین های ربات رو از تمامی گروه های ربات محروم کنید*", 0, "md")
end
end
if is_gbanned(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *globally banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم بود*", 0, "md")
end
end
administration['gban_users'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
kick_user(data.id_, arg.chat_id)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از تمام گروه های ربات محروم شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, gban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "unbanall" then
local function ungban_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration['gban_users'] then
administration['gban_users'] = {}
save_data(_config.moderation.data, administration)
end
if not is_gbanned(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *globally banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم نبود*", 0, "md")
end
end
administration['gban_users'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally unbanned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه های ربات خارج شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, ungban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "kick" then
if is_mod1(data.chat_id_, data.sender_user_id_) then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_You can't kick_ *mods,owners and bot admins*", 0, "md")
elseif lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md")
end
else
kick_user(data.sender_user_id_, data.chat_id_)
end
end
if cmd == "delall" then
if is_mod1(data.chat_id_, data.sender_user_id_) then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_You can't delete messages_ *mods,owners and bot admins*", 0, "md")
elseif lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md")
end
else
tdcli.deleteMessagesFromUser(data.chat_id_, data.sender_user_id_, dl_cb, nil)
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_All_ *messages* _of_ *[ "..data.sender_user_id_.." ]* _has been_ *deleted*", 0, "md")
elseif lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "*تمام پیام های* *[ "..data.sender_user_id_.." ]* *پاک شد*", 0, "md")
end
end
end
else
if lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function action_by_username(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local cmd = arg.cmd
local administration = load_data(_config.moderation.data)
if not arg.username then return false end
if data.id_ then
if data.type_.user_.username_ then
user_name = '@'..check_markdown(data.type_.user_.username_)
else
user_name = check_markdown(data.title_)
end
if cmd == "ban" then
if is_mod1(arg.chat_id, data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't ban_ *mods,owners and bot admins*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه، و ادمین های ربات رو از گروه محروم کنید*", 0, "md")
end
end
if administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* * از گروه محروم بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
kick_user(data.id_, arg.chat_id)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم شد*", 0, "md")
end
end
if cmd == "unban" then
if not administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *unbanned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه خارج شد*", 0, "md")
end
end
if cmd == "silent" then
if is_mod1(arg.chat_id, data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't silent_ *mods,owners and bot admins*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه، و ادمین های ربات بگیرید*", 0, "md")
end
end
if administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *silent*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن رو نداشت*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _added to_ *silent users list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو از دست داد*", 0, "md")
end
end
if cmd == "unsilent" then
if not administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *silent*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن را داشت*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _removed from_ *silent users list*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو به دست آورد*", 0, "md")
end
end
if cmd == "banall" then
if not administration['gban_users'] then
administration['gban_users'] = {}
save_data(_config.moderation.data, administration)
end
if is_admin1(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't_ *globally ban* _other admins_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید ادمین های ربات رو از تمامی گروه های ربات محروم کنید*", 0, "md")
end
end
if is_gbanned(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *globally banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم بود*", 0, "md")
end
end
administration['gban_users'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
kick_user(data.id_, arg.chat_id)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از تمام گروه های ربات محروم شد*", 0, "md")
end
end
if cmd == "unbanall" then
if not administration['gban_users'] then
administration['gban_users'] = {}
save_data(_config.moderation.data, administration)
end
if not is_gbanned(data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *globally banned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم نبود*", 0, "md")
end
end
administration['gban_users'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally unbanned*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه های ربات خارج شد*", 0, "md")
end
end
if cmd == "kick" then
if is_mod1(arg.chat_id, data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't kick_ *mods,owners and bot admins*", 0, "md")
elseif lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md")
end
else
kick_user(data.id_, arg.chat_id)
end
end
if cmd == "delall" then
if is_mod1(arg.chat_id, data.id_) then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't delete messages_ *mods,owners and bot admins*", 0, "md")
elseif lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md")
end
else
tdcli.deleteMessagesFromUser(arg.chat_id, data.id_, dl_cb, nil)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_All_ *messages* _of_ "..user_name.." *[ "..data.id_.." ]* _has been_ *deleted*", 0, "md")
elseif lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "*تمام پیام های* "..user_name.." *[ "..data.id_.." ]* *پاک شد*", 0, "md")
end
end
end
else
if lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function run(msg, matches)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
chat = msg.chat_id_
user = msg.sender_user_id_
if matches[1] == "kick" and is_mod(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="kick"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_mod1(msg.chat_id_, matches[2]) then
if not lang then
tdcli.sendMessage(msg.chat_id_, "", 0, "_You can't kick mods,owners or bot admins_", 0, "md")
elseif lang then
tdcli.sendMessage(msg.chat_id_, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md")
end
else
kick_user(matches[2], msg.chat_id_)
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="kick"})
end
end
if matches[1] == "delall" and is_mod(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="delall"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_mod1(msg.chat_id_, matches[2]) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_You can't delete messages mods,owners or bot admins_", 0, "md")
elseif lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md")
end
else
tdcli.deleteMessagesFromUser(msg.chat_id_, matches[2], dl_cb, nil)
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_All_ *messages* _of_ *[ "..matches[2].." ]* _has been_ *deleted*", 0, "md")
elseif lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "*تمامی پیام های* *[ "..matches[2].." ]* *پاک شد*", 0, "md")
end
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="delall"})
end
end
if matches[1] == "banall" and is_admin(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="banall"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_admin1(matches[2]) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_You can't globally ban other admins_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, "", 0, "*شما نمیتوانید ادمین های ربات رو از گروه های ربات محروم کنید*", 0, "md")
end
end
if is_gbanned(matches[2]) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "*User "..matches[2].." is already globally banned*", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, "", 0, "*کاربر "..matches[2].." از گروه های ربات محروم بود*", 0, "md")
end
end
data['gban_users'][tostring(matches[2])] = ""
save_data(_config.moderation.data, data)
kick_user(matches[2], msg.chat_id_)
if not lang then
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "*User "..matches[2].." has been globally banned*", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "*کاربر "..matches[2].." از تمام گروه هار ربات محروم شد*", 0, "md")
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="banall"})
end
end
if matches[1] == "unbanall" and is_admin(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="unbanall"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if not is_gbanned(matches[2]) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "*User "..matches[2].." is not globally banned*", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, "", 0, "*کاربر "..matches[2].." از گروه های ربات محروم نبود*", 0, "md")
end
end
data['gban_users'][tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
if not lang then
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "*User "..matches[2].." has been globally unbanned*", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "*کاربر "..matches[2].." از محرومیت گروه های ربات خارج شد*", 0, "md")
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="unbanall"})
end
end
if matches[1] == "ban" and is_mod(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="ban"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_mod1(msg.chat_id_, matches[2]) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_You can't ban mods,owners or bot admins_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو از گروه محروم کنید*", 0, "md")
end
end
if is_banned(matches[2], msg.chat_id_) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_User "..matches[2].." is already banned_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, "", 0, "*کاربر "..matches[2].." از گروه محروم بود*", 0, "md")
end
end
data[tostring(chat)]['banned'][tostring(matches[2])] = ""
save_data(_config.moderation.data, data)
kick_user(matches[2], msg.chat_id_)
if not lang then
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "_User "..matches[2].." has been banned_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "*کاربر "..matches[2].." از گروه محروم شد*", 0, "md")
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="ban"})
end
end
if matches[1] == "unban" and is_mod(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="unban"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if not is_banned(matches[2], msg.chat_id_) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_User "..matches[2].." is not banned_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, "", 0, "*کاربر "..matches[2].." از گروه محروم نبود*", 0, "md")
end
end
data[tostring(chat)]['banned'][tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
if not lang then
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "_User "..matches[2].." has been unbanned_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "*کاربر "..matches[2].." از محرومیت گروه خارج شد*", 0, "md")
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="unban"})
end
end
if matches[1] == "silent" and is_mod(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="silent"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if is_mod1(msg.chat_id_, matches[2]) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_You can't silent mods,leaders or bot admins_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه و ادمین های ربات بگیرید*", 0, "md")
end
end
if is_silent_user(matches[2], chat) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_User "..matches[2].." is already silent_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, "", 0, "*کاربر "..matches[2].." از قبل توانایی چت کردن رو نداشت*", 0, "md")
end
end
data[tostring(chat)]['is_silent_users'][tostring(matches[2])] = ""
save_data(_config.moderation.data, data)
if not lang then
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "_User "..matches[2].." added to silent users list_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "*کاربر "..matches[2].." توانایی چت کردن رو از دست داد*", 0, "md")
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="silent"})
end
end
if matches[1] == "unsilent" and is_mod(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="unsilent"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
if not is_silent_user(matches[2], chat) then
if not lang then
return tdcli.sendMessage(msg.chat_id_, "", 0, "_User "..matches[2].." is not silent_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, "", 0, "*کاربر "..matches[2].." از قبل توانایی چت کردن رو داشت*", 0, "md")
end
end
data[tostring(chat)]['is_silent_users'][tostring(matches[2])] = nil
save_data(_config.moderation.data, data)
if not lang then
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "_User "..matches[2].." removed from silent users list_", 0, "md")
else
return tdcli.sendMessage(msg.chat_id_, msg.id_, 0, "*کاربر "..matches[2].." توانایی چت کردن رو به دست آورد*", 0, "md")
end
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="unsilent"})
end
end
if matches[1]:lower() == 'clean' and is_owner(msg) then
if matches[2] == 'bans' then
if next(data[tostring(chat)]['banned']) == nil then
if not lang then
return "_No_ *banned* _users in this group_"
else
return "*هیچ کاربری از این گروه محروم نشده*"
end
end
for k,v in pairs(data[tostring(chat)]['banned']) do
data[tostring(chat)]['banned'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
if not lang then
return "_All_ *banned* _users has been unbanned_"
else
return "*تمام کاربران محروم شده از گروه از محرومیت خارج شدند*"
end
end
if matches[2] == 'silentlist' then
if next(data[tostring(chat)]['is_silent_users']) == nil then
if not lang then
return "_No_ *silent* _users in this group_"
else
return "*لیست کاربران سایلنت شده خالی است*"
end
end
for k,v in pairs(data[tostring(chat)]['is_silent_users']) do
data[tostring(chat)]['is_silent_users'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
if not lang then
return "*Silent list* _has been cleaned_"
else
return "*لیست کاربران سایلنت شده پاک شد*"
end
end
end
if matches[1]:lower() == 'clean' and is_sudo(msg) then
if matches[2] == 'gbans' then
if next(data['gban_users']) == nil then
if not lang then
return "_No_ *globally banned* _users available_"
else
return "*هیچ کاربری از گروه های ربات محروم نشده*"
end
end
for k,v in pairs(data['gban_users']) do
data['gban_users'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
if not lang then
return "_All_ *globally banned* _users has been unbanned_"
else
return "*تمام کاربرانی که از گروه های ربات محروم بودند از محرومیت خارج شدند*"
end
end
end
if matches[1] == "gbanlist" and is_admin(msg) then
return gbanned_list(msg)
end
if matches[1] == "silentlist" and is_mod(msg) then
return silent_users_list(chat)
end
if matches[1] == "banlist" and is_mod(msg) then
return banned_list(chat)
end
end
return {
patterns = {
"^[!/#](banall)$",
"^[!/#](banall) (.*)$",
"^[!/#](unbanall)$",
"^[!/#](unbanall) (.*)$",
"^[!/#](gbanlist)$",
"^[!/#](ban)$",
"^[!/#](ban) (.*)$",
"^[!/#](unban)$",
"^[!/#](unban) (.*)$",
"^[!/#](banlist)$",
"^[!/#](silent)$",
"^[!/#](silent) (.*)$",
"^[!/#](unsilent)$",
"^[!/#](unsilent) (.*)$",
"^[!/#](silentlist)$",
"^[!/#](kick)$",
"^[!/#](kick) (.*)$",
"^[!/#](delall)$",
"^[!/#](delall) (.*)$",
"^[!/#](clean) (.*)$",
},
run = run,
pre_process = pre_process
}
-- کد های پایین در ربات نشان داده نمیشوند
-- @aliaz001
| gpl-3.0 |
szymonkaliski/Dotfiles | Dotfiles/hammerspoon/bindings/global.lua | 1 | 1665 | local module = {}
local grid = require('ext.grid')
local smartLaunchOrFocus = require('ext.application').smartLaunchOrFocus
local system = require('ext.system')
local window = require('ext.window')
-- local toggleCaffeine = require('utils.controlplane.caffeine').toggleCaffeine
-- local toggleVPN = require('utils.controlplane.persistvpn').toggleVPN
module.start = function()
-- ultra bindings
local ultra = { 'ctrl', 'alt', 'cmd' }
-- ctrl + tab as alternative to cmd + tab
hs.hotkey.bind({ 'ctrl' }, 'tab', window.windowHints)
-- force paste (sometimes cmd + v is blocked)
hs.hotkey.bind({ 'cmd', 'alt', 'shift' }, 'v', function()
hs.eventtap.keyStrokes(hs.pasteboard.getContents())
end)
-- toggles
hs.fnutils.each({
{ key = '/', fn = system.toggleConsole },
{ key = 'b', fn = system.toggleBluetooth },
{ key = 'd', fn = system.toggleDND },
{ key = 'g', fn = grid.toggleGrid },
{ key = 'l', fn = wm.cycleLayout },
{ key = 'q', fn = system.displaySleep },
{ key = 'r', fn = system.reloadHS },
{ key = 't', fn = system.toggleTheme },
{ key = 'w', fn = system.toggleWiFi },
}, function(object)
hs.hotkey.bind(ultra, object.key, object.fn)
end)
-- apps
hs.fnutils.each({
{ key = 'return', apps = config.apps.terms },
{ key = 'space', apps = config.apps.browsers },
{ key = ',', apps = { 'System Preferences' } }
}, function(object)
hs.hotkey.bind(ultra, object.key, function() smartLaunchOrFocus(object.apps) end)
end)
end
module.stop = function()
end
return module
| mit |
BooM-amour/koskhol | plugins/owners.lua | 4 | 12713 |
local function lock_group_namemod(msg, data, target)
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)
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)
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)
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)
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)
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 unlock_group_photomod(msg, data, target)
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 show_group_settingsmod(msg, data, target)
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 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.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
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 set_description(target, about)
local data = load_data(_config.moderation.data)
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 run(msg, matches)
if msg.to.type ~= 'chat' then
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback (extra , success, result)
local receiver = 'chat#'..matches[1]
vardump(result)
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local receiver = 'chat#'..matches[1]
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ")
export_chat_link(receiver, callback, true)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "------")
send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^[!/]([Oo]wners) (%d+) ([^%s]+) (.*)$",
"^[!/]([Oo]wners) (%d+) ([^%s]+)$",
"^[!/]([Cc]hangeabout) (%d+) (.*)$",
"^[!/]([Cc]hangerules) (%d+) (.*)$",
"^[!/]([Cc]hangename) (%d+) (.*)$",
"^[!/]([Ll]oggroup) (%d+)$",
"^([Oo]wners) (%d+) ([^%s]+) (.*)$",
"^([Oo]wners) (%d+) ([^%s]+)$",
"^([Cc]hangeabout) (%d+) (.*)$",
"^([Cc]hangerules) (%d+) (.*)$",
"^([Cc]hangename) (%d+) (.*)$",
"^([Ll]oggroup) (%d+)$"
},
run = run
}
| gpl-2.0 |
ld-test/dromozoa-graph | test/test_bfs.lua | 2 | 2068 | -- Copyright (C) 2015 Tomoyuki Fujimori <moyu@dromozoa.com>
--
-- This file is part of dromozoa-graph.
--
-- dromozoa-graph 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.
--
-- dromozoa-graph 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 dromozoa-graph. If not, see <http://www.gnu.org/licenses/>.
local graph = require "dromozoa.graph"
local g = graph()
local v1 = g:create_vertex()
local v2 = g:create_vertex()
local v3 = g:create_vertex()
local v4 = g:create_vertex()
local v5 = g:create_vertex()
g:create_edge(v1, v2)
g:create_edge(v2, v2)
g:create_edge(v2, v3)
g:create_edge(v3, v2)
g:create_edge(v1, v4)
g:create_edge(v5, v4)
v1:bfs({
tree_edge = function (_, e, u, v)
print("tree_edge", u.id, v.id)
end;
gray_target = function (_, e, u, v)
print("gray_target", u.id, v.id)
end;
black_target = function (_, e, u, v)
print("black_target", u.id, v.id)
end;
})
local g = graph()
local v1 = g:create_vertex()
local v2 = g:create_vertex()
local v3 = g:create_vertex()
local v4 = g:create_vertex()
local v5 = g:create_vertex()
g:create_edge(v1, v2)
g:create_edge(v1, v3)
g:create_edge(v2, v4)
g:create_edge(v3, v5)
local result = {}
v1:bfs({
discover_vertex = function (_, u)
result[#result + 1] = u.id
end;
})
assert(result[1] == 1)
assert(result[2] == 2)
assert(result[3] == 3)
assert(result[4] == 4)
assert(result[5] == 5)
local result = {}
v1:bfs({
examine_edge = function (_, e, u, v)
return e.id ~= 1
end;
discover_vertex = function (_, u)
result[#result + 1] = u.id
end;
})
assert(result[1] == 1)
assert(result[2] == 3)
assert(result[3] == 5)
| gpl-3.0 |
eulerreich/nn | FlattenTable.lua | 24 | 3131 | local FlattenTable, parent = torch.class('nn.FlattenTable', 'nn.Module')
function FlattenTable:__init()
parent.__init(self)
self.output = {}
self.input_map = {}
self.gradInput = {}
end
-- Recursive function to flatten a table (output is a table)
local function flatten(output, input)
local input_map -- has the same structure as input, but stores the
-- indices to the corresponding output
if type(input) == 'table' then
input_map = {}
-- forward DFS order
for i = 1, #input do
input_map[#input_map+1] = flatten(output, input[i])
end
else
input_map = #output + 1
output[input_map] = input -- append the tensor
end
return input_map
end
-- Recursive function to check if we need to rebuild the output table
local function checkMapping(output, input, input_map)
if input_map == nil or output == nil or input == nil then
return false
end
if type(input) == 'table' then
if type(input_map) ~= 'table' then
return false
end
if #input ~= #input_map then
return false
end
-- forward DFS order
for i = 1, #input do
local ok = checkMapping(output, input[i], input_map[i])
if not ok then
return false
end
end
return true
else
if type(input_map) ~= 'number' then
return false
end
return output[input_map] == input
end
end
-- During BPROP we have to build a gradInput with the same shape as the
-- input. This is a recursive function to build up a gradInput
local function inverseFlatten(gradOutput, input_map)
if type(input_map) == 'table' then
local gradInput = {}
for i = 1, #input_map do
gradInput[#gradInput + 1] = inverseFlatten(gradOutput, input_map[i])
end
return gradInput
else
return gradOutput[input_map]
end
end
function FlattenTable:updateOutput(input)
assert(type(input) == 'table', 'input must be a table')
-- to avoid updating rebuilding the flattened table every updateOutput call
-- we will do a DFS pass over the existing output table and the inputs to
-- see if it needs to be rebuilt.
if not checkMapping(self.output, input, self.input_map) then
self.output = {}
self.input_map = flatten(self.output, input)
end
return self.output
end
function FlattenTable:updateGradInput(input, gradOutput)
assert(type(input) == 'table', 'input must be a table')
assert(type(input) == 'table', 'gradOutput must be a table')
-- If the input changes between the updateOutput and updateGradInput call,
-- then we may have to rebuild the input_map! However, let's assume that
-- the input_map is valid and that forward has already been called.
-- However, we should check that the gradInput is valid:
if not checkMapping(gradOutput, self.gradInput, self.input_map) then
self.gradInput = inverseFlatten(gradOutput, self.input_map)
end
return self.gradInput
end
function FlattenTable:type(type, tensorCache)
-- This function just stores references so we don't need to do any type
-- conversions. Just force the tables to be empty.
self.output = {}
self.input_map = {}
end
| bsd-3-clause |
marqueza/syzygy | lib/rotLove/src/rot/type/pointSet.lua | 2 | 1544 | --- Pair set.
-- An unordered collection of unique value-pairs.
-- @module ROT.Type.PointSet
local ROT = require((...):gsub(('.[^./\\]*'):rep(2) .. '$', ''))
local PointSet = ROT.Class:extend("PointSet")
function PointSet:init()
self._index = {}
end
local function hash(x, y)
return x and y * 0x4000000 + x or false -- 26-bit x and y
end
function PointSet:find(x, y)
return self._index[hash(x, y)]
end
function PointSet:peek(i)
return self[i], self[i + 1]
end
function PointSet:poke(i, x, y)
self._index[hash(self:peek(i))] = nil
self._index[hash(x, y)] = i
self._index[false] = nil
self[i], self[i + 1] = x, y
return self
end
function PointSet:push(x, y)
local key = hash(x, y)
local i = self._index[key]
if i then return nil, i end
i = #self + 1
self:poke(i, x, y)
self._index[key] = i
self._index[false] = nil
return i
end
function PointSet:pluck(i)
local last, x, y = #self - 1, self:peek(i)
self:poke(i, self:peek(last)):poke(last)
self._index[hash(x, y)] = nil
self._index[hash(self:peek(i))] = i
self._index[false] = nil
return x, y
end
function PointSet:prune(x, y)
local i = self:find(x, y)
return i and self:pluck(i)
end
local function iterate(self, i)
i = i - 2
if i > 0 then
return i, self:peek(i)
end
end
function PointSet:each()
return iterate, self, #self + 1
end
function PointSet:getRandom()
local i = self._rng:random(1, #self / 2) * 2 - 1
return self:peek(i)
end
return PointSet
| gpl-3.0 |
MaxyTibia/forgottenserver | data/talkactions/scripts/create_item.lua | 24 | 1147 | function onSay(player, words, param)
if not player:getGroup():getAccess() then
return true
end
if player:getAccountType() < ACCOUNT_TYPE_GOD then
return false
end
local split = param:split(",")
local itemType = ItemType(split[1])
if itemType:getId() == 0 then
itemType = ItemType(tonumber(split[1]))
if itemType:getId() == 0 then
player:sendCancelMessage("There is no item with that id or name.")
return false
end
end
local count = tonumber(split[2])
if count ~= nil then
if itemType:isStackable() then
count = math.min(10000, math.max(1, count))
elseif not itemType:isFluidContainer() then
count = math.min(100, math.max(1, count))
else
count = math.max(0, count)
end
else
if not itemType:isFluidContainer() then
count = 1
else
count = 0
end
end
local result = player:addItem(itemType:getId(), count)
if result ~= nil then
if not itemType:isStackable() then
if type(result) == "table" then
for _, item in ipairs(result) do
item:decay()
end
else
result:decay()
end
end
player:getPosition():sendMagicEffect(CONST_ME_MAGIC_GREEN)
end
return false
end
| gpl-2.0 |
jmackellar/Touhoulike | lib/rotLove/rot/map/arena.lua | 2 | 1180 | --- The Arena map generator.
-- Generates an arena style map. All cells except for the extreme borders are floors. The borders are walls.
-- @module ROT.Map.Arena
local ROT = require((...):gsub(('.[^./\\]*'):rep(2) .. '$', ''))
local Arena = ROT.Map:extend("Arena")
--- Constructor.
-- Called with ROT.Map.Arena:new(width, height)
-- @tparam int width Width in cells of the map
-- @tparam int height Height in cells of the map
function Arena:init(width, height)
Arena.super.init(self, width, height)
end
--- Create.
-- Creates a map.
-- @tparam function callback This function will be called for every cell. It must accept the following parameters:
-- @tparam int callback.x The x-position of a cell in the map
-- @tparam int callback.y The y-position of a cell in the map
-- @tparam int callback.value A value representing the cell-type. 0==floor, 1==wall
-- @treturn ROT.Map.Arena self
function Arena:create(callback)
local w, h = self._width, self._height
if not callback then return self end
for y = 1, h do
for x = 1, w do
callback(x, y, x>1 and y>1 and x<w and y<h and 0 or 1)
end
end
return self
end
return Arena
| gpl-3.0 |
sneakin/MrRobOboto | data/blocks/minecraft.lua | 1 | 15685 | return {
["minecraft:air"] = { 0 }, -- false {}
["minecraft:stone"] = { 1 }, -- true {variant="stone"}
["minecraft:grass"] = { 2 }, -- true {snowy="false"}
["minecraft:dirt"] = { 3 }, -- true {variant="dirt",snowy="false"}
["minecraft:cobblestone"] = { 4 }, -- false {}
["minecraft:planks"] = { 5 }, -- true {variant="oak"}
["minecraft:sapling"] = { 6 }, -- true {stage="0",type="oak"}
["minecraft:bedrock"] = { 7 }, -- false {}
["minecraft:flowing_water"] = { 8 }, -- true {level="0"}
["minecraft:water"] = { 9 }, -- true {level="0"}
["minecraft:flowing_lava"] = { 10 }, -- true {level="0"}
["minecraft:lava"] = { 11 }, -- true {level="0"}
["minecraft:sand"] = { 12 }, -- true {variant="sand"}
["minecraft:gravel"] = { 13 }, -- false {}
["minecraft:gold_ore"] = { 14 }, -- false {}
["minecraft:iron_ore"] = { 15 }, -- false {}
["minecraft:coal_ore"] = { 16 }, -- false {}
["minecraft:log"] = { 17 }, -- true {variant="oak",axis="y"}
["minecraft:leaves"] = { 18 }, -- true {variant="oak",check_decay="true",decayable="true"}
["minecraft:sponge"] = { 19 }, -- true {wet="false"}
["minecraft:glass"] = { 20 }, -- false {}
["minecraft:lapis_ore"] = { 21 }, -- false {}
["minecraft:lapis_block"] = { 22 }, -- false {}
["minecraft:dispenser"] = { 23 }, -- true {facing="down",triggered="false"}
["minecraft:sandstone"] = { 24 }, -- true {type="sandstone"}
["minecraft:noteblock"] = { 25 }, -- false {}
["minecraft:bed"] = { 26 }, -- true {part="foot",facing="south",occupied="false"}
["minecraft:golden_rail"] = { 27 }, -- true {powered="false",shape="north_south"}
["minecraft:detector_rail"] = { 28 }, -- true {powered="false",shape="north_south"}
["minecraft:sticky_piston"] = { 29 }, -- true {facing="down",extended="false"}
["minecraft:web"] = { 30 }, -- false {}
["minecraft:tallgrass"] = { 31 }, -- true {type="dead_bush"}
["minecraft:deadbush"] = { 32 }, -- false {}
["minecraft:piston"] = { 33 }, -- true {facing="down",extended="false"}
["minecraft:piston_head"] = { 34 }, -- true {short="false",facing="down",type="normal"}
["minecraft:wool"] = { 35 }, -- true {color="white"}
["minecraft:piston_extension"] = { 36 }, -- true {facing="down",type="normal"}
["minecraft:yellow_flower"] = { 37 }, -- true {type="dandelion"}
["minecraft:red_flower"] = { 38 }, -- true {type="poppy"}
["minecraft:brown_mushroom"] = { 39 }, -- false {}
["minecraft:red_mushroom"] = { 40 }, -- false {}
["minecraft:gold_block"] = { 41 }, -- false {}
["minecraft:iron_block"] = { 42 }, -- false {}
["minecraft:double_stone_slab"] = { 43 }, -- true {variant="stone",seamless="false"}
["minecraft:stone_slab"] = { 44 }, -- true {variant="stone",half="bottom"}
["minecraft:brick_block"] = { 45 }, -- false {}
["minecraft:tnt"] = { 46 }, -- true {explode="false"}
["minecraft:bookshelf"] = { 47 }, -- false {}
["minecraft:mossy_cobblestone"] = { 48 }, -- false {}
["minecraft:obsidian"] = { 49 }, -- false {}
["minecraft:torch"] = { 50 }, -- true {facing="up"}
["minecraft:fire"] = { 51 }, -- true {south="false",up="false",east="false",west="false",north="false",age="0"}
["minecraft:mob_spawner"] = { 52 }, -- false {}
["minecraft:oak_stairs"] = { 53 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:chest"] = { 54 }, -- true {facing="north"}
["minecraft:redstone_wire"] = { 55 }, -- true {south="none",power="0",east="none",west="none",north="none"}
["minecraft:diamond_ore"] = { 56 }, -- false {}
["minecraft:diamond_block"] = { 57 }, -- false {}
["minecraft:crafting_table"] = { 58 }, -- false {}
["minecraft:wheat"] = { 59 }, -- true {age="0"}
["minecraft:farmland"] = { 60 }, -- true {moisture="0"}
["minecraft:furnace"] = { 61 }, -- true {facing="north"}
["minecraft:lit_furnace"] = { 62 }, -- true {facing="north"}
["minecraft:standing_sign"] = { 63 }, -- true {rotation="0"}
["minecraft:wooden_door"] = { 64 }, -- true {half="lower",facing="east",powered="false",hinge="left",open="false"}
["minecraft:ladder"] = { 65 }, -- true {facing="north"}
["minecraft:rail"] = { 66 }, -- true {shape="north_south"}
["minecraft:stone_stairs"] = { 67 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:wall_sign"] = { 68 }, -- true {facing="north"}
["minecraft:lever"] = { 69 }, -- true {facing="down_x",powered="false"}
["minecraft:stone_pressure_plate"] = { 70 }, -- true {powered="false"}
["minecraft:iron_door"] = { 71 }, -- true {half="lower",facing="east",powered="false",hinge="left",open="false"}
["minecraft:wooden_pressure_plate"] = { 72 }, -- true {powered="false"}
["minecraft:redstone_ore"] = { 73 }, -- false {}
["minecraft:lit_redstone_ore"] = { 74 }, -- false {}
["minecraft:unlit_redstone_torch"] = { 75 }, -- true {facing="up"}
["minecraft:redstone_torch"] = { 76 }, -- true {facing="up"}
["minecraft:snow_layer"] = { 78 }, -- true {layers="1"}
["minecraft:ice"] = { 79 }, -- false {}
["minecraft:snow"] = { 80 }, -- false {}
["minecraft:cactus"] = { 81 }, -- true {age="0"}
["minecraft:clay"] = { 82 }, -- false {}
["minecraft:reeds"] = { 83 }, -- true {age="0"}
["minecraft:jukebox"] = { 84 }, -- true {has_record="false"}
["minecraft:fence"] = { 85 }, -- true {south="false",east="false",north="false",west="false"}
["minecraft:pumpkin"] = { 86 }, -- true {facing="south"}
["minecraft:netherrack"] = { 87 }, -- false {}
["minecraft:soul_sand"] = { 88 }, -- false {}
["minecraft:glowstone"] = { 89 }, -- false {}
["minecraft:portal"] = { 90 }, -- true {axis="x"}
["minecraft:lit_pumpkin"] = { 91 }, -- true {facing="south"}
["minecraft:cake"] = { 92 }, -- true {bites="0"}
["minecraft:unpowered_repeater"] = { 93 }, -- true {delay="1",facing="south",locked="false"}
["minecraft:powered_repeater"] = { 94 }, -- true {delay="1",facing="south",locked="false"}
["minecraft:stained_glass"] = { 95 }, -- true {color="white"}
["minecraft:trapdoor"] = { 96 }, -- true {half="bottom",facing="north",open="false"}
["minecraft:monster_egg"] = { 97 }, -- true {variant="stone"}
["minecraft:stonebrick"] = { 98 }, -- true {variant="stonebrick"}
["minecraft:brown_mushroom_block"] = { 99 }, -- true {variant="all_inside"}
["minecraft:red_mushroom_block"] = { 100 }, -- true {variant="all_inside"}
["minecraft:iron_bars"] = { 101 }, -- true {south="false",east="false",north="false",west="false"}
["minecraft:glass_pane"] = { 102 }, -- true {south="false",east="false",north="false",west="false"}
["minecraft:melon_block"] = { 103 }, -- false {}
["minecraft:pumpkin_stem"] = { 104 }, -- true {age="0",facing="up"}
["minecraft:melon_stem"] = { 105 }, -- true {age="0",facing="up"}
["minecraft:vine"] = { 106 }, -- true {south="false",up="false",east="false",west="false",north="false"}
["minecraft:fence_gate"] = { 107 }, -- true {powered="false",open="false",facing="south",in_wall="false"}
["minecraft:brick_stairs"] = { 108 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:stone_brick_stairs"] = { 109 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:mycelium"] = { 110 }, -- true {snowy="false"}
["minecraft:waterlily"] = { 111 }, -- false {}
["minecraft:nether_brick"] = { 112 }, -- false {}
["minecraft:nether_brick_fence"] = { 113 }, -- true {south="false",east="false",north="false",west="false"}
["minecraft:nether_brick_stairs"] = { 114 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:nether_wart"] = { 115 }, -- true {age="0"}
["minecraft:enchanting_table"] = { 116 }, -- false {}
["minecraft:brewing_stand"] = { 117 }, -- true {has_bottle_0="false",has_bottle_1="false",has_bottle_2="false"}
["minecraft:cauldron"] = { 118 }, -- true {level="0"}
["minecraft:end_portal"] = { 119 }, -- false {}
["minecraft:end_portal_frame"] = { 120 }, -- true {facing="south",eye="false"}
["minecraft:end_stone"] = { 121 }, -- false {}
["minecraft:dragon_egg"] = { 122 }, -- false {}
["minecraft:redstone_lamp"] = { 123 }, -- false {}
["minecraft:lit_redstone_lamp"] = { 124 }, -- false {}
["minecraft:double_wooden_slab"] = { 125 }, -- true {variant="oak"}
["minecraft:wooden_slab"] = { 126 }, -- true {variant="oak",half="bottom"}
["minecraft:cocoa"] = { 127 }, -- true {age="0",facing="south"}
["minecraft:sandstone_stairs"] = { 128 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:emerald_ore"] = { 129 }, -- false {}
["minecraft:ender_chest"] = { 130 }, -- true {facing="north"}
["minecraft:tripwire_hook"] = { 131 }, -- true {powered="false",facing="south",attached="false"}
["minecraft:tripwire"] = { 132 }, -- true {south="false",attached="false",disarmed="false",powered="false",west="false",north="false",east="false"}
["minecraft:emerald_block"] = { 133 }, -- false {}
["minecraft:spruce_stairs"] = { 134 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:birch_stairs"] = { 135 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:jungle_stairs"] = { 136 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:command_block"] = { 137 }, -- true {facing="down",conditional="false"}
["minecraft:beacon"] = { 138 }, -- false {}
["minecraft:cobblestone_wall"] = { 139 }, -- true {south="false",up="false",east="false",west="false",north="false",variant="cobblestone"}
["minecraft:flower_pot"] = { 140 }, -- true {contents="empty",legacy_data="0"}
["minecraft:carrots"] = { 141 }, -- true {age="0"}
["minecraft:potatoes"] = { 142 }, -- true {age="0"}
["minecraft:wooden_button"] = { 143 }, -- true {facing="down",powered="false"}
["minecraft:skull"] = { 144 }, -- true {facing="down",nodrop="false"}
["minecraft:anvil"] = { 145 }, -- true {damage="0",facing="south"}
["minecraft:trapped_chest"] = { 146 }, -- true {facing="north"}
["minecraft:light_weighted_pressure_plate"] = { 147 }, -- true {power="0"}
["minecraft:heavy_weighted_pressure_plate"] = { 148 }, -- true {power="0"}
["minecraft:unpowered_comparator"] = { 149 }, -- true {mode="compare",facing="south",powered="false"}
["minecraft:powered_comparator"] = { 150 }, -- true {mode="compare",facing="south",powered="false"}
["minecraft:daylight_detector"] = { 151 }, -- true {power="0"}
["minecraft:redstone_block"] = { 152 }, -- false {}
["minecraft:quartz_ore"] = { 153 }, -- false {}
["minecraft:hopper"] = { 154 }, -- true {enabled="true",facing="down"}
["minecraft:quartz_block"] = { 155 }, -- true {variant="default"}
["minecraft:quartz_stairs"] = { 156 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:activator_rail"] = { 157 }, -- true {powered="false",shape="north_south"}
["minecraft:dropper"] = { 158 }, -- true {facing="down",triggered="false"}
["minecraft:stained_hardened_clay"] = { 159 }, -- true {color="white"}
["minecraft:stained_glass_pane"] = { 160 }, -- true {south="false",east="false",west="false",color="white",north="false"}
["minecraft:leaves2"] = { 161 }, -- true {variant="acacia",check_decay="false",decayable="true"}
["minecraft:log2"] = { 162 }, -- true {variant="acacia",axis="y"}
["minecraft:acacia_stairs"] = { 163 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:dark_oak_stairs"] = { 164 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:slime"] = { 165 }, -- false {}
["minecraft:barrier"] = { 166 }, -- false {}
["minecraft:iron_trapdoor"] = { 167 }, -- true {half="bottom",facing="north",open="false"}
["minecraft:prismarine"] = { 168 }, -- true {variant="prismarine"}
["minecraft:sea_lantern"] = { 169 }, -- false {}
["minecraft:hay_block"] = { 170 }, -- true {axis="y"}
["minecraft:carpet"] = { 171 }, -- true {color="white"}
["minecraft:hardened_clay"] = { 172 }, -- false {}
["minecraft:coal_block"] = { 173 }, -- false {}
["minecraft:packed_ice"] = { 174 }, -- false {}
["minecraft:double_plant"] = { 175 }, -- true {variant="sunflower",half="lower",facing="north"}
["minecraft:standing_banner"] = { 176 }, -- true {rotation="0"}
["minecraft:wall_banner"] = { 177 }, -- true {facing="north"}
["minecraft:daylight_detector_inverted"] = { 178 }, -- true {power="0"}
["minecraft:red_sandstone"] = { 179 }, -- true {type="red_sandstone"}
["minecraft:red_sandstone_stairs"] = { 180 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:double_stone_slab2"] = { 181 }, -- true {variant="red_sandstone",seamless="false"}
["minecraft:stone_slab2"] = { 182 }, -- true {variant="red_sandstone",half="bottom"}
["minecraft:spruce_fence_gate"] = { 183 }, -- true {powered="false",open="false",facing="south",in_wall="false"}
["minecraft:birch_fence_gate"] = { 184 }, -- true {powered="false",open="false",facing="south",in_wall="false"}
["minecraft:jungle_fence_gate"] = { 185 }, -- true {powered="false",open="false",facing="south",in_wall="false"}
["minecraft:dark_oak_fence_gate"] = { 186 }, -- true {powered="false",open="false",facing="south",in_wall="false"}
["minecraft:acacia_fence_gate"] = { 187 }, -- true {powered="false",open="false",facing="south",in_wall="false"}
["minecraft:spruce_fence"] = { 188 }, -- true {south="false",east="false",north="false",west="false"}
["minecraft:birch_fence"] = { 189 }, -- true {south="false",east="false",north="false",west="false"}
["minecraft:jungle_fence"] = { 190 }, -- true {south="false",east="false",north="false",west="false"}
["minecraft:dark_oak_fence"] = { 191 }, -- true {south="false",east="false",north="false",west="false"}
["minecraft:acacia_fence"] = { 192 }, -- true {south="false",east="false",north="false",west="false"}
["minecraft:spruce_door"] = { 193 }, -- true {half="lower",facing="east",powered="false",hinge="left",open="false"}
["minecraft:birch_door"] = { 194 }, -- true {half="lower",facing="east",powered="false",hinge="left",open="false"}
["minecraft:jungle_door"] = { 195 }, -- true {half="lower",facing="east",powered="false",hinge="left",open="false"}
["minecraft:acacia_door"] = { 196 }, -- true {half="lower",facing="east",powered="false",hinge="left",open="false"}
["minecraft:dark_oak_door"] = { 197 }, -- true {half="lower",facing="east",powered="false",hinge="left",open="false"}
["minecraft:end_rod"] = { 198 }, -- true {facing="down"}
["minecraft:chorus_plant"] = { 199 }, -- true {south="false",up="false",east="false",west="false",north="false",down="false"}
["minecraft:chorus_flower"] = { 200 }, -- true {age="0"}
["minecraft:purpur_block"] = { 201 }, -- false {}
["minecraft:purpur_pillar"] = { 202 }, -- true {axis="y"}
["minecraft:purpur_stairs"] = { 203 }, -- true {shape="straight",half="bottom",facing="east"}
["minecraft:purpur_double_slab"] = { 204 }, -- true {variant="default"}
["minecraft:purpur_slab"] = { 205 }, -- true {variant="default",half="bottom"}
["minecraft:end_bricks"] = { 206 }, -- false {}
["minecraft:beetroots"] = { 207 }, -- true {age="0"}
["minecraft:grass_path"] = { 208 }, -- false {}
["minecraft:end_gateway"] = { 209 }, -- false {}
["minecraft:repeating_command_block"] = { 210 }, -- true {facing="down",conditional="false"}
["minecraft:chain_command_block"] = { 211 }, -- true {facing="down",conditional="false"}
["minecraft:frosted_ice"] = { 212 }, -- true {age="0"}
["minecraft:magma"] = { 213 }, -- false {}
["minecraft:nether_wart_block"] = { 214 }, -- false {}
["minecraft:red_nether_brick"] = { 215 }, -- false {}
["minecraft:bone_block"] = { 216 }, -- true {axis="y"}
["minecraft:structure_void"] = { 217 }, -- false {}
["minecraft:structure_block"] = { 255 }, -- true {mode="save"}
}
| gpl-3.0 |
qwertzdenek/elevator-music-generator | load_midi.lua | 1 | 2188 | -- load_midi.lua
-- Zdeněk Janeček, 2016 (ycdmdj@gmail.com)
--
-- University of West Bohemia
MIDI=require 'MIDI'
require 'paths'
input_pool = {}
roll_height = 88
number_count = 0
function init_pool(conf)
for fname in paths.files(conf.data_dir) do
if fname ~= '..' and fname ~= '.' then
local piano_roll = load_song(conf.data_dir..'/'..fname)
for t=1, piano_roll:size(2) do
-- input
local input = torch.ByteTensor(roll_height)
input:copy(piano_roll[{{}, t}])
table.insert(input_pool, input)
if #input_pool%(conf.batch_size+conf.rho-1)==0 then
number_count = number_count + 1
end
end
end
end
end
function load_batch(number, batch, conf)
assert(number<=number_count, "non existing batch")
-- because indexing from 1 sucks
local begin = (number-1)*#batch+1
for t=0, #batch-1 do
for i=0, conf.batch_size-1 do
batch[t+1][i+1]:copy(input_pool[begin+t+i])
end
end
end
function load_song(name)
local f=assert(io.open(name, 'r'))
local score=MIDI.midi2score(f:read('*all'))
local stats=MIDI.score2stats(score)
f:close()
-- read only assigned tracks
local assigned = {}
for key, val in pairs(stats['channels_by_track']) do
if #val > 0 then
table.insert(assigned, key+1)
end
end
local division_4 = score[1]
local division_32 = division_4 / 4
local song_len = stats['nticks']
local song_bitmap = torch.ByteTensor(roll_height, math.ceil(song_len / division_32)+2):zero()
-- for each track with music
for key, track in pairs(assigned) do
-- for each event
for k,event in pairs(score[track]) do
-- if it is note, not drum on channel 10 and regular instrument
if event[1] == 'note' and event[4] ~= 10 and event[5] < 112 then
start = math.ceil(event[2] / division_32) + 1
duration = math.ceil(event[3] / division_32)
note = event[5]
if note >= 21 and note <= 108 then
song_bitmap[{note-20, {start, start+duration}}] = 1
end
end
end
end
return song_bitmap
end
| gpl-3.0 |
sjznxd/lc-20130112 | applications/luci-statistics/luasrc/model/cbi/luci_statistics/dns.lua | 78 | 1344 | --[[
Luci configuration model for statistics - collectd dns plugin configuration
(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$
]]--
require("luci.sys")
m = Map("luci_statistics",
translate("DNS Plugin Configuration"),
translate(
"The dns plugin collects detailled statistics about dns " ..
"related traffic on selected interfaces."
))
-- collectd_dns config section
s = m:section( NamedSection, "collectd_dns", "luci_statistics" )
-- collectd_dns.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_dns.interfaces (Interface)
interfaces = s:option( MultiValue, "Interfaces", translate("Monitor interfaces") )
interfaces.widget = "select"
interfaces.size = 5
interfaces:depends( "enable", 1 )
interfaces:value("any")
for k, v in pairs(luci.sys.net.devices()) do
interfaces:value(v)
end
-- collectd_dns.ignoresources (IgnoreSource)
ignoresources = s:option( Value, "IgnoreSources", translate("Ignore source addresses") )
ignoresources.default = "127.0.0.1"
ignoresources:depends( "enable", 1 )
return m
| apache-2.0 |
quyse/flaw | flaw-lua-refimpl/src/lua-5.3.4-tests/bitwise.lua | 12 | 9209 | -- $Id: bitwise.lua,v 1.26 2016/11/07 13:11:28 roberto Exp $
-- See Copyright Notice in file all.lua
print("testing bitwise operations")
local numbits = string.packsize('j') * 8
assert(~0 == -1)
assert((1 << (numbits - 1)) == math.mininteger)
-- basic tests for bitwise operators;
-- use variables to avoid constant folding
local a, b, c, d
a = 0xFFFFFFFFFFFFFFFF
assert(a == -1 and a & -1 == a and a & 35 == 35)
a = 0xF0F0F0F0F0F0F0F0
assert(a | -1 == -1)
assert(a ~ a == 0 and a ~ 0 == a and a ~ ~a == -1)
assert(a >> 4 == ~a)
a = 0xF0; b = 0xCC; c = 0xAA; d = 0xFD
assert(a | b ~ c & d == 0xF4)
a = 0xF0.0; b = 0xCC.0; c = "0xAA.0"; d = "0xFD.0"
assert(a | b ~ c & d == 0xF4)
a = 0xF0000000; b = 0xCC000000;
c = 0xAA000000; d = 0xFD000000
assert(a | b ~ c & d == 0xF4000000)
assert(~~a == a and ~a == -1 ~ a and -d == ~d + 1)
a = a << 32
b = b << 32
c = c << 32
d = d << 32
assert(a | b ~ c & d == 0xF4000000 << 32)
assert(~~a == a and ~a == -1 ~ a and -d == ~d + 1)
assert(-1 >> 1 == (1 << (numbits - 1)) - 1 and 1 << 31 == 0x80000000)
assert(-1 >> (numbits - 1) == 1)
assert(-1 >> numbits == 0 and
-1 >> -numbits == 0 and
-1 << numbits == 0 and
-1 << -numbits == 0)
assert((2^30 - 1) << 2^30 == 0)
assert((2^30 - 1) >> 2^30 == 0)
assert(1 >> -3 == 1 << 3 and 1000 >> 5 == 1000 << -5)
-- coercion from strings to integers
assert("0xffffffffffffffff" | 0 == -1)
assert("0xfffffffffffffffe" & "-1" == -2)
assert(" \t-0xfffffffffffffffe\n\t" & "-1" == 2)
assert(" \n -45 \t " >> " -2 " == -45 * 4)
-- out of range number
assert(not pcall(function () return "0xffffffffffffffff.0" | 0 end))
-- embedded zeros
assert(not pcall(function () return "0xffffffffffffffff\0" | 0 end))
print'+'
package.preload.bit32 = function () --{
-- no built-in 'bit32' library: implement it using bitwise operators
local bit = {}
function bit.bnot (a)
return ~a & 0xFFFFFFFF
end
--
-- in all vararg functions, avoid creating 'arg' table when there are
-- only 2 (or less) parameters, as 2 parameters is the common case
--
function bit.band (x, y, z, ...)
if not z then
return ((x or -1) & (y or -1)) & 0xFFFFFFFF
else
local arg = {...}
local res = x & y & z
for i = 1, #arg do res = res & arg[i] end
return res & 0xFFFFFFFF
end
end
function bit.bor (x, y, z, ...)
if not z then
return ((x or 0) | (y or 0)) & 0xFFFFFFFF
else
local arg = {...}
local res = x | y | z
for i = 1, #arg do res = res | arg[i] end
return res & 0xFFFFFFFF
end
end
function bit.bxor (x, y, z, ...)
if not z then
return ((x or 0) ~ (y or 0)) & 0xFFFFFFFF
else
local arg = {...}
local res = x ~ y ~ z
for i = 1, #arg do res = res ~ arg[i] end
return res & 0xFFFFFFFF
end
end
function bit.btest (...)
return bit.band(...) ~= 0
end
function bit.lshift (a, b)
return ((a & 0xFFFFFFFF) << b) & 0xFFFFFFFF
end
function bit.rshift (a, b)
return ((a & 0xFFFFFFFF) >> b) & 0xFFFFFFFF
end
function bit.arshift (a, b)
a = a & 0xFFFFFFFF
if b <= 0 or (a & 0x80000000) == 0 then
return (a >> b) & 0xFFFFFFFF
else
return ((a >> b) | ~(0xFFFFFFFF >> b)) & 0xFFFFFFFF
end
end
function bit.lrotate (a ,b)
b = b & 31
a = a & 0xFFFFFFFF
a = (a << b) | (a >> (32 - b))
return a & 0xFFFFFFFF
end
function bit.rrotate (a, b)
return bit.lrotate(a, -b)
end
local function checkfield (f, w)
w = w or 1
assert(f >= 0, "field cannot be negative")
assert(w > 0, "width must be positive")
assert(f + w <= 32, "trying to access non-existent bits")
return f, ~(-1 << w)
end
function bit.extract (a, f, w)
local f, mask = checkfield(f, w)
return (a >> f) & mask
end
function bit.replace (a, v, f, w)
local f, mask = checkfield(f, w)
v = v & mask
a = (a & ~(mask << f)) | (v << f)
return a & 0xFFFFFFFF
end
return bit
end --}
print("testing bitwise library")
local bit32 = require'bit32'
assert(bit32.band() == bit32.bnot(0))
assert(bit32.btest() == true)
assert(bit32.bor() == 0)
assert(bit32.bxor() == 0)
assert(bit32.band() == bit32.band(0xffffffff))
assert(bit32.band(1,2) == 0)
-- out-of-range numbers
assert(bit32.band(-1) == 0xffffffff)
assert(bit32.band((1 << 33) - 1) == 0xffffffff)
assert(bit32.band(-(1 << 33) - 1) == 0xffffffff)
assert(bit32.band((1 << 33) + 1) == 1)
assert(bit32.band(-(1 << 33) + 1) == 1)
assert(bit32.band(-(1 << 40)) == 0)
assert(bit32.band(1 << 40) == 0)
assert(bit32.band(-(1 << 40) - 2) == 0xfffffffe)
assert(bit32.band((1 << 40) - 4) == 0xfffffffc)
assert(bit32.lrotate(0, -1) == 0)
assert(bit32.lrotate(0, 7) == 0)
assert(bit32.lrotate(0x12345678, 0) == 0x12345678)
assert(bit32.lrotate(0x12345678, 32) == 0x12345678)
assert(bit32.lrotate(0x12345678, 4) == 0x23456781)
assert(bit32.rrotate(0x12345678, -4) == 0x23456781)
assert(bit32.lrotate(0x12345678, -8) == 0x78123456)
assert(bit32.rrotate(0x12345678, 8) == 0x78123456)
assert(bit32.lrotate(0xaaaaaaaa, 2) == 0xaaaaaaaa)
assert(bit32.lrotate(0xaaaaaaaa, -2) == 0xaaaaaaaa)
for i = -50, 50 do
assert(bit32.lrotate(0x89abcdef, i) == bit32.lrotate(0x89abcdef, i%32))
end
assert(bit32.lshift(0x12345678, 4) == 0x23456780)
assert(bit32.lshift(0x12345678, 8) == 0x34567800)
assert(bit32.lshift(0x12345678, -4) == 0x01234567)
assert(bit32.lshift(0x12345678, -8) == 0x00123456)
assert(bit32.lshift(0x12345678, 32) == 0)
assert(bit32.lshift(0x12345678, -32) == 0)
assert(bit32.rshift(0x12345678, 4) == 0x01234567)
assert(bit32.rshift(0x12345678, 8) == 0x00123456)
assert(bit32.rshift(0x12345678, 32) == 0)
assert(bit32.rshift(0x12345678, -32) == 0)
assert(bit32.arshift(0x12345678, 0) == 0x12345678)
assert(bit32.arshift(0x12345678, 1) == 0x12345678 // 2)
assert(bit32.arshift(0x12345678, -1) == 0x12345678 * 2)
assert(bit32.arshift(-1, 1) == 0xffffffff)
assert(bit32.arshift(-1, 24) == 0xffffffff)
assert(bit32.arshift(-1, 32) == 0xffffffff)
assert(bit32.arshift(-1, -1) == bit32.band(-1 * 2, 0xffffffff))
assert(0x12345678 << 4 == 0x123456780)
assert(0x12345678 << 8 == 0x1234567800)
assert(0x12345678 << -4 == 0x01234567)
assert(0x12345678 << -8 == 0x00123456)
assert(0x12345678 << 32 == 0x1234567800000000)
assert(0x12345678 << -32 == 0)
assert(0x12345678 >> 4 == 0x01234567)
assert(0x12345678 >> 8 == 0x00123456)
assert(0x12345678 >> 32 == 0)
assert(0x12345678 >> -32 == 0x1234567800000000)
print("+")
-- some special cases
local c = {0, 1, 2, 3, 10, 0x80000000, 0xaaaaaaaa, 0x55555555,
0xffffffff, 0x7fffffff}
for _, b in pairs(c) do
assert(bit32.band(b) == b)
assert(bit32.band(b, b) == b)
assert(bit32.band(b, b, b, b) == b)
assert(bit32.btest(b, b) == (b ~= 0))
assert(bit32.band(b, b, b) == b)
assert(bit32.band(b, b, b, ~b) == 0)
assert(bit32.btest(b, b, b) == (b ~= 0))
assert(bit32.band(b, bit32.bnot(b)) == 0)
assert(bit32.bor(b, bit32.bnot(b)) == bit32.bnot(0))
assert(bit32.bor(b) == b)
assert(bit32.bor(b, b) == b)
assert(bit32.bor(b, b, b) == b)
assert(bit32.bor(b, b, 0, ~b) == 0xffffffff)
assert(bit32.bxor(b) == b)
assert(bit32.bxor(b, b) == 0)
assert(bit32.bxor(b, b, b) == b)
assert(bit32.bxor(b, b, b, b) == 0)
assert(bit32.bxor(b, 0) == b)
assert(bit32.bnot(b) ~= b)
assert(bit32.bnot(bit32.bnot(b)) == b)
assert(bit32.bnot(b) == (1 << 32) - 1 - b)
assert(bit32.lrotate(b, 32) == b)
assert(bit32.rrotate(b, 32) == b)
assert(bit32.lshift(bit32.lshift(b, -4), 4) == bit32.band(b, bit32.bnot(0xf)))
assert(bit32.rshift(bit32.rshift(b, 4), -4) == bit32.band(b, bit32.bnot(0xf)))
end
-- for this test, use at most 24 bits (mantissa of a single float)
c = {0, 1, 2, 3, 10, 0x800000, 0xaaaaaa, 0x555555, 0xffffff, 0x7fffff}
for _, b in pairs(c) do
for i = -40, 40 do
local x = bit32.lshift(b, i)
local y = math.floor(math.fmod(b * 2.0^i, 2.0^32))
assert(math.fmod(x - y, 2.0^32) == 0)
end
end
assert(not pcall(bit32.band, {}))
assert(not pcall(bit32.bnot, "a"))
assert(not pcall(bit32.lshift, 45))
assert(not pcall(bit32.lshift, 45, print))
assert(not pcall(bit32.rshift, 45, print))
print("+")
-- testing extract/replace
assert(bit32.extract(0x12345678, 0, 4) == 8)
assert(bit32.extract(0x12345678, 4, 4) == 7)
assert(bit32.extract(0xa0001111, 28, 4) == 0xa)
assert(bit32.extract(0xa0001111, 31, 1) == 1)
assert(bit32.extract(0x50000111, 31, 1) == 0)
assert(bit32.extract(0xf2345679, 0, 32) == 0xf2345679)
assert(not pcall(bit32.extract, 0, -1))
assert(not pcall(bit32.extract, 0, 32))
assert(not pcall(bit32.extract, 0, 0, 33))
assert(not pcall(bit32.extract, 0, 31, 2))
assert(bit32.replace(0x12345678, 5, 28, 4) == 0x52345678)
assert(bit32.replace(0x12345678, 0x87654321, 0, 32) == 0x87654321)
assert(bit32.replace(0, 1, 2) == 2^2)
assert(bit32.replace(0, -1, 4) == 2^4)
assert(bit32.replace(-1, 0, 31) == (1 << 31) - 1)
assert(bit32.replace(-1, 0, 1, 2) == (1 << 32) - 7)
-- testing conversion of floats
assert(bit32.bor(3.0) == 3)
assert(bit32.bor(-4.0) == 0xfffffffc)
-- large floats and large-enough integers?
if 2.0^50 < 2.0^50 + 1.0 and 2.0^50 < (-1 >> 1) then
assert(bit32.bor(2.0^32 - 5.0) == 0xfffffffb)
assert(bit32.bor(-2.0^32 - 6.0) == 0xfffffffa)
assert(bit32.bor(2.0^48 - 5.0) == 0xfffffffb)
assert(bit32.bor(-2.0^48 - 6.0) == 0xfffffffa)
end
print'OK'
| mit |
djkamran021/antispambot | plugins/setrank.lua | 40 | 8897 | do
local Dev = 122774063 --put your id here(BOT OWNER ID)
local function setrank(msg, name, value) -- setrank function
local hash = nil
if msg.to.type == 'chat' then
hash = 'rank:'..msg.to.id..':variables'
end
if hash then
redis:hset(hash, name, value)
return send_msg('chat#id'..msg.to.id, 'مقام کاربر ('..name..') به '..value..' تغییر داده شد ', ok_cb, true)
end
end
local function res_user_callback(extra, success, result) -- /info <username> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = 'ندارد'
end
local text = 'نام کامل : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'یوزر: '..Username..'\n'
..'ایدی کاربری : '..result.id..'\n\n'
local hash = 'rank:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(Dev) then
text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n'
elseif is_admin2(result.id) then
text = text..'مقام : ادمین ربات (Admin) \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'مقام : مدیر کل گروه (Owner) \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'مقام : مدیر گروه (Moderator) \n\n'
else
text = text..'مقام : کاربر (Member) \n\n'
end
else
text = text..'مقام : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n'
text = text..'SBSS Team'
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, extra.user..' نام کاربری مورد نظر یافت نشد.', ok_cb, false)
end
end
local function action_by_id(extra, success, result) -- /info <ID> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = 'ندارد'
end
local text = 'نام کامل : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'یوزر: '..Username..'\n'
..'ایدی کاربری : '..result.id..'\n\n'
local hash = 'rank:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(Dev) then
text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n'
elseif is_admin2(result.id) then
text = text..'مقام : ادمین ربات (Admin) \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'مقام : مدیر کل گروه (Owner) \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'مقام : مدیر گروه (Moderator) \n\n'
else
text = text..'مقام : کاربر (Member) \n\n'
end
else
text = text..'مقام : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n'
text = text..'SBSS Team'
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, 'ایدی شخص مورد نظر در سیستم ثبت نشده است.\nاز دستور زیر استفاده کنید\n/info @username', ok_cb, false)
end
end
local function action_by_reply(extra, success, result)-- (reply) /info function
if result.from.username then
Username = '@'..result.from.username
else
Username = 'ندارد'
end
local text = 'نام کامل : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n'
..'یوزر: '..Username..'\n'
..'ایدی کاربری : '..result.from.id..'\n\n'
local hash = 'rank:'..result.to.id..':variables'
local value = redis:hget(hash, result.from.id)
if not value then
if result.from.id == tonumber(Dev) then
text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n'
elseif is_admin2(result.from.id) then
text = text..'مقام : ادمین ربات (Admin) \n\n'
elseif is_owner2(result.from.id, result.to.id) then
text = text..'مقام : مدیر کل گروه (Owner) \n\n'
elseif is_momod2(result.from.id, result.to.id) then
text = text..'مقام : مدیر گروه (Moderator) \n\n'
else
text = text..'مقام : کاربر (Member) \n\n'
end
else
text = text..'مقام : '..value..'\n\n'
end
local user_info = {}
local uhash = 'user:'..result.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.from.id..':'..result.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n'
text = text..'SBSS Team'
send_msg(extra.receiver, text, ok_cb, true)
end
local function action_by_reply2(extra, success, result)
local value = extra.value
setrank(result, result.from.id, value)
end
local function run(msg, matches)
if matches[1]:lower() == 'setrank' then
local hash = 'usecommands:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
if not is_sudo(msg) then
return "Only for Sudo"
end
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
local value = string.sub(matches[2], 1, 1000)
msgr = get_message(msg.reply_id, action_by_reply2, {receiver=receiver, Reply=Reply, value=value})
else
local name = string.sub(matches[2], 1, 50)
local value = string.sub(matches[3], 1, 1000)
local text = setrank(msg, name, value)
return text
end
end
if matches[1]:lower() == 'آیدی' and not matches[2] then
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver, Reply=Reply})
else
if msg.from.username then
Username = '@'..msg.from.username
else
Username = 'ندارد'
end
local text = 'نام : '..(msg.from.first_name or 'ندارد')..'\n'
local text = text..'فامیل : '..(msg.from.last_name or 'ندارد')..'\n'
local text = text..'یوزر : '..Username..'\n'
local text = text..'ایدی کاربری : '..msg.from.id..'\n\n'
local hash = 'rank:'..msg.to.id..':variables'
if hash then
local value = redis:hget(hash, msg.from.id)
if not value then
if msg.from.id == tonumber(Dev) then
text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n'
elseif is_sudo(msg) then
text = text..'مقام : ادمین ربات (Admin) \n\n'
elseif is_owner(msg) then
text = text..'مقام : مدیر کل گروه (Owner) \n\n'
elseif is_momod(msg) then
text = text..'مقام : مدیر گروه (Moderator) \n\n'
else
text = text..'مقام : کاربر (Member) \n\n'
end
else
text = text..'مقام : '..value..'\n'
end
end
local uhash = 'user:'..msg.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..msg.from.id..':'..msg.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n'
if msg.to.type == 'chat' then
text = text..'نام گروه : '..msg.to.title..'\n'
text = text..'ایدی گروه : '..msg.to.id
end
text = text..'\n\nSBSS Team'
return send_msg(receiver, text, ok_cb, true)
end
end
if matches[1]:lower() == 'info' and matches[2] then
local user = matches[2]
local chat2 = msg.to.id
local receiver = get_receiver(msg)
if string.match(user, '^%d+$') then
user_info('user#id'..user, action_by_id, {receiver=receiver, user=user, text=text, chat2=chat2})
elseif string.match(user, '^@.+$') then
username = string.gsub(user, '@', '')
msgr = res_user(username, res_user_callback, {receiver=receiver, user=user, text=text, chat2=chat2})
end
end
end
return {
description = 'Know your information or the info of a chat members.',
usage = {
'!info: Return your info and the chat info if you are in one.',
'(Reply)!info: Return info of replied user if used by reply.',
'!info <id>: Return the info\'s of the <id>.',
'!info @<user_name>: Return the member @<user_name> information from the current chat.',
'!setrank <userid> <rank>: change members rank.',
'(Reply)!setrank <rank>: change members rank.',
},
patterns = {
"^(آیدی)$",
"^(آیدی) (.*)$",
"^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$",
"^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$",
},
run = run
}
end
| gpl-2.0 |
SherlockMe/basewars.1.1 | gamemode/modules/money.lua | 2 | 2697 | MODULE.Name = "Money"
MODULE.Author = "Q2F2, Ghosty and Tenrys"
MODULE.Credits = "Based on sh_money by Tenrys; https://github.com/Tenrys/tenrys-scripts/blob/master/lua/autorun/sh_money.lua"
local tag = "BaseWars.Money"
local tag_escaped = "basewars_money"
local PLAYER = debug.getregistry().Player
local function isPlayer(ply)
return (IsValid(ply) and ply:IsPlayer())
end
function MODULE:GetMoney(ply)
if SERVER then
local dirName = self:InitMoney(ply)
local money = tonumber(file.Read(tag_escaped .. "/" .. dirName .. "/money.txt", "DATA"))
return money
elseif CLIENT then
return tonumber(ply:GetNWString(tag)) or 0
end
end
PLAYER.GetMoney = Curry(MODULE.GetMoney)
if SERVER then
function MODULE:InitMoney(ply)
local dirName = isPlayer(ply) and ply:SteamID64() or (isstring(ply) and ply or nil)
if not file.IsDir(tag_escaped .. "/" .. dirName, "DATA") then file.CreateDir(tag_escaped .. "/" .. dirName) end
if not file.Exists(tag_escaped .. "/" .. dirName .. "/money.txt", "DATA") then file.Write(tag_escaped .. "/" .. dirName .. "/money.txt", tostring(BaseWars.Config.StartMoney)) end
file.Write(tag_escaped .. "/" .. dirName .. "/player.txt", ply:Name())
return dirName
end
PLAYER.InitMoney = Curry(MODULE.InitMoney)
for k, v in next,player.GetAll() do
MODULE:InitMoney(v)
end
function MODULE:SaveMoney(ply, amount)
local dirName = self:InitMoney(ply)
file.Write(tag_escaped .. "/" .. dirName .. "/money.txt", amount or self:GetMoney(ply))
end
PLAYER.SaveMoney = Curry(MODULE.SaveMoney)
function MODULE:LoadMoney(ply)
self:InitMoney(ply)
ply:SetNWString(tag, tostring(self:GetMoney(ply)))
end
PLAYER.LoadMoney = Curry(MODULE.LoadMoney)
function MODULE:SetMoney(ply, amount)
if not isnumber(amount) or amount < 0 then amount = 0 end
if amount > 2^63 then amount = 2^63 end
if amount ~= amount then amount = 0 end
amount = math.Round(amount)
self:SaveMoney(ply, amount)
ply:SetNWString(tag, tostring(amount))
end
PLAYER.SetMoney = Curry(MODULE.SetMoney)
function MODULE:GiveMoney(ply, amount)
self:SetMoney(ply, self:GetMoney(ply) + amount)
end
PLAYER.GiveMoney = Curry(MODULE.GiveMoney)
function MODULE:TakeMoney(ply, amount)
self:SetMoney(ply, self:GetMoney(ply) - amount)
end
PLAYER.TakeMoney = Curry(MODULE.TakeMoney)
function MODULE:TransferMoney(ply1, amount, ply2)
self:TakeMoney(ply1, amount)
self:GiveMoney(ply2, amount)
end
PLAYER.TransferMoney = Curry(MODULE.TransferMoney)
hook.Add("PlayerAuthed", tag .. ".Load", Curry(MODULE.LoadMoney))
hook.Add("PlayerDisconnected", tag .. ".Save", Curry(MODULE.SaveMoney))
end
| apache-2.0 |
NoriSilverrage/Revamped-Factorio-Machines | RFM-tweaks_1.1.4/prototypes/hardcrafting.lua | 1 | 7593 | data:extend({
{
type = "item",
name = "crusher-2",
icon = modname.."/graphics/icons/crusher-2.png",
flags = {"goes-to-quickbar"},
subgroup = "advanced-processing-machine",
order = "f",
place_result = "crusher-2",
enabled = false,
stack_size = 50
},
{
type = "item",
name = "crusher-3",
icon = modname.."/graphics/icons/crusher-3.png",
flags = {"goes-to-quickbar"},
subgroup = "advanced-processing-machine",
order = "f",
place_result = "crusher-3",
enabled = false,
stack_size = 50
},
-- {
-- type = "item",
-- name = "crusher-4",
-- icon = modname.."/graphics/icons/crusher-4.png",
-- flags = {"goes-to-quickbar"},
-- subgroup = "advanced-processing-machine",
-- order = "f",
-- place_result = "crusher-4",
-- enabled = false,
-- stack_size = 50
-- },
{
type = "item",
name = "pulverizer-2",
icon = "__hardCrafting__/graphics/icons/pulverizer.png",
flags = {"goes-to-quickbar"},
subgroup = "advanced-processing-machine",
order = "g",
place_result = "pulverizer-2",
enabled = false,
stack_size = 50
},
{
type = "item",
name = "pulverizer-3",
icon = "__hardCrafting__/graphics/icons/pulverizer.png",
flags = {"goes-to-quickbar"},
subgroup = "advanced-processing-machine",
order = "g",
place_result = "pulverizer-3",
enabled = false,
stack_size = 50
},
-- {
-- type = "item",
-- name = "pulverizer-4",
-- icon = "__hardCrafting__/graphics/icons/pulverizer.png",
-- flags = {"goes-to-quickbar"},
-- subgroup = "advanced-processing-machine",
-- order = "g",
-- place_result = "pulverizer-4",
-- enabled = false,
-- stack_size = 50
-- },
{
type = "recipe",
name = "crusher-2",
energy_required = 5,
enabled = "false",
ingredients =
{
{"crusher", 1},
{"iron-gear-wheel", 10},
{"electronic-circuit", 5}
},
result = "crusher-2"
},
{
type = "recipe",
name = "crusher-3",
energy_required = 5,
enabled = "false",
ingredients =
{
{"crusher-2", 1},
{"iron-gear-wheel", 10},
{"steel-plate", 3},
{"advanced-circuit", 5}
},
result = "crusher-3"
},
-- {
-- type = "recipe",
-- name = "crusher-4",
-- energy_required = 5,
-- enabled = "false",
-- ingredients =
-- {
-- {"crusher-3", 1},
-- {"iron-gear-wheel", 10},
-- {"processing-unit", 5},
-- {"steel-plate", 6}
-- },
-- result= "crusher-4"
-- },
{
type = "recipe",
name = "pulverizer-2",
energy_required = 5,
enabled = "false",
ingredients =
{
{"pulverizer", 1},
{"steel-plate",10},
{"iron-gear-wheel",15},
{"electronic-circuit",5}
},
result = "pulverizer-2"
},
{
type = "recipe",
name = "pulverizer-3",
energy_required = 5,
enabled = "false",
ingredients =
{
{"pulverizer-2", 1},
{"steel-plate",12},
{"iron-gear-wheel",15},
{"advanced-circuit", 5}
},
result = "pulverizer-3"
},
-- {
-- type = "recipe",
-- name = "pulverizer-4",
-- energy_required = 5,
-- enabled = "false",
-- ingredients =
-- {
-- {"pulverizer-3", 1},
-- {"steel-plate",15},
-- {"iron-gear-wheel",15},
-- {"processing-unit", 5},
-- },
-- result = "pulverizer-4"
-- }
})
-- Crusher Mk2 to Mk4 **************************************************************************
local crusher2 = table.deepcopy(data.raw["assembling-machine"]["crusher"])
crusher2.name = "crusher-2"
crusher2.energy_usage = "120kW"
crusher2.minable.result = "crusher-2"
crusher2.crafting_speed = 1.5
crusher2.fast_replaceable_group = "assembling-machine"
crusher2.icon = modname.."/graphics/icons/crusher-2.png"
crusher2.animation.filename=modname.."/graphics/entity/crusher/crusher-base-2.png"
data:extend({ crusher2 })
-- Mk 3
local crusher3 = table.deepcopy(data.raw["assembling-machine"]["crusher"])
crusher3.name = "crusher-3"
crusher3.energy_usage = "170kW"
crusher3.minable.result = "crusher-3"
crusher3.crafting_speed = 2
crusher3.module_specification =
{
module_slots = 3,
module_info_icon_shift = {0, 0.8}
}
crusher3.fast_replaceable_group = "assembling-machine"
crusher3.icon = modname.."/graphics/icons/crusher-3.png"
crusher3.animation.filename=modname.."/graphics/entity/crusher/crusher-base-3.png"
data:extend({ crusher3 })
---- Mk 4
--local crusher4 = table.deepcopy(data.raw["furnace"]["crusher"])
--crusher4.name = "crusher-4"
--crusher4.energy_usage = "210kW"
--crusher4.minable.result = "crusher-4"
--crusher4.crafting_speed = 3
--crusher4.module_specification =
-- {
-- module_slots = 4,
-- module_info_icon_shift = {0, 0.8}
-- }
--crusher4.fast_replaceable_group = "furnace"
--crusher4.icon = modname.."/graphics/icons/crusher-4.png"
--crusher4.animation.filename=modname.."/graphics/entity/crusher/crusher-base-4.png"
--data:extend({ crusher4 })
-- Pulverizer Mk2 and MK3 *************************************************************************
local pulverizer2 = table.deepcopy(data.raw["assembling-machine"]["pulverizer"])
pulverizer2.name = "pulverizer-2"
pulverizer2.energy_usage = "210kW"
pulverizer2.crafting_speed = 1.5
pulverizer2.minable.result = "pulverizer-2"
pulverizer2.fast_replaceable_group = "assembling-machine"
pulverizer2.animation.filename=modname.."/graphics/entity/crusher/crusher-base-2.png"
data:extend({ pulverizer2 })
-- Mk3
local pulverizer3 = table.deepcopy(data.raw["assembling-machine"]["pulverizer"])
pulverizer3.name = "pulverizer-3"
pulverizer3.energy_usage = "300kW"
pulverizer3.crafting_speed = 2
pulverizer3.minable.result = "pulverizer-3"
pulverizer3.fast_replaceable_group = "assembling-machine"
pulverizer3.module_specification =
{
module_slots = 3,
module_info_icon_shift = {0, 0.5},
module_info_multi_row_initial_height_modifier = -0.3
}
pulverizer3.fast_replaceable_group = "assembling-machine"
pulverizer3.animation.filename=modname.."/graphics/entity/crusher/crusher-base-3.png"
data:extend({ pulverizer3 })
---- Mk4
--local pulverizer4 = table.deepcopy(data.raw["assembling-machine"]["pulverizer"])
--pulverizer4.name = "pulverizer-4"
--pulverizer4.energy_usage = "370kW"
--pulverizer4.crafting_speed = 3
--pulverizer4.minable.result = "pulverizer-4"
--pulverizer4.fast_replaceable_group = "assembling-machine"
--pulverizer4.module_specification =
-- {
-- module_slots = 4,
-- module_info_icon_shift = {0, 0.5},
-- module_info_multi_row_initial_height_modifier = -0.3
-- }
--pulverizer4.fast_replaceable_group = "assembling-machine"
--pulverizer4.animation.filename=modname.."/graphics/entity/crusher/crusher-base-4.png"
--data:extend({ pulverizer4 })
table.insert(data.raw["technology"]["advanced-material-processing-2"].effects,{type="unlock-recipe",recipe="crusher-2"})
table.insert(data.raw["technology"]["advanced-material-processing-2"].effects,{type="unlock-recipe",recipe="pulverizer-2"})
table.insert(data.raw["technology"]["advanced-material-processing-3"].effects,{type="unlock-recipe",recipe="crusher-3"})
table.insert(data.raw["technology"]["advanced-material-processing-3"].effects,{type="unlock-recipe",recipe="pulverizer-3"})
--table.insert(data.raw["technology"]["advanced-material-processing-4"].effects,{type="unlock-recipe",recipe="crusher-4"})
--table.insert(data.raw["technology"]["advanced-material-processing-4"].effects,{type="unlock-recipe",recipe="pulverizer-4"}) | mit |
kmul00/nn | BCECriterion.lua | 12 | 2712 | local BCECriterion, parent = torch.class('nn.BCECriterion', 'nn.Criterion')
local eps = 1e-12
function BCECriterion:__init(weights, sizeAverage)
parent.__init(self)
if sizeAverage ~= nil then
self.sizeAverage = sizeAverage
else
self.sizeAverage = true
end
if weights ~= nil then
assert(weights:dim() == 1, "weights input should be 1-D Tensor")
self.weights = weights
end
end
function BCECriterion:__len()
if (self.weights) then
return #self.weights
else
return 0
end
end
function BCECriterion:updateOutput(input, target)
-- - log(input) * target - log(1 - input) * (1 - target)
assert( input:nElement() == target:nElement(),
"input and target size mismatch")
self.buffer = self.buffer or input.new()
local buffer = self.buffer
local weights = self.weights
local output
buffer:resizeAs(input)
if weights ~= nil and target:dim() ~= 1 then
weights = self.weights:view(1, target:size(2)):expandAs(target)
end
-- log(input) * target
buffer:add(input, eps):log()
if weights ~= nil then buffer:cmul(weights) end
output = torch.dot(target, buffer)
-- log(1 - input) * (1 - target)
buffer:mul(input, -1):add(1):add(eps):log()
if weights ~= nil then buffer:cmul(weights) end
output = output + torch.sum(buffer)
output = output - torch.dot(target, buffer)
if self.sizeAverage then
output = output / input:nElement()
end
self.output = - output
return self.output
end
function BCECriterion:updateGradInput(input, target)
-- - (target - input) / ( input (1 - input) )
-- The gradient is slightly incorrect:
-- It should have be divided by (input + eps) (1 - input + eps)
-- but it is divided by input (1 - input + eps) + eps
-- This modification requires less memory to be computed.
assert( input:nElement() == target:nElement(),
"input and target size mismatch")
self.buffer = self.buffer or input.new()
local buffer = self.buffer
local weights = self.weights
local gradInput = self.gradInput
if weights ~= nil and target:dim() ~= 1 then
weights = self.weights:view(1, target:size(2)):expandAs(target)
end
buffer:resizeAs(input)
-- - x ( 1 + eps -x ) + eps
buffer:add(input, -1):add(-eps):cmul(input):add(-eps)
gradInput:resizeAs(input)
-- y - x
gradInput:add(target, -1, input)
-- - (y - x) / ( x ( 1 + eps -x ) + eps )
gradInput:cdiv(buffer)
if weights ~= nil then
gradInput:cmul(weights)
end
if self.sizeAverage then
gradInput:div(target:nElement())
end
return gradInput
end
| bsd-3-clause |
georgerbr/gamecode4 | Assets/Scripts/TeapotStates.lua | 44 | 13650 | --========================================================================
-- ActorManager.lua : Defines all the states for an AI controlled teapot
--
-- Part of the GameCode4 Application
--
-- GameCode4 is the sample application that encapsulates much of the source code
-- discussed in "Game Coding Complete - 4th Edition" by Mike McShaffry and David
-- "Rez" Graham, published by Charles River Media.
-- ISBN-10: 1133776574 | ISBN-13: 978-1133776574
--
-- If this source code has found it's way to you, and you think it has helped you
-- in any way, do the authors a favor and buy a new copy of the book - there are
-- detailed explanations in it that compliment this code well. Buy a copy at Amazon.com
-- by clicking here:
-- http://www.amazon.com/gp/product/1133776574/ref=olp_product_details?ie=UTF8&me=&seller=
--
-- There's a companion web site at http://www.mcshaffry.com/GameCode/
--
-- The source code is managed and maintained through Google Code:
-- http://code.google.com/p/gamecode4/
--
-- (c) Copyright 2012 Michael L. McShaffry and David Graham
--
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser GPL v3
-- as published by the Free Software Foundation.
--
-- 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
-- http://www.gnu.org/licenses/lgpl-3.0.txt for more details.
--
-- You should have received a copy of the GNU Lesser GPL v3
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--
--========================================================================
-----------------------------------------------------------------------------------------------------------------------
-- TeapotState - Chapter 18, page 619
-- This is the base class for all Teapot states
-----------------------------------------------------------------------------------------------------------------------
TeapotState = class(nil,
{
_teapot = nil,
_teapotMoveSpeed = 5.25,
});
function TeapotState:Init()
if (self._teapot == nil) then
print("Invalid teapot in TeapotState");
return false;
end
return true;
end
function TeapotState:Update(deltaMs)
error("Calling unimplemented TeapotState.Update() fucntion");
end
-----------------------------------------------------------------------------------------------------------------------
-- PatrolState
-----------------------------------------------------------------------------------------------------------------------
PatrolState = class(TeapotState,
{
name = "PatrolState",
_patrolPoints =
{
Vec3:Create({ x = 20, y = 1, z = 20 }),
Vec3:Create({ x = -20, y = 1, z = 20 }),
};
_patrolPointIndex = 1;
_patrolSpeedMultiplier = 0.75;
_hasStartedRotation = false;
_hasFinishedRotating = false;
_angularAcceleration = 7;
_waitTimer = 0;
});
function PatrolState:Update(deltaMs)
if (self._waitTimer > 0) then
self._waitTimer = self._waitTimer - deltaMs;
return;
end
local teapotPos = Vec3:Create(self._teapot:GetPos());
local diff = self._patrolPoints[self._patrolPointIndex] - teapotPos;
if (not self._hasFinishedRotating) then
-- get necessary rotation
local targetOrientation = GccMath.GetYRotationFromVector(diff); -- this is the orientation we need to be at to face the player
local currOrientation = self._teapot:GetYOrientationRadians();
-- if we're not facing the right direction, start rotating if we haven't already
if (math.abs(targetOrientation - currOrientation) > 0.01) then
if (not self._hasStartedRotation) then
self._teapot:RotateY(targetOrientation);
self._targetOrientation = targetOrientation;
self._hasStartedRotation = true;
end
else
self._hasFinishedRotating = true;
end
else -- done rotating
-- grab the distance to the patrol point and see if we're already there
local distanceToPatrolPoint = diff:Length();
if (distanceToPatrolPoint < 0.1) then
self:GetNextPatrolPoint();
return;
end
-- not there yet so calculate the velocity vector, which provides direction and speed
local velocityVector = Vec3:Create(diff); -- clone the diff vector
velocityVector:Normalize();
local speed = (self._teapotMoveSpeed * self._patrolSpeedMultiplier) * (deltaMs / 1000);
velocityVector = velocityVector * speed;
-- if we're about to overshoot our desitination, adjust the velocity so that we land on it
if (velocityVector:Length() > distanceToPatrolPoint) then
velocityVector = diff;
end
-- send the event
teapotPos = teapotPos + velocityVector;
self._teapot:SetPosition(teapotPos.x, teapotPos.y, teapotPos.z);
end
end
function PatrolState:GetNextPatrolPoint()
-- update the patrol point index and wrap if necessary
self._patrolPointIndex = self._patrolPointIndex + 1;
if (self._patrolPointIndex > #self._patrolPoints) then
self._patrolPointIndex = 1;
end
-- reset rotation flags
self._hasStartedRotation = false;
self._hasFinishedRotating = false;
-- wait here for a bit
self._waitTimer = 1000;
end
-----------------------------------------------------------------------------------------------------------------------
-- AttackState
-----------------------------------------------------------------------------------------------------------------------
AttackState = class(TeapotState,
{
name = "AttackState",
_hasStartedRotating = false,
_targetOrientation = nil,
_weaponsRange = {15, 18},
_fireInterval = 1500,
_fireTimer = 0,
});
function AttackState:Init()
self.base.Init(self);
-- initialize target orientation to something reasonable
self._targetOrientation = self._teapot:GetYOrientationRadians();
end
function AttackState:Update(deltaMs)
-- update the fire timer
self._fireTimer = self._fireTimer + deltaMs;
-- get necessary rotation
local playerPos = Vec3:Create(g_actorMgr:GetPlayer():GetPos());
local teapotPos = Vec3:Create(self._teapot:GetPos());
local diff = playerPos - teapotPos;
local targetOrientation = GccMath.GetYRotationFromVector(diff); -- this is the orientation we need to be at to face the player
local currOrientation = self._teapot:GetYOrientationRadians();
-- see if we need to recalculate the rotation
if (math.abs(self._targetOrientation - targetOrientation) > 0.01) then
self._hasStartedRotation = false;
end
-- if we're not facing the right direction, start rotating if we haven't already
if (math.abs(targetOrientation - currOrientation) > 0.01) then
if (not self._hasStartedRotation) then
self._teapot:RotateY(targetOrientation);
self._targetOrientation = targetOrientation;
self._hasStartedRotation = true;
end
-- if we're already facing the right direction, pretend we rotated there
elseif (not self._hasStartedRotation) then
self._hasStartedRotation = true;
-- if we get here, we're done rotating
else
self._hasStartedRotation = false;
local distanceToPlayer = diff:Length();
diff:Normalize();
-- check to see if we're within firing range
if (distanceToPlayer >= self._weaponsRange[1] and distanceToPlayer <= self._weaponsRange[2]) then
self:_AttemptToFireWeapon();
-- not in range, so towards (or away from) then player
else
-- teapot is too close, back up
if (distanceToPlayer < self._weaponsRange[1]) then
diff = diff * -1;
end
local speed = self._teapotMoveSpeed * (deltaMs / 1000);
diff = diff * speed;
-- QueueEvent(EventType.EvtData_AiTranslate, {id = self._teapot:GetActorId(), distanceAndDirection = diff});
teapotPos = teapotPos + diff;
self._teapot:SetPosition(teapotPos.x, teapotPos.y, teapotPos.z);
end
end
end
function AttackState:_AttemptToFireWeapon()
if (self._fireTimer >= self._fireInterval) then
QueueEvent(EventType.EvtData_Fire_Weapon, {id = self._teapot:GetActorId()});
self._fireTimer = 0;
end
end
-----------------------------------------------------------------------------------------------------------------------
-- RunAwayState
-----------------------------------------------------------------------------------------------------------------------
RunAwayState = class(TeapotState,
{
name = "RunAwayState",
_runPoints =
{
Vec3:Create({ x = 25, y = 1, z = 25 }),
Vec3:Create({ x = -25, y = 1, z = 25 }),
Vec3:Create({ x = 25, y = 1, z = -25 }),
Vec3:Create({ x = -25, y = 1, z = -25 }),
},
_runPointIndex = 0;
_hasRotated = false;
_checkForBetterRunPointTimer = 0;
_checkForBetterRunPointFrequency = 2000; -- check for a better run point every 2 seconds
});
function RunAwayState:Init()
self.base.Init(self);
self:_FindRunPoint();
end
function RunAwayState:Update(deltaMs)
-- update the timer and see if it's time to check for a better run point
self._checkForBetterRunPointTimer = self._checkForBetterRunPointTimer + deltaMs;
if (self._checkForBetterRunPointTimer >= self._checkForBetterRunPointFrequency) then
self:_FindRunPoint();
self._checkForBetterRunPointTimer = 0;
end
-- grab the teapot position and the delta to the run point
local teapotPos = Vec3:Create(self._teapot:GetPos());
local diff = self._runPoints[self._runPointIndex] - teapotPos;
if (not self._hasRotated) then
local teapotPos = Vec3:Create(self._teapot:GetPos());
local diff = self._runPoints[self._runPointIndex] - teapotPos;
local targetOrientation = GccMath.GetYRotationFromVector(diff); -- this is the orientation we need to be at to face the player
local currOrientation = self._teapot:GetYOrientationRadians();
-- already facing the right way
if (math.abs(currOrientation - targetOrientation) < 0.01) then
self._hasRotated = true;
-- start rotating
else
self._teapot:RotateY(targetOrientation);
self._hasRotated = true;
end
return;
-- teapot has already started rotation so start moving
else
-- grab the distance to the run point and see if we're already there
local distanceToRunPoint = diff:Length();
if (distanceToRunPoint < 0.1) then
return;
end
-- not there yet so calculate the velocity vector, which provides direction and speed
local velocityVector = Vec3:Create(diff); -- clone the diff vector
velocityVector:Normalize();
local speed = self._teapotMoveSpeed * (deltaMs / 1000);
velocityVector = velocityVector * speed;
-- if we're about to overshoot our desitination, adjust the velocity so that we land on it
if (velocityVector:Length() > distanceToRunPoint) then
velocityVector = diff;
end
-- send the event
-- QueueEvent(EventType.EvtData_AiTranslate, {id = self._teapot:GetActorId(), distanceAndDirection = velocityVector});
teapotPos = teapotPos + velocityVector;
self._teapot:SetPosition(teapotPos.x, teapotPos.y, teapotPos.z);
end
end
function RunAwayState:_FindRunPoint()
local oldRunPoint = self._runPointIndex;
local playerPos = Vec3:Create(g_actorMgr:GetPlayer():GetPos());
-- find the furthest run point from the player
local bestDistance2 = nil;
for index, value in ipairs(self._runPoints) do
local diff = value - playerPos;
local distance2 = diff:Length2();
if (bestDistance2 == nil or distance2 > bestDistance2) then
self._runPointIndex = index;
bestDistance2 = distance2;
end
end
-- if we found a better run point, we need to rotate to the new point
if (self._runPointIndex ~= oldRunPoint) then
self._hasRotated = false;
end
return (self._runPointIndex ~= oldRunPoint);
end
-----------------------------------------------------------------------------------------------------------------------
-- WatchPlayerState (for debugging)
-----------------------------------------------------------------------------------------------------------------------
WatchPlayerState = class(TeapotState,
{
name = "WatchPlayerState"
});
function WatchPlayerState:Init()
self.base.Init(self);
end
function WatchPlayerState:Update(deltaMs)
-- grab the teapot position and the delta to the run point
local teapotPos = Vec3:Create(self._teapot:GetPos());
local playerPos = Vec3:Create(g_actorMgr:GetPlayer():GetPos());
local diff = playerPos - teapotPos;
local targetOrientation = GccMath.GetYRotationFromVector(diff); -- this is the orientation we need to be at to face the player
self._teapot:RotateY(targetOrientation);
end
-----------------------------------------------------------------------------------------------------------------------
-- RotateState (for debugging)
-----------------------------------------------------------------------------------------------------------------------
RotateState = class(TeapotState,
{
name = "RotateState"
});
function RotateState:Init()
self.base.Init(self);
self._teapot:RotateY(0);
self._nextOrientation = 0.5;
self._delayTime = 5000;
self._timer = self._delayTime;
end
function RotateState:Update(deltaMs)
-- update timer
if (self._timer > 0) then
self._timer = self._timer - deltaMs;
return;
end
self._timer = self._delayTime;
self._teapot:RotateY(self._nextOrientation);
self._nextOrientation = self._nextOrientation + 0.5;
GccMath.WrapPi(self._nextOrientation);
end
| lgpl-3.0 |
17twenty/sysdig | userspace/sysdig/chisels/topfiles_errors.lua | 1 | 1131 | --[[
Copyright (C) 2013-2014 Draios inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
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/>.
--]]
-- Chisel description
description = "Shows the top files in terms of I/O errros."
short_description = "top files by number of errors"
category = "errors"
-- Chisel argument list
args = {}
-- The number of items to show
TOP_NUMBER = 10
-- Argument notification callback
function on_set_arg(name, val)
return false
end
-- Initialization callback
function on_init()
chisel.exec("table_generator",
"fd.name",
"Filename",
"evt.count",
"#Errors",
"fd.type=file and evt.failed=true",
"100",
"none")
return true
end
| gpl-2.0 |
kmul00/nn | SpatialConvolution.lua | 2 | 5080 | local THNN = require 'nn.THNN'
local SpatialConvolution, parent = torch.class('nn.SpatialConvolution', 'nn.Module')
function SpatialConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padW, padH)
parent.__init(self)
dW = dW or 1
dH = dH or 1
self.nInputPlane = nInputPlane
self.nOutputPlane = nOutputPlane
self.kW = kW
self.kH = kH
self.dW = dW
self.dH = dH
self.padW = padW or 0
self.padH = padH or self.padW
self.weight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW)
self.bias = torch.Tensor(nOutputPlane)
self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kH, kW)
self.gradBias = torch.Tensor(nOutputPlane)
self:reset()
end
function SpatialConvolution:noBias()
self.bias = nil
self.gradBias = nil
return self
end
function SpatialConvolution:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane)
end
if nn.oldSeed then
self.weight:apply(function()
return torch.uniform(-stdv, stdv)
end)
if self.bias then
self.bias:apply(function()
return torch.uniform(-stdv, stdv)
end)
end
else
self.weight:uniform(-stdv, stdv)
if self.bias then
self.bias:uniform(-stdv, stdv)
end
end
end
local function backCompatibility(self)
self.finput = self.finput or self.weight.new()
self.fgradInput = self.fgradInput or self.weight.new()
if self.padding then
self.padW = self.padding
self.padH = self.padding
self.padding = nil
else
self.padW = self.padW or 0
self.padH = self.padH or 0
end
if self.weight:dim() == 2 then
self.weight = self.weight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW)
end
if self.gradWeight and self.gradWeight:dim() == 2 then
self.gradWeight = self.gradWeight:view(self.nOutputPlane, self.nInputPlane, self.kH, self.kW)
end
end
local function makeContiguous(self, input, gradOutput)
if not input:isContiguous() then
self._input = self._input or input.new()
self._input:resizeAs(input):copy(input)
input = self._input
end
if gradOutput then
if not gradOutput:isContiguous() then
self._gradOutput = self._gradOutput or gradOutput.new()
self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
gradOutput = self._gradOutput
end
end
return input, gradOutput
end
function SpatialConvolution:updateOutput(input)
assert(input.THNN, torch.type(input)..'.THNN backend not imported')
backCompatibility(self)
input = makeContiguous(self, input)
input.THNN.SpatialConvolutionMM_updateOutput(
input:cdata(),
self.output:cdata(),
self.weight:cdata(),
THNN.optionalTensor(self.bias),
self.finput:cdata(),
self.fgradInput:cdata(),
self.kW, self.kH,
self.dW, self.dH,
self.padW, self.padH
)
return self.output
end
function SpatialConvolution:updateGradInput(input, gradOutput)
assert(input.THNN, torch.type(input)..'.THNN backend not imported')
if self.gradInput then
backCompatibility(self)
input, gradOutput = makeContiguous(self, input, gradOutput)
input.THNN.SpatialConvolutionMM_updateGradInput(
input:cdata(),
gradOutput:cdata(),
self.gradInput:cdata(),
self.weight:cdata(),
self.finput:cdata(),
self.fgradInput:cdata(),
self.kW, self.kH,
self.dW, self.dH,
self.padW, self.padH
)
return self.gradInput
end
end
function SpatialConvolution:accGradParameters(input, gradOutput, scale)
assert(input.THNN, torch.type(input)..'.THNN backend not imported')
scale = scale or 1
backCompatibility(self)
input, gradOutput = makeContiguous(self, input, gradOutput)
input.THNN.SpatialConvolutionMM_accGradParameters(
input:cdata(),
gradOutput:cdata(),
self.gradWeight:cdata(),
THNN.optionalTensor(self.gradBias),
self.finput:cdata(),
self.fgradInput:cdata(),
self.kW, self.kH,
self.dW, self.dH,
self.padW, self.padH,
scale
)
end
function SpatialConvolution:type(type,tensorCache)
self.finput = self.finput and torch.Tensor()
self.fgradInput = self.fgradInput and torch.Tensor()
return parent.type(self,type,tensorCache)
end
function SpatialConvolution:__tostring__()
local s = string.format('%s(%d -> %d, %dx%d', torch.type(self),
self.nInputPlane, self.nOutputPlane, self.kW, self.kH)
if self.dW ~= 1 or self.dH ~= 1 or self.padW ~= 0 or self.padH ~= 0 then
s = s .. string.format(', %d,%d', self.dW, self.dH)
end
if (self.padW or self.padH) and (self.padW ~= 0 or self.padH ~= 0) then
s = s .. ', ' .. self.padW .. ',' .. self.padH
end
if self.bias then
return s .. ')'
else
return s .. ') without bias'
end
end
function SpatialConvolution:clearState()
nn.utils.clear(self, 'finput', 'fgradInput', '_input', '_gradOutput')
return parent.clearState(self)
end
| bsd-3-clause |
ufoai/ufoai | base/ufos/ui/initialsettings.lua | 2 | 5931 | --!usr/bin/lua
--[[
-- @file
-- @brief Initial settings popup
--]]
--[[
Copyright (C) 2002-2020 UFO: Alien Invasion.
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--]]
if (initialsettings == nil) then
require("ufox.lua")
initialsettings = {}
initialsettings.check = function ()
local cl_name = ufo.getvar("cl_name")
if (cl_name == nil or cl_name:as_string() == "") then
return false
end
local s_language = ufo.getvar("s_language")
if (s_language == nil or s_language:as_string() == "") then
return false
end
return true
end
initialsettings.build = function ()
local settings = ufox.build_window({
name = "initial_settings",
class = "window",
super = "ipopup",
modal = true,
preventtypingescape = true,
pos = {124, 192},
size = {777, 368},
backgroundcolor = {0, 0, 0, 0.9},
validate_form = function (sender)
local valid = true
local ok_button = sender:child("ok")
local username = ufo.getvar("cl_name")
local username_field = sender:child("username")
if (username == nil or string.match(username:as_string(), "^[ \t\r\n]*$")) then
username_field:set_bordersize(2)
username_field:set_tooltip("_Player name cannot be empty")
valid = false
else
username_field:set_bordersize(0)
username_field:set_tooltip("")
end
local language = ufo.getvar("s_language")
local language_field = sender:child("language_select")
if (language == nil or string.match(language:as_string(), "^\s*$")) then
language_field:set_bordersize(2)
language_field:set_tooltip("_Please select your preferred language")
valid = false
else
language_field:set_bordersize(0)
language_field:set_tooltip("")
end
ok_button:set_disabled(not valid)
return valid
end,
{
name = "title",
text = "_Initial settings",
size = {777, 30},
},
-- USER INFORMATION
{
name = "userinfo_label",
class = "string",
text = "_User information",
pos = {26, 48},
size = {300, 30},
font = "f_normal",
},
{
name = "username_label",
class = "string",
text = "_Name:",
pos = {41, 88},
size = {300, 20},
color = {1, 1, 1, 1},
},
{
name = "username",
class = "textentry",
text = "*cvar:cl_name",
font = "f_verysmall",
pos = {170, 82},
size = {185, 34},
backgroundcolor = {0, 0, 0, 0.5},
bordercolor = {1, 0, 0, 1},
bordersize = 0,
on_keyreleased = function (sender)
sender:root():validate_form()
end,
},
-- VOLUME SETTINGS
{
name = "volume_str",
class = "string",
text = "_Volume Control",
pos = {26, 218},
size = {390, 25},
font = "f_normal",
},
{
name = "effects_str",
class = "string",
text = "_Effects:",
pos = {41, 248},
size = {150, 20},
},
{
name = "effects_bar",
class = "bar",
value = "*cvar:snd_volume",
pos = {170, 258},
size = {238, 6},
color = {0.582, 0.808, 0.758, 1},
bordercolor = {0.582, 0.808, 0.758, 1},
bordersize = 1,
max = 1.0,
},
{
name = "music_str",
class = "string",
text = "_Music:",
pos = {41, 273},
size = {150, 20},
},
{
name = "music_bar",
class = "bar",
value = "*cvar:snd_music_volume",
pos = {170, 283},
size = {238, 6},
color = {0.582, 0.808, 0.758, 1},
bordercolor = {0.582, 0.808, 0.758, 1},
bordersize = 1,
max = 128.0,
},
-- LANGUAGE
{
name = "language_settings",
class = "string",
text = "_Language",
pos = {460, 48},
size = {300, 25},
font = "f_normal",
},
{
-- @TODO eliminate optionlists
name = "language_select",
class = "optionlist",
pos = {461, 78},
size = {275, 226},
font = "f_language",
--background = "ui/panel",
color = {1, 1, 1, 0.5},
selectcolor = {1, 1, 1, 0.9},
backgroundcolor = {0, 0, 0, 0.5},
bordercolor = {1, 0, 0, 1},
bordersize = 0,
padding = 6,
contentalign = ufo.ALIGN_CC,
dataid = ufo.OPTION_LANGUAGES,
cvar = "*cvar:s_language",
on_change = function (sender)
sender:root():validate_form()
end,
on_viewchange = function (sender)
sender:root():child("language_select_scroll"):set_current(sender:current())
sender:root():child("language_select_scroll"):set_fullsize(sender:fullsize())
sender:root():child("language_select_scroll"):set_viewsize(sender:viewsize())
end,
},
{
name = "language_select_scroll",
class = "vscrollbar",
pos = {742, 78},
height = 226,
viewsize = 8,
fullsize = 21,
current = 0,
image = "ui/scrollbar_v",
on_change = function (sender)
sender:root():child("language_select"):set_current(sender:current())
end,
},
{
name = "message",
class = "string",
text = "_You have to set the playername and hit the 'OK' button:",
pos = {41, 338},
size = {500, 20},
color = {1, 1, 1, 0.5},
},
{
name = "ok",
class = "MainMenuBtn",
text = "_OK",
tooltip = "_Save settings",
pos = {547, 338},
size = {230, 30},
on_click = function (sender)
ufo.cmd("saveconfig config.cfg;")
ufo.pop_window(false)
end,
},
{
class = "fuzzyScreen",
name = "overlay",
},
on_windowopened = function (sender)
sender:validate_form()
end,
on_windowclosed = function (sender)
sender:delete_node()
end,
})
return settings
end
end
| gpl-2.0 |
DuanWeiye/rpiBot | Others/Arduino_Code/TempWebServer/main.lua | 1 | 3857 | #!/usr/bin/lua
--HTTP header
print [[
Content-Type: text/plain
]]
warningTemperature = 40
successReturnText = "succ_ardu_openwrt"
localLogPath = "/mnt/web/data/node_"
globalLogPath = "/mnt/web/data/global.log"
mailList = "/mnt/web/data/mail.list"
mailTempPath = "/tmp/warning.mail"
maskCode = "ArduinoEnvNode"
function Split(str, delim, maxNb)
if string.find(str, delim) == nil then
return { str }
end
if maxNb == nil or maxNb < 1 then
maxNb = 0
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gfind(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
if nb == maxNb then break end
end
if nb ~= maxNb then
result[nb + 1] = string.sub(str, lastPos)
end
return result
end
function GetPing(target)
local ret, retText, retNumber, popen = nil, nil, 0, io.popen
retText = popen('ping -W 1 -c 3 -w 3 ' .. target ..' | grep -m 1 "min/avg/max" | cut -d " " -f 4 | cut -d "/" -f 2'):read()
if retText ~= nil then
retNumber = math.ceil(10 * tonumber(retText))
ret = retNumber
else
ret = '0'
end
return ret
end
function SendMail()
local globalLog = io.open(globalLogPath, "a+")
for line in globalLog:lines() do
if line ~= nil then
local globalData = Split(line, "|", nil)
if globalData[4] == data[2] and globalData[1] == lTimeDate and globalData[2] == lTimeHour then
print("Giveup SendMail\n")
do return end
end
end
end
globalLog:write(nowText)
globalLog:close()
local mailFile = io.open(mailTempPath, "w")
mailFile:write("From: Environment Monitor <admin@brainexplode.com>\n")
mailFile:write("To: Administrator\n")
mailFile:write("Subject: Environment Warning\n\n")
mailFile:write("\n")
mailFile:write("Time: " .. lTimeMail .. "\n")
mailFile:write("Node IP: " .. data[2] .. "\n")
mailFile:write("Node Avg.Ping: " .. lAvgPing .. "\n")
mailFile:write("Temperature: " .. data[3] .. " C\n")
mailFile:write("Humidity: " .. data[4] .. " %\n")
mailFile:write("\n")
mailFile:close()
local mailTo = io.open(mailList, "r")
for line in mailTo:lines() do
if line ~= nil then
print("SendMail To: " .. line .. "\n")
local cmdText = string.format("cat %s | sendmail %s", mailTempPath, line)
os.execute(cmdText)
end
end
mailTo:close()
end
function main()
parameter = os.getenv("QUERY_STRING")
if parameter ~= nil then
data = Split(parameter, ",", nil)
if table.getn(data) == 4 then
if data[1] == maskCode then
print(successReturnText)
-- [2014/05/09|08|30|192.168.1.1|30|20|120]
lTimeMail = os.date("%Y/%m/%d %H:%M:%S", time)
lTimeDate = os.date("%Y/%m/%d", time)
lTimeHour = os.date("%H", time)
lTimeMinute = os.date("%M", time)
lAvgPing = GetPing(data[2])
nowText = lTimeDate .. "|" .. lTimeHour .. "|" .. lTimeMinute .. "|" .. data[2] .. "|" .. data[3] .. "|" .. data[4] .. "|" .. lAvgPing .. "\n"
local logFile = io.open(localLogPath .. data[2], "a+")
local last2Text = nil
local last1Text = nil
for line in logFile:lines() do
if line ~= nil then
last2Text = last1Text
last1Text = line
end
end
if last1Text == nil or last2Text == nil then
print("WriteLog\n")
logFile:write(nowText)
else
local last2Data = Split(last2Text, "|", nil)
local last1Data = Split(last1Text, "|", nil)
if last1Data[1] ~= lTimeDate or last1Data[2] ~= lTimeHour or last1Data[3] ~= lTimeMinute then
print("WriteLog\n")
logFile:write(nowText)
end
end
logFile:close()
if last2Data[1] == lTimeDate and last1Data[1] == lTimeDate and tonumber(last2Data[5]) >= warningTemperature and tonumber(last1Data[5]) >= warningTemperature and tonumber(data[3]) >= warningTemperature then
SendMail()
end
end
end
end
end
main()
| mit |
tederis/mta-resources | papi/postprocess_client.lua | 1 | 4952 | --[[
Postprocess & XRAY & 30.06.2012
Эффекты постпроцессинга:
-Add color(оттенок изображения)
-Base color
-Gray color(насыщенность)
-Duality(раздвоение изображения)
-Noise(шум)
-Blur(размытие изображения)
-ColorMapper
Постэффекты можно анимировать посредством ключей
]]
sw, sh = guiGetScreenSize ( )
Postprocess = {
shader = dxCreateShader ( "shaders/noise.fx" ),
screenSource = dxCreateScreenSource ( sw, sh )
}
Postprocess.__index = Postprocess
dxSetShaderValue ( Postprocess.shader, "Tex0", Postprocess.screenSource )
function Postprocess.create ( effector )
if Postprocess.effector then
removeEventHandler ( "onClientRender", root, Postprocess.draw )
end
--Инициализируем эффектор
Postprocess.initEffector ( effector )
--Разрешаем приступить к работе
Postprocess.effector = effector
addEventHandler ( "onClientRender", root, Postprocess.draw )
end
function Postprocess.initEffector ( effector )
local now = getTickCount ( )
for _, set in pairs ( effector ) do
set.progress = 0
set.startTime = now
set.point = 1
end
if effector.noise then
noise.create ( )
end
end
function Postprocess.draw ( )
local now = getTickCount ( )
for name, set in pairs ( Postprocess.effector ) do
local progress = 1
if set.point > 1 then
local elapsedTime = now - set.startTime
local duration = set [ set.point ] [ 1 ] - set [ set.point - 1 ] [ 1 ]
progress = elapsedTime / duration
end
local point = set [ set.point ]
local prevPoint = set.point > 1 and set [ set.point - 1 ] or point
if name == "grayColor" then
local grayIntensity = math.slerp ( prevPoint [ 5 ], point [ 5 ], progress )
dxSetShaderValue ( Postprocess.shader, "grayColor", 0.3, 0.3, 0.3, (1-grayIntensity)/1 )
elseif name == "noise" then
local noiseIntensity = math.slerp ( prevPoint [ 3 ], point [ 3 ], progress )
noise.setIntensity ( (1-noiseIntensity)/1 )
end
dxUpdateScreenSource ( Postprocess.screenSource )
dxDrawImage ( 0, 0, sw, sh, Postprocess.shader, 0, 0, 0, tocolor ( 255 * 0.15, 255 * 0.25, 255 * 0.25, 255 ) )
if progress >= 1 then
set.point = set.point + 1
if set.point > #set then
set.point = 1
end
--set.point = math.min ( set.point + 1, #set )
--set.point = set.point + 1
set.startTime = now
--if set.point > #set then
--removeEventHandler ( "onClientRender", root, Postprocess.draw )
--end
end
end
end
---------------------------------
--Noise
---------------------------------
noise = {
lastUpdate = getTickCount ( ),
frame = 1,
rate = 24,
sequence = {
"textures/noise/ui_noise_00.dds",
"textures/noise/ui_noise_01.dds",
"textures/noise/ui_noise_02.dds",
"textures/noise/ui_noise_03.dds",
"textures/noise/ui_noise_04.dds",
"textures/noise/ui_noise_03.dds",
"textures/noise/ui_noise_01.dds",
"textures/noise/ui_noise_02.dds",
"textures/noise/ui_noise_00.dds",
"textures/noise/ui_noise_03.dds",
"textures/noise/ui_noise_04.dds"
}
}
function noise.create ( )
if noise.textures then
return
end
noise.frame = 1
noise.textures = { }
for i, filepath in ipairs ( noise.sequence ) do
noise.textures [ i ] = dxCreateTexture ( filepath )
end
addEventHandler ( "onClientRender", root, noise.update )
end
function noise.abort ( )
if not noise.textures then
return
end
for _, texture in ipairs ( noise.textures ) do
destroyElement ( texture )
end
noise.textures = nil
removeEventHandler ( "onClientRender", root, noise.update )
end
function noise.setIntensity ( intensity )
dxSetShaderValue ( Postprocess.shader, "NoiseIntensity", intensity )
end
function noise.update ( )
local now = getTickCount ( )
if now - noise.lastUpdate > noise.rate then
dxSetShaderValue ( Postprocess.shader, "NoiseTex", noise.textures [ noise.frame ] )
noise.frame = noise.frame + 1
if noise.frame > #noise.sequence then
noise.frame = 1
end
noise.lastUpdate = now
end
end
local electra = {
--r, g, b
--addColor = {
--TODO
--},
--r, g, b
baseColor = {
{ 0, 0.15, 0.25, 0.25 }
},
--r, g, b, intensity
grayColor = {
{ 0, 0, 0, 0, 0.50 },
{ 3000, 0, 0, 0, 0.85 },
{ 6000, 0, 0, 0, 0.50 }
},
--h, v
duality = {
{ 0, 0, 0 },
{ 2000, 0, 0 }
},
--intensity, grain, fps
noise = {
{ 0, 1, 0.20, 30 },
{ 3000, 1, 0.50, 8 },
{ 6000, 1, 0.20, 15 }
},
--r, g, b, intensity
blur = {
{ 0, 0, 0, 0, 0.50 },
{ 3000, 0, 0, 0, 0.85 },
{ 6000, 0, 0, 0, 0.50 }
},
--influence
--colorMapper = {
--TODO
--}
}
--Postprocess.create ( electra ) | gpl-3.0 |
htx/mmoserver | data/script/TatooineNpcTest.lua | 4 | 9195 | -- Tatooine NPC test
-- This script will not start until Zoneserver is ready.
-- math.pi
local MM = require 'Script/TatooineNpcTest2'
local baseUpdateTime = 750
-- local spawnPosX = -1197
local spawnPosX = -1325.0
local defaultYPos = 12
-- local spawnPosZ = -3561
local spawnPosZ = -3657.0
local spawnPos1X = -1212
local spawnPos1Z = -3557
local spawnPos2X = -1221
local spawnPos2Z = -3567
local spawnPos3X = -1208
local spawnPos3Z = -3578.5
local spawnPos4X = -1220
local spawnPos4Z = -3593
local spawnPos5X = -1231
local spawnPos5Z = -3606
local spawnPos6X = -1219
local spawnPos6Z = -3615
local spawnPos7X = -1209
local spawnPos7Z = -3615
-- Turn place
local spawnPos8X = -1205
local spawnPos8Z = -3612
local spawnPos9X = -1220
local spawnPos9Z = -3634
local spawnPos10X = -1229
local spawnPos10Z = -3644
local spawnPos11X = -1284
local spawnPos11Z = -3617
local spawnPos12X = -1365
local spawnPos12Z = -3723
local spawnPos13X = -1371
local spawnPos13Z = -3747
local spawnPosA1X = -1211
local spawnPosA1Z = -3603
local spawnPosA2X = -1215
local spawnPosA2Z = -3604
local spawnPosA3X = -1222
local spawnPosA3Z = -3613
local spawnPosA4X = -1246
local spawnPosA4Z = -3621
local spawnPosA5X = -1275
local spawnPosA5Z = -3600
local spawnPosA6X = -1275
local spawnPosA6Z = -3596
local spawnPosA7X = -1267
local spawnPosA7Z = -3580
local spawnPosA8X = -1289
local spawnPosA8Z = -3592
local spawnPosA9X = -1288
local spawnPosA9Z = -3566
local spawnPosA10X = -1243
local spawnPosA10Z = -3551
local spawnPosB1X = -1413
local spawnPosB1Z = -3770
local spawnPosB2X = -1427
local spawnPosB2Z = -3767.5
local spawnPosB3X = -1417
local spawnPosB3Z = -3774
local spawnPosB4X = -1414
local spawnPosB4Z = -3737
local spawnPosB5X = -1345
local spawnPosB5Z = -3687
local spawnPosB6X = -1348
local spawnPosB6Z = -3666
local spawnPosB7X = -1318
local spawnPosB7Z = -3663
-- formula for moving
-- x = new x position - current x position
-- z = new z position - current z position
-- deltaX = x/h , where h is the length to travel.
-- deltaZ = z/h , where h is the length to travel.
-- Adjust the base speed time for any increased length due to the truncation above.
-- updateTime = baseUpdateTime * (h /getIntOf(h))
local xPos = spawnPosX;
local yPos = defaultYPos;
local zPos = spawnPosZ;
local ss
local npc
local routeTab = { };
local posTab = { };
-- Functions
local getLength = function(x, z)
return math.sqrt((x * x) + (z * z));
end
local getIntOf = function(length)
i, f = math.modf(length);
return i;
end
local moveTo = function(newPosX, newPosY, newPosZ)
local x = newPosX - xPos;
local z = newPosZ - zPos;
local h = getLength(x, z);
local i = getIntOf(h);
local deltaX = x/i;
local deltaZ = z/i;
local updateTime = baseUpdateTime * (h /i);
ss:npcDirection(npc, x, z);
-- print("Tatooine test NPC is moving a distance of " .. (h /i) .. " m every" .. updateTime .. " ms");
for count = 1,i do
xPos = xPos + deltaX;
zPos = zPos + deltaZ;
-- print("Moving to " .. xPos .. ", " .. zPos)
ss:npcMove(npc, xPos , yPos, zPos );
LuaScriptEngine.WaitMSec(updateTime);
end;
end;
routeA6ToB2 = function()
moveTo(spawnPosB1X, yPos, spawnPosB1Z);
moveTo(spawnPosB2X, yPos, spawnPosB2Z);
end;
routeB2ToA6 = function()
moveTo(spawnPosB3X, yPos, spawnPosB3Z);
moveTo(spawnPosB4X, yPos, spawnPosB4Z);
moveTo(spawnPosB5X, yPos, spawnPosB5Z);
moveTo(spawnPosB6X, yPos, spawnPosB6Z);
moveTo(spawnPosB7X, yPos, spawnPosB7Z);
moveTo(spawnPosA6X, yPos, spawnPosA6Z);
end;
routeA6ToA9 = function()
moveTo(spawnPosA8X, yPos, spawnPosA8Z);
moveTo(spawnPosA9X, yPos, spawnPosA9Z);
end;
routeA6ToA7 = function()
moveTo(spawnPosA7X, yPos, spawnPosA7Z);
end;
routeA6ToX5 = function()
moveTo(spawnPosA5X, yPos, spawnPosA5Z);
moveTo(spawnPosA4X, yPos, spawnPosA4Z);
moveTo(spawnPos5X, yPos, spawnPos5Z);
end;
routeA9ToA6 = function()
moveTo(spawnPosA8X, yPos, spawnPosA8Z);
moveTo(spawnPosA6X, yPos, spawnPosA6Z);
end;
routeA7ToA9 = function()
moveTo(spawnPosA9X, yPos, spawnPosA9Z);
end;
routeA9ToA7 = function()
moveTo(spawnPosA7X, yPos, spawnPosA7Z);
end;
routeA7ToA6 = function()
moveTo(spawnPosA6X, yPos, spawnPosA6Z);
end;
routeA7ToX2 = function()
moveTo(spawnPosA10X, yPos, spawnPosA10Z);
moveTo(spawnPos2X, yPos, spawnPos2Z);
end;
routeX2ToX1 = function()
moveTo(spawnPos1X, yPos, spawnPos1Z);
end;
routeX1ToX2 = function()
moveTo(spawnPos2X, yPos, spawnPos2Z);
end;
routeX2ToX5 = function()
moveTo(spawnPos3X, yPos, spawnPos3Z);
moveTo(spawnPos4X, yPos, spawnPos4Z);
moveTo(spawnPos5X, yPos, spawnPos5Z);
end;
routeX2ToA7 = function()
moveTo(spawnPosA10X, yPos, spawnPosA10Z);
moveTo(spawnPosA7X, yPos, spawnPosA7Z);
end;
routeX5ToX8 = function()
moveTo(spawnPos6X, yPos, spawnPos6Z);
moveTo(spawnPos7X, yPos, spawnPos7Z);
moveTo(spawnPos8X, yPos, spawnPos8Z);
end;
routeX5ToX2 = function()
moveTo(spawnPos4X, yPos, spawnPos4Z);
moveTo(spawnPos3X, yPos, spawnPos3Z);
moveTo(spawnPos2X, yPos, spawnPos2Z);
end;
routeX5ToA6 = function()
moveTo(spawnPosA4X, yPos, spawnPosA4Z);
moveTo(spawnPosA5X, yPos, spawnPosA5Z);
moveTo(spawnPosA6X, yPos, spawnPosA6Z);
end;
-- New
routeX8ToX5 = function()
moveTo(spawnPosA1X, yPos, spawnPosA1Z);
moveTo(spawnPosA2X, yPos, spawnPosA2Z);
moveTo(spawnPosA3X, yPos, spawnPosA3Z);
moveTo(spawnPos5X, yPos, spawnPos5Z);
end;
routeX8ToB2 = function()
moveTo(spawnPos9X, yPos, spawnPos9Z);
moveTo(spawnPos10X, yPos, spawnPos10Z);
moveTo(spawnPos11X, yPos, spawnPos11Z);
moveTo(spawnPos12X, yPos, spawnPos12Z);
moveTo(spawnPos13X, yPos, spawnPos13Z);
moveTo(spawnPosB1X, yPos, spawnPosB1Z);
moveTo(spawnPosB2X, yPos, spawnPosB2Z);
end;
local routeSelection = function(destTab, prevPos)
local index = 0;
while (index == 0) do
local rand = math.random();
-- print("Random value is " .. rand );
if rand <= 0.25 then
index = 1;
elseif rand <= 0.50 then
index = 2;
elseif rand <= 0.75 then
index = 3;
else
index = 4;
end
if (destTab[index] == prevPos) or (destTab[index] == "") then
-- We will not go back to where we came from.
index = 0;
end;
end;
return index;
end;
-- Program start
-- Tatooine NPC test
math.randomseed( os.time() );
ss = ScriptSupport:Instance();
-- LuaScriptEngine.WaitMSec(45000);
-- Create the npc
-- local npcId = ss:npcCreate(47513075777);
-- if npcId == 0 then
-- print("Failed creating NPC");
-- end;
-- while ss:objectIsReady(npcId) == false do
-- LuaScriptEngine.WaitMSec(1000);
-- end
-- npc = ss:npcGetObject(npcId);
-- print("Tatooine-Bestine: an ace Imperial storm commando is spawning");
-- ss:npcSpawn(npc, npcId, 0, "", "", 0.71, 0.71, xPos, yPos, zPos)
local routeFromB2 = {routeB2ToA6};
local destFromB2 = {"A6", "", "", ""};
local routeFromA6 = {routeA6ToA7, routeA6ToA9, routeA6ToX5, routeA6ToB2};
local destFromA6 = {"A7", "A9", "X5", "B2"};
local routeFromA7 = {routeA7ToA6, routeA7ToA9, routeA7ToX2};
local destFromA7 = {"A6", "A9", "X2", ""};
local routeFromA9 = {routeA9ToA6, routeA9ToA7};
local destFromA9 = {"A6", "A7", "", ""};
local routeFromX5 = {routeX5ToA6, routeX5ToX2, routeX5ToX8};
local destFromX5 = {"A6", "X2", "X8", ""};
local routeFromX8 = {routeX8ToX5, routeX8ToB2, routeX8ToX5, routeX8ToX5 };
local destFromX8 = {"X5", "B2", "X5", "X5"};
local routeFromX2 = {routeX2ToX5, routeX2ToX1, routeX2ToA7, routeX2ToA7};
local destFromX2 = {"X5", "X1", "A7", "A7"};
local routeFromX1 = {routeX1ToX2};
local destFromX1 = {"X2", "", "", ""};
-- npc = MM.createAndSpawnNpc(47513075777, "", "", xPos, yPos, zPos);
npc = MM.createAndSpawnNpc(3, "", "", xPos, yPos, zPos);
-- print("Starting to move that crackdown_storm_commando_hard");
moveTo(spawnPosB1X, yPos, spawnPosB1Z);
moveTo(spawnPosB2X, yPos, spawnPosB2Z);
local myPos = "B2"
local prevPos = "A6"; -- kind of....
while (1) do
local index;
if myPos == "B2" then
index = routeSelection(destFromB2, "");
prevPos = myPos;
myPos = destFromB2[index];
routeFromB2[index]()
-- one way only, to A6.
elseif myPos == "A6" then
index = routeSelection(destFromA6, prevPos);
-- prevPos = myPos;
prevPos = "";
myPos = destFromA6[index];
routeFromA6[index]()
elseif myPos == "A7" then
-- index = routeSelection(destFromA7, "X2");
index = routeSelection(destFromA7, prevPos);
prevPos = myPos;
myPos = destFromA7[index];
routeFromA7[index]()
elseif myPos == "A9" then
index = routeSelection(destFromA9, "");
prevPos = myPos;
myPos = destFromA9[index];
routeFromA9[index]()
elseif myPos == "X5" then
index = routeSelection(destFromX5, prevPos);
prevPos = myPos;
myPos = destFromX5[index];
routeFromX5[index]()
elseif myPos == "X8" then
index = routeSelection(destFromX8, "");
prevPos = myPos;
myPos = destFromX8[index];
routeFromX8[index]()
elseif myPos == "X2" then
index = routeSelection(destFromX2, prevPos);
prevPos = myPos;
myPos = destFromX2[index];
routeFromX2[index]()
elseif myPos == "X1" then
index = routeSelection(destFromX1, "");
prevPos = myPos;
myPos = destFromX1[index];
routeFromX1[index]()
else
print("Unknown position:" .. myPos);
LuaScriptEngine.WaitMSec(5000);
end
end
| gpl-3.0 |
mero97/Hp_II303II | plugins/leave_bot.lua | 1 | 3147 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY MOHAMMED HISHAM ▀▄ ▄▀
▀▄ ▄▀ BY MOHAMMEDHISHAM (@TH3BOSS) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY MOHAMMED HISHAM ▀▄ ▄▀
▀▄ ▄▀ ANTI BOT : منع بوتات ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
local function isAntiBotEnabled (chatId)
local hash = 'bot:lock:'..chatId
local lock = redis:get(hash)
return lock
end
local function enableAntiBot (chatId)
local hash = 'bot:lock:'..chatId
redis:set(hash, true)
end
local function disableAntiBot (chatId)
local hash = 'bot:lock:'..chatId
redis:del(hash)
end
local function isABot (user)
local binFlagIsBot = 4096
local result = bit32.band(user.flags, binFlagIsBot)
return result == binFlagIsBot
end
local function isABotBadWay (user)
local username = user.username or ''
return username:match("[Bb]ot$")
end
local function kickUser(userId, chatId)
local channel = 'channel#id'..chatId
local user = 'user#id'..userId
channel_kick_user(channel, user, function (data, success, result)
if success ~= 1 then
print('I can\'t kick '..data.user..' but should be kicked')
end
end, {chat=chat, user=user})
end
local function mohammed (msg, matches)
if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then
if msg.to.type ~= 'chat' and msg.to.type ~= 'channel' then
return nil
end
end
local chatId = msg.to.id
if matches[1] == 'قفل البوتات' then
enableAntiBot(chatId)
return 'تم ☑️ قفل 🔒 اضافه البوتات \n📌 Order By : @'..(msg.from.username or " لا يــــوجــــد ")..'\n📌 Order By : '.. msg.from.id..'\n'
end
if matches[1] == 'فتح البوتات' then
disableAntiBot(chatId)
return 'تم ☑️ فتح 🔓 اضافه البوتات \n📌 Order By : @'..(msg.from.username or " لا يــــوجــــد ")..'\n📌 Order By : '.. msg.from.id..'\n'
end
if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then
local user = msg.action.user or msg.from
if isABotBadWay(user) then
print("It' a bot!")
if isAntiBotEnabled(chatId) then
print('bot is locked')
local userId = user.id
if not isBotAllowed(userId, chatId) then
kickUser(userId, chatId)
else
print('')
end
end
end
end
end
return {
description = 'Anti bot create',
usage = {
'/bot lock: locked add bots to supergroup',
'/bot unlock: unlock add bots to supergroup'
},
patterns = {
'^(قفل البوتات)$',
'^(فتح البوتات)$',
'^!!tgservice (chat_add_user)$',
'^!!tgservice (chat_add_user_link)$'
},
run = mohammed
}
| gpl-2.0 |
To0fan/ali | plugins/all.lua | 184 | 4452 | do
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)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_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
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.\nUse /type in the group to set type.'
end
return group_type
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(msg,target,receiver)
local data = load_data(_config.moderation.data)
if not data[tostring(target)] then
return
end
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
if group_type == "Group" or group_type == "Realm" then
local settings = show_group_settingsmod(msg,target)
text = text.."\n\n"..settings
elseif group_type == "SuperGroup" then
local settings = show_supergroup_settingsmod(msg,target)
text = text..'\n\n'..settings
end
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local mutes_list = mutes_list(target)
text = text.."\n\n"..mutes_list
local muted_user_list = muted_user_list(target)
text = text.."\n\n"..muted_user_list
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
local function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(msg,target,receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
return all(msg,msg.to.id,receiver)
end
end
return {
patterns = {
"^[#!/](all)$",
"^[#!/](all) (%d+)$"
},
run = run
}
end | gpl-2.0 |
HenrytheSlav/OpenRA | mods/ra/maps/allies-05a/allies05a-AI.lua | 4 | 6731 |
IdlingUnits = { }
AttackGroupSize = 6
Barracks = { Barracks2, Barracks3 }
Rallypoints = { VehicleRallypoint1, VehicleRallypoint2, VehicleRallypoint3, VehicleRallypoint4, VehicleRallypoint5 }
WaterLZs = { WaterLZ1, WaterLZ2 }
Airfields = { Airfield1, Airfield2 }
Yaks = { }
SovietInfantryTypes = { "e1", "e1", "e2", "e4" }
SovietVehicleTypes = { "3tnk", "3tnk", "3tnk", "v2rl", "v2rl", "apc" }
SovietAircraftType = { "yak" }
HoldProduction = true
BuildVehicles = true
TrainInfantry = true
IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end
SetupAttackGroup = function()
local units = { }
for i = 0, AttackGroupSize, 1 do
if #IdlingUnits == 0 then
return units
end
local number = Utils.RandomInteger(1, #IdlingUnits)
if IdlingUnits[number] and not IdlingUnits[number].IsDead then
units[i] = IdlingUnits[number]
table.remove(IdlingUnits, number)
end
end
return units
end
SendAttack = function()
if Attacking then
return
end
Attacking = true
HoldProduction = true
local units = { }
if SendWaterTransports and Utils.RandomInteger(0,2) == 1 then
units = WaterAttack()
Utils.Do(units, function(unit)
Trigger.OnAddedToWorld(unit, function()
Trigger.OnIdle(unit, unit.Hunt)
end)
end)
Trigger.AfterDelay(DateTime.Seconds(20), function()
Attacking = false
HoldProduction = false
end)
else
units = SetupAttackGroup()
Utils.Do(units, function(unit)
IdleHunt(unit)
end)
Trigger.AfterDelay(DateTime.Minutes(1), function() Attacking = false end)
Trigger.AfterDelay(DateTime.Minutes(2), function() HoldProduction = false end)
end
end
WaterAttack = function()
local types = { }
for i = 1, 5, 1 do
types[i] = Utils.Random(SovietInfantryTypes)
end
return Reinforcements.ReinforceWithTransport(ussr, InsertionTransport, types, { WaterTransportSpawn.Location, Utils.Random(WaterLZs).Location }, { WaterTransportSpawn.Location })[2]
end
ProtectHarvester = function(unit)
Trigger.OnDamaged(unit, function(self, attacker)
-- TODO: Send the Harvester to the service depo
if AttackOnGoing then
return
end
AttackOnGoing = true
local Guards = SetupAttackGroup()
Utils.Do(Guards, function(unit)
if not self.IsDead then
unit.AttackMove(self.Location)
end
IdleHunt(unit)
end)
Trigger.OnAllRemovedFromWorld(Guards, function() AttackOnGoing = false end)
end)
Trigger.OnKilled(unit, function() HarvesterKilled = true end)
end
InitAIUnits = function()
IdlingUnits = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == ussr and self.HasProperty("Hunt") and self.Location.Y > MainBaseTopLeft.Location.Y end)
local buildings = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == ussr and self.HasProperty("StartBuildingRepairs") end)
Utils.Do(buildings, function(actor)
Trigger.OnDamaged(actor, function(building)
if building.Owner == ussr and building.Health < building.MaxHealth * 3/4 then
building.StartBuildingRepairs()
end
end)
end)
end
InitAIEconomy = function()
ussr.Cash = 6000
if not Harvester.IsDead then
Harvester.FindResources()
ProtectHarvester(Harvester)
end
end
InitProductionBuildings = function()
if not Warfactory2.IsDead then
Warfactory2.IsPrimaryBuilding = true
Trigger.OnKilled(Warfactory2, function() BuildVehicles = false end)
else
BuildVehicles = false
end
if not Barracks2.IsDead then
Barracks2.IsPrimaryBuilding = true
Trigger.OnKilled(Barracks2, function()
if not Barracks3.IsDead then
Barracks3.IsPrimaryBuilding = true
else
TrainInfantry = false
end
end)
elseif not Barracks3.IsDead then
Barracks3.IsPrimaryBuilding = true
else
TrainInfantry = false
end
if not Barracks3.IsDead then
Trigger.OnKilled(Barracks3, function()
if Barracks2.IsDead then
TrainInfantry = false
end
end)
end
if Map.Difficulty ~= "Easy" then
if not Airfield1.IsDead then
Trigger.OnKilled(Airfield1, function()
if Airfield2.IsDead then
AirAttacks = false
else
Airfield2.IsPrimaryBuilding = true
Trigger.OnKilled(Airfield2, function() AirAttacks = false end)
end
end)
Airfield1.IsPrimaryBuilding = true
AirAttacks = true
elseif not Airfield2.IsDead then
Trigger.OnKilled(Airfield2, function() AirAttacks = false end)
Airfield2.IsPrimaryBuilding = true
AirAttacks = true
end
end
end
ProduceInfantry = function()
if not TrainInfantry then
return
end
if HoldProduction then
Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry)
return
end
local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9))
local toBuild = { Utils.Random(SovietInfantryTypes) }
ussr.Build(toBuild, function(unit)
IdlingUnits[#IdlingUnits + 1] = unit[1]
Trigger.AfterDelay(delay, ProduceInfantry)
if #IdlingUnits >= (AttackGroupSize * 2.5) then
SendAttack()
end
end)
end
ProduceVehicles = function()
if not BuildVehicles then
return
end
if HoldProduction then
Trigger.AfterDelay(DateTime.Minutes(1), ProduceVehicles)
return
end
local delay = Utils.RandomInteger(DateTime.Seconds(5), DateTime.Seconds(9))
if HarvesterKilled then
HarvesterKilled = false
ussr.Build({ "harv" }, function(harv)
harv[1].FindResources()
ProtectHarvester(harv[1])
Trigger.AfterDelay(delay, ProduceVehicles)
end)
return
end
Warfactory2.RallyPoint = Utils.Random(Rallypoints).Location
local toBuild = { Utils.Random(SovietVehicleTypes) }
ussr.Build(toBuild, function(unit)
IdlingUnits[#IdlingUnits + 1] = unit[1]
Trigger.AfterDelay(delay, ProduceVehicles)
if #IdlingUnits >= (AttackGroupSize * 2.5) then
SendAttack()
end
end)
end
ProduceAircraft = function()
if not AirAttacks then
return
end
ussr.Build(SovietAircraftType, function(units)
Yaks[#Yaks + 1] = units[1]
if #Yaks == 2 then
Trigger.OnKilled(units[1], ProduceAircraft)
else
Trigger.AfterDelay(DateTime.Minutes(1), ProduceAircraft)
end
local target = nil
Trigger.OnIdle(units[1], function()
if not target or target.IsDead or (not target.IsInWorld) then
local enemies = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == greece and self.HasProperty("Health") end)
if #enemies > 0 then
target = Utils.Random(enemies)
units[1].Attack(target)
end
else
units[1].Attack(target)
end
end)
end)
end
ActivateAI = function()
InitAIUnits()
InitAIEconomy()
InitProductionBuildings()
Trigger.AfterDelay(DateTime.Minutes(5), function()
ProduceInfantry()
ProduceVehicles()
if false and AirAttacks then -- disable air strikes for now since they are broken
Trigger.AfterDelay(DateTime.Minutes(3), ProduceAircraft)
end
end)
end
| gpl-3.0 |
quyse/flaw | flaw-lua-refimpl/src/lua-5.3.4-tests/all.lua | 5 | 7672 | #!../lua
-- $Id: all.lua,v 1.95 2016/11/07 13:11:28 roberto Exp $
-- See Copyright Notice at the end of this file
local version = "Lua 5.3"
if _VERSION ~= version then
io.stderr:write("\nThis test suite is for ", version, ", not for ", _VERSION,
"\nExiting tests\n")
return
end
_G._ARG = arg -- save arg for other tests
-- next variables control the execution of some tests
-- true means no test (so an undefined variable does not skip a test)
-- defaults are for Linux; test everything.
-- Make true to avoid long or memory consuming tests
_soft = rawget(_G, "_soft") or false
-- Make true to avoid non-portable tests
_port = rawget(_G, "_port") or false
-- Make true to avoid messages about tests not performed
_nomsg = rawget(_G, "_nomsg") or false
local usertests = rawget(_G, "_U")
if usertests then
-- tests for sissies ;) Avoid problems
_soft = true
_port = true
_nomsg = true
end
-- tests should require debug when needed
debug = nil
if usertests then
T = nil -- no "internal" tests for user tests
else
T = rawget(_G, "T") -- avoid problems with 'strict' module
end
math.randomseed(0)
--[=[
example of a long [comment],
[[spanning several [lines]]]
]=]
print("current path:\n****" .. package.path .. "****\n")
local initclock = os.clock()
local lastclock = initclock
local walltime = os.time()
local collectgarbage = collectgarbage
do -- (
-- track messages for tests not performed
local msgs = {}
function Message (m)
if not _nomsg then
print(m)
msgs[#msgs+1] = string.sub(m, 3, -3)
end
end
assert(os.setlocale"C")
local T,print,format,write,assert,type,unpack,floor =
T,print,string.format,io.write,assert,type,table.unpack,math.floor
-- use K for 1000 and M for 1000000 (not 2^10 -- 2^20)
local function F (m)
local function round (m)
m = m + 0.04999
return format("%.1f", m) -- keep one decimal digit
end
if m < 1000 then return m
else
m = m / 1000
if m < 1000 then return round(m).."K"
else
return round(m/1000).."M"
end
end
end
local showmem
if not T then
local max = 0
showmem = function ()
local m = collectgarbage("count") * 1024
max = (m > max) and m or max
print(format(" ---- total memory: %s, max memory: %s ----\n",
F(m), F(max)))
end
else
showmem = function ()
T.checkmemory()
local total, numblocks, maxmem = T.totalmem()
local count = collectgarbage("count")
print(format(
"\n ---- total memory: %s (%.0fK), max use: %s, blocks: %d\n",
F(total), count, F(maxmem), numblocks))
print(format("\t(strings: %d, tables: %d, functions: %d, "..
"\n\tudata: %d, threads: %d)",
T.totalmem"string", T.totalmem"table", T.totalmem"function",
T.totalmem"userdata", T.totalmem"thread"))
end
end
--
-- redefine dofile to run files through dump/undump
--
local function report (n) print("\n***** FILE '"..n.."'*****") end
local olddofile = dofile
local dofile = function (n, strip)
showmem()
local c = os.clock()
print(string.format("time: %g (+%g)", c - initclock, c - lastclock))
lastclock = c
report(n)
local f = assert(loadfile(n))
local b = string.dump(f, strip)
f = assert(load(b))
return f()
end
dofile('main.lua')
do
local next, setmetatable, stderr = next, setmetatable, io.stderr
-- track collections
local mt = {}
-- each time a table is collected, remark it for finalization
-- on next cycle
mt.__gc = function (o)
stderr:write'.' -- mark progress
local n = setmetatable(o, mt) -- remark it
end
local n = setmetatable({}, mt) -- create object
end
report"gc.lua"
local f = assert(loadfile('gc.lua'))
f()
dofile('db.lua')
assert(dofile('calls.lua') == deep and deep)
olddofile('strings.lua')
olddofile('literals.lua')
dofile('tpack.lua')
assert(dofile('attrib.lua') == 27)
assert(dofile('locals.lua') == 5)
dofile('constructs.lua')
dofile('code.lua', true)
if not _G._soft then
report('big.lua')
local f = coroutine.wrap(assert(loadfile('big.lua')))
assert(f() == 'b')
assert(f() == 'a')
end
dofile('nextvar.lua')
dofile('pm.lua')
dofile('utf8.lua')
dofile('api.lua')
assert(dofile('events.lua') == 12)
dofile('vararg.lua')
dofile('closure.lua')
dofile('coroutine.lua')
dofile('goto.lua', true)
dofile('errors.lua')
dofile('math.lua')
dofile('sort.lua', true)
dofile('bitwise.lua')
assert(dofile('verybig.lua', true) == 10); collectgarbage()
dofile('files.lua')
if #msgs > 0 then
print("\ntests not performed:")
for i=1,#msgs do
print(msgs[i])
end
print()
end
-- no test module should define 'debug'
assert(debug == nil)
local debug = require "debug"
print(string.format("%d-bit integers, %d-bit floats",
string.packsize("j") * 8, string.packsize("n") * 8))
debug.sethook(function (a) assert(type(a) == 'string') end, "cr")
-- to survive outside block
_G.showmem = showmem
end --)
local _G, showmem, print, format, clock, time, difftime, assert, open =
_G, showmem, print, string.format, os.clock, os.time, os.difftime,
assert, io.open
-- file with time of last performed test
local fname = T and "time-debug.txt" or "time.txt"
local lasttime
if not usertests then
-- open file with time of last performed test
local f = io.open(fname)
if f then
lasttime = assert(tonumber(f:read'a'))
f:close();
else -- no such file; assume it is recording time for first time
lasttime = nil
end
end
-- erase (almost) all globals
print('cleaning all!!!!')
for n in pairs(_G) do
if not ({___Glob = 1, tostring = 1})[n] then
_G[n] = nil
end
end
collectgarbage()
collectgarbage()
collectgarbage()
collectgarbage()
collectgarbage()
collectgarbage();showmem()
local clocktime = clock() - initclock
walltime = difftime(time(), walltime)
print(format("\n\ntotal time: %.2fs (wall time: %gs)\n", clocktime, walltime))
if not usertests then
lasttime = lasttime or clocktime -- if no last time, ignore difference
-- check whether current test time differs more than 5% from last time
local diff = (clocktime - lasttime) / lasttime
local tolerance = 0.05 -- 5%
if (diff >= tolerance or diff <= -tolerance) then
print(format("WARNING: time difference from previous test: %+.1f%%",
diff * 100))
end
assert(open(fname, "w")):write(clocktime):close()
end
print("final OK !!!")
--[[
*****************************************************************************
* Copyright (C) 1994-2016 Lua.org, PUC-Rio.
*
* 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.
*****************************************************************************
]]
| mit |
MidflightDigital/ddrsn3-theme | DDR SN3/Graphics/ScreenGameplay LifeFrame/_old.lua | 1 | 5254 | -- gameplay life frame
-- The math.floor(10000*aspect) trick is used to circumvent float precision problems.
local aspectRatioSuffix = {
[math.floor(10000*4/3)] = " 4_3",
[math.floor(10000*16/9)] = " 16_9",
[math.floor(10000*16/10)] = " 16_9"
}
--fall back on the 4:3 frame if we don't know about this aspect ratio at all
setmetatable(aspectRatioSuffix,{__index=function() return " standard" end})
local suffix = aspectRatioSuffix[math.floor(10000*PREFSMAN:GetPreference("DisplayAspectRatio"))]
local lifeFrame = "normal"
-- todo: show oni on life meter battery as well
if GAMESTATE:GetPlayMode() == 'PlayMode_Oni' then lifeFrame = "special" end
if GAMESTATE:GetPlayMode() == 'PlayMode_Nonstop' then lifeFrame = "special" end
if GAMESTATE:GetPlayMode() == 'PlayMode_Rave' then lifeFrame = "special" end
if GAMESTATE:IsAnExtraStage() then lifeFrame = "special" end
-- fall back on the 4:3 frame if there's no frame available for this aspect ratio
if ResolveRelativePath(lifeFrame..suffix,1,true) then
lifeFrame = lifeFrame .. suffix
line = "lines" .. suffix
else
Warn("ScreenGameplay LifeFrame: missing frame \""..lifeFrame..suffix.."\". Using fallback assets.")
lifeFrame = lifeFrame.." 4_3"
line = "lines 4_3"
end
-- fall back on 4:3 frame because tug doesn't like lua scripts.
if GAMESTATE:GetPlayMode() == "PlayMode_Rave" then
lifeFrame = "special 4_3"
line = "lines 4_3"
end
local xPosPlayer = {
P1 = -(SCREEN_WIDTH/6.7),
P2 = (SCREEN_WIDTH/6.7)
}
local xPosPlayerRave = {
P1 = -(640/6.7),
P2 = (640/6.7)
};
local t = Def.ActorFrame{}
t[#t+1] = LoadActor("flicker")
for _, pn in pairs(GAMESTATE:GetEnabledPlayers()) do
t[#t+1] = LoadActor(lifeFrame)..{
Name = pn,
InitCommand=function(self)
local short = ToEnumShortString(pn)
if GAMESTATE:GetPlayMode() == "PlayMode_Rave" then
self:x(xPosPlayerRave[short])
else
self:x(xPosPlayer[short])
end;
self:halign(0.75)
end,
OnCommand=function(s) s:zoomx(pn=='PlayerNumber_P2' and -1 or 1) end,
};
t[#t+1] = LoadActor(line)..{
InitCommand=function(self)
local short = ToEnumShortString(pn)
if GAMESTATE:GetPlayMode() == "PlayMode_Rave" then
self:x(xPosPlayerRave[short])
else
self:x(xPosPlayer[short])
end;
self:halign(0.75)
:diffusealpha(0.4)
end,
OnCommand=function(s) s:zoomx(pn=='PlayerNumber_P2' and -1 or 1) end,
BeginCommand=function(self,param)
if GAMESTATE:PlayerIsUsingModifier('PlayerNumber_P1','battery') or GAMESTATE:GetPlayMode() == 'PlayMode_Oni' then
self:visible(false);
elseif GAMESTATE:PlayerIsUsingModifier('PlayerNumber_P2','battery') or GAMESTATE:GetPlayMode() == 'PlayMode_Oni' then
self:visible(false);
else
self:visible(true);
end;
end;
};
end;
t[#t+1] = LoadActor("../_shared/Badges/LifeBar/P1")..{
InitCommand=function(self)
if GAMESTATE:GetPlayMode() == "PlayMode_Rave" then
self:x(-(640/2.08))
else
self:x(WideScale(-(SCREEN_WIDTH/2.08),-(SCREEN_WIDTH/2.12)))
end;
end;
BeginCommand=function(self,param)
if GAMESTATE:IsPlayerEnabled('PlayerNumber_P1') then
self:visible(true);
else
self:visible(false);
end;
end;
};
t[#t+1] = LoadActor("../_shared/Badges/LifeBar/P2")..{
InitCommand=function(self)
if GAMESTATE:GetPlayMode() == "PlayMode_Rave" then
self:x((640/2.08))
else
self:x(WideScale((SCREEN_WIDTH/2.08),(SCREEN_WIDTH/2.12)))
end;
end,
BeginCommand=function(self,param)
if GAMESTATE:IsPlayerEnabled('PlayerNumber_P2') then
self:visible(true);
else
self:visible(false);
end;
end;
};
--Player 1 Risky Splitter
if GAMESTATE:IsPlayerEnabled('PlayerNumber_P1') then
t[#t+1] = LoadActor("splitter")..{
InitCommand=function(self)
self:x(-(SCREEN_WIDTH/5.7)):skewx(WideScale(-1.5,-0.9)):zoomto((SCREEN_WIDTH/2.54),14):halign(0.75);
end;
BeginCommand=function(self,param)
if GAMESTATE:PlayerIsUsingModifier('PlayerNumber_P1','battery') or GAMESTATE:GetPlayMode() == 'PlayMode_Oni' then
self:visible(true);
else
self:visible(false);
end;
end;
};
end;
--Player 2 Risky Splitter
if GAMESTATE:IsPlayerEnabled('PlayerNumber_P2') then
t[#t+1] = LoadActor("splitter")..{
InitCommand=function(self)
self:x((SCREEN_WIDTH/5.7)):skewx(WideScale(1.5,0.9)):zoomto((SCREEN_WIDTH/2.54),14):halign(0.25);
end;
BeginCommand=function(self,param)
if GAMESTATE:PlayerIsUsingModifier('PlayerNumber_P2','battery') or GAMESTATE:GetPlayMode() == 'PlayMode_Oni' then
self:visible(true);
else
self:visible(false);
end;
end;
};
end;
--Player 1 Danger
t[#t+1] = LoadActor("danger 2x1")..{
InitCommand=cmd(x,WideScale(-160,-213.5);visible,false);
HealthStateChangedMessageCommand=function(self, param)
if GAMESTATE:IsPlayerEnabled('PlayerNumber_P1') then
if param.HealthState == "HealthState_Danger" then
self:visible(true);
else
self:visible(false);
end;
end;
end;
};
--Player 2 Danger
t[#t+1] = LoadActor("danger 2x1")..{
InitCommand=cmd(x,WideScale(160,213.5);visible,false);
HealthStateChangedMessageCommand=function(self, param)
if GAMESTATE:IsPlayerEnabled('PlayerNumber_P2') then
if param.HealthState == "HealthState_Danger" then
self:visible(true);
else
self:visible(false);
end;
end;
end;
};
return t
| mit |
adib1380/iranian_bot | plugins/stats.lua | 5 | 3759 | do
local NUM_MSG_MAX = 6
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..'\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
local kick = chat_del_user(chat_id , user_id, ok_cb, true)
vardump(kick)
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
chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false)
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 ' تنها در گروه کار میکند❗️ '
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return " شما مجوز این بخش را ندارید❌ "
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return " شما مجوز این بخش را ندارید❌ "
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: نمایش بیشترین تعداد چت ",
"!stats chat <chat_id>: نمایش امار گروه ",
"!stats bot: نمایش امار بات تنها ادمین ها "
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
renyidong/milkywayathome_client | nbody/tests/GenerateResults.lua | 4 | 3175 |
require "NBodyTesting"
require "persistence"
local arg = {...}
local nbodyBinary = assert(arg[1])
local nbodyFlags = getExtraNBodyFlags()
eprintf("NBODY_FLAGS = %s\n", nbodyFlags)
local testDir = "orphan_models"
math.randomseed(os.time())
-- When generating results, write results to stdout and everything
-- else to stderr to make things easier
function generateSampleUnits(outputName, testName, histograms, nbodies, iterations)
local file, results, newResults = false
local allResults = persistence.load(outputName)
if allResults == nil then
eprintf("Could not open file '%s', creating new\n", outputName)
allResults = { }
newResults = true
end
local results
if allResults[testName] == nil then
allResults[testName] = { }
end
results = allResults[testName]
for _, nbody in ipairs(nbodies) do
if results[nbody] == nil then
results[nbody] = { }
end
local histTable = results[nbody]
local nSamples = { } -- we need to know how many are there originally to avoid clobbering old ones
for _, histogram in ipairs(histograms) do
if histTable[histogram] == nil then
histTable[histogram] = { }
histTable[histogram]["samples"] = { }
end
nSamples[histogram] = #histTable[histogram]["samples"]
end
for i = 1, iterations do
local seed = randomSeed()
local cached = false -- we only need to run the sim once and match against all histograms
for _, histogram in ipairs(histograms) do
local this = histTable[histogram]["samples"]
eprintf("Running test '%s' with %d bodies. cached = %s\n", testName, nbody, tostring(cached))
local output = runFullTest{
nbodyBin = nbodyBinary,
testDir = testDir,
testName = testName,
histogram = histogram,
seed = seed,
cached = cached,
extraArgs = { nbody }
}
local result = findLikelihood(output, false)
assert(result, "Did not find result in test output")
eprintf(" iteration %4d (seed %6d) = %f\n", i, seed, result)
this[i + nSamples[histogram]] = result
cached = true
end
end
for _, histogram in pairs(histograms) do
local histItem = histTable[histogram]
local histSamples = histItem["samples"]
histItem["mean"], histItem["stddev"] = calcStats(histSamples)
histItem["min"], histItem["max"] = findMinMax(histSamples)
end
end
if not newResults then
os.rename(outputName, outputName .. ".bak")
end
local tmpName = outputName .. ".tmp"
persistence.store(tmpName, allResults)
os.rename(tmpName, outputName)
end
local testName = assert(arg[2])
local outputFile = arg[3] or "GeneratedResults.lua"
local nbody = arg[4] or 10000
local nIter = arg[5] or 10
local histograms = {"orphan_model_histogram", "model_1_self.hist"}
local nbodies = { nbody }
for i = 1, nIter do
generateSampleUnits(outputFile, testName, histograms, nbodies, 1)
end
| gpl-3.0 |
me2beats/reapack | Tracks/me2beats_Translit (sel tracks names).lua | 1 | 1408 | -- @description Translit (sel tracks names)
-- @version 1.0
-- @author me2beats
-- @changelog
-- + init
local r = reaper; local function nothing() end; local function bla() r.defer(nothing) end
local tracks = r.CountSelectedTracks()
if tracks == 0 then bla() return end
local v = {}
v['А']='A'
v['Б']='B'
v['В']='V'
v['Г']='G'
v['Д']='D'
v['Е']='E'
v['Ё']='Yo'
v['Ж']='Zh'
v['З']='Z'
v['И']='I'
v['Й']='J'
v['К']='K'
v['Л']='L'
v['М']='M'
v['Н']='N'
v['О']='O'
v['П']='P'
v['Р']='R'
v['С']='S'
v['Т']='T'
v['У']='U'
v['Ф']='F'
v['Х']='H'
v['Ц']='Ts'
v['Ч']='Ch'
v['Ш']='Sh'
v['Щ']='Sch'
v['Ы']='Y'
v['Ь']="'"
v['Э']='E'
v['Ю']='Ju'
v['Я']='Ja'
v['а']='a'
v['б']='b'
v['в']='v'
v['г']='g'
v['д']='d'
v['е']='e'
v['ё']='yo'
v['ж']='zh'
v['з']='z'
v['и']='i'
v['й']='j'
v['к']='k'
v['л']='l'
v['м']='m'
v['н']='n'
v['о']='o'
v['п']='p'
v['р']='r'
v['с']='s'
v['т']='t'
v['у']='u'
v['ф']='f'
v['х']='h'
v['ц']='ts'
v['ч']='ch'
v['ш']='sh'
v['щ']='sch'
v['ы']='y'
v['ь']="'"
v['э']='e'
v['ю']='ju'
r.Undo_BeginBlock()
for i = 0, tracks-1 do
local track = r.GetSelectedTrack(0,i)
_, tr_name = r.GetSetMediaTrackInfo_String(track, 'P_NAME', '', 0)
for key,val in pairs(v) do
tr_name = tr_name:gsub(key,val)
end
r.GetSetMediaTrackInfo_String(track, 'P_NAME', tr_name, 1)
end
r.Undo_EndBlock('Translit (sel tracks names)', -1)
| gpl-3.0 |
alirezanile/BiG-BoSS | plugins/rss.lua | 700 | 5434 | local function get_base_redis(id, option, extra)
local ex = ''
if option ~= nil then
ex = ex .. ':' .. option
if extra ~= nil then
ex = ex .. ':' .. extra
end
end
return 'rss:' .. id .. ex
end
local function prot_url(url)
local url, h = string.gsub(url, "http://", "")
local url, hs = string.gsub(url, "https://", "")
local protocol = "http"
if hs == 1 then
protocol = "https"
end
return url, protocol
end
local function get_rss(url, prot)
local res, code = nil, 0
if prot == "http" then
res, code = http.request(url)
elseif prot == "https" then
res, code = https.request(url)
end
if code ~= 200 then
return nil, "Error while doing the petition to " .. url
end
local parsed = feedparser.parse(res)
if parsed == nil then
return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?"
end
return parsed, nil
end
local function get_new_entries(last, nentries)
local entries = {}
for k,v in pairs(nentries) do
if v.id == last then
return entries
else
table.insert(entries, v)
end
end
return entries
end
local function print_subs(id)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
local text = id .. ' are subscribed to:\n---------\n'
for k,v in pairs(subs) do
text = text .. k .. ") " .. v .. '\n'
end
return text
end
local function subscribe(id, url)
local baseurl, protocol = prot_url(url)
local prothash = get_base_redis(baseurl, "protocol")
local lasthash = get_base_redis(baseurl, "last_entry")
local lhash = get_base_redis(baseurl, "subs")
local uhash = get_base_redis(id)
if redis:sismember(uhash, baseurl) then
return "You are already subscribed to " .. url
end
local parsed, err = get_rss(url, protocol)
if err ~= nil then
return err
end
local last_entry = ""
if #parsed.entries > 0 then
last_entry = parsed.entries[1].id
end
local name = parsed.feed.title
redis:set(prothash, protocol)
redis:set(lasthash, last_entry)
redis:sadd(lhash, id)
redis:sadd(uhash, baseurl)
return "You had been subscribed to " .. name
end
local function unsubscribe(id, n)
if #n > 3 then
return "I don't think that you have that many subscriptions."
end
n = tonumber(n)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
if n < 1 or n > #subs then
return "Subscription id out of range!"
end
local sub = subs[n]
local lhash = get_base_redis(sub, "subs")
redis:srem(uhash, sub)
redis:srem(lhash, id)
local left = redis:smembers(lhash)
if #left < 1 then -- no one subscribed, remove it
local prothash = get_base_redis(sub, "protocol")
local lasthash = get_base_redis(sub, "last_entry")
redis:del(prothash)
redis:del(lasthash)
end
return "You had been unsubscribed from " .. sub
end
local function cron()
-- sync every 15 mins?
local keys = redis:keys(get_base_redis("*", "subs"))
for k,v in pairs(keys) do
local base = string.match(v, "rss:(.+):subs") -- Get the URL base
local prot = redis:get(get_base_redis(base, "protocol"))
local last = redis:get(get_base_redis(base, "last_entry"))
local url = prot .. "://" .. base
local parsed, err = get_rss(url, prot)
if err ~= nil then
return
end
local newentr = get_new_entries(last, parsed.entries)
local subscribers = {}
local text = '' -- Send only one message with all updates
for k2, v2 in pairs(newentr) do
local title = v2.title or 'No title'
local link = v2.link or v2.id or 'No Link'
text = text .. "[rss](" .. link .. ") - " .. title .. '\n'
end
if text ~= '' then
local newlast = newentr[1].id
redis:set(get_base_redis(base, "last_entry"), newlast)
for k2, receiver in pairs(redis:smembers(v)) do
send_msg(receiver, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
local id = "user#id" .. msg.from.id
if is_chat_msg(msg) then
id = "chat#id" .. msg.to.id
end
if matches[1] == "!rss"then
return print_subs(id)
end
if matches[1] == "sync" then
if not is_sudo(msg) then
return "Only sudo users can sync the RSS."
end
cron()
end
if matches[1] == "subscribe" or matches[1] == "sub" then
return subscribe(id, matches[2])
end
if matches[1] == "unsubscribe" or matches[1] == "uns" then
return unsubscribe(id, matches[2])
end
end
return {
description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.",
usage = {
"!rss: Get your rss (or chat rss) subscriptions",
"!rss subscribe (url): Subscribe to that url",
"!rss unsubscribe (id): Unsubscribe of that id",
"!rss sync: Download now the updates and send it. Only sudo users can use this option."
},
patterns = {
"^!rss$",
"^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (unsubscribe) (%d+)$",
"^!rss (uns) (%d+)$",
"^!rss (sync)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
openwisp/openwisp-controller-http | openwisp-config/files/sbin/openwisp-store-unmanaged.lua | 1 | 3126 | #!/usr/bin/env lua
-- stores unmanaged configurations
local os = require('os')
local io = require('io')
local uci = require('uci')
local utils = require('openwisp.utils')
local sections
local arg={...}
-- parse arguments
local test = false
for key, value in pairs(arg) do
-- test argument
if value == '--test=1' then test = true; end
-- sections argument
if string.sub(value, 1, 3) == '-o=' then
sections = value:gsub('%-o=', '')
sections = sections:gsub('%"', '')
end
end
local standard_prefix = test and '../tests/' or '/etc/'
local unmanaged_prefix = test and '../tests/' or '/tmp/openwisp/'
local standard_path = standard_prefix .. 'config/'
local unmanaged_path = unmanaged_prefix .. 'unmanaged/'
local uci_tmp_path = '/tmp/openwisp/.uci'
local function empty_file(path)
local file = io.open(path, 'w')
file:write('')
file:close()
end
-- convert list of sections in a table with a structure like:
-- {
-- network = {
-- {name = 'loopback'},
-- {name = 'globals'},
-- {type = 'switch'},
-- {type = 'switch_vlan'}
-- },
-- system = {
-- {name = 'ntp'},
-- {type = 'led'}
-- }
-- }
local unmanaged_map = {}
local section_list = utils.split(sections)
for _, section in pairs(section_list) do
local parts = utils.split(section, '.')
-- skip unrecognized strings
if parts[1] and parts[2] then
local config = parts[1]
local section_type = nil
local section_name = nil
-- anonymous section
if string.sub(parts[2], 1, 1) == '@' then
section_type = string.sub(parts[2], 2, -1)
-- named section
else
section_name = parts[2]
end
if config and (section_name or section_type) then
if not unmanaged_map[config] then
unmanaged_map[config] = {}
end
local el = {name=section_name, type=section_type}
table.insert(unmanaged_map[config], el)
end
end
end
-- cleanup temporary files to avoid conflicts
os.execute('mkdir -p ' .. uci_tmp_path)
os.execute('rm -rf ' .. unmanaged_path)
os.execute('mkdir -p ' .. unmanaged_path)
-- standard cursor
local standard = uci.cursor(standard_path)
-- unmanaged cursor
local unmanaged = uci.cursor(unmanaged_path, uci_tmp_path)
-- loop over standard sections and store a copy in unmanaged
for config_name, config_values in pairs(unmanaged_map) do
local uci_table = standard:get_all(config_name)
if uci_table then
-- create empty file
empty_file(unmanaged_path .. config_name)
for i, element in pairs(config_values) do
if element.name then
local section = uci_table[element.name]
if section then
utils.write_uci_section(unmanaged, config_name, section)
end
else
standard:foreach(config_name, element.type, function(section)
utils.write_uci_section(unmanaged, config_name, section)
end)
end
end
end
unmanaged:commit(config_name)
end
| gpl-3.0 |
HenrytheSlav/OpenRA | mods/cnc/maps/gdi06/gdi06.lua | 12 | 6352 | IslandSamSites = { SAM01, SAM02 }
NodBase = { PowerPlant1, PowerPlant2, PowerPlant3, PowerPlant4, PowerPlant5, Refinery, HandOfNod, Silo1, Silo2, Silo3, Silo4, ConYard, CommCenter }
FlameSquad = { FlameGuy1, FlameGuy2, FlameGuy3 }
FlameSquadRoute = { waypoint4.Location, waypoint12.Location, waypoint4.Location, waypoint6.Location }
FootPatrol1Squad = { MiniGunner1, MiniGunner2, RocketSoldier1 }
FootPatrol1Route = {
waypoint4.Location,
waypoint12.Location,
waypoint13.Location,
waypoint3.Location,
waypoint2.Location,
waypoint7.Location,
waypoint6.Location
}
FootPatrol2Squad = { MiniGunner3, MiniGunner4 }
FootPatrol2Route = {
waypoint14.Location,
waypoint16.Location
}
FootPatrol3Squad = { MiniGunner5, MiniGunner6 }
FootPatrol3Route = {
waypoint15.Location,
waypoint17.Location
}
FootPatrol4Route = {
waypoint4.Location,
waypoint5.Location
}
FootPatrol5Squad = { RocketSoldier2, RocketSoldier3, RocketSoldier4 }
FootPatrol5Route = {
waypoint4.Location,
waypoint12.Location,
waypoint13.Location,
waypoint8.Location,
waypoint9.Location,
}
Buggy1Route = {
waypoint6.Location,
waypoint7.Location,
waypoint2.Location,
waypoint8.Location,
waypoint9.Location,
waypoint8.Location,
waypoint2.Location,
waypoint7.Location
}
Buggy2Route = {
waypoint6.Location,
waypoint10.Location,
waypoint11.Location,
waypoint10.Location
}
HuntTriggerActivator = { SAM03, SAM04, SAM05, SAM06, LightTank1, LightTank2, LightTank3, Buggy1, Buggy2, Turret1, Turret2 }
AttackCellTriggerActivator = { CPos.New(57,26), CPos.New(56,26), CPos.New(57,25), CPos.New(56,25), CPos.New(57,24), CPos.New(56,24), CPos.New(57,23), CPos.New(56,23), CPos.New(57,22), CPos.New(56,22), CPos.New(57,21), CPos.New(56,21) }
AttackUnits = { LightTank2, LightTank3 }
KillCounter = 0
WorldLoaded = function()
player = Player.GetPlayer("GDI")
enemy = Player.GetPlayer("Nod")
civilian = Player.GetPlayer("Neutral")
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
if Map.Difficulty == "Easy" then
CommandoType = "rmbo.easy"
KillCounterHuntThreshold = 30
elseif Map.Difficulty == "Hard" then
CommandoType = "rmbo.hard"
KillCounterHuntThreshold = 15
else
CommandoType = "rmbo"
KillCounterHuntThreshold = 20
end
destroyObjective = player.AddPrimaryObjective("Destroy the Nod ********.")
Trigger.OnKilled(Airfield, function()
player.MarkCompletedObjective(destroyObjective)
end)
Utils.Do(NodBase, function(structure)
Trigger.OnKilled(structure, function()
player.MarkCompletedObjective(destroyObjective)
end)
end)
Trigger.OnAllKilled(IslandSamSites, function()
TransportFlare = Actor.Create('flare', true, { Owner = player, Location = Flare.Location })
Reinforcements.ReinforceWithTransport(player, 'tran', nil, { lstStart.Location, TransportRally.Location })
end)
Trigger.OnKilled(CivFleeTrigger, function()
if not Civilian.IsDead then
Civilian.Move(CivHideOut.Location)
end
end)
Trigger.OnKilled(AttackTrigger2, function()
Utils.Do(FlameSquad, function(unit)
if not unit.IsDead then
unit.Patrol(FlameSquadRoute, false)
end
end)
end)
Trigger.OnEnteredFootprint(AttackCellTriggerActivator, function(a, id)
if a.Owner == player then
Utils.Do(AttackUnits, function(unit)
if not unit.IsDead then
unit.AttackMove(waypoint10.Location)
end
end)
Trigger.RemoveFootprintTrigger(id)
end
end)
Utils.Do(HuntTriggerActivator, function(unit)
Trigger.OnDamaged(unit, HuntTriggerFunction)
end)
Trigger.AfterDelay(5, NodKillCounter)
Utils.Do(FootPatrol1Squad, function(unit)
unit.Patrol(FootPatrol1Route, true)
end)
Utils.Do(FootPatrol2Squad, function(unit)
unit.Patrol(FootPatrol2Route, true, 50)
end)
Utils.Do(FootPatrol3Squad, function(unit)
unit.Patrol(FootPatrol3Route, true, 50)
end)
Utils.Do(FootPatrol5Squad, function(unit)
unit.Patrol(FootPatrol5Route, true, 50)
end)
AttackTrigger2.Patrol(FootPatrol4Route, true, 25)
LightTank1.Move(waypoint6.Location)
Buggy1.Patrol(Buggy1Route, true, 25)
Buggy2.Patrol(Buggy2Route, true, 25)
Camera.Position = UnitsRally.CenterPosition
Reinforce({ CommandoType })
end
Tick = function()
if DateTime.GameTime > DateTime.Seconds(5) and player.HasNoRequiredUnits() then
player.MarkFailedObjective(destroyObjective)
end
end
Reinforce = function(units)
Media.PlaySpeechNotification(player, "Reinforce")
ReinforceWithLandingCraft(units, lstStart.Location, lstEnd.Location, UnitsRally.Location)
end
ReinforceWithLandingCraft = function(units, transportStart, transportUnload, rallypoint)
local transport = Actor.Create("oldlst", true, { Owner = player, Facing = 0, Location = transportStart })
local subcell = 0
Utils.Do(units, function(a)
transport.LoadPassenger(Actor.Create(a, false, { Owner = transport.Owner, Facing = transport.Facing, Location = transportUnload, SubCell = subcell }))
subcell = subcell + 1
end)
transport.ScriptedMove(transportUnload)
transport.CallFunc(function()
Utils.Do(units, function()
local a = transport.UnloadPassenger()
a.IsInWorld = true
a.MoveIntoWorld(transport.Location - CVec.New(0, 1))
if rallypoint ~= nil then
a.Move(rallypoint)
end
end)
end)
transport.Wait(5)
transport.ScriptedMove(transportStart)
transport.Destroy()
end
NodKillCounter = function()
local enemyUnits = enemy.GetGroundAttackers()
Utils.Do(enemyUnits, function(unit)
Trigger.OnKilled(unit, function()
KillCounter = KillCounter + 1
if KillCounter >= KillCounterHuntThreshold then
HuntTriggerFunction()
end
end)
end)
end
HuntTriggerFunction = function()
local list = enemy.GetGroundAttackers()
Utils.Do(list, function(unit)
IdleHunt(unit)
end)
end
IdleHunt = function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end
| gpl-3.0 |
marqueza/syzygy | lib/lovetoys/src/System.lua | 3 | 2895 | -- Getting folder that contains our src
local folderOfThisFile = (...):match("(.-)[^%/%.]+$")
local lovetoys = require(folderOfThisFile .. 'namespace')
local System = lovetoys.class("System")
function System:initialize()
-- Liste aller Entities, die die RequiredComponents dieses Systems haben
self.targets = {}
self.active = true
end
function System:requires() return {} end
function System:addEntity(entity, category)
-- If there are multiple requirement lists, the added entities will
-- be added to their respetive list.
if category then
self.targets[category][entity.id] = entity
else
-- Otherwise they'll be added to the normal self.targets list
self.targets[entity.id] = entity
end
if self.onAddEntity then self:onAddEntity(entity) end
end
function System:removeEntity(entity, component)
-- Get the first element and check if it's a component name
-- In case it is an Entity, we know that this System doesn't have multiple
-- Requirements. Otherwise we remove the Entity from each category.
local firstIndex, _ = next(self.targets)
if firstIndex then
if type(firstIndex) == "string" then
-- Removing entities from their respective category target list.
for index, _ in pairs(self.targets) do
self.targets[index][entity.id] = nil
end
else
self.targets[entity.id] = nil
end
end
end
function System:componentRemoved(entity, component)
-- Get the first element and check if it's a component name
-- In case a System has multiple requirements we need to check for
-- each requirement category if the entity has to be removed.
local firstIndex, _ = next(self.targets)
if firstIndex then
if type(firstIndex) == "string" then
-- Removing entities from their respective category target list.
for index, _ in pairs(self.targets) do
for _, req in pairs(self:requires()[index]) do
if req == component then
self.targets[index][entity.id] = nil
break
end
end
end
else
self.targets[entity.id] = nil
end
end
end
function System:pickRequiredComponents(entity)
local components = {}
local requirements = self:requires()
if type(lovetoys.util.firstElement(requirements)) == "string" then
for _, componentName in pairs(requirements) do
table.insert(components, entity:get(componentName))
end
elseif type(lovetoys.util.firstElement(requirements)) == "table" then
lovetoys.debug("System: :pickRequiredComponents() is not supported for systems with multiple component constellations")
return nil
end
return unpack(components)
end
return System
| gpl-3.0 |
Zhen-hao/lstm | data.lua | 9 | 1953 | --
---- Copyright (c) 2014, Facebook, Inc.
---- All rights reserved.
----
---- This source code is licensed under the Apache 2 license found in the
---- LICENSE file in the root directory of this source tree.
----
local stringx = require('pl.stringx')
local file = require('pl.file')
local ptb_path = "./data/"
local vocab_idx = 0
local vocab_map = {}
-- Stacks replicated, shifted versions of x_inp
-- into a single matrix of size x_inp:size(1) x batch_size.
local function replicate(x_inp, batch_size)
local s = x_inp:size(1)
local x = torch.zeros(torch.floor(s / batch_size), batch_size)
for i = 1, batch_size do
local start = torch.round((i - 1) * s / batch_size) + 1
local finish = start + x:size(1) - 1
x:sub(1, x:size(1), i, i):copy(x_inp:sub(start, finish))
end
return x
end
local function load_data(fname)
local data = file.read(fname)
data = stringx.replace(data, '\n', '<eos>')
data = stringx.split(data)
print(string.format("Loading %s, size of data = %d", fname, #data))
local x = torch.zeros(#data)
for i = 1, #data do
if vocab_map[data[i]] == nil then
vocab_idx = vocab_idx + 1
vocab_map[data[i]] = vocab_idx
end
x[i] = vocab_map[data[i]]
end
return x
end
local function traindataset(batch_size)
local x = load_data(ptb_path .. "ptb.train.txt")
x = replicate(x, batch_size)
return x
end
-- Intentionally we repeat dimensions without offseting.
-- Pass over this batch corresponds to the fully sequential processing.
local function testdataset(batch_size)
local x = load_data(ptb_path .. "ptb.test.txt")
x = x:resize(x:size(1), 1):expand(x:size(1), batch_size)
return x
end
local function validdataset(batch_size)
local x = load_data(ptb_path .. "ptb.valid.txt")
x = replicate(x, batch_size)
return x
end
return {traindataset=traindataset,
testdataset=testdataset,
validdataset=validdataset}
| apache-2.0 |
me2beats/reapack | Markers and regions/me2beats_Set time selection to nearest project or tempo markers from mouse.lua | 1 | 1589 | -- @description Set time selection to nearest project or tempo markers from mouse
-- @version 1.13
-- @author me2beats
-- @changelog
-- + init
local r = reaper; local function nothing() end; local function bla() r.defer(nothing) end
local t_start,t_end,m_start,m_end,m_start_i,t_start_i,mouse,x,y
local window, segment, details = r.BR_GetMouseCursorContext()
mouse = r.BR_GetMouseCursorContext_Position()
if not mouse or mouse ==-1 then bla() return end
m_start_i, t_start_i = r.GetLastMarkerAndCurRegion(0, mouse), r.FindTempoTimeSigMarker(0, mouse)
if m_start_i ~= -1 then
_,_, m_start = r.EnumProjectMarkers(m_start_i)
_,_, m_end = r.EnumProjectMarkers(m_start_i+1)
if m_end<=m_start then m_end = nil end
else
_,_, m_end = r.EnumProjectMarkers(0)
if m_end == -1 then m_end = nil else m_start = 0 end
end
if t_start_i ~= -1 then
_, t_start = r.GetTempoTimeSigMarker(0, t_start_i)
_, t_end = r.GetTempoTimeSigMarker(0, t_start_i+1)
if t_end<=t_start then t_end = nil end
end
if not ((m_start or t_start) and (m_end or t_end)) then bla() return end
if t_start and m_start then
if mouse-m_start < mouse-t_start then x = m_start else x = t_start end
elseif t_start then x = t_start else x = m_start end
if t_end and m_end then
if m_end-mouse < t_end-mouse then y = m_end else y = t_end end
elseif t_end then y = t_end else y = m_end end
if not (x or y) or x == y then bla() return end
r.Undo_BeginBlock() r.PreventUIRefresh(1)
r.GetSet_LoopTimeRange(1, 0, x,y, 0)
r.PreventUIRefresh(-1) r.Undo_EndBlock('Set time selection to nearest markers from mouse', -1)
| gpl-3.0 |
teleoktan/teleoktan | libs/serpent.lua | 31 | 8016 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
-- کد های پایین در ربات نشان داده نمیشوند
-- http://permag.ir
-- @permag_ir
-- @permag_bots
-- @permag
| gpl-3.0 |
jtg-gg/skia | tools/lua/skia.lua | 207 | 1863 | -- Experimental helpers for skia --
function string.startsWith(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
function string.endsWith(String,End)
return End=='' or string.sub(String,-string.len(End))==End
end
Sk = {}
function Sk.isFinite(x)
return x * 0 == 0
end
-------------------------------------------------------------------------------
Sk.Rect = { left = 0, top = 0, right = 0, bottom = 0 }
Sk.Rect.__index = Sk.Rect
function Sk.Rect.new(l, t, r, b)
local rect
if r then
-- 4 arguments
rect = { left = l, top = t, right = r, bottom = b }
elseif l then
-- 2 arguments
rect = { right = l, bottom = t }
else
-- 0 arguments
rect = {}
end
setmetatable(rect, Sk.Rect)
return rect;
end
function Sk.Rect:width()
return self.right - self.left
end
function Sk.Rect:height()
return self.bottom - self.top
end
function Sk.Rect:isEmpty()
return self:width() <= 0 or self:height() <= 0
end
function Sk.Rect:isFinite()
local value = self.left * 0
value = value * self.top
value = value * self.right
value = value * self.bottom
return 0 == value
end
function Sk.Rect:setEmpty()
self.left = 0
self.top = 0
self.right = 0
self.bottom = 0
end
function Sk.Rect:set(l, t, r, b)
self.left = l
self.top = t
self.right = r
self.bottom = b
end
function Sk.Rect:offset(dx, dy)
dy = dy or dx
self.left = self.left + dx
self.top = self.top + dy
self.right = self.right + dx
self.bottom = self.bottom + dy
end
function Sk.Rect:inset(dx, dy)
dy = dy or dx
self.left = self.left + dx
self.top = self.top + dy
self.right = self.right - dx
self.bottom = self.bottom - dy
end
-------------------------------------------------------------------------------
| bsd-3-clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.