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 |
|---|---|---|---|---|---|
barryk/CHDK-SD1200 | CHDK/SCRIPTS/examples/stopwatch.lua | 9 | 1211 | --stopwatch.lua by Kettmeister & msl from the german forum
--[[
@title stopwatch
@param a split time (1)/lap time(0)
@default a 1
]]
--declare functions
--formating output (thx fbonomi)
function format_nn(n)
r=tostring(n)
if n<10 then
r= "0" .. n
end
return r
end
--get stop time and print
function to_time()
if(a==0) then -- lap time
ztime=(get_tick_count()-count_a)/1000
count_a=get_tick_count()
else -- split time
ztime=(get_tick_count()-count_a)/1000
end
s = ztime % 60
m = (ztime / 60) % 60
h = (ztime / 3600) % 24
print("> "..format_nn(h)..":"..format_nn(m)..":"..format_nn(s))
end
--start script
if (a~=1 and a~=0) then a=1 end
i=1
ztime=0
count_a=0
cls()
print("[SET] start")
while(i==1) do
wait_click(0)
if is_pressed "set" then -- started
count_a=get_tick_count()
cls()
print("[SET] time [MENU] end")
print()
print("started")
i=0
end
end
i=1
while(i==1) do
wait_click(0)
if is_pressed "set" then -- take time
cls()
print("[SET] time [MENU] end")
print()
to_time()
end
if is_pressed "menu" then -- end
cls()
to_time()
print("finished")
sleep(3000)
i=0
end
end | gpl-2.0 |
MohammadPishro/Spam-Detector | config.lua | 1 | 6139 | return {
bot_api_key = '250803352:AAGVd91-Zn__r1nEyUkENSjEZGHcNf_moew',
version = '4.0',
cmd = '^[/!#]',
db = 2, --default redis db: 0
admin = {
owner = 102924326,
admins = {
[102924326] = true
}
},
log_chat = -1001057801239,
bot_settings = {
cache_time = {
adminlist = 18000, --5 hours (18000s)
},
testing_mode = true,
multipurpose_mode = true,
notify_bug = true,
log_api_errors = false
},
channel = '@SUBJECTCOM', --channel username with the '@'
help_groups = {
['Internatonal (English)'] = 'https://telegram.me/joinchat/CoMuIUFr88O5znpG2nxJGg', --group link, not username!
['Italian'] = false, --'https://telegram.me/joinchat/CHYUej7oPES-Gdw5hmgAXg',
['Persian'] = 'https://telegram.me/joinchat/CoMuIUFr88O5znpG2nxJGg',
['Spanish'] = false
},
plugins = {
'onmessage.lua', --THIS MUST BE THE FIRST: IF AN USER IS SPAMMING/IS BLOCKED, THE BOT WON'T GO THROUGH PLUGINS
'configure.lua',
'menu.lua',
'dashboard.lua',
'banhammer.lua',
'users.lua',
'help.lua',
'rules.lua',
'about.lua',
'service.lua',
'links.lua',
'warn.lua',
'setlang.lua',
'floodmanager.lua',
'mediasettings.lua',
'private.lua',
'admin.lua',
'restore.lua',
'test.lua',
'extra.lua', --has to be the last
},
multipurpose_plugins = {
'commit.lua',
'eightball.lua'
},
available_languages = {
['en'] = 'English 🇬🇧',
['it'] = 'Italiano 🇮🇹',
['es'] = 'Español 🇪🇸',
['pt_BR'] = 'Português 🇧🇷',
['ru'] = 'Русский 🇷🇺',
['de'] = 'Deutschland 🇩🇪',
['sv'] = 'Svensk 🇸🇪',
['ar'] = 'العربية 🇸🇩',
['fr'] = 'Français 🇫🇷',
['zh'] = '中文 🇨🇳',
['fa'] = 'فارسی 🇮🇷'
-- more to come
},
allow_fuzzy_translations = false,
media_list = {
'image',
'audio',
'video',
'sticker',
'gif',
'voice',
'contact',
'file',
'link'
},
chat_settings = {
['settings'] = {
['Welcome'] = 'on',
['Extra'] = 'on',
['Flood'] = 'off',
['Silent'] = 'off',
['Rules'] = 'off'
},
['flood'] = {
['MaxFlood'] = 5,
['ActionFlood'] = 'kick'
},
['char'] = {
['Arab'] = 'allowed',
['Rtl'] = 'allowed'
},
['floodexceptions'] = {
['text'] = 'no',
['image'] = 'no',
['video'] = 'no',
['sticker'] = 'no',
['gif'] = 'no'
},
['warnsettings'] = {
['type'] = 'ban',
['mediatype'] = 'ban',
['max'] = 3,
['mediamax'] = 2
},
['welcome'] = {
['type'] = 'no',
['content'] = 'no'
},
['media'] = {
['image'] = 'ok', --'notok'
['audio'] = 'ok',
['video'] = 'ok',
['sticker'] = 'ok',
['gif'] = 'ok',
['voice'] = 'ok',
['contact'] = 'ok',
['file'] = 'ok',
['link'] = 'ok',
['TGlink'] = 'ok'
},
},
private_settings = {
rules_on_join = 'on',
motivation_on_kick = 'on',
reports = 'off'
},
chat_custom_texts = {'extra', 'info', 'links', 'warns', 'mediawarn'},
bot_keys = {
d3 = {'bot:general', 'bot:usernames', 'bot:chat:latsmsg'},
d2 = {'bot:groupsid', 'bot:groupsid:removed', 'tempbanned', 'bot:blocked'}
},
api_errors = {
[101] = 'Not enough rights to kick participant', --SUPERGROUP: bot is not admin
[102] = 'USER_ADMIN_INVALID', --SUPERGROUP: trying to kick an admin
[103] = 'method is available for supergroup chats only', --NORMAL: trying to unban
[104] = 'Only creator of the group can kick administrators from the group', --NORMAL: trying to kick an admin
[105] = 'Bad Request: Need to be inviter of the user to kick it from the group', --NORMAL: bot is not an admin or everyone is an admin
[106] = 'USER_NOT_PARTICIPANT', --NORMAL: trying to kick an user that is not in the group
[107] = 'CHAT_ADMIN_REQUIRED', --NORMAL: bot is not an admin or everyone is an admin
[108] = 'there is no administrators in the private chat', --something asked in a private chat with the api methods 2.1
[110] = 'PEER_ID_INVALID', --user never started the bot
[111] = 'message is not modified', --the edit message method hasn't modified the message
[112] = 'Can\'t parse message text: Can\'t find end of the entity starting at byte offset %d+', --the markdown is wrong and breaks the delivery
[113] = 'group chat is migrated to a supergroup chat', --group updated to supergroup
[114] = 'Message can\'t be forwarded', --unknown
[115] = 'Message text is empty', --empty message
[116] = 'message not found', --message id invalid, I guess
[117] = 'chat not found', --I don't know
[118] = 'Message is too long', --over 4096 char
[119] = 'User not found', --unknown user_id
[120] = 'Can\'t parse reply keyboard markup JSON object', --keyboard table invalid
[121] = 'Field \\\"inline_keyboard\\\" of the InlineKeyboardMarkup should be an Array of Arrays', --inline keyboard is not an array of array
[122] = 'Can\'t parse inline keyboard button: InlineKeyboardButton should be an Object',
[123] = 'Bad Request: Object expected as reply markup', --empty inline keyboard table
[124] = 'QUERY_ID_INVALID', --callback query id invalid
[125] = 'CHANNEL_PRIVATE', --I don't know
[126] = 'MESSAGE_TOO_LONG', --text of an inline callback answer is too long
[127] = 'wrong user_id specified', --invalid user_id
[128] = 'Too big total timeout [%d%.]+', --something about spam an inline keyboards
[129] = 'BUTTON_DATA_INVALID', --callback_data string invalid
[130] = 'Type of file to send mismatch', --trying to send a media with the wrong method
[131] = 'MESSAGE_ID_INVALID', --I don't know
[132] = 'Can\'t parse inline keyboard button: Can\'t find field "text"', --the text of a button could be nil
[133] = 'Can\'t parse inline keyboard button: Field "text" must be of type String',
[134] = 'USER_ID_INVALID',
[135] = 'CHAT_INVALID',
[136] = 'USER_DEACTIVATED', --deleted account, probably
[137] = 'Can\'t parse inline keyboard button: Text buttons are unallowed in the inline keyboard',
[138] = 'Message was not forwarded',
[403] = 'Bot was blocked by the user', --user blocked the bot
[429] = 'Too many requests: retry later', --the bot is hitting api limits
[430] = 'Too big total timeout', --too many callback_data requests
}
}
| gpl-2.0 |
the-useless-one/useless_dotfiles | config/awesome/themes/zenburn/theme.lua | 6 | 5400 | -------------------------------
-- "Zenburn" awesome theme --
-- By Adrian C. (anrxc) --
-------------------------------
-- Alternative icon sets and widget icons:
-- * http://awesome.naquadah.org/wiki/Nice_Icons
-- {{{ Main
theme = {}
theme.wallpaper_cmd = { "awsetbg /usr/share/awesome/themes/zenburn/zenburn-background.png" }
-- }}}
-- {{{ Styles
theme.font = "sans 8"
-- {{{ Colors
theme.fg_normal = "#DCDCCC"
theme.fg_focus = "#F0DFAF"
theme.fg_urgent = "#CC9393"
theme.bg_normal = "#3F3F3F"
theme.bg_focus = "#1E2320"
theme.bg_urgent = "#3F3F3F"
-- }}}
-- {{{ Borders
theme.border_width = "2"
theme.border_normal = "#3F3F3F"
theme.border_focus = "#6F6F6F"
theme.border_marked = "#CC9393"
-- }}}
-- {{{ Titlebars
theme.titlebar_bg_focus = "#3F3F3F"
theme.titlebar_bg_normal = "#3F3F3F"
-- }}}
-- There are other variable sets
-- overriding the default one when
-- defined, the sets are:
-- [taglist|tasklist]_[bg|fg]_[focus|urgent]
-- titlebar_[normal|focus]
-- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color]
-- Example:
--theme.taglist_bg_focus = "#CC9393"
-- }}}
-- {{{ Widgets
-- You can add as many variables as
-- you wish and access them by using
-- beautiful.variable in your rc.lua
--theme.fg_widget = "#AECF96"
--theme.fg_center_widget = "#88A175"
--theme.fg_end_widget = "#FF5656"
--theme.bg_widget = "#494B4F"
--theme.border_widget = "#3F3F3F"
-- }}}
-- {{{ Mouse finder
theme.mouse_finder_color = "#CC9393"
-- mouse_finder_[timeout|animate_timeout|radius|factor]
-- }}}
-- {{{ Menu
-- Variables set for theming the menu:
-- menu_[bg|fg]_[normal|focus]
-- menu_[border_color|border_width]
theme.menu_height = "15"
theme.menu_width = "100"
-- }}}
-- {{{ Icons
-- {{{ Taglist
theme.taglist_squares_sel = "/usr/share/awesome/themes/zenburn/taglist/squarefz.png"
theme.taglist_squares_unsel = "/usr/share/awesome/themes/zenburn/taglist/squarez.png"
--theme.taglist_squares_resize = "false"
-- }}}
-- {{{ Misc
theme.awesome_icon = "/usr/share/awesome/themes/zenburn/awesome-icon.png"
theme.menu_submenu_icon = "/usr/share/awesome/themes/default/submenu.png"
theme.tasklist_floating_icon = "/usr/share/awesome/themes/default/tasklist/floatingw.png"
-- }}}
-- {{{ Layout
theme.layout_tile = "/usr/share/awesome/themes/zenburn/layouts/tile.png"
theme.layout_tileleft = "/usr/share/awesome/themes/zenburn/layouts/tileleft.png"
theme.layout_tilebottom = "/usr/share/awesome/themes/zenburn/layouts/tilebottom.png"
theme.layout_tiletop = "/usr/share/awesome/themes/zenburn/layouts/tiletop.png"
theme.layout_fairv = "/usr/share/awesome/themes/zenburn/layouts/fairv.png"
theme.layout_fairh = "/usr/share/awesome/themes/zenburn/layouts/fairh.png"
theme.layout_spiral = "/usr/share/awesome/themes/zenburn/layouts/spiral.png"
theme.layout_dwindle = "/usr/share/awesome/themes/zenburn/layouts/dwindle.png"
theme.layout_max = "/usr/share/awesome/themes/zenburn/layouts/max.png"
theme.layout_fullscreen = "/usr/share/awesome/themes/zenburn/layouts/fullscreen.png"
theme.layout_magnifier = "/usr/share/awesome/themes/zenburn/layouts/magnifier.png"
theme.layout_floating = "/usr/share/awesome/themes/zenburn/layouts/floating.png"
-- }}}
-- {{{ Titlebar
theme.titlebar_close_button_focus = "/usr/share/awesome/themes/zenburn/titlebar/close_focus.png"
theme.titlebar_close_button_normal = "/usr/share/awesome/themes/zenburn/titlebar/close_normal.png"
theme.titlebar_ontop_button_focus_active = "/usr/share/awesome/themes/zenburn/titlebar/ontop_focus_active.png"
theme.titlebar_ontop_button_normal_active = "/usr/share/awesome/themes/zenburn/titlebar/ontop_normal_active.png"
theme.titlebar_ontop_button_focus_inactive = "/usr/share/awesome/themes/zenburn/titlebar/ontop_focus_inactive.png"
theme.titlebar_ontop_button_normal_inactive = "/usr/share/awesome/themes/zenburn/titlebar/ontop_normal_inactive.png"
theme.titlebar_sticky_button_focus_active = "/usr/share/awesome/themes/zenburn/titlebar/sticky_focus_active.png"
theme.titlebar_sticky_button_normal_active = "/usr/share/awesome/themes/zenburn/titlebar/sticky_normal_active.png"
theme.titlebar_sticky_button_focus_inactive = "/usr/share/awesome/themes/zenburn/titlebar/sticky_focus_inactive.png"
theme.titlebar_sticky_button_normal_inactive = "/usr/share/awesome/themes/zenburn/titlebar/sticky_normal_inactive.png"
theme.titlebar_floating_button_focus_active = "/usr/share/awesome/themes/zenburn/titlebar/floating_focus_active.png"
theme.titlebar_floating_button_normal_active = "/usr/share/awesome/themes/zenburn/titlebar/floating_normal_active.png"
theme.titlebar_floating_button_focus_inactive = "/usr/share/awesome/themes/zenburn/titlebar/floating_focus_inactive.png"
theme.titlebar_floating_button_normal_inactive = "/usr/share/awesome/themes/zenburn/titlebar/floating_normal_inactive.png"
theme.titlebar_maximized_button_focus_active = "/usr/share/awesome/themes/zenburn/titlebar/maximized_focus_active.png"
theme.titlebar_maximized_button_normal_active = "/usr/share/awesome/themes/zenburn/titlebar/maximized_normal_active.png"
theme.titlebar_maximized_button_focus_inactive = "/usr/share/awesome/themes/zenburn/titlebar/maximized_focus_inactive.png"
theme.titlebar_maximized_button_normal_inactive = "/usr/share/awesome/themes/zenburn/titlebar/maximized_normal_inactive.png"
-- }}}
-- }}}
return theme
| gpl-3.0 |
cochrane/OpenTomb | scripts/level/tr1/LEVEL1.lua | 2 | 1111 | -- OPENTOMB STATIC MESH COLLISION SCRIPT
-- FOR TOMB RAIDER, LEVEL1 (CAVES)
print("Level script loaded (LEVEL1.lua)");
-- STATIC COLLISION FLAGS ------------------------------------------------------
--------------------------------------------------------------------------------
static_tbl[06] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Hanging plant
static_tbl[08] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Hanging plant
static_tbl[10] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Wood barrier
static_tbl[33] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Bridge part 1
static_tbl[34] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Bridge part 2
static_tbl[38] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Door frame
static_tbl[39] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Wall bricks
static_tbl[43] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Icicle
| lgpl-3.0 |
cochrane/OpenTomb | scripts/level/tr2/WALL.lua | 2 | 1189 | -- OPENTOMB LEVEL SCRIPT
-- FOR TOMB RAIDER 2, WALL.TR2
print("Level script loaded (WALL.lua)");
-- STATIC COLLISION FLAGS ------------------------------------------------------
--------------------------------------------------------------------------------
static_tbl[00] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Bank rock
static_tbl[01] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Death slide rope
static_tbl[02] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Skeleton 1
static_tbl[03] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Skeleton 2
static_tbl[04] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Cobweb
static_tbl[10] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Fireplace
static_tbl[11] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Crate with book
static_tbl[12] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Briefcase
static_tbl[13] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Crates | lgpl-3.0 |
plinkopenguin/wire-extras | lua/entities/gmod_wire_realmagnet/init.lua | 1 | 3369 |
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.OverlayUpdateRate=2
ENT.LastOverlayUpdate=1
ENT.WireDebugName = "Magnet"
function ENT:Initialize()
--self:SetModel("models/props_junk/gascan001a.mdl")
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self, { "On", "Strength", "Effect length" })
self.TargetPlayers = false
--self:SetBeamLength(2048)
--self:ShowOutput()
self:SetOn(false)
self:TriggerInput("On", 0)
self:ShowOutput()
end
function ENT:OnRemove()
Wire_Remove(self)
end
function ENT:Setup(mdl,trgmetal,str,leng,mdlfilter)
self:SetModel(mdl)
self:SetPropFilter(mdlfilter)
self:SetTargetOnlyMetal(trgmetal)
self:SetStrength(str)
self:SetLength(leng)
end
function ENT:Think()
if self:IsOn()==true then
--print(tostring(self:GetLength()))
local entsTA=ents.FindInSphere(self:GetPos(),self:GetLength())
local myPos=self:GetPos()
for k,ent in pairs(entsTA) do
if ent:IsValid() and ent!=self and ent:GetModel()!=nil and ent:GetModel()!="" then
//model
if self:GetPropFilter()==nil or self:GetPropFilter()=="" or (self:GetPropFilter()!="" and string.find( ent:GetModel(),self:GetPropFilter())!=nil) then//(self:IsTargetOnlyMetal()==false) or (self:IsTargetOnlyMetal()==true and tr.MatType != MAT_METAL Stuff not done yet
local phys = ent:GetPhysicsObject();
if phys:IsValid() then
--[[local tdata={}
tdata.start=myPos
tdata.endpos=ent:GetPos()
local tr=util.TraceLine(tdata)]]
local direction = ent:GetPos()-myPos
local dist=math.sqrt(((ent:GetPos().x-myPos.x)^2)+((ent:GetPos().y-myPos.y)^2)+((ent:GetPos().z-myPos.z)^2))
dist=dist/self:GetLength()
dist=math.abs(dist-1)
if self:IsBackwards()==true then dist=-dist end
direction:Normalize()
direction = direction*(1*-(self.Strength*dist))
phys:ApplyForceCenter(direction)
phys:Wake()
end
end
end
end
end
//WHY DOESNT THE OVERLAY WORK?!?
/*if self.LastOverlayUpdate+self.OverlayUpdateRate<CurTime() then
self:ShowOutput()
self.LastOverlayUpdate=CurTime()
end*/
self:NextThink( CurTime() + self.CachedTickRate)
return true
end
function ENT:TriggerInput(iname, value)
self.CachedTickRate=GetConVarNumber("sbox_wire_magnets_tickrate")
if (iname == "On") then
if (value > 0) then
self:SetOn(true)
else
self:SetOn(false)
end
self:ShowOutput()
else
if(iname == "Strength") then
self:SetStrength(value)
self:ShowOutput()
end
if(iname == "Effect length") then
self:SetLength(value)
self:ShowOutput()
end
end
end
function ENT:ShowOutput()
//set overlay
local ontxt="Off"
if self:IsOn()==true then ontxt="On" end
self:SetOverlayText(
"Wire Magnet"
)
end
function ENT:OnRestore()
Wire_Restored(self)
end
function ENT:SpawnFunction( ply, tr)
if ( !tr.Hit ) then return end
local SpawnPos = tr.HitPos + tr.HitNormal * 16
local ent = ents.Create( "gmod_wire_realmagnet" )
ent:SetPos( SpawnPos )
ent:Spawn()
ent:Activate()
return ent
end
| gpl-3.0 |
jackscott/thrift | test/lua/test_basic_client.lua | 57 | 7626 | -- 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('TSocket')
require('TBinaryProtocol')
require('ThriftTest_ThriftTest')
require('liblualongnumber')
local client
function teardown()
if client then
-- Shuts down the server
client:testVoid()
-- close the connection
client:close()
end
end
function assertEqual(val1, val2, msg)
assert(val1 == val2, msg)
end
function testBasicClient()
local socket = TSocket:new{
port = 9090
}
assert(socket, 'Failed to create client socket')
socket:setTimeout(5000)
local protocol = TBinaryProtocol:new{
trans = socket
}
assert(protocol, 'Failed to create binary protocol')
client = ThriftTestClient:new{
protocol = protocol
}
assert(client, 'Failed to create client')
-- Open the socket
local status, _ = pcall(socket.open, socket)
assert(status, 'Failed to connect to server')
-- String
assertEqual(client:testString('lala'), 'lala', 'Failed testString')
assertEqual(client:testString('wahoo'), 'wahoo', 'Failed testString')
-- Byte
assertEqual(client:testByte(0x01), 1, 'Failed testByte 1')
assertEqual(client:testByte(0x40), 64, 'Failed testByte 2')
assertEqual(client:testByte(0x7f), 127, 'Failed testByte 3')
assertEqual(client:testByte(0x80), -128, 'Failed testByte 4')
assertEqual(client:testByte(0xbf), -65, 'Failed testByte 5')
assertEqual(client:testByte(0xff), -1, 'Failed testByte 6')
assertEqual(client:testByte(128), -128, 'Failed testByte 7')
assertEqual(client:testByte(255), -1, 'Failed testByte 8')
-- I32
assertEqual(client:testI32(0x00000001), 1, 'Failed testI32 1')
assertEqual(client:testI32(0x40000000), 1073741824, 'Failed testI32 2')
assertEqual(client:testI32(0x7fffffff), 2147483647, 'Failed testI32 3')
assertEqual(client:testI32(0x80000000), -2147483648, 'Failed testI32 4')
assertEqual(client:testI32(0xbfffffff), -1073741825, 'Failed testI32 5')
assertEqual(client:testI32(0xffffffff), -1, 'Failed testI32 6')
assertEqual(client:testI32(2147483648), -2147483648, 'Failed testI32 7')
assertEqual(client:testI32(4294967295), -1, 'Failed testI32 8')
-- I64 (lua only supports 16 decimal precision so larger numbers are
-- initialized by their string value)
local long = liblualongnumber.new
assertEqual(client:testI64(long(0x0000000000000001)),
long(1),
'Failed testI64 1')
assertEqual(client:testI64(long(0x4000000000000000)),
long(4611686018427387904),
'Failed testI64 2')
assertEqual(client:testI64(long('0x7fffffffffffffff')),
long('9223372036854775807'),
'Failed testI64 3')
assertEqual(client:testI64(long(0x8000000000000000)),
long(-9223372036854775808),
'Failed testI64 4')
assertEqual(client:testI64(long('0xbfffffffffffffff')),
long('-4611686018427387905'),
'Failed testI64 5')
assertEqual(client:testI64(long('0xffffffffffffffff')),
long(-1),
'Failed testI64 6')
-- Double
assertEqual(
client:testDouble(1.23456789), 1.23456789, 'Failed testDouble 1')
assertEqual(
client:testDouble(0.123456789), 0.123456789, 'Failed testDouble 2')
assertEqual(
client:testDouble(0.123456789), 0.123456789, 'Failed testDouble 3')
-- TODO testBinary() ...
-- Accuracy of 16 decimal digits (rounds)
local a, b = 1.12345678906666663, 1.12345678906666661
assertEqual(a, b)
assertEqual(client:testDouble(a), b, 'Failed testDouble 5')
-- Struct
local a = {
string_thing = 'Zero',
byte_thing = 1,
i32_thing = -3,
i64_thing = long(-5)
}
-- TODO fix client struct equality
--assertEqual(client:testStruct(a), a, 'Failed testStruct')
-- Call the void function and end the test (handler stops server)
client:testVoid()
end
testBasicClient()
teardown() | apache-2.0 |
barryk/CHDK-SD1200 | CHDK/SCRIPTS/examples/input_1.lua | 9 | 2958 | --[[
@title char input
@param f key delay
@default f 200
]]
key_delay = f
output=""
function button()
local x = 0
repeat
wait_click(key_delay)
if is_pressed "remote" then
key = "REMOTE"
x = 1
end
if is_pressed "set" then
key = "SET"
x = 1
end
if is_pressed "erase" then
key = "ERASE"
x = 1
end
if is_pressed "display" then
key = "DISP."
x = 1
end
if is_pressed "menu" then
key = "MENU"
x = 1
end
if is_pressed "up" then
key = "UP"
x = 1
end
if is_pressed "down" then
key = "DOWN"
x = 1
end
if is_pressed "left" then
key = "LEFT"
x = 1
end
if is_pressed "right" then
key = "RIGHT"
x = 1
end
if is_pressed "zoom_in" then
key = "ZOOM_IN"
x = 1
end
if is_pressed "zoom_out" then
key = "ZOOM_OUT"
x = 1
end
until x == 1
set_led (8,1)
sleep (10)
set_led (8,0)
end
function tabToStr()
output=table.concat(word)
end
function input()
abc_lower = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p",
"q","r","s","t","u","v","w","x","y","z"}
abc_upper = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P",
"Q","R","S","T","U","V","W","X","Y","Z"}
abc_spec = {"0","1","2","3","4","5","6","7","8","9",",",".","-",";",":","_",
"/",".JPG",".CRW",".CR2",".THM",".WAV",".LUA",".BAS",".TXT"," "}
word = {}
a=0
b=0
actChar=""
repeat
print("[<-][->][SET] [+/-][MENU]")
print("[ZOOM in/out] [UP][DOWN]")
button()
cls()
if key == "RIGHT" then a=a+1 end
if key == "LEFT" then a=a-1 end
if key == "UP" then b=b+1 end
if key == "DOWN" then a=1 end
if key == "ZOOM_IN" then a=a+5 end
if key == "ZOOM_OUT" then a=a-5 end
if a >= 27 then a=1 end
if a <= 0 then a=26 end
if b>=3 then b=0 end
if b==0 then
actChar=abc_lower[a]
char_info="lower case"
end
if b==1 then
actChar=abc_upper[a]
char_info="upper case"
end
if b==2 then
actChar=abc_spec[a]
char_info="special char"
end
print(char_info..": "..actChar)
if key == "SET" then table.insert(word,actChar) end
if key == "ERASE" then table.remove(word) end
tabToStr()
print("input: "..output)
print (" ")
until key == "MENU"
end
function make_dir(dirname)
os.mkdir(dirname)
end
x=0
repeat
input()
cls()
print("INPUT: "..output)
print("[SET] new input")
print("[DISP] make dir and stop")
print("[MENU] stop")
button()
if key == "SET" then cls() end
if key == "DISP." then
dir = "A/"..output
make_dir(dir)
print "ready"
sleep(3000)
x=1
end
if key == "MENU" then
print "ready"
sleep(3000)
x=1
end
until x==1
--[[
***possible commands***
function make_dir(dirname)
os.mkdir(dirname)
end
function delete_dir(dirname)
os.remove(dirname)
end
function rename_file(old_filename, new_filename)
os.rename(old_filename, new_filename)
end
function delete_file(filename)
os.remove(filename)
end
***missing commands***
-os.list_dir
]]
| gpl-2.0 |
cochrane/OpenTomb | scripts/level/tr4/BIKEBIT.lua | 2 | 4662 | -- OPENTOMB LEVEL SCRIPT
-- FOR TOMB RAIDER 4, BIKEBIT.TR4
print("Level script loaded (BIKEBIT)");
-- STATIC COLLISION FLAGS ------------------------------------------------------
--------------------------------------------------------------------------------
static_tbl[01] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Tower
static_tbl[04] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Wall light
static_tbl[10] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Stone wall block
static_tbl[11] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Stone wall block 2
static_tbl[12] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Stone wall block 3
static_tbl[13] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Stone wall block 4
static_tbl[14] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Ladder
static_tbl[15] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Green top
static_tbl[16] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Pole
static_tbl[17] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Stone arch
static_tbl[18] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Thick pillar
static_tbl[19] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Ceiling part
static_tbl[20] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Stairs
static_tbl[21] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Stairs 2
static_tbl[22] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Pillar
static_tbl[23] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Pillar arches
static_tbl[24] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Street around the corner
static_tbl[25] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Stairs 3
static_tbl[26] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Stairs 4
static_tbl[27] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Pedestal
static_tbl[28] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Pedestal 2
static_tbl[31] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Stone arch part
static_tbl[32] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Ceiling part
static_tbl[34] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Rounded building
static_tbl[36] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Tower 2
static_tbl[37] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Tower 3
static_tbl[38] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Balcony
static_tbl[39] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Balcony 2
static_tbl[40] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Doorway
static_tbl[41] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX, hide = 1}; -- Doorway dummy mesh 1
static_tbl[42] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX, hide = 1}; -- Doorway dummy mesh 2
static_tbl[43] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Stairs 5
static_tbl[44] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Fence
static_tbl[45] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Grated fence 1
static_tbl[46] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Grated fence 2
static_tbl[47] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Stone decoration
static_tbl[48] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Stone arch part 2
static_tbl[49] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Stone arch part 3
-- SHATTER STATICS
static_tbl[51] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Ice spirit capsule
static_tbl[52] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Warning fence
static_tbl[53] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Fuel barrel
| lgpl-3.0 |
loringmoore/The-Forgotten-Server | data/spells/scripts/custom/apocalypse.lua | 14 | 1199 | local combat = createCombatObject()
arr = {
{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0},
{0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0},
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0},
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0},
{1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1},
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0},
{0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0},
{0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0},
{0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0},
{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0},
}
local area = createCombatArea(arr)
setCombatArea(combat, area)
function spellCallback(param)
if isCreature(param.cid) then
if param.count > 0 or math.random(0, 1) == 1 and isCreature(param.cid) then
doSendMagicEffect(param.pos, CONST_ME_HITBYFIRE)
doAreaCombatHealth(param.cid, COMBAT_FIREDAMAGE, param.pos, 0, -100, -100, CONST_ME_EXPLOSIONHIT)
end
if(param.count < 5) then
param.count = param.count + 1
addEvent(spellCallback, math.random(1000, 4000), param)
end
end
end
function onTargetTile(cid, pos)
local param = {}
param.cid = cid
param.pos = pos
param.count = 0
spellCallback(param)
end
setCombatCallback(combat, CALLBACK_PARAM_TARGETTILE, "onTargetTile")
function onCastSpell(cid, var)
return doCombat(cid, combat, var)
end
| gpl-2.0 |
TheUltimateMuffin/MineWacke | town_protection/init.lua | 1 | 3655 | meta_save_location = vector.new(0,0,0)
local function town_center_after_place_node(pos, placer, itemstack, pointed_thing)
local meta = minetest.env:get_meta(pos)
local protection_positions = {}
meta:set_int("posx", 0)
meta:set_int("posy", 0)
meta:set_int("posz", 0)
meta:set_int("negx", 0)
meta:set_int("negy", 0)
meta:set_int("negz", 0)
meta:set_string("owner", placer:get_player_name())
local save_meta = minetest.env:get_meta(meta_save_location)
if save_meta:get_string("prot_saves") ~= "" then
protection_positions = minetest.parse_json(save_meta:get_string("prot_saves"))
end
table.insert(protection_positions, pos)
print(minetest.write_json(protection_positions).. "whoop")
save_meta:set_string("prot_saves", minetest.write_json(protection_positions))
end
local function town_center_on_rightclick(pos, node, player, itemstack, pointed_thing)
local meta = minetest.env:get_meta(pos)
local form
--minetest.env:set_node_level(pos, 40)
if player:get_player_name() ~= meta:get_string("owner") then
--Formspec for buyer
form = "size[13,10;]"..
"list[current_player;main;4.5,6;8,4;]"
minetest.show_formspec(player:get_player_name(), "Town Center", form)
else
--formspec for seller
form = "size[10,10;]"..
"field[1,1;2,1;plux;Positive X;0]"..
"field[0,2;2,1;pluy;Positive Y;0]"..
"field[2,2;2,1;pluz;Positive Z;0]"..
"field[1,3;2,1;negx;Negative X;0]"..
"field[5,1;2,1;negy;Negative X;0]"..
"field[5,2;2,1;negz;Negative X;0]"..
"button[8,2;2,1;set;Set Protection]"..
"bgcolor[#008900b0;false]"..
--these are to send the node's location as fields to the player when it receives a button press and makes a second formspec
"field[0,0;0,0;posx;;"..pos["x"].."]"..
"field[0,0;0,0;posy;;"..pos["y"].."]"..
"field[0,0;0,0;posz;;"..pos["z"].."]"
minetest.show_formspec(player:get_player_name(), "Town Center", form)
end
end
local old_is_protected = minetest.is_protected
function minetest.is_protected(pos, name)
local save_meta = minetest.env:get_meta(meta_save_location)
local protection_positions = {}
if save_meta:get_string("prot_saves") ~= "" then
protection_positions = minetest.parse_json(save_meta:get_string("prot_saves"))
end
for a, pos_check in pairs(protection_positions) do
local meta = minetest.env:get_meta(pos_check)
if name ~= meta:get_string("owner") and
(pos.x < pos_check.x + meta:get_int("posx") and pos.y < pos_check.y + meta:get_int("posy") and pos.z < pos_check.z + meta:get_int("posz") and pos.x > pos_check.x - meta:get_int("negx") and pos.y > pos_check.y - meta:get_int("negy") and pos.z > pos_check.z - meta:get_int("negz")) then
print("achoo")
return true
end
end
return old_is_protected(pos, name)
end
minetest.register_on_player_receive_fields(function(player, formname, fields)
if formname == "Town Center" then
local meta = minetest.env:get_meta(vector.new(tonumber(fields.posx),tonumber(fields.posy),tonumber(fields.posz)))
if fields.set == "Set Protection" then
meta:set_int("posx", tonumber(fields.plux))
meta:set_int("posy", tonumber(fields.pluy))
meta:set_int("posz", tonumber(fields.pluz))
meta:set_int("negx", tonumber(fields.negx))
meta:set_int("negy", tonumber(fields.negy))
meta:set_int("negz", tonumber(fields.negz))
end
end
end)
minetest.register_on_protection_violation(function(pos, name)
print("hello")
end)
minetest.register_node("town_protection:town_center", {
description = "Protection Block",
tiles = {"house.png"},
groups = {melty=3, oddly_breakable_by_hand=3, choppy=3},
after_place_node = town_center_after_place_node,
on_rightclick = town_center_on_rightclick,
}) | lgpl-2.1 |
cochrane/OpenTomb | scripts/level/tr3/COMPOUND.lua | 2 | 2403 | -- OPENTOMB LEVEL SCRIPT
-- FOR TOMB RAIDER 3, COMPOUND.TR2
print("Level script loaded (COMPOUND.lua)");
-- STATIC COLLISION FLAGS ------------------------------------------------------
--------------------------------------------------------------------------------
static_tbl[10] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Misaligned crate
static_tbl[20] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Truck
static_tbl[21] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Truck wheels
static_tbl[23] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Dining desk 1
static_tbl[24] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Dining desk 2
static_tbl[25] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Twin chain
static_tbl[26] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Ceiling lamp
static_tbl[30] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Sink
static_tbl[31] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- WC
static_tbl[32] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Vertical pole
static_tbl[33] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Grated panel
static_tbl[34] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Chair
static_tbl[35] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Mainframe 1
static_tbl[36] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Mainframe 2
static_tbl[37] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- Sink set
static_tbl[38] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_TRIMESH}; -- WC set
static_tbl[39] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Keypad
static_tbl[40] = {coll = COLLISION_TYPE_STATIC, shape = COLLISION_SHAPE_BOX}; -- Pipe
static_tbl[41] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Food 1
static_tbl[42] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- Food 2
static_tbl[47] = {coll = COLLISION_TYPE_NONE, shape = COLLISION_SHAPE_BOX}; -- F-117
| lgpl-3.0 |
paulmarsy/Console | Libraries/nmap/App/nselib/ipp.lua | 6 | 12844 | local bin = require "bin"
local http = require "http"
local nmap = require "nmap"
local os = require "os"
local stdnse = require "stdnse"
local tab = require "tab"
local table = require "table"
_ENV = stdnse.module("ipp", stdnse.seeall)
---
--
-- A small CUPS ipp (Internet Printing Protocol) library implementation
--
-- @author Patrik Karlsson
--
-- The IPP layer
IPP = {
StatusCode = {
OK = 0,
},
State = {
IPP_JOB_PENDING = 3,
IPP_JOB_HELD = 4,
IPP_JOB_PROCESSING = 5,
IPP_JOB_STOPPED = 6,
IPP_JOB_CANCELED = 7,
IPP_JOB_ABORTED = 8,
IPP_JOB_COMPLETED = 9,
},
StateName = {
[3] = "Pending",
[4] = "Held",
[5] = "Processing",
[6] = "Stopped",
[7] = "Canceled",
[8] = "Aborted",
[9] = "Completed",
},
OperationID = {
IPP_CANCEL_JOB = 0x0008,
IPP_GET_JOB_ATTRIBUTES = 0x0009,
IPP_GET_JOBS = 0x000a,
CUPS_GET_PRINTERS = 0x4002,
CUPS_GET_DOCUMENT = 0x4027
},
PrinterState = {
IPP_PRINTER_IDLE = 3,
IPP_PRINTER_PROCESSING = 4,
IPP_PRINTER_STOPPED = 5,
},
Attribute = {
IPP_TAG_OPERATION = 0x01,
IPP_TAG_JOB = 0x02,
IPP_TAG_END = 0x03,
IPP_TAG_PRINTER = 0x04,
IPP_TAG_INTEGER = 0x21,
IPP_TAG_ENUM = 0x23,
IPP_TAG_NAME = 0x42,
IPP_TAG_KEYWORD = 0x44,
IPP_TAG_URI = 0x45,
IPP_TAG_CHARSET = 0x47,
IPP_TAG_LANGUAGE = 0x48,
new = function(self, tag, name, value)
local o = { tag = tag, name = name, value = value }
setmetatable(o, self)
self.__index = self
return o
end,
parse = function(data, pos)
local attrib = IPP.Attribute:new()
local val
pos, attrib.tag, attrib.name, val = bin.unpack(">CPP", data, pos)
-- print(attrib.name, stdnse.tohex(val))
attrib.value = {}
table.insert(attrib.value, { tag = attrib.tag, val = val })
repeat
local tag, name_len, val
if ( #data < pos + 3 ) then
break
end
pos, tag, name_len = bin.unpack(">CS", data, pos)
if ( name_len == 0 ) then
pos, val = bin.unpack(">P", data, pos)
table.insert(attrib.value, { tag = tag, val = val })
else
pos = pos - 3
end
until( name_len ~= 0 )
-- do minimal decoding
for i=1, #attrib.value do
if ( attrib.value[i].tag == IPP.Attribute.IPP_TAG_INTEGER ) then
attrib.value[i].val = select(2, bin.unpack(">I", attrib.value[i].val))
elseif ( attrib.value[i].tag == IPP.Attribute.IPP_TAG_ENUM ) then
attrib.value[i].val = select(2, bin.unpack(">I", attrib.value[i].val))
end
end
if ( 1 == #attrib.value ) then
attrib.value = attrib.value[1].val
end
--print(attrib.name, attrib.value, stdnse.tohex(val))
return pos, attrib
end,
__tostring = function(self)
if ( "string" == type(self.value) ) then
return bin.pack(">CSASA", self.tag, #self.name, self.name, #self.value, self.value)
else
local data = bin.pack(">CSASA", self.tag, #self.name, self.name, #self.value[1].val, self.value[1].val)
for i=2, #self.value do
data = data .. bin.pack(">CSP", self.value[i].tag, 0, self.value[i].val)
end
return data
end
end
},
-- An attribute group, groups several attributes
AttributeGroup = {
new = function(self, tag, attribs)
local o = { tag = tag, attribs = attribs or {} }
setmetatable(o, self)
self.__index = self
return o
end,
addAttribute = function(self, attrib)
table.insert(self.attribs, attrib)
end,
--
-- Gets the first attribute matching name and optionally tag from the
-- attribute group.
--
-- @param name string containing the attribute name
-- @param tag number containing the attribute tag
getAttribute = function(self, name, tag)
for _, attrib in ipairs(self.attribs) do
if ( attrib.name == name ) then
if ( not(tag) ) then
return attrib
elseif ( tag and attrib.tag == tag ) then
return attrib
end
end
end
end,
getAttributeValue = function(self, name, tag)
for _, attrib in ipairs(self.attribs) do
if ( attrib.name == name ) then
if ( not(tag) ) then
return attrib.value
elseif ( tag and attrib.tag == tag ) then
return attrib.value
end
end
end
end,
__tostring = function(self)
local data = bin.pack("C", self.tag)
for _, attrib in ipairs(self.attribs) do
data = data .. tostring(attrib)
end
return data
end
},
-- The IPP request
Request = {
new = function(self, opid, reqid)
local o = {
version = 0x0101,
opid = opid,
reqid = reqid,
attrib_groups = {},
}
setmetatable(o, self)
self.__index = self
return o
end,
addAttributeGroup = function(self, group)
table.insert( self.attrib_groups, group )
end,
__tostring = function(self)
local data = bin.pack(">SSI", self.version, self.opid, self.reqid )
for _, group in ipairs(self.attrib_groups) do
data = data .. tostring(group)
end
data = data .. bin.pack("C", IPP.Attribute.IPP_TAG_END)
return data
end,
},
-- A class to handle responses from the server
Response = {
-- Creates a new instance of response
new = function(self)
local o = {}
setmetatable(o, self)
self.__index = self
return o
end,
getAttributeGroups = function(self, tag)
local groups = {}
for _, v in ipairs(self.attrib_groups or {}) do
if ( v.tag == tag ) then
table.insert(groups, v)
end
end
return groups
end,
parse = function(data)
local resp = IPP.Response:new()
local pos
pos, resp.version, resp.status, resp.reqid = bin.unpack(">SSI", data)
resp.attrib_groups = {}
local group
repeat
local tag, attrib
pos, tag = bin.unpack(">C", data, pos)
if ( tag == IPP.Attribute.IPP_TAG_OPERATION or
tag == IPP.Attribute.IPP_TAG_JOB or
tag == IPP.Attribute.IPP_TAG_PRINTER or
tag == IPP.Attribute.IPP_TAG_END ) then
if ( group ) then
table.insert(resp.attrib_groups, group)
group = IPP.AttributeGroup:new(tag)
else
group = IPP.AttributeGroup:new(tag)
end
else
pos = pos - 1
end
if ( not(group) ) then
stdnse.debug2("Unexpected tag: %d", tag)
return
end
pos, attrib = IPP.Attribute.parse(data, pos)
group:addAttribute(attrib)
until( pos == #data + 1)
return resp
end,
},
}
HTTP = {
Request = function(host, port, request)
local headers = {
['Content-Type'] = 'application/ipp',
['User-Agent'] = 'CUPS/1.5.1',
}
port.version.service_tunnel = "ssl"
local http_resp = http.post(host, port, '/', { header = headers }, nil, tostring(request))
if ( http_resp.status ~= 200 ) then
return false, "Unexpected response from server"
end
local response = IPP.Response.parse(http_resp.body)
if ( not(response) ) then
return false, "Failed to parse response"
end
return true, response
end,
}
Helper = {
new = function(self, host, port, options)
local o = { host = host, port = port, options = options or {} }
setmetatable(o, self)
self.__index = self
return o
end,
connect = function(self)
self.socket = nmap.new_socket()
self.socket:set_timeout(self.options.timeout or 10000)
return self.socket:connect(self.host, self.port)
end,
getPrinters = function(self)
local attribs = {
IPP.Attribute:new(IPP.Attribute.IPP_TAG_CHARSET, "attributes-charset", "utf-8" ),
IPP.Attribute:new(IPP.Attribute.IPP_TAG_LANGUAGE, "attributes-natural-language", "en"),
}
local ag = IPP.AttributeGroup:new(IPP.Attribute.IPP_TAG_OPERATION, attribs)
local request = IPP.Request:new(IPP.OperationID.CUPS_GET_PRINTERS, 1)
request:addAttributeGroup(ag)
local status, response = HTTP.Request( self.host, self.port, tostring(request) )
if ( not(response) ) then
return status, response
end
local printers = {}
for _, ag in ipairs(response:getAttributeGroups(IPP.Attribute.IPP_TAG_PRINTER)) do
local attrib = {
["printer-name"] = "name",
["printer-location"] = "location",
["printer-make-and-model"] = "model",
["printer-state"] = "state",
["queued-job-count"] = "queue_count",
["printer-dns-sd-name"] = "dns_sd_name",
}
local printer = {}
for k, v in pairs(attrib) do
if ( ag:getAttributeValue(k) ) then
printer[v] = ag:getAttributeValue(k)
end
end
table.insert(printers, printer)
end
return true, printers
end,
getQueueInfo = function(self, uri)
local uri = uri or ("ipp://%s/"):format(self.host.ip)
local attribs = {
IPP.Attribute:new(IPP.Attribute.IPP_TAG_CHARSET, "attributes-charset", "utf-8" ),
IPP.Attribute:new(IPP.Attribute.IPP_TAG_LANGUAGE, "attributes-natural-language", "en-us"),
IPP.Attribute:new(IPP.Attribute.IPP_TAG_URI, "printer-uri", uri),
IPP.Attribute:new(IPP.Attribute.IPP_TAG_KEYWORD, "requested-attributes", {
-- { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-originating-host-name"},
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "com.apple.print.JobInfo.PMJobName"},
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "com.apple.print.JobInfo.PMJobOwner"},
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-id" },
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-k-octets" },
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-name" },
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-state" },
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "printer-uri" },
-- { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-originating-user-name" },
-- { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-printer-state-message" },
-- { tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "job-printer-uri" },
{ tag = IPP.Attribute.IPP_TAG_KEYWORD, val = "time-at-creation" } } ),
IPP.Attribute:new(IPP.Attribute.IPP_TAG_KEYWORD, "which-jobs", "not-completed" )
}
local ag = IPP.AttributeGroup:new(IPP.Attribute.IPP_TAG_OPERATION, attribs)
local request = IPP.Request:new(IPP.OperationID.IPP_GET_JOBS, 1)
request:addAttributeGroup(ag)
local status, response = HTTP.Request( self.host, self.port, tostring(request) )
if ( not(response) ) then
return status, response
end
local results = {}
for _, ag in ipairs(response:getAttributeGroups(IPP.Attribute.IPP_TAG_JOB)) do
local uri = ag:getAttributeValue("printer-uri")
local printer = uri:match(".*/(.*)$") or "Unknown"
-- some jobs have multiple state attributes, so far the ENUM ones have been correct
local state = ag:getAttributeValue("job-state", IPP.Attribute.IPP_TAG_ENUM) or ag:getAttributeValue("job-state")
-- some jobs have multiple id tag, so far the INTEGER type have shown the correct ID
local id = ag:getAttributeValue("job-id", IPP.Attribute.IPP_TAG_INTEGER) or ag:getAttributeValue("job-id")
local attr = ag:getAttribute("time-at-creation")
local tm = ag:getAttributeValue("time-at-creation")
local size = ag:getAttributeValue("job-k-octets") .. "k"
local jobname = ag:getAttributeValue("com.apple.print.JobInfo.PMJobName") or "Unknown"
local owner = ag:getAttributeValue("com.apple.print.JobInfo.PMJobOwner") or "Unknown"
results[printer] = results[printer] or {}
table.insert(results[printer], {
id = id,
time = os.date("%Y-%m-%d %H:%M:%S", tm),
state = ( IPP.StateName[tonumber(state)] or "Unknown" ),
size = size,
owner = owner,
jobname = jobname })
end
local output = {}
for name, entries in pairs(results) do
local t = tab.new(5)
tab.addrow(t, "id", "time", "state", "size (kb)", "owner", "jobname")
for _, entry in ipairs(entries) do
tab.addrow(t, entry.id, entry.time, entry.state, entry.size, entry.owner, entry.jobname)
end
if ( 1<#t ) then
table.insert(output, { name = name, tab.dump(t) })
end
end
return output
end,
close = function(self)
return self.socket:close()
end,
}
return _ENV;
| mit |
lcheylus/haka | lib/haka/lua/lua/dissector.lua | 3 | 8024 | -- 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 type = {}
local dissector = {}
local log = haka.log_section("dissector")
local log_lua = haka.log_section("lua")
--
-- Dissector base class
--
type.Dissector = class.class('Dissector')
local event_mt = {
__index = function (self, name)
check.error(string.format("unkown event '%s'", name))
end
}
function type.Dissector.__class_init(self, cls)
self.super:__class_init(cls)
cls.events = {}
setmetatable(cls.events, event_mt)
self.inherit_events(cls)
cls.options = {}
end
function type.Dissector.register_event(cls, name, continue, signal, options)
continue = continue or function (self) return self:continue() end
cls.events[name] = haka.event.Event:new(string.format('%s:%s', cls.name, name), continue, signal, options)
end
function type.Dissector.inherit_events(cls)
local parent_events = cls.super.events
if parent_events then
local events = cls.events
for name, event in pairs(parent_events) do
events[name] = event:clone()
events[name].name = string.format('%s:%s', cls.name, name)
end
end
end
type.Dissector.auto_state_machine = true
function type.Dissector.method:__init()
local cls = class.classof(self)
if cls.state_machine and cls.auto_state_machine then
self.state = cls.state_machine:instanciate(self)
end
end
type.Dissector.property.name = {
get = function (self) return class.classof(self).name end
}
function type.Dissector.method:trigger(signal, ...)
haka.context:signal(self, class.classof(self).events[signal], ...)
end
function type.Dissector.method:send()
error("not implemented")
end
function type.Dissector.method:drop()
error("not implemented")
end
function type.Dissector.method:can_continue()
error("not implemented")
end
function type.Dissector.method:continue()
if not self:can_continue() then
haka.abort()
end
end
function type.Dissector.method:error()
self:drop()
end
function dissector.pcall(self, f)
local ret, err = xpcall(f, debug.format_error)
if not ret then
if err then
log_lua.error("%s: %s", self.name, err)
return self:error()
end
end
-- return the result of f
return err
end
--
-- Packet based type
--
type.PacketDissector = class.class('PacketDissector', type.Dissector)
type.PacketDissector:register_event('receive_packet')
type.PacketDissector:register_event('send_packet')
local npkt
local function preceive()
npkt:receive()
end
function type.PacketDissector:receive(pkt)
npkt = self:new(pkt)
if not npkt then
return
end
return dissector.pcall(npkt, preceive)
end
function type.PacketDissector.method:receive()
error("not implemented")
end
function type.PacketDissector.method:send()
error("not implemented")
end
function type.PacketDissector.method:inject()
error("not implemented")
end
function type.PacketDissector.method:drop()
error("not implemented")
end
type.EncapsulatedPacketDissector = class.class('EncapsulatedPacketDissector', type.PacketDissector)
function type.EncapsulatedPacketDissector.method:receive()
self:parse(self._parent)
return self:emit()
end
function type.EncapsulatedPacketDissector.method:__init(parent)
class.super(type.EncapsulatedPacketDissector).__init(self)
self._parent = parent
end
function type.EncapsulatedPacketDissector.method:parse(pkt)
self._select, self._payload = pkt.payload:sub(0, 'all'):select()
self:parse_payload(pkt, self._payload)
end
function type.EncapsulatedPacketDissector.method:parse_payload(pkt, payload)
error("not implemented")
end
function type.EncapsulatedPacketDissector.method:create(init, pkt)
self._select, self._payload = pkt.payload:sub(0, 'all'):select()
self:create_payload(pkt, self._payload, init)
end
function type.EncapsulatedPacketDissector.method:create_payload(pkt, payload, init)
error("not implemented")
end
function type.EncapsulatedPacketDissector.method:forge(pkt)
self:forge_payload(pkt, self._payload)
self._select:restore(self._payload)
self._payload = nil
self._select = nil
end
function type.EncapsulatedPacketDissector.method:forge_payload(pkt, payload)
error("not implemented")
end
function type.EncapsulatedPacketDissector.method:can_continue()
return self._parent:can_continue()
end
function type.EncapsulatedPacketDissector.method:drop()
return self._parent:drop()
end
function type.EncapsulatedPacketDissector.method:next_dissector()
return nil
end
function type.EncapsulatedPacketDissector.method:emit()
self:trigger('receive_packet')
local next_dissector = self:next_dissector()
if next_dissector then
return next_dissector:receive(self)
else
return self:send()
end
end
function type.EncapsulatedPacketDissector.method:send()
self:trigger('send_packet')
self:forge(self._parent)
self._parent:send()
self._parent = nil
end
function type.EncapsulatedPacketDissector.method:inject()
self:forge(self._parent)
self._parent:inject()
self._parent = nil
end
--
-- Flow based dissector
--
type.FlowDissector = class.class('FlowDissector', type.Dissector)
function type.FlowDissector.stream_wrapper(f, options, self, stream, current, ...)
if options and options.streamed then
self:streamed(stream, f, self, current, ...)
else
if (not current or not current:check_available(1)) and
not stream.isfinished then
return
end
if current then
local sub = current:copy():sub('available')
if sub then
f(self, sub, ...)
end
end
end
end
function type.FlowDissector.register_streamed_event(cls, name, continue, options)
type.Dissector.register_event(cls, name, continue, type.FlowDissector.stream_wrapper, options)
end
function type.FlowDissector.method:connections()
local connections = class.classof(self).connections
if connections then
return haka.event.ObjectEventConnections:new(self, connections)
end
end
function type.FlowDissector.method:send(pkt)
pkt:send()
end
function type.FlowDissector.method:streamed(stream, f, this, current, ...)
if (not current or not current:check_available(1)) and
not stream.isfinished then
return
end
local cur
if current then cur = current:copy() end
local comanager = self:get_comanager(stream, ...)
-- unique id for the function to execute
local id = comanager.hash(f, this)
if not comanager:has(id) then
local args = {...}
comanager:start(id, function (iter) return f(this, iter, unpack(args)) end)
end
comanager:process(id, cur)
end
function type.FlowDissector.method:get_comanager(stream)
if not self._costream then
self._costream = {}
end
if not self._costream[stream] then
self._costream[stream] = haka.vbuffer_stream_comanager:new(stream)
end
return self._costream[stream]
end
function type.FlowDissector.method:next_dissector()
return self._next_dissector
end
function type.FlowDissector.method:select_next_dissector(dissector)
haka.context:register_connections(dissector:connections())
self._next_dissector = dissector
end
--
-- Utility functions
--
local dissectors = {}
function dissector.new(args)
check.assert(args.type, string.format("no type defined for dissector '%s'", args.name))
if haka.mode ~= 'console' then
log("register new dissector '%s'", args.name)
end
local d = class.class(args.name, args.type)
table.insert(dissectors, d)
return d
end
local other_direction = {
up = 'down',
down = 'up'
};
function dissector.opposite_direction(dir)
return other_direction[dir]
end
function haka.console.events()
local ret = {}
local event = {}
for _, dissector in pairs(dissectors) do
for _, event in pairs(dissector.events) do
local er = { event=event.name, listener=0 }
table.insert(ret, er)
event[event.name] = er
end
end
for event, listeners in pairs(haka.context.connections) do
event[event.name].listener = #listeners
end
return ret
end
haka.dissector = dissector
table.merge(haka.helper, type)
| mpl-2.0 |
deepak78/new-luci | protocols/luci-proto-ppp/luasrc/model/cbi/admin_network/proto_ppp.lua | 47 | 3692 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local device, username, password
local ipv6, defaultroute, metric, peerdns, dns,
keepalive_failure, keepalive_interval, demand, mtu
device = section:taboption("general", Value, "device", translate("Modem device"))
device.rmempty = false
local device_suggestions = nixio.fs.glob("/dev/tty*S*")
or nixio.fs.glob("/dev/tts/*")
if device_suggestions then
local node
for node in device_suggestions do
device:value(node)
end
end
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", ListValue, "ipv6")
ipv6:value("auto", translate("Automatic"))
ipv6:value("0", translate("Disabled"))
ipv6:value("1", translate("Manual"))
ipv6.default = "auto"
end
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
translate("LCP echo failure threshold"),
translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))
function keepalive_failure.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
end
end
keepalive_failure.placeholder = "0"
keepalive_failure.datatype = "uinteger"
keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
translate("LCP echo interval"),
translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))
function keepalive_interval.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^%d+[ ,]+(%d+)"))
end
end
function keepalive_interval.write(self, section, value)
local f = tonumber(keepalive_failure:formvalue(section)) or 0
local i = tonumber(value) or 5
if i < 1 then i = 1 end
if f > 0 then
m:set(section, "keepalive", "%d %d" %{ f, i })
else
m:del(section, "keepalive")
end
end
keepalive_interval.remove = keepalive_interval.write
keepalive_failure.write = keepalive_interval.write
keepalive_failure.remove = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype = "min(1)"
demand = section:taboption("advanced", Value, "demand",
translate("Inactivity timeout"),
translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))
demand.placeholder = "0"
demand.datatype = "uinteger"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(9200)"
| apache-2.0 |
rollokb/tsdemuxer | xupnpd/src/profiles/skel/skel.lua | 5 | 2519 | -- Copyright (C) 2011-2012 Anton Burdinuk
-- clark15b@gmail.com
-- https://tsdemuxer.googlecode.com/svn/trunk/xupnpd
-- skeleton
profiles['Skeleton']=
{
-- comment this for enable
['disabled']=true,
-- device description
['desc']='Skeleton for example',
-- function which identifies device by User-Agent HTTP header (must return true or false)
['match']=function(user_agent)
if string.find(user_agent,'User-Agent of Device',1,true) then
return true
else
return false
end
end,
-- any option from 'cfg' namespace, cfg.dlna_headers for example; expect description in '-- options for profiles' of xupnpd_main.lua
['options']=
{
['dev_desc_xml']='/dev.xml', -- UPnP Device Description XML (/dev.xml, /wmc.xml)
['upnp_container']='object.container', -- UPnP class for containers (object.container, object.container.storageFolder)
['upnp_artist']=false, -- send <upnp:artist> / <upnp:actor> in SOAP response
['upnp_feature_list']='', -- X_GetFeatureList response body (XML)
['upnp_albumart']=0, -- 0: <upnp:albumArtURI>direct url</upnp:albumArtURI>, 1: <res>direct url<res>, 2: <upnp:albumArtURI>local url</upnp:
['dlna_headers']=true, -- send TransferMode.DLNA.ORG and ContentFeatures.DLNA.ORG in HTTP response
['dlna_extras']=true, -- DLNA extras in headers and SOAP
['cfg.content_disp']=false, -- send Content-Disposition when streaming
['soap_length']=true, -- send Content-Length in SOAP response
['cfg.wdtv']=false, -- WDTV Live compatible mode
['cfg.sec_extras']=false -- Samsung extras
-- ...
},
-- replace mime={} or join with mime_types={}
['replace_mime_types']=true
-- any exist in mime={} or new file type, expect xupnpd_mime.lua
['mime_types']=
{
['avi'] = { upnp_type.video, upnp_class.video, 'video/avi', upnp_proto.avi, dlna_org_extras.divx5 },
['asf'] = { upnp_type.video, upnp_class.video, 'video/x-ms-asf', upnp_proto.asf, dlna_org_extras.asf_mpeg4_sp }
-- ...
}
}
| mit |
rollokb/tsdemuxer | xupnpd/src/plugins/staff/xupnpd_ex.lua | 6 | 3479 | -- Copyright (C) 2012
--- Uses PARAMETER of [url]http://www.ex.ua/view/PARAMETER?r=23775[/url] on [url]http://www.ex.ua/ru/video[/url]
-- <guid isPermaLink="false">PARAMETER</guid> on [url]http://www.ex.ua/rss/23775[/url]
--
-- 23775 - ВИДЕО (раздел)
-- 70538 - НАШЕ (подраздел)
-- v=1,0 - показывать списком, новое вначале
-- p=1 - страница 2
-- per=100 - 100 позиций на странице
-- [url]http://www.ex.ua/view/70538?r=23775&v=1,0&per=100&p=1[/url]
--
-- config example
-- feeds =
-- {
-- { "ex", "2", "Зарубежное" },
-- { "ex", "70538", "Наше" },
-- }
-- pages num from 0
cfg.ex_max_pages=10
cfg.debug=1
function ex_updatefeed(feed,friendly_name)
local rc=false
local feed_url='http://www.ex.ua/view/'..feed..'?r=23775&v=1,0&per=100'
local feed_name='ex_'..string.gsub(feed,'/','_')
local feed_m3u_path=cfg.feeds_path..feed_name..'.m3u'
local tmp_m3u_path=cfg.tmp_path..feed_name..'.m3u'
local page=0
local scroll=true
if feed_url then
local dfd=io.open(tmp_m3u_path,'w+')
if dfd then
dfd:write('#EXTM3U name=\"',friendly_name or feed_name,'\" plugin=ex\n')
--dfd:write('#EXTM3U name=\"',friendly_name or feed_name,'\" plugin=generic dlna_extras=mp4_avc_sd_ac3\n')
--dfd:write('#EXTM3U name=\"',friendly_name or feed_name,'\" type=mp4 plugin=ex\n')
local page=0
while(page<cfg.ex_max_pages) do
local url=feed_url..'&p='..page
if cfg.debug>0 then print('EX.UA try url '..url) end
local feed_data
feed_data=http.download(url)
if feed_data then
for urn1,urn2,logo,name in string.gmatch(feed_data,'<tr><td><a href=\'/view/(.-)\?r=(.-)\'><img src=\'(.-)\' width=.-alt=\'(.-)\'>') do
local chapter=1
local url_spec='http://www.ex.ua/playlist/'..urn1..'.m3u'
local feed_data_spec=http.download(url_spec)
if feed_data_spec then
for urs in string.gmatch(feed_data_spec,'http://www.ex.ua/get/(%d*)') do
--dfd:write('#EXTINF:0 logo=',logo,' ,',name,' (chapter-',chapter,')','\n','http://www.ex.ua/get/',urs,'\n')
dfd:write('#EXTINF:0 ,',name,' (chapter-',chapter,')','\n','http://www.ex.ua/get/',urs,'\n')
if cfg.debug>0 then print('EX.UA find urs '..urs..' name '..name) end
chapter=chapter+1
end
end
feed_data_spec=nil end
feed_data=nil
end
page=page+1
end
dfd:close()
if util.md5(tmp_m3u_path)~=util.md5(feed_m3u_path) then
if os.execute(string.format('mv %s %s',tmp_m3u_path,feed_m3u_path))==0 then
if cfg.debug>0 then print('EX.UA feed \''..feed_name..'\' updated') end
rc=true
end
else
util.unlink(tmp_m3u_path)
end
end
end
return rc
end
function ex_sendurl(ex_url,range)
local rc,location
location=ex_url
for i=1,5,1 do
rc,location=http.sendurl(location,1,range)
if not location then
break
else
if cfg.debug>0 then print('Redirect #'..i..' to: '..location) end
end
end
end
plugins['ex']={}
plugins.ex.sendurl=ex_sendurl
plugins.ex.updatefeed=ex_updatefeed
| mit |
iamliqiang/prosody-modules | mod_delegation/mod_delegation.lua | 16 | 17451 | -- XEP-0355 (Namespace Delegation)
-- Copyright (C) 2015 Jérôme Poisson
--
-- This module is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
-- This module manage namespace delegation, a way to delegate server features
-- to an external entity/component. Only the admin mode is implemented so far
-- TODO: client mode
local jid = require("util/jid")
local st = require("util/stanza")
local set = require("util/set")
local delegation_session = module:shared("/*/delegation/session")
if delegation_session.connected_cb == nil then
-- set used to have connected event listeners
-- which allow a host to react on events from
-- other hosts
delegation_session.connected_cb = set.new()
end
local connected_cb = delegation_session.connected_cb
local _DELEGATION_NS = 'urn:xmpp:delegation:1'
local _FORWARDED_NS = 'urn:xmpp:forward:0'
local _DISCO_NS = 'http://jabber.org/protocol/disco#info'
local _DATA_NS = 'jabber:x:data'
local _MAIN_SEP = '::'
local _BARE_SEP = ':bare:'
local _MAIN_PREFIX = _DELEGATION_NS.._MAIN_SEP
local _BARE_PREFIX = _DELEGATION_NS.._BARE_SEP
local _PREFIXES = {_MAIN_PREFIX, _BARE_PREFIX}
local disco_nest
module:log("debug", "Loading namespace delegation module ");
--> Configuration management <--
local ns_delegations = module:get_option("delegations", {})
local jid2ns = {}
for namespace, ns_data in pairs(ns_delegations) do
-- "connected" contain the full jid of connected managing entity
ns_data.connected = nil
if ns_data.jid then
if jid2ns[ns_data.jid] == nil then
jid2ns[ns_data.jid] = {}
end
jid2ns[ns_data.jid][namespace] = ns_data
module:log("debug", "Namespace %s is delegated%s to %s", namespace, ns_data.filtering and " (with filtering)" or "", ns_data.jid)
else
module:log("warn", "Ignoring delegation for %s: no jid specified", tostring(namespace))
ns_delegations[namespace] = nil
end
end
local function advertise_delegations(session, to_jid)
-- send <message/> stanza to advertise delegations
-- as expained in § 4.2
local message = st.message({from=module.host, to=to_jid})
:tag("delegation", {xmlns=_DELEGATION_NS})
-- we need to check if a delegation is granted because the configuration
-- can be complicated if some delegations are granted to bare jid
-- and other to full jids, and several resources are connected.
local have_delegation = false
for namespace, ns_data in pairs(jid2ns[to_jid]) do
if ns_data.connected == to_jid then
have_delegation = true
message:tag("delegated", {namespace=namespace})
if type(ns_data.filtering) == "table" then
for _, attribute in pairs(ns_data.filtering) do
message:tag("attribute", {name=attribute}):up()
end
message:up()
end
end
end
if have_delegation then
session.send(message)
end
end
local function set_connected(entity_jid)
-- set the "connected" key for all namespace managed by entity_jid
-- if the namespace has already a connected entity, ignore the new one
local function set_config(jid_)
for namespace, ns_data in pairs(jid2ns[jid_]) do
if ns_data.connected == nil then
ns_data.connected = entity_jid
disco_nest(namespace, entity_jid)
end
end
end
local bare_jid = jid.bare(entity_jid)
set_config(bare_jid)
-- We can have a bare jid of a full jid specified in configuration
-- so we try our luck with both (first connected resource will
-- manage the namespaces in case of bare jid)
if bare_jid ~= entity_jid then
set_config(entity_jid)
jid2ns[entity_jid] = jid2ns[bare_jid]
end
end
local function on_presence(event)
local session = event.origin
local bare_jid = jid.bare(session.full_jid)
if jid2ns[bare_jid] or jid2ns[session.full_jid] then
set_connected(session.full_jid)
advertise_delegations(session, session.full_jid)
end
end
local function on_component_connected(event)
-- method called by the module loaded by the component
-- /!\ the event come from the component host,
-- not from the host of this module
local session = event.session
local bare_jid = jid.join(session.username, session.host)
local jid_delegations = jid2ns[bare_jid]
if jid_delegations ~= nil then
set_connected(bare_jid)
advertise_delegations(session, bare_jid)
end
end
local function on_component_auth(event)
-- react to component-authenticated event from this host
-- and call the on_connected methods from all other hosts
-- needed for the component to get delegations advertising
for callback in connected_cb:items() do
callback(event)
end
end
connected_cb:add(on_component_connected)
module:hook('component-authenticated', on_component_auth)
module:hook('presence/initial', on_presence)
--> delegated namespaces hook <--
local managing_ent_error
local stanza_cache = {} -- we cache original stanza to build reply
local function managing_ent_result(event)
-- this function manage iq results from the managing entity
-- it do a couple of security check before sending the
-- result to the managed entity
local stanza = event.stanza
if stanza.attr.to ~= module.host then
module:log("warn", 'forwarded stanza result has "to" attribute not addressed to current host, id conflict ?')
return
end
module:unhook("iq-result/host/"..stanza.attr.id, managing_ent_result)
module:unhook("iq-error/host/"..stanza.attr.id, managing_ent_error)
-- lot of checks to do...
local delegation = stanza.tags[1]
if #stanza ~= 1 or delegation.name ~= "delegation" or
delegation.attr.xmlns ~= _DELEGATION_NS then
module:log("warn", "ignoring invalid iq result from managing entity %s", stanza.attr.from)
stanza_cache[stanza.attr.from][stanza.attr.id] = nil
return true
end
local forwarded = delegation.tags[1]
if #delegation ~= 1 or forwarded.name ~= "forwarded" or
forwarded.attr.xmlns ~= _FORWARDED_NS then
module:log("warn", "ignoring invalid iq result from managing entity %s", stanza.attr.from)
stanza_cache[stanza.attr.from][stanza.attr.id] = nil
return true
end
local iq = forwarded.tags[1]
if #forwarded ~= 1 or iq.name ~= "iq" or
iq.attr.xmlns ~= 'jabber:client' or
(iq.attr.type =='result' and #iq ~= 1) or
(iq.attr.type == 'error' and #iq > 2) then
module:log("warn", "ignoring invalid iq result from managing entity %s", stanza.attr.from)
stanza_cache[stanza.attr.from][stanza.attr.id] = nil
return true
end
iq.attr.xmlns = nil
local original = stanza_cache[stanza.attr.from][stanza.attr.id]
stanza_cache[stanza.attr.from][stanza.attr.id] = nil
-- we get namespace from original and not iq
-- because the namespace can be lacking in case of error
local namespace = original.tags[1].attr.xmlns
local ns_data = ns_delegations[namespace]
if stanza.attr.from ~= ns_data.connected or (iq.attr.type ~= "result" and iq.attr.type ~= "error") or
iq.attr.id ~= original.attr.id or iq.attr.to ~= original.attr.from then
module:log("warn", "ignoring forbidden iq result from managing entity %s, please check that the component is no trying to do something bad (stanza: %s)", stanza.attr.from, tostring(stanza))
module:send(st.error_reply(original, 'cancel', 'service-unavailable'))
return true
end
-- at this point eveything is checked,
-- and we (hopefully) can send the the result safely
module:send(iq)
return true
end
function managing_ent_error(event)
local stanza = event.stanza
if stanza.attr.to ~= module.host then
module:log("warn", 'Stanza result has "to" attribute not addressed to current host, id conflict ?')
return
end
module:unhook("iq-result/host/"..stanza.attr.id, managing_ent_result)
module:unhook("iq-error/host/"..stanza.attr.id, managing_ent_error)
local original = stanza_cache[stanza.attr.from][stanza.attr.id]
stanza_cache[stanza.attr.from][stanza.attr.id] = nil
module:log("warn", "Got an error after forwarding stanza to "..stanza.attr.from)
module:send(st.error_reply(original, 'cancel', 'service-unavailable'))
return true
end
local function forward_iq(stanza, ns_data)
local to_jid = ns_data.connected
stanza.attr.xmlns = 'jabber:client'
local iq_stanza = st.iq({ from=module.host, to=to_jid, type="set" })
:tag("delegation", { xmlns=_DELEGATION_NS })
:tag("forwarded", { xmlns=_FORWARDED_NS })
:add_child(stanza)
local iq_id = iq_stanza.attr.id
-- we save the original stanza to check the managing entity result
if not stanza_cache[to_jid] then stanza_cache[to_jid] = {} end
stanza_cache[to_jid][iq_id] = stanza
module:hook("iq-result/host/"..iq_id, managing_ent_result)
module:hook("iq-error/host/"..iq_id, managing_ent_error)
module:log("debug", "stanza forwarded")
module:send(iq_stanza)
end
local function iq_hook(event)
-- general hook for all the iq which forward delegated ones
-- and continue normal behaviour else. If a namespace is
-- delegated but managing entity is offline, a service-unavailable
-- error will be sent, as requested by the XEP
local session, stanza = event.origin, event.stanza
if #stanza == 1 and stanza.attr.type == 'get' or stanza.attr.type == 'set' then
local namespace = stanza.tags[1].attr.xmlns
local ns_data = ns_delegations[namespace]
if ns_data then
if stanza.attr.from == ns_data.connected then
-- we don't forward stanzas from managing entity itself
return
end
if ns_data.filtering then
local first_child = stanza.tags[1]
for _, attribute in ns_data.filtering do
-- if any filtered attribute if not present,
-- we must continue the normal bahaviour
if not first_child.attr[attribute] then
-- Filtered attribute is not present, we do normal workflow
return;
end
end
end
if not ns_data.connected then
module:log("warn", "No connected entity to manage "..namespace)
session.send(st.error_reply(stanza, 'cancel', 'service-unavailable'))
else
forward_iq(stanza, ns_data)
end
return true
else
-- we have no delegation, we continue normal behaviour
return
end
end
end
module:hook("iq/self", iq_hook, 2^32)
module:hook("iq/bare", iq_hook, 2^32)
module:hook("iq/host", iq_hook, 2^32)
--> discovery nesting <--
-- disabling internal features/identities
local function find_form_type(stanza)
local form_type = nil
for field in stanza.childtags('field', 'jabber:x:data') do
if field.attr.var=='FORM_TYPE' and field.attr.type=='hidden' then
local value = field:get_child('value')
if not value then
module:log("warn", "No value found in FORM_TYPE field: "..tostring(stanza))
else
form_type=value.get_text()
end
end
end
return form_type
end
-- modules whose features/identities are managed by delegation
local disabled_modules = set.new()
local disabled_identities = set.new()
local function identity_added(event)
local source = event.source
if disabled_modules:contains(source) then
local item = event.item
local category, type_, name = item.category, item.type, item.name
module:log("debug", "Removing (%s/%s%s) identity because of delegation", category, type_, name and "/"..name or "")
disabled_identities:add(item)
source:remove_item("identity", item)
end
end
local function feature_added(event)
local source, item = event.source, event.item
for namespace, _ in pairs(ns_delegations) do
if source ~= module and string.sub(item, 1, #namespace) == namespace then
module:log("debug", "Removing %s feature which is delegated", item)
source:remove_item("feature", item)
disabled_modules:add(source)
if source.items and source.items.identity then
-- we remove all identities added by the source module
-- that can cause issues if the module manages several features/identities
-- but this case is probably rare (or doesn't happen at all)
-- FIXME: any better way ?
for _, identity in pairs(source.items.identity) do
identity_added({source=source, item=identity})
end
end
end
end
end
local function extension_added(event)
local source, stanza = event.source, event.item
local form_type = find_form_type(stanza)
if not form_type then return; end
for namespace, _ in pairs(ns_delegations) do
if source ~= module and string.sub(form_type, 1, #namespace) == namespace then
module:log("debug", "Removing extension which is delegated: %s", tostring(stanza))
source:remove_item("extension", stanza)
end
end
end
-- for disco nesting (see § 7.2) we need to remove internal features
-- we use handle_items as it allow to remove already added features
-- and catch the ones which can come later
module:handle_items("feature", feature_added, function(_) end)
module:handle_items("identity", identity_added, function(_) end, false)
module:handle_items("extension", extension_added, function(_) end)
-- managing entity features/identities collection
local disco_error
local bare_features = set.new()
local bare_identities = {}
local bare_extensions = {}
local function disco_result(event)
-- parse result from disco nesting request
-- and fill module features/identities and bare_features/bare_identities accordingly
local session, stanza = event.origin, event.stanza
if stanza.attr.to ~= module.host then
module:log("warn", 'Stanza result has "to" attribute not addressed to current host, id conflict ?')
return
end
module:unhook("iq-result/host/"..stanza.attr.id, disco_result)
module:unhook("iq-error/host/"..stanza.attr.id, disco_error)
local query = stanza:get_child("query", _DISCO_NS)
if not query or not query.attr.node then
session.send(st.error_reply(stanza, 'modify', 'not-acceptable'))
return true
end
local node = query.attr.node
local main
if string.sub(node, 1, #_MAIN_PREFIX) == _MAIN_PREFIX then
main=true
elseif string.sub(node, 1, #_BARE_PREFIX) == _BARE_PREFIX then
main=false
else
module:log("warn", "Unexpected node: "..node)
session.send(st.error_reply(stanza, 'modify', 'not-acceptable'))
return true
end
for feature in query:childtags("feature") do
local namespace = feature.attr.var
if main then
module:add_feature(namespace)
else
bare_features:add(namespace)
end
end
for identity in query:childtags("identity") do
local category, type_, name = identity.attr.category, identity.attr.type, identity.attr.name
if main then
module:add_identity(category, type_, name)
else
table.insert(bare_identities, {category=category, type=type_, name=name})
end
end
for extension in query:childtags("x", _DATA_NS) do
if main then
module:add_extension(extension)
else
table.insert(bare_extensions, extension)
end
end
end
function disco_error(event)
local stanza = event.stanza
if stanza.attr.to ~= module.host then
module:log("warn", 'Stanza result has "to" attribute not addressed to current host, id conflict ?')
return
end
module:unhook("iq-result/host/"..stanza.attr.id, disco_result)
module:unhook("iq-error/host/"..stanza.attr.id, disco_error)
module:log("warn", "Got an error while requesting disco for nesting to "..stanza.attr.from)
module:log("warn", "Ignoring disco nesting")
end
function disco_nest(namespace, entity_jid)
-- manage discovery nesting (see § 7.2)
-- first we reset the current values
if module.items then
module.items['feature'] = nil
module.items['identity'] = nil
module.items['extension'] = nil
bare_features = set.new()
bare_identities = {}
bare_extensions = {}
end
for _, prefix in ipairs(_PREFIXES) do
local node = prefix..namespace
local iq = st.iq({from=module.host, to=entity_jid, type='get'})
:tag('query', {xmlns=_DISCO_NS, node=node})
local iq_id = iq.attr.id
module:hook("iq-result/host/"..iq_id, disco_result)
module:hook("iq-error/host/"..iq_id, disco_error)
module:send(iq)
end
end
-- disco to bare jids special case
module:hook("account-disco-info", function(event)
-- this event is called when a disco info request is done on a bare jid
-- we get the final reply and filter delegated features/identities/extensions
local reply = event.reply;
reply.tags[1]:maptags(function(child)
if child.name == 'feature' then
local feature_ns = child.attr.var
for namespace, _ in pairs(ns_delegations) do
if string.sub(feature_ns, 1, #namespace) == namespace then
module:log("debug", "Removing feature namespace %s which is delegated", feature_ns)
return nil
end
end
elseif child.name == 'identity' then
for item in disabled_identities:items() do
if item.category == child.attr.category
and item.type == child.attr.type
-- we don't check name, because mod_pep use a name for main disco, but not in account-disco-info hook
-- and item.name == child.attr.name
then
module:log("debug", "Removing (%s/%s%s) identity because of delegation", item.category, item.type, item.name and "/"..item.name or "")
return nil
end
end
elseif child.name == 'x' and child.attr.xmlns == _DATA_NS then
local form_type = find_form_type(child)
if form_type then
for namespace, _ in pairs(ns_delegations) do
if string.sub(form_type, 1, #namespace) == namespace then
module:log("debug", "Removing extension which is delegated: %s", tostring(child))
return nil
end
end
end
end
return child
end)
for feature in bare_features:items() do
reply:tag('feature', {var=feature}):up()
end
for _, item in ipairs(bare_identities) do
reply:tag('identity', {category=item.category, type=item.type, name=item.name}):up()
end
for _, stanza in ipairs(bare_extensions) do
reply:add_child(stanza)
end
end, -2^32);
| mit |
spacebuild/sbep | lua/entities/sbep_base_door/init.lua | 2 | 17719 | AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include( "shared.lua" )
ENT.WireDebugName = "SBEP Door"
local DTT = {}
--[[DTT[ "Door Type Name (Class)" ] = { { model = "models/examplemodelpath.mdl" , UD = Length of sequence (s) , OD = time before door can be walked though , CD = time before door becomes solid ,
Opening Sounds => { [time 1(s)] = "Sound 1 Name" , [time 2(s)] = "Sound 2 Name" , etc } ,
Closing Soungs => { [time 1(s)] = "Sound 1 Name" , [time 2(s)] = "Sound 2 Name" , etc } }]]
DTT[ "Door_AnimS1" ] = { { model = "models/smallbridge/sents/sbadoors1a.mdl" , UD = 3 , OD = 2 , CD = 1 ,
OS = { [0] = "Doors.Move14" , [1.45] = "Doors.FullOpen8" , [2.75] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.45] = "Doors.FullOpen8" , [2.75] = "Doors.FullOpen9" } } ,
{ model = "models/smallbridge/sents/sbadoors1.mdl" , UD = 3 , OD = 2 , CD = 1 ,
OS = { [0] = "Doors.Move14" , [1.45] = "Doors.FullOpen8" , [2.75] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.45] = "Doors.FullOpen8" , [2.75] = "Doors.FullOpen9" } } ,
{ model = "models/smallbridge/sents/forcedoor.mdl" , UD = 1.4 , OD = 0.52 , CD = 0.88 ,
OS = { [0] = "TriggerSuperArmor.DoneCharging" , [0.40] = "Doors.FullOpen8" , [0.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [0.40] = "Doors.FullOpen8" , [0.95] = "TriggerSuperArmor.DoneCharging" } } }
DTT[ "Door_AnimS2" ] = { { model = "models/smallbridge/sents/sbadoors2a.mdl" , UD = 2 , OD = 1 , CD = 1 ,
OS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } } ,
{ model = "models/smallbridge/sents/sbadoors2.mdl" , UD = 2 , OD = 1 , CD = 1 ,
OS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } } ,
{ model = "models/smallbridge/sents/sbadoors3.mdl" , UD = 2 , OD = 1.5 , CD = 0.5 ,
OS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } } ,
{ model = "models/smallbridge/sents/forcesquare.mdl" , UD = 1.4 , OD = 0.52 , CD = 0.88 ,
OS = { [0] = "TriggerSuperArmor.DoneCharging" , [0.40] = "Doors.FullOpen8" , [0.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [0.40] = "Doors.FullOpen8" , [0.95] = "TriggerSuperArmor.DoneCharging" } } }
DTT[ "Door_AnimT" ] = { { model = "models/smallbridge/sents/sbadoort.mdl" , UD = 2 , OD = 1 , CD = 1 ,
OS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } } ,
{ model = "models/smallbridge/sents/sbadoort2.mdl" , UD = 2 , OD = 1.5 , CD = 0.5 ,
OS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } } ,
{ model = "models/smallbridge/sents/forcetall.mdl" , UD = 1.4 , OD = 0.52 , CD = 0.88 ,
OS = { [0] = "TriggerSuperArmor.DoneCharging" , [0.40] = "Doors.FullOpen8" , [0.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [0.40] = "Doors.FullOpen8" , [0.95] = "TriggerSuperArmor.DoneCharging" } } }
DTT[ "Door_SIris" ] = { { model = "models/smallbridge/sents/sbadoorsirisa.mdl", UD = 3 , OD = 2 , CD = 1 ,
OS = { [0] = "Doors.Move14" , [0.90] = "Doors.FullOpen8" , [2.65] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen8" , [2.75] = "Doors.FullOpen9" } } ,
{ model = "models/smallbridge/sents/sbadoorsiris.mdl", UD = 3 , OD = 2 , CD = 1 ,
OS = { [0] = "Doors.Move14" , [0.90] = "Doors.FullOpen8" , [2.65] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen8" , [2.75] = "Doors.FullOpen9" } } }
DTT[ "Door_AnimW" ] = { { model = "models/smallbridge/sents/sbadoorwb.mdl" , UD = 3 , OD = 1.5 , CD = 1.5 ,
OS = { [0] = "Doors.Move14" , [0.95] = "Doors.FullOpen8" , [1.95] = "Doors.FullOpen8" , [2.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [0.95] = "Doors.FullOpen8" , [1.95] = "Doors.FullOpen8" , [2.95] = "Doors.FullOpen9" } } ,
{ model = "models/smallbridge/sents/sbadoorwa.mdl" , UD = 3 , OD = 1.5 , CD = 1.5 ,
OS = { [0] = "Doors.Move14" , [0.95] = "Doors.FullOpen8" , [1.95] = "Doors.FullOpen8" , [2.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [0.95] = "Doors.FullOpen8" , [1.95] = "Doors.FullOpen8" , [2.95] = "Doors.FullOpen9" } } ,
{ model = "models/smallbridge/sents/forcewide.mdl" , UD = 1.4 , OD = 0.52 , CD = 0.88 ,
OS = { [0] = "TriggerSuperArmor.DoneCharging" , [0.40] = "Doors.FullOpen8" , [0.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [0.40] = "Doors.FullOpen8" , [0.95] = "TriggerSuperArmor.DoneCharging" } } }
DTT[ "Door_AnimL" ] = { { model = "models/smallbridge/sents/sbadoorla.mdl" , UD = 3 , OD = 1.5 , CD = 1.5 ,
OS = { [0] = "Doors.Move14" , [0.80] = "Doors.FullOpen8" , [1.60] = "Doors.FullOpen8" , [2.40] = "Doors.FullOpen8" , [2.90] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.35] = "Doors.FullOpen8" , [2.15] = "Doors.FullOpen8" , [2.90] = "Doors.FullOpen9" } } ,
{ model = "models/smallbridge/sents/sbadoorl.mdl" , UD = 3 , OD = 1.5 , CD = 1.5 ,
OS = { [0] = "Doors.Move14" , [0.80] = "Doors.FullOpen8" , [1.60] = "Doors.FullOpen8" , [2.40] = "Doors.FullOpen8" , [2.90] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.35] = "Doors.FullOpen8" , [2.15] = "Doors.FullOpen8" , [2.90] = "Doors.FullOpen9" } } }
DTT[ "Door_Insert" ] = { { model = "models/smallbridge/sents/insertdoor.mdl" , UD = 2 , OD = 1 , CD = 1 ,
OS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } } }
DTT[ "Door_Sly1" ] = { { model = "models/slyfo/slyadoor1.mdl" , UD = 2 , OD = 0.5 , CD = 1.5 ,
OS = { [0] = "Doors.Move14" , [1.80] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.80] = "Doors.FullOpen9" } } }
DTT[ "Door_SlyDHatch" ] = { { model = "models/slyfo/doublehatchdoor.mdl" , UD = 2 , OD = 1 , CD = 1 ,
OS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } } ,
{ model = "models/slyfo/doublehatchdoor2.mdl" , UD = 2 , OD = 1 , CD = 1 ,
OS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } } ,
{ model = "models/slyfo/doublehatchdoor3.mdl" , UD = 2 , OD = 2 , CD = 1 ,
OS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.95] = "Doors.FullOpen9" } } }
DTT[ "Door_d12MBSFrame" ] = { { model = "models/slyfo/d12mbdoorn.mdl" , UD = 5 , OD = 2 , CD = 3 ,
OS = { [0] = "Doors.Move14" , [1.80] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.80] = "Doors.FullOpen9" } } }
DTT[ "Door_DBS" ] = { { model = "models/smallbridge/sents/sbadoordbs.mdl" , UD = 5 , OD = 4 , CD = 1.5 ,
OS = { [0] = "Doors.Move14" , [1.30] = "Doors.FullOpen8" , [2.60] = "Doors.FullOpen8" , [3.90] = "Doors.FullOpen9" , [4.90] = "Doors.FullOpen8" } ,
CS = { [0] = "Doors.Move14" , [2.60] = "Doors.FullOpen8" , [3.95] = "Doors.FullOpen8" , [4.90] = "Doors.FullOpen9" } } }
DTT[ "Door_Hull" ] = { { model = "models/smallbridge/sents/sbahulldse.mdl" , UD = 3 , OD = 1.5 , CD = 1.5 ,
OS = { [0] = "Doors.Move14" , [0.95] = "Doors.FullOpen8" , [1.95] = "Doors.FullOpen8" , [2.85] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [0.95] = "Doors.FullOpen8" , [1.95] = "Doors.FullOpen8" , [2.90] = "Doors.FullOpen9" } } }
DTT[ "Door_ElevHatch_S"] = { { model = "models/smallbridge/sents/sbahatchelevs.mdl" , UD = 1 , OD = 0.6 , CD = 0.4 ,
OS = { [0] = "Doors.Move14" , [0.40] = "Doors.FullOpen8" , [0.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [0.40] = "Doors.FullOpen8" , [0.95] = "Doors.FullOpen9" } } }
DTT[ "Door_ElevHatch_L"] = { { model = "models/smallbridge/sents/sbahatchelevl.mdl" , UD = 2 , OD = 0.6 , CD = 1 ,
OS = { [0] = "Doors.Move14" , [1.00] = "Doors.FullOpen8" , [1.90] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.00] = "Doors.FullOpen8" , [1.90] = "Doors.FullOpen9" } } }
DTT[ "Door_ModBridge_11a"] = { { model = "models/cerus/modbridge/misc/doors/door11a_anim.mdl" , UD = 3.8 , OD = 1.5 , CD = 2 ,
OS = { [0] = "Doors.FullOpen8" , [0.50] = "Doors.Move14" , [1.50] = "Doors.FullOpen8" , [3.40] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.50] = "Doors.FullOpen8" , [2.30] = "Doors.FullOpen9" , [3.00] = "Doors.Move14" , [3.60] = "Doors.FullOpen8" } } }
DTT[ "Door_ModBridge_11b"] = { { model = "models/cerus/modbridge/misc/doors/door11b_anim.mdl" , UD = 1.4 , OD = 0.52 , CD = 0.88 ,
OS = { [0] = "TriggerSuperArmor.DoneCharging" , [0.40] = "Doors.FullOpen8" , [0.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [0.40] = "Doors.FullOpen8" , [0.95] = "TriggerSuperArmor.DoneCharging" } } }
DTT[ "Door_ModBridge_12b"] = { { model = "models/cerus/modbridge/misc/doors/door12b_anim.mdl" , UD = 1.4 , OD = 0.52 , CD = 0.88 ,
OS = { [0] = "TriggerSuperArmor.DoneCharging" , [0.40] = "Doors.FullOpen8" , [0.95] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [0.40] = "Doors.FullOpen8" , [0.95] = "TriggerSuperArmor.DoneCharging" } } }
DTT[ "Door_ModBridge_12a"] = { { model = "models/cerus/modbridge/misc/doors/door12a_anim.mdl" , UD = 3.0 , OD = 1.5 , CD = 1.5 ,
OS = { [0] = "Doors.Move14" , [0.90] = "Doors.FullOpen8" , [1.90] = "Doors.FullOpen8" , [2.70] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [0.90] = "Doors.FullOpen8" , [1.90] = "Doors.FullOpen8" , [2.70] = "Doors.FullOpen9" } } }
DTT[ "Door_ModBridge_13a"] = { { model = "models/cerus/modbridge/misc/doors/door13a_anim.mdl" , UD = 4.8 , OD = 2 , CD = 3.5 ,
OS = { [0] = "Doors.Move14" , [1.00] = "Doors.FullOpen8" , [1.90] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.00] = "Doors.FullOpen8" , [1.90] = "Doors.FullOpen9" } } }
DTT[ "Door_ModBridge_23a"] = { { model = "models/cerus/modbridge/misc/doors/door23a_anim.mdl" , UD = 5.2 , OD = 4 , CD = 1.5 ,
OS = { [0] = "Doors.Move14" , [0.90] = "Doors.Move14" , [2.80] = "Doors.FullOpen8" , [5.00] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Fullopen8" , [2.40] = "Doors.FullOpen8" , [3.40] = "Doors.Move14" , [4.40] = "Doors.FullOpen8" , [5.20] = "Doors.FullOpen9" } } }
DTT[ "Door_ModBridge_33a"] = { { model = "models/cerus/modbridge/misc/doors/door33a_anim.mdl" , UD = 2.8 , OD = 1.6 , CD = 1.2 ,
OS = { [0] = "Doors.Move14" , [1.00] = "Doors.FullOpen8" , [1.90] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Move14" , [1.00] = "Doors.FullOpen8" , [1.90] = "Doors.FullOpen9" } } }
DTT[ "ACC_Furnace1"] = { { model = "models/cerus/modbridge/misc/accessories/acc_furnace1_anim.mdl" , UD = 1 , OD = 0.2 , CD = 0.8 ,
OS = { [0] = "Doors.Move14" , [1.00] = "Doors.FullOpen9" } ,
CS = { [0] = "Doors.Fullopen8" , [1.00] = "Doors.Move14" } } }
function ENT:Initialize()
self.D = {}
self.OpenStatus = false
self.OpenTrigger = false
self.Locked = false
self.DisableUse = false
self.Timers = {}
self.Index = self:EntIndex()
self:SetUseType( SIMPLE_USE )
self:PhysicsInitialize()
end
function ENT:PhysicsInitialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
local phys = self:GetPhysicsObject()
if (phys:IsValid()) then
phys:Wake()
phys:EnableGravity(false)
--phys:EnableDrag(false)
phys:EnableMotion( true )
end
end
function ENT:SetDoorType( strType , nClass )
if !strType or (strType == self.type and nClass == self.DClass) then
print( "Invalid Door Type: "..tostring(strType) )
return false
end
self:SetDoorVars( strType , nClass )
self:SetModel( self.D.model )
self:GetSequenceData()
self:PhysicsInitialize()
self:Close()
end
function ENT:SetDoorVars( strType , nClass )
if !strType or ( nClass and !DTT[strType][nClass] ) then return end
self.type = strType
self.DClass = nClass or 1
self.D = DTT[ strType ][ self.DClass ]
end
function GetDoorType()
return self.type
end
function ENT:SetDoorClass( nClass )
nClass = math.fmod( nClass - 1 , #DTT[ self.type ] ) + 1
if DTT[ self.type ][ nClass ] then
self:SetDoorType( self.type, nClass )
end
end
function ENT:GetDoorClass()
return self.DClass
end
function ENT:Attach( ent , V , A )
self.D = self.D || {}
local Voff = Vector(0,0,0)
if V then Voff = Vector( V.x , V.y , V.z ) end
self:SetPos( ent:LocalToWorld( Voff ) )
local Aoff = Angle(0,0,0)
if A then Aoff = Angle( A.p , A.y , A.r ) end
self:SetAngles( ent:GetAngles() + Aoff )
self.ATWeld = constraint.Weld( ent , self , 0, 0, 0, true )
self:SetSkin( ent:GetSkin() )
--self.OpenTrigger = false
self.ATEnt = ent
self.VecOff = Voff
self.AngOff = Aoff
self:GetPhysicsObject():EnableMotion( true )
ent:DeleteOnRemove( self )
end
function ENT:SetController( cont , sysnum )
if cont and IsValid(cont) then
self.Cont = cont
end
if sysnum then
self.SDN = sysnum
end
end
function ENT:OpenDoorSounds()
self:EmitSound( self.D.OS[0] )
for k,v in pairs( self.D.OS ) do
local var = "SBEP_"..tostring( self.Index ).."_OpenSounds_"..tostring( k )
table.insert( self.Timers , var )
timer.Create( var , k , 1 , function()
if( not v ) then return end
self:EmitSound( v )
end )
end
end
function ENT:CloseDoorSounds()
self:EmitSound( self.D.CS[0] )
for k,v in pairs( self.D.CS ) do
local var = "SBEP_"..tostring( self.Index ).."_CloseSounds_"..tostring( k )
table.insert( self.Timers , var )
timer.Create( var , k , 1 , function()
if( not v ) then return end
self:EmitSound( v )
end )
end
end
function ENT:GetSequenceData()
self.OSeq = self:LookupSequence( "open" )
self.CSeq = self:LookupSequence( "close" )
end
function ENT:Open()
self:ResetSequence( self.OSeq )
self:OpenDoorSounds()
local var = "SBEP_"..tostring( self.Index ).."_OpenSolid"
table.insert( self.Timers , var )
timer.Create( var , self.D.OD , 1 , function()
self:SetNotSolid( true )
end)
local var = "SBEP_"..tostring( self.Index ).."_OpenStatus"
table.insert( self.Timers , var )
timer.Create( var , self.D.UD , 1 , function()
self.OpenStatus = true
if self.Cont then
WireLib.TriggerOutput(self.Cont,"Open_"..tostring( self.SDN ),1)
end
end)
if self.Cont then
WireLib.TriggerOutput(self.Cont,"Open_"..tostring( self.SDN ),0.5)
end
end
function ENT:Close()
self:ResetSequence( self.CSeq )
self:CloseDoorSounds()
local var = "SBEP_"..tostring( self.Index ).."_CloseSolid"
table.insert( self.Timers , var )
timer.Create( var , self.D.CD , 1 , function()
self:SetNotSolid( false )
end)
local var = "SBEP_"..tostring( self.Index ).."_CloseStatus"
table.insert( self.Timers , var )
timer.Create( var , self.D.UD , 1 , function()
self.OpenStatus = false
if self.Cont then
WireLib.TriggerOutput(self.Cont,"Open_"..tostring( self.SDN ),0)
end
end)
if self.Cont then
WireLib.TriggerOutput(self.Cont,"Open_"..tostring( self.SDN ),0.5)
end
end
function ENT:Think()
if !(self.OpenTrigger == nil) then
if self.OpenTrigger and !self:IsOpen() and !self.OpenStatus then
self:Open()
elseif !self.OpenTrigger and self:IsOpen() and self.OpenStatus then
self:Close()
end
end
if (self.ATEnt and self.ATEnt:IsValid() ) and (!self.ATWeld or !self.ATWeld:IsValid()) then
local wt = constraint.FindConstraints( self , "Weld" )
for n,C in ipairs( wt ) do
if C.Ent2 == self.ATEnt or C.Ent1 == self.ATEnt then
self.ATWeld = C.Constraint
end
end
if !self.Duped and (!self.ATWeld or !self.ATWeld:IsValid()) then
self:Attach( self.ATEnt , self.VecOff , self.AngOff )
else
if self.ATWeld then self.Duped=nil end
end
end
if self.Cont then
if self:GetSkin() ~= self.Cont.Skin && self.Cont.Skin then
self:SetSkin( self.Cont.Skin )
end
end
self:NextThink( CurTime() + 0.05 )
return true
end
function ENT:IsOpen()
if self:GetSequence() == self.OSeq then -- and self.OpenStatus then
return true
elseif self:GetSequence() == self.CSeq then -- and !self.OpenStatus then
return false
end
end
function ENT:Use( activator, caller )
if IsValid(self.Cont) and self.Cont then
self.Cont:Trigger()
end
end
function ENT:OnRemove()
for k,v in ipairs( self.Timers ) do
if timer.Exists( v ) then
timer.Remove( v )
end
end
if self.Cont and IsValid( self.Cont ) then
table.remove( self.Cont.DT , self.SDN )
self.Cont:MakeWire( true )
end
end
function ENT:PreEntityCopy()
local DI = {}
DI.type = self.type
DI.DClass = self.DClass
if self.Cont then
DI.Cont = self.Cont:EntIndex()
end
DI.D = self.D
DI.ATEnt = self.ATEnt:EntIndex()
DI.VecOff = self.VecOff
DI.AngOff = self.AngOff
duplicator.StoreEntityModifier(self, "SBEPD", DI)
end
duplicator.RegisterEntityModifier( "SBEPD" , function() end)
function ENT:PostEntityPaste(pl, Ent, CreatedEntities)
local DI = Ent.EntityMods.SBEPD
self.type = DI.type
self.DClass = DI.DClass or 1
self.D = DI.D
self.ATEnt = CreatedEntities[ DI.ATEnt ]
self.VecOff = DI.VecOff
self.AngOff = DI.AngOff
self.Duped = true
if Ent.EntityMods.SBEPD.Cont then
self:SetController( CreatedEntities[ DI.Cont ] )
end
self:PhysicsInitialize()
self:GetSequenceData()
self:Close()
end
function MakeDoor( Player, Data )
local ent = ents.Create( Data.Class )
duplicator.DoGeneric( ent, Data )
ent:Spawn()
duplicator.DoGenericPhysics( ent, Player, Data )
return ent
end
duplicator.RegisterEntityClass( "sbep_base_door", MakeDoor, "Data" ) | apache-2.0 |
m-creations/openwrt | feeds/routing/luci-app-cjdns/luasrc/controller/cjdns.lua | 10 | 2652 | module("luci.controller.cjdns", package.seeall)
cjdns = require "cjdns/init"
dkjson = require "dkjson"
function index()
if not nixio.fs.access("/etc/config/cjdns") then
return
end
entry({"admin", "services", "cjdns"},
cbi("cjdns/overview"), _("cjdns")).dependent = true
entry({"admin", "services", "cjdns", "overview"},
cbi("cjdns/overview"), _("Overview"), 1).leaf = false
entry({"admin", "services", "cjdns", "peering"},
cbi("cjdns/peering"), _("Peers"), 2).leaf = false
entry({"admin", "services", "cjdns", "iptunnel"},
cbi("cjdns/iptunnel"), _("IP Tunnel"), 3).leaf = false
entry({"admin", "services", "cjdns", "settings"},
cbi("cjdns/settings"), _("Settings"), 4).leaf = false
entry({"admin", "services", "cjdns", "cjdrouteconf"},
cbi("cjdns/cjdrouteconf"), _("cjdroute.conf"), 5).leaf = false
entry({"admin", "services", "cjdns", "peers"}, call("act_peers")).leaf = true
entry({"admin", "services", "cjdns", "ping"}, call("act_ping")).leaf = true
end
function act_peers()
require("cjdns/uci")
admin = cjdns.uci.makeInterface()
local page = 0
local peers = {}
while page do
local response, err = admin:auth({
q = "InterfaceController_peerStats",
page = page
})
if err or response.error then
luci.http.status(502, "Bad Gateway")
luci.http.prepare_content("application/json")
luci.http.write_json({ err = err, response = response })
return
end
for i,peer in pairs(response.peers) do
peer.ipv6 = publictoip6(peer.publicKey)
if peer.user == nil then
peer.user = ''
uci.cursor():foreach("cjdns", "udp_peer", function(udp_peer)
if peer.publicKey == udp_peer.public_key then
peer.user = udp_peer.user
end
end)
end
peers[#peers + 1] = peer
end
if response.more then
page = page + 1
else
page = nil
end
end
luci.http.status(200, "OK")
luci.http.prepare_content("application/json")
luci.http.write_json(peers)
end
function act_ping()
require("cjdns/uci")
admin = cjdns.uci.makeInterface()
local response, err = admin:auth({
q = "SwitchPinger_ping",
path = luci.http.formvalue("label"),
timeout = tonumber(luci.http.formvalue("timeout"))
})
if err or response.error then
luci.http.status(502, "Bad Gateway")
luci.http.prepare_content("application/json")
luci.http.write_json({ err = err, response = response })
return
end
luci.http.status(200, "OK")
luci.http.prepare_content("application/json")
luci.http.write_json(response)
end
function publictoip6(publicKey)
local process = io.popen("/usr/bin/publictoip6 " .. publicKey, "r")
local ipv6 = process:read()
process:close()
return ipv6
end
| gpl-2.0 |
MmxBoy/Metal-bot | plugins/bugzilla.lua | 611 | 3983 | do
local BASE_URL = "https://bugzilla.mozilla.org/rest/"
local function bugzilla_login()
local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password
print("accessing " .. url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_check(id)
-- data = bugzilla_login()
local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey
-- print(url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_listopened(email)
local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey
local res,code = https.request( url )
print(res)
local data = json:decode(res)
return data
end
local function run(msg, matches)
local response = ""
if matches[1] == "status" then
local data = bugzilla_check(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
response = response .. "\n Last update: "..data.bugs[1].last_change_time
response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
print(response)
end
elseif matches[1] == "list" then
local data = bugzilla_listopened(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
-- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
-- response = response .. "\n Last update: "..data.bugs[1].last_change_time
-- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
-- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
-- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
local total = table.map_length(data.bugs)
print("total bugs: " .. total)
local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2]
if total > 0 then
response = response .. ": "
for tableKey, bug in pairs(data.bugs) do
response = response .. "\n #" .. bug.id
response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution
response = response .. "\n Whiteboard: " .. bug.whiteboard
response = response .. "\n Summary: " .. bug.summary
end
end
end
end
return response
end
-- (table)
-- [bugs] = (table)
-- [1] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 927704
-- [whiteboard] = (string) [approved][full processed]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/
-- [2] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 1049337
-- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/
-- total bugs: 2
return {
description = "Lookup bugzilla status update",
usage = "/bot bugzilla [bug number]",
patterns = {
"^/bugzilla (status) (.*)$",
"^/bugzilla (list) (.*)$"
},
run = run
}
end | gpl-2.0 |
nl253/Dot-files | .vim/after/ftplugin/markdown/task-list.lua | 1 | 3843 | local List = require 'pandoc.List'
local M = {}
local function is_html (format)
return format == 'html' or format == 'html4' or format == 'html5'
end
--- Create a ballot box for the given output format.
function M.ballot_box (format)
if is_html(format) then
return pandoc.RawInline(
'html',
'<input type="checkbox" class="task-list-item-checkbox" disabled />'
)
elseif format == 'gfm' then
-- GFM includes raw HTML
return pandoc.RawInline('html', '[ ]')
elseif format == 'org' then
return pandoc.RawInline('org', '[ ]')
elseif format == 'latex' then
return pandoc.RawInline('tex', '$\\square$')
else
return pandoc.Str '☐'
end
end
--- Create a checked ballot box for the given output format.
function M.ballot_box_with_check (format)
if is_html(format) then
return pandoc.RawInline(
'html',
'<input type="checkbox" class="task-list-item-checkbox" checked disabled />'
)
elseif format == 'gfm' then
-- GFM includes raw HTML
return pandoc.RawInline('html', '[x]')
elseif format == 'org' then
return pandoc.RawInline('org', '[X]')
elseif format == 'latex' then
return pandoc.RawInline('tex', '$\\rlap{$\\checkmark$}\\square$')
else
return pandoc.Str '☑'
end
end
--- Replace a Github-style task indicator with a bullet box representation
--- suitable for the given output format.
function M.todo_marker (inlines, format)
if (inlines[1] and inlines[1].text == '[' and
inlines[2] and inlines[2].t == 'Space' and
inlines[3] and inlines[3].text == ']') then
return M.ballot_box(format), 3
elseif (inlines[1] and
(inlines[1].text == '[x]' or
inlines[1].text == '[X]')) then
return M.ballot_box_with_check(format), 1
else
return nil, 0
end
end
M.css_styles = [[
<style>
.task-list-item {
list-style-type: none;
}
.task-list-item-checkbox {
margin-left: -1.6em;
}
</style>
]]
--- Add task-list CSS styles to the header.
function M.add_task_list_css(meta)
local header_includes
if meta['header-includes'] and meta['header-includes'].t == 'MetaList' then
header_includes = meta['header-includes']
else
header_includes = pandoc.MetaList{meta['header-includes']}
end
header_includes[#header_includes + 1] =
pandoc.MetaBlocks{pandoc.RawBlock('html', M.css_styles)}
meta['header-includes'] = header_includes
return meta
end
--- Replace the todo marker in the given block, if any.
function M.replace_todo_markers (blk, format)
if blk.t ~= 'Para' and blk.t ~= 'Plain' then
return blk
end
local inlines = blk.content
local box, num_inlines = M.todo_marker(inlines, format)
if box == nil then
return blk
end
local new_inlines = List:new{box}
for j = 1, #inlines do
new_inlines[j + 1] = inlines[j + num_inlines]
end
return pandoc[blk.t](new_inlines) -- create Plain or Para
end
--- Convert Github- and org-mode-style task markers in a BulletList.
function M.modifyBulletList (list)
if not is_html(FORMAT) then
for _, item in ipairs(list.content) do
item[1] = M.replace_todo_markers(item[1], FORMAT)
end
return list
else
local res = List:new{pandoc.RawBlock('html', '<ul>')}
for _, item in ipairs(list.content) do
local blk = M.replace_todo_markers(item[1], FORMAT)
if blk == item[1] then -- does not have a todo marker
res[#res + 1] = pandoc.RawBlock('html', '<li>')
else
res[#res + 1] = pandoc.RawBlock('html', '<li class="task-list-item">')
item[1] = blk
end
res:extend(item)
res[#res + 1] = pandoc.RawBlock('html', '</li>')
end
res[#res + 1] = pandoc.RawBlock('html', '</ul>')
return res
end
end
M[1] = {
BulletList = M.modifyBulletList,
Meta = is_html(FORMAT) and M.add_task_list_css or nil
}
return M
| mit |
m-creations/openwrt | feeds/luci/applications/luci-app-vnstat/luasrc/model/cbi/vnstat.lua | 78 | 1816 | -- Copyright 2010-2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local utl = require "luci.util"
local sys = require "luci.sys"
local fs = require "nixio.fs"
local nw = require "luci.model.network"
local dbdir, line
for line in io.lines("/etc/vnstat.conf") do
dbdir = line:match("^%s*DatabaseDir%s+[\"'](%S-)[\"']")
if dbdir then break end
end
dbdir = dbdir or "/var/lib/vnstat"
m = Map("vnstat", translate("VnStat"),
translate("VnStat is a network traffic monitor for Linux that keeps a log of network traffic for the selected interface(s)."))
m.submit = translate("Restart VnStat")
m.reset = false
nw.init(luci.model.uci.cursor_state())
local ifaces = { }
local enabled = { }
local iface
if fs.access(dbdir) then
for iface in fs.dir(dbdir) do
if iface:sub(1,1) ~= '.' then
ifaces[iface] = iface
enabled[iface] = iface
end
end
end
for _, iface in ipairs(sys.net.devices()) do
ifaces[iface] = iface
end
local s = m:section(TypedSection, "vnstat")
s.anonymous = true
s.addremove = false
mon_ifaces = s:option(Value, "interface", translate("Monitor selected interfaces"))
mon_ifaces.template = "cbi/network_ifacelist"
mon_ifaces.widget = "checkbox"
mon_ifaces.cast = "table"
mon_ifaces.noinactive = true
mon_ifaces.nocreate = true
function mon_ifaces.write(self, section, val)
local i
local s = { }
if val then
for _, i in ipairs(type(val) == "table" and val or { val }) do
s[i] = true
end
end
for i, _ in pairs(ifaces) do
if not s[i] then
fs.unlink(dbdir .. "/" .. i)
fs.unlink(dbdir .. "/." .. i)
end
end
if next(s) then
m.uci:set_list("vnstat", section, "interface", utl.keys(s))
else
m.uci:delete("vnstat", section, "interface")
end
end
mon_ifaces.remove = mon_ifaces.write
return m
| gpl-2.0 |
SlimSaber/android_external_skia | tools/lua/bitmap_statistics.lua | 207 | 1862 | 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
local canvas = nil
local num_perspective_bitmaps = 0
local num_affine_bitmaps = 0
local num_scaled_bitmaps = 0
local num_translated_bitmaps = 0
local num_identity_bitmaps = 0
local num_scaled_up = 0
local num_scaled_down = 0
function sk_scrape_startcanvas(c, fileName)
canvas = c
end
function sk_scrape_endcanvas(c, fileName)
canvas = nil
end
function sk_scrape_accumulate(t)
-- dump the params in t, specifically showing the verb first, which we
-- then nil out so it doesn't appear in tostr()
if (string.startsWith(t.verb,"drawBitmap")) then
matrix = canvas:getTotalMatrix()
matrixType = matrix:getType()
if matrixType.perspective then
num_perspective_bitmaps = num_perspective_bitmaps + 1
elseif matrixType.affine then
num_affine_bitmaps = num_affine_bitmaps + 1
elseif matrixType.scale then
num_scaled_bitmaps = num_scaled_bitmaps + 1
if matrix:getScaleX() > 1 or matrix:getScaleY() > 1 then
num_scaled_up = num_scaled_up + 1
else
num_scaled_down = num_scaled_down + 1
end
elseif matrixType.translate then
num_translated_bitmaps = num_translated_bitmaps + 1
else
num_identity_bitmaps = num_identity_bitmaps + 1
end
end
end
function sk_scrape_summarize()
io.write( "identity = ", num_identity_bitmaps,
", translated = ", num_translated_bitmaps,
", scaled = ", num_scaled_bitmaps, " (up = ", num_scaled_up, "; down = ", num_scaled_down, ")",
", affine = ", num_affine_bitmaps,
", perspective = ", num_perspective_bitmaps,
"\n")
end
| bsd-3-clause |
rasolllll/tele_gold | plugins/inrealm.lua | 850 | 25085 | -- 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 is_sudo(msg) or is_realm(msg) and is_admin(msg) then
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
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['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, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
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
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) 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]
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
deepak78/new-luci | applications/luci-app-multiwan/luasrc/controller/multiwan.lua | 62 | 1929 | module("luci.controller.multiwan", package.seeall)
function index()
local fs = require "nixio.fs"
if not fs.access("/etc/config/multiwan") then
return
end
local page
page = entry({"admin", "network", "multiwan"}, cbi("multiwan/multiwan"), _("Multi-WAN"))
page.dependent = true
entry({"admin", "network", "multiwan", "status"}, call("multiwan_status"))
page = entry({"mini", "network", "multiwan"}, cbi("multiwan/multiwanmini", {autoapply=true}), _("Multi-WAN"))
page.dependent = true
end
function multiwan_status()
local nfs = require "nixio.fs"
local cachefile = "/tmp/.mwan/cache"
local rv = { }
cachefile = nfs.readfile(cachefile)
if cachefile then
local ntm = require "luci.model.network".init()
_, _, wan_if_map = string.find(cachefile, "wan_if_map=\"([^\"]*)\"")
_, _, wan_fail_map = string.find(cachefile, "wan_fail_map=\"([^\"]*)\"")
_, _, wan_recovery_map = string.find(cachefile, "wan_recovery_map=\"([^\"]*)\"")
rv.wans = { }
wansid = {}
for wanname, wanifname in string.gfind(wan_if_map, "([^%[]+)%[([^%]]+)%]") do
local wanlink = ntm:get_interface(wanifname)
wanlink = wanlink and wanlink:get_network()
wanlink = wanlink and wanlink:adminlink() or "#"
wansid[wanname] = #rv.wans + 1
rv.wans[wansid[wanname]] = { name = wanname, link = wanlink, ifname = wanifname, status = "ok", count = 0 }
end
for wanname, failcount in string.gfind(wan_fail_map, "([^%[]+)%[([^%]]+)%]") do
if failcount == "x" then
rv.wans[wansid[wanname]].status = "ko"
else
rv.wans[wansid[wanname]].status = "failing"
rv.wans[wansid[wanname]].count = failcount
end
end
for wanname, recoverycount in string.gfind(wan_recovery_map, "([^%[]+)%[([^%]]+)%]") do
rv.wans[wansid[wanname]].status = "recovering"
rv.wans[wansid[wanname]].count = recoverycount
end
end
luci.http.prepare_content("application/json")
luci.http.write_json(rv)
end
| apache-2.0 |
vzaramel/kong | kong/plugins/rate-limiting/access.lua | 6 | 2468 | local constants = require "kong.constants"
local timestamp = require "kong.tools.timestamp"
local responses = require "kong.tools.responses"
local _M = {}
local function get_identifier()
local identifier
-- Consumer is identified by ip address or authenticated_entity id
if ngx.ctx.authenticated_entity then
identifier = ngx.ctx.authenticated_entity.id
else
identifier = ngx.var.remote_addr
end
return identifier
end
local function increment(api_id, identifier, current_timestamp, value)
-- Increment metrics for all periods if the request goes through
local _, stmt_err = dao.ratelimiting_metrics:increment(api_id, identifier, current_timestamp, value)
if stmt_err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(stmt_err)
end
end
local function get_usage(api_id, identifier, current_timestamp, limits)
local usage = {}
local stop
for name, limit in pairs(limits) do
local current_metric, err = dao.ratelimiting_metrics:find_one(api_id, identifier, current_timestamp, name)
if err then
return responses.send_HTTP_INTERNAL_SERVER_ERROR(err)
end
-- What is the current usage for the configured limit name?
local current_usage = current_metric and current_metric.value or 0
local remaining = limit - current_usage
-- Recording usage
usage[name] = {
limit = limit,
remaining = remaining
}
if remaining <= 0 then
stop = name
end
end
return usage, stop
end
function _M.execute(conf)
local current_timestamp = timestamp.get_utc()
-- Consumer is identified by ip address or authenticated_entity id
local identifier = get_identifier()
local api_id = ngx.ctx.api.id
-- Load current metric for configured period
local usage, stop = get_usage(api_id, identifier, current_timestamp, conf)
-- Adding headers
for k, v in pairs(usage) do
ngx.header[constants.HEADERS.RATELIMIT_LIMIT.."-"..k] = v.limit
ngx.header[constants.HEADERS.RATELIMIT_REMAINING.."-"..k] = math.max(0, (stop == nil or stop == k) and v.remaining - 1 or v.remaining) -- -increment_value for this current request
end
-- If limit is exceeded, terminate the request
if stop then
ngx.ctx.stop_phases = true -- interrupt other phases of this request
return responses.send(429, "API rate limit exceeded")
end
-- Increment metrics for all periods if the request goes through
increment(api_id, identifier, current_timestamp, 1)
end
return _M
| apache-2.0 |
LegionXI/darkstar | scripts/zones/Mount_Kamihr/Zone.lua | 30 | 1254 | -----------------------------------
--
-- Zone: Mount Kamihr
--
-----------------------------------
package.loaded["scripts/zones/Mount_Kamihr/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Mount_Kamihr/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
-- player:setPos(x, y, z, r);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
LegionXI/darkstar | scripts/globals/items/galkan_sausage_+2.lua | 12 | 1357 | -----------------------------------------
-- ID: 5860
-- Item: galkan_sausage_+2
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Strength 5
-- Intelligence -6
-- Attack 11
-- Ranged Attack 11
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5860);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 5);
target:addMod(MOD_INT, -6);
target:addMod(MOD_ATT, 11);
target:addMod(MOD_RATT, 11);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 5);
target:delMod(MOD_INT, -6);
target:delMod(MOD_ATT, 11);
target:delMod(MOD_RATT, 11);
end;
| gpl-3.0 |
lache/RacingKingLee | crazyclient/frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ActionTimelineNode.lua | 11 | 1809 |
--------------------------------
-- @module ActionTimelineNode
-- @extend Node
-- @parent_module ccs
--------------------------------
--
-- @function [parent=#ActionTimelineNode] getRoot
-- @param self
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
--
-- @function [parent=#ActionTimelineNode] getActionTimeline
-- @param self
-- @return ActionTimeline#ActionTimeline ret (return value: ccs.ActionTimeline)
--------------------------------
--
-- @function [parent=#ActionTimelineNode] setActionTimeline
-- @param self
-- @param #ccs.ActionTimeline action
-- @return ActionTimelineNode#ActionTimelineNode self (return value: ccs.ActionTimelineNode)
--------------------------------
--
-- @function [parent=#ActionTimelineNode] init
-- @param self
-- @param #cc.Node root
-- @param #ccs.ActionTimeline action
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ActionTimelineNode] setRoot
-- @param self
-- @param #cc.Node root
-- @return ActionTimelineNode#ActionTimelineNode self (return value: ccs.ActionTimelineNode)
--------------------------------
--
-- @function [parent=#ActionTimelineNode] create
-- @param self
-- @param #cc.Node root
-- @param #ccs.ActionTimeline action
-- @return ActionTimelineNode#ActionTimelineNode ret (return value: ccs.ActionTimelineNode)
--------------------------------
--
-- @function [parent=#ActionTimelineNode] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ActionTimelineNode] ActionTimelineNode
-- @param self
-- @return ActionTimelineNode#ActionTimelineNode self (return value: ccs.ActionTimelineNode)
return nil
| mit |
greasydeal/darkstar | scripts/globals/spells/bluemagic/smite_of_rage.lua | 28 | 1707 | -----------------------------------------
-- Spell: Smite of Rage
-- Damage varies with TP
-- Spell cost: 28 MP
-- Monster Type: Arcana
-- Spell Type: Physical (Slashing)
-- Blue Magic Points: 3
-- Stat Bonus: AGI+3
-- Level: 34
-- Casting Time: 0.5 seconds
-- Recast Time: 13 seconds
-- Skillchain Element(s): Wind (can open Scission or Gravitation; can close Detonation)
-- Combos: Undead Killer
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_DAMAGE;
params.dmgtype = DMGTYPE_SLASH;
params.scattr = SC_DETONATION;
params.numhits = 1;
params.multiplier = 1.5;
params.tp150 = 2.25;
params.tp300 = 2.5;
params.azuretp = 2.53125;
params.duppercap = 35;
params.str_wsc = 0.2;
params.dex_wsc = 0.2;
params.vit_wsc = 0.0;
params.agi_wsc = 0.0;
params.int_wsc = 0.0;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
ibm2431/darkstar | scripts/globals/mobskills/dancing_chains.lua | 11 | 1058 | ---------------------------------------------
-- Dancing Chains
--
-- Description: Additional effect: Drown
-- Type: Magical
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: Unknown cone
-- Notes:
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 1
local accmod = 1
local dmgmod = 3
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.BLUNT,info.hitslanded)
local typeEffect = dsp.effect.DROWN
local power = mob:getMainLvl() / 3
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, power, 3, 60)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.BLUNT)
return dmg
end
| gpl-3.0 |
evrooije/beerarchy | mods/00_bt_misc/intllib/init.lua | 2 | 3701 |
-- Old multi-load method compatibility
if rawget(_G, "intllib") then return end
intllib = {
getters = {},
strings = {},
}
local MP = minetest.get_modpath("intllib")
dofile(MP.."/lib.lua")
local LANG = minetest.setting_get("language")
if not (LANG and (LANG ~= "")) then LANG = os.getenv("LANG") end
if not (LANG and (LANG ~= "")) then LANG = "en" end
local INS_CHAR = intllib.INSERTION_CHAR
local insertion_pattern = "("..INS_CHAR.."?)"..INS_CHAR.."(%(?)(%d+)(%)?)"
local function do_replacements(str, ...)
local args = {...}
-- Outer parens discard extra return values
return (str:gsub(insertion_pattern, function(escape, open, num, close)
if escape == "" then
local replacement = tostring(args[tonumber(num)])
if open == "" then
replacement = replacement..close
end
return replacement
else
return INS_CHAR..open..num..close
end
end))
end
local function make_getter(msgstrs)
return function(s, ...)
local str
if msgstrs then
str = msgstrs[s]
end
if not str or str == "" then
str = s
end
if select("#", ...) == 0 then
return str
end
return do_replacements(str, ...)
end
end
local function Getter(modname)
modname = modname or minetest.get_current_modname()
if not intllib.getters[modname] then
local msgstr = intllib.get_strings(modname)
intllib.getters[modname] = make_getter(msgstr)
end
return intllib.getters[modname]
end
function intllib.Getter(modname)
minetest.log("deprecated", "intllib.Getter is deprecated."
.."Please use intllib.make_gettext_pair instead.")
return Getter(modname)
end
local gettext = dofile(minetest.get_modpath("intllib").."/gettext.lua")
local function catgettext(catalogs, msgid)
for _, cat in ipairs(catalogs) do
local msgstr = cat and cat[msgid]
if msgstr and msgstr~="" then
local msg = msgstr[0]
return msg~="" and msg or nil
end
end
end
local function catngettext(catalogs, msgid, msgid_plural, n)
n = math.floor(n)
for _, cat in ipairs(catalogs) do
local msgstr = cat and cat[msgid]
if msgstr then
local index = cat.plural_index(n)
local msg = msgstr[index]
return msg~="" and msg or nil
end
end
return n==1 and msgid or msgid_plural
end
local gettext_getters = { }
function intllib.make_gettext_pair(modname)
modname = modname or minetest.get_current_modname()
if gettext_getters[modname] then
return unpack(gettext_getters[modname])
end
local localedir = minetest.get_modpath(modname).."/locale"
local catalogs = gettext.load_catalogs(localedir)
local getter = Getter(modname)
local function gettext_func(msgid, ...)
local msgstr = (catgettext(catalogs, msgid)
or getter(msgid))
return do_replacements(msgstr, ...)
end
local function ngettext_func(msgid, msgid_plural, n, ...)
local msgstr = (catngettext(catalogs, msgid, msgid_plural, n)
or getter(msgid))
return do_replacements(msgstr, ...)
end
gettext_getters[modname] = { gettext_func, ngettext_func }
return gettext_func, ngettext_func
end
local function get_locales(code)
local ll, cc = code:match("^(..)_(..)")
if ll then
return { ll.."_"..cc, ll, ll~="en" and "en" or nil }
else
return { code, code~="en" and "en" or nil }
end
end
function intllib.get_strings(modname, langcode)
langcode = langcode or LANG
modname = modname or minetest.get_current_modname()
local msgstr = intllib.strings[modname]
if not msgstr then
local modpath = minetest.get_modpath(modname)
msgstr = { }
for _, l in ipairs(get_locales(langcode)) do
local t = intllib.load_strings(modpath.."/locale/"..l..".txt") or { }
for k, v in pairs(t) do
msgstr[k] = msgstr[k] or v
end
end
intllib.strings[modname] = msgstr
end
return msgstr
end
| lgpl-2.1 |
naclander/tome | game/engines/default/engine/dialogs/AudioOptions.lua | 3 | 2335 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
local Dialog = require "engine.ui.Dialog"
local Textzone = require "engine.ui.Textzone"
local Checkbox = require "engine.ui.Checkbox"
local Numberbox = require "engine.ui.Numberbox"
local Separator = require "engine.ui.Separator"
module(..., package.seeall, class.inherit(Dialog))
function _M:init()
Dialog.init(self, "Audio Options", 400, 300)
self.c_enable = Checkbox.new{title="Enable audio", default=config.settings.audio.enable, fct=function() end, on_change=function(s) self:sfxEnable(s) end}
self.c_music_vol = Numberbox.new{title="Music volume: ", number=config.settings.audio.music_volume, max=100, min=0, chars=5, fct=function() end, on_change=function(v) self:sfxVolume("music", v) end}
self.c_effects_vol = Numberbox.new{title="Sound effects volume: ", number=config.settings.audio.effects_volume, max=100, min=0, chars=5, fct=function() end, on_change=function(v) self:sfxVolume("effects", v) end}
self:loadUI{
{left=0, top=0, ui=self.c_enable},
{left=0, top=self.c_enable.h + 10, ui=self.c_music_vol},
{left=0, top=self.c_enable.h + 10 + self.c_music_vol.h, ui=self.c_effects_vol},
}
self:setupUI(true, true)
self.key:addBinds{
EXIT = function() game:unregisterDialog(self) end,
}
end
function _M:sfxEnable(s)
config.settings.audio.enable = s and true or false
core.sound.enable(s)
game:audioSaveSettings()
end
function _M:sfxVolume(what, s)
if what == "music" and game.volumeMusic then game:volumeMusic(s)
elseif what == "effects" and game.volumeSoundEffects then game:volumeSoundEffects(s) end
end
| gpl-3.0 |
ibm2431/darkstar | scripts/zones/Western_Altepa_Desert/npcs/qm2.lua | 9 | 1412 | -----------------------------------
-- Area: Western Altepa Desert
-- NPC: qm2 (???)
-- Involved in Mission: Bastok 6-1
-- !pos -325 0 -111 125
-----------------------------------
local ID = require("scripts/zones/Western_Altepa_Desert/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
if
player:getCurrentMission(BASTOK) == dsp.mission.id.bastok.RETURN_OF_THE_TALEKEEPER and
player:getCharVar("MissionStatus") == 2 and
not player:hasKeyItem(dsp.ki.ALTEPA_MOONPEBBLE)
then
if not GetMobByID(ID.mob.EASTERN_SPHINX):isSpawned() and not GetMobByID(ID.mob.WESTERN_SPHINX):isSpawned() then
if player:getCharVar("Mission6-1MobKilled") > 0 then
player:addKeyItem(dsp.ki.ALTEPA_MOONPEBBLE)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.ALTEPA_MOONPEBBLE)
player:setCharVar("Mission6-1MobKilled", 0)
player:setCharVar("MissionStatus", 3)
else
SpawnMob(ID.mob.EASTERN_SPHINX)
SpawnMob(ID.mob.WESTERN_SPHINX)
end
end
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/The_Celestial_Nexus/bcnms/celestial_nexus.lua | 13 | 1989 | -----------------------------------
-- Area: The Celestial Nexus
-- Name: The Celestial Nexus (ZM16)
-----------------------------------
package.loaded["scripts/zones/The_Celestial_Nexus/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/titles");
require("scripts/globals/missions");
require("scripts/zones/The_Celestial_Nexus/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if(player:hasCompletedMission(ZILART,THE_CELESTIAL_NEXUS)) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0);
end
elseif(leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if(csid == 0x7d01) then
if(player:getCurrentMission(ZILART) == THE_CELESTIAL_NEXUS) then
player:completeMission(ZILART,THE_CELESTIAL_NEXUS);
player:addMission(ZILART,AWAKENING);
player:addTitle(BURIER_OF_THE_ILLUSION);
player:setVar("ZilartStatus",0);
end
-- You will be transported to the Hall of the Gods
player:setPos(0,-18,137,64,251);
end
end; | gpl-3.0 |
LegionXI/darkstar | scripts/globals/items/heat_rod.lua | 41 | 1097 | -----------------------------------------
-- ID: 17071
-- Item: Heat Rod
-- Additional Effect: Lightning Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(5,20);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_LIGHTNING, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHTNING,0);
dmg = adjustForTarget(target,dmg,ELE_LIGHTNING);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHTNING,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_LIGHTNING_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
pokemoncentral/wiki-lua-modules | Stats.lua | 1 | 28242 | --[[
This module displays wikicode for anything
related to a set of values for all six statistics.
So far, it can display stats for a single
Pokémon, the average for a single type and
user-supplied values
--]]
local s = {}
local txt = require('Wikilib-strings') -- luacheck: no unused
local tab = require('Wikilib-tables') -- luacheck: no unused
local formUtil = require('Wikilib-forms')
local formulas = require('Wikilib-formulas')
local gamesUtil = require('Wikilib-games')
local genUtil = require('Wikilib-gens')
local list = require('Wikilib-lists')
local mg = require('Wikilib-multigen')
local oop = require('Wikilib-oop')
local statsUtil = require('Wikilib-stats')
local multigen = require('Wikilib-multigen')
local w = require('Wikilib')
local css = require('Css')
local cc = require('ChooseColor')
local alt = require("AltForms-data")
local c = require("Colore-data")
local gendata = require("Gens-data")
local pokes = require('Poké-data')
local stats = require("PokéStats-data")
local mw = require('mw')
-- Mapping of stat keys to user-interface names
local statNames = {
hp = 'PS',
atk = 'Attacco',
def = 'Difesa',
spatk = 'Att. Sp.',
spdef = 'Dif. Sp.',
spec = 'Speciali',
spe = 'Velocità'
}
-- Mapping of stat keys to URL fragments in 'Statistiche' page
local statLinks = mw.clone(statNames)
statLinks.spatk = 'Attacco_Speciale'
statLinks.spdef = 'Difesa_Speciale'
-- Long wikicode strings making functions unreadable
local strings = {
boundsFooter = [=[
* Le [[statistiche]] minime sono calcolate con ${minParams}.
* Le statistiche massime sono calcolate ${maxParams}.]=],
boxFormWrapper = [[==== ${title} ====
<div class="${collapse}">
${box}
</div>]],
boxStats = [=[{| class="roundy text-center${align}${width} ${textcolor}" style="border-spacing: 0 0.3ex; padding: 0.3ex 0.5ex; font-weight: bolder; ${bg};"
! colspan="2" ${rs}style="padding: 0.3ex 0.8ex;" | Statistiche base${values}
${stats}
|-
| style="padding: 0.3ex 0.8ex;" | Totale
| class="text-left" style="padding: 0.3ex 0.8ex 0.3ex 1.8ex;" | ${total}${footer}
|}]=],
catSpecToBoth = '[[Categoria:Pokémon la cui statistica Speciali è diventata sia Attacco Speciale che Difesa Speciale|${display}]]',
catSpecToSpatk = '[[Categoria:Pokémon la cui statistica Speciali è diventata Attacco Speciale|${display}]]',
catSpecToSpdef = '[[Categoria:Pokémon la cui statistica Speciali è diventata Difesa Speciale|${display}]]',
catStatsChanged = '[[Categoria:Pokémon le cui statistiche base sono cambiate in ${gen} generazione|${display}]]',
catTotal = '[[Categoria:Pokémon con statistiche base totali di ${tot}|${display}]]',
catStatsEqual = '[[Categoria:Pokémon con lo stesso valore in tutte le statistiche base|${display}]]',
footer = [=[
| colspan="3" class="hidden-xs" |
|-
| colspan="5" class="hidden-xs text-left text-small" style="font-weight: normal;" | ${content}]=],
headerValues = [=[
! colspan="3" class="min-width-xl-30 hidden-xs" style="padding: 0.3ex 0.8ex;" | Valori
|-
! class="hidden-xs" style="width: 0.1ex; padding: 0;" |
! class="hidden-xs text-small" style="padding: 0.3ex 0.8ex;" | Lv. 50
! class="hidden-xs text-small" style="padding: 0.3ex 0.8ex;" | Lv. 100]=],
oldValueFooter = [=[
* La statistica <span style="background: #${stat_color}; padding: 0 0.3ex;">${stat}</span> di questo Pokémon ${when} era pari a '''${old_value}'''.]=],
singleGenFooter = [=[in [[${gen} generazione]]]=],
beforeGenFooter = [=[prima della [[${gen} generazione]]]=],
betweenGenFooter = [=[tra la [[${startGen} generazione|${startGen}]] e la [[${endGen} generazione]]]=],
listFooter = [=[
* Le statistiche di questo Pokémon sono cambiate nel corso delle generazioni. Tutti i valori sono disponibili [[Elenco Pokémon per statistiche base|qui]]. ]=],
statBar = [=[<div class="roundyright text-left" style="width: calc(1em + ${width}%); color: #${dark}; ${bg};">'''${val}'''</div>]=],
statBounds = [=[
| class="hidden-xs" |
| class="${rleft}text-small hidden-xs black-text" style="padding: 0.3ex 0.8ex; white-space: nowrap; background: #${bg};" | ${min50}—${max50}
| class="${rright}text-small hidden-xs black-text" style="padding: 0.3ex 0.8ex; white-space: nowrap; background: #${bg};" | ${min100}—${max100}]=],
statRow = [=[|-
| ${rleft}style="width: 5.5em; padding: 0.3ex 0.8ex; background: #${light};" | [[Statistiche#${link}|<span style="color: #${normale};">${stat}</span>]]
| ${rright}style="padding: 0.3ex 0.8ex 0.3ex 1.8ex; min-width: 9em; background: #${light};" | ${statBar}${bounds}]=],
totalLink = [=[<div class="flex flex-nowrap flex-row flex-main-start flex-items-center">${tot}<span class="text-small text-center" style="margin-left: 2ex;">[[:Categoria:Pokémon con statistiche base totali di ${tot}|Altri Pokémon con questo totale]]</span></div>]=]
}
--[[
Returns the statistics-related categories
a Pokémon should have. As usual, the Pokémon
is to be given as the name + abbreviation
string found in data modules.
--]]
local makeCategories = function(poke, tot)
--[[
Displaying page in the category with
the form name.
--]]
local baseName, abbr = formUtil.getNameAbbr(poke)
local catInterp = {display = table.concat(table.unique{
pokes[poke].name,
alt[baseName] and alt[baseName].names[abbr] or nil
}, ' ')}
-- Closure, as it needs catInterp
local interpCat = function(catString, interpVal)
interpVal = interpVal
and table.merge(catInterp, interpVal)
or catInterp
return string.interp(catString, interpVal)
end
local categories = {interpCat(strings.catTotal, {tot = tot})}
-- Handling gen II special split, if necessary
if stats[poke].spec then
local gen2Stats = mg.getGen(stats[poke], 2)
if gen2Stats.spec == gen2Stats.spatk
and gen2Stats.spec == gen2Stats.spdef then
table.insert(categories, interpCat(strings.catSpecToBoth))
elseif gen2Stats.spec == gen2Stats.spatk then
table.insert(categories, interpCat(strings.catSpecToSpatk))
elseif gen2Stats.spec == gen2Stats.spdef then
table.insert(categories, interpCat(strings.catSpecToSpdef))
end
end
--[[
Handling base stats changes in generations.
Starting from 6 because since gen II until
gen V stats were untouched, and we handled
gen II earlier on.
--]]
for gen = 6, gendata.latest do
local changedInGen = table.any(stats[poke],
function(val)
return type(val) == 'table'
and multigen.getfirstgen(val) ~= gen
and val[gen]
end)
if changedInGen then
table.insert(categories, interpCat(
strings.catStatsChanged, {gen = gendata[gen].ext}))
local genTotal = statsUtil.statsSum(
statsUtil.getStatsGen(stats[poke], gen - 1))
table.insert(categories, interpCat(
strings.catTotal, { tot = genTotal }))
end
end
-- Category for Pokémon with all the base stats equal
do
local firstStat = mg.getGenValue(stats[poke].atk)
local equalFirst = function(val)
return mg.getGenValue(val) == firstStat
end
if table.all(stats[poke], equalFirst) then
table.insert(categories, interpCat(strings.catStatsEqual))
end
end
return table.concat(categories)
end
--[[
Computes the avreage stats of the Pokémon
whose names are given, for the provided generation.
Names must be the name + abbreviation
combination seen in all data modules.
--]]
local statsAvg = function(pokeNames, gen)
local avgStats = statsUtil.getStatsGen({hp = 0,
atk = 0, def = 0, spatk = 0,
spdef = 0, spe = 0, spec = 0}, gen)
-- Computing sum for every stat
avgStats = table.fold(pokeNames, avgStats, function(avgStats, poke)
local pokeStats = statsUtil.getStatsGen(stats[poke], gen)
return table.map(avgStats, function(stat, statName)
return stat + pokeStats[statName]
end)
end)
-- Actually computing average
local pokesCount = table.getn(pokeNames)
return table.map(avgStats, function(stat)
return stat / pokesCount
end)
end
--[[
Prints a row of the stats box for a single stat.
It's fed the stat name, its value, the roundyness
and a generation; the latter two default to false.
The meaning of roundyness values is:
- anything evaluating to false - no roundyness
- 'top' - cells rounded at one top corner
- 'bottom' - cells rounded at bottom corners
The interpretation of the generation is:
- when valid (a number between 1 and `latest`),
it computest min and max values for the
stat, using that generation formula.
- when not valid, (a non-number, or a number
is less than 1 or more than `latest`),
nothing is computed
--]]
local statRow = function(stat, value, gen, roundyness)
local computeBounds = genUtil.isValidGen(gen)
--[[
Interpolation values for basic case,
which means no roundyness and no
min-max calculation.
--]]
local bounds = ''
local roundy = {left = '', right = '',
boundsLeft = '', boundsRight = ''}
if roundyness then
local edge = roundyness:sub(1, 1)
roundy.left = table.concat{'class="roundy', edge, 'l" '}
roundy.right = table.concat{'class="roundy', edge, 'r" '}
if computeBounds then
roundy.boundsLeft = table.concat{'roundy', edge, 'l '}
roundy.boundsRight = table.concat{'roundy', edge, 'r '}
end
end
if computeBounds then
local interpVal
-- Shedinja's HP are not worth to be handled in any other way
if value == 1 then
interpVal = {
rleft = roundy.boundsLeft,
bg = c[stat].light,
min50 = 1,
max50 = 1,
rright = roundy.boundsRight,
min100 = 1,
max100 = 1
}
-- Any normal stat calculation
else
local calcStat = formulas.stats[gen][stat == 'hp' and 'hp' or 'anyOther']
local maxIV, maxEV = statsUtil.ivEvMax(gen)
--[[
Natures are ignored for generations before third and for HP
because the function has one less argument
--]]
interpVal = {
rleft = roundy.boundsLeft,
bg = c[stat].light,
min50 = calcStat(0, value, 0, 50, 0.9),
max50 = calcStat(maxIV, value, maxEV, 50, 1.1),
rright = roundy.boundsRight,
min100 = calcStat(0, value, 0, 100, 0.9),
max100 = calcStat(maxIV, value, maxEV, 100, 1.1)
}
end
bounds = string.interp(strings.statBounds, interpVal)
end
return string.interp(strings.statRow,
{
rleft = roundy.left,
light = c[stat].light,
link = statLinks[stat],
normale = c[stat].normale,
stat = statNames[stat],
rright = roundy.right,
statBar = s.statBarLua(stat, value),
bounds = bounds
})
end
--[[
Prints all the footer lines needed for a stat changed over time.
It takes the stat name and the stat table (in multigen format).
--]]
local makeStatFooterLines = function(stat, values)
local footerLines = {}
local spans = mg.getGenSpan(values)
for k, v in ipairs(spans) do
if k < #spans then -- the last value shouldn't be in the footer
local interpVal = {
stat_color = c[stat].normale,
stat = statLinks[stat]:gsub('_', ' '),
old_value = v.val,
}
if v.first == v.last then
-- Single generation span
interpVal.when = string.interp(strings.singleGenFooter, {
gen = gendata[v.first].ext,
})
elseif k == 1 then
-- The first element has a different text
interpVal.when = string.interp(strings.beforeGenFooter, {
gen = gendata[v.last + 1].ext,
})
else
interpVal.when = string.interp(strings.betweenGenFooter, {
startGen = gendata[v.first].ext,
endGen = gendata[v.last].ext,
})
end
local line = string.interp(strings.oldValueFooter, interpVal)
footerLines[k] = line
end
end
return table.concat(footerLines)
end
--[[
This class represents a statistics box for
a single Pokémon. Forms having the same stats
share can a single box, their names appearing
as a label for the box itself.
--]]
local PokeStatBox = oop.makeClass(list.Labelled)
--[[
Class constructor: as per makeFormsLabelledBoxes
specifications, it takes the name of a Pokémon,
with an appended abbreviations for alternative
forms, a form extended name, and a table with the
following key-value pairs:
- gen: the generation for which statistics
and min-max values will be worked out.
- noCats: whether or not stats-related
categories will be printed.
It will return nil, complying to makeFormsLabelledBoxes,
if no statistics are defined for the Pokémon
or if it is not present in the given generation.
--]]
PokeStatBox.new = function(poke, formExtName, args)
local gen, noCats = args.gen, args.noCats
--[[
Aborting entry: no stats data for the Pokémon
or Pokémon/form not in generation
Actually we keep out of gen Pokés/forms because
they are so few that there isn't really any
advantage in skipping them
--]]
if not stats[poke] then
-- or not gamesUtil.isInGen(poke, gen) then
return nil
end
local this = PokeStatBox.super.new(formExtName)
--[[
Shared boxes have base form types,
which are retrieved if necessary
using the base form name.
--]]
this.baseFormName = formUtil.getNameAbbr(poke)
this.gen = gen
this.listLink = statsUtil.didStatsChange(stats[poke])
this.poke = not noCats and poke
this.stats = statsUtil.getStatsGen(stats[poke], gen)
this.multigenStats = table.map(stats[poke], function(val, key)
if key == 'spec' then
-- Handling stats speciali
return {[1] = val, [2] = 0}
end
return type(val) == 'table' and val or nil
end)
local pokeData = multigen.getGen(pokes[poke])
this.types = {type1 = pokeData.type1, type2 = pokeData.type2}
return setmetatable(this, PokeStatBox)
end
-- Two equal stat boxes have the same stats
PokeStatBox.__eq = function(a, b)
return table.equal(a.stats, b.stats)
end
--[[
Wikicode for Pokémon stat boxes: min-max values
and a link to other Pokémon with the same base
stat total are displayed withing the standard
stats box. If there are any labels, they are
displayed in a heading, and the box is hidden
according to the collapsed status. Statistics
related categories are also printed.
--]]
PokeStatBox.__tostring = function(this)
local statsTot = statsUtil.statsSum(this.stats)
local box = s.boxStats{
stats = this.stats,
tot = statsTot,
types = this.types,
align = 'center',
gen = this.gen,
totalLink = true,
listLink = false,
multigenStats = this.multigenStats,
} .. (not this.poke and '' or
makeCategories(this.poke, statsTot))
if not PokeStatBox.super.hasLabel(this) then
return box
end
return string.interp(strings.boxFormWrapper,
{
title = mw.text.listToText(this.labels),
collapse = this.collapse or '',
box = box
})
end
--[[
This method adds a form label to the current list.
The superclass overriding is necessary to fetch
base form types, which is the rule for shared boxes.
--]]
PokeStatBox.addLabel = function(this, label)
PokeStatBox.super.addLabel(this, label)
local pokeData = multigen.getGen(pokes[this.baseFormName])
this.types = {type1 = pokeData.type1, type2 = pokeData.type2}
end
-- Sets the collapsed status
PokeStatBox.setCollapse = function(this, collapse)
this.collapse = collapse
end
--[[
Prints a statistics box. Arguments are named:
- stats: table with statistics to be printed,
in the format as PokéStats/data.
- tot: base stats total, so as to avoid
multiple computations. Completely
optional, if not passed will be
computed from the passed stats.
- types: table of type names, in a format
accepted by css module
- align: alignemnt of the table. One of
'center', 'left' or 'right'
- gen: generation, used for statistics min-max
values calculation. When a non-number,
or an invalid generation, nothing is
computed. Defaults to false.
- totalLink: if the link to other Pokémon with
the same base stat total is to be displayed.
Defaults to false.
- listLink: if the link to all Pokémon by stats
list page is to be displayed.
Defaults to false.
- multigenStats: table of stats with multigen values for the footer.
The keys are the stat names, the values the multigen tables
--]]
s.boxStats = function(args)
local stats, types = args.stats, args.types
local tot = string.printNumber(args.tot
or statsUtil.statsSum(stats))
local gen, align = args.gen, args.align
local totalLink, listLink = args.totalLink, args.listLink
local multigenStats = args.multigenStats
local computeBounds = genUtil.isValidGen(gen)
--[[
Need to get rid of non-existent stats because no
holes are allowed when concatenating later on
--]]
local statsOrder = statsUtil.statsOrder[gen or (stats.spec and 1 or 2)]
local statRows = table.filter(statsOrder, function(stat)
return stats[stat] end)
--[[
Interpolation values for basic case,
which means no min-max calculation
and no link to other Pokémon with the
same base stat total displayed.
--]]
local interpVal = {
align = align == 'left' and '' or ' pull-' .. align,
width = ' width-xl-30 width-md-50 width-sm-60 width-xs-100',
textcolor = cc.forModGradBgLua(
types['type1'] or 'pcwiki',
types['type2'] or types['type1'] or 'pcwiki'),
bg = css.horizGradLua(types),
rs = '',
values = '',
stats = w.mapAndConcat(statRows, '\n',
function(stat, index)
local roundy = false
if index == 1 then
roundy = 'top'
elseif index == table.getn(statRows) then
roundy = 'bottom'
end
return statRow(stat, stats[stat], gen, roundy)
end),
total = tot,
footer = ''
}
if computeBounds then
local maxIV, maxEV = statsUtil.ivEvMax(gen)
interpVal.width = ''
interpVal.rs = 'rowspan="2" '
interpVal.values = strings.headerValues
interpVal.footer = string.interp(strings.boundsFooter,
{
minParams = mw.text.listToText{
'0 [[Punti base|PA]]',
'[[Punti individuali|VI]] pari a 0',
gen > 2 and 'una [[natura]] sfavorevole' or nil
},
maxParams = mw.text.listToText{
maxEV .. ' PA',
'VI pari a ' .. maxIV,
gen > 2 and 'una natura favorevole' or nil
},
})
end
if totalLink then
interpVal.width = ''
interpVal.total = string.interp(strings.totalLink,
{tot = tot})
end
if listLink then
interpVal.footer = interpVal.footer .. strings.listFooter
end
if multigenStats then
multigenStats = table.map(multigenStats, function(val, key)
return makeStatFooterLines(key, val)
end)
local multigenFooter = {}
-- Handling stat speciali
table.insert(multigenFooter, multigenStats.spec)
for _, stat in ipairs(statsUtil.statsOrder[2]) do
-- Doesn't insert non multigen stats because their value is nil
table.insert(multigenFooter, multigenStats[stat])
end
interpVal.footer = interpVal.footer .. table.concat(multigenFooter)
end
if interpVal.footer ~= '' then
interpVal.footer = string.interp(strings.footer,
{content = interpVal.footer})
end
return string.interp(strings.boxStats, interpVal)
end
s.boxstats, s.box_stats = s.boxStats, s.boxStats
--[[
Returns the wikicode for a statistic bar: it
has the value inside, a gradient as a background
and its width is proportional to the value,
relatively to 255.
--]]
s.statBarLua = function(stat, value)
return string.interp(strings.statBar,
{
width = value / 270 * 100,
bg = css.horizGradLua{type = stat},
dark = c[stat].dark,
val = string.printNumber(value)
})
end
s.stat_bar_lua = s.statBarLua
--[[
Returns the wikicode for a statistic bar: it
has the value inside, a gradient as a background
and its width is proportional to the value,
relatively to 255. The first argument, or the
named stat, is the statistic name, while the second
one, or the one with key value, is its value.
Examples:
{{#invoke Stats | statBar | ps | 120 }}
{{#invoke Stats | statBar | stat = ps | value = 120 }}
--]]
s.statBar = function(frame)
local p = w.trimAll(mw.clone(frame.args))
return s.statBarLua(p.stat or p[1], p.value or p[2])
end
s.StatBar, s.statbar = s.statBar, s.statBar
--[[
Prints statistics box for a single Pokémon.
Minimin and maximum values for each statistic are
displayed, as well as a link to other Pokémon with
the same base stat total.
Statistics related categories are printed by default,
but they can be turned off by passing 'yes' as a
fourth parameter, or named 'noCat'.
Alternative forms are included by default, although
it is possible to display stats for a single form
only by passing 'yes' as a second argument, or named
'noForms'.
Statistic values are that of the latest generation
by default, unless a third argument, or named 'gen',
is passed with another number.
Examples:
All forms:
{{#invoke: Stats | PokeStats | Rotom }}
IN POKÉMON PAGES ONLY!
{{#invoke: Stats | PokeStats | {{BASEPAGENAME}} }}
Older generations and no category:
{{#invoke: Stats | PokeStats | Gengar | | 5 | yes }}
{{#invoke: Stats | PokeStats | Gengar | gen = 5 | noCat = yes }}
--]]
s.pokeStats = function(frame)
local p = w.trimAll(mw.clone(frame.args))
local poke = string.lower(mw.text.decode(p[1] or p.poke))
local noForms = (p[2] or p.noForms or 'no'):lower() == 'yes'
local gen = tonumber(p[3] or p.gen) or gendata.latest
local noCat = (p[4] or p.noCat or 'no'):lower() == 'yes'
local boxArgs = {gen = gen, noCats = noCat}
if noForms then
return tostring(PokeStatBox.new(poke, nil, boxArgs))
else
return list.makeFormsLabelledBoxes{
name = poke,
makeBox = PokeStatBox.new,
boxArgs = boxArgs,
printBoxes = function(boxes)
-- No collapse and extra markup for single boxes
if #boxes == 1 then
return tostring(boxes[1])
end
--[[
All boxes collapsible and all but the
first collapsed by default
--]]
return w.mapAndConcat(boxes, function(box, key)
box:setCollapse('mw-collapsible' ..
(key == 1 and '' or ' mw-collapsed'))
return tostring(box)
end, '\n')
end
}
end
end
s.PokeStats, s['pokéStats'], s['PokéStats'] =
s.pokeStats, s.pokeStats, s.pokeStats
--[[
Prints the average of the statistics for Pokémon
of a specific type, alternative forms included,
as a statistics box. A generation can be specified,
and the latest one will be used if not. Minimum
and maximum values for each statistic are not
displayed, and neither is the link to other Pokémon
with the same base stat total.
Examples:
{{#invoke: Stats | typeAvg | Elettro }}
IN TYPE PAGES ONLY!
{{#invoke: Stats | typeAvg | {{BASEPAGENAME}} }}
With generation:
{{#invoke Stats | typeAvg | Fuoco | 4 }}
--]]
s.typeAvg = function(frame)
local type = string.trim(frame.args[1]):lower()
local gen = tonumber(string.trim(frame.args[2]))
or gendata.latest
--[[
string.find is used instead of plain equality
because of coleot/coleottero dualism. stats[poke]
is checked first because it might be that
statistics data and Pokémon data are not updated
together consistently.
--]]
local typedPokes = table.keys(table.filter(pokes, function(data, poke)
data = multigen.getGen(data)
return stats[poke]
and not string.parseInt(poke)
and gamesUtil.isInGen(poke, gen)
and (data.type1:find(type) or data.type2:find(type))
end))
return s.boxStats{
stats = statsAvg(typedPokes, gen),
types = {type1 = type},
align = 'left',
}
end
s.TypeAvg, s.typeavg = s.typeAvg, s.typeavg
--[[
Prints out a statistics box given
everything necessary as a parameter:
- hp: HP base stat value
- atk: Attack base stat value
- def: Defense base stat value
- spatk: Special Attack base stat value
- spdef: Special Defense base stat value
- spe: Speed base stat value
= spec: Special stat value, gen 1 only
- type: Primary or only type used for
background gradient.
- type1: Primary type used for background
gradient. Defaults to 'type' parameter.
- type2: Secondary type used for background
gradient.
- bounds: yes/no flag telling whether to
work out min and max values.
Defaults to no.
- gen: generation, only meaningful for min
and max statistic calculation.
Defaults to the latest one.
- totalLink: yes/no flag telling whether to
display the link for other Pokémon
with the same base sta total.
Defaults to no.
- listLink: yes/no flag telling whether to
display the link to all Pokémon
stats list. Defaults to no.
- align: alignment of the box stat. One of
'left', 'center', ir 'right'.
Defaults to 'center'.
Examples:
{{#invoke: Stats | statsBox
|hp = 50
|atk = 220
|def = 210
|spatk = 90
|spdef = 21
|spe = 120
|type = acciaio
|totalLink = yes
|align = left
}}
{{#invoke: Stats | statsBox
|hp = 200
|atk = 40
|def = 80
|spatk = 93
|spdef = 135
|spe = 63
|type1 = elettro
|type2 = fuoco
|bounds = yes
|gen = 3
|listLink = yes
}}
--]]
s.statsBox = function(frame)
-- tonumber() is necessary for stats values
local p = w.trimAndMap(mw.clone(frame.args), true,
function(val) return tonumber(val) or val end)
local bounds = (p.bounds or 'no'):lower() == 'yes'
p.bounds = nil
p.stats = {
hp = p.hp,
atk = p.atk,
def = p.def,
spatk = p.spatk,
spdef = p.spdef,
spe = p.spe,
spec = p.spec
}
p.types = {
type = p.type,
type1 = p.type1 or p.type,
type2 = p.type2
}
p.gen = bounds and (p.gen or gendata.latest)
p.totalLink = (p.totalLink or 'no'):lower() == 'yes'
p.listLink = (p.listLink or 'no'):lower() == 'yes'
p.align = (p.align or 'center')
return s.boxStats(p)
end
s.StatsBox, s.statsbox = s.statsBox, s.statsBox
return s
| cc0-1.0 |
evrooije/beerarchy | mods/00_bt_mobs/dmobs/mobs/golem.lua | 1 | 1104 | --stone golem
mobs:register_mob("dmobs:golem", {
type = "monster",
reach = 3,
damage = 4,
attack_type = "dogfight",
hp_min = 62,
hp_max = 72,
armor = 100,
collisionbox = {-0.4, 0, -0.4, 0.4, 2.5, 0.4},
visual = "mesh",
mesh = "golem.b3d",
textures = {
{"dmobs_golem.png"},
},
blood_texture = "default_stone.png",
visual_size = {x=1, y=1},
makes_footstep_sound = true,
walk_velocity = 1,
run_velocity = 2.5,
jump = true,
drops = {
{name = "dmobs:golemstone", chance = 30, min = 1, max = 1},
},
water_damage = 0,
lava_damage = 2,
-- light_damage = 1,
fall_damage = 0,
fear_height = 10,
view_range = 14,
animation = {
speed_normal = 10,
speed_run = 14,
walk_start = 46,
walk_end = 66,
stand_start = 1,
stand_end = 20,
run_start = 46,
run_end = 66,
punch_start = 20,
punch_end = 45,
},
sounds = {
random = "mobs_golem_footstep",
war_cry = "mobs_golem_growl",
attack = "mobs_golem_growl",
damage = "mobs_golem_growl",
jump = "mobs_golem_footstep",
distance = 20,
},
})
mobs:register_egg("dmobs:golem", "Stone Golem", "default_stone.png", 1)
| lgpl-2.1 |
OpenPrograms/SuPeRMiNoR2-Programs | osmagdoor/osmag.lua | 1 | 3117 | local serialization = require("serialization")
local filesystem = require("filesystem")
m = {}
dbfile = "/authdb.dat"
logfile = "/authlog.txt"
function m.makeCode()
local l = 10
local s = ""
for i = 1, l do
s = s .. string.char(math.random(97, 122))
end
return s
end
function m.loadDB()
if filesystem.exists(dbfile) == false then
ldb = {pairs = {}, registered = {}, new = {}, groups = {}}
table.insert(ldb["groups"], {gid = 1, name = "Default Group"})
else
f = io.open(dbfile, "rb")
rdb = f:read("*a")
ldb = serialization.unserialize(rdb)
f:close()
end
return ldb
end
function m.saveDB(ldb)
if filesystem.exists("/backups") == false then
filesystem.makeDirectory("/backups")
end
filesystem.copy(dbfile, "/backups/" .. os.date() .. ".backup")
f = io.open(dbfile, "wb")
f:write(serialization.serialize(ldb))
f:close()
end
function m.updateDB()
local db = m.loadDB()
--print("[DBUpdate] Database update starting...")
--Make sure that all doors have passwords and groups set
--This allows updating from old databases that didn't have those features
for i, pair in ipairs(db["pairs"]) do
if not pair["password"] then
newpass = osmag.makeCode()
db["pairs"][i]["password"] = newpass
doorc = component.proxy(pair["door"])
doorc.setPassword(newpass)
print("[DBUpdate] Added password to door "..pair["name"])
end
if not pair["gid"] then
db["pairs"][i]["gid"] = 1
print("[DBUpdate] Added default group to door "..pair["name"])
end
end
--Remove expired cards
currenttime = os.time()
for i, card in ipairs(db["registered"]) do
if card["type"] == "temp" then
if currenttime > card["expire"] then
print("[DBUpdate] Removing expired card: "..card["title"])
table.remove(db["registered"], i)
end
end
if not card["groups"] then
db["registered"][i]["groups"] = {}
table.insert(db["registered"][i]["groups"], 1)
print("[DBUpdate] Added default group to card "..card["title"])
end
end
--Add group structure if it doesn't exist
if not db["groups"] then
print("[DBUpdate] Adding default group structure...")
db["groups"] = {}
table.insert(ldb["groups"], {gid = 1, name = "Default Group"})
end
--print("[DBUpdate] Database update complete.")
m.saveDB(db)
end
function killDoor(address, password)
local door = component.proxy(address)
door.setPassword(password, "")
end
function m.checkCardMembership(db, card, gid)
for i, d in ipairs(db["registered"][card]["groups"]) do
if d == gid then
return true
end
end
return false
end
function m.tryToDeleteDoor(address, password)
pcall(killDoor, address, password)
end
function m.log(logdata)
local f = io.open(logfile, "a")
f:write(logdata .. "\n")
f:close()
end
return m | mit |
naclander/tome | game/engines/default/engine/ui/VariableList.lua | 3 | 6717 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
local Base = require "engine.ui.Base"
local Focusable = require "engine.ui.Focusable"
local Slider = require "engine.ui.Slider"
--- A generic UI list
module(..., package.seeall, class.inherit(Base, Focusable))
function _M:init(t)
self.list = assert(t.list, "no list list")
self.w = assert(t.width, "no list width")
self.max_h = t.max_height
self.fct = t.fct
self.select = t.select
self.scrollbar = t.scrollbar
self.min_items_shown = t.min_items_shown or 3
self.display_prop = t.display_prop or "name"
Base.init(self, t)
end
function _M:generate()
self.mouse:reset()
self.key:reset()
self.sel = 1
self.scroll = 1
self.max = #self.list
local fw, fh = self.w, self.font_h
self.fw, self.fh = fw, fh
self.frame = self:makeFrame(nil, fw, fh)
self.frame_sel = self:makeFrame("ui/selector-sel", fw, fh)
self.frame_usel = self:makeFrame("ui/selector", fw, fh)
-- Draw the list items
local sh = 0
local minh = 0
for i, item in ipairs(self.list) do
local color = item.color or {255,255,255}
local text = item[self.display_prop]:splitLines(fw - self.frame_sel.b4.w - self.frame_sel.b6.w, self.font)
local fh = fh * #text + self.frame_sel.b8.w / 3 * 2
local s = core.display.newSurface(fw, fh)
s:erase(0, 0, 0, 0)
local color_r, color_g, color_b = color[1], color[2], color[3]
for z = 1, #text do
color_r, color_g, color_b = s:drawColorStringBlended(self.font, text[z], self.frame_sel.b4.w, self.frame_sel.b8.w / 3 + self.font_h * (z-1), color_r, color_g, color_b, true)
end
item.start_h = sh
item.fh = fh
item._tex = {s:glTexture()}
sh = sh + fh
if i <= self.min_items_shown then minh = sh end
end
self.h = math.max(minh, math.min(self.max_h or 1000000, sh))
if sh > self.h then self.scrollbar = true end
self.scroll_inertia = 0
self.scroll = 0
if self.scrollbar then self.scrollbar = Slider.new{size=self.h, max=sh} end
self.mouse:registerZone(0, 0, self.w, self.h, function(button, x, y, xrel, yrel, bx, by, event)
self.last_input_was_keyboard = false
if event == "button" and button == "wheelup" then if self.scrollbar then self.scroll_inertia = math.min(self.scroll_inertia, 0) - 5 end
elseif event == "button" and button == "wheeldown" then if self.scrollbar then self.scroll_inertia = math.max(self.scroll_inertia, 0) + 5 end
end
for i = 1, #self.list do
local item = self.list[i]
if by + self.scroll >= item.start_h and by + self.scroll < item.start_h + item.fh then
if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end
self.sel = i
self:onSelect()
if button == "left" and event == "button" then self:onUse() end
break
end
end
end)
-- Add UI controls
self.key:addBinds{
ACCEPT = function() self:onUse() end,
MOVE_UP = function()
if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end
self.sel = util.boundWrap(self.sel - 1, 1, self.max) self:onSelect()
end,
MOVE_DOWN = function()
if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end
self.sel = util.boundWrap(self.sel + 1, 1, self.max) self:onSelect()
end,
}
end
function _M:onUse()
local item = self.list[self.sel]
if not item then return end
self:sound("button")
if item.fct then item:fct()
else self.fct(item, self.sel) end
end
function _M:onSelect()
local item = self.list[self.sel]
if not item then return end
if self.scrollbar then
local pos = 0
for i = 1, #self.list do
local itm = self.list[i]
pos = pos + itm.fh
-- we've reached selected row
if self.sel == i then
-- check if it was visible if not go scroll over there
if pos - itm.fh < self.scrollbar.pos then self.scrollbar.pos = util.minBound(pos - itm.fh, 0, self.scrollbar.max)
elseif pos > self.scrollbar.pos + self.h then self.scrollbar.pos = util.minBound(pos - self.h, 0, self.scrollbar.max)
end
break
end
end
end
if rawget(self, "select") then self.select(item, self.sel) end
end
function _M:display(x, y, nb_keyframes, screen_x, screen_y)
local by = y
core.display.glScissor(true, screen_x, screen_y, self.w, self.h)
if self.scrollbar then
local tmp_pos = self.scrollbar.pos
self.scrollbar.pos = util.minBound(self.scrollbar.pos + self.scroll_inertia, 0, self.scrollbar.max)
if self.scroll_inertia > 0 then self.scroll_inertia = math.max(self.scroll_inertia - 1, 0)
elseif self.scroll_inertia < 0 then self.scroll_inertia = math.min(self.scroll_inertia + 1, 0)
end
if self.scrollbar.pos == 0 or self.scrollbar.pos == self.scrollbar.max then self.scroll_inertia = 0 end
y = y + (self.scrollbar and -self.scrollbar.pos or 0)
self.scroll = self.scrollbar.pos
end
for i = 1, self.max do
local item = self.list[i]
if not item then break end
self.frame.h = item.fh
self.frame_sel.h = item.fh
self.frame_usel.h = item.fh
if self.sel == i then
if self.focused then self:drawFrame(self.frame_sel, x, y)
else self:drawFrame(self.frame_usel, x, y) end
else
self:drawFrame(self.frame, x, y)
if item.focus_decay then
if self.focused then self:drawFrame(self.frame_sel, x, y, 1, 1, 1, item.focus_decay / self.focus_decay_max_d)
else self:drawFrame(self.frame_usel, x, y, 1, 1, 1, item.focus_decay / self.focus_decay_max_d) end
item.focus_decay = item.focus_decay - nb_keyframes
if item.focus_decay <= 0 then item.focus_decay = nil end
end
end
if self.text_shadow then item._tex[1]:toScreenFull(x+1 + self.frame_sel.b4.w, y+1, self.fw, item.fh, item._tex[2], item._tex[3], 0, 0, 0, self.text_shadow) end
item._tex[1]:toScreenFull(x + self.frame_sel.b4.w, y, self.fw, item.fh, item._tex[2], item._tex[3])
y = y + item.fh
end
core.display.glScissor(false)
if self.focused and self.scrollbar then
self.scrollbar:display(x + self.w - self.scrollbar.w, by)
self.last_scroll = self.scrollbar.pos
end
end
| gpl-3.0 |
gwlim/luci | modules/admin-full/luasrc/controller/admin/index.lua | 79 | 1245 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.admin.index", package.seeall)
function index()
local root = node()
if not root.target then
root.target = alias("admin")
root.index = true
end
local page = node("admin")
page.target = firstchild()
page.title = _("Administration")
page.order = 10
page.sysauth = "root"
page.sysauth_authenticator = "htmlauth"
page.ucidata = true
page.index = true
-- Empty services menu to be populated by addons
entry({"admin", "services"}, firstchild(), _("Services"), 40).index = true
entry({"admin", "logout"}, call("action_logout"), _("Logout"), 90)
end
function action_logout()
local dsp = require "luci.dispatcher"
local sauth = require "luci.sauth"
if dsp.context.authsession then
sauth.kill(dsp.context.authsession)
dsp.context.urltoken.stok = nil
end
luci.http.header("Set-Cookie", "sysauth=; path=" .. dsp.build_url())
luci.http.redirect(luci.dispatcher.build_url())
end
| apache-2.0 |
greasydeal/darkstar | scripts/globals/spells/knights_minne_v.lua | 13 | 1519 | -----------------------------------------
-- Spell: Knight's Minne V
-- Grants Defense bonus to all allies.
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 50 + math.floor((sLvl + iLvl)/10);
if(power >= 120) then
power = 120;
end
local iBoost = caster:getMod(MOD_MINNE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
if (iBoost > 0) then
power = power + 1 + (iBoost-1)*4;
end
power = power + caster:getMerit(MERIT_MINNE_EFFECT);
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_MINNE,power,0,duration,caster:getID(), 0, 5)) then
spell:setMsg(75);
end
return EFFECT_MINNE;
end; | gpl-3.0 |
greasydeal/darkstar | scripts/globals/items/bowl_of_sunset_soup.lua | 35 | 1498 | -----------------------------------------
-- ID: 4341
-- Item: bowl_of_sunset_soup
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- Agility 3
-- Vitality -1
-- HP Recovered While Healing 5
-- Ranged Accuracy % 9 (cap 20)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4341);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 3);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_HPHEAL, 5);
target:addMod(MOD_FOOD_RACCP, 9);
target:addMod(MOD_FOOD_RACC_CAP, 20);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 3);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_HPHEAL, 5);
target:delMod(MOD_FOOD_RACCP, 9);
target:delMod(MOD_FOOD_RACC_CAP, 20);
end;
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Al_Zahbi/npcs/Devonte.lua | 14 | 1034 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Devonte
-- Type: Standard NPC
-- @zone 48
-- @pos 29.449 -1 142.671
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00f9);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
ibm2431/darkstar | scripts/globals/weaponskills/death_blossom.lua | 10 | 2640 | -----------------------------------
-- Death Blossom
-- Sword weapon skill (RDM main only)
-- Description: Delivers a threefold attack that lowers target's magic evasion. Chance of lowering target's magic evasion varies with TP. Murgleis: Aftermath effect varies with TP.
-- Lowers magic evasion by up to 10.
-- Effect lasts up to 55 seconds.
-- Available only after completing the Unlocking a Myth (Red Mage) quest.
-- Aligned with the Breeze Gorget, Thunder Gorget, Aqua Gorget & Snow Gorget.
-- Aligned with the Breeze Belt, Thunder Belt, Aqua Belt & Snow Belt.
-- Modifiers: STR:30% MND:50%
-- 100%TP 200%TP 300%TP
-- 4 4 4 new
-- 1.125 1.125 1.125 old
-----------------------------------
require("scripts/globals/aftermath")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 3
-- ftp damage mods (for Damage Varies with TP lines are calculated in the function
params.ftp100 = 1.125 params.ftp200 = 1.125 params.ftp300 = 1.125
-- wscs are in % so 0.2=20%
params.str_wsc = 0.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0
params.mnd_wsc = 0.5 params.chr_wsc = 0.0
-- critical mods, again in % (ONLY USE FOR critICAL HIT VARIES WITH TP)
params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0
params.canCrit = false
-- accuracy mods (ONLY USE FOR accURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp.
params.acc100 = 0.0 params.acc200 = 0.0 params.acc300 = 0.0
-- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1;
if USE_ADOULIN_WEAPON_SKILL_CHANGES then
params.ftp100 = 4.0 params.ftp200 = 4.0 params.ftp300 = 4.0
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
if damage > 0 then
local duration = tp / 1000 * 20 - 5
if not target:hasStatusEffect(dsp.effect.MAGIC_EVASION_DOWN) then
target:addStatusEffect(dsp.effect.MAGIC_EVASION_DOWN, 10, 0, duration)
end
-- Apply aftermath
dsp.aftermath.addStatusEffect(player, tp, dsp.slot.MAIN, dsp.aftermath.type.MYTHIC)
end
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
ibm2431/darkstar | scripts/zones/Tahrongi_Canyon/npcs/Shattered_Telepoint.lua | 9 | 1913 | -----------------------------------
-- Area: Tahrongi_Canyon
-- NPC: Shattered Telepoint
-- !pos 179 35 255 117
-----------------------------------
local ID = require("scripts/zones/Tahrongi_Canyon/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
if player:getCurrentMission(COP) == dsp.mission.id.cop.BELOW_THE_ARKS and player:getCharVar("PromathiaStatus") == 1 then
player:startEvent(913, 0, 0, 1) -- first time in promy -> have you made your preparations cs
elseif player:getCurrentMission(COP) == dsp.mission.id.cop.THE_MOTHERCRYSTALS and (player:hasKeyItem(dsp.ki.LIGHT_OF_HOLLA) or player:hasKeyItem(dsp.ki.LIGHT_OF_DEM)) then
if player:getCharVar("cspromy2") == 1 then
player:startEvent(912) -- cs you get nearing second promyvion
else
player:startEvent(913)
end
elseif player:getCurrentMission(COP) > dsp.mission.id.cop.THE_MOTHERCRYSTALS or player:hasCompletedMission(COP, dsp.mission.id.cop.THE_LAST_VERSE) or (player:getCurrentMission(COP) == dsp.mission.id.cop.BELOW_THE_ARKS and player:getCharVar("PromathiaStatus") > 1) then
player:startEvent(913) -- normal cs (third promyvion and each entrance after having that promyvion visited or mission completed)
else
player:messageSpecial(ID.text.TELEPOINT_HAS_BEEN_SHATTERED)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 912 then
player:setCharVar("cspromy2", 0)
player:setCharVar("cs2ndpromy", 1)
player:setPos(280.066, -80.635, -67.096, 191, 14) -- To Hall of Transference {R}
elseif csid == 913 and option == 0 then
player:setPos(280.066, -80.635, -67.096, 191, 14) -- To Hall of Transference {R}
end
end | gpl-3.0 |
Startg/security | plugins/report.lua | 4 | 1671 | -- Begin report.lua
local function run(msg, matches)
local ldata = load_data(_config.moderation.data)
if matches[1]:lower() == 'setmaster' and is_admin(msg) then
local idmas = matches[2]
local chk = ldata[tostring(msg.chat_id_)]["master"]
if chk then
ldata[tostring(msg.chat_id_)]["master"]["id"] = idmas
save_data(_config.moderation.data, ldata)
return '_ایدی مستر جایگزین شد_'
else
ldata[tostring(msg.chat_id_)]["master"] = {id = idmas}
save_data(_config.moderation.data, ldata)
return '_ایدی مستر ذخیره شد_'
end
end
if matches[1]:lower() == 'report' and msg.reply_to_message_id_ then
local user_name = ''
local chat = msg.chat_id_
local master = ldata[tostring(chat)]["master"]
if master then
master = ldata[tostring(chat)]["master"]["id"]
function id_cb(arg, data)
if data.username_ then
user_name = '@'..data.username_
else
user_name = data.first_name_
end
tdcli.sendMessage(msg.chat_id_, 0, 1, '_گزارش شما به مدیر گروه ارسال شد._', 1, 'md')
tdcli.sendMessage(master, 0, 1, '[ <code>'..msg.sender_user_id_..'</code> ] '..user_name..' <b>send to you a report:</b>', 1, 'html')
tdcli.forwardMessages(master, msg.chat_id_,{[0] = msg.reply_to_message_id_}, 0,dl_cb,nil)
end
else
return '_ایدی مستر تعیین نشده است!_'
end
tdcli_function ({ ID = "GetUser", user_id_ = msg.sender_user_id_ }, id_cb, {chat_id=msg.chat_id_,user_id=msg.sender_user_id_})
end
end
return { patterns = { '^[/!#]([Rr]eport)$', '^[/!#]([Ss]etmaster) (%d+)$' }, run = run }
-- END
-- CHANNEL: @luaError & @BeyondTeam
| gpl-3.0 |
gchanan/TemporalConvolutionTBC | init.lua | 1 | 1814 | require 'torch'
require 'nn'
local tbc = tbc or {}
tbc.C = require('tbc.ffi') -- keep the loaded C object around, so that it doesn't get garbage collected
function tbc.bind(lib, base_names, type_name, state_getter)
local ftable = {}
local prefix = 'TemporalConvolutionTBC_'
for i,n in ipairs(base_names) do
local ok,v = pcall(function() return lib[prefix .. n .. '_' .. type_name] end)
if ok then
if state_getter then
ftable[n] = function(...) v(state_getter, ...) end
else
ftable[n] = function(...) v(...) end
end
else
print('not found: ' .. prefix .. n .. '_' .. type_name)
end
end
return ftable
end
local function_names = {"updateOutput", "updateGradInput", "accGradParameters"}
tbc.kernels = {}
tbc.kernels['torch.FloatTensor'] = tbc.bind(tbc.C, function_names, 'Float')
tbc.kernels['torch.DoubleTensor'] = tbc.bind(tbc.C, function_names, 'Double')
torch.getmetatable('torch.FloatTensor').TBC = tbc.kernels['torch.FloatTensor']
torch.getmetatable('torch.DoubleTensor').TBC = tbc.kernels['torch.DoubleTensor']
if tbc.C.torchtbc_has_cuda() == 1 then
tbc.kernels['torch.CudaTensor'] = tbc.bind(tbc.C, function_names, 'Cuda', cutorch.getState())
tbc.kernels['torch.CudaDoubleTensor'] = tbc.bind(tbc.C, function_names, 'CudaDouble', cutorch.getState())
torch.getmetatable('torch.CudaTensor').TBC = tbc.kernels['torch.CudaTensor']
torch.getmetatable('torch.CudaDoubleTensor').TBC = tbc.kernels['torch.CudaDoubleTensor']
if cutorch.hasHalf then
tbc.kernels['torch.CudaHalfTensor'] = tbc.bind(tbc.C, function_names, 'CudaHalf', cutorch.getState())
torch.getmetatable('torch.CudaHalfTensor').TBC = tbc.kernels['torch.CudaHalfTensor']
end
end
require('tbc.TemporalConvolutionTBC')
return tbc
| bsd-3-clause |
greasydeal/darkstar | scripts/globals/summon.lua | 17 | 9662 |
require("scripts/globals/common");
require("scripts/globals/status");
SUMMONING_MAGIC_SKILL = 38
MSG_NONE = 0; -- display nothing
MSG_NO_EFFECT = 189;
MSG_DAMAGE = 185; -- player uses, target takes 10 damage. DEFAULT
MSG_MISS = 188;
MSG_RESIST = 85;
function AvatarPhysicalMove(avatar,target,skill,numberofhits,accmod,dmgmod1,dmgmodsubsequent,tpeffect,mtp100,mtp200,mtp300)
returninfo = {};
--Damage = (D+fSTR) * dmgmod * PDIF
-- printf("str: %f, vit: %f", avatar:getStat(MOD_STR), target:getStat(MOD_VIT));
fstr = avatarFSTR(avatar:getStat(MOD_STR), target:getStat(MOD_VIT));
lvluser = avatar:getMainLvl();
lvltarget = target:getMainLvl();
acc = avatar:getACC();
eva = target:getEVA();
local base = avatar:getWeaponDmg() + fstr;
local ratio = avatar:getStat(MOD_ATT)/target:getStat(MOD_DEF);
lvldiff = lvluser - lvltarget;
--work out hit rate for mobs (bias towards them)
hitrate = (acc*accmod) - eva;
if (lvluser > lvltarget) then
hitrate = hitrate + ((lvluser-lvltarget)*5);
end
if (lvltarget > lvluser) then
hitrate = hitrate + ((lvltarget-lvluser)*3);
end
if (hitrate > 95) then
hitrate = 95;
end
if (hitrate < 20) then
hitrate = 20;
end
if(base < 1) then
base = 1;
end
hitdamage = base * dmgmod1;
subsequenthitdamage = base * dmgmodsubsequent;
if(ratio<=1) then
maxRatio = 1;
minRatio = 1/3;
elseif(ratio<1.6) then
maxRatio = ((4/6) * ratio) + (2/6);
minRatio = ((7/9) * ratio) - (4/9);
elseif(ratio<=1.8) then
maxRatio = 1.8;
minRatio = 1;
elseif(ratio<3.6) then
maxRatio = (2.4 * ratio) - 2.52;
minRatio = ((5/3) * ratio) - 2;
else
maxRatio = 4.2;
minRatio = 4;
end
if(tpeffect==TP_DMG_BONUS) then
hitdamage = hitdamage * avatarFTP(skill:getTP(), mtp100, mtp200, mtp300);
end
--Applying pDIF
local pdif = 0;
-- start the hits
local hitchance = math.random();
finaldmg = 0;
hitsdone = 1; hitslanded = 0;
--add on native crit hit rate (guesstimated, it actually follows an exponential curve)
nativecrit = (avatar:getStat(MOD_DEX) - target:getStat(MOD_AGI))*0.005; --assumes +0.5% crit rate per 1 dDEX
nativecrit = nativecrit + (avatar:getMod(MOD_CRITHITRATE)/100);
if(nativecrit > 0.2) then --caps!
nativecrit = 0.2;
elseif(nativecrit < 0.05) then
nativecrit = 0.05;
end
local critchance = math.random();
local hitchance = 0;
local crit = false;
if critchance <= nativecrit then
crit = true;
else
hitchance = math.random();
end
if crit == true or hitchance*100 <= 95 then
pdif = math.random((minRatio * 1000), (maxRatio * 1000));
pdif = pdif/1000;
if crit == true then
pdif = pdif + 1;
if pdif > 4.2 then
pdif = 4.2
end
end
finaldmg = finaldmg + hitdamage * pdif;
hitslanded = hitslanded + 1;
end
while (hitsdone < numberofhits) do
chance = math.random();
if ((chance*100)<=hitrate) then
pdif = math.random((minRatio * 1000), (maxRatio * 1000));
pdif = pdif/1000;
finaldmg = finaldmg + subsequenthitdamage * pdif;
hitslanded = hitslanded + 1;
end
hitsdone = hitsdone + 1;
end
-- all hits missed
if(hitslanded == 0 or finaldmg == 0) then
finaldmg = 0;
hitslanded = 0;
skill:setMsg(MSG_MISS);
end
returninfo.dmg = finaldmg;
returninfo.hitslanded = hitslanded;
return returninfo;
end;
--Given the attacker's str and the mob's vit, fSTR is calculated
function avatarFSTR(atk_str,def_vit)
local dSTR = atk_str - def_vit;
if (dSTR >= 12) then
fSTR2 = ((dSTR+4)/2);
elseif (dSTR >= 6) then
fSTR2 = ((dSTR+6)/2);
elseif (dSTR >= 1) then
fSTR2 = ((dSTR+7)/2);
elseif (dSTR >= -2) then
fSTR2 = ((dSTR+8)/2);
elseif (dSTR >= -7) then
fSTR2 = ((dSTR+9)/2);
elseif (dSTR >= -15) then
fSTR2 = ((dSTR+10)/2);
elseif (dSTR >= -21) then
fSTR2 = ((dSTR+12)/2);
else
fSTR2 = ((dSTR+13)/2);
end
--Apply fSTR caps.
if (fSTR2< -1) then
fSTR2 = -1;
elseif (fSTR2>8) then
fSTR2 = 8;
end
return fSTR2;
end;
function AvatarFinalAdjustments(dmg,mob,skill,target,skilltype,skillparam,shadowbehav)
-- physical attack missed, skip rest
if(skilltype == MOBSKILL_PHYSICAL and dmg == 0) then
return 0;
end
-- set message to damage
-- this is for AoE because its only set once
skill:setMsg(MSG_DAMAGE);
--Handle shadows depending on shadow behaviour / skilltype
if(shadowbehav < 5 and shadowbehav ~= MOBPARAM_IGNORE_SHADOWS) then --remove 'shadowbehav' shadows.
targShadows = target:getMod(MOD_UTSUSEMI);
shadowType = MOD_UTSUSEMI;
if(targShadows==0)then --try blink, as utsusemi always overwrites blink this is okay
targShadows = target:getMod(MOD_BLINK);
shadowType = MOD_BLINK;
end
if(targShadows>0)then
--Blink has a VERY high chance of blocking tp moves, so im assuming its 100% because its easier!
if(targShadows >= shadowbehav) then --no damage, just suck the shadows
skill:setMsg(31);
target:setMod(shadowType,(targShadows-shadowbehav));
if(shadowType == MOD_UTSUSEMI) then --update icon
effect = target:getStatusEffect(EFFECT_COPY_IMAGE);
if(effect ~= nil) then
if((targShadows-shadowbehav) == 0) then
target:delStatusEffect(EFFECT_COPY_IMAGE);
target:delStatusEffect(EFFECT_BLINK);
elseif((targShadows-shadowbehav) == 1) then
effect:setIcon(EFFECT_COPY_IMAGE);
elseif((targShadows-shadowbehav) == 2) then
effect:setIcon(EFFECT_COPY_IMAGE_2);
elseif((targShadows-shadowbehav) == 3) then
effect:setIcon(EFFECT_COPY_IMAGE_3);
end
end
end
return shadowbehav;
else --less shadows than this move will take, remove all and factor damage down
dmg = dmg * ((shadowbehav-targShadows)/shadowbehav);
target:setMod(MOD_UTSUSEMI,0);
target:setMod(MOD_BLINK,0);
target:delStatusEffect(EFFECT_COPY_IMAGE);
target:delStatusEffect(EFFECT_BLINK);
end
end
elseif(shadowbehav == MOBPARAM_WIPE_SHADOWS) then --take em all!
target:setMod(MOD_UTSUSEMI,0);
target:setMod(MOD_BLINK,0);
target:delStatusEffect(EFFECT_COPY_IMAGE);
target:delStatusEffect(EFFECT_BLINK);
end
--handle Third Eye using shadowbehav as a guide
teye = target:getStatusEffect(EFFECT_THIRD_EYE);
if(teye ~= nil and skilltype==MOBSKILL_PHYSICAL) then --T.Eye only procs when active with PHYSICAL stuff
if(shadowbehav == MOBPARAM_WIPE_SHADOWS) then --e.g. aoe moves
target:delStatusEffect(EFFECT_THIRD_EYE);
elseif(shadowbehav ~= MOBPARAM_IGNORE_SHADOWS) then --it can be absorbed by shadows
--third eye doesnt care how many shadows, so attempt to anticipate, but reduce
--chance of anticipate based on previous successful anticipates.
prevAnt = teye:getPower();
if(prevAnt == 0) then
--100% proc
teye:setPower(1);
skill:setMsg(30);
return 0;
end
if( (math.random()*100) < (80-(prevAnt*10)) ) then
--anticipated!
teye:setPower(prevAnt+1);
skill:setMsg(30);
return 0;
end
target:delStatusEffect(EFFECT_THIRD_EYE);
end
end
--TODO: Handle anything else (e.g. if you have Magic Shield and its a Magic skill, then do 0 damage.
if(skilltype == MOBSKILL_PHYSICAL and target:hasStatusEffect(EFFECT_PHYSICAL_SHIELD)) then
return 0;
end
if(skilltype == MOBSKILL_RANGED and target:hasStatusEffect(EFFECT_ARROW_SHIELD)) then
return 0;
end
-- handle elemental resistence
if(skilltype == MOBSKILL_MAGICAL and target:hasStatusEffect(EFFECT_MAGIC_SHIELD)) then
return 0;
end
--handling phalanx
dmg = dmg - target:getMod(MOD_PHALANX);
if(dmg<0) then
return 0;
end
--handle invincible
if(target:hasStatusEffect(EFFECT_INVINCIBLE) and skilltype==MOBSKILL_PHYSICAL)then
return 0;
end
--handle pd
if((target:hasStatusEffect(EFFECT_PERFECT_DODGE) or target:hasStatusEffect(EFFECT_ALL_MISS) )
and skilltype==MOBSKILL_PHYSICAL) then
return 0;
end
--handling stoneskin
skin = target:getMod(MOD_STONESKIN);
if(skin>0) then
if(skin >= dmg) then --absorb all damage
target:delMod(MOD_STONESKIN,dmg);
if(target:getMod(MOD_STONESKIN)==0) then
target:delStatusEffect(EFFECT_STONESKIN);
end
return 0;
else --absorbs some damage then wear
target:delMod(MOD_STONESKIN,skin);
target:delStatusEffect(EFFECT_STONESKIN);
return dmg - skin;
end
end
return dmg;
end;
-- returns true if mob attack hit
-- used to stop tp move status effects
function AvatarPhysicalHit(skill, dmg)
-- if message is not the default. Then there was a miss, shadow taken etc
return skill:getMsg() == MSG_DAMAGE;
end;
function avatarFTP(tp,ftp1,ftp2,ftp3)
if(tp<100) then
tp=100;
end
if(tp>=100 and tp<200) then
return ftp1 + ( ((ftp2-ftp1)/100) * (tp-100));
elseif(tp>=200 and tp<=300) then
--generate a straight line between ftp2 and ftp3 and find point @ tp
return ftp2 + ( ((ftp3-ftp2)/100) * (tp-200));
end
return 1; --no ftp mod
end;
--------
-- Checks if the summoner is in a Trial Size Avatar Mini Fight (used to restrict summoning while in bcnm)
--------
function avatarMiniFightCheck(caster)
local result = 0;
local bcnmid;
if (caster:hasStatusEffect(EFFECT_BATTLEFIELD) == true) then
bcnmid = caster:getStatusEffect(EFFECT_BATTLEFIELD):getPower();
if(bcnmid == 418 or bcnmid == 609 or bcnmid == 450 or bcnmid == 482 or bcnmid == 545 or bcnmid == 578) then -- Mini Avatar Fights
result = 40; -- Cannot use <spell> in this area.
end
end
return result;
end; | gpl-3.0 |
ibm2431/darkstar | scripts/globals/items/saltena.lua | 11 | 1034 | -----------------------------------------
-- ID: 5885
-- Item: saltena
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP +6% (cap 100)
-- Increases rate of combat skill gains by 20%
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,5885)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.FOOD_HPP, 6)
target:addMod(dsp.mod.FOOD_HP_CAP, 100)
target:addMod(dsp.mod.COMBAT_SKILLUP_RATE, 20)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_HPP, 6)
target:delMod(dsp.mod.FOOD_HP_CAP, 100)
target:delMod(dsp.mod.COMBAT_SKILLUP_RATE, 20)
end
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/Upper_Jeuno/TextIDs.lua | 4 | 1699 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6542; -- Obtained: <item>.
GIL_OBTAINED = 6543; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6545; -- Obtained key item: <keyitem>.
KEYITEM_LOST = 6546; -- Lost key item:
NOT_HAVE_ENOUGH_GIL = 6547; -- You do not have enough gil.
HOMEPOINT_SET = 6665; -- Home point set!
NOTHING_OUT_OF_ORDINARY = 6556; -- There is nothing out of the ordinary here.
-- Other Texts
ITEM_DELIVERY_DIALOG = 8049; -- Delivering goods to residences everywhere!
-- Conquest system
CONQUEST = 7716; -- You've earned conquest points!
-- NPC Texts
KIRISOMANRISO_DIALOG = 8049; -- Delivering goods to residences everywhere!
YOU_CAN_NOW_BECOME_A_BEASTMASTER = 7160; -- You can now become a beastmaster.
UNLOCK_DANCER = 11803; -- You can now become a dancer!
GUIDE_STONE = 6955; -- Up: Ru'Lude Gardens Down: Lower Jeuno
-- Shop Texts
GLYKE_SHOP_DIALOG = 6950; -- Can I help you?
MEJUONE_SHOP_DIALOG = 6951; -- Welcome to the Chocobo Shop.
COUMUNA_SHOP_DIALOG = 6952; -- Welcome to Viette's Finest Weapons.
ANTONIA_SHOP_DIALOG = 6952; -- Welcome to Viette's Finest Weapons.
DEADLYMINNOW_SHOP_DIALOG = 6953; -- Welcome to Durable Shields.
KHECHALAHKO_SHOP_DIALOG = 6953; -- Welcome to Durable Shields.
AREEBAH_SHOP_DIALOG = 6954; -- Welcome to M & P's Market.
CHAMPALPIEU_SHOP_DIALOG = 6954; -- Welcome to M & P's Market.
LEILLAINE_SHOP_DIALOG = 6980; -- Hello. Are you feeling all right?
-- conquest Base
CONQUEST_BASE = 0;
| gpl-3.0 |
LegionXI/darkstar | scripts/globals/abilities/pets/flaming_crush.lua | 29 | 1356 | ---------------------------------------------------
-- Flaming Crush M=10, 2, 2? (STILL don't know)
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/summon");
require("scripts/globals/magic");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill)
local numhits = 3;
local accmod = 1;
local dmgmod = 10;
local dmgmodsubsequent = 1;
local totaldamage = 0;
local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,dmgmodsubsequent,TP_NO_EFFECT,1,2,3);
--get resist multiplier (1x if no resist)
local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, ELE_FIRE);
--get the resisted damage
damage.dmg = damage.dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
damage.dmg = mobAddBonuses(pet,spell,target,damage.dmg,1);
totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,numhits);
target:delHP(totaldamage);
target:updateEnmityFromDamage(pet,totaldamage);
return totaldamage;
end | gpl-3.0 |
greasydeal/darkstar | scripts/globals/mobskills/PW_Fulmination.lua | 18 | 1127 | ---------------------------------------------
-- Fulmination
--
-- Description: Deals heavy magical damage in an area of effect. Additional effect: Paralysis + Stun
-- Type: Magical
-- Wipes Shadows
-- Range: 30 yalms
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
local mobSkin = mob:getModelId();
if (mobSkin == 1805) then
return 0;
else
return 1;
end
end;
function onMobWeaponSkill(target, mob, skill)
local dmgmod = 3;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg() * 4,ELE_LIGHTNING,dmgmod,TP_MAB_BONUS,1);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_THUNDER,MOBPARAM_WIPE_SHADOWS);
MobStatusEffectMove(mob,target,EFFECT_PARALYSIS, 40, 0, 60);
MobStatusEffectMove(mob,target,EFFECT_STUN, 1, 0, 4);
-- TODO: Hits all players near Khimaira, not just alliance.
target:delHP(dmg);
return dmg;
end; | gpl-3.0 |
greasydeal/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/MieuseloirBEnchelles1.lua | 36 | 1055 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Miuseloir B Enchelles
-- @zone 80
-- @pos 120 0 104
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
------------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x09A);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Codex-NG/otxserver | 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 |
ricker75/Global-Server | data/npc/scripts/Marvin.lua | 1 | 1862 | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
function creatureSayCallback(cid, type, msg)
if(not(npcHandler:isFocused(cid))) then
return false
end
if(msgcontains(msg, "funding")) then
if(getPlayerStorageValue(cid, 10050) == 7) then
selfSay("So far you earned x votes. Each single vote can be spent on a different topic or you're also able to cast all your votes on one voting. ...", cid)
selfSay("Well in the topic b you have the possibility to vote for the funding of the {archives}, import of bug {milk} or street {repairs}.", cid)
npcHandler.topic[cid] = 1
end
elseif(msgcontains(msg, "archives")) then
if(npcHandler.topic[cid] == 1) then
npcHandler:say("How many of your x votes do you want to cast?", cid)
npcHandler.topic[cid] = 2
end
elseif(msgcontains(msg, "1")) then
if(npcHandler.topic[cid] == 2) then
npcHandler:say("Did I get that right: You want to cast 1 of your votes on funding the {archives?}", cid)
npcHandler.topic[cid] = 3
end
elseif(msgcontains(msg, "yes")) then
if(npcHandler.topic[cid] == 3) then
setPlayerStorageValue(cid, 10050, 8)
setPlayerStorageValue(cid, 20057, 1)
setPlayerStorageValue(cid, 20058, 0)
npcHandler:say("Thanks, you successfully cast your vote. Feel free to continue gathering votes by helping the city! Farewell.", cid)
npcHandler.topic[cid] = 0
end
end
return true
end
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
| gpl-2.0 |
greasydeal/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Miah_Riyuh.lua | 50 | 5024 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Miah Riyuh
-- @pos 5.323 -2 37.462 94
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/Windurst_Waters_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Allegiance = player:getCampaignAllegiance();
-- 0 = none, 1 = San d'Oria Iron Rams, 2 = Bastok Fighting Fourth, 3 = Windurst Cobras
local TheFightingFourth = player:getQuestStatus(CRYSTAL_WAR,THE_FIGHTING_FOURTH);
local SnakeOnThePlains = player:getQuestStatus(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS);
local SteamedRams = player:getQuestStatus(CRYSTAL_WAR,STEAMED_RAMS);
local GreenLetter = player:hasKeyItem(GREEN_RECOMMENDATION_LETTER);
if (SteamedRams == QUEST_ACCEPTED or TheFightingFourth == QUEST_ACCEPTED) then
player:startEvent(122);
elseif (SnakeOnThePlains == QUEST_AVAILABLE and GreenLetter == true) then
player:startEvent(103);
elseif (SnakeOnThePlains == QUEST_AVAILABLE and player:getVar("GREEN_R_LETTER_USED") == 1) then
player:startEvent(105);
elseif (SnakeOnThePlains == QUEST_ACCEPTED and player:isMaskFull(player:getVar("SEALED_DOORS"),3) == true) then
player:startEvent(106);
elseif (SnakeOnThePlains == QUEST_ACCEPTED and player:hasKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY)) then
local PuttyUsed = 0;
if (player:getMaskBit(player:getVar("SEALED_DOORS"),0)) then
PuttyUsed = PuttyUsed +1;
end
if (player:getMaskBit(player:getVar("SEALED_DOORS"),1)) then
PuttyUsed = PuttyUsed +1;
end
if (player:getMaskBit(player:getVar("SEALED_DOORS"),2)) then
PuttyUsed = PuttyUsed +1;
end
player:startEvent(104, 0, 0, 0, 0, 0, 0, 0, PuttyUsed);
elseif (SnakeOnThePlains == QUEST_COMPLETED and Allegiance == 3) then
player:startEvent(107);
else
player:startEvent(121);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 103 and option == 0) then
player:addQuest(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS);
player:addKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY);
player:setVar("GREEN_R_LETTER_USED",1);
player:delKeyItem(GREEN_RECOMMENDATION_LETTER);
player:messageSpecial(KEYITEM_OBTAINED, ZONPAZIPPAS_ALLPURPOSE_PUTTY);
elseif (csid == 103 and option == 1) then
player:setVar("GREEN_R_LETTER_USED",1);
player:delKeyItem(GREEN_RECOMMENDATION_LETTER);
elseif (csid == 104 and option == 1) then
player:delQuest(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS);
player:delKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY);
player:setVar("SEALED_DOORS", 0);
elseif (csid == 105 and option == 0) then
player:addQuest(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS);
player:addKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY);
player:setVar("GREEN_R_LETTER_USED",1);
player:delKeyItem(GREEN_RECOMMENDATION_LETTER);
player:messageSpecial(KEYITEM_OBTAINED, ZONPAZIPPAS_ALLPURPOSE_PUTTY);
elseif (csid == 106 and option == 0) then
-- Is first join, so add Sprinter's Shoes and bronze medal
if (player:getVar("Campaign_Nation") == 0) then
if (player:getFreeSlotsCount() >= 1) then
player:setCampaignAllegiance(3);
player:setVar("GREEN_R_LETTER_USED",0);
player:addTitle(COBRA_UNIT_MERCENARY);
player:addKeyItem(BRONZE_RIBBON_OF_SERVICE);
player:addItem(15754);
player:completeQuest(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS);
player:setVar("SEALED_DOORS", 0);
player:messageSpecial(KEYITEM_OBTAINED, BRONZE_RIBBON_OF_SERVICE);
player:messageSpecial(ITEM_OBTAINED, 15754);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 15754);
end
else
player:setCampaignAllegiance(3);
player:setVar("GREEN_R_LETTER_USED",0);
player:addTitle(COBRA_UNIT_MERCENARY);
player:completeQuest(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS);
player:setVar("SEALED_DOORS", 0);
end
end
end; | gpl-3.0 |
Quozlet/DST-Etho | scripts/prefabs/etho.lua | 1 | 16751 | --[[TODO
Balancing
Putting minions in "wait" mode
TNT
]]--
local MakePlayerCharacter = require "prefabs/player_common"
local _MADBOMBERCHANCE = 0.01
local _SLIPCHANCE = 0.8
local _TELEPORTCHANCE = 0.8
local _NODARKCHANCE = 0.5
local _NOFREEZECHANCE = 0.9
local _NOFIRECHANCE = 0.9
local _INVISICHANCE = 0.2
local _SHIELDCHANCE = 0.7
local _SLEEPCHANCE = 0.5
local _INSANECHANCE = 0.2
local _WEAKENCHANCE = 0.8
local _STRENGTHENCHANCE = 0.8
local _SLOWCHANCE = 0.6
local _SPEEDCHANCE = 0.6
local _COOLCHANCE = 0.9
local _HEATCHANCE = 0.9
local _POISONCHANCE = 0.5
local _REGENCHANCE = 0.5
local _DAMAGECHANCE = 0.6
local _HEALCHANCE = 0.6
local _EPOWDERCHANCE = 0.6
local _MADBOMBERDURATION = 10
local _NODARKDURATION = 10
local _NOFREEZEDURATION = 10
local _NOFIREDURATION = 10
local _INVISIDURATION = 10
local _SHIELDDURATION = 10
local _SLEEPDURATION = 10
local _INSANEDURATION = 10
local _WEAKENDURATION = 10
local _STRENGTHENDURATION = 10
local _SLOWDURATION = 10
local _SPEEDDURATION = 10
local _POISONDURATION = 10
local _REGENDURATION = 10
local assets = {
Asset("SCRIPT", "scripts/prefabs/player_common.lua"),
}
local prefabs = {}
-- Custom starting items
local start_inv = {
}
local followers = {
"etho_knight",
"etho_rook",
"etho_robot"
}
-- When the character is revived from human
local function onbecamehuman(inst)
-- Set speed when reviving from ghost (optional)
inst.components.locomotor:SetExternalSpeedMultiplier(inst, "etho_speed_mod", 1)
end
local function stopfreeze(inst,bool) --assertion for RemoveEventCallback wasn't working ¯\_(ツ)_/¯
if bool then
inst.components.freezable:Thaw(0)
end
end
local function makehidden(inst, bool)
if bool then
inst.sg:AddStateTag("invisible")
inst:AddTag("notarget")
end
end
local function stopcharlie(inst, bool)
if bool then
if inst and inst.components.grue then
inst.components.grue.nextHitTime = 300
inst.components.grue.nextSoundTime = 300
end
end
end
local function onbecameghost(inst)
-- Remove speed modifier when becoming a ghost
inst.components.locomotor:RemoveExternalSpeedMultiplier(inst, "etho_speed_mod")
end
-- When loading or spawning the character
local function onload(inst, data)
inst:ListenForEvent("ms_respawnedfromghost", onbecamehuman)
inst:ListenForEvent("ms_becameghost", onbecameghost)
if inst:HasTag("playerghost") then
onbecameghost(inst)
else
onbecamehuman(inst)
end
if data then
print("Summons:")
print(data.summons)
if data.summons ~= nil then
inst.summons = {}
for i=1, #data.summons do
local creature = SpawnSaveRecord(data.summons[i])
inst.summons[i] = creature
creature.persists = false
creature._playerlink = inst
inst.components.leader:AddFollower(creature, true)
end
end
end
end
local function onsave(inst, data)
data.summons = {}
for i=1, #inst.summons do
print(inst.summons[i])
if inst.summons[i].components.health and inst.summons[i].components.health:IsDead() == false then
data.summons[i] = inst.summons[i]:GetSaveRecord()
end
end
end
local function oncraft(inst, data)
local item = data.item
print("checking prefab")
for i=1, #followers do
if(item.prefab == followers[i]) then
print("prefab craft check success")
item.components.follower:SetLeader(inst)
table.insert(inst.summons, item)
end
end
end
local goop_fx =
{
[1] = function() --heal
if math.random() <= _HEALCHANCE then
ThePlayer.components.health:DoDelta(50*math.random())
ThePlayer.components.talker:Say("Much better!")
return true
end
return false
end,
[2] = function() --damage
if math.random() <= _DAMAGECHANCE then
ThePlayer.components.health:DoDelta(-50*math.random())
ThePlayer.components.talker:Say("Ow!")
return true
end
return false
end,
[3] = function() --regen
if math.random() <= _REGENCHANCE then
ThePlayer.regenfx = ThePlayer:DoPeriodicTask(1,function() ThePlayer.components.health:DoDelta(1+5*math.random(),true,10) end)
ThePlayer.components.talker:Say("Cellular regeneration!")
ThePlayer:DoTaskInTime(_REGENDURATION*math.random()+1, function() ThePlayer.regenfx:Cancel() ThePlayer.regenfx = nil end)
return true
end
return false
end,
[4] = function() --poison
if math.random() <= _POISONCHANCE then
ThePlayer.poisonfx = ThePlayer:DoPeriodicTask(1,function() ThePlayer.components.health:DoDelta(-1-5*math.random(),true,10) end)
ThePlayer.components.talker:Say("Cellular degeneration!")
ThePlayer:DoTaskInTime(_POISONDURATION*math.random()+1, function() ThePlayer.poisonfx:Cancel() ThePlayer.poisonfx = nil end)
return true
end
return false
end,
[5] = function() --heatup
if math.random() <= _HEATCHANCE then
ThePlayer.components.temperature:SetTemperature(ThePlayer.components.temperature.current + 20*math.random())
ThePlayer.components.talker:Say("Is it getting warm out?")
return true
end
return false
end,
[6] = function() --cooldown
if math.random() <= _COOLCHANCE then
ThePlayer.components.temperature:SetTemperature(ThePlayer.components.temperature.current - 20*math.random())
ThePlayer.components.talker:Say("Is it getting cold out?")
return true
end
return false
end,
[7] = function() --speedup
if math.random() <= _SPEEDCHANCE then
if ThePlayer.components.locomotor then
ThePlayer.components.locomotor:SetExternalSpeedMultiplier(ThePlayer, "Wet Goop Boost", 1+math.random())
end
ThePlayer.components.talker:Say("Who needs a walking cane?!")
ThePlayer:DoTaskInTime(_SLOWDURATION*math.random()+1,
function()
if ThePlayer.components.locomotor then
ThePlayer.components.locomotor:SetExternalSpeedMultiplier(ThePlayer, "Wet Goop Worn Off", 1)
end
end)
return true
end
return false
end,
[8] = function() --slowdown
if math.random() <= _SLOWCHANCE then
if ThePlayer.components.locomotor then
ThePlayer.components.locomotor:SetExternalSpeedMultiplier(ThePlayer, "Wet Goop Snare", 1-math.random())
end
ThePlayer.components.talker:Say("I need a walking cane...")
ThePlayer:DoTaskInTime(_SLOWDURATION*math.random()+1,
function()
if ThePlayer.components.locomotor then
ThePlayer.components.locomotor:SetExternalSpeedMultiplier(ThePlayer, "Wet Goop Worn Off", 1)
end
end)
return true
end
return false
end,
[9] = function() --strengthen
if math.random() <= _STRENGTHENCHANCE then
ThePlayer.components.combat.damagemultiplier = math.random()*4+1
ThePlayer.components.talker:Say("Wolfgang got nothing on this!")
ThePlayer:DoTaskInTime(_STRENGTHENDURATION*math.random()+1, function() ThePlayer.components.combat.damagemultiplier = 1 end)
return true
end
return false
end,
[10] = function() --weaken
if math.random() <= _WEAKENCHANCE then
ThePlayer.components.combat.damagemultiplier = math.random()
ThePlayer.components.talker:Say("Scrawnier than usual...")
ThePlayer:DoTaskInTime(_WEAKENDURATION*math.random()+1, function() ThePlayer.components.combat.damagemultiplier = 1 end)
return true
end
return false
end,
[11] = function() --insanity
if math.random() <= _INSANECHANCE then
ThePlayer.components.sanity.inducedinsanity = "Wet Goop"
ThePlayer.components.talker:Say("There are bats in my teeth!")
ThePlayer:DoTaskInTime(_INSANEDURATION*math.random()+1,
function()
if ThePlayer.components.sanity.inducedinsanity == "Wet Goop" then
ThePlayer.components.sanity.inducedinsanity = nil
end
end)
return true
end
return false
end,
[12] = function() --sleep
if math.random() <= _SLEEPCHANCE then
ThePlayer:PushEvent("yawn", { grogginess = 4, knockoutduration = 10 + 10*math.random() })
ThePlayer.components.talker:Say("Night night")
return true
end
return false
end,
[13] = function() --shield
if math.random() <= _SHIELDCHANCE then
local absorb_amt = 100*math.random()
ThePlayer.components.health.absorb = ThePlayer.components.health.absorb + absorb_amt
ThePlayer.components.talker:Say("I suddenly feel quite protected")
ThePlayer:DoTaskInTime(_SHIELDDURATION*math.random()+1, function() ThePlayer.components.health.absorb = ThePlayer.components.health.absorb - absorb_amt end)
return true
end
return false
end,
[14] = function() --invisible
if math.random() <= _INVISICHANCE then
ThePlayer:Hide()
ThePlayer:ListenForEvent("newstate", makehidden(ThePlayer,true))
ThePlayer.components.talker:Say("I'm going to sneak into a Pig House!")
ThePlayer:DoTaskInTime(_INVISIDURATION*math.random()+1, function() makehidden(ThePlayer,false) ThePlayer:RemoveTag("notarget") ThePlayer:Show() end)
return true
end
return false
end,
[15] = function() --nofire
if math.random() <= _NOFIRECHANCE then
ThePlayer.components.health.vulnerabletoheatdamage = false
ThePlayer.components.talker:Say("I have the suddent urge to stick my hand in fire")
ThePlayer:DoTaskInTime(_NOFIREDURATION*math.random()+1, function() ThePlayer.components.health.vulnerabletoheatdamage = true end)
return true
end
return false
end,
[16] = function() --nofreeze
if math.random() <= _NOFREEZECHANCE then
ThePlayer:ListenForEvent("freeze", stopfreeze(ThePlayer, true))
ThePlayer.components.talker:Say("♫ The cold never bothered me anyway! ♫")
ThePlayer:DoTaskInTime(_NOFREEZEDURATION*math.random()+1, stopfreeze(ThePlayer, false))
return true
end
return false
end,
[17] = function() --nocharlie
if math.random() <= _NODARKCHANCE then
ThePlayer:ListenForEvent("enterdark", stopcharlie(ThePlayer, true))
ThePlayer.components.talker:Say("The Darkness has nothing on me")
ThePlayer:DoTaskInTime(_NODARKDURATION*math.random()+1, stopcharlie(ThePlayer, false))
return true
end
return false
end,
[18] = function() --teleport
if math.random() <= _TELEPORTCHANCE then
local etho_pos = ThePlayer:GetPosition()
local offset = FindWalkableOffset(etho_pos, math.random() * 2 * math.pi, math.random(5*(math.random()+1),12*(math.random()+1)), 12)
if offset then
etho_pos = etho_pos + offset
ThePlayer.Transform:SetPosition(etho_pos:Get())
end
ThePlayer.components.talker:Say("Um... high speed transport?!")
return true
end
return false
end,
[19] = function() --slippery
if math.random() <= _SLIPCHANCE then
if ThePlayer.components.inventory.activeitem then
ThePlayer.components.inventory:DropActiveItem()
elseif ThePlayer.components.inventory.equipslots[EQUIPSLOTS.HANDS] then
ThePlayer.components.inventory:DropItem(ThePlayer.components.inventory.equipslots[EQUIPSLOTS.HANDS])
elseif ThePlayer.components.inventory.equipslots[EQUIPSLOTS.HEAD] then
ThePlayer.components.inventory:DropItem(ThePlayer.components.inventory.equipslots[EQUIPSLOTS.HEAD])
else
ThePlayer.components.inventory:DropItem(ThePlayer.components.inventory:FindItem(function() return true end))
end
ThePlayer.components.talker:Say("Goop is slippery!")
return true
end
return false
end,
[20] = function() --madbomber
if math.random() <= _MADBOMBERCHANCE then
local temp = _EPOWDERCHANCE
TUNING._EPOWDERCHANCE = 1.0
ThePlayer.components.talker:Say("Ahahahaha!\nYou get Etho Powder! And you get Etho Powder!")
for i=1,_MADBOMBERDURATION+1 do
ThePlayer:DoTaskInTime(1+10*math.random(), function()
if ThePlayer.components.inventory:FindItem(function(item) return item.prefab=="etho_powder" end) then
ThePlayer.components.inventory:DropItem(ThePlayer.components.inventory:FindItem(function(item) return item.prefab=="etho_powder" end))
else
ThePlayer.components.inventory:GiveItem(SpawnPrefab("etho_powder"))
ThePlayer.components.inventory:DropItem(ThePlayer.components.inventory:FindItem(function(item) return item.prefab=="etho_powder" end))
end
end)
end
TUNING._EPOWDERCHANCE = temp
return true
end
return false
end,
[21] = function() --nothing
ThePlayer.components.talker:Say("Huh... nothing happened")
return true
end
}
local function wetgoopeater(inst, food)
if food and food.components.edible and food.prefab == "wetgoop" then
if ThePlayer.prefab == "etho" then
local choice = math.random(21)
while goop_fx[choice]() ~= true do
end
end
end
end
-- This initializes for both the server and client. Tags can be added here.
local common_postinit = function(inst)
-- Minimap icon
inst.MiniMapEntity:SetIcon( "etho.tex" )
inst:AddTag("madscientist")
end
-- This initializes for the server only. Components are added here.
local master_postinit = function(inst)
-- choose which sounds this character will play
inst.soundsname = "waxwell"
-- Uncomment if "wathgrithr"(Wigfrid) or "webber" voice is used
--inst.talker_path_override = "dontstarve_DLC001/characters/"
-- Stats
inst.components.health:SetMaxHealth(100)
inst.components.hunger:SetMax(175)
inst.components.sanity:SetMax(100)
inst.components.eater:SetOnEatFn(wetgoopeater)
-- Isn't afraid of anything
inst.components.sanity.night_drain_mult = 0
inst.components.sanity.rate_modifier = 0
-- Damage multiplier (optional)
inst.components.combat.damagemultiplier = .5
inst.components.combat.onhitotherfn = (function(attacker, target)
local weapon = attacker.components.combat:GetWeapon()
if weapon and target.components.health and not target:HasTag("chess") then
local damage = (weapon.components.weapon.damage/10) * -1
target:AddTag("bleeding")
target.bleedticks = 5
if not target:HasTag("bleeder") then
target:AddTag("bleeder")
target:DoPeriodicTask(1, function(inst)
if inst:HasTag("bleeding") then
inst.bleedticks = inst.bleedticks - 1
print("Health: "..inst.components.health.currenthealth)
print(damage)
inst.components.health:DoDelta(damage, true, "bleed", false, attacker, false)
inst.AnimState:SetMultColour(1,0,0,.8)
inst:DoTaskInTime(.1, function(inst)
inst.AnimState:SetMultColour(1,1,1,1)
end)
end
if inst.bleedticks <= 0 then
inst:RemoveTag("bleeding")
end
end)
end
end
end)
inst.summons = {}
inst:ListenForEvent("buildstructure", oncraft)
inst.components.builder:UnlockRecipesForTech("SCIENCE")
inst.components.builder:UnlockRecipesForTech("MAGIC")
inst.components.builder:UnlockRecipesForTech("CARTOGRAPHY")
inst.components.builder:UnlockRecipesForTech("SCULPTING")
-- Hunger rate (optional)
inst.components.hunger.hungerrate = 1 * TUNING.WILSON_HUNGER_RATE
inst.components.locomotor.groundspeedmultiplier = 1.1
inst.OnSave = onsave
inst.OnLoad = onload
inst.OnNewSpawn = onload
end
return MakePlayerCharacter("etho", prefabs, assets, common_postinit, master_postinit, start_inv)
| mit |
pokemoncentral/wiki-lua-modules | VexEntry.lua | 1 | 5164 | --[[
Module to replace the VexEntry template. Right now only replace it, but I
intend to use it to replace all its derivate templates (Vex*).
The interface is as simple as:
{{#invoke: VexEntry | Vex1 | <args> }}
{{#invoke: VexEntry | Vexhs | <args> }}
and so on for any other variant.
Arguments are only positional and are in order ndex, name of the Pokémon and a
list of "yes"/"no" that states the presence of the Pokémon in each game of the
entry (in the entry's order)
--]]
local v = {}
local mw = require('mw')
local txt = require('Wikilib-strings') -- luacheck: no unused
local tab = require('Wikilib-tables') -- luacheck: no unused
local formlib = require('Wikilib-forms')
local multigen = require('Wikilib-multigen')
local w = require('Wikilib')
local css = require('Css')
local ms = require('MiniSprite')
local blackabbr = require("Blackabbrev-data")
local colorabbr = require("Colorabbrev-data")
local pokes = require("Poké-data")
--[[
Make a single game's abbr, either black or color depending on disp.
Arguments:
- disp: either "yes" or "no", if "yes" means that the Pokémon is present so
the game must be blackabbrev, otherwise is colorabbrev.
- abbr: abbr of the game to display. If abbr is nil or the empty string
this function return an empty string (handles parameter not passed)
--]]
v.makeGame = function(disp, abbr)
if not abbr or abbr == "" then
return ""
end
return disp == "yes" and blackabbr[abbr]
or table.concat{ " ", colorabbr[abbr], " " }
end
--[[
Main builder of WikiCode interfaces.
Parametri (named):
- ndex: numero di Dex (compresa sigla dell'eventuale forma alternativa).
- pkmn: nome del Pokémon (senza eventuale forma alternativa).
- gen: generazione dell'entry, usata per prendere i tipi del Pokémon
(opzionale, default alla generazione corrente).
- abbr1: sigla del primo gioco.
- disp1: disponibilità nel primo gioco (''yes''/''no'').
- abbr2, disp2: seconda sigla e disponibilità nel secondo gioco (come sopra).
- abbr3, disp3: terza sigla e disponibilità nel terzo gioco (come sopra, ma
appare solo se presente).
- abbr4, disp4: quarta sigla e disponibilità nel quarto gioco (come sopra,
ma appare solo se presente).
--]]
v.VexEntry = function(args)
local p = w.trimAll(args)
formlib.loadUseless(true)
local form = formlib.getLink(p.ndex, "black") or ""
local baseName, _ = formlib.getNameAbbr(p.ndex)
local pokedata = pokes[p.ndex] or pokes[baseName]
pokedata = multigen.getGen(pokedata, args.gen)
return string.interp([=[
|-
| style="padding: 0.5em;" | <div class="flex flex-row flex-nowrap flex-items-center"><div class="inline-block roundy-full" style="${radialGrad}">${ms}</div>
<span class="flex-item-fill" style="padding-left: 0.3em;">[[${pkmn}]]${formLink}</span></div>
| style="padding: 0.5em;" | ${abbr1}${abbr2}${abbr3}${abbr4}
]=], {
radialGrad = css.radialGradLua{"circle closest-side",
type1 = pokedata.type1,
type2 = pokedata.type2 },
ms = ms.staticLua{ndex = p.ndex, gen = args.gen},
pkmn = p.pkmn,
formLink = form ~= "" and string.interp(
'<div class="small-text">${form}</div>', { form = form }) or "",
abbr1 = v.makeGame(p.disp1, p.abbr1),
abbr2 = v.makeGame(p.disp2, p.abbr2),
abbr3 = v.makeGame(p.disp3, p.abbr3),
abbr4 = v.makeGame(p.disp4, p.abbr4),
})
end
--[[
Derived entries: are just an interface to the general one with some parameters
fixed. Automatically generated from the set of fixed parameters.
baseParamMap contains a map from positional arguments of interfaces to named
arguments of the base function "VexEntry".
The fixedParams table contains the list of fixed parameters for the entry
"Vex" .. key where key is the key in the table. To create a new WikiCode
interface is enough to add such a table.
--]]
local baseParamMap = { "ndex", "pkmn", "disp1", "disp2", "disp3", "disp4" }
local fixedParams = {
['1'] = { abbr1 = "R", abbr2 = "V", abbr3 = "B", abbr4 = "G", gen = 1 },
['2'] = { abbr1 = "O", abbr2 = "A", abbr3 = "C", gen = 2 },
['3'] = { abbr1 = "Ru", abbr2 = "Z", abbr3 = "S", gen = 3 },
fl = { abbr1 = "RF", abbr2 = "VF", gen = 3 },
['4'] = { abbr1 = "D", abbr2 = "P", abbr3 = "Pt", gen = 4 },
hs = { abbr1 = "HG", abbr2 = "SS", gen = 4 },
['5'] = { abbr1 = "N", abbr2 = "Bi", gen = 5 },
n2b2 = { abbr1 = "N2", abbr2 = "B2", gen = 5 },
['6'] = { abbr1 = "X", abbr2 = "Y", gen = 6 },
roza = { abbr1 = "RO", abbr2 = "ZA", gen = 6 },
['7'] = { abbr1 = "So", abbr2 = "L", gen = 7 },
usul = { abbr1 = "US", abbr2 = "UL", gen = 7 },
['8'] = { abbr1 = "Sp", abbr2 = "Sc", gen = 8 },
LGPE = { abbr1 = "LGP", abbr2 = "LGE", gen = 7 },
DLPS = { abbr1 = "DL", abbr2 = "PS", gen = 8 },
md1 = { abbr1 = "PMDR", abbr2 = "PMDB", gen = 3 },
md2 = { abbr1 = "PMDT", abbr2 = "PMDO", abbr3 = "PMDC", gen = 4 },
}
for funcName, params in pairs(fixedParams) do
v['Vex' .. funcName] = function(frame)
local args = mw.clone(params)
for k, val in pairs(frame.args) do
args[baseParamMap[k]] = val
end
return v.VexEntry(args)
end
end
return v
| cc0-1.0 |
greasydeal/darkstar | scripts/globals/mobskills/Luminous_Lance.lua | 19 | 1379 | ---------------------------------------------
-- Luminous Lance
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/zones/Empyreal_Paradox/TextIDs");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
local lanceTime = mob:getLocalVar("lanceTime");
local lanceOut = mob:getLocalVar("lanceOut");
if (not (target:hasStatusEffect(EFFECT_PHYSICAL_SHIELD) and target:hasStatusEffect(EFFECT_MAGIC_SHIELD)))
and (lanceTime + 60 < mob:getBattleTime()) and target:getCurrentAction() ~= ACTION_MOBABILITY_USING
and lanceOut == 1 then
return 0;
end
return 1;
end;
function onMobWeaponSkill(target, mob, skill)
mob:showText(mob, SELHTEUS_TEXT + 1);
local numhits = 1;
local accmod = 1;
local dmgmod = 1.6;
local info = MobRangedMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_RANGED,MOBPARAM_PIERCE,info.hitslanded);
mob:entityAnimationPacket("ids0");
mob:setLocalVar("lanceTime", mob:getBattleTime())
mob:setLocalVar("lanceOut", 0)
target:AnimationSub(3);
target:addStatusEffect(EFFECT_STUN, 0, 0, 20);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Lower_Jeuno/npcs/Susu.lua | 17 | 1634 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Susu
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,SUSU_SHOP_DIALOG);
stock = {0x1227,20000, -- Banishga II
0x1248,244, -- Barsleep
0x1249,400, -- Barpoison
0x124a,780, -- Barparalyze
0x124b,2030, -- Barblind
0x124c,4608, -- Barsilence
0x1256,244, -- Barsleepra
0x1257,400, -- Barpoisonra
0x1258,780, -- Barparalyzra
0x1259,2030, -- Barblindra
0x125a,4608, -- Barsilencera
0x1214,8586, -- Cursna
0x1215,35000, -- Holy
0x1211,2330, -- Silena
0x1212,19200, -- Stona
0x1213,13300} -- Viruna
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
ibm2431/darkstar | scripts/zones/QuBia_Arena/mobs/Ghul-I-Beaban.lua | 9 | 1497 | -----------------------------------
-- Area: Qu'Bia Arena
-- Mob: Ghul-I-Beaban
-- BCNM: Undying Promise
-----------------------------------
require("scripts/globals/status")
-----------------------------------
function reraiseGhul(mob, reraises, target)
mob:setLocalVar("RERAISES", reraises)
mob:setMod(dsp.mod.ATT, 25 * reraises)
mob:setHP(mob:getMaxHP() * (1 - (0.10 * reraises)))
mob:resetAI()
mob:stun(3000)
if target then
mob:updateClaim(target)
end
if reraises == 4 then
mob:getBattlefield():setLocalVar("lootSpawned", 0)
end
end
function onMobInitialize(mob)
mob:addListener("DEATH", "GHUL_DEATH", function(mob)
local mobId = mob:getID()
local reraises = mob:getLocalVar("RERAISES") + 1
local target = mob:getTarget()
-- spawn second form (BLM)
if reraises == 3 then
mob:timer(9000, function(mob)
mob:setStatus(dsp.status.DISAPPEAR)
local finalMobId = mobId + 1
local finalMob = GetMobByID(finalMobId)
finalMob:setSpawn(mob:getXPos(), mob:getYPos(), mob:getZPos())
finalMob:spawn()
reraiseGhul(finalMob, 3, target)
end)
-- reraise up to 4 times
elseif reraises < 5 then
mob:timer(9000, function(mob)
reraiseGhul(mob, reraises, target)
end)
end
end)
end
function onMobDeath(mob, player, isKiller)
end
| gpl-3.0 |
GENRALVS/GENRAL-VS | plugins/helps.pv.lua | 1 | 1160 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY xx_hetler_xx ▀▄ ▄▀
▀▄ ▄▀ BY hetler (hetler_ip) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY hetler ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local function DevPoint(msg,matches)
if is_momod(msg) and matches[1]== 'pv' and matches[2]== 'help' then
local help_text = tostring(_config.help_text_super)
send_large_msg("user#id"..msg.from.id, help_text)
return "Done sent a list of commands to the private !"
end
local reply_id = msg['id']
if not is_momod(msg) then
local iDev1 = 'only 4 admin'
reply_msg(msg.id, iDev1, ok_cb, false)
end
end
return {
patterns ={"^[!/#](pv) (help)$"},
run = xx_hetler_xx 👾 }
end | gpl-2.0 |
greasydeal/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Wyatt.lua | 17 | 1981 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Wyatt
-- @zone 80
-- @pos 124 0 84
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/titles");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 4 and trade:hasItemQty(2506,4)) then
player:startEvent(0x0004);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local seeingSpots = player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS);
if (seeingSpots == QUEST_AVAILABLE) then
player:startEvent(0x0002);
elseif (seeingSpots == QUEST_ACCEPTED) then
player:startEvent(0x0003);
else
player:showText(npc, WYATT_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0002) then
player:addQuest(CRYSTAL_WAR,SEEING_SPOTS);
elseif (csid == 0x0004) then
player:tradeComplete();
if(player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS) == QUEST_ACCEPTED) then
player:addTitle(LADY_KILLER);
player:addGil(GIL_RATE*3000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000);
player:completeQuest(CRYSTAL_WAR,SEEING_SPOTS);
else
player:addTitle(LADY_KILLER);
player:addGil(GIL_RATE*1500);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500);
end
end
end; | gpl-3.0 |
LegionXI/darkstar | scripts/globals/items/himesama_rice_ball.lua | 51 | 1477 | -----------------------------------------
-- ID: 5928
-- Item: Himesama Rice Ball
-- Food Effect: 30 Mins, All Races
-----------------------------------------
-- HP +25
-- Dexterity +4
-- Vitality +4
-- Character +4
-- Effect with enhancing equipment (Note: these are latents on gear with the effect)
-- Attack +60
-- Defense +40
-- Triple Attack +1%
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5928);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 25);
target:addMod(MOD_DEX, 4);
target:addMod(MOD_VIT, 4);
target:addMod(MOD_CHR, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 25);
target:delMod(MOD_DEX, 4);
target:delMod(MOD_VIT, 4);
target:delMod(MOD_CHR, 4);
end; | gpl-3.0 |
shadog/shado | lock_media.lua | 3 | 1457 | --[[
#
#ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ
#:((
# For More Information ....!
#manstir : < @alasmr_199 >
#manstir
# Version: 1.1
#:))
#ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ
#
]]
local function DevPoint(msg, matches)
if is_momod(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['media'] then
lock_media = data[tostring(msg.to.id)]['settings']['media']
end
end
end
local chat = get_receiver(msg)
local user = "user#id"..msg.from.id
if lock_media == "yes" then
delete_msg(msg.id, ok_cb, true)
send_large_msg(get_receiver(msg), 'عزيزي " '..msg.from.first_name..' "\nممنوع مشاركة " الصور - الروابط - الاعلانات - المواقع " هنا التزم بقوانين المجموعة 👮\n#Username : @'..msg.from.username)
end
end
return {
patterns = {
"%[(photo)%]",
"%[(document)%]",
"%[(video)%]",
"%[(audio)%]",
"%[(gif)%]",
"%[(sticker)%]",
},
run = DevPoint
}
| gpl-2.0 |
ibm2431/darkstar | scripts/globals/items/marinara_pizza_+1.lua | 11 | 1285 | -----------------------------------------
-- ID: 5744
-- Item: marinara_pizza +1
-- Food Effect: 4 hours, all Races
-----------------------------------------
-- HP +25
-- Attack +21% (cap 55)
-- Accuracy +11% (cap 58)
-- Undead Killer
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,14400,5744)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.HP, 25)
target:addMod(dsp.mod.FOOD_ATTP, 21)
target:addMod(dsp.mod.FOOD_ATT_CAP, 55)
target:addMod(dsp.mod.FOOD_ACCP, 11)
target:addMod(dsp.mod.FOOD_ACC_CAP, 58)
target:addMod(dsp.mod.UNDEAD_KILLER, 5)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.HP, 25)
target:delMod(dsp.mod.FOOD_ATTP, 21)
target:delMod(dsp.mod.FOOD_ATT_CAP, 55)
target:delMod(dsp.mod.FOOD_ACCP, 11)
target:delMod(dsp.mod.FOOD_ACC_CAP, 58)
target:delMod(dsp.mod.UNDEAD_KILLER, 5)
end
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Bastok_Markets/npcs/Offa.lua | 14 | 1306 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Offa
-- Type: Quest NPC
-- @pos -281.628 -16.971 -140.607 235
--
-- Auto-Script: Requires Verification. Verified standard dialog - thrydwolf 12/18/2011
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local SmokeOnTheMountain = player:getQuestStatus(BASTOK,SMOKE_ON_THE_MOUNTAIN);
if (SmokeOnTheMountain == QUEST_ACCEPTED) then
player:startEvent(0x00de);
else
player:startEvent(0x007c);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
BackupGGCode/teebx | misc/luabash/md5/test.lua | 4 | 2423 | #!/usr/bin/env lua
-- --- T2-COPYRIGHT-NOTE-BEGIN ---
-- This copyright note is auto-generated by ./scripts/Create-CopyPatch.
--
-- T2 SDE: misc/luabash/md5/test.lua
-- Copyright (C) 2006 The T2 SDE Project
--
-- More information can be found in the files COPYING and README.
--
-- 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; version 2 of the License. A copy of the
-- GNU General Public License can be found in the file COPYING.
-- --- T2-COPYRIGHT-NOTE-END ---
require"md5"
-- test some known sums
assert(md5.sum("") == "d41d8cd98f00b204e9800998ecf8427e")
assert(md5.sum("a") == "0cc175b9c0f1b6a831c399e269772661")
assert(md5.sum("abc") == "900150983cd24fb0d6963f7d28e17f72")
assert(md5.sum("message digest") == "f96b697d7cb7938d525a2f31aaf161d0")
assert(md5.sum("abcdefghijklmnopqrstuvwxyz") == "c3fcd3d76192e4007dfb496cca67e13b")
assert(md5.sum("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789")
== "d174ab98d277d9f5a5611c2c9f419d9f")
-- test padding borders
assert(md5.sum(string.rep('a',53)) == "e9e7e260dce84ffa6e0e7eb5fd9d37fc")
assert(md5.sum(string.rep('a',54)) == "eced9e0b81ef2bba605cbc5e2e76a1d0")
assert(md5.sum(string.rep('a',55)) == "ef1772b6dff9a122358552954ad0df65")
assert(md5.sum(string.rep('a',56)) == "3b0c8ac703f828b04c6c197006d17218")
assert(md5.sum(string.rep('a',57)) == "652b906d60af96844ebd21b674f35e93")
assert(md5.sum(string.rep('a',63)) == "b06521f39153d618550606be297466d5")
assert(md5.sum(string.rep('a',64)) == "014842d480b571495a4a0363793f7367")
assert(md5.sum(string.rep('a',65)) == "c743a45e0d2e6a95cb859adae0248435")
assert(md5.sum(string.rep('a',255)) == "46bc249a5a8fc5d622cf12c42c463ae0")
assert(md5.sum(string.rep('a',256)) == "81109eec5aa1a284fb5327b10e9c16b9")
assert(md5.sum(
"12345678901234567890123456789012345678901234567890123456789012345678901234567890")
== "57edf4a22be3c955ac49da2e2107b67a")
print"OK"
-- our t2 use case
-- cut -d ' ' -f 2 /var/adm/flists/gtk+ | grep -v '^var/adm/' | sed -e 's,^.*,/"\0",' | xargs -r /usr/embutils/md5sum
local f = io.open ("/var/adm/flists/gtk+", "r")
for line in f:lines() do
local sum, file = string.match (line, "(%S*)%s(.*)")
--print (sum .. ": " ..file)
local f2 = io.open ("/"..file)
print (md5.sum(f2) .. " " .. "/"..file)
f2:close()
end
f:close()
| gpl-2.0 |
greasydeal/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Ozzmo-Mazmo.lua | 38 | 1053 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Ozzmo-Mazmo
-- Type: Standard NPC
-- @zone: 94
-- @pos -61.677 -13.311 106.400
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01b0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Sacrarium/npcs/qm6.lua | 14 | 1799 | -----------------------------------
-- Area: Sacrarium
-- NPC: qm6 (???)
-- Notes: Used to spawn Old Prof. Mariselle
-- @pos 62.668 -3.111 -127.310 28
-----------------------------------
package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Sacrarium/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local OldProfessor = 16891970;
if (GetServerVariable("Old_Prof_Spawn_Location") == 6) then
if (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 3 and player:hasKeyItem(RELIQUIARIUM_KEY)==false and GetMobAction(OldProfessor) == 0) then
player:messageSpecial(EVIL_PRESENCE);
SpawnMob(OldProfessor):updateClaim(player);
GetMobByID(OldProfessor):setPos(npc:getXPos()+1, npc:getYPos(), npc:getZPos()+1); -- Set Prof. spawn x and z pos. +1 from NPC
else
player:messageSpecial(DRAWER_SHUT);
end
elseif (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 4 and player:hasKeyItem(RELIQUIARIUM_KEY)==false) then
player:addKeyItem(RELIQUIARIUM_KEY);
player:messageSpecial(KEYITEM_OBTAINED,RELIQUIARIUM_KEY);
else
player:messageSpecial(DRAWER_OPEN);
player:messageSpecial(DRAWER_EMPTY);
end
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
ibm2431/darkstar | scripts/globals/items/mutton_tortilla.lua | 11 | 1457 | -----------------------------------------
-- ID: 4506
-- Item: mutton_tortilla
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Magic 10
-- Strength 3
-- Vitality 1
-- Intelligence -1
-- Attack % 27
-- Attack Cap 30
-- Ranged ATT % 27
-- Ranged ATT Cap 30
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,4506)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.MP, 10)
target:addMod(dsp.mod.STR, 3)
target:addMod(dsp.mod.VIT, 1)
target:addMod(dsp.mod.INT, -1)
target:addMod(dsp.mod.FOOD_ATTP, 27)
target:addMod(dsp.mod.FOOD_ATT_CAP, 30)
target:addMod(dsp.mod.FOOD_RATTP, 27)
target:addMod(dsp.mod.FOOD_RATT_CAP, 30)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.MP, 10)
target:delMod(dsp.mod.STR, 3)
target:delMod(dsp.mod.VIT, 1)
target:delMod(dsp.mod.INT, -1)
target:delMod(dsp.mod.FOOD_ATTP, 27)
target:delMod(dsp.mod.FOOD_ATT_CAP, 30)
target:delMod(dsp.mod.FOOD_RATTP, 27)
target:delMod(dsp.mod.FOOD_RATT_CAP, 30)
end
| gpl-3.0 |
greasydeal/darkstar | scripts/globals/mobskills/Auroral_Drape.lua | 7 | 1027 | ---------------------------------------------
-- Auroral Drape
--
-- Description: Silence and Blind Area of Effect (10.0')
-- Type: Enfeebling
-- Utsusemi/Blink absorb: Ignores shadows
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local silenced = false;
local blinded = false;
silenced = MobStatusEffectMove(mob, target, EFFECT_SILENCE, 1, 0, 60);
blinded = MobStatusEffectMove(mob, target, EFFECT_BLINDNESS, 60, 0, 60);
skill:setMsg(MSG_ENFEEB_IS);
-- display silenced first, else blind
if(silenced == MSG_ENFEEB_IS) then
typeEffect = EFFECT_SILENCE;
elseif(blinded == MSG_ENFEEB_IS) then
typeEffect = EFFECT_BLINDNESS;
else
skill:setMsg(MSG_MISS);
end
return typeEffect;
end;
| gpl-3.0 |
LegionXI/darkstar | scripts/zones/Port_Jeuno/npcs/Rinzei.lua | 17 | 1375 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Rinzei
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Jeuno/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatJeuno = player:getVar("WildcatJeuno");
if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,18) == false) then
player:startEvent(315);
else
player:startEvent(0x38);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 315) then
player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",18,true);
end
end;
| gpl-3.0 |
LegionXI/darkstar | scripts/globals/spells/bluemagic/cold_wave.lua | 9 | 2132 | -----------------------------------------
-- Spell: Cold Wave
-- Deals ice damage that lowers Agility and gradually reduces HP of enemies within range
-- Spell cost: 37 MP
-- Monster Type: Arcana
-- Spell Type: Magical (Ice)
-- Blue Magic Points: 1
-- Stat Bonus: INT-1
-- Level: 52
-- Casting Time: 4 seconds
-- Recast Time: 60 seconds
-- Magic Bursts on: Induration, Distortion, and Darkness
-- Combos: Auto Refresh
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local typeEffect = EFFECT_FROST;
local dINT = caster:getStat(MOD_INT)-target:getStat(MOD_INT);
local resist = applyResistance(caster,spell,target,dINT,BLUE_SKILL,0);
if (target:getStatusEffect(EFFECT_BURN) ~= nil) then
spell:setMsg(75); -- no effect
elseif (resist > 0.5) then
if (target:getStatusEffect(EFFECT_CHOKE) ~= nil) then
target:delStatusEffect(EFFECT_CHOKE);
end;
local sINT = caster:getStat(MOD_INT);
local DOT = getElementalDebuffDOT(sINT);
local effect = target:getStatusEffect(typeEffect);
local noeffect = false;
if (effect ~= nil) then
if (effect:getPower() >= DOT) then
noeffect = true;
end;
end;
if (noeffect) then
spell:setMsg(75); -- no effect
else
if (effect ~= nil) then
target:delStatusEffect(typeEffect);
end;
spell:setMsg(237);
local duration = math.floor(ELEMENTAL_DEBUFF_DURATION * resist);
target:addStatusEffect(typeEffect,DOT,3,ELEMENTAL_DEBUFF_DURATION,FLAG_ERASABLE);
end;
else
spell:setMsg(85);
end;
return typeEffect;
end;
| gpl-3.0 |
lbthomsen/openwrt-luci | applications/luci-app-lxc/luasrc/controller/lxc.lua | 5 | 5280 | --[[
LuCI LXC module
Copyright (C) 2014, Cisco Systems, Inc.
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
Author: Petar Koretic <petar.koretic@sartura.hr>
]]--
module("luci.controller.lxc", package.seeall)
local uci = require "luci.model.uci".cursor()
local util = require "luci.util"
local nx = require "nixio"
local url = util.shellquote(uci:get("lxc", "lxc", "url"))
function index()
if not nixio.fs.access("/etc/config/lxc") then
return
end
page = node("admin", "services", "lxc")
page.target = cbi("lxc")
page.title = _("LXC Containers")
page.order = 70
page.acl_depends = { "luci-app-lxc" }
page = entry({"admin", "services", "lxc_create"}, call("lxc_create"), nil)
page.acl_depends = { "luci-app-lxc" }
page.leaf = true
page = entry({"admin", "services", "lxc_action"}, call("lxc_action"), nil)
page.acl_depends = { "luci-app-lxc" }
page.leaf = true
page = entry({"admin", "services", "lxc_get_downloadable"}, call("lxc_get_downloadable"), nil)
page.acl_depends = { "luci-app-lxc" }
page.leaf = true
page = entry({"admin", "services", "lxc_configuration_get"}, call("lxc_configuration_get"), nil)
page.acl_depends = { "luci-app-lxc" }
page.leaf = true
page = entry({"admin", "services", "lxc_configuration_set"}, call("lxc_configuration_set"), nil)
page.acl_depends = { "luci-app-lxc" }
page.leaf = true
end
function lxc_get_downloadable()
local target = lxc_get_arch_target(url)
local ssl_status = lxc_get_ssl_status()
local templates = {}
local f = io.popen('sh /usr/share/lxc/templates/lxc-download --list %s --server %s 2>/dev/null'
%{ ssl_status, url }, 'r')
local line
for line in f:lines() do
local dist, version, dist_target = line:match("^(%S+)%s+(%S+)%s+(%S+)%s+default%s+%S+$")
if dist and version and dist_target and dist_target == target then
templates[#templates+1] = "%s:%s" %{ dist, version }
end
end
f:close()
luci.http.prepare_content("application/json")
luci.http.write_json(templates)
end
function lxc_create(lxc_name, lxc_template)
luci.http.prepare_content("text/plain")
local path = lxc_get_config_path()
if not path then
return
end
local ssl_status = lxc_get_ssl_status()
local lxc_dist, lxc_release = lxc_template:match("^(.+):(.+)$")
luci.sys.call('/usr/bin/lxc-create --quiet --name %s --bdev best --template download -- --dist %s --release %s --arch %s --server %s %s'
%{ lxc_name, lxc_dist, lxc_release, lxc_get_arch_target(url), url, ssl_status })
while (nx.fs.access(path .. lxc_name .. "/partial")) do
nx.nanosleep(1)
end
luci.http.write("0")
end
function lxc_action(lxc_action, lxc_name)
local data, ec = util.ubus("lxc", lxc_action, lxc_name and { name = lxc_name } or {})
luci.http.prepare_content("application/json")
luci.http.write_json(ec and {} or data)
end
function lxc_get_config_path()
local f = io.open("/etc/lxc/lxc.conf", "r")
local content = f:read("*all")
f:close()
local ret = content:match('^%s*lxc.lxcpath%s*=%s*([^%s]*)')
if ret then
if nx.fs.access(ret) then
local min_space = tonumber(uci:get("lxc", "lxc", "min_space")) or 100000
local free_space = tonumber(util.exec("df " ..ret.. " | awk '{if(NR==2)print $4}'"))
if free_space and free_space >= min_space then
local min_temp = tonumber(uci:get("lxc", "lxc", "min_temp")) or 100000
local free_temp = tonumber(util.exec("df /tmp | awk '{if(NR==2)print $4}'"))
if free_temp and free_temp >= min_temp then
return ret .. "/"
else
util.perror("lxc error: not enough temporary space (< " ..min_temp.. " KB)")
end
else
util.perror("lxc error: not enough space (< " ..min_space.. " KB)")
end
else
util.perror("lxc error: directory not found")
end
else
util.perror("lxc error: config path is empty")
end
end
function lxc_configuration_get(lxc_name)
luci.http.prepare_content("text/plain")
local f = io.open(lxc_get_config_path() .. lxc_name .. "/config", "r")
local content = f:read("*all")
f:close()
luci.http.write(content)
end
function lxc_configuration_set(lxc_name)
luci.http.prepare_content("text/plain")
local lxc_configuration = luci.http.formvalue("lxc_conf")
if lxc_configuration == nil then
util.perror("lxc error: config formvalue is empty")
return
end
local f, err = io.open(lxc_get_config_path() .. lxc_name .. "/config","w+")
if not f then
util.perror("lxc error: config file not found")
return
end
f:write(lxc_configuration)
f:close()
luci.http.write("0")
end
function lxc_get_arch_target(url)
local target = nx.uname().machine
if url and url:match("images.linuxcontainers.org") then
local target_map = {
armv5 = "armel",
armv6 = "armel",
armv7 = "armhf",
armv8 = "arm64",
aarch64 = "arm64",
i686 = "i386",
x86_64 = "amd64"
}
local k, v
for k, v in pairs(target_map) do
if target:find(k) then
return v
end
end
end
return target
end
function lxc_get_ssl_status()
local ssl_enabled = uci:get("lxc", "lxc", "ssl_enabled")
local ssl_status = "--no-validate"
if ssl_enabled and ssl_enabled == "1" then
ssl_status = ""
end
return ssl_status
end
| apache-2.0 |
ricker75/Global-Server | data/actions/scripts/in service of yalahar quest/inServiceOfYalaharQuestMechanism.lua | 2 | 1694 | local mechanisms = {
[3091] = {pos = {x = 32744, y = 31161, z = 5}, value = 21}, -- Alchemist
[3092] = {pos = {x = 32744, y = 31164, z = 5}, value = 21},
[3093] = {pos = {x = 32833, y = 31269, z = 5}, value = 24}, -- Trade
[3094] = {pos = {x = 32833, y = 31266, z = 5}, value = 24},
[3095] = {pos = {x = 32729, y = 31200, z = 5}, value = 29}, -- Arena
[3096] = {pos = {x = 32734, y = 31200, z = 5}, value = 29},
[3097] = {pos = {x = 32776, y = 31141, z = 5}, value = 35}, -- Cemetery
[3098] = {pos = {x = 32776, y = 31145, z = 5}, value = 35},
[3099] = {pos = {x = 32874, y = 31202, z = 5}, value = 41}, -- Sunken
[3100] = {pos = {x = 32869, y = 31202, z = 5}, value = 41},
[3101] = {pos = {x = 32856, y = 31251, z = 5}, value = 45}, -- Factory
[3102] = {pos = {x = 32854, y = 31248, z = 5}, value = 45}
}
local mechanisms2 = {
[9235] = {pos = {x = 32773, y = 31116, z = 7}},
[9236] = {pos = {x = 32780, y = 31115, z = 7}}
}
function onUse(cid, item, fromPosition, itemEx, toPosition)
local player = Player(cid)
if(mechanisms[item.uid]) then
if(player:getStorageValue(30) >= mechanisms[item.uid].value) then
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
player:teleportTo(mechanisms[item.uid].pos)
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
else
player:sendTextMessage(MESSAGE_EVENT_ADVANCE, "The gate mechanism won't move. You probably have to find a way around until you figure out how to operate the gate.")
end
elseif(mechanisms2[item.uid]) then
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
player:teleportTo(mechanisms2[item.uid].pos)
player:getPosition():sendMagicEffect(CONST_ME_TELEPORT)
end
return true
end
| gpl-2.0 |
lache/RacingKingLee | crazyclient/frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/AnimationCache.lua | 18 | 3150 |
--------------------------------
-- @module AnimationCache
-- @extend Ref
-- @parent_module cc
--------------------------------
-- Returns a Animation that was previously added.<br>
-- If the name is not found it will return nil.<br>
-- You should retain the returned copy if you are going to use it.<br>
-- return A Animation that was previously added. If the name is not found it will return nil.
-- @function [parent=#AnimationCache] getAnimation
-- @param self
-- @param #string name
-- @return Animation#Animation ret (return value: cc.Animation)
--------------------------------
-- Adds a Animation with a name.<br>
-- param animation An animation.<br>
-- param name The name of animation.
-- @function [parent=#AnimationCache] addAnimation
-- @param self
-- @param #cc.Animation animation
-- @param #string name
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
--------------------------------
--
-- @function [parent=#AnimationCache] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Adds an animation from an NSDictionary.<br>
-- Make sure that the frames were previously loaded in the SpriteFrameCache.<br>
-- param dictionary An NSDictionary.<br>
-- param plist The path of the relative file,it use to find the plist path for load SpriteFrames.<br>
-- since v1.1<br>
-- js NA
-- @function [parent=#AnimationCache] addAnimationsWithDictionary
-- @param self
-- @param #map_table dictionary
-- @param #string plist
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
--------------------------------
-- Deletes a Animation from the cache.<br>
-- param name The name of animation.
-- @function [parent=#AnimationCache] removeAnimation
-- @param self
-- @param #string name
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
--------------------------------
-- Adds an animation from a plist file.<br>
-- Make sure that the frames were previously loaded in the SpriteFrameCache.<br>
-- since v1.1<br>
-- js addAnimations<br>
-- lua addAnimations<br>
-- param plist An animation from a plist file.
-- @function [parent=#AnimationCache] addAnimationsWithFile
-- @param self
-- @param #string plist
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
--------------------------------
-- Purges the cache. It releases all the Animation objects and the shared instance.<br>
-- js NA
-- @function [parent=#AnimationCache] destroyInstance
-- @param self
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
--------------------------------
-- Returns the shared instance of the Animation cache <br>
-- js NA
-- @function [parent=#AnimationCache] getInstance
-- @param self
-- @return AnimationCache#AnimationCache ret (return value: cc.AnimationCache)
--------------------------------
-- js ctor
-- @function [parent=#AnimationCache] AnimationCache
-- @param self
-- @return AnimationCache#AnimationCache self (return value: cc.AnimationCache)
return nil
| mit |
bbn1234/uzzbot | plugins/invite.lua | 299 | 1025 | -- Invite other user to the chat group.
-- Use !invite name User_name or !invite id id_number
-- The User_name is the print_name (there are no spaces but _)
do
local function callback(extra, success, result)
vardump(success)
vardump(result)
end
local function run(msg, matches)
local user = matches[2]
-- User submitted a user name
if matches[1] == "name" then
user = string.gsub(user," ","_")
end
-- User submitted an id
if matches[1] == "id" then
user = 'user#id'..user
end
-- The message must come from a chat group
if msg.to.type == 'chat' then
local chat = 'chat#id'..msg.to.id
chat_add_user(chat, user, callback, false)
return "Add: "..user.." to "..chat
else
return 'This isnt a chat group!'
end
end
return {
description = "Invite other user to the chat group",
usage = {
"!invite name [user_name]",
"!invite id [user_id]" },
patterns = {
"^!invite (name) (.*)$",
"^!invite (id) (%d+)$"
},
run = run,
moderation = true
}
end | gpl-2.0 |
greasydeal/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Fayeewah.lua | 34 | 1200 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Fayeewah
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,FAYEEWAH_SHOP_DIALOG);
stock = {0x15c2,68, -- Cup of Chai
0x15c4,2075} -- Irmik Helvasi
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
softer/prosody-modules | mod_register_json/register_json/mod_register_json.lua | 32 | 10044 | -- Expose a simple token based servlet to handle user registrations from web pages
-- through Base64 encoded JSON.
-- Copyright (C) 2010 - 2013, Marco Cirillo (LW.Org)
local datamanager = datamanager
local b64_decode = require "util.encodings".base64.decode
local b64_encode = require "util.encodings".base64.encode
local http_event = require "net.http.server".fire_event
local jid_prep = require "util.jid".prep
local jid_split = require "util.jid".split
local json_decode = require "util.json".decode
local nodeprep = require "util.encodings".stringprep.nodeprep
local open, os_time, setmt, type = io.open, os.time, setmetatable, type
local sha1 = require "util.hashes".sha1
local urldecode = http.urldecode
local usermanager = usermanager
local uuid_gen = require "util.uuid".generate
local timer = require "util.timer"
module:depends("http")
-- Pick up configuration and setup stores/variables.
local auth_token = module:get_option_string("reg_servlet_auth_token")
local secure = module:get_option_boolean("reg_servlet_secure", true)
local base_path = module:get_option_string("reg_servlet_base", "/register_account/")
local throttle_time = module:get_option_number("reg_servlet_ttime", nil)
local whitelist = module:get_option_set("reg_servlet_wl", {})
local blacklist = module:get_option_set("reg_servlet_bl", {})
local fm_patterns = module:get_option("reg_servlet_filtered_mails", {})
if type(fm_patterns) ~= "table" then fm_patterns = {} end
local files_base = module.path:gsub("/[^/]+$","") .. "/template/"
local recent_ips = {}
local pending = {}
local pending_node = {}
-- Setup hashes data structure
hashes = { _index = {} }
local hashes_mt = {} ; hashes_mt.__index = hashes_mt
function hashes_mt:add(node, mail)
local _hash = b64_encode(sha1(mail))
if not self:exists(_hash) then
self[_hash] = node ; self._index[node] = _hash ; self:save()
return true
else
return false
end
end
function hashes_mt:exists(hash)
if hashes[hash] then return true else return false end
end
function hashes_mt:remove(node)
local _hash = self._index[node]
if _hash then
self[_hash] = nil ; self._index[node] = nil ; self:save()
end
end
function hashes_mt:save()
if not datamanager.store("register_json", module.host, "hashes", hashes) then
module:log("error", "Failed to save the mail addresses' hashes store.")
end
end
local function check_mail(address)
for _, pattern in ipairs(fm_patterns) do
if address:match(pattern) then return false end
end
return true
end
-- Begin
local function handle(code, message) return http_event("http-error", { code = code, message = message }) end
local function http_response(event, code, message, headers)
local response = event.response
if headers then
for header, data in pairs(headers) do response.headers[header] = data end
end
response.status_code = code
response:send(handle(code, message))
end
local function handle_req(event)
local request = event.request
if secure and not request.secure then return nil end
if request.method ~= "POST" then
return http_response(event, 405, "Bad method.", {["Allow"] = "POST"})
end
local req_body
-- We check that what we have is valid JSON wise else we throw an error...
if not pcall(function() req_body = json_decode(b64_decode(request.body)) end) then
module:log("debug", "Data submitted for user registration by %s failed to Decode.", user)
return http_response(event, 400, "Decoding failed.")
else
-- Decode JSON data and check that all bits are there else throw an error
if req_body["username"] == nil or req_body["password"] == nil or req_body["ip"] == nil or req_body["mail"] == nil or
req_body["auth_token"] == nil then
module:log("debug", "%s supplied an insufficent number of elements or wrong elements for the JSON registration", user)
return http_response(event, 400, "Invalid syntax.")
end
-- Set up variables
local username, password, ip, mail, token = req_body.username, req_body.password, req_body.ip, req_body.mail, req_body.auth_token
-- Check if user is an admin of said host
if token ~= auth_token then
module:log("warn", "%s tried to retrieve a registration token for %s@%s", request.ip, username, module.host)
return http_response(event, 401, "Auth token is invalid! The attempt has been logged.")
else
-- Blacklist can be checked here.
if blacklist:contains(ip) then
module:log("warn", "Attempt of reg. submission to the JSON servlet from blacklisted address: %s", ip)
return http_response(event, 403, "The specified address is blacklisted, sorry.")
end
if not check_mail(mail) then
module:log("warn", "%s attempted to use a mail address (%s) matching one of the forbidden patterns.", ip, mail)
return http_response(event, 403, "Requesting to register using this E-Mail address is forbidden, sorry.")
end
-- We first check if the supplied username for registration is already there.
-- And nodeprep the username
username = nodeprep(username)
if not username then
module:log("debug", "An username containing invalid characters was supplied: %s", req_body["username"])
return http_response(event, 406, "Supplied username contains invalid characters, see RFC 6122.")
else
if pending_node[username] then
module:log("warn", "%s attempted to submit a registration request but another request for that user (%s) is pending", ip, username)
return http_response(event, 401, "Another user registration by that username is pending.")
end
if not usermanager.user_exists(username, module.host) then
-- if username fails to register successive requests shouldn't be throttled until one is successful.
if throttle_time and not whitelist:contains(ip) then
if not recent_ips[ip] then
recent_ips[ip] = os_time()
else
if os_time() - recent_ips[ip] < throttle_time then
recent_ips[ip] = os_time()
module:log("warn", "JSON Registration request from %s has been throttled.", req_body["ip"])
return http_response(event, 503, "Request throttled, wait a bit and try again.")
end
recent_ips[ip] = os_time()
end
end
local uuid = uuid_gen()
if not hashes:add(username, mail) then
module:log("warn", "%s (%s) attempted to register to the server with an E-Mail address we already possess the hash of.", username, ip)
return http_response(event, 409, "The E-Mail Address provided matches the hash associated to an existing account.")
end
pending[uuid] = { node = username, password = password, ip = ip }
pending_node[username] = uuid
timer.add_task(300, function()
if pending[uuid] then
pending[uuid] = nil
pending_node[username] = nil
hashes:remove(username)
end
end)
module:log("info", "%s (%s) submitted a registration request and is awaiting final verification", username, uuid)
return uuid
else
module:log("debug", "%s registration data submission failed (user already exists)", username)
return http_response(event, 409, "User already exists.")
end
end
end
end
end
local function open_file(file)
local f, err = open(file, "rb");
if not f then return nil end
local data = f:read("*a") ; f:close()
return data
end
local function r_template(event, type)
local data = open_file(files_base..type.."_t.html")
if data then
data = data:gsub("%%REG%-URL", base_path.."verify/")
return data
else return http_response(event, 500, "Failed to obtain template.") end
end
local function handle_verify(event, path)
local request = event.request
local body = request.body
if secure and not request.secure then return nil end
local valid_files = {
["css/style.css"] = files_base.."css/style.css",
["images/tile.png"] = files_base.."images/tile.png",
["images/header.png"] = files_base.."images/header.png"
}
if request.method == "GET" then
if path == "" then
return r_template(event, "form")
end
if valid_files[path] then
local data = open_file(valid_files[path])
if data then return data
else return http_response(event, 404, "Not found.") end
end
elseif request.method == "POST" then
if path == "" then
if not body then return http_response(event, 400, "Bad Request.") end
local uuid = urldecode(body):match("^uuid=(.*)$")
if not pending[uuid] then
return r_template(event, "fail")
else
local username, password, ip =
pending[uuid].node, pending[uuid].password, pending[uuid].ip
local ok, error = usermanager.create_user(username, password, module.host)
if ok then
module:fire_event(
"user-registered",
{ username = username, host = module.host, source = "mod_register_json", session = { ip = ip } }
)
module:log("info", "Account %s@%s is successfully verified and activated", username, module.host)
-- we shall not clean the user from the pending lists as long as registration doesn't succeed.
pending[uuid] = nil ; pending_node[username] = nil
return r_template(event, "success")
else
module:log("error", "User creation failed: "..error)
return http_response(event, 500, "Encountered server error while creating the user: "..error)
end
end
end
else
return http_response(event, 405, "Invalid method.")
end
end
local function handle_user_deletion(event)
local user, hostname = event.username, event.host
if hostname == module.host then hashes:remove(user) end
end
-- Set it up!
hashes = datamanager.load("register_json", module.host, "hashes") or hashes ; setmt(hashes, hashes_mt)
module:provides("http", {
default_path = base_path,
route = {
["GET /"] = handle_req,
["POST /"] = handle_req,
["GET /verify/*"] = handle_verify,
["POST /verify/*"] = handle_verify
}
})
module:hook_global("user-deleted", handle_user_deletion, 10);
-- Reloadability
module.save = function() return { hashes = hashes } end
module.restore = function(data) hashes = data.hashes or { _index = {} } ; setmt(hashes, hashes_mt) end
| mit |
LegionXI/darkstar | scripts/globals/abilities/pets/glittering_ruby.lua | 26 | 1148 | ---------------------------------------------------
-- Glittering Ruby
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill)
--randomly give str/dex/vit/agi/int/mnd/chr (+12)
local effect = math.random();
local effectid = EFFECT_STR_BOOST;
if (effect<=0.14) then --STR
effectid = EFFECT_STR_BOOST;
elseif (effect<=0.28) then --DEX
effectid = EFFECT_DEX_BOOST;
elseif (effect<=0.42) then --VIT
effectid = EFFECT_VIT_BOOST;
elseif (effect<=0.56) then --AGI
effectid = EFFECT_AGI_BOOST;
elseif (effect<=0.7) then --INT
effectid = EFFECT_INT_BOOST;
elseif (effect<=0.84) then --MND
effectid = EFFECT_MND_BOOST;
else --CHR
effectid = EFFECT_CHR_BOOST;
end
target:addStatusEffect(effectid,math.random(12,14),0,90);
skill:setMsg(MSG_BUFF);
return effectid;
end
| gpl-3.0 |
greasydeal/darkstar | scripts/globals/items/bowl_of_adoulin_soup_+1.lua | 36 | 1507 | -----------------------------------------
-- ID: 5999
-- Item: Bowl of Adoulin Soup +1
-- Food Effect: 240 Min, All Races
-----------------------------------------
-- HP % 4 Cap 45
-- Vitality 4
-- Defense % 16 Cap 75
-- HP Healing 7
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5999);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 4);
target:addMod(MOD_FOOD_HP_CAP, 45);
target:addMod(MOD_VIT, 4);
target:addMod(MOD_FOOD_DEFP, 16);
target:addMod(MOD_FOOD_DEF_CAP, 75);
target:addMod(MOD_HPHEAL, 7);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 4);
target:delMod(MOD_FOOD_HP_CAP, 45);
target:delMod(MOD_VIT, 4);
target:delMod(MOD_FOOD_DEFP, 16);
target:delMod(MOD_FOOD_DEF_CAP, 75);
target:delMod(MOD_HPHEAL, 7);
end;
| gpl-3.0 |
CuteOne/meta | Libs/DiesalGUI-1.0/Objects/Input.lua | 6 | 4285 | -- $Id: Input.lua 60 2016-11-04 01:34:23Z diesal2010 $
local DiesalGUI = LibStub("DiesalGUI-1.0")
-- ~~| Libraries |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local DiesalTools = LibStub("DiesalTools-1.0")
local DiesalStyle = LibStub("DiesalStyle-1.0")
-- ~~| Diesal Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local Colors = DiesalStyle.Colors
local HSL, ShadeColor, TintColor = DiesalTools.HSL, DiesalTools.ShadeColor, DiesalTools.TintColor
-- ~~| Lua Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- | Input |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local Type = "Input"
local Version = 1
-- | Stylesheets |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local Stylesheet = {
['frame-background'] = {
type = 'texture',
layer = 'BACKGROUND',
color = '000000',
alpha = .6,
},
['editBox-outline'] = {
type = 'outline',
layer = 'BORDER',
color = 'FFFFFF',
alpha = .02,
position = 1,
},
['editBox-inline'] = {
type = 'outline',
layer = 'BORDER',
color = '000000',
alpha = .7,
},
['editBox-hover'] = {
type = 'texture',
layer = 'HIGHLIGHT',
color = 'ffffff',
alpha = .05,
position = -1,
},
['editBox-font'] = {
type = 'Font',
color = Colors.UI_TEXT,
},
}
-- ~~| Spinner Methods |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local methods = {
['OnAcquire'] = function(self)
self:SetStylesheet(Stylesheet)
self:ApplySettings()
self:Show()
end,
['OnRelease'] = function(self)
end,
['ApplySettings'] = function(self)
self:SetWidth( self.settings.width)
self:SetHeight( self.settings.height)
end,
['GetText'] = function(self)
return self.editBox:GetText()
end,
['SetText'] = function(self,txt)
self.editBox:SetText(txt)
end,
['SetTextColor'] = function(self,color,alpha)
alpha = alpha or 1
color = {DiesalTools.GetColor(color)}
self.editBox:SetTextColor(color[1],color[2],color[3],alpha)
end,
}
-- | Constructor |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local function Constructor()
local self = DiesalGUI:CreateObjectBase(Type)
local frame = CreateFrame('Frame',nil,UIParent)
self.frame = frame
self.defaults = {
height = 16,
width = 50,
mouse = true,
}
-- ~~ Events ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- OnAcquire, OnRelease, OnHeightSet, OnWidthSet
-- OnEnter, OnLeave, OnEnterPressed, OnValueChanged
-- ~~ Construct ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
frame:SetScript("OnHide",function(this)
self:FireEvent("OnHide")
end)
local editBox = self:CreateRegion("EditBox", 'editBox', frame)
editBox:SetAllPoints()
editBox:SetAutoFocus(false)
editBox:SetJustifyH("LEFT")
editBox:SetJustifyV("CENTER")
editBox:SetTextInsets(3,0,2,0)
editBox:SetScript('OnEnterPressed', function(this,...)
self:FireEvent("OnEnterPressed",...)
DiesalGUI:ClearFocus()
end)
editBox:HookScript('OnEscapePressed', function(this,...)
self:FireEvent("OnEscapePressed",...)
end)
editBox:HookScript('OnEditFocusLost', function(this,...)
self:FireEvent("OnEditFocusLost",...)
end)
editBox:HookScript('OnEditFocusGained', function(this,...)
self:FireEvent("OnEditFocusGained",...)
end)
editBox:SetScript("OnEnter",function(this,...)
self:FireEvent("OnEnter",...)
end)
editBox:SetScript("OnLeave", function(this,...)
self:FireEvent("OnLeave",...)
end)
-- ~~ Methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for method, func in pairs(methods) do self[method] = func end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
return self
end
DiesalGUI:RegisterObjectConstructor(Type,Constructor,Version)
| gpl-3.0 |
greasydeal/darkstar | scripts/globals/items/plate_of_yahata-style_carp_sushi.lua | 35 | 1422 | -----------------------------------------
-- ID: 5186
-- Item: plate_of_yahata-style_carp_sushi
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Dexterity 2
-- Accuracy % 11
-- HP Recovered While Healing 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5186);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_FOOD_ACCP, 11);
target:addMod(MOD_FOOD_ACC_CAP, 999);
target:addMod(MOD_HPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_FOOD_ACCP, 11);
target:delMod(MOD_FOOD_ACC_CAP, 999);
target:delMod(MOD_HPHEAL, 2);
end;
| gpl-3.0 |
icyxp/kong | spec/03-plugins/19-acl/02-access_spec.lua | 3 | 14154 | local helpers = require "spec.helpers"
local cjson = require "cjson"
describe("Plugin: ACL (access)", function()
local client, api_client
setup(function()
helpers.run_migrations()
local consumer1 = assert(helpers.dao.consumers:insert {
username = "consumer1"
})
assert(helpers.dao.keyauth_credentials:insert {
key = "apikey123",
consumer_id = consumer1.id
})
local consumer2 = assert(helpers.dao.consumers:insert {
username = "consumer2"
})
assert(helpers.dao.keyauth_credentials:insert {
key = "apikey124",
consumer_id = consumer2.id
})
assert(helpers.dao.acls:insert {
group = "admin",
consumer_id = consumer2.id
})
local consumer3 = assert(helpers.dao.consumers:insert {
username = "consumer3"
})
assert(helpers.dao.keyauth_credentials:insert {
key = "apikey125",
consumer_id = consumer3.id
})
assert(helpers.dao.acls:insert {
group = "pro",
consumer_id = consumer3.id
})
assert(helpers.dao.acls:insert {
group = "hello",
consumer_id = consumer3.id
})
local consumer4 = assert(helpers.dao.consumers:insert {
username = "consumer4"
})
assert(helpers.dao.keyauth_credentials:insert {
key = "apikey126",
consumer_id = consumer4.id
})
assert(helpers.dao.acls:insert {
group = "free",
consumer_id = consumer4.id
})
assert(helpers.dao.acls:insert {
group = "hello",
consumer_id = consumer4.id
})
local anonymous = assert(helpers.dao.consumers:insert {
username = "anonymous"
})
assert(helpers.dao.acls:insert {
group = "anonymous",
consumer_id = anonymous.id
})
local api1 = assert(helpers.dao.apis:insert {
name = "api-1",
hosts = { "acl1.com" },
upstream_url = helpers.mock_upstream_url,
})
assert(helpers.dao.plugins:insert {
name = "acl",
api_id = api1.id,
config = {
whitelist = "admin"
}
})
local api2 = assert(helpers.dao.apis:insert {
name = "api-2",
hosts = { "acl2.com" },
upstream_url = helpers.mock_upstream_url,
})
assert(helpers.dao.plugins:insert {
name = "acl",
api_id = api2.id,
config = {
whitelist = "admin"
}
})
assert(helpers.dao.plugins:insert {
name = "key-auth",
api_id = api2.id,
config = {}
})
local api3 = assert(helpers.dao.apis:insert {
name = "api-3",
hosts = { "acl3.com" },
upstream_url = helpers.mock_upstream_url,
})
assert(helpers.dao.plugins:insert {
name = "acl",
api_id = api3.id,
config = {
blacklist = {"admin"}
}
})
assert(helpers.dao.plugins:insert {
name = "key-auth",
api_id = api3.id,
config = {}
})
local api4 = assert(helpers.dao.apis:insert {
name = "api-4",
hosts = { "acl4.com" },
upstream_url = helpers.mock_upstream_url,
})
assert(helpers.dao.plugins:insert {
name = "acl",
api_id = api4.id,
config = {
whitelist = {"admin", "pro"}
}
})
assert(helpers.dao.plugins:insert {
name = "key-auth",
api_id = api4.id,
config = {}
})
local api5 = assert(helpers.dao.apis:insert {
name = "api-5",
hosts = { "acl5.com" },
upstream_url = helpers.mock_upstream_url,
})
assert(helpers.dao.plugins:insert {
name = "acl",
api_id = api5.id,
config = {
blacklist = {"admin", "pro"}
}
})
assert(helpers.dao.plugins:insert {
name = "key-auth",
api_id = api5.id,
config = {}
})
local api6 = assert(helpers.dao.apis:insert {
name = "api-6",
hosts = { "acl6.com" },
upstream_url = helpers.mock_upstream_url,
})
assert(helpers.dao.plugins:insert {
name = "acl",
api_id = api6.id,
config = {
blacklist = {"admin", "pro", "hello"}
}
})
assert(helpers.dao.plugins:insert {
name = "key-auth",
api_id = api6.id,
config = {}
})
local api7 = assert(helpers.dao.apis:insert {
name = "api-7",
hosts = { "acl7.com" },
upstream_url = helpers.mock_upstream_url,
})
assert(helpers.dao.plugins:insert {
name = "acl",
api_id = api7.id,
config = {
whitelist = {"admin", "pro", "hello"}
}
})
assert(helpers.dao.plugins:insert {
name = "key-auth",
api_id = api7.id,
config = {}
})
local api8 = assert(helpers.dao.apis:insert {
name = "api-8",
hosts = { "acl8.com" },
upstream_url = helpers.mock_upstream_url,
})
assert(helpers.dao.plugins:insert {
name = "acl",
api_id = api8.id,
config = {
whitelist = {"anonymous"}
}
})
assert(helpers.dao.plugins:insert {
name = "key-auth",
api_id = api8.id,
config = {
anonymous = anonymous.id,
}
})
assert(helpers.start_kong({
nginx_conf = "spec/fixtures/custom_nginx.template",
}))
end)
before_each(function()
client = helpers.proxy_client()
api_client = helpers.admin_client()
end)
after_each(function ()
client:close()
api_client:close()
end)
teardown(function()
helpers.stop_kong()
end)
describe("Mapping to Consumer", function()
it("should work with consumer with credentials", function()
local res = assert(client:send {
method = "GET",
path = "/request?apikey=apikey124",
headers = {
["Host"] = "acl2.com"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.equal("admin", body.headers["x-consumer-groups"])
end)
it("should work with consumer without credentials", function()
local res = assert(client:send {
method = "GET",
path = "/request",
headers = {
["Host"] = "acl8.com"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.equal("anonymous", body.headers["x-consumer-groups"])
end)
end)
describe("Simple lists", function()
it("should fail when an authentication plugin is missing", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
["Host"] = "acl1.com"
}
})
local body = assert.res_status(403, res)
local json = cjson.decode(body)
assert.same({ message = "You cannot consume this service" }, json)
end)
it("should fail when not in whitelist", function()
local res = assert(client:send {
method = "GET",
path = "/status/200?apikey=apikey123",
headers = {
["Host"] = "acl2.com"
}
})
local body = assert.res_status(403, res)
local json = cjson.decode(body)
assert.same({ message = "You cannot consume this service" }, json)
end)
it("should work when in whitelist", function()
local res = assert(client:send {
method = "GET",
path = "/request?apikey=apikey124",
headers = {
["Host"] = "acl2.com"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.equal("admin", body.headers["x-consumer-groups"])
end)
it("should work when not in blacklist", function()
local res = assert(client:send {
method = "GET",
path = "/request?apikey=apikey123",
headers = {
["Host"] = "acl3.com"
}
})
assert.res_status(200, res)
end)
it("should fail when in blacklist", function()
local res = assert(client:send {
method = "GET",
path = "/request?apikey=apikey124",
headers = {
["Host"] = "acl3.com"
}
})
local body = assert.res_status(403, res)
local json = cjson.decode(body)
assert.same({ message = "You cannot consume this service" }, json)
end)
end)
describe("Multi lists", function()
it("should work when in whitelist", function()
local res = assert(client:send {
method = "GET",
path = "/request?apikey=apikey125",
headers = {
["Host"] = "acl4.com"
}
})
local body = cjson.decode(assert.res_status(200, res))
assert.True(body.headers["x-consumer-groups"] == "pro, hello" or body.headers["x-consumer-groups"] == "hello, pro")
end)
it("should fail when not in whitelist", function()
local res = assert(client:send {
method = "GET",
path = "/request?apikey=apikey126",
headers = {
["Host"] = "acl4.com"
}
})
local body = assert.res_status(403, res)
local json = cjson.decode(body)
assert.same({ message = "You cannot consume this service" }, json)
end)
it("should fail when in blacklist", function()
local res = assert(client:send {
method = "GET",
path = "/request?apikey=apikey125",
headers = {
["Host"] = "acl5.com"
}
})
local body = assert.res_status(403, res)
local json = cjson.decode(body)
assert.same({ message = "You cannot consume this service" }, json)
end)
it("should work when not in blacklist", function()
local res = assert(client:send {
method = "GET",
path = "/request?apikey=apikey126",
headers = {
["Host"] = "acl5.com"
}
})
assert.res_status(200, res)
end)
it("should not work when one of the ACLs in the blacklist", function()
local res = assert(client:send {
method = "GET",
path = "/request?apikey=apikey126",
headers = {
["Host"] = "acl6.com"
}
})
local body = assert.res_status(403, res)
local json = cjson.decode(body)
assert.same({ message = "You cannot consume this service" }, json)
end)
it("should work when one of the ACLs in the whitelist", function()
local res = assert(client:send {
method = "GET",
path = "/request?apikey=apikey126",
headers = {
["Host"] = "acl7.com"
}
})
assert.res_status(200, res)
end)
it("should not work when at least one of the ACLs in the blacklist", function()
local res = assert(client:send {
method = "GET",
path = "/request?apikey=apikey125",
headers = {
["Host"] = "acl6.com"
}
})
local body = assert.res_status(403, res)
local json = cjson.decode(body)
assert.same({ message = "You cannot consume this service" }, json)
end)
end)
describe("Real-world usage", function()
it("should not fail when multiple rules are set fast", function()
-- Create consumer
local res = assert(api_client:send {
method = "POST",
path = "/consumers/",
headers = {
["Content-Type"] = "application/json"
},
body = {
username = "acl_consumer"
}
})
local body = cjson.decode(assert.res_status(201, res))
local consumer_id = body.id
-- Create key
local res = assert(api_client:send {
method = "POST",
path = "/consumers/acl_consumer/key-auth/",
headers = {
["Content-Type"] = "application/json"
},
body = {
key = "secret123"
}
})
assert.res_status(201, res)
for i = 1, 3 do
-- Create API
local res = assert(api_client:send {
method = "POST",
path = "/apis/",
headers = {
["Content-Type"] = "application/json"
},
body = {
name = "acl_test" .. i,
hosts = { "acl_test" .. i .. ".com" },
upstream_url = helpers.mock_upstream_url,
},
})
assert.res_status(201, res)
-- Add the ACL plugin to the new API with the new group
local res = assert(api_client:send {
method = "POST",
path = "/apis/acl_test" .. i .. "/plugins/",
headers = {
["Content-Type"] = "application/json"
},
body = {
name = "acl",
["config.whitelist"] = "admin" .. i
}
})
assert.res_status(201, res)
-- Add key-authentication to API
local res = assert(api_client:send {
method = "POST",
path = "/apis/acl_test" .. i .. "/plugins/",
headers = {
["Content-Type"] = "application/json"
},
body = {
name = "key-auth"
}
})
assert.res_status(201, res)
-- Add a new group the the consumer
local res = assert(api_client:send {
method = "POST",
path = "/consumers/acl_consumer/acls/",
headers = {
["Content-Type"] = "application/json"
},
body = {
group = "admin" .. i
}
})
assert.res_status(201, res)
-- Wait for cache to be invalidated
local cache_key = helpers.dao.acls:cache_key(consumer_id)
helpers.wait_until(function()
local res = assert(api_client:send {
method = "GET",
path = "/cache/" .. cache_key
})
res:read_body()
return res.status == 404
end, 5)
-- Make the request, and it should work
local res
helpers.wait_until(function()
res = assert(client:send {
method = "GET",
path = "/status/200?apikey=secret123",
headers = {
["Host"] = "acl_test" .. i .. ".com"
}
})
res:read_body()
return res.status ~= 404
end, 5)
assert.res_status(200, res)
end
end)
end)
end)
| apache-2.0 |
greasydeal/darkstar | scripts/zones/PsoXja/npcs/_095.lua | 8 | 1608 | -----------------------------------
-- Area: Pso'Xja
-- NPC: _095 (Stone Gate)
-- Notes: Spawns Gargoyle when triggered
-- @pos -330.000 14.074 -261.600 9
-----------------------------------
package.loaded["scripts/zones/PsoXja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/PsoXja/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local X=player:getXPos();
if (npc:getAnimation() == 9) then
if(X >= 299)then
if(GetMobAction(16814086) == 0) then
local Rand = math.random(1,10);
if (Rand <=9) then -- Spawn Gargoyle
player:messageSpecial(TRAP_ACTIVATED);
SpawnMob(16814086,120):updateClaim(player); -- Gargoyle
else
player:messageSpecial(TRAP_FAILS);
npc:openDoor(30);
end
else
player:messageSpecial(DOOR_LOCKED);
end
elseif(X <= 298)then
player:startEvent(0x001A);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if(csid == 0x001A and option == 1) then
player:setPos(260,-0.25,-20,254,111);
end
end; | gpl-3.0 |
gaohuang/SnapshotEnsemble | main_snapshot_ensemble.lua | 1 | 2735 | --
-- Copyright (c) 2016, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- Code modified for Snapshot Ensembles by Gao Huang
require 'torch'
require 'paths'
require 'optim'
require 'nn'
local DataLoader = require 'dataloader'
local models = require 'models/init'
local Trainer = require 'train'
local EnsembleTester = require 'test_ensemble'
local opts = require 'opts'
local checkpoints = require 'checkpoints'
torch.setdefaulttensortype('torch.FloatTensor')
torch.setnumthreads(1)
local opt = opts.parse(arg)
torch.manualSeed(opt.manualSeed)
cutorch.manualSeedAll(opt.manualSeed)
-- Load previous checkpoint, if it exists
local checkpoint, optimState = checkpoints.latest(opt)
-- Create model
local model, criterion = models.setup(opt, checkpoint)
-- Data loading
local trainLoader, valLoader = DataLoader.create(opt)
-- The trainer handles the training loop and evaluation on validation set
local trainer = Trainer(model, criterion, opt, optimState)
if opt.testOnly then
local top1Err, top5Err = trainer:test(0, valLoader)
print(string.format(' * Results top1: %6.3f top5: %6.3f', top1Err, top5Err))
return
end
local startEpoch = checkpoint and checkpoint.epoch + 1 or opt.epochNumber
local bestTop1 = math.huge
local bestTop5 = math.huge
for epoch = startEpoch, opt.nEpochs do
-- Train for a single epoch
local trainTop1, trainTop5, trainLoss = trainer:train(epoch, trainLoader)
-- Run model on validation set
local testTop1, testTop5 = trainer:test(epoch, valLoader)
local bestModel = false
if testTop1 < bestTop1 then
bestModel = true
bestTop1 = testTop1
bestTop5 = testTop5
print(' * Best model ', testTop1, testTop5)
end
checkpoints.save(epoch, model, trainer.optimState, bestModel, opt)
end
-- Test Snapshot Ensembles
local model_ensemble_fw = {}
local model_ensemble_bw = {}
for cycle = 1, opt.nCycles do
local idx = (cycle == opt.nCycles) and opt.nEpochs or cycle * torch.floor(opt.nEpochs / opt.nCycles)
model_ensemble_fw[#model_ensemble_fw+1] = torch.load(opt.save..'/model_'..idx..'.t7')
model_ensemble_bw[opt.nCycles-cycle+1] = model_ensemble_fw[#model_ensemble_fw]
end
local tester_fw = EnsembleTester(model_ensemble_fw, opt)
local SingleTop1_fw, SingleTop5_fw, EnsembleTop1Evolve_fw, EnsembleTop5Evolove_fw = tester_fw:test(valLoader)
local tester_bw = EnsembleTester(model_ensemble_bw, opt)
local SingleTop1_bw, SingleTop5_bw, EnsembleTop1Evolve_bw, EnsembleTop5Evolove_bw = tester_bw:test(valLoader)
| bsd-3-clause |
LegionXI/darkstar | scripts/zones/West_Sarutabaruta/npcs/Cavernous_Maw.lua | 29 | 1467 | -----------------------------------
-- Area: West Sarutabaruta
-- NPC: Cavernous Maw
-- Teleports Players to West Sarutabaruta [S]
-- @pos -2.229 0.001 -162.715 115
-----------------------------------
package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/teleports");
require("scripts/globals/campaign");
require("scripts/zones/West_Sarutabaruta/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) and hasMawActivated(player,8)) then
player:startEvent(0x0388);
else
player:messageSpecial(NOTHING_HAPPENS);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0388 and option == 1) then
toMaw(player,7);
end
end; | gpl-3.0 |
LegionXI/darkstar | scripts/zones/Port_Windurst/Zone.lua | 12 | 2515 | -----------------------------------
--
-- Zone: Port_Windurst (240)
--
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/globals/zone");
require("scripts/globals/settings");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
SetExplorerMoogles(17760450);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
-- FIRST LOGIN (START CS)
if (player:getPlaytime(false) == 0) then
if (OPENING_CUTSCENE_ENABLE == 1) then
cs = 0x0131;
end
player:setPos(-120,-5.5,175,48);
player:setHomePoint();
end
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
if (prevZone == 225) then
cs = 0x2714;
player:setPos(228.000, -3.000, 76.000, 160);
else
position = math.random(1,5) + 195;
player:setPos(position,-15.56,258,65);
if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then
cs = 0x7534;
end
player:setVar("PlayerMainJob",0);
end
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onTransportEvent
-----------------------------------
function onTransportEvent(player,transport)
player:startEvent(0x2712);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- print("RESULT: ",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0131) then
player:messageSpecial(ITEM_OBTAINED,536);
elseif (csid == 0x2712) then
player:setPos(0,0,0,0,225);
elseif (csid == 0x7534 and option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
end
end;
| gpl-3.0 |
greasydeal/darkstar | scripts/globals/items/prime_beef_stewpot.lua | 36 | 1890 | -----------------------------------------
-- ID: 5548
-- Item: Prime Beef Stewpot
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP +10% Cap 75
-- MP +15
-- Strength +2
-- Agility +1
-- Mind +1
-- HP Recovered while healing +7
-- MP Recovered while healing +2
-- Attack 18% Cap 60
-- Evasion +6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5548);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 10);
target:addMod(MOD_FOOD_HP_CAP, 75);
target:addMod(MOD_MP, 15);
target:addMod(MOD_STR, 2);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_MND, 1);
target:addMod(MOD_HPHEAL, 7);
target:addMod(MOD_MPHEAL, 2);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 60);
target:addMod(MOD_EVA, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 10);
target:delMod(MOD_FOOD_HP_CAP, 75);
target:delMod(MOD_MP, 15);
target:delMod(MOD_STR, 2);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_MND, 1);
target:delMod(MOD_HPHEAL, 7);
target:delMod(MOD_MPHEAL, 2);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 60);
target:delMod(MOD_EVA, 6);
end;
| gpl-3.0 |
greasydeal/darkstar | scripts/globals/items/plate_of_ikra_gunkan_+1.lua | 35 | 1733 | -----------------------------------------
-- ID: 5220
-- Item: plate_of_ikra_gunkan_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 30
-- Magic 12
-- Dexterity 3
-- Mind -1
-- Accuracy % 17
-- Accuracy Cap 30
-- Ranged ACC % 17
-- Ranged ACC Cap 30
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5220);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 30);
target:addMod(MOD_MP, 12);
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -1);
target:addMod(MOD_FOOD_ACCP, 17);
target:addMod(MOD_FOOD_ACC_CAP, 30);
target:addMod(MOD_FOOD_RACCP, 17);
target:addMod(MOD_FOOD_RACC_CAP, 30);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 30);
target:delMod(MOD_MP, 12);
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -1);
target:delMod(MOD_FOOD_ACCP, 17);
target:delMod(MOD_FOOD_ACC_CAP, 30);
target:delMod(MOD_FOOD_RACCP, 17);
target:delMod(MOD_FOOD_RACC_CAP, 30);
end;
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/Windurst_Woods/npcs/Abby_Jalunshi.lua | 38 | 1042 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Abby Jalunshi
-- Type: Moghouse Renter
-- @zone: 241
-- @pos -101.895 -5 36.172
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x031e);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/Port_San_dOria/npcs/Deguerendars.lua | 36 | 2054 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Deguerendars
-- Only sells when San d'Oria contrls Tavnazian Archipelago
-- Only available to those with CoP Ch. 4.1 or higher
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(TAVNAZIANARCH);
cop = 40; --player:getVar("chainsOfPromathiaMissions");
if (cop >= 40) then
if (RegionOwner ~= SANDORIA) then
player:showText(npc,DEGUERENDARS_CLOSED_DIALOG);
else
player:showText(npc,DEGUERENDARS_OPEN_DIALOG);
stock = {0x05f3,290, --Apple Mint
0x142c,1945, --Ground Wasabi
0x426d,99, --Lufaise Fly
0x144b,233} --Misareaux Parsley
showShop(player,SANDORIA,stock);
end
else
player:showText(npc,DEGUERENDARS_COP_NOT_COMPLETED);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
everhopingandwaiting/telegram-bot | plugins/banhammer.lua | 22 | 5639 | local function is_user_whitelisted(id)
local hash = 'whitelist:user#id'..id
local white = redis:get(hash) or false
return white
end
local function is_chat_whitelisted(id)
local hash = 'whitelist:chat#id'..id
local white = redis:get(hash) or false
return white
end
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
local function ban_user(user_id, chat_id)
-- Save to redis
local hash = 'banned:'..chat_id..':'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function is_banned(user_id, chat_id)
local hash = 'banned:'..chat_id..':'..user_id
local banned = redis:get(hash)
return banned or false
end
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat
if action == 'chat_add_user' or action == 'chat_add_user_link' then
local user_id
if msg.action.link_issuer then
user_id = msg.from.id
else
user_id = msg.action.user.id
end
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned then
print('User is banned!')
kick_user(user_id, msg.to.id)
end
end
-- No further checks
return msg
end
-- BANNED USER TALKING
if msg.to.type == 'chat' then
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned then
print('Banned user talking!')
ban_user(user_id, chat_id)
msg.text = ''
end
end
-- WHITELIST
local hash = 'whitelist:enabled'
local whitelist = redis:get(hash)
local issudo = is_sudo(msg)
-- Allow all sudo users even if whitelist is allowed
if whitelist and not issudo then
print('Whitelist enabled and not sudo')
-- Check if user or chat is whitelisted
local allowed = is_user_whitelisted(msg.from.id)
if not allowed then
print('User '..msg.from.id..' not whitelisted')
if msg.to.type == 'chat' then
allowed = is_chat_whitelisted(msg.to.id)
if not allowed then
print ('Chat '..msg.to.id..' not whitelisted')
else
print ('Chat '..msg.to.id..' whitelisted :)')
end
end
else
print('User '..msg.from.id..' allowed :)')
end
if not allowed then
msg.text = ''
end
else
print('Whitelist not enabled or is sudo')
end
return msg
end
local function run(msg, matches)
-- Silent ignore
if not is_sudo(msg) then
return nil
end
if matches[1] == 'ban' then
local user_id = matches[3]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if matches[2] == 'user' then
ban_user(user_id, chat_id)
return 'User '..user_id..' banned'
end
if matches[2] == 'delete' then
local hash = 'banned:'..chat_id..':'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'kick' then
if msg.to.type == 'chat' then
kick_user(matches[2], msg.to.id)
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'whitelist' then
if matches[2] == 'enable' then
local hash = 'whitelist:enabled'
redis:set(hash, true)
return 'Enabled whitelist'
end
if matches[2] == 'disable' then
local hash = 'whitelist:enabled'
redis:del(hash)
return 'Disabled whitelist'
end
if matches[2] == 'user' then
local hash = 'whitelist:user#id'..matches[3]
redis:set(hash, true)
return 'User '..msg.from.id..' whitelisted'
end
if matches[2] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:set(hash, true)
return 'Chat '..msg.to.id..' whitelisted'
end
if matches[2] == 'delete' and matches[3] == 'user' then
local hash = 'whitelist:user#id'..matches[4]
redis:del(hash)
return 'User '..matches[4]..' removed from whitelist'
end
if matches[2] == 'delete' and matches[3] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:del(hash)
return 'Chat '..msg.to.id..' removed from whitelist'
end
end
end
return {
description = "Plugin to manage bans, kicks and white/black lists.",
usage = {
"!whitelist <enable>/<disable>: Enable or disable whitelist mode",
"!whitelist user <user_id>: Allow user to use the bot when whitelist mode is enabled",
"!whitelist chat: Allow everybody on current chat to use the bot when whitelist mode is enabled",
"!whitelist delete user <user_id>: Remove user from whitelist",
"!whitelist delete chat: Remove chat from whitelist",
"!ban user <user_id>: Kick user from chat and kicks it if joins chat again",
"!ban delete <user_id>: Unban user",
"!kick <user_id> Kick user from chat group"
},
patterns = {
"^!(whitelist) (enable)$",
"^!(whitelist) (disable)$",
"^!(whitelist) (user) (%d+)$",
"^!(whitelist) (chat)$",
"^!(whitelist) (delete) (user) (%d+)$",
"^!(whitelist) (delete) (chat)$",
"^!(ban) (user) (%d+)$",
"^!(ban) (delete) (%d+)$",
"^!(kick) (%d+)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
Igalia/snabbswitch | lib/luajit/testsuite/test/lib/string/lower_upper.lua | 6 | 1040 | do --- smoke
assert(("abc123DEF_<>"):lower() == "abc123def_<>")
assert(("abc123DEF_<>"):upper() == "ABC123DEF_<>")
end
do --- repeated
local l = "the quick brown fox..."
local u = "THE QUICK BROWN FOX..."
local s = l
for i = 1, 75 do
s = s:upper()
assert(s == u)
s = s:lower()
assert(s == l)
end
end
do --- repeated with growing string
local y, z
local x = "aBcDe"
for i=1,100 do
y = string.upper(x)
z = y.."fgh"
end
assert(y == "ABCDE")
assert(z == "ABCDEfgh")
end
do --- misc upper
local y
for i=1,100 do y = string.upper("aBc9") end
assert(y == "ABC9")
local x = ":abCd+"
for i=1,100 do y = string.upper(x) end
assert(y == ":ABCD+")
x = 1234
for i=1,100 do y = string.upper(x) end
assert(y == "1234")
end
do --- misc lower
local y
for i=1,100 do y = string.lower("aBc9") end
assert(y == "abc9")
local x = ":abcd+"
for i=1,100 do y = string.lower(x) end
assert(y == ":abcd+")
x = 1234
for i=1,100 do y = string.lower(x) end
assert(y == "1234")
end
| apache-2.0 |
greasydeal/darkstar | scripts/globals/items/cluster_of_paprika.lua | 36 | 1233 | -----------------------------------------
-- ID: 5740
-- Item: Cluster of Paprika
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility 1
-- Vitality -3
-- Defense -1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5740);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 1);
target:addMod(MOD_VIT, -3);
target:addMod(MOD_DEF, -1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 1);
target:delMod(MOD_VIT, -3);
target:delMod(MOD_DEF, -1);
end;
| gpl-3.0 |
naclander/tome | game/modules/tome/data/gfx/particles/snowing.lua | 3 | 1570 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
dir = dir or math.rad(110)
factor = factor or 1
r = r or 1
g = g or 1
b = b or 1
rv = rv or 1
gv = gv or 1
bv = bv or 1
return { generator = function()
local x, y = rng.range(-width/2, width), rng.range(-height/2, height)
local vel = rng.float(5, 20)
local dir = dir + math.rad(rng.float(-10, 10))
return {
trail = 0,
life = 30,
size = rng.float(9, 12), sizev = 0, sizea = 0,
x = x, xv = 0, xa = 0,
y = y, yv = 0, ya = 0,
dir = dir, dirv = blur, dira = 0,
vel = vel, velv = 0, vela = 0,
r = r, rv = rv, ra = 0,
g = g, gv = gv, ga = 0,
b = b, bv = bv, ba = 0,
a = rng.float(0.6, 0.9), av = 0, aa = 0,
}
end, },
function(self)
if first then
self.ps:emit(700 * factor)
else
self.ps:emit(2 * factor)
end
first = false
end,
1000 * factor,
"weather/snowflake"
| gpl-3.0 |
greasydeal/darkstar | scripts/zones/Northern_San_dOria/npcs/_6fc.lua | 2 | 1891 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Papal Chambers
-- Finish Mission: The Davoi Report
-- @pos 131 -11 122 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
package.loaded["scripts/globals/missions"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/keyitems");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getCurrentMission(SANDORIA) == THE_DAVOI_REPORT and player:hasKeyItem(TEMPLE_KNIGHTS_DAVOI_REPORT)) then
player:startEvent(0x02b7); -- Finish Mission "The Davoi Report"
elseif(player:getCurrentMission(SANDORIA) == PRESTIGE_OF_THE_PAPSQUE and player:getVar("MissionStatus") == 0) then
player:startEvent(0x0007);
elseif(player:getCurrentMission(SANDORIA) == PRESTIGE_OF_THE_PAPSQUE and player:getVar("MissionStatus") == 1) then
player:startEvent(0x0009);
elseif(player:getCurrentMission(SANDORIA) == PRESTIGE_OF_THE_PAPSQUE and player:hasKeyItem(ANCIENT_SANDORIAN_TABLET)) then
player:startEvent(0x0008);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x02b7 or csid == 0x0007 or csid == 0x0008) then
finishMissionTimeline(player,3,csid,option);
end
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.