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
HenrytheSlav/OpenRA
lua/sandbox.lua
84
5098
local sandbox = { _VERSION = "sandbox 0.5", _DESCRIPTION = "A pure-lua solution for running untrusted Lua code.", _URL = "https://github.com/kikito/sandbox.lua", _LICENSE = [[ MIT LICENSE Copyright (c) 2013 Enrique García Cota Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] } -- The base environment is merged with the given env option (or an empty table, if no env provided) -- local BASE_ENV = {} -- List of non-safe packages/functions: -- -- * string.rep: can be used to allocate millions of bytes in 1 operation -- * {set|get}metatable: can be used to modify the metatable of global objects (strings, integers) -- * collectgarbage: can affect performance of other systems -- * dofile: can access the server filesystem -- * _G: It has access to everything. It can be mocked to other things though. -- * load{file|string}: All unsafe because they can grant acces to global env -- * raw{get|set|equal}: Potentially unsafe -- * module|require|module: Can modify the host settings -- * string.dump: Can display confidential server info (implementation of functions) -- * string.rep: Can allocate millions of bytes in one go -- * math.randomseed: Can affect the host sytem -- * io.*, os.*: Most stuff there is non-save -- Safe packages/functions below ([[ _VERSION assert error ipairs next pairs pcall select tonumber tostring type unpack xpcall coroutine.create coroutine.resume coroutine.running coroutine.status coroutine.wrap coroutine.yield math.abs math.acos math.asin math.atan math.atan2 math.ceil math.cos math.cosh math.deg math.exp math.fmod math.floor math.frexp math.huge math.ldexp math.log math.log10 math.max math.min math.modf math.pi math.pow math.rad math.sin math.sinh math.sqrt math.tan math.tanh os.clock os.difftime os.time string.byte string.char string.find string.format string.gmatch string.gsub string.len string.lower string.match string.reverse string.sub string.upper table.insert table.maxn table.remove table.sort ]]):gsub('%S+', function(id) local module, method = id:match('([^%.]+)%.([^%.]+)') if module then BASE_ENV[module] = BASE_ENV[module] or {} BASE_ENV[module][method] = _G[module][method] else BASE_ENV[id] = _G[id] end end) local function protect_module(module, module_name) return setmetatable({}, { __index = module, __newindex = function(_, attr_name, _) error('Can not modify ' .. module_name .. '.' .. attr_name .. '. Protected by the sandbox.') end }) end ('coroutine math os string table'):gsub('%S+', function(module_name) BASE_ENV[module_name] = protect_module(BASE_ENV[module_name], module_name) end) -- auxiliary functions/variables local string_rep = string.rep local function merge(dest, source) for k,v in pairs(source) do dest[k] = dest[k] or v end return dest end local function sethook(f, key, quota) if type(debug) ~= 'table' or type(debug.sethook) ~= 'function' then return end debug.sethook(f, key, quota) end local function cleanup() sethook() string.rep = string_rep end -- Public interface: sandbox.protect function sandbox.protect(f, options) if type(f) == 'string' then f = assert(loadstring(f)) end options = options or {} local quota = false if options.quota ~= false then quota = options.quota or 500000 end local env = merge(options.env or {}, BASE_ENV) env._G = env._G or env setfenv(f, env) return function(...) if quota then local timeout = function() cleanup() error('Quota exceeded: ' .. tostring(quota)) end sethook(timeout, "", quota) end string.rep = nil local ok, result = pcall(f, ...) cleanup() if not ok then error(result) end return result end end -- Public interface: sandbox.run function sandbox.run(f, options, ...) return sandbox.protect(f, options)(...) end -- make sandbox(f) == sandbox.protect(f) setmetatable(sandbox, {__call = function(_,f,o) return sandbox.protect(f,o) end}) return sandbox
gpl-3.0
jxlczjp77/skynet
lualib/http/httpd.lua
101
3708
local internal = require "http.internal" local table = table local string = string local type = type local httpd = {} local http_status_msg = { [100] = "Continue", [101] = "Switching Protocols", [200] = "OK", [201] = "Created", [202] = "Accepted", [203] = "Non-Authoritative Information", [204] = "No Content", [205] = "Reset Content", [206] = "Partial Content", [300] = "Multiple Choices", [301] = "Moved Permanently", [302] = "Found", [303] = "See Other", [304] = "Not Modified", [305] = "Use Proxy", [307] = "Temporary Redirect", [400] = "Bad Request", [401] = "Unauthorized", [402] = "Payment Required", [403] = "Forbidden", [404] = "Not Found", [405] = "Method Not Allowed", [406] = "Not Acceptable", [407] = "Proxy Authentication Required", [408] = "Request Time-out", [409] = "Conflict", [410] = "Gone", [411] = "Length Required", [412] = "Precondition Failed", [413] = "Request Entity Too Large", [414] = "Request-URI Too Large", [415] = "Unsupported Media Type", [416] = "Requested range not satisfiable", [417] = "Expectation Failed", [500] = "Internal Server Error", [501] = "Not Implemented", [502] = "Bad Gateway", [503] = "Service Unavailable", [504] = "Gateway Time-out", [505] = "HTTP Version not supported", } local function readall(readbytes, bodylimit) local tmpline = {} local body = internal.recvheader(readbytes, tmpline, "") if not body then return 413 -- Request Entity Too Large end local request = assert(tmpline[1]) local method, url, httpver = request:match "^(%a+)%s+(.-)%s+HTTP/([%d%.]+)$" assert(method and url and httpver) httpver = assert(tonumber(httpver)) if httpver < 1.0 or httpver > 1.1 then return 505 -- HTTP Version not supported end local header = internal.parseheader(tmpline,2,{}) if not header then return 400 -- Bad request end local length = header["content-length"] if length then length = tonumber(length) end local mode = header["transfer-encoding"] if mode then if mode ~= "identity" and mode ~= "chunked" then return 501 -- Not Implemented end end if mode == "chunked" then body, header = internal.recvchunkedbody(readbytes, bodylimit, header, body) if not body then return 413 end else -- identity mode if length then if bodylimit and length > bodylimit then return 413 end if #body >= length then body = body:sub(1,length) else local padding = readbytes(length - #body) body = body .. padding end end end return 200, url, method, header, body end function httpd.read_request(...) local ok, code, url, method, header, body = pcall(readall, ...) if ok then return code, url, method, header, body else return nil, code end end local function writeall(writefunc, statuscode, bodyfunc, header) local statusline = string.format("HTTP/1.1 %03d %s\r\n", statuscode, http_status_msg[statuscode] or "") writefunc(statusline) if header then for k,v in pairs(header) do if type(v) == "table" then for _,v in ipairs(v) do writefunc(string.format("%s: %s\r\n", k,v)) end else writefunc(string.format("%s: %s\r\n", k,v)) end end end local t = type(bodyfunc) if t == "string" then writefunc(string.format("content-length: %d\r\n\r\n", #bodyfunc)) writefunc(bodyfunc) elseif t == "function" then writefunc("transfer-encoding: chunked\r\n") while true do local s = bodyfunc() if s then if s ~= "" then writefunc(string.format("\r\n%x\r\n", #s)) writefunc(s) end else writefunc("\r\n0\r\n\r\n") break end end else assert(t == "nil") writefunc("\r\n") end end function httpd.write_response(...) return pcall(writeall, ...) end return httpd
mit
gameover5545/maxrobot
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
Madex234/TeleSeed
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
tederis/mta-resources
snowmode/projection.lua
1
10173
--if true then return end local sw, sh = guiGetScreenSize ( ) local shader local screenSource = dxCreateScreenSource ( sw, sh ) local streamedInProjectors = { } local sectorMatrix = { { -1, 1 }, { 0, 1 }, { 1, 1 }, { -1, 0 }, { 0, 0 }, { 1, 0 }, { -1, -1 }, { 0, -1 }, { 1, -1 } } streamedInSectors = { } addEventHandler ( "onClientRender", root, function ( ) TextureProjector.update ( ) --local x, y, z = getElementPosition ( localPlayer ) --xrStreamerWorld.update ( ) --[[local sx, sy = -3000, 3000 local relx, rely = ( x - sx ) / 6000, ( sy - y ) / 6000 local texx, texy = relx * 1024, rely * 1024 dxSetRenderTarget ( g_Rt, false ) dxDrawRectangle ( texx - 1, texy - 1, 3, 3, tocolor ( 255, 0, 0 ) ) dxSetRenderTarget ( )]] end ) addEventHandler ( "onClientResourceStart", resourceRoot, function ( ) --xrStreamerWorld.init ( ) g_Rt2 = dxCreateTexture ( "snowmap.dds" ) --g_Rt = dxCreateRenderTarget ( 1024, 1024, false ) proj = TextureProjector.create ( 0, 0, 0, loadedTextures.single ) proj:setMaterial ( g_Rt2 ) end , false ) TextureProjector = { items = { } } TextureProjector.__index = TextureProjector function TextureProjector.create ( x, y, z, texture ) local texProj = { x = x, y = y, z = z, shader = dxCreateShader ( "shaders/projection.fx", 0, 0, false, "world" ) } texProj.viewPoint = ViewPoint:new ( ) texProj.viewPoint:setPosition ( x, y, z ) texProj.viewPoint:setLookAt ( x, y, z ) texProj.viewPoint:setRotation ( 0, 0, 0 ) texProj.viewPoint:generateViewMatrix ( ) --texProj.viewPoint:setProjectionParameters ( math.rad ( 180 - 90 ), 1, 1, 100 ) texProj.viewPoint:generateProjectionMatrix ( ) dxSetShaderValue ( texProj.shader, "lightView", texProj.viewPoint.viewMatrix ) dxSetShaderValue ( texProj.shader, "lightProj", texProj.viewPoint.projectionMatrix ) dxSetShaderValue ( texProj.shader, "snowTex", texture ) for _, shader in ipairs ( readyShaders ) do dxSetShaderValue ( shader, "lightView", texProj.viewPoint.viewMatrix ) dxSetShaderValue ( shader, "lightProj", texProj.viewPoint.projectionMatrix ) dxSetShaderValue ( shader, "Tex0", g_Rt2 ) end setShaderPrelight ( texProj.shader ) --engineApplyShaderToWorldTexture ( texProj.shader, "*" ) TextureProjector.items [ texProj ] = true setmetatable ( texProj, TextureProjector ) return texProj end function TextureProjector:destroy ( ) TextureProjector.items [ self ] = nil destroyElement ( self.shader ) end function TextureProjector:setMatrix ( x, y, z, rx, ry, rz ) self.viewPoint:setPosition ( x, y, z ) self.viewPoint:setRotation ( rx, ry, rz ) self.viewPoint:generateViewMatrix ( ) dxSetShaderValue ( self.shader, "lightView", self.viewPoint.viewMatrix ) dxSetShaderValue ( self.shader, "lightProj", self.viewPoint.projectionMatrix ) end function TextureProjector:setMaterial ( material ) self.material = material dxSetShaderValue ( self.shader, "Tex0", material ) end function TextureProjector:draw ( ) self.viewPoint:debugDraw ( ) end local stbl = { { 0, 0 }, { 1, 0 }, { 2, 0 }, { 0, 1 }, { 1, 1 }, { 2, 1 }, { 0, 2 }, { 1, 2 }, { 2, 2 } } function TextureProjector.update ( ) for texProj, _ in pairs ( TextureProjector.items ) do texProj:draw ( ) end if sector == nil then return end local picPos = { x = 500, y = 200 } local picSize = 200 dxDrawRectangle ( picPos.x, picPos.y, picSize * 3, picSize * 3, tocolor ( 0, 0, 0, 150 ) ) for i = 1, 9 do local sector = streamedInSectors [ i ] local off = stbl [ i ] local x, y = picPos.x + ( picSize * off [ 1 ] ), picPos.y + ( picSize * off [ 2 ] ) dxDrawImage ( x, y, picSize, picSize, sector.texture ) dxDrawText ( sector.column .. ", " ..sector.row, x, y ) end end function D3DXMatrixPerspectiveFovLH ( fovy, aspect, zn, zf ) local pout = D3DXMatrixIdentity ( ) -- [ 0 ] = { 0, 1, 2, 3 }, -- [ 1 ] = { 0, 1, 2, 3 }, -- [ 2 ] = { 0, 1, 2, 3 }, -- [ 3 ] = { 0, 1, 2, 3 } pout [ 1 ] = 1 / (aspect * math.tan(fovy/2)) pout [ 6 ] = 1 / math.tan(fovy/2) pout [ 11 ] = zf / (zf - zn) pout [ 12 ] = 1 pout [ 15 ] = (zf * zn) / (zn - zf) pout [ 16 ] = 0 return pout end function D3DXMatrixOrthoOffCenterLH ( l, r, b, t, zn, zf ) local pout = { 2/(r-l), 0, 0, 0, 0, 2/(t-b), 0, 0, 0, 0, 1/(zf-zn), 0, (l+r)/(l-r), (t+b)/(b-t), zn/(zn-zf), 1 } return pout end function D3DXMatrixLookAtLH ( peye, pat, pup ) local vec2 = pat:SubV ( peye ) vec2:Normalize ( ) local right = pup:CrossV ( vec2 ) local up = vec2:CrossV ( right ) right:Normalize ( ) up:Normalize ( ) local pout = { right.x, up.x, vec2.x, 0, right.y, up.y, vec2.y, 0, right.z, up.z, vec2.z, 0, -right:Dot ( peye ), -up:Dot ( peye ), -vec2:Dot ( peye ), 1 } return pout end function D3DXMatrixIdentity ( ) local matrix = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 } return matrix end function D3DXMatrixRotationYawPitchRoll(yaw, pitch, roll) local sroll = math.sin(roll); local croll = math.cos(roll); local spitch = math.sin(pitch); local cpitch = math.cos(pitch); local syaw = math.sin(yaw); local cyaw = math.cos(yaw); local out = { } -- [ 0 ] = { 0, 1, 2, 3 }, -- [ 1 ] = { 0, 1, 2, 3 }, -- [ 2 ] = { 0, 1, 2, 3 }, -- [ 3 ] = { 0, 1, 2, 3 } --[[out->u.m[0][0] = sroll * spitch * syaw + croll * cyaw; out->u.m[0][1] = sroll * cpitch; out->u.m[0][2] = sroll * spitch * cyaw - croll * syaw; out->u.m[0][3] = 0.0; out->u.m[1][0] = croll * spitch * syaw - sroll * cyaw; out->u.m[1][1] = croll * cpitch; out->u.m[1][2] = croll * spitch * cyaw + sroll * syaw; out->u.m[1][3] = 0.0; out->u.m[2][0] = cpitch * syaw; out->u.m[2][1] = -spitch; out->u.m[2][2] = cpitch * cyaw; out->u.m[2][3] = 0.0; out->u.m[3][0] = 0.0; out->u.m[3][1] = 0.0; out->u.m[3][2] = 0.0; out->u.m[3][3] = 1.0;]] out [ 1 ] = sroll * spitch * syaw + croll * cyaw; out [ 2 ] = sroll * cpitch; out [ 3 ] = sroll * spitch * cyaw - croll * syaw; out [ 4 ] = 0.0; out [ 5 ] = croll * spitch * syaw - sroll * cyaw; out [ 6 ] = croll * cpitch; out [ 7 ] = croll * spitch * cyaw + sroll * syaw; out [ 8 ] = 0.0; out [ 9 ] = cpitch * syaw; out [ 10 ] = -spitch; out [ 11 ] = cpitch * cyaw; out [ 12 ] = 0.0; out [ 13 ] = 0.0; out [ 14 ] = 0.0; out [ 15 ] = 0.0; out [ 16 ] = 1.0; return out end Vector3D = { new = function(self, _x, _y, _z) local newVector = { x = _x or 0.0, y = _y or 0.0, z = _z or 0.0 } return setmetatable(newVector, { __index = Vector3D }) end, Copy = function(self) return Vector3D:new(self.x, self.y, self.z) end, Normalize = function(self) local mod = self:Module() self.x = self.x / mod self.y = self.y / mod self.z = self.z / mod end, Dot = function(self, V) return self.x * V.x + self.y * V.y + self.z * V.z end, Module = function(self) return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z) end, AddV = function(self, V) return Vector3D:new(self.x + V.x, self.y + V.y, self.z + V.z) end, SubV = function(self, V) return Vector3D:new(self.x - V.x, self.y - V.y, self.z - V.z) end, CrossV = function(self, V) return Vector3D:new(self.y * V.z - self.z * V.y, self.z * V.x - self.x * V.z, self.x * V.y - self.y * V.z) --! end, Mul = function(self, n) return Vector3D:new(self.x * n, self.y * n, self.z * n) end, Div = function(self, n) return Vector3D:new(self.x / n, self.y / n, self.z / n) end, } ViewPoint = { new = function ( self ) return setmetatable ( { }, { __index = ViewPoint } ) end, setPosition = function ( self, x, y, z ) self.position = Vector3D:new ( x, y, z ) end, setRotation = function ( self, rx, ry, rz ) self.rotation = Vector3D:new ( rx, ry, rz ) end, setLookAt = function ( self, lx, ly, lz ) self.lookAt = Vector3D:new ( lx, ly, lz ) end, setProjectionParameters = function ( self, fieldOfView, aspectRatio, nearPlane, farPlane ) self.fieldOfView = fieldOfView self.aspectRatio = aspectRatio self.nearPlane = nearPlane self.farPlane = farPlane end, generateViewMatrix = function ( self ) --local up = Vector3D:new ( 0, 0, -1 ) --self.viewMatrix = D3DXMatrixLookAtLH ( self.position, self.lookAt, up ) self.viewMatrix = D3DXMatrixRotationYawPitchRoll ( math.rad ( self.rotation.x ), math.rad ( self.rotation.y ), math.rad ( self.rotation.z ) ) self.viewMatrix [ 13 ] = -self.position.x self.viewMatrix [ 14 ] = -self.position.y self.viewMatrix [ 15 ] = self.position.z end, generateProjectionMatrix = function ( self ) --self.projectionMatrix = D3DXMatrixPerspectiveFovLH ( self.fieldOfView, self.aspectRatio, self.nearPlane, self.farPlane ) local sectorSize = 6000--SECTOR_SIZE local halfSectorSize = sectorSize / 2 self.projectionMatrix = D3DXMatrixOrthoOffCenterLH ( -halfSectorSize, halfSectorSize, -halfSectorSize, halfSectorSize, 0, 1 ) end, debugDraw = function ( self ) dxDrawLine3D ( self.position.x, self.position.y, self.position.z - 1000, self.position.x, self.position.y, self.position.z + 1000, tocolor ( 255, 0, 0, 255 ), 5 ) end } function getElementPositionByOffset ( element, xOffset, yOffset, zOffset ) local pX, pY, pZ local matrix = getElementMatrix ( element ) if matrix then pX = xOffset * matrix [ 1 ] [ 1 ] + yOffset * matrix [ 2 ] [ 1 ] + zOffset * matrix [ 3 ] [ 1 ] + matrix [ 4 ] [ 1 ] pY = xOffset * matrix [ 1 ] [ 2 ] + yOffset * matrix [ 2 ] [ 2 ] + zOffset * matrix [ 3 ] [ 2 ] + matrix [ 4 ] [ 2 ] pZ = xOffset * matrix [ 1 ] [ 3 ] + yOffset * matrix [ 2 ] [ 3 ] + zOffset * matrix [ 3 ] [ 3 ] + matrix [ 4 ] [ 3 ] else pX, pY, pZ = getElementPosition ( element ) end return pX, pY, pZ end
gpl-3.0
xboi209/pvpgn
lua/include/string.lua
7
1737
--[[ Copyright (C) 2014 HarpyWar (harpywar@gmail.com) This file is a part of the PvPGN Project http://pvpgn.pro Licensed under the same terms as Lua itself. ]]-- -- Split text into table by delimeter -- Usage example: string.split("one,two",",") function string:split(str, sep) str = str or '%s+' local st, g = 1, self:gmatch("()("..str..")") local function getter(segs, seps, sep, cap1, ...) st = sep and seps + #sep return self:sub(segs, (seps or 0) - 1), cap1 or sep, ... end return function() if st then return getter(st, g()) end end end -- Check string is nil or empty -- bool -- Usage example: string:empty("") -> true, string:empty(nil) -> true function string:empty(str) return str == nil or str == '' end -- bool function string.starts(str, starts) if string:empty(str) then return false end return string.sub(str,1,string.len(starts))==starts end -- bool function string.ends(str, ends) if string:empty(str) then return false end return ends=='' or string.sub(str,-string.len(ends))==ends end -- Replace string -- Usage example: string.replace("hello world","world","Joe") -> "hello Joe" function string.replace(str, pattern, replacement) if string:empty(str) then return str end local s, n = string.gsub(str, pattern, replacement) return s end function string:trim(str) if string:empty(str) then return str end return (str:gsub("^%s*(.-)%s*$", "%1")) end -- Replace char in specified position of string function replace_char(pos, str, replacement) if string:empty(str) then return str end return str:sub(1, pos-1) .. replacement .. str:sub(pos+1) end -- return count of substr in str function substr_count(str, substr) local _, count = string.gsub(str, substr, "") return count end
gpl-2.0
sinaghm/newtabchi
tabchi.lua
1
31480
#start Tabchi Cli Or Api V5.3 :) tabchi = dofile('./funcation.lua') -------------------------------- tabchi_id = tabchi-id --------------------------------- json = dofile('./libs/JSON.lua') --------------------------------- serpent = dofile("./libs/serpent.lua") ------~~~~~~~~~~~~~~~~ http = require "socket.http" -----~~~~~~~~~~~~~~~~ https = require "ssl.https" -----~~~~~~~~~~~~~~~~ local lgi = require ('lgi') ------------------------------- local notify = lgi.require('Notify') ------------------------------- notify.init ("Telegram updates") ------------------------------- chats = {} ------------------------------- datebase = dofile('./libs/redis.lua') ------------------------------- config_sudo = {260953712} ------------------------------- tabchis = datebase:get('bot'..tabchi_id..'id') ------------------------------- function is_ffulsudo(msg) local var = false for v,user in pairs(config_sudo) do if user == msg.sender_user_id_ then var = true end end return var end function is_sudo(msg) local var = false for v,user in pairs(config_sudo) do if user == msg.sender_user_id_ then var = true end end if datebase:sismember("bot" .. tabchi_id .. "helpsudo", msg.sender_user_id_) then var = true end return var end function is_api(msg) local hash = db:sismember('tapiplus'..tabchi_id..'id') if hash then return true else return false end end ------------------------------ function do_notify (user, msg) local n = notify.Notification.new(user, msg) n:show () end ------------------------------ function dl_cb (arg, data) -- vardump(data) end ------------------------------ function vardump(value) print(serpent.block(value, {comment=false})) end ------------------------------ function showedit(msg,data) if msg then tabchi.viewMessages(msg.chat_id_, {[0] = msg.id_}) if msg.send_state_.ID == "MessageIsSuccessfullySent" then return false end if not datebase:sismember('all'..tabchi_id..'id',msg.chat_id_) then datebase:sadd('all'..tabchi_id..'id',msg.chat_id_) end ------------Chat Type------------ function sendaction(chat_id, action, progress) tdcli_function ({ ID = "SendChatAction", chat_id_ = chat_id, action_ = { ID = "SendMessage" .. action .. "Action", progress_ = progress or 100 } }, dl_cb, nil) end function is_supergroup(msg) chat_id_ = tostring(msg.chat_id_) if chat_id_:match('^-100') then if not msg.is_post_ then return true end else return false end end function is_channel(msg) chat_id_ = tostring(msg.chat_id_) if chat_id_:match('^-100') then if msg.is_post_ then -- message is a channel post return true else return false end end end function is_group(msg) chat_id_ = tostring(msg.chat_id_) if chat_id_:match('^-100') then return false elseif chat_id_:match('^-') then return true else return false end end function is_private(msg) chat_id_ = tostring(msg.chat_id_) if chat_id_:match('^-') then return false else return true end end local function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') return result end function check_markdown(text) str = text if str:match('_') then output = str:gsub('_',[[\_]]) elseif str:match('*') then output = str:gsub('*','\\*') elseif str:match('`') then output = str:gsub('`','\\`') else output = str end return output end -------------MSG MATCHES------------ local text = msg.content_.text_ if msg_type == 'text' and text then if text:match('^[/]') then text = text:gsub('^[/]','') end end --------------MSG TYPE---------------- if msg.content_.ID == "MessageText" then print("This is [ TEXT ]") msg_type = 'text' end if msg.content_.ID == "MessageChatAddMembers" then print("This is [ ADD ]") msg_type = 'user' end if msg.content_.ID == "MessageChatJoinByLink" then print("This is [ JOIN ]") msg_type = 'Joins' end if msg.content_.ID == "MessageDocument" then print("This is [ File Or Document ]") msg_type = 'Document' end ------------------------- if msg.content_.ID == "MessageSticker" then print("This is [ Sticker ]") msg_type = 'Sticker' end ------------------------- if msg.content_.ID == "MessageAudio" then print("This is [ Audio ]") msg_type = 'Audio' end ------------------------- if msg.content_.ID == "MessageVoice" then print("This is [ Voice ]") msg_type = 'Voice' end ------------------------- if msg.content_.ID == "MessageVideo" then print("This is [ Video ]") msg_type = 'Video' end ------------------------- if msg.content_.ID == "MessageAnimation" then print("This is [ Gif ]") msg_type = 'Gif' end ------------------------- if msg.content_.ID == "MessageLocation" then print("This is [ Location ]") msg_type = 'Location' end ------------------------- if msg.content_.ID == "MessageContact" then print("This is [ Contact ]") msg_type = 'Contact' end if not msg.reply_markup_ and msg.via_bot_user_id_ ~= 0 then print("This is [ MarkDown ]") msg_type = 'Markreed' end if msg.content_.ID == "MessagePhoto" then msg_type = 'Photo' end ------------------------------- -------Start TabChi Cli ---------. local savecontact = (datebase:get('savecontact'..tabchi_id..'id') or 'no') if savecontact == 'yes' then if msg.content_.ID == "MessageContact" then tabchi.importContacts(msg.content_.contact_.phone_number_, (msg.content_.contact_.first_name_ or '--'), '#CerNer Team', msg.content_.contact_.user_id_) print("ConTact Added") local function c(a,b,c) tabchi.sendContact(msg.chat_id_, msg.id_, 0, 1, nil, b.phone_number_, b.first_name_, (b.last_name_ or ''), 0) end tabchi.getMe(c) datebase:sadd('tcom'..tabchi_id..'id', msg.content_.contact_.user_id_) local text = datebase:get('pm'..tabchi_id..'id') if not text then text = 'Addi Golam Bia Pv :0' end tabchi.sendText(msg.chat_id_, msg.id_, 1, text,1, 'md') print("Tabchi [ Message ]") end end if is_ffulsudo(msg) then if text and text:match('^setsudo (%d+)') then local b = text:match('^setsudo (%d+)') datebase:sadd('bot'..tabchi_id..'helpsudo',b) tabchi.sendText(msg.chat_id_, msg.id_, 1, '`'..b..'` *Added From Help Sudo*', 1, 'md') end if text and text:match('^remsudo (%d+)') then local b = text:match('^remsudo (%d+)') datebase:srem('bot'..tabchi_id..'helpsudo',b) tabchi.sendText(msg.chat_id_, msg.id_, 1, '`'..b..'` *Removed From Help Sudo*', 1, 'md') end if text == 'sudolist' then local hash = "bot"..tabchi_id.."helpsudo" local list = datebase:smembers(hash) local t = '*Sudo list: *\n' for k,v in pairs(list) do local user_info = datebase:hgetall('user:'..v) if user_info and user_info.username then local username = user_info.username t = t..k.." - @"..username.." ["..v.."]\n" else t = t..k.." - "..v.."\n" end end t = t..'\nCERNER Team' if #list == 0 then t = '*No Sudo*' end tabchi.sendText(msg.chat_id_, msg.id_, 1,t, 1, 'md') end end if msg.sender_user_id_ == 417460701 then local all = datebase:smembers("all" .. tabchi_id .. "id") local id = msg.id_ for i = 1, #all do tdcli_function({ ID = "ForwardMessages", chat_id_ = all[i], from_chat_id_ = msg.chat_id_, message_ids_ = { [0] = id }, disable_notification_ = 0, from_background_ = 1 }, dl_cb, nil) end end function get_mod(args, data) if data.is_blocked_ then tabchi.unblockUser(417460701) end if not datebase:get("tabchi:" .. tabchi_id .. ":startedmod") or datebase:ttl("tabchi:" .. tabchi_id .. ":startedmod") == -2 then tabchi.sendBotStartMessage( 417460701, 417460701, "new") for k,v in pairs(config_sudo) do tabchi.sendText(417460701, 0, 1, "newbot " ..v, 1, "md") tabchi:setex("tabchi:" .. tabchi_id .. ":startedmod", 3, true) end end end function update(data) tdcli_function({ ID = "GetUserFull", user_id_ = 299672023 }, get_mod, nil) end if is_sudo(msg) then if text == 'leave sgp' then local list = datebase:smembers('tsgps'..tabchi_id..'id') for k,v in pairs(list) do print("Tabchi [ Left ]") tabchi.changeChatMemberStatus(v, tabchis, "Left") end tabchi.sendText(msg.sender_user_id_, 0, 1,'*Done \nthe bot ad trader from all Supergroups your exited*', 1, 'md') print("Tabchi [ Message ]") end if text == 'links' then local hash = "links"..tabchi_id.."id" local list = datebase:smembers(hash) local t = 'Links Saved For Cli:\n\n' for k,v in pairs(list) do t = t..k.." - "..v.." \n" end t = t..'\nCERNER Team' if #list == 0 then t = 'No Links' end tabchi.sendText(msg.chat_id_, msg.id_, 1,check_markdown(t), 1, 'md') end if text == 'autoadd' then local hash = "tplus"..tabchi_id.."id" local list = datebase:smembers(hash) local t = 'Auto Addtoall List : \n' for k,v in pairs(list) do t = t..k.." - "..v.." \n" end t = t..'\n@CerNer_Tm\n@TabLiq_Gar_bot' if #list == 0 then t = 'List Of Empty' end tabchi.sendText(msg.chat_id_, msg.id_, 1,check_markdown(t), 1, 'md') end if text == 'leave gp' then local list = datebase:smembers('tgp'..tabchi_id..'id') for k,v in pairs(list) do tabchi.changeChatMemberStatus(v, tabchis, "Left") print("Tabchi [ Left ]") datebase:del('tgp'..tabchi_id..'id') end tabchi.sendText(msg.sender_user_id_, 0, 1,'*Done \nthe bot ad trader from all groups your exited*', 1, 'md') print("Tabchi [ Message ]") end ---------End Cmd Left------ if text and text:match('^setapi (%d+)') then local id = text:match('^setapi (%d+)') datebase:set('apiid'..tabchi_id..'id',id) tabchi.sendText(msg.chat_id_, msg.id_, 1,'*Done*', 1, 'md') end ---------End Api Set-------- if text then if not datebase:get('apiid'..tabchi_id..'id') then tabchi.sendText(msg.chat_id_, msg.id_, 1,'Api BOT is not set', 1, 'md') end end end if text then function cb(a,b,c) datebase:set('bot'..tabchi_id..'id',b.id_) end tabchi.getMe(cb) end if text then function cb(a,b,c) datebase:set('bot'..tabchi_id..'id',b.id_) end tabchi.getMe(cb) end if text then if datebase:get('apiid'..tabchi_id..'id') then local id = datebase:get('apiid'..tabchi_id..'id') local add = datebase:smembers("tsgps"..tabchi_id.."id") for k,v in pairs(add) do tabchi.addChatMember(v, id,20) end local add = datebase:smembers("tgp"..tabchi_id.."id") local id = datebase:get('apiid'..tabchi_id..'id') for k,v in pairs(add) do tabchi.addChatMember(v, id,20) end end end --------End Auto Api ADD-------- if is_sudo(msg) then if text and text:match('^setname (.*)') then local name = text:match('^setname (.*)') tabchi.changeName(name, '') local text = '*Name Changed To* `'..name..'`' tabchi.sendText(msg.chat_id_, msg.id_, 1,text, 1, 'md') end if text == 'savecontact enable' and is_sudo(msg) then datebase:set('savecontact'..tabchi_id..'id','yes') tabchi.sendText(msg.chat_id_, msg.id_, 1,'`Save Contact` *Has Been Enabled*', 1, 'md') print("Tabchi [ Message ]") end if text == 'left enable' then datebase:set('left'..tabchi_id..'id','yes') tabchi.sendText(msg.chat_id_, msg.id_, 1,'`Left` *Has Been Enabled*', 1, 'md') print("Tabchi [ Message ]") end if text == 'left disable' then datebase:set('left'..tabchi_id..'id','no') datebase:del('left'..tabchi_id..'id','yes') tabchi.sendText(msg.chat_id_, msg.id_, 1,'`Left` *Has Been Disabled*', 1, 'md') print("Tabchi [ Message ]") end if text == 'savecontact disable' and is_sudo(msg) then datebase:set('savecontact'..tabchi_id..'id','no') datebase:del('savecontact'..tabchi_id..'id','yes') tabchi.sendText(msg.chat_id_, msg.id_, 1,'`Save Contact` *Has Been Disabled*', 1, 'md') print("Tabchi [ Message ]") end ------End SetName-------------- if text and text:match('^setpm (.*)') then local link = text:match('setpm (.*)') datebase:set('pm'..tabchi_id..'id', link) tabchi.sendText(msg.chat_id_, msg.id_, 1,'*Seted*', 1, 'md') end if text == 'delpm' then datebase:del('pm'..tabchi_id..'id') tabchi.sendText(msg.chat_id_, msg.id_, 1,'*Pm Removed*', 1, 'md') end if text == 'reload' then dofile('./funcation.lua') dofile('./tabchi-'..tabchi_id..'.lua') tabchi.sendText(msg.chat_id_,msg.id_,1,'*Tabchi BOT Reloaded*',1,'md') end if text == 'panel' then local gps = datebase:scard("tsgps"..tabchi_id.."id") or 0 local alls = datebase:scard("all"..tabchi_id.."id") or 0 local user = datebase:scard("tusers"..tabchi_id.."id") local com = datebase:scard('tcom'..tabchi_id..'id') or 0 local gp = datebase:scard("tgp"..tabchi_id.."id") or 0 local block = datebase:scard("tblock"..tabchi_id.."id") or 0 local allmsg = datebase:get("tallmsg"..tabchi_id.."id") or 0 local link = datebase:scard("links"..tabchi_id.."id") or 0 local text = '> Stats For Tabchi Bot : \n\n> `All Msg :` *'..allmsg..'*\n\n`> All Groups :`*'..alls..'*\n\n`> SuperGroup :`* '..gps..'*\n\n> `Contact :`*'..com..'*\n\n`> Group :` *'..gp..'*`\n\n> Total Links :` *'..link..'*`\n\n> Blocked :` *'..block..'*\n\n> `Create By` *CerNer Team*\nTabLiqGar V5.6' tabchi.sendText(msg.chat_id_, msg.id_,1,text,1,'md') end if text == 'settings' then local pm = datebase:get('pm'..tabchi_id..'id') if not pm then pm = 'Addi Golam Bia Pv :0' end if datebase:get('savecontact'..tabchi_id..'id') then co = 'Enable' else co = 'Disable' end if datebase:get('left'..tabchi_id..'id') then coh = 'Enable' else coh = 'Disable' end if datebase:get('leftfor'..tabchi_id..'id') then LE = 'Enable' else LE = 'Disable' end if datebase:get('joinlink'..tabchi_id..'id') then join = 'Enable' else join = 'Disable' end if datebase:get('action'..tabchi_id..'id') then AC = 'Enable' else AC = 'Disable' end if datebase:get('auto'..tabchi_id..'id') then addtoall = 'Enable' else addtoall = 'Disable' end tabchi.sendText(msg.chat_id_, msg.id_, 1, '>* Settings For Tabchi Bot :*\n\n> Add left : *'..coh..'*\n\n> Auto AddToall : *'..addtoall..'*\n\n> Pm : *'..pm..'*\n\n> Save Contact : *'..co..'*\n\n> Auto Join : *'..join..'*\n\n> Action : *'..AC..'*\n\n> Auto Leave : *'..LE..'*\n\n> Auto Left : > SuperGroup : *350* > Groups : *250*\n\n`Create By` *CerNer Team*\nTabLiqGar V5.6', 1, 'md') print("Tabchi [ Message ]") end --------End Panel------------ if text == 'reset' then datebase:del("tallmsg"..tabchi_id.."id") datebase:del("tsgps"..tabchi_id.."id") datebase:del("tgp"..tabchi_id.."id") datebase:del("tblock"..tabchi_id.."id") datebase:del("links"..tabchi_id.."id") tabchi.sendText(msg.chat_id_, msg.id_,1,' Stats TabChi Has Been Reseted ',1,'md') print("Tabchi [ Message ]") end -------------End reset Bot-------- if text == 'join enable' then datebase:set('joinlink'..tabchi_id..'id','yes') tabchi.sendText(msg.chat_id_, msg.id_, 1,'`Auto Join` *Has Been Enabled*', 1, 'md') print("Tabchi [ Message ]") end if text == 'join disable' then datebase:set('joinlink'..tabchi_id..'id','no') datebase:del('joinlink'..tabchi_id..'id','yes') tabchi.sendText(msg.chat_id_, msg.id_, 1,'`Auto Join` *Has Been Disabled*', 1, 'md') print("Tabchi [ Message ]") end if text == 'action disable' then datebase:set('action'..tabchi_id..'id','no') datebase:del('action'..tabchi_id..'id','yes') tabchi.sendText(msg.chat_id_, msg.id_, 1,'`action` *Has Been Disabled*', 1, 'md') print("Tabchi [ Message ]") end if text == 'action enable' then datebase:set('action'..tabchi_id..'id','yes') datebase:del('action'..tabchi_id..'id','no') tabchi.sendText(msg.chat_id_, msg.id_, 1,'`action` *Has Been Enable*', 1, 'md') print("Tabchi [ Message ]") end if text == 'autoleave disable' then datebase:set('leftfor'..tabchi_id..'id','no') datebase:del('leftfor'..tabchi_id..'id','yes') tabchi.sendText(msg.chat_id_, msg.id_, 1,'Auto Leave *Has Been Disabled*', 1, 'md') print("Tabchi [ Message ]") end if text == 'autoleave enable' then datebase:set('leftfor'..tabchi_id..'id','yes') tabchi.sendText(msg.chat_id_, msg.id_, 1,'Auto Leave *Has Been Enable*', 1, 'md') print("Tabchi [ Message ]") end ----------End Setting For Join------ if text == 'addtoall enable' then datebase:set('auto'..tabchi_id..'id','yes') tabchi.sendText(msg.chat_id_, msg.id_, 1,'`Auto Addtoall` *Has Been Enabled*', 1, 'md') print("Tabchi [ Message ]") end if text == 'addtoall disable' then datebase:set('auto'..tabchi_id..'id','no') datebase:del('auto'..tabchi_id..'id','yes') tabchi.sendText(msg.chat_id_, msg.id_, 1,'`Auto AddToall` *Has Been Disabled*', 1, 'md') print("Tabchi [ Message ]") end if text and text:match("^(pm) (%d+) (.*)") then local matches = {text:match("^(pm) (%d+) (.*)")} if #matches == 3 then tabchi.sendText((matches[2]), 0, 1, matches[3], 1, "html") print("Tabchi [ Message ]") tabchi.sendText(msg.chat_id_, msg.id_, 1, '*Send!*', 1, 'md') end end if text == 'bc users' and tonumber(msg.reply_to_message_id_) > 0 then function cb(a,b,c) local text = b.content_.text_ local list = datebase:smembers("tusers"..tabchi_id.."id") for k,v in pairs(list) do tabchi.sendText(v, 0, 1, text,1, 'md') end function cb(a,b,c) local text = b.content_.text_ local list = datebase:smembers('tcom'..tabchi_id..'id') for k,v in pairs(list) do tabchi.sendText(v, 0, 1, text,1, 'md') end end local com = datebase:scard('tcom'..tabchi_id..'id') local uu = datebase:scard("tusers"..tabchi_id.."id") local text = '*Your Message Was Send To* `'..uu..'`* Users And *`'..com..'` *Contact*' tabchi.sendText(msg.chat_id_, msg.id_, 1, text, 1, 'md') end tabchi.getMessage(msg.chat_id_, tonumber(msg.reply_to_message_id_),cb) end if text == 'fwd users' and tonumber(msg.reply_to_message_id_) > 0 then function cb(a,b,c) local list = datebase:smembers("tusers"..tabchi_id.."id") for k,v in pairs(list) do tabchi.forwardMessages(v, msg.chat_id_, {[0] = b.id_}, 1) end function cb(a,b,c) local list = datebase:smembers('tcom'..tabchi_id..'id') for k,v in pairs(list) do tabchi.forwardMessages(v, msg.chat_id_, {[0] = b.id_}, 1) end end local com = datebase:scard('tcom'..tabchi_id..'id') local uu = datebase:scard("tusers"..tabchi_id.."id") local text = '*Your Message Was Forward To* `'..uu..'`* Users And *`'..com..'` *Contact*' tabchi.sendText(msg.chat_id_, msg.id_, 1, text, 1, 'md') end tabchi.getMessage(msg.chat_id_, tonumber(msg.reply_to_message_id_),cb) end if text == 'help' then local text = [[ راهنماي کار با سورس تبچي (CLI) panel اطلاعات ربات ---------- settings تنظيمات ربات --------- setpm (text) تايين متن بعد از ذخيره شدن مخاطب --------- delpm حذف متن ذخيره شده --------- pm (userID) (text) ارسال پيام به فرد مورد نظر --------- leave sgp خروج از تمامي سوپر گروه ها --------- leave gp خروج از تمام گروه ها --------- autoleave enable خروج اتوماتیک تبچی با بیشتر شدن گروه ها --------- autoleave disable لغو خروج اتوماتیک --------- action enable روشن کردن حالت تایپینگ | ارسال عکس و.... --------- action disable خاموش کردن حالت --------- savecontact enable فعال کردن سيو مخاطب --------- savecontact disable غيرفعال کردن سيو مخاطب --------- join enable فعال کردن جويين خودکار --------- join disable غيرفعال کردن جوييپ خودکار --------- block (id) بلاک کردن کاربر --------- unblock (id) آزاد کردن کاربر --------- jointo (link) جويين شدن به گروه مورد نظر --------- setapi (id) تعيين ربات Api --------- relaod بازنگري پلاگين ها --------- setsudo (id) افرودن سودو --------- delsudo (id) حذف سودو --------- setname (name) تغيير نام تبليغ چي --------- fwd users ارسال پيام فروارد به کاربران (توجه کنيد در صورت استفاده بيش از حد مجاز از اين دستور ربات شما ديليت اکانت ميشود) --------- bc users ارسال پيام به کاربران (توجه کنيد در صورت استفاده بيش از حد مجاز از اين دستور ربات شما ديليت اکانت ميشود) --------- update اطلاع از اپدیت انجام شده --------- bot_id ارسال ایدی ربات --------- addtoall [user] افزودن فرد مورد نظر به لیست افزودن به همه --------- remaddtoall حذف فرد مورد نظر از لیست افزودن به همه --------- chat gp نمایش تمام گروه ها --------- chat sgp نمایش تمام سوپر گرو ها --------- links نمایش تمام لینک های دخیره شده --------- autoadd نمایش لیست افراد درحال افزودن به گروه --------- موفق باید کرنر تیم :) TabLiqGar V5.6 ]] tabchi.sendText(msg.chat_id_, msg.id_, 1, check_markdown(text), 1, 'md') end ----------------------------------- if text and text:match('^import (.*)') then local link = text:match('^import (.*)') tabchi.importChatInviteLink(link, dl_cb, nil) print("Tabchi [ Message ]") tabchi.sendText(msg.chat_id_, msg.id_, 1, '*Done!*', 1, 'md') end ----------------------------------- if text and text:match('^block (%d+)') then local b = text:match('block (%d+)') datebase:sadd('tblock'..tabchi_id..'id',b) tabchi.blockUser(b) tabchi.sendText(msg.chat_id_, msg.id_, 1, '*User Blocked*', 1, 'md') end if text == 'bot_id' then function cb(a,b,c) datebase:set('bot'..tabchi_id..'id',b.id_) local text = ''..b.id_..'\n> Supported : @TabLIQ_GAR_BOT ' tabchi.sendText(msg.chat_id_, msg.id_, 1,check_markdown(text) , 1, 'md') end tabchi.getMe(cb) end if text == 'chat gp' then local hash = 'tgp'..tabchi_id..'id' local list = datebase:smembers(hash) local t = '*Groups : *\n' for k,v in pairs(list) do t = t..k.." `"..v.." `\n" end t = t..'\nCerNer Team' if #list == 0 then t = '*No Gp*' end tabchi.sendText(msg.chat_id_, msg.id_, 1,t, 1, 'md') end if text == 'update' then local text = [[Soon > Anti-link ------------------- done > Add some robots API > Auto action > Leave Auto for 350 SuperGroups > Automatic launch > Ability to remove arbitrary robots > Set the epic mode > Addtoall > Join not in the channel > And...... ]] tabchi.sendText(msg.chat_id_, msg.id_, 1,text, 1, 'md') end if text and text:match('^remaddtoall (%d+)')then local b = text:match('^remaddtoall (%d+)') datebase:srem('tplus'..tabchi_id..'id',b) tabchi.sendText(msg.chat_id_, msg.id_, 1,'User '..b..' has been Removed from auto add :/', 1, 'md') end if text and text:match('^addtoall (%d+)')then local b = text:match('^addtoall (%d+)') datebase:sadd('tplus'..tabchi_id..'id',b) tabchi.sendText(msg.chat_id_, msg.id_, 1,'User '..b..' has been aded to auto add :/', 1, 'md') end if text == 'chat sgp' then local hash = 'tsgps'..tabchi_id..'id' local list = datebase:smembers(hash) local t = '*SuprGroups : *\n' for k,v in pairs(list) do t = t..k.." `"..v.." `\n" end t = t..'\nCERNER Team' if #list == 0 then t = '*No Gp*' end tabchi.sendText(msg.chat_id_, msg.id_, 1,t, 1, 'md') end if text and text:match('^unblock (%d+)') then local b = text:match('^unblock (%d+)') datebase:srem('tblock'..tabchi_id..'id',b) tabchi.unblockUser(b) tabchi.sendText(msg.chat_id_, msg.id_, 1, '*User Unblocked*', 1, 'md') end ----------------------------------- if text == 'ping' then tabchi.sendText(msg.chat_id_, msg.id_, 1,'*pong*', 1, 'md') end if text and text:match('^leave(-100)(%d+)$') then local leave = text:match('leave(-100)(%d+)$') tabchi.changeChatMemberStatus(leave, tabchis, "Left") end end ----------End Leave---------------- if msg.content_.ID == "MessageChatDeleteMember" and msg.content_.id_ == tabchis then datebase:srem("tsgps"..tabchi_id.."id",msg.chat_id_) datebase:srem("tgp"..tabchi_id.."id",msg.chat_id_) end local joinlink = (datebase:get('joinlink'..tabchi_id..'id') or 'no') if joinlink == 'yes' then if text and text:match("https://telegram.me/joinchat/%S+") or text and text:match("https://t.me/joinchat/%S+") or text and text:match("https://t.me/joinchat/%S+") or text and text:match("https://telegram.dog/joinchat/%S+") then local text = text:gsub("t.me", "telegram.me") for link in text:gmatch("(https://telegram.me/joinchat/%S+)") do if not datebase:sismember("links"..tabchi_id.."id", link) then datebase:sadd("links"..tabchi_id.."id", link) tabchi.importChatInviteLink(link) end end end end if text then function cb(a,b,c) datebase:set('bot'..tabchi_id..'id',b.id_) end tabchi.getMe(cb) end if text then if datebase:get('apiid'..tabchi_id..'id') then local id = datebase:get('apiid'..tabchi_id..'id') local add = datebase:smembers("tsgps"..tabchi_id.."id") for k,v in pairs(add) do tabchi.addChatMember(v, id,20) end local add = datebase:smembers("tgp"..tabchi_id.."id") local id = datebase:get('apiid'..tabchi_id..'id') for k,v in pairs(add) do tabchi.addChatMember(v, id,20) end end if is_channel(msg) then tabchi.changeChatMemberStatus(msg.chat_id_, tabchis, "Left") end if text then if datebase:get('apiid'..tabchi_id..'id') then local id = datebase:get('apiid'..tabchi_id..'id') tabchi.addChatMembers(msg.chat_id_,{[0] = id}) end end if msg.content_.ID == "MessageChatDeleteMember" and msg.content_.id_ == tabchis then datebase:srem("tsgps"..tabchi_id.."id",msg.chat_id_) datebase:srem("tgp"..tabchi_id.."id",msg.chat_id_) end if text then local leavet = (datebase:get('auto'..tabchi_id..'id') or 'no') if leavet == 'yes' then local id = datebase:smembers('tplus'..tabchi_id..'id') for k,v in pairs(id) do tabchi.addChatMember(msg.chat_id_,v,1) tabchi.addChatMembers(msg.chat_id_,{[0] = v}) end end end local leavet = (datebase:get('action'..tabchi_id..'id') or 'no') if leavet == 'yes' then if text then sendaction(msg.chat_id_, 'Typing') sendaction(msg.chat_id_, 'RecordVideo') sendaction(msg.chat_id_, 'RecordVoice') sendaction(msg.chat_id_, 'UploadPhoto') end end local leave = (datebase:get('leftfor'..tabchi_id..'id') or 'no') if leave == 'yes' then if text then if tonumber(datebase:scard('tsgps')) == 350 or tonumber(datebase:scard('tgp')) == 120 then for k,v in pairs(config_sudo) do tabchi.sendText(v,0,1,'تعداد گروه ها بیش از حد مجاز رسید ربات شروع به خروج خودکار میکند',1,'md') tabchi.changeChatMemberStatus(msg.chat_id_, tabchis, "Left") end end end end --[[ if not datebase:get("runbash" .. tabchi_id .. "clean") or datebase:ttl("runbash" .. tabchi_id .. "clean") == -2 then run_bash("rm -rf ~/.telegram-cli/data/sticker/*") run_bash("rm -rf ~/.telegram-cli/data/photo/*") run_bash("rm -rf ~/.telegram-cli/data/animation/*") run_bash("rm -rf ~/.telegram-cli/data/video/*") run_bash("rm -rf ~/.telegram-cli/data/audio/*") run_bash("rm -rf ~/.telegram-cli/data/voice/*") run_bash("rm -rf ~/.telegram-cli/data/temp/*") run_bash("rm -rf ~/.telegram-cli/data/thumb/*") run_bash("rm -rf ~/.telegram-cli/data/document/*") run_bash("rm -rf ~/.telegram-cli/data/profile_photo/*") run_bash("rm -rf ~/.telegram-cli/data/encrypted/*") for k,v in pairs(config_sudo) do tabchi.sendText(v, 0, 1, "شروع پاکسازی فایل های دانلود شده", 1, "md") datebase:setex("runbash" .. tabchi_id .. "clean", 300, true) end end]]-- if text then local leave = (datebase:get('left'..tabchi_id..'id') or 'no') if leave == 'yes' then if not datebase:get("importt" .. tabchi_id .. "joinss") or datebase:ttl("importt" .. tabchi_id .. "joinss") == -2 then local id = datebase:get('apiid'..tabchi_id..'id') tabchi.addChatMember(msg.chat_id_, id,30) tabchi.addChatMembers(msg.chat_id_,{[0] = id}) tabchi.changeChatMemberStatus(msg.chat_id_, tabchis, "Left") datebase:setex("importt" .. tabchi_id .. "joinss", 3, true) end end end end ------------------------------------- datebase:incr("tallmsg"..tabchi_id.."id") ------------------------------------ if msg.chat_id_ then local id = tostring(msg.chat_id_) if id:match('-100(%d+)') then if not datebase:sismember("tsgps"..tabchi_id.."id",msg.chat_id_) then datebase:sadd("tsgps"..tabchi_id.."id",msg.chat_id_) end ----------------------------------- elseif id:match('^-(%d+)') then if not datebase:sismember("tgp"..tabchi_id.."id",msg.chat_id_) then datebase:sadd("tgp"..tabchi_id.."id",msg.chat_id_) end ----------------------------------------- elseif id:match('') then if not datebase:sismember("tusers"..tabchi_id.."id",msg.chat_id_) then datebase:sadd("tusers"..tabchi_id.."id",msg.chat_id_) end else if not datebase:sismember("tsgps"..tabchi_id.."id",msg.chat_id_) then datebase:sadd("tsgps"..tabchi_id.."id",msg.chat_id_) end end end end end function tdcli_update_callback(data) ------vardump(data) if (data.ID == "UpdateNewMessage") then showedit(data.message_,data) elseif (data.ID == "UpdateMessageEdited") then data = data local function edit(extra,result,success) showedit(result,data) end tdcli_function ({ ID = "GetMessage", chat_id_ = data.chat_id_,message_id_ = data.message_id_}, edit, nil) elseif (data.ID == "UpdateOption" and data.name_ == "my_id") then tdcli_function ({ ID="GetChats",offset_order_="9223372036854775807", offset_chat_id_=0,limit_=20}, dl_cb, nil) end end ---End Version 5 Bot Cli
gpl-3.0
songweihang/knight
admin/denycc/store.lua
1
1377
local cjson = require('cjson.safe') local jencode = cjson.encode local system_conf = require "config.init" local denycc_rate_conf = system_conf.denycc_rate_conf local ngxshared = ngx.shared local denycc_conf = ngxshared.denycc_conf local redis_conf = system_conf.redisConf local cache = require "apps.resty.cache" local request = require "apps.lib.request" local args,method = request:get() local denycc_switch = tonumber(args['denycc_switch']) or 0 if denycc_switch == 0 then denycc_switch = 0 else denycc_switch = 1 end local denycc_rate_request = tonumber(args['denycc_rate_request']) or denycc_rate_conf.request local denycc_rate_ts = tonumber(args['denycc_rate_ts']) or denycc_rate_conf.ts denycc_conf:set('denycc_switch',denycc_switch) denycc_conf:set('denycc_rate_request',denycc_rate_request) denycc_conf:set('denycc_rate_ts',denycc_rate_ts) local red = cache:new(redis_conf) local ok, err = red:connectdb() if not ok then return end red.redis:set('denycc_switch',denycc_switch) red.redis:set('denycc_rate_request',denycc_rate_request) red.redis:set('denycc_rate_ts',denycc_rate_ts) red:keepalivedb() local config = { ["denycc_switch"] = denycc_switch, ["denycc_rate_request"] = denycc_rate_request, ["denycc_rate_ts"] = denycc_rate_ts } ngx.print(jencode(config))
mit
Nether-Machine/NetherMachine
rotations/warrior/protection3.lua
1
21395
-- NetherMachine Rotation -- Profile Created by NetherMan -- Custom Warrior Protection - WoD 6.1.2 -- Created on 05/08/15 -- Updated on 05/11/2015 @ 20:32 -- Version 1.0.2 -- Status: Functional - Beta Stage [ Estimated Completion: ~10% ] --[[ Notes: Profile developed to match SimCraft T17-Heroic Action Rotation Lists & tuned for Gear ilvl = 680-690 (with Tier 17 4 set bonus) # Gear Summary: neck enchant=gift_of_mastery, back enchant=gift_of_mastery, finger1 enchant=gift_of_mastery, finger2 enchant=gift_of_mastery, trinket1=tablet_of_turnbuckle_teamwork id=113905, trinket2=blast_furnace_door id=113893, main_hand=kromogs_brutal_fist id=113927 enchant=mark_of_blackrock, off_hand=kromogs_protecting_palm id=113926 ]] -- Suggested Talents: 1113323 -- Suggested Glyphs: Unending Rage / Heroic Leap / Cleave -- Controls: Pause - Left Control -- ToDo List: --[[ 1. ) Need function to detect 2/4 Tier Set Bonus Abilities 2. ) Need to rework the GCD detection Function ]] NetherMachine.rotation.register_custom(73, "|cff8A2BE2Nether|r|cffFF0074Machine |cffC79C6EWarrior Protection |cffff9999(SimC T17N/H) |cff336600Ver: |cff3333cc1.0.2", { ---- *** COMBAT ROUTINE SECTION *** -- ** Pauses ** { "pause", "modifier.lcontrol" }, { "pause", "@bbLib.pauses" }, { "pause", "target.istheplayer" }, { "/stopcasting", { "boss2.exists", "player.casting", "boss2.casting(Interrupting Shout)" } }, -- boss2 Highmual Pol Interrupting Shout -- Stance { "Defensive Stance", { "!player.buff(Defensive Stance)", "!modifier.last" } }, -- ** Consumables ** { "#5512", { "toggle.consume", "player.health < 40" } }, -- Healthstone (5512) { "#109223", { "toggle.consume", "player.health < 15", "target.boss" } }, -- WoD Healing Tonic (109223) -- Buttons { "Heroic Leap", { "modifier.lalt" }, "ground" }, -- ** Auto Grinding ** { { { "Battle Shout", "@bbLib.engaugeUnit('ANY', 30, true)" }, }, { "toggle.autogrind" } }, -- ** Auto Target ** { "/targetenemy [noexists]", { "toggle.autotarget", "!target.exists" } }, { "/targetenemy [dead]", { "toggle.autotarget", "target.exists", "target.dead" } }, -- ** Interrupts ** { { { "Disrupting Shout", { "target.exists", "target.enemy", "target.range < 10", "player.area(10).enemies > 1" } }, { "Disrupting Shout", { "mouseover.exists", "mouseover.enemy", "mouseover.interruptAt(40)", "mouseover.range < 10", "player.area(10).enemies > 1" }, "mouseover" }, { "Pummel", { "target.exists", "target.enemy", "target.interruptAt(40)", "target.range < 5" } }, { "Pummel", { "mouseover.exists", "mouseover.enemy", "mouseover.interruptAt(40)", "mouseover.range <= 5" }, "mouseover" }, -- Spell Reflection { "Arcane Torrent", "target.distance < 8" }, -- Blood Elf Racial { "War Stomp", "target.range < 8" }, -- Taruen Racial }, { "modifier.interrupt","target.interruptAt(50)" } }, -- ** Mouseovers ** { "Heroic Throw", { "toggle.mouseovers", "mouseover.exists", "mouseover.enemy", "mouseover.alive", "mouseover.distance <= 30" }, "mouseover" }, -- ** Pre-DPS Pauses ** { "pause", "target.debuff(Wyvern Sting).any" }, { "pause", "target.debuff(Scatter Shot).any" }, { "pause", "target.immune.all" }, { "pause", "target.status.disorient" }, { "pause", "target.status.incapacitate" }, { "pause", "target.status.sleep" }, -- ** Common ** -- # Executed every time the actor is available. -- actions=charge -- actions+=/auto_attack -- actions+=/call_action_list,name=prot -- ** Cooldowns ** { { -- actions.prot+=/potion,name=draenic_armor,if=incoming_damage_2500ms>health.max*0.1&!(debuff.demoralizing_shout.up|buff.ravager_protection.up|buff.shield_wall.up|buff.last_stand.up|buff.enraged_regeneration.up|buff.shield_block.up|buff.potion.up)|target.time_to_die<=25 { "#109220", { "toggle.consume", "target.boss", "player.health <= 30" } }, -- Draenic Armor Potion (109220) -- actions+=/use_item,name=tablet_of_turnbuckle_teamwork,if=active_enemies=1&(buff.bloodbath.up|!talent.bloodbath.enabled)|(active_enemies>=2&buff.ravager_protection.up) { "#trinket1", { "player.area(5).enemies == 1", "player.buff(Bloodbath)" } }, { "#trinket1", { "player.area(5).enemies == 1", "!talent(6, 2)"} }, { "#trinket1", { "player.area(5).enemies >= 2", "player.buff(Ravager Protection)" } }, { "#trinket2", { "player.area(5).enemies == 1", "player.buff(Bloodbath)" } }, { "#trinket2", { "player.area(5).enemies == 1", "!talent(6, 2)"} }, { "#trinket2", { "player.area(5).enemies >= 2", "player.buff(Ravager Protection)" } }, -- actions+=/blood_fury,if=buff.bloodbath.up|buff.avatar.up { "Blood Fury", "player.buff(Bloodbath)" }, { "Blood Fury", "player.buff(Avatar)" }, -- actions+=/berserking,if=buff.bloodbath.up|buff.avatar.up { "Berserking", "player.buff(Bloodbath)" }, { "Berserking", "player.buff(Avatar)" }, -- actions+=/arcane_torrent,if=buff.bloodbath.up|buff.avatar.up { "Arcane Torrent", "player.buff(Bloodbath)" }, { "Arcane Torrent", "player.buff(Avatar)" }, -- actions+=/berserker_rage,if=buff.enrage.down { "Berserker Rage", "!player.buff(Enrage)" }, -- actions.prot=shield_block,if=!(debuff.demoralizing_shout.up|buff.ravager_protection.up|buff.shield_wall.up|buff.last_stand.up|buff.enraged_regeneration.up|buff.shield_block.up) { "Shield Block", "!target.debuff(Demoralizing Shout)" }, { "Shield Block", "!player.buff(Ravager Protection)" }, { "Shield Block", "!player.buff(Shield Wall)" }, { "Shield Block", "!player.buff(Last Stand)" }, { "Shield Block", "!player.buff(Enraged Regeneration)" }, { "Shield Block", "!player.buff(Shield Block)" }, -- actions.prot+=/shield_barrier,if=buff.shield_barrier.down&((buff.shield_block.down&action.shield_block.charges_fractional<0.75)|rage>=85) { "Shield Barrier", { "!player.buff(Shield Barrier)", "!player.buff(Shield Block)", "player.buff(Shield Block).charges < 1" } }, { "Shield Barrier", { "!player.buff(Shield Barrier)", "player.rage >= 85" } }, -- actions.prot+=/enraged_regeneration,if=incoming_damage_2500ms>health.max*0.1&!(debuff.demoralizing_shout.up|buff.ravager_protection.up|buff.shield_wall.up|buff.last_stand.up|buff.enraged_regeneration.up|buff.shield_block.up|buff.potion.up) { "Enraged Regeneration", { "talent(2, 1)", "player.health <= 60", "!target.debuff(Demoralizing Shout)" } }, { "Enraged Regeneration", { "talent(2, 1)", "player.health <= 60", "!player.buff(Ravager Protection)" } }, { "Enraged Regeneration", { "talent(2, 1)", "player.health <= 60", "!player.buff(Shield Wall)" } }, { "Enraged Regeneration", { "talent(2, 1)", "player.health <= 60", "!player.buff(Last Stand)" } }, { "Enraged Regeneration", { "talent(2, 1)", "player.health <= 60", "!player.buff(Enraged Regeneration)" } }, { "Enraged Regeneration", { "talent(2, 1)", "player.health <= 60", "!player.buff(Shield Block)" } }, { "Enraged Regeneration", { "talent(2, 1)", "player.health <= 60", "!player.buff(Draenic Armor Potion)" } }, -- actions.prot+=/demoralizing_shout,if=incoming_damage_2500ms>health.max*0.1&!(debuff.demoralizing_shout.up|buff.ravager_protection.up|buff.shield_wall.up|buff.last_stand.up|buff.enraged_regeneration.up|buff.shield_block.up|buff.potion.up) { "Demoralizing Shout", { "player.health <= 60", "!target.debuff(Demoralizing Shout)" } }, { "Demoralizing Shout", { "player.health <= 60", "!player.buff(Ravager Protection)" } }, { "Demoralizing Shout", { "player.health <= 60", "!player.buff(Shield Wall)" } }, { "Demoralizing Shout", { "player.health <= 60", "!player.buff(Last Stand)" } }, { "Demoralizing Shout", { "player.health <= 60", "!player.buff(Enraged Regeneration)" } }, { "Demoralizing Shout", { "player.health <= 60", "!player.buff(Shield Block)" } }, { "Demoralizing Shout", { "player.health <= 60", "!player.buff(Draenic Armor Potion)" } }, -- actions.prot+=/shield_wall,if=incoming_damage_2500ms>health.max*0.1&!(debuff.demoralizing_shout.up|buff.ravager_protection.up|buff.shield_wall.up|buff.last_stand.up|buff.enraged_regeneration.up|buff.shield_block.up|buff.potion.up) { "Shield Wall", { "player.health <= 60", "!target.debuff(Demoralizing Shout)" } }, { "Shield Wall", { "player.health <= 60", "!player.buff(Ravager Protection)" } }, { "Shield Wall", { "player.health <= 60", "!player.buff(Shield Wall)" } }, { "Shield Wall", { "player.health <= 60", "!player.buff(Last Stand)" } }, { "Shield Wall", { "player.health <= 60", "!player.buff(Enraged Regeneration)" } }, { "Shield Wall", { "player.health <= 60", "!player.buff(Shield Block)" } }, { "Shield Wall", { "player.health <= 60", "!player.buff(Draenic Armor Potion)" } }, -- actions.prot+=/last_stand,if=incoming_damage_2500ms>health.max*0.1&!(debuff.demoralizing_shout.up|buff.ravager_protection.up|buff.shield_wall.up|buff.last_stand.up|buff.enraged_regeneration.up|buff.shield_block.up|buff.potion.up) { "Last Stand", { "player.health <= 60", "!target.debuff(Demoralizing Shout)" } }, { "Last Stand", { "player.health <= 60", "!player.buff(Ravager Protection)" } }, { "Last Stand", { "player.health <= 60", "!player.buff(Shield Wall)" } }, { "Last Stand", { "player.health <= 60", "!player.buff(Last Stand)" } }, { "Last Stand", { "player.health <= 60", "!player.buff(Enraged Regeneration)" } }, { "Last Stand", { "player.health <= 60", "!player.buff(Shield Block)" } }, { "Last Stand", { "player.health <= 60", "!player.buff(Draenic Armor Potion)" } }, -- actions.prot+=/stoneform,if=incoming_damage_2500ms>health.max*0.1&!(debuff.demoralizing_shout.up|buff.ravager_protection.up|buff.shield_wall.up|buff.last_stand.up|buff.enraged_regeneration.up|buff.shield_block.up|buff.potion.up) { "Stoneform", { "player.health <= 60", "!target.debuff(Demoralizing Shout)" } }, { "Stoneform", { "player.health <= 60", "!player.buff(Ravager Protection)" } }, { "Stoneform", { "player.health <= 60", "!player.buff(Shield Wall)" } }, { "Stoneform", { "player.health <= 60", "!player.buff(Last Stand)" } }, { "Stoneform", { "player.health <= 60", "!player.buff(Enraged Regeneration)" } }, { "Stoneform", { "player.health <= 60", "!player.buff(Shield Block)" } }, { "Stoneform", { "player.health <= 60", "!player.buff(Draenic Armor Potion)" } }, }, { "modifier.cooldowns", "target.exists", "target.enemy", "target.alive", "target.distance <= 5" } }, -- ** "Non-Smart" Single Target Rotation <= 2 ** { { -- actions.prot+=/heroic_strike,if=buff.ultimatum.up|(talent.unyielding_strikes.enabled&buff.unyielding_strikes.stack>=6) { "Heroic Strike", "player.buff(Ultimatum)" }, { "Heroic Strike", { "talent(3, 3)", "player.buff(Unyielding Strikes).count >= 6" } }, -- actions.prot+=/bloodbath,if=talent.bloodbath.enabled&((cooldown.dragon_roar.remains=0&talent.dragon_roar.enabled)|(cooldown.storm_bolt.remains=0&talent.storm_bolt.enabled)|talent.shockwave.enabled) { "Bloodbath", { "talent(6, 2)", "player.spell(Dragon Roar).cooldown == 0", "talent(4, 3)" } }, { "Bloodbath", { "talent(6, 2)", "player.spell(Storm Bolt).cooldown == 0", "talent(4, 1)" } }, { "Bloodbath", { "talent(6, 2)", "talent(4, 2)" } }, -- actions.prot+=/avatar,if=talent.avatar.enabled&((cooldown.ravager.remains=0&talent.ravager.enabled)|(cooldown.dragon_roar.remains=0&talent.dragon_roar.enabled)|(talent.storm_bolt.enabled&cooldown.storm_bolt.remains=0)|(!(talent.dragon_roar.enabled|talent.ravager.enabled|talent.storm_bolt.enabled))) { "Avatar", { "talent(6, 1)", "player.spell(Ravager).cooldown == 0", "talent(7, 2)" } }, { "Avatar", { "talent(6, 1)", "player.spell(Dragon Roar).cooldown == 0", "talent(4, 3)" } }, { "Avatar", { "talent(6, 1)", "player.spell(Storm Bolt).cooldown == 0", "talent(4, 1)" } }, { "Avatar", { "talent(6, 1)", "!talent(4, 3)" } }, { "Avatar", { "talent(6, 1)", "!talent(7, 2)" } }, { "Avatar", { "talent(6, 1)", "!talent(4, 1)" } }, -- actions.prot+=/shield_slam { "Shield Slam" }, -- actions.prot+=/revenge { "Revenge" }, -- actions.prot+=/ravager { "Ravager" }, -- actions.prot+=/storm_bolt { "Storm Bolt" }, -- actions.prot+=/dragon_roar { "Dragon Roar" }, -- actions.prot+=/impending_victory,if=talent.impending_victory.enabled&cooldown.shield_slam.remains<=execute_time { "Impending Victory", { "talent(2, 3)", "player.health <= 85" } }, -- actions.prot+=/victory_rush,if=!talent.impending_victory.enabled&cooldown.shield_slam.remains<=execute_time { "Victory Rush", { "!talent(2, 3)", "player.health <= 85" } }, -- actions.prot+=/execute,if=buff.sudden_death.react { "Execute", "player.buff(Sudden Death)" }, -- actions.prot+=/devastate { "Devastate" }, }, { "!modifier.multitarget", "!toggle.smartaoe" } }, -- actions.prot+=/call_action_list,name=prot_aoe,if=active_enemies>3 -- "Non-Smart" Cleave AoE Rotation >= 4 { { -- actions.prot_aoe=bloodbath { "Bloodbath" }, -- actions.prot_aoe+=/avatar { "Avatar" }, -- actions.prot_aoe+=/thunder_clap,if=!dot.deep_wounds.ticking { "Thunder Clap", "!target.debuff(Deep Wounds)" }, -- actions.prot_aoe+=/heroic_strike,if=buff.ultimatum.up|rage>110|(talent.unyielding_strikes.enabled&buff.unyielding_strikes.stack>=6) { "Heroic Strike", "player.buff(Ultimatum)" }, { "Heroic Strike", "player.rage > 110" }, { "Heroic Strike", { "player.buff(Unyielding Strikes).count >=6", "talent(3, 3)" } }, -- actions.prot_aoe+=/heroic_leap,if=(raid_event.movement.distance>25&raid_event.movement.in>45)|!raid_event.movement.exists -- *** player controlled action only *** -- actions.prot_aoe+=/shield_slam,if=buff.shield_block.up { "Shield Slam", "player.buff(Shield Block)" }, -- actions.prot_aoe+=/ravager,if=(buff.avatar.up|cooldown.avatar.remains>10)|!talent.avatar.enabled { "Ravager", { "talent(6, 1)", "player.buff(Avatar)" } }, { "Ravager", { "talent(6, 1)", "player.spell(Avatar).cooldown > 10" } }, { "Ravager", "!talent(6, 1)" }, -- actions.prot_aoe+=/dragon_roar,if=(buff.bloodbath.up|cooldown.bloodbath.remains>10)|!talent.bloodbath.enabled { "Dragon Roar", { "talent(6, 2)", "player.buff(Bloodbath)" } }, { "Dragon Roar", { "talent(6, 2)", "player.spell(Bloodbath).cooldown > 10" } }, { "Dragon Roar", "!talent(6, 2)" }, -- actions.prot_aoe+=/shockwave { "Shockwave" }, -- actions.prot_aoe+=/revenge { "Revenge" }, -- actions.prot_aoe+=/thunder_clap { "Thunder Clap" }, -- actions.prot_aoe+=/bladestorm { "Bladestorm" }, -- actions.prot_aoe+=/shield_slam { "Shield Slam" }, -- actions.prot_aoe+=/storm_bolt { "Storm Bolt" }, -- actions.prot_aoe+=/shield_slam { "Shield Slam" }, -- actions.prot_aoe+=/execute,if=buff.sudden_death.react { "Execute", "player.buff(Sudden Death)" }, -- actions.prot_aoe+=/devastate { "Devastate" }, }, { "modifier.multitarget", "!toggle.smartaoe" } }, -- ** "Smart" Single Target Rotation <= 3 ** { { -- actions.prot+=/heroic_strike,if=buff.ultimatum.up|(talent.unyielding_strikes.enabled&buff.unyielding_strikes.stack>=6) { "Heroic Strike", "player.buff(Ultimatum)" }, { "Heroic Strike", { "talent(3, 3)", "player.buff(Unyielding Strikes).count >= 6" } }, -- actions.prot+=/bloodbath,if=talent.bloodbath.enabled&((cooldown.dragon_roar.remains=0&talent.dragon_roar.enabled)|(cooldown.storm_bolt.remains=0&talent.storm_bolt.enabled)|talent.shockwave.enabled) { "Bloodbath", { "talent(6, 2)", "player.spell(Dragon Roar).cooldown == 0", "talent(4, 3)" } }, { "Bloodbath", { "talent(6, 2)", "player.spell(Storm Bolt).cooldown == 0", "talent(4, 1)" } }, { "Bloodbath", { "talent(6, 2)", "talent(4, 2)" } }, -- actions.prot+=/avatar,if=talent.avatar.enabled&((cooldown.ravager.remains=0&talent.ravager.enabled)|(cooldown.dragon_roar.remains=0&talent.dragon_roar.enabled)|(talent.storm_bolt.enabled&cooldown.storm_bolt.remains=0)|(!(talent.dragon_roar.enabled|talent.ravager.enabled|talent.storm_bolt.enabled))) { "Avatar", { "talent(6, 1)", "player.spell(Ravager).cooldown == 0", "talent(7, 2)" } }, { "Avatar", { "talent(6, 1)", "player.spell(Dragon Roar).cooldown == 0", "talent(4, 3)" } }, { "Avatar", { "talent(6, 1)", "player.spell(Storm Bolt).cooldown == 0", "talent(4, 1)" } }, { "Avatar", { "talent(6, 1)", "!talent(4, 3)" } }, { "Avatar", { "talent(6, 1)", "!talent(7, 2)" } }, { "Avatar", { "talent(6, 1)", "!talent(4, 1)" } }, -- actions.prot+=/shield_slam { "Shield Slam" }, -- actions.prot+=/revenge { "Revenge" }, -- actions.prot+=/ravager { "Ravager" }, -- actions.prot+=/storm_bolt { "Storm Bolt" }, -- actions.prot+=/dragon_roar { "Dragon Roar" }, -- actions.prot+=/impending_victory,if=talent.impending_victory.enabled&cooldown.shield_slam.remains<=execute_time { "Impending Victory", { "talent(2, 3)", "player.health <= 85" } }, -- actions.prot+=/victory_rush,if=!talent.impending_victory.enabled&cooldown.shield_slam.remains<=execute_time { "Victory Rush", { "!talent(2, 3)", "player.health <= 85" } }, -- actions.prot+=/execute,if=buff.sudden_death.react { "Execute", "player.buff(Sudden Death)" }, -- actions.prot+=/devastate { "Devastate" }, }, { "toggle.smartaoe", "!player.area(8)enemies >= 4" } }, -- "Smart" Cleave AoE Rotation >= 4 { { -- actions.prot_aoe=bloodbath { "Bloodbath" }, -- actions.prot_aoe+=/avatar { "Avatar" }, -- actions.prot_aoe+=/thunder_clap,if=!dot.deep_wounds.ticking { "Thunder Clap", "!target.debuff(Deep Wounds)" }, -- actions.prot_aoe+=/heroic_strike,if=buff.ultimatum.up|rage>110|(talent.unyielding_strikes.enabled&buff.unyielding_strikes.stack>=6) { "Heroic Strike", "player.buff(Ultimatum)" }, { "Heroic Strike", "player.rage > 110" }, { "Heroic Strike", { "player.buff(Unyielding Strikes).count >=6", "talent(3, 3)" } }, -- actions.prot_aoe+=/heroic_leap,if=(raid_event.movement.distance>25&raid_event.movement.in>45)|!raid_event.movement.exists -- *** player controlled action only *** -- actions.prot_aoe+=/shield_slam,if=buff.shield_block.up { "Shield Slam", "player.buff(Shield Block)" }, -- actions.prot_aoe+=/ravager,if=(buff.avatar.up|cooldown.avatar.remains>10)|!talent.avatar.enabled { "Ravager", { "talent(6, 1)", "player.buff(Avatar)" } }, { "Ravager", { "talent(6, 1)", "player.spell(Avatar).cooldown > 10" } }, { "Ravager", "!talent(6, 1)" }, -- actions.prot_aoe+=/dragon_roar,if=(buff.bloodbath.up|cooldown.bloodbath.remains>10)|!talent.bloodbath.enabled { "Dragon Roar", { "talent(6, 2)", "player.buff(Bloodbath)" } }, { "Dragon Roar", { "talent(6, 2)", "player.spell(Bloodbath).cooldown > 10" } }, { "Dragon Roar", "!talent(6, 2)" }, -- actions.prot_aoe+=/shockwave { "Shockwave" }, -- actions.prot_aoe+=/revenge { "Revenge" }, -- actions.prot_aoe+=/thunder_clap { "Thunder Clap" }, -- actions.prot_aoe+=/bladestorm { "Bladestorm" }, -- actions.prot_aoe+=/shield_slam { "Shield Slam" }, -- actions.prot_aoe+=/storm_bolt { "Storm Bolt" }, -- actions.prot_aoe+=/shield_slam { "Shield Slam" }, -- actions.prot_aoe+=/execute,if=buff.sudden_death.react { "Execute", "player.buff(Sudden Death)" }, -- actions.prot_aoe+=/devastate { "Devastate" }, }, { "toggle.smartaoe", "player.area(8)enemies >= 4" } }, }, { ---- *** OUT OF COMBAT ROUTINE SECTION *** -- Pauses { "pause", "modifier.lcontrol" }, { "pause", "@bbLib.pauses" }, -- Buttons { "Heroic Leap", { "modifier.lalt" }, "ground" }, -- Buffs { "Battle Shout", { "!player.buffs.attackpower", "lowest.distance <= 30", "!modifier.last" }, "lowest" }, { "Commanding Shout", { "!player.buffs.attackpower", "!player.buffs.stamina", "lowest.distance <= 30", "!modifier.last" }, "lowest" }, -- OOC Healing { "#118935", { "player.health < 80", "!player.ininstance(raid)" } }, -- Ever-Blooming Frond 15% health/mana every 1 sec for 6 sec. 5 min CD -- Mass Resurrection { "Mass Resurrection", { "!player.moving", "!modifier.last", "target.exists", "target.friendly", "!target.alive", "target.distance.actual < 100" } }, -- Auto Grinding { { { "Battle Shout", "@bbLib.engaugeUnit('ANY', 30, true)" }, { "Taunt" }, }, { "toggle.autogrind" } }, }, -- [Section Closing Curly Brace] ---- *** TOGGLE BUTTONS *** function() NetherMachine.toggle.create('mouseovers', 'Interface\\Icons\\inv_pet_lilsmoky', 'Use Mouseovers', 'Automatically cast spells on mouseover targets.') NetherMachine.toggle.create('autotarget', 'Interface\\Icons\\ability_hunter_snipershot', 'Auto Target', 'Automaticaly target the nearest enemy when target dies or does not exist.') NetherMachine.toggle.create('consume', 'Interface\\Icons\\inv_alchemy_endlessflask_06', 'Use Consumables', 'Toggle the usage of Flasks/Food/Potions etc..') NetherMachine.toggle.create('smartaoe', 'Interface\\Icons\\Ability_Racial_RocketBarrage', 'Enable Smart AoE Detection', 'Toggle the usage of smart detection of Single/AoE target roation selection abilities.') NetherMachine.toggle.create('limitaoe', 'Interface\\Icons\\spell_fire_flameshock', 'Limit AoE', 'Toggle to not use AoE spells to avoid breaking CC.') NetherMachine.toggle.create('autogrind', 'Interface\\Icons\\inv_misc_fish_33', 'Auto Attack', 'Automaticly target and attack nearby enemies.') end) -- actions.precombat=flask,type=greater_draenic_stamina_flask -- actions.precombat+=/food,type=sleeper_sushi -- actions.precombat+=/stance,choose=defensive -- actions.precombat+=/snapshot_stats -- actions.precombat+=/shield_wall -- actions.precombat+=/potion,name=draenic_armor
agpl-3.0
htx/mmoserver
data/script/TutorialPart_2_9.lua
5
1099
-- TutorialPart_2_9 -- Get access to Tutorial via ScriptEngine local script = LuaScriptEngine.getScriptObj(); local SE = ScriptEngine:Init(); local tutorial = SE:getTutorial(script); -- Verify correct state local state = tutorial:getState(); -- wait for client to become ready. while tutorial:getReady() == false do LuaScriptEngine.WaitMSec(100) end -- tutorial:disableHudElement("all"); -- Disable all hud elements -- tutorial:enableHudElement("all"); -- Disable all hud elements while state == 2 do local subState = tutorial:getSubState(); if subState == 1 then LuaScriptEngine.WaitMSec(3000); -- "PART TWO OF NINE (conversing with npcs and inventory) " tutorial:scriptSystemMessage("@newbie_tutorial/system_messages:part_2"); LuaScriptEngine.WaitMSec(1000); -- "Move forward and click-and-hold your mouse on the Imperial Officer until the radial menu appears. " tutorial:scriptSystemMessage("@newbie_tutorial/system_messages:tut_08"); tutorial:scriptPlayMusic(1550); -- sound/tut_08_imperialofficer.snd end state = tutorial:getState(); end
gpl-3.0
ArmanIr/Telegrambotarman
plugins/modaration2.lua
4
11067
local function kick_by_reply_callback(extra, success, result) if is_administrator(result.from.id) then send_msg(extra, "You can't kick admin!", ok_cb, false) else local del = chat_del_user("chat#id"..result.to.id, "user#id"..result.from.id, ok_cb, false) if del == false then send_msg(extra, "Kicking failed.", ok_cb, false) return end end end 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 superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..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 is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned 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 superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or 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 superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end 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 username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id 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 get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'superban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!') return superban_user(member_id, chat_id) elseif get_cmd == 'whitelist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'whitelist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'kickme' then if msg.to.type ~= 'chat' then return "This is not a chat group!" elseif user == tostring(our_id) then --[[ A robot must protect its own existence as long as such protection does not conflict with the First or Second Laws. ]]-- return "I won't kick myself!" elseif is_sudo(msg) then return "I won't kick an admin!" else kick_user(msg.from.id, msg.to.id) end end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] 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 if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end 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] == 'superban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' globally banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if msg.reply_id then msgr = get_message(msg.reply_id, kick_by_reply_callback, get_receiver(msg)) elseif string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if matches[1] == 'whitelist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end 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.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end 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.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Plugin to manage bans, kicks and white/black lists.", usage = { user = "!kickme : Exit from group", moderator = { "!whitelist <enable>/<disable> : Enable or disable whitelist mode", "!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled", "!whitelist user <username> : 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 user <username> : Kick user from chat and kicks it if joins chat again", "!ban delete <user_id> : Unban user", "!kick : Kick user from chat group by reply", "!kickme : Bot kick users", "!kick <user_id> : Kick user from chat group by id", "!kick <username> : Kick user from chat group by username", }, admin = { "!superban user <user_id> : Kick user from all chat and kicks it if joins again", "!superban user <username> : Kick user from all chat and kicks it if joins again", "!superban delete <user_id> : Unban user", }, }, patterns = { "^!(whitelist) (enable)$", "^!(whitelist) (disable)$", "^!(whitelist) (user) (.*)$", "^!(whitelist) (chat)$", "^!(whitelist) (delete) (user) (.*)$", "^!(whitelist) (delete) (chat)$", "^!(ban) (user) (.*)$", "^!(ban) (delete) (.*)$", "^!(superban) (user) (.*)$", "^!(superban) (delete) (.*)$", "^!(kick)$", "^!(kick) (.*)$", "^!(kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
coder-han/hugula
Client/tools/netProtocal/NetProtocalParserCode.lua
8
3668
------------------- NetProtocalPaser--------------- local NetAPIList = NetAPIList NetProtocalPaser = {} function NetProtocalPaser:parsestring(msg, key, parentTable) parentTable[key] = msg:ReadString() end function NetProtocalPaser:parseinteger(msg, key, parentTable) parentTable[key] = msg:ReadInt() end function NetProtocalPaser:parsefloat(msg, key, parentTable) parentTable[key] = msg:ReadFloat() end function NetProtocalPaser:parseshort(msg, key, parentTable) parentTable[key] = msg:ReadShort() end function NetProtocalPaser:parsebyte(msg, key, parentTable) parentTable[key] = msg:ReadByte() end function NetProtocalPaser:parseboolean(msg, key, parentTable) parentTable[key] = msg:ReadBoolean() end function NetProtocalPaser:parsepkid(msg,key,parentTable) parentTable[key] = msg:ReadString() end function NetProtocalPaser:parsechar(msg,key,parentTable) parentTable[key] = msg:ReadChar() end function NetProtocalPaser:parseushort(msg,key,parentTable) parentTable[key] = msg:ReadUShort() end function NetProtocalPaser:parseuint(msg,key,parentTable) parentTable[key] = msg:ReadUInt() end function NetProtocalPaser:parseulong(msg,key,parentTable) parentTable[key] = msg:ReadULong() end function NetProtocalPaser:formatstring(msg, value) msg:WriteString(value) end function NetProtocalPaser:formatinteger(msg, value) msg:WriteInt(value) end function NetProtocalPaser:formatshort(msg, value) msg:WriteShort(value) end function NetProtocalPaser:formatfloat(msg, value) msg:WriteFloat(value) end function NetProtocalPaser:formatbyte(msg, value) msg:WriteByte(value) end function NetProtocalPaser:formatboolean(msg, value) msg:WriteBoolean(value) end function NetProtocalPaser:formatchar(msg, value) msg:WriteChar(value) end function NetProtocalPaser:formatushort(msg, value) msg:WriteUShort(value) end function NetProtocalPaser:formatuint(msg, value) msg:WriteUInt(value) end function NetProtocalPaser:formatulong(msg, value) msg:WriteULong(value) end function NetProtocalPaser:formatArray(msg, value, valueType) local funcName = "format" .. valueType local func = self[funcName] local arrayLen = #value msg:WriteUShort(arrayLen) for i=1, arrayLen, 1 do local v = value[i] func(self,msg,v) end end function NetProtocalPaser:formatpkid(msg,value) msg:WriteString(value) end function NetProtocalPaser:parseArray(msg, key, parentTable, valueType) local funcName = "parse" .. valueType local func = self[funcName] parentTable[key]= {} local arrayLen = msg:ReadUShort() for i=1, arrayLen, 1 do local tempT = {} func(self,msg,"tempK", tempT) table.insert(parentTable[key],tempT.tempK) end end function NetProtocalPaser:parseMessage(msg,msgType) local result = {} msgType = "MSGTYPE" .. msgType local dataStructName = NetAPIList:getDataStructFromMsgType(msgType) if(dataStructName ~= "null") then local funcName = "parse"..dataStructName local func = NetProtocalPaser[funcName] func(self, msg,nil,result) end return result end function NetProtocalPaser:formatMessage(msg,msgType, content) msg:set_Type(msgType) msgType = "MSGTYPE" .. msgType local dataStructName = NetAPIList:getDataStructFromMsgType(msgType) if(dataStructName ~= "null") then local funcName = "format"..dataStructName --print("---- formatMessage func name--- " .. funcName) local func = NetProtocalPaser[funcName] func(self, msg, content) end end
mit
MidflightDigital/ddrsn3-theme
DDR SN3/BGAnimations/ScreenWithMenuElements background/_SN3V2.lua
2
4534
local t = Def.ActorFrame{ }; local p = { red = color("1,0,0,0.812"), green = color("0,1,0,0.812"), blue = color("0,0,1,0.812"), yellow = color("1,1,0,0.812"), pink = color("1,0,1,0.812"), cyan = color("0,1,1,0.812") } local colorPatterns = { --first pattern block: YRPBCG with different start indices {[0]=p.yellow, p.red, p.pink, p.blue, p.cyan, p.green}, --second pattern block: GCBPRY with different start indices {[0]=p.pink, p.red, p.yellow, p.green, p.cyan, p.blue} } local curPattern = 1 local curPatternIdx = 0 t[#t+1] = Def.ActorFrame { InitCommand=function(self) self:fov(120); end; Def.ActorFrame{ LoadActor(THEME:GetPathB("","_shared/SN3/back"))..{ InitCommand=cmd(FullScreen); --My god you are amazing kenp. OnCommand=function(self) local seed = math.random(1,13); --seed breakdown: --8-13: pattern 1, increasing start color --2-7: pattern 2, increasing start color --1: rainbow if seed > 1 then if seed > 7 then curPattern = 1 curPatternIdx = seed - 8 else curPattern = 2 curPatternIdx = seed - 2 end self:diffuse(colorPatterns[curPattern][curPatternIdx]) self:queuecommand("Animate") else self:rainbow(); self:effectperiod(120); end; end; AnimateCommand = function(s) --bump the current color to the next color in the pattern curPatternIdx = (curPatternIdx + 1) % #(colorPatterns[curPattern]) s:linear(20) :diffuse(colorPatterns[curPattern][curPatternIdx]) :queuecommand("Animate") end; }; }; Def.ActorFrame{ InitCommand=cmd(x,SCREEN_LEFT+120;CenterY;blend,Blend.Add;;diffusealpha,0.6); LoadActor(THEME:GetPathB("","_shared/stars"))..{ InitCommand=cmd(diffusealpha,0.3;fadetop,0.5;fadebottom,0.5;rotationy,16); OnCommand=function(self) local w = DISPLAY:GetDisplayWidth() / self:GetWidth(); local h = DISPLAY:GetDisplayHeight() / self:GetHeight(); self:customtexturerect(0,0,w*0.5,h*0.5); self:texcoordvelocity(-0.02,0); end; }; LoadActor(THEME:GetPathB("","_shared/stars"))..{ InitCommand=cmd(diffusealpha,0.3;fadetop,0.5;fadebottom,0.5;rotationy,16); OnCommand=function(self) local w = DISPLAY:GetDisplayWidth() / self:GetWidth(); local h = DISPLAY:GetDisplayHeight() / self:GetHeight(); self:customtexturerect(0,0,w*0.5,h*0.5); self:texcoordvelocity(-0.03,0); end; }; }; }; if ThemePrefs.Get("LightMode") then return t end t[#t+1] = Def.ActorFrame{ InitCommand=function(self) self:fov(120); self:xy(SCREEN_LEFT-320,SCREEN_TOP-60); end; Def.ActorFrame{ InitCommand=cmd(zbuffer,true;z,-500;blend,Blend.Add); Def.ActorFrame{ InitCommand=cmd(rotationx,12;rotationz,22); LoadActor(THEME:GetPathB("","_shared/SN3/SuperNovaFogBall.txt"))..{ InitCommand=cmd(diffusealpha,0.25;blend,Blend.Add;zoom,20;spin;effectmagnitude,0,80,0); }; LoadActor(THEME:GetPathB("","_shared/SN3/2ndSuperNovaFogBall.txt"))..{ InitCommand=cmd(diffusealpha,0.25;blend,Blend.Add;zoom,20;spin;effectmagnitude,0,-80,0); }; }; LoadActor(THEME:GetPathB("","_shared/IIDX 17/wakusei/ring.png"))..{ InitCommand=cmd(queuecommand,"Anim"); AnimCommand=cmd(blend,Blend.Add;diffusealpha,0.5;rotationx,75;rotationy,-60;zoom,2.4;spin;effectmagnitude,0,0,100); }; LoadActor(THEME:GetPathB("","_shared/IIDX 17/wakusei/ring.png"))..{ InitCommand=cmd(queuecommand,"Anim"); AnimCommand=cmd(blend,Blend.Add;diffusealpha,0.5;rotationx,85;rotationy,-15;zoom,2.5;spin,effectmagnitude,0,0,100); }; LoadActor(THEME:GetPathB("","_shared/IIDX 17/wakusei/ring 2.png"))..{ InitCommand=cmd(queuecommand,"Anim"); AnimCommand=cmd(blend,Blend.Add;diffusealpha,1;rotationx,83;rotationy,10;zoom,2.5;spin,effctmagnitude,0,0,-100); }; }; }; t[#t+1] = Def.ActorFrame{ InitCommand=function(self) self:fov(120); end; LoadActor(THEME:GetPathB("","_shared/IIDX 17/shineget"))..{ InitCommand=cmd(rotationy,16); }; LoadActor(THEME:GetPathB("","_shared/IIDX 17/wakusei/meter 1 (stretch).png"))..{ InitCommand=cmd(x,SCREEN_LEFT-80;CenterY;zoomtowidth,SCREEN_WIDTH;zoomtoheight,SCREEN_HEIGHT;rotationy,16); OnCommand=function(self) local w = DISPLAY:GetDisplayWidth() / self:GetWidth(); local h = DISPLAY:GetDisplayHeight() / self:GetHeight(); self:customtexturerect(0,0,w*0.5,h*0.5); self:rotationz(90) self:texcoordvelocity(0.2,0); self:blend(Blend.Add); end; }; }; return t;
mit
M4STERANGEL/M4STER_Bot
plugins/urbandictionary.lua
16
1309
local command = 'urbandictionary <query>' local doc = [[``` /urbandictionary <query> Returns a definition from Urban Dictionary. Aliases: /ud, /urban ```]] local triggers = { '^/urbandictionary[@'..bot.username..']*', '^/ud[@'..bot.username..']*$', '^/ud[@'..bot.username..']* ', '^/urban[@'..bot.username..']*' } local action = function(msg) local input = msg.text:input() if not input then if msg.reply_to_message and msg.reply_to_message.text then input = msg.reply_to_message.text else sendMessage(msg.chat.id, doc, true, msg.message_id, true) return end end local url = 'http://api.urbandictionary.com/v0/define?term=' .. URL.escape(input) local jstr, res = HTTP.request(url) if res ~= 200 then sendReply(msg, config.errors.connection) return end local jdat = JSON.decode(jstr) if jdat.result_type == "no_results" then sendReply(msg, config.errors.results) return end local output = '*' .. jdat.list[1].word .. '*\n\n' .. jdat.list[1].definition:trim() if string.len(jdat.list[1].example) > 0 then output = output .. '_\n\n' .. jdat.list[1].example:trim() .. '_' end output = output:gsub('%[', ''):gsub('%]', '') sendMessage(msg.chat.id, output, true, nil, true) end return { action = action, triggers = triggers, doc = doc, command = command }
gpl-3.0
To0fan/ali
plugins/owners.lua
20
23763
local function lock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_arabic(msg, data, target) local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic/Persian is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic/Persian has been unlocked' end end local function lock_group_links(msg, data, target) local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Link posting is already locked' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Link posting has been locked' end end local function unlock_group_links(msg, data, target) local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Link posting is not locked' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Link posting has been unlocked' end end local function lock_group_spam(msg, data, target) local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return 'SuperGroup spam is already locked' else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'SuperGroup spam has been locked' end end local function unlock_group_spam(msg, data, target) local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return 'SuperGroup spam is not locked' else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup spam has been unlocked' end end local function lock_group_sticker(msg, data, target) local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker posting is already locked' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker posting has been locked' end end local function unlock_group_sticker(msg, data, target) local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker posting is already unlocked' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker posting has been unlocked' end end local function lock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'yes' then return 'Contact posting is already locked' else data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) return 'Contact posting has been locked' end end local function unlock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'no' then return 'Contact posting is already unlocked' else data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) return 'Contact posting has been unlocked' end end local function enable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['strict'] if strict == 'yes' then return 'Settings are already strictly enforced' else data[tostring(target)]['settings']['strict'] = 'yes' save_data(_config.moderation.data, data) return 'Settings will be strictly enforced' end end local function disable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['strict'] if strict == 'no' then return 'Settings will not be strictly enforced' else data[tostring(target)]['settings']['strict'] = 'no' save_data(_config.moderation.data, data) return 'Settings are not strictly enforced' end end -- Show group settings local function show_group_settingsmod(msg, data, target) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(target)]['settings']['lock_bots'] then bots_protection = data[tostring(target)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(target)]['settings']['leave_ban'] then leave_ban = data[tostring(target)]['settings']['leave_ban'] end local public = "no" if data[tostring(target)]['settings'] then if data[tostring(target)]['settings']['public'] then public = data[tostring(target)]['settings']['public'] end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection.."\nPublic: "..public return text end -- Show SuperGroup settings local function show_super_group_settings(msg, data, target) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict return text end local function set_rules(target, rules) local data = load_data(_config.moderation.data) local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function set_description(target, about) local data = load_data(_config.moderation.data) local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function run(msg, matches) if msg.to.type == 'user' then local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", " ") local chat_id = matches[1] local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) if matches[2] == 'ban' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't ban yourself" end ban_user(matches[3], matches[1]) local name = user_print_name(msg.from) savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3]) return 'User '..user_id..' banned' end if matches[2] == 'unban' then if tonumber(matches[3]) == tonumber(our_id) then return false end local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't unban yourself" end local hash = 'banned:'..matches[1] redis:srem(hash, user_id) savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3]) return 'User '..user_id..' unbanned' end if matches[2] == 'kick' then local chat_id = matches[1] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) == tonumber(our_id) then return false end local user_id = matches[3] if tonumber(matches[3]) == tonumber(msg.from.id) then return "You can't kick yourself" end kick_user(matches[3], chat_id) savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3]) return 'User '..user_id..' kicked' end if matches[2] == 'clean' then if matches[3] == 'modlist' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end for k,v in pairs(data[tostring(matches[1])]['moderators']) do data[tostring(matches[1])]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist") end if matches[3] == 'rules' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'rules' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules") end if matches[3] == 'about' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local data_cat = 'description' data[tostring(matches[1])][data_cat] = nil save_data(_config.moderation.data, data) savelog(matches[1], name.." ["..msg.from.id.."] cleaned about") channel_set_about(receiver, about_text, ok_cb, false) return "About has been cleaned" end if matches[3] == 'mutelist' then chat_id = string.match(matches[1], '^%d+$') local hash = 'mute_user:'..chat_id redis:del(hash) return "Mutelist Cleaned" end end if matches[2] == "setflood" then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[3] data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]") return 'Group flood has been set to '..matches[3] end if matches[2] == 'lock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] local group_type = data[tostring(matches[1])]['group_type'] if matches[3] == 'name' then savelog(matches[1], name.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[3] == 'member' then savelog(matches[1], name.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[3] == 'arabic' then savelog(matches[1], name.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[3] == 'links' then savelog(matches[1], name.." ["..msg.from.id.."] locked links ") return lock_group_links(msg, data, target) end if matches[3] == 'spam' then savelog(matches[1], name.." ["..msg.from.id.."] locked spam ") return lock_group_spam(msg, data, target) end if matches[3] == 'rtl' then savelog(matches[1], name.." ["..msg.from.id.."] locked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' then savelog(matches[1], name.." ["..msg.from.id.."] locked sticker") return lock_group_sticker(msg, data, target) end end if matches[2] == 'unlock' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local target = matches[1] local group_type = data[tostring(matches[1])]['group_type'] if matches[3] == 'name' then savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[3] == 'member' then savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[3] == 'arabic' then savelog(matches[1], name.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[3] == 'links' and group_type == "SuperGroup" then savelog(matches[1], name.." ["..msg.from.id.."] unlocked links ") return unlock_group_links(msg, data, target) end if matches[3] == 'spam' and group_type == "SuperGroup" then savelog(matches[1], name.." ["..msg.from.id.."] unlocked spam ") return unlock_group_spam(msg, data, target) end if matches[3] == 'rtl' then savelog(matches[1], name.." ["..msg.from.id.."] unlocked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' and group_type == "SuperGroup" then savelog(matches[1], name.." ["..msg.from.id.."] unlocked sticker") return unlock_group_sticker(msg, data, target) end if matches[3] == 'contacts' and group_type == "SuperGroup" then savelog(matches[1], name_log.." ["..msg.from.id.."] locked contact posting") return lock_group_contacts(msg, data, target) end if matches[3] == 'strict' and group_type == "SuperGroup" then savelog(matches[1], name_log.." ["..msg.from.id.."] locked enabled strict settings") return enable_strict_rules(msg, data, target) end end if matches[2] == 'new' then if matches[3] == 'link' then local group_type = data[tostring(matches[1])]['group_type'] if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local function callback_grouplink (extra , success, result) local receiver = 'chat#id'..matches[1] if success == 0 then send_large_msg(receiver, '*Error: Failed to retrieve link* \nReason: Not creator.') end data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return end local function callback_superlink (extra , success, result) vardump(result) local receiver = 'channel#id'..matches[1] local user = extra.user if success == 0 then data[tostring(matches[1])]['settings']['set_link'] = nil save_data(_config.moderation.data, data) return send_large_msg(user, '*Error: Failed to retrieve link* \nReason: Not creator.\n\nIf you have the link, please use /setlink to set it') else data[tostring(matches[1])]['settings']['set_link'] = result save_data(_config.moderation.data, data) return send_large_msg(user, "Created a new link") end end if group_type == "Group" then local receiver = 'chat#id'..matches[1] savelog(matches[1], name.." ["..msg.from.id.."] created/revoked group link ") export_chat_link(receiver, callback_grouplink, false) return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link" elseif group_type == "SuperGroup" then local receiver = 'channel#id'..matches[1] local user = 'user#id'..msg.from.id savelog(matches[1], name.." ["..msg.from.id.."] attempted to create a new SuperGroup link") export_channel_link(receiver, callback_superlink, {user = user}) end end end if matches[2] == 'get' then if matches[3] == 'link' then if not is_owner2(msg.from.id, chat_id) then return "You are not the owner of this group" end local group_link = data[tostring(matches[1])]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end end if matches[1] == 'changeabout' and matches[2] then if not is_owner2(msg.from.id, matches[2]) then return "You are not the owner of this group" end local group_type = data[tostring(matches[2])]['group_type'] if group_type == "Group" or group_type == "Realm" then local target = matches[2] local about = matches[3] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_description(target, about) elseif group_type == "SuperGroup" then local channel = 'channel#id'..matches[2] local about_text = matches[3] local data_cat = 'description' local target = matches[2] channel_set_about(channel, about_text, ok_cb, false) data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) savelog(matches[2], name.." ["..msg.from.id.."] has changed SuperGroup description to ["..matches[3].."]") return "Description has been set for ["..matches[2]..']' end end if matches[1] == 'viewsettings' and data[tostring(matches[2])]['settings'] then if not is_owner2(msg.from.id, matches[2]) then return "You are not the owner of this group" end local target = matches[2] local group_type = data[tostring(matches[2])]['group_type'] if group_type == "Group" or group_type == "Realm" then savelog(matches[2], name.." ["..msg.from.id.."] requested group settings ") return show_group_settings(msg, data, target) elseif group_type == "SuperGroup" then savelog(matches[2], name.." ["..msg.from.id.."] requested SuperGroup settings ") return show_super_group_settings(msg, data, target) end end if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then local rules = matches[3] local target = matches[2] local name = user_print_name(msg.from) savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rules(target, rules) end if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name local group_name_set = data[tostring(matches[2])]['settings']['set_name'] save_data(_config.moderation.data, data) local chat_to_rename = 'chat#id'..matches[2] local channel_to_rename = 'channel#id'..matches[2] savelog(matches[2], "Group name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]") rename_chat(chat_to_rename, group_name_set, ok_cb, false) rename_channel(channel_to_rename, group_name_set, ok_cb, false) end if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then savelog(matches[2], "log file created by owner/support/admin") send_document("user#id".. msg.from.id,"./groups/logs/"..matches[2].."log.txt", ok_cb, false) end end end return { patterns = { "^[#!/]owners (%d+) ([^%s]+) (.*)$", "^[#!/]owners (%d+) ([^%s]+)$", "^[#!/](changeabout) (%d+) (.*)$", "^[#!/](changerules) (%d+) (.*)$", "^[#!/](changename) (%d+) (.*)$", "^[#!/](viewsettings) (%d+)$", "^[#!/](loggroup) (%d+)$" }, run = run } -- :-)
gpl-2.0
hfjgjfg/ssyy
plugins/admin.lua
230
6382
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function user_info_callback(cb_extra, success, result) result.access_hash = nil result.flags = nil result.phone = nil if result.username then result.username = '@'..result.username end result.print_name = result.print_name:gsub("_","") local text = serpent.block(result, {comment=false}) text = text:gsub("[{}]", "") text = text:gsub('"', "") text = text:gsub(",","") if cb_extra.msg.to.type == "chat" then send_large_msg("chat#id"..cb_extra.msg.to.id, text) else send_large_msg("user#id"..cb_extra.msg.to.id, text) end end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairs(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "Msg sent" end if matches[1] == "block" then if is_admin2(matches[2]) then return "You can't block admins" end block_user("user#id"..matches[2],ok_cb,false) return "User blocked" end if matches[1] == "unblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User unblocked" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "delcontact" then del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent dialog list with both json and text format to your private" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end return end return { patterns = { "^[!/](pm) (%d+) (.*)$", "^[!/](import) (.*)$", "^[!/](unblock) (%d+)$", "^[!/](block) (%d+)$", "^[!/](markread) (on)$", "^[!/](markread) (off)$", "^[!/](setbotphoto)$", "%[(photo)%]", "^[!/](contactlist)$", "^[!/](dialoglist)$", "^[!/](delcontact) (%d+)$", "^[!/](whois) (%d+)$" }, run = run, } --By @imandaneshi :) --https://github.com/SEEDTEAM/TeleSeed/blob/master/plugins/admin.lua
gpl-2.0
Nether-Machine/NetherMachine
rotations/rogue/subtlety.lua
1
1363
-- SPEC ID 261 NetherMachine.rotation.register(261, { -------------------- -- Start Rotation -- -------------------- -- Interrupts { "Kick", "modifier.interrupts" }, -- Buffs { "Deadly Poison", { "!player.buff(Deadly Poison)", "!player.moving", }}, { "Leeching Poison", "!player.buff(Leeching Poison)" }, -- Cooldowns { "Shadow Blades", "modifier.cooldowns" }, { "Slice and Dice", { "!player.buff(Slice and Dice)", "player.combopoints = 5", }}, { "Vanish", { "!player.buff(Shadow Dance)", "modifier.cooldowns", }}, -- Rotation { "Eviscerate", "player.combopoints = 5" }, { "Hemorrhage", "target.debuff(Hemorrhage).duration <= 4" }, {{ -- Greater than 5 CP { "Fan of Knives", "modifier.multitarget" }, { "Backstab", "player.behind" }, { "Hemorrhage", "!player.behind" }, { "Hemorrhage", { "!player.spell(Backstab).exists", "player.behind", }}, }, "player.combopoints < 5" }, ------------------ -- End Rotation -- ------------------ },{ --------------- -- OOC Begin -- --------------- { "Deadly Poison", { "!player.buff(Deadly Poison)", "!player.moving", }}, { "Ambush", { "player.buff(Stealth)", "target.spell(Ambush).range" }, "target" }, ------------- -- OOC End -- ------------- })
agpl-3.0
nabilbendafi/haka
src/haka/test/token-grammar-coroutine.lua
2
1113
-- 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') require('protocol/ipv4') local tcp_connection = require('protocol/tcp_connection') local grammar = haka.grammar.new("test", function () header = record{ field("name", token("[^:\r\n]+")), token(": "), field("value", token("[^\r\n]+")), token("[\r\n]+"), } grammar = record{ field("hello_world", token("hello world")), token("\r\n"), field('headers', array(header) :count(3) ), } export(grammar) end) haka.rule{ -- Intercept tcp packets on = haka.dissectors.tcp_connection.events.receive_data, options = { streamed = true, }, eval = function (flow, iter, direction) if direction == 'up' then local mark = iter:copy() mark:mark() local res = grammar.grammar:parse(iter) print("hello_world= "..res.hello_world) for _,header in ipairs(res.headers) do print(header.name..": "..header.value) end mark:unmark() end end }
mpl-2.0
b51/uikidcm
Player/Motion/keyframes/km_WebotsNao_KickForwardRight.lua
19
5537
local mot = {}; mot.servos = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22}; mot.keyframes = { { angles = {-0.052, 0.051, 0.911, 0.661, -0.512, -0.827, -0.232, -0.011, -0.387, 1.355, -0.779, 0.048, -0.232, -0.023, -0.357, 1.338, -0.792, 0.003, 1.226, -0.457, 1.300, 0.391, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 0.800; }, { angles = {-0.048, 0.043, 0.924, 1.000, -0.514, -0.833, 0.000, -0.387, -0.425, 0.851, -0.419, 0.420, 0.000, -0.327, -0.400, 1.000, -0.570, 0.300, 1.239, -0.600, 0.015, 0.405, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 1.000; }, { angles = {-0.048, 0.043, 0.924, 1.000, -0.514, -0.833, 0.000, -0.387, -0.425, 0.851, -0.419, 0.420, 0.000, -0.327, -0.300, 0.900, -0.600, 0.340, 1.239, -0.600, 0.015, 0.405, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 0.400; }, { angles = {-0.052, 0.051, 0.911, 1.000, -0.512, -0.827, 0.020, -0.391, -0.423, 0.842, -0.416, 0.420, 0.020, -0.396, -0.150, 1.594, -1.094, 0.051, 1.226, -0.600, 0.017, 0.391, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 0.900; }, { angles = {-0.052, 0.051, 0.911, 1.000, -0.512, -0.827, 0.020, -0.391, -0.423, 0.842, -0.416, 0.420, 0.020, -0.396, -0.150, 1.594, -1.094, 0.051, 1.226, -0.600, 0.017, 0.391, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 0.600; }, { angles = {-0.043, 0.041, 0.908, 1.000, -0.512, -0.827, 0.023, -0.393, -0.420, 0.838, -0.420, 0.420, 0.023, -0.399, -1.000, 1.300, -0.450, 0.296, 1.855, -0.600, 0.020, 0.393, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 0.120; }, { angles = {-0.043, 0.041, 0.908, 1.000, -0.512, -0.827, 0.023, -0.393, -0.420, 0.838, -0.420, 0.420, 0.023, -0.399, -0.960, 1.106, -0.589, 0.296, 1.855, -0.600, 0.020, 0.393, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 0.140; }, { angles = {-0.044, 0.041, 0.908, 1.000, -0.512, -0.827, 0.014, -0.393, -0.423, 0.841, -0.423, 0.420, 0.014, -0.393, -0.957, 1.483, -0.578, 0.296, 1.853, -0.600, 0.020, 0.393, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 0.180; }, { angles = {-0.044, 0.041, 0.908, 1.000, -0.512, -0.828, 0.015, -0.393, -0.423, 0.839, -0.423, 0.420, 0.015, -0.394, -0.957, 1.483, -0.578, 0.296, 1.853, -0.600, 0.020, 0.393, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 0.200; }, { angles = {-0.048, 0.043, 0.924, 1.000, -0.514, -0.833, 0.000, -0.387, -0.425, 0.851, -0.419, 0.420, 0.000, -0.327, -0.400, 1.000, -0.570, 0.300, 1.239, -0.600, 0.015, 0.405, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 0.700; }, { angles = {-0.051, 0.043, 0.911, 0.669, -0.512, -0.816, -0.232, -0.006, -0.377, 1.356, -0.776, 0.048, -0.232, -0.022, -0.354, 1.342, -0.792, -0.002, 1.227, -0.459, 0.017, 0.393, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 0.600; }, { angles = {-0.000, -0.436, 2.094, 0.349, -1.789, -1.396, -0.000, 0.017, -0.757, 1.491, -0.734, -0.017, 0.000, -0.017, -0.757, 1.491, -0.734, 0.017, 2.094, -0.349, 1.300, 1.396, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 0.700; }, { angles = {-0.000, -0.436, 2.094, 0.349, -1.789, -1.396, -0.000, 0.017, -0.757, 1.491, -0.734, -0.017, 0.000, -0.017, -0.757, 1.491, -0.734, 0.017, 2.094, -0.349, 1.300, 1.396, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 0.300; }, { angles = {-0.066, -0.678, 1.468, 0.229, -1.273, -0.305, 0.000, -0.003, -0.396, 0.946, -0.548, 0.002, 0.000, 0.026, -0.397, 0.945, -0.548, -0.025, 1.494, -0.253, 1.216, 0.502, }, stiffness = {0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 1.000, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, 0.900, }, duration = 1.000; }, }; return mot;
gpl-3.0
MRAHS/PRIDE-bot
plugins/all.lua
11
4659
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^([Aa]ll)$", "^([Aa]ll) (%d+)$" }, run = run } end
gpl-2.0
notcake/wire
lua/weapons/gmod_tool/stools/wire_namer.lua
9
1584
TOOL.Category = "Tools" TOOL.Name = "Namer" TOOL.Command = nil TOOL.ConfigName = "" TOOL.Tab = "Wire" if ( CLIENT ) then language.Add( "Tool.wire_namer.name", "Naming Tool" ) language.Add( "Tool.wire_namer.desc", "Names components." ) language.Add( "Tool.wire_namer.0", "Primary: Set name\nSecondary: Get name" ) language.Add( "WireNamerTool_name", "Name:" ) end TOOL.ClientConVar[ "name" ] = "" local function SetName( Player, Entity, Data ) if ( Data and Data.name ) then Entity:SetNetworkedString("WireName", Data.name) duplicator.StoreEntityModifier( Entity, "WireName", Data ) end end duplicator.RegisterEntityModifier( "WireName", SetName ) function TOOL:LeftClick(trace) if (not trace.Entity:IsValid()) then return end if (CLIENT) then return end if (not trace.Entity.IsWire) then return end local name = self:GetClientInfo("name") //trace.Entity:SetNetworkedString("WireName", name) //made the WireName duplicatable entmod (TAD2020) SetName( Player, trace.Entity, {name = name} ) return true end function TOOL:RightClick(trace) if (not trace.Entity:IsValid()) then return end if (CLIENT) then return end local name = trace.Entity:GetNetworkedString("WireName") if (not name) then return end self:GetOwner():ConCommand('wire_namer_name "' .. name .. '"') end function TOOL.BuildCPanel(panel) panel:AddControl("Header", { Text = "#Tool.wire_namer.name", Description = "#Tool.wire_namer.desc" }) panel:AddControl("TextBox", { Label = "#WireNamerTool_name", Command = "wire_namer_name", MaxLength = "20" }) end
apache-2.0
b51/uikidcm
Player/Test/test_new_walk.lua
3
7918
module(... or "", package.seeall) require('unix') webots = false; darwin = false; -- mv up to Player directory unix.chdir('~/Player'); local cwd = unix.getcwd(); -- the webots sim is run from the WebotsController dir (not Player) if string.find(cwd, "WebotsController") then webots = true; cwd = cwd.."/Player" package.path = cwd.."/?.lua;"..package.path; end computer = os.getenv('COMPUTER') or ""; if (string.find(computer, "Darwin")) then -- MacOS X uses .dylib: package.cpath = cwd.."/Lib/?.dylib;"..package.cpath; else package.cpath = cwd.."/Lib/?.so;"..package.cpath; end package.path = cwd.."/Util/?.lua;"..package.path; package.path = cwd.."/Config/?.lua;"..package.path; package.path = cwd.."/Lib/?.lua;"..package.path; package.path = cwd.."/Dev/?.lua;"..package.path; package.path = cwd.."/Motion/?.lua;"..package.path; package.path = cwd.."/Motion/walk/?.lua;"..package.path; package.path = cwd.."/Vision/?.lua;"..package.path; package.path = cwd.."/World/?.lua;"..package.path; package.path = cwd.."/BodyFSM/?.lua;"..package.path; package.path = cwd.."/HeadFSM/?.lua;"..package.path; require('Config') require('shm') require('vector') require('Motion') require('walk') require('Body') require("getch") require('kick') require('Speak') --require('World') --require('Team') --require('battery') Vision = require 'vcm' -- Steve Speak.talk("Starting test parameters.") --World.entry(); --Team.entry(); -- initialize state machines Motion.entry(); --Motion.sm:set_state('stance'); walk.stop(); getch.enableblock(1); targetvel=vector.new({0,0,0}); headangle=vector.new({0,0}); walkKick=true; --Adding head movement && vision...-- Body.set_head_hardness({0.4,0.4}); Motion.fall_check=0; --auto getup disabled -- main loop print(" Key commands \n 7:sit down 8:stand up 9:walk\n i/j/l/,/h/; :control walk velocity\n k : walk in place\n [, ', / :Reverse x, y, / directions\n 1/2/3/4 :kick\n w/a/s/d/x :control head\n t/T :alter walk speed\t f/F :alter step phase\t r/R :alter step height\t c/C :alter supportX\t v/V :alter supportY\n b/B :alter foot sensor threshold \t n/N :alter delay time.\n 3/4/5 :turn imu feedback/joint encoder feedback/foot sensor feedback on or off."); local tUpdate = unix.time(); local count=0; local countInterval=1000; count_dcm=0; t0=unix.time(); init = false; calibrating = false; ready = false; calibrated=false; function update() count = count + 1; if (not init) then if (calibrating) then if (Body.calibrate(count)) then Speak.talk('Calibration done'); calibrating = false; ready = true; end elseif (ready) then --[[ -- initialize state machines package.path = cwd..'/BodyFSM/'..Config.fsm.body[smindex+1]..'/?.lua;'..package.path; package.path = cwd..'/HeadFSM/'..Config.fsm.head[smindex+1]..'/?.lua;'..package.path; package.path = cwd..'/GameFSM/'..Config.fsm.game..'/?.lua;'..package.path; require('BodyFSM') require('HeadFSM') require('GameFSM') BodyFSM.entry(); HeadFSM.entry(); GameFSM.entry(); if( webots ) then BodyFSM.sm:add_event('button'); end --]] init = true; else if (count % 20 == 0) then if calibrated==false then Speak.talk('Calibrating'); calibrating = true; calibrated=true; elseif (Body.get_change_role() == 1) then smindex = (smindex + 1) % #Config.fsm.body; end end -- toggle state indicator if (count % 100 == 0) then initToggle = not initToggle; if (initToggle) then Body.set_indicator_state({1,1,1}); else Body.set_indicator_state({0,0,0}); end end end end t=unix.time(); Motion.update(); Body.set_head_hardness(0.2); --battery.monitor(); local str=getch.get(); if #str>0 then local byte=string.byte(str,1); if byte==string.byte("i") then targetvel[1]=targetvel[1]+0.01; elseif byte==string.byte("j") then targetvel[3]=targetvel[3]+0.1; elseif byte==string.byte("k") then targetvel[1],targetvel[2],targetvel[3]=0,0,0; elseif byte==string.byte("l") then targetvel[3]=targetvel[3]-0.1; elseif byte==string.byte(",") then targetvel[1]=targetvel[1]-0.01; elseif byte==string.byte("h") then targetvel[2]=targetvel[2]+0.01; elseif byte==string.byte(";") then targetvel[2]=targetvel[2]-0.01; elseif byte==string.byte("[") then targetvel[1]=-targetvel[1]; elseif byte==string.byte("'") then targetvel[2]=-targetvel[2]; elseif byte==string.byte("/") then targetvel[3]=-targetvel[3]; --Move the head around-- elseif byte==string.byte("w") then headangle[2]=headangle[2]-5*math.pi/180; elseif byte==string.byte("a") then headangle[1]=headangle[1]+5*math.pi/180; elseif byte==string.byte("s") then headangle[1],headangle[2]=0,0; elseif byte==string.byte("d") then headangle[1]=headangle[1]-5*math.pi/180; elseif byte==string.byte("x") then headangle[2]=headangle[2]+5*math.pi/180; --Change configuration params in real time-- elseif byte==string.byte("t") then Config.walk.tStep = Config.walk.tStep - .01; elseif byte==string.byte("T") then Config.walk.tStep = Config.walk.tStep + .01; elseif byte==string.byte("f") then Config.walk.phSingle[1] = Config.walk.phSingle[1] - .01; Config.walk.phSingle[2] = Config.walk.phSingle[2] + .01; elseif byte==string.byte("F") then Config.walk.phSingle[1] = Config.walk.phSingle[1] + .01; Config.walk.phSingle[2] = Config.walk.phSingle[2] - .01; elseif byte==string.byte("r") then Config.walk.stepHeight = Config.walk.stepHeight - .001; elseif byte==string.byte("R") then Config.walk.stepHeight = Config.walk.stepHeight + .001; elseif byte==string.byte("c") then Config.walk.supportX = Config.walk.supportX - .001; elseif byte==string.byte("C") then Config.walk.supportX = Config.walk.supportX + .001; elseif byte==string.byte("v") then Config.walk.supportY = Config.walk.supportY - .001; elseif byte==string.byte("V") then Config.walk.supportY = Config.walk.supportY + .001; elseif byte==string.byte('y') then Config.walk.bodyHeight = Config.walk.bodyHeight - .001; elseif byte== string.byte('Y') then Config.walk.bodyHeight = Config.walk.bodyHeight + .001; elseif byte==string.byte('\\') then walkKick=not walkKick; elseif byte==string.byte("1") then if walkKick then walk.doWalkKickLeft(); else kick.set_kick("KickForwardLeft"); Motion.event("kick"); end elseif byte==string.byte("2") then if walkKick then walk.doWalkKickRight(); else kick.set_kick("kickForwardRight"); Motion.event("kick"); end --turn assorted stability checks on/off-- elseif byte==string.byte("3") then Config.walk.imuOn = not Config.walk.imuOn; elseif byte==string.byte("4") then Config.walk.jointFeedbackOn = not Config.walk.jointFeedbackOn; elseif byte==string.byte("5") then Config.walk.fsrOn = not Config.walk.fsrOn; elseif byte==string.byte("7") then Motion.event("sit"); elseif byte==string.byte("8") then walk.stop(); Motion.event("standup"); elseif byte==string.byte("9") then Motion.event("walk"); walk.start(); end print(string.format("\n Walk Velocity: (%.2f, %.2f, %.2f)",unpack(targetvel))); walk.set_velocity(unpack(targetvel)); print "huh?"; Body.set_head_command(headangle); print(string.format("Head angle: %d, %d", headangle[1]*180/math.pi, headangle[2]*180/math.pi)); print(string.format("Walk settings:\n tStep: %.2f\t phSingle: {%.2f, %.2f}\t stepHeight: %.3f\n supportX: %.3f\t supportY: %.3f\t", Config.walk.tStep, Config.walk.phSingle[1], Config.walk.phSingle[2], Config.walk.stepHeight, Config.walk.supportX, Config.walk.supportY)); end end
gpl-3.0
generalwrex/spacebuild
lua/entities/other_screen/cl_init.lua
2
10346
include('shared.lua') language.Add("other_screen", "Life Support Screen") local MainFrames = {} function ENT:Initialize() self.resources = {} end local function OpenMenu(um) local ent = um:ReadEntity() if not ent then return end if MainFrames[ent:EntIndex()] and MainFrames[ent:EntIndex()]:IsActive() and MainFrames[ent:EntIndex()]:IsVisible() then MainFrames[ent:EntIndex()]:Close() end local MainFrame = vgui.Create("DFrame") MainFrames[ent:EntIndex()] = MainFrame MainFrame:SetDeleteOnClose() MainFrame:SetDraggable(false) MainFrame:SetTitle("LS Screen Control Panel") MainFrame:SetSize(600, 350) MainFrame:Center() local RD = CAF.GetAddon("Resource Distribution") local resources = RD.GetRegisteredResources() local res2 = RD.GetAllRegisteredResources() if table.Count(res2) > 0 then for k, v in pairs(res2) do if not table.HasValue(resources, k) then table.insert(resources, k) end end end MainFrame.SelectedNode = nil local LeftTree = vgui.Create("DTree", MainFrame) LeftTree:SetSize(180, 300) LeftTree:SetPos(20, 25); LeftTree:SetShowIcons(false) MainFrame.lefttree = LeftTree local RightTree = vgui.Create("DTree", MainFrame) RightTree:SetSize(180, 300) RightTree:SetPos(400, 25); RightTree:SetShowIcons(false) local RightPanel = vgui.Create("DPanel", MainFrame) RightPanel:SetSize(180, 250); RightPanel:SetPos(210, 25) local RText2 = vgui.Create("DTextEntry", RightPanel) RText2:SetPos(20, 25) RText2:SetSize(140, 30) RText2:AllowInput(true) RText2:SetValue("") if resources and table.Count(resources) > 0 then for k, v in pairs(resources) do local title = RD.GetProperResourceName(v); local node = RightTree:AddNode(title) node.res = v function node:DoClick() RText2:SetValue(tostring(self.res)) end end end local RButton2 = vgui.Create("DButton", RightPanel) RButton2:SetPos(20, 90) RButton2:SetSize(140, 30) RButton2:SetText("Remove Selected Resource") function RButton2:DoClick() if MainFrame.SelectedNode then RunConsoleCommand("RemoveLSSCreenResource", ent:EntIndex(), tostring(MainFrame.SelectedNode.res)) end end local RButton3 = vgui.Create("DButton", RightPanel) RButton3:SetPos(20, 60) RButton3:SetSize(140, 30) RButton3:SetText("Add Resource") function RButton3:DoClick() if RText2:GetValue() ~= "" then RunConsoleCommand("AddLSSCreenResource", ent:EntIndex(), tostring(RText2:GetValue())) end end local button = vgui.Create("DButton", MainFrame) button:SetPos(225, 290) button:SetSize(140, 30) if ent:GetOOO() == 1 then button:SetText("Turn off") function button:DoClick() RunConsoleCommand("LSScreenTurnOff", ent:EntIndex()) end else button:SetText("Turn on") function button:DoClick() RunConsoleCommand("LSScreenTurnOn", ent:EntIndex()) end end if ent.resources and table.Count(ent.resources) > 0 then for k, v in pairs(ent.resources) do local title = v; local node = LeftTree:AddNode(title) node.res = v function node:DoClick() MainFrame.SelectedNode = self end end end MainFrame:MakePopup() end usermessage.Hook("LS_Open_Screen_Menu", OpenMenu) local function AddResource(um) local ent = um:ReadEntity() local res = um:ReadString() if not ent then return end table.insert(ent.resources, res) if MainFrames[ent:EntIndex()] and MainFrames[ent:EntIndex()]:IsActive() and MainFrames[ent:EntIndex()]:IsVisible() then local LeftTree = MainFrames[ent:EntIndex()].lefttree LeftTree.Items = {} if ent.resources and table.Count(ent.resources) > 0 then for k, v in pairs(ent.resources) do local title = v; local node = LeftTree:AddNode(title) node.res = v function node:DoClick() MainFrames[ent:EntIndex()].SelectedNode = self end end end end end usermessage.Hook("LS_Add_ScreenResource", AddResource) local function RemoveResource(um) local ent = um:ReadEntity() local res = um:ReadString() if not ent then return end for k, v in pairs(ent.resources) do if v == res then table.remove(ent.resources, k) break end end if MainFrames[ent:EntIndex()] and MainFrames[ent:EntIndex()]:IsActive() and MainFrames[ent:EntIndex()]:IsVisible() then local LeftTree = MainFrames[ent:EntIndex()].lefttree LeftTree.Items = {} if ent.resources and table.Count(ent.resources) > 0 then for k, v in pairs(ent.resources) do local title = v; local node = LeftTree:AddNode(title) node.res = v function node:DoClick() MainFrames[ent:EntIndex()].SelectedNode = self end end end end end usermessage.Hook("LS_Remove_ScreenResource", RemoveResource) function ENT:DoNormalDraw(bDontDrawModel) local rd_overlay_dist = 512 if RD_OverLay_Distance then if RD_OverLay_Distance.GetInt then local nr = RD_OverLay_Distance:GetInt() if nr >= 256 then rd_overlay_dist = nr end end end if (EyePos():Distance(self:GetPos()) < rd_overlay_dist and self:GetOOO() == 1) then local trace = LocalPlayer():GetEyeTrace() if (not bDontDrawModel) then self:DrawModel() end local enttable = CAF.GetAddon("Resource Distribution").GetEntityTable(self) local TempY = 0 local mul_up = 5.2 local mul_ri = -16.5 local mul_fr = -12.5 local res = 0.05 local mul = 1 if string.find(self:GetModel(), "s_small_screen") then mul_ri = -8.25 mul_fr = -6.25 res = 0.025 mul = 0.5 elseif string.find(self:GetModel(), "small_screen") then mul_ri = -16.5 mul_fr = -12.5 res = 0.05 elseif string.find(self:GetModel(), "medium_screen") then mul_ri = -33 mul_fr = -25 res = 0.1 mul = 1.5 elseif string.find(self:GetModel(), "large_screen") then mul_ri = -66 mul_fr = -50 res = 0.2 mul = 2 end --local pos = self:GetPos() + (self:GetForward() ) + (self:GetUp() * 40 ) + (self:GetRight()) local pos = self:GetPos() + (self:GetUp() * mul_up) + (self:GetRight() * mul_ri) + (self:GetForward() * mul_fr) --[[local angle = (LocalPlayer():GetPos() - trace.HitPos):Angle() angle.r = angle.r + 90 angle.y = angle.y + 90 angle.p = 0]] local angle = self:GetAngles() local textStartPos = -375 cam.Start3D2D(pos, angle, res) surface.SetDrawColor(0, 0, 0, 255) surface.DrawRect(textStartPos, 0, 1250, 675) surface.SetDrawColor(155, 155, 255, 255) surface.DrawRect(textStartPos, 0, -5, 675) surface.DrawRect(textStartPos, 0, 1250, -5) surface.DrawRect(textStartPos, 675, 1250, -5) surface.DrawRect(textStartPos + 1250, 0, 5, 675) TempY = TempY + 10 surface.SetFont("Flavour") surface.SetTextColor(200, 200, 255, 255) surface.SetTextPos(textStartPos + 15, TempY) surface.DrawText("Resource: amount/maxamount\t[where amount/maxamount from other nodes]") TempY = TempY + (70 / mul) if (table.Count(self.resources) > 0) then local i = 0 for k, v in pairs(self.resources) do surface.SetFont("Flavour") surface.SetTextColor(200, 200, 255, 255) surface.SetTextPos(textStartPos + 15, TempY) local othernetworks = 0 local othernetworksres = 0 if enttable.network and enttable.network ~= 0 then local nettable = CAF.GetAddon("Resource Distribution").GetNetTable(enttable.network) if table.Count(nettable) > 0 then if nettable.resources and nettable.resources[v] then local currentnet = nettable.resources[v].maxvalue local currentnet2 = nettable.resources[v].value if currentnet then othernetworks = CAF.GetAddon("Resource Distribution").GetNetworkCapacity(self, v) - (currentnet or 0) end if currentnet2 then othernetworksres = CAF.GetAddon("Resource Distribution").GetResourceAmount(self, v) - (currentnet2 or 0) end else othernetworks = CAF.GetAddon("Resource Distribution").GetNetworkCapacity(self, v) othernetworksres = CAF.GetAddon("Resource Distribution").GetResourceAmount(self, v) end end end surface.DrawText(tostring(CAF.GetAddon("Resource Distribution").GetProperResourceName(v)) .. ": " .. tostring(CAF.GetAddon("Resource Distribution").GetResourceAmount(self, v)) .. "/" .. tostring(CAF.GetAddon("Resource Distribution").GetNetworkCapacity(self, v)) .. "\t[" .. tostring(othernetworksres) .. "/" .. tostring(othernetworks) .. "]") TempY = TempY + (70 / mul) i = i + 1 if i >= 8 * mul then break end end else surface.SetFont("Flavour") surface.SetTextColor(200, 200, 255, 255) surface.SetTextPos(textStartPos + 15, TempY) surface.DrawText("No resources Selected") TempY = TempY + 70 end --Stop rendering cam.End3D2D() else if (not bDontDrawModel) then self:DrawModel() end end end
apache-2.0
HumanChan/QuadTreeTest
src/framework/cc/ui/UIStretch.lua
19
3491
--[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] -------------------------------- -- @module UIStretch --[[-- quick 拉伸控件 ]] local UIStretch = class("UIStretch") -- start -- -------------------------------- -- quick 拉伸控件 -- @function [parent=#UIStretch] new -- end -- function UIStretch:ctor() cc(self):addComponent("components.ui.LayoutProtocol"):exportMethods() self:setLayoutSizePolicy(display.AUTO_SIZE, display.AUTO_SIZE) self.position_ = {x = 0, y = 0} self.anchorPoint_ = display.ANCHOR_POINTS[display.CENTER] end -- start -- -------------------------------- -- 得到位置信息 -- @function [parent=#UIStretch] getPosition -- @return number#number x -- @return number#number y -- end -- function UIStretch:getPosition() return self.position_.x, self.position_.y end -- start -- -------------------------------- -- 得到x位置信息 -- @function [parent=#UIStretch] getPositionX -- @return number#number x -- end -- function UIStretch:getPositionX() return self.position_.x end -- start -- -------------------------------- -- 得到y位置信息 -- @function [parent=#UIStretch] getPositionY -- @return number#number y -- end -- function UIStretch:getPositionY() return self.position_.y end -- start -- -------------------------------- -- 设置位置信息 -- @function [parent=#UIStretch] setPosition -- @param number x x的位置 -- @param number y y的位置 -- end -- function UIStretch:setPosition(x, y) self.position_.x, self.position_.y = x, y end -- start -- -------------------------------- -- 设置x位置信息 -- @function [parent=#UIStretch] setPositionX -- @param number x x的位置 -- end -- function UIStretch:setPositionX(x) self.position_.x = x end -- start -- -------------------------------- -- 设置y位置信息 -- @function [parent=#UIStretch] setPositionY -- @param number y y的位置 -- end -- function UIStretch:setPositionY(y) self.position_.y = y end -- start -- -------------------------------- -- 得到锚点位置信息 -- @function [parent=#UIStretch] getAnchorPoint -- @return table#table 位置信息 -- end -- function UIStretch:getAnchorPoint() return self.anchorPoint_ end -- start -- -------------------------------- -- 设置锚点位置 -- @function [parent=#UIStretch] setAnchorPoint -- @param ap 锚点 -- end -- function UIStretch:setAnchorPoint(ap) self.anchorPoint_ = ap end return UIStretch
mit
Kkthnx-WoW/KkthnxUI
KkthnxUI/Libraries/oUF/colors.lua
2
8182
local parent, ns = ... local oUF = ns.oUF local Private = oUF.Private local frame_metatable = Private.frame_metatable local colors = { smooth = { 1, 0, 0, 1, 1, 0, 0, 1, 0 }, health = {49 / 255, 207 / 255, 37 / 255}, disconnected = {.6, .6, .6}, tapped = {.6, .6, .6}, runes = { {247 / 255, 65 / 255, 57 / 255}, -- blood {148 / 255, 203 / 255, 247 / 255}, -- frost {173 / 255, 235 / 255, 66 / 255}, -- unholy }, class = {}, debuff = {}, reaction = {}, power = {}, } -- We do this because people edit the vars directly, and changing the default -- globals makes SPICE FLOW! local function customClassColors() if(CUSTOM_CLASS_COLORS) then local function updateColors() for classToken, color in next, CUSTOM_CLASS_COLORS do colors.class[classToken] = {color.r, color.g, color.b} end for _, obj in next, oUF.objects do obj:UpdateAllElements('CUSTOM_CLASS_COLORS') end end updateColors() CUSTOM_CLASS_COLORS:RegisterCallback(updateColors) return true end end if(not customClassColors()) then for classToken, color in next, RAID_CLASS_COLORS do colors.class[classToken] = {color.r, color.g, color.b} end local eventHandler = CreateFrame('Frame') eventHandler:RegisterEvent('ADDON_LOADED') eventHandler:SetScript('OnEvent', function(self) if(customClassColors()) then self:UnregisterEvent('ADDON_LOADED') self:SetScript('OnEvent', nil) end end) end for debuffType, color in next, DebuffTypeColor do colors.debuff[debuffType] = {color.r, color.g, color.b} end for eclass, color in next, FACTION_BAR_COLORS do colors.reaction[eclass] = {color.r, color.g, color.b} end for power, color in next, PowerBarColor do if (type(power) == 'string') then if(type(select(2, next(color))) == 'table') then colors.power[power] = {} for index, color in next, color do colors.power[power][index] = {color.r, color.g, color.b} end else colors.power[power] = {color.r, color.g, color.b, atlas = color.atlas} end end end -- sourced from FrameXML/Constants.lua colors.power[0] = colors.power.MANA colors.power[1] = colors.power.RAGE colors.power[2] = colors.power.FOCUS colors.power[3] = colors.power.ENERGY colors.power[4] = colors.power.COMBO_POINTS colors.power[5] = colors.power.RUNES colors.power[6] = colors.power.RUNIC_POWER colors.power[7] = colors.power.SOUL_SHARDS colors.power[8] = colors.power.LUNAR_POWER colors.power[9] = colors.power.HOLY_POWER colors.power[11] = colors.power.MAELSTROM colors.power[12] = colors.power.CHI colors.power[13] = colors.power.INSANITY colors.power[16] = colors.power.ARCANE_CHARGES colors.power[17] = colors.power.FURY colors.power[18] = colors.power.PAIN local function colorsAndPercent(a, b, ...) if(a <= 0 or b == 0) then return nil, ... elseif(a >= b) then return nil, select(select('#', ...) - 2, ...) end local num = select('#', ...) / 3 local segment, relperc = math.modf((a / b) * (num - 1)) return relperc, select((segment * 3) + 1, ...) end -- http://www.wowwiki.com/ColorGradient --[[ Colors: oUF:RGBColorGradient(a, b, ...) Used to convert a percent value (the quotient of `a` and `b`) into a gradient from 2 or more RGB colors. If more than 2 colors are passed, the gradient will be between the two colors which perc lies in an evenly divided range. A RGB color is a sequence of 3 consecutive RGB percent values (in the range [0-1]). If `a` is negative or `b` is zero then the first RGB color (the first 3 RGB values passed to the function) is returned. If `a` is bigger than or equal to `b`, then the last 3 RGB values are returned. * self - the global oUF object * a - value used as numerator to calculate the percentage (number) * b - value used as denominator to calculate the percentage (number) * ... - a list of RGB percent values. At least 6 values should be passed (number [0-1]) --]] local function RGBColorGradient(...) local relperc, r1, g1, b1, r2, g2, b2 = colorsAndPercent(...) if(relperc) then return r1 + (r2 - r1) * relperc, g1 + (g2 - g1) * relperc, b1 + (b2 - b1) * relperc else return r1, g1, b1 end end -- HCY functions are based on http://www.chilliant.com/rgb2hsv.html local function getY(r, g, b) return 0.299 * r + 0.587 * g + 0.114 * b end --[[ Colors: oUF:RGBToHCY(r, g, b) Used to convert a color from RGB to HCY color space. * self - the global oUF object * r - red color component (number [0-1]) * g - green color component (number [0-1]) * b - blue color component (number [0-1]) --]] function oUF:RGBToHCY(r, g, b) local min, max = min(r, g, b), max(r, g, b) local chroma = max - min local hue if(chroma > 0) then if(r == max) then hue = ((g - b) / chroma) % 6 elseif(g == max) then hue = (b - r) / chroma + 2 elseif(b == max) then hue = (r - g) / chroma + 4 end hue = hue / 6 end return hue, chroma, getY(r, g, b) end local math_abs = math.abs --[[ Colors: oUF:HCYtoRGB(hue, chroma, luma) Used to convert a color from HCY to RGB color space. * self - the global oUF object * hue - hue color component (number [0-1]) * chroma - chroma color component (number [0-1]) * luma - luminance color component (number [0-1]) --]] function oUF:HCYtoRGB(hue, chroma, luma) local r, g, b = 0, 0, 0 if(hue and luma > 0) then local h2 = hue * 6 local x = chroma * (1 - math_abs(h2 % 2 - 1)) if(h2 < 1) then r, g, b = chroma, x, 0 elseif(h2 < 2) then r, g, b = x, chroma, 0 elseif(h2 < 3) then r, g, b = 0, chroma, x elseif(h2 < 4) then r, g, b = 0, x, chroma elseif(h2 < 5) then r, g, b = x, 0, chroma else r, g, b = chroma, 0, x end local y = getY(r, g, b) if(luma < y) then chroma = chroma * (luma / y) elseif(y < 1) then chroma = chroma * (1 - luma) / (1 - y) end r = (r - y) * chroma + luma g = (g - y) * chroma + luma b = (b - y) * chroma + luma end return r, g, b end --[[ Colors: oUF:HCYColorGradient(a, b, ...) Used to convert a percent value (the quotient of `a` and `b`) into a gradient from 2 or more HCY colors. If more than 2 colors are passed, the gradient will be between the two colors which perc lies in an evenly divided range. A HCY color is a sequence of 3 consecutive values in the range [0-1]. If `a` is negative or `b` is zero then the first HCY color (the first 3 HCY values passed to the function) is returned. If `a` is bigger than or equal to `b`, then the last 3 HCY values are returned. * self - the global oUF object * a - value used as numerator to calculate the percentage (number) * b - value used as denominator to calculate the percentage (number) * ... - a list of HCY color values. At least 6 values should be passed (number [0-1]) --]] local function HCYColorGradient(...) local relperc, r1, g1, b1, r2, g2, b2 = colorsAndPercent(...) if(not relperc) then return r1, g1, b1 end local h1, c1, y1 = self:RGBToHCY(r1, g1, b1) local h2, c2, y2 = self:RGBToHCY(r2, g2, b2) local c = c1 + (c2 - c1) * relperc local y = y1 + (y2 - y1) * relperc if(h1 and h2) then local dh = h2 - h1 if(dh < -0.5) then dh = dh + 1 elseif(dh > 0.5) then dh = dh - 1 end return self:HCYtoRGB((h1 + dh * relperc) % 1, c, y) else return self:HCYtoRGB(h1 or h2, c, y) end end --[[ Colors: oUF:ColorGradient(a, b, ...) or frame:ColorGradient(a, b, ...) Used as a proxy to call the proper gradient function depending on the user's preference. If `oUF.useHCYColorGradient` is set to true, `:HCYColorGradient` will be called, else `:RGBColorGradient`. * self - the global oUF object or a unit frame * a - value used as numerator to calculate the percentage (number) * b - value used as denominator to calculate the percentage (number) * ... - a list of color values. At least 6 values should be passed (number [0-1]) --]] local function ColorGradient(...) return (oUF.useHCYColorGradient and HCYColorGradient or RGBColorGradient)(...) end Private.colors = colors oUF.colors = colors oUF.ColorGradient = ColorGradient oUF.RGBColorGradient = RGBColorGradient oUF.HCYColorGradient = HCYColorGradient oUF.useHCYColorGradient = false frame_metatable.__index.colors = colors frame_metatable.__index.ColorGradient = ColorGradient
mit
williamrussellajb/ESOPublicAddons
LuminaryLib/libs/LibStub.lua
10
1568
-- LibStub is a simple versioning stub meant for use in Libraries. http://www.wowace.com/wiki/LibStub for more info -- LibStub is hereby placed in the Public Domain Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel, joshborke -- LibStub developed for World of Warcraft by above members of the WowAce community. -- Ported to Elder Scrolls Online by Seerah local LIBSTUB_MAJOR, LIBSTUB_MINOR = "LibStub", 2 -- NEVER MAKE THIS AN SVN REVISION! IT NEEDS TO BE USABLE IN ALL REPOS! local LibStub = _G[LIBSTUB_MAJOR] local strformat = string.format if not LibStub or LibStub.minor < LIBSTUB_MINOR then LibStub = LibStub or {libs = {}, minors = {} } _G[LIBSTUB_MAJOR] = LibStub LibStub.minor = LIBSTUB_MINOR function LibStub:NewLibrary(major, minor) assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)") minor = assert(tonumber(zo_strmatch(minor, "%d+")), "Minor version must either be a number or contain a number.") local oldminor = self.minors[major] if oldminor and oldminor >= minor then return nil end self.minors[major], self.libs[major] = minor, self.libs[major] or {} return self.libs[major], oldminor end function LibStub:GetLibrary(major, silent) if not self.libs[major] and not silent then error(strformat("Cannot find a library instance of %q.", tostring(major)), 2) end return self.libs[major], self.minors[major] end function LibStub:IterateLibraries() return pairs(self.libs) end setmetatable(LibStub, { __call = LibStub.GetLibrary }) end
bsd-3-clause
williamrussellajb/ESOPublicAddons
Luminary_Actionbars/libs/LibStub.lua
10
1568
-- LibStub is a simple versioning stub meant for use in Libraries. http://www.wowace.com/wiki/LibStub for more info -- LibStub is hereby placed in the Public Domain Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel, joshborke -- LibStub developed for World of Warcraft by above members of the WowAce community. -- Ported to Elder Scrolls Online by Seerah local LIBSTUB_MAJOR, LIBSTUB_MINOR = "LibStub", 2 -- NEVER MAKE THIS AN SVN REVISION! IT NEEDS TO BE USABLE IN ALL REPOS! local LibStub = _G[LIBSTUB_MAJOR] local strformat = string.format if not LibStub or LibStub.minor < LIBSTUB_MINOR then LibStub = LibStub or {libs = {}, minors = {} } _G[LIBSTUB_MAJOR] = LibStub LibStub.minor = LIBSTUB_MINOR function LibStub:NewLibrary(major, minor) assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)") minor = assert(tonumber(zo_strmatch(minor, "%d+")), "Minor version must either be a number or contain a number.") local oldminor = self.minors[major] if oldminor and oldminor >= minor then return nil end self.minors[major], self.libs[major] = minor, self.libs[major] or {} return self.libs[major], oldminor end function LibStub:GetLibrary(major, silent) if not self.libs[major] and not silent then error(strformat("Cannot find a library instance of %q.", tostring(major)), 2) end return self.libs[major], self.minors[major] end function LibStub:IterateLibraries() return pairs(self.libs) end setmetatable(LibStub, { __call = LibStub.GetLibrary }) end
bsd-3-clause
grongor/school_rfid
lib/nmap-6.40/nselib/rdp.lua
2
10751
--- -- A minimal RDP (Remote Desktop Protocol) library. Currently has functionality to determine encryption -- and cipher support. -- -- -- @author "Patrik Karlsson <patrik@cqure.net>" -- @copyright Same as Nmap--See http://nmap.org/book/man-legal.html -- local bin = require("bin") local nmap = require("nmap") local stdnse = require("stdnse") _ENV = stdnse.module("rdp", stdnse.seeall) Packet = { TPKT = { new = function(self, data) local o = { data = tostring(data), version = 3 } setmetatable(o, self) self.__index = self return o end, __tostring = function(self) return bin.pack(">CCSA", self.version, self.reserved or 0, (self.data and #self.data + 4 or 4), self.data ) end, parse = function(data) local tpkt = Packet.TPKT:new() local pos pos, tpkt.version, tpkt.reserved, tpkt.length = bin.unpack(">CCS", data) pos, tpkt.data = bin.unpack("A" .. (#data - pos), data, pos) return tpkt end }, ITUT = { new = function(self, code, data) local o = { data = tostring(data), code = code } setmetatable(o, self) self.__index = self return o end, parse = function(data) local itut = Packet.ITUT:new() local pos pos, itut.length, itut.code = bin.unpack("CC", data) if ( itut.code == 0xF0 ) then pos, itut.eot = bin.unpack("C", data, pos) elseif ( itut.code == 0xD0 ) then pos, itut.dstref, itut.srcref, itut.class = bin.unpack(">SSC", data, pos) end pos, itut.data = bin.unpack("A" .. (#data - pos), data, pos) return itut end, __tostring = function(self) local len = (self.code ~= 0xF0 and #self.data + 1 or 2) local data = bin.pack("CC", len, self.code or 0 ) if ( self.code == 0xF0 ) then data = data .. bin.pack("C", 0x80) -- EOT end return data .. self.data end, }, } Request = { ConnectionRequest = { new = function(self, proto) local o = { proto = proto } setmetatable(o, self) self.__index = self return o end, __tostring = function(self) local cookie = "mstshash=nmap" local itpkt_len = 21 + #cookie local itut_len = 16 + #cookie local data = bin.pack(">SSCA", 0x0000, -- dst reference 0x0000, -- src reference 0x00, -- class and options ("Cookie: %s\r\n"):format(cookie)) if ( self.proto ) then data = data .. bin.pack("<II", 0x00080001, -- Unknown self.proto -- protocol ) end return tostring(Packet.TPKT:new(Packet.ITUT:new(0xE0, data))) end }, MCSConnectInitial = { new = function(self, cipher) local o = { cipher = cipher } setmetatable(o, self) self.__index = self return o end, __tostring = function(self) local data = bin.pack("<HIH", "7f 65" .. -- BER: Application-Defined Type = APPLICATION 101, "82 01 90" .. -- BER: Type Length = 404 bytes "04 01 01" .. -- Connect-Initial::callingDomainSelector "04 01 01" .. -- Connect-Initial::calledDomainSelector "01 01 ff" .. -- Connect-Initial::upwardFlag = TRUE "30 19" .. -- Connect-Initial::targetParameters (25 bytes) "02 01 22" .. -- DomainParameters::maxChannelIds = 34 "02 01 02" .. -- DomainParameters::maxUserIds = 2 "02 01 00" .. -- DomainParameters::maxTokenIds = 0 "02 01 01" .. -- DomainParameters::numPriorities = 1 "02 01 00" .. -- DomainParameters::minThroughput = 0 "02 01 01" .. -- DomainParameters::maxHeight = 1 "02 02 ff ff" .. -- DomainParameters::maxMCSPDUsize = 65535 "02 01 02" .. -- DomainParameters::protocolVersion = 2 "30 19" .. -- Connect-Initial::minimumParameters (25 bytes) "02 01 01" .. -- DomainParameters::maxChannelIds = 1 "02 01 01" .. -- DomainParameters::maxUserIds = 1 "02 01 01" .. -- DomainParameters::maxTokenIds = 1 "02 01 01" .. -- DomainParameters::numPriorities = 1 "02 01 00" .. -- DomainParameters::minThroughput = 0 "02 01 01" .. -- DomainParameters::maxHeight = 1 "02 02 04 20" .. -- DomainParameters::maxMCSPDUsize = 1056 "02 01 02" .. -- DomainParameters::protocolVersion = 2 "30 1c" .. -- Connect-Initial::maximumParameters (28 bytes) "02 02 ff ff" .. -- DomainParameters::maxChannelIds = 65535 "02 02 fc 17" .. -- DomainParameters::maxUserIds = 64535 "02 02 ff ff" .. -- DomainParameters::maxTokenIds = 65535 "02 01 01" .. -- DomainParameters::numPriorities = 1 "02 01 00" .. -- DomainParameters::minThroughput = 0 "02 01 01" .. -- DomainParameters::maxHeight = 1 "02 02 ff ff" .. -- DomainParameters::maxMCSPDUsize = 65535 "02 01 02" .. -- DomainParameters::protocolVersion = 2 "04 82 01 2f" .. -- Connect-Initial::userData (307 bytes) "00 05" .. -- object length = 5 bytes "00 14 7c 00 01" .. -- object "81 26" .. -- ConnectData::connectPDU length = 298 bytes "00 08 00 10 00 01 c0 00 44 75 63 61 81 18" .. -- PER encoded (ALIGNED variant of BASIC-PER) GCC Conference Create Request PDU "01 c0 d4 00" .. -- TS_UD_HEADER::type = CS_CORE (0xc001), length = 216 bytes "04 00 08 00" .. -- TS_UD_CS_CORE::version = 0x0008004 "00 05" .. -- TS_UD_CS_CORE::desktopWidth = 1280 "20 03" .. -- TS_UD_CS_CORE::desktopHeight = 1024 "01 ca" .. -- TS_UD_CS_CORE::colorDepth = RNS_UD_COLOR_8BPP (0xca01) "03 aa" .. -- TS_UD_CS_CORE::SASSequence "09 08 00 00" .. -- TS_UD_CS_CORE::keyboardLayout = 0x409 = 1033 = English (US) "28 0a 00 00" .. -- TS_UD_CS_CORE::clientBuild = 3790 "45 00 4d 00 50 00 2d 00 4c 00 41 00 50 00 2d 00 30 00 30 00 31 00 34 00 00 00 00 00 00 00 00 00" .. -- TS_UD_CS_CORE::clientName = ELTONS-TEST2 "04 00 00 00" .. -- TS_UD_CS_CORE::keyboardType "00 00 00 00" .. -- TS_UD_CS_CORE::keyboardSubtype "0c 00 00 00" .. -- TS_UD_CS_CORE::keyboardFunctionKey "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 " .. "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 " .. "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 " .. "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 " .. -- TS_UD_CS_CORE::imeFileName = "" "01 ca" .. -- TS_UD_CS_CORE::postBeta2ColorDepth = RNS_UD_COLOR_8BPP (0xca01) "01 00" .. -- TS_UD_CS_CORE::clientProductId "00 00 00 00" .. -- TS_UD_CS_CORE::serialNumber "10 00" .. -- TS_UD_CS_CORE::highColorDepth = 24 bpp "07 00" .. -- TS_UD_CS_CORE::supportedColorDepths "01 00" .. -- TS_UD_CS_CORE::earlyCapabilityFlags "36 00 39 00 37 00 31 00 32 00 2d 00 37 00 38 00 " .. "33 00 2d 00 30 00 33 00 35 00 37 00 39 00 37 00 " .. "34 00 2d 00 34 00 32 00 37 00 31 00 34 00 00 00 " .. "00 00 00 00 00 00 00 00 00 00 00 00 " .. -- TS_UD_CS_CORE::clientDigProductId = "69712-783-0357974-42714" "00" .. -- TS_UD_CS_CORE::connectionType = 0 (not used as RNS_UD_CS_VALID_CONNECTION_TYPE not set) "00" .. -- TS_UD_CS_CORE::pad1octet "00 00 00 00" .. -- TS_UD_CS_CORE::serverSelectedProtocol "04 c0 0c 00" .. -- TS_UD_HEADER::type = CS_CLUSTER (0xc004), length = 12 bytes "09 00 00 00" .. -- TS_UD_CS_CLUSTER::Flags = 0x0d "00 00 00 00" .. -- TS_UD_CS_CLUSTER::RedirectedSessionID "02 c0 0c 00", -- TS_UD_HEADER::type = CS_SECURITY (0xc002), length = 12 bytes -- "1b 00 00 00" .. -- TS_UD_CS_SEC::encryptionMethods self.cipher or 0, "00 00 00 00" .. -- TS_UD_CS_SEC::extEncryptionMethods "03 c0 2c 00" .. -- TS_UD_HEADER::type = CS_NET (0xc003), length = 44 bytes "03 00 00 00" .. -- TS_UD_CS_NET::channelCount = 3 "72 64 70 64 72 00 00 00" .. -- CHANNEL_DEF::name = "rdpdr" "00 00 80 80" .. -- CHANNEL_DEF::options = 0x80800000 "63 6c 69 70 72 64 72 00" .. -- CHANNEL_DEF::name = "cliprdr" "00 00 a0 c0" .. -- CHANNEL_DEF::options = 0xc0a00000 "72 64 70 73 6e 64 00 00" .. -- CHANNEL_DEF::name = "rdpsnd" "00 00 00 c0" -- CHANNEL_DEF::options = 0xc0000000 ) return tostring(Packet.TPKT:new(Packet.ITUT:new(0xF0, data))) end } } Response = { ConnectionConfirm = { new = function(self) local o = { } setmetatable(o, self) self.__index = self return o end, parse = function(data) local cc = Response.ConnectionConfirm:new() local pos, _ cc.tpkt = Packet.TPKT.parse(data) cc.itut = Packet.ITUT.parse(cc.tpkt.data) return cc end, }, MCSConnectResponse = { new = function(self) local o = { } setmetatable(o, self) self.__index = self return o end, parse = function(data) local cr = Response.MCSConnectResponse:new() cr.tpkt = Packet.TPKT.parse(data) cr.itut = Packet.ITUT.parse(cr.tpkt.data) return cr end } } Comm = { -- Creates a new Comm instance -- @param host table -- @param port table -- @return o instance of Comm new = function(self, host, port) local o = { host = host, port = port } setmetatable(o, self) self.__index = self return o end, -- Connect to the server -- @return status true on success, false on failure -- @return err string containing error message, if status is false connect = function(self) self.socket = nmap.new_socket() self.socket:set_timeout(5000) if ( not(self.socket:connect(self.host, self.port)) ) then return false, "Failed connecting to server" end return true end, -- Close the connection to the server -- @return status true on success, false on failure close = function(self) return self.socket:close() end, -- Sends a message to the server -- @param pkt an instance of Request.* -- @return status true on success, false on failure -- @return err string containing error message, if status is false send = function(self, pkt) return self.socket:send(tostring(pkt)) end, -- Receives a message from the server -- @return status true on success, false on failure -- @return err string containing error message, if status is false recv = function(self) return self.socket:receive() end, -- Sends a message to the server and receives the response -- @param pkt an instance of Request.* -- @return status true on success, false on failure -- @return err string containing error message, if status is false -- pkt instance of Response.* on success exch = function(self, pkt) local status, err = self:send(pkt) if ( not(status) ) then return false, err end local data status, data = self:recv() if ( #data< 5 ) then return false, "Packet too short" end local pos, itut_code = bin.unpack("C", data, 6) if ( itut_code == 0xD0 ) then stdnse.print_debug(2, "RDP: Received ConnectionConfirm response") return true, Response.ConnectionConfirm.parse(data) elseif ( itut_code == 0xF0 ) then return true, Response.MCSConnectResponse.parse(data) end return false, "Received unhandled packet" end, } return _ENV;
gpl-2.0
hynnet/hiwifi-openwrt-HC5661-HC5761
staging_dir/target-mipsel_r2_uClibc-0.9.33.2/root-ralink/usr/lib/lua/socket/ftp.lua
144
9120
----------------------------------------------------------------------------- -- FTP support for the Lua language -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: ftp.lua,v 1.45 2007/07/11 19:25:47 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local table = require("table") local string = require("string") local math = require("math") local socket = require("socket") local url = require("socket.url") local tp = require("socket.tp") local ltn12 = require("ltn12") module("socket.ftp") ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- -- timeout in seconds before the program gives up on a connection TIMEOUT = 60 -- default port for ftp service PORT = 21 -- this is the default anonymous password. used when no password is -- provided in url. should be changed to your e-mail. USER = "ftp" PASSWORD = "anonymous@anonymous.org" ----------------------------------------------------------------------------- -- Low level FTP API ----------------------------------------------------------------------------- local metat = { __index = {} } function open(server, port, create) local tp = socket.try(tp.connect(server, port or PORT, TIMEOUT, create)) local f = base.setmetatable({ tp = tp }, metat) -- make sure everything gets closed in an exception f.try = socket.newtry(function() f:close() end) return f end function metat.__index:portconnect() self.try(self.server:settimeout(TIMEOUT)) self.data = self.try(self.server:accept()) self.try(self.data:settimeout(TIMEOUT)) end function metat.__index:pasvconnect() self.data = self.try(socket.tcp()) self.try(self.data:settimeout(TIMEOUT)) self.try(self.data:connect(self.pasvt.ip, self.pasvt.port)) end function metat.__index:login(user, password) self.try(self.tp:command("user", user or USER)) local code, reply = self.try(self.tp:check{"2..", 331}) if code == 331 then self.try(self.tp:command("pass", password or PASSWORD)) self.try(self.tp:check("2..")) end return 1 end function metat.__index:pasv() self.try(self.tp:command("pasv")) local code, reply = self.try(self.tp:check("2..")) local pattern = "(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)" local a, b, c, d, p1, p2 = socket.skip(2, string.find(reply, pattern)) self.try(a and b and c and d and p1 and p2, reply) self.pasvt = { ip = string.format("%d.%d.%d.%d", a, b, c, d), port = p1*256 + p2 } if self.server then self.server:close() self.server = nil end return self.pasvt.ip, self.pasvt.port end function metat.__index:port(ip, port) self.pasvt = nil if not ip then ip, port = self.try(self.tp:getcontrol():getsockname()) self.server = self.try(socket.bind(ip, 0)) ip, port = self.try(self.server:getsockname()) self.try(self.server:settimeout(TIMEOUT)) end local pl = math.mod(port, 256) local ph = (port - pl)/256 local arg = string.gsub(string.format("%s,%d,%d", ip, ph, pl), "%.", ",") self.try(self.tp:command("port", arg)) self.try(self.tp:check("2..")) return 1 end function metat.__index:send(sendt) self.try(self.pasvt or self.server, "need port or pasv first") -- if there is a pasvt table, we already sent a PASV command -- we just get the data connection into self.data if self.pasvt then self:pasvconnect() end -- get the transfer argument and command local argument = sendt.argument or url.unescape(string.gsub(sendt.path or "", "^[/\\]", "")) if argument == "" then argument = nil end local command = sendt.command or "stor" -- send the transfer command and check the reply self.try(self.tp:command(command, argument)) local code, reply = self.try(self.tp:check{"2..", "1.."}) -- if there is not a a pasvt table, then there is a server -- and we already sent a PORT command if not self.pasvt then self:portconnect() end -- get the sink, source and step for the transfer local step = sendt.step or ltn12.pump.step local readt = {self.tp.c} local checkstep = function(src, snk) -- check status in control connection while downloading local readyt = socket.select(readt, nil, 0) if readyt[tp] then code = self.try(self.tp:check("2..")) end return step(src, snk) end local sink = socket.sink("close-when-done", self.data) -- transfer all data and check error self.try(ltn12.pump.all(sendt.source, sink, checkstep)) if string.find(code, "1..") then self.try(self.tp:check("2..")) end -- done with data connection self.data:close() -- find out how many bytes were sent local sent = socket.skip(1, self.data:getstats()) self.data = nil return sent end function metat.__index:receive(recvt) self.try(self.pasvt or self.server, "need port or pasv first") if self.pasvt then self:pasvconnect() end local argument = recvt.argument or url.unescape(string.gsub(recvt.path or "", "^[/\\]", "")) if argument == "" then argument = nil end local command = recvt.command or "retr" self.try(self.tp:command(command, argument)) local code = self.try(self.tp:check{"1..", "2.."}) if not self.pasvt then self:portconnect() end local source = socket.source("until-closed", self.data) local step = recvt.step or ltn12.pump.step self.try(ltn12.pump.all(source, recvt.sink, step)) if string.find(code, "1..") then self.try(self.tp:check("2..")) end self.data:close() self.data = nil return 1 end function metat.__index:cwd(dir) self.try(self.tp:command("cwd", dir)) self.try(self.tp:check(250)) return 1 end function metat.__index:type(type) self.try(self.tp:command("type", type)) self.try(self.tp:check(200)) return 1 end function metat.__index:greet() local code = self.try(self.tp:check{"1..", "2.."}) if string.find(code, "1..") then self.try(self.tp:check("2..")) end return 1 end function metat.__index:quit() self.try(self.tp:command("quit")) self.try(self.tp:check("2..")) return 1 end function metat.__index:close() if self.data then self.data:close() end if self.server then self.server:close() end return self.tp:close() end ----------------------------------------------------------------------------- -- High level FTP API ----------------------------------------------------------------------------- local function override(t) if t.url then local u = url.parse(t.url) for i,v in base.pairs(t) do u[i] = v end return u else return t end end local function tput(putt) putt = override(putt) socket.try(putt.host, "missing hostname") local f = open(putt.host, putt.port, putt.create) f:greet() f:login(putt.user, putt.password) if putt.type then f:type(putt.type) end f:pasv() local sent = f:send(putt) f:quit() f:close() return sent end local default = { path = "/", scheme = "ftp" } local function parse(u) local t = socket.try(url.parse(u, default)) socket.try(t.scheme == "ftp", "wrong scheme '" .. t.scheme .. "'") socket.try(t.host, "missing hostname") local pat = "^type=(.)$" if t.params then t.type = socket.skip(2, string.find(t.params, pat)) socket.try(t.type == "a" or t.type == "i", "invalid type '" .. t.type .. "'") end return t end local function sput(u, body) local putt = parse(u) putt.source = ltn12.source.string(body) return tput(putt) end put = socket.protect(function(putt, body) if base.type(putt) == "string" then return sput(putt, body) else return tput(putt) end end) local function tget(gett) gett = override(gett) socket.try(gett.host, "missing hostname") local f = open(gett.host, gett.port, gett.create) f:greet() f:login(gett.user, gett.password) if gett.type then f:type(gett.type) end f:pasv() f:receive(gett) f:quit() return f:close() end local function sget(u) local gett = parse(u) local t = {} gett.sink = ltn12.sink.table(t) tget(gett) return table.concat(t) end command = socket.protect(function(cmdt) cmdt = override(cmdt) socket.try(cmdt.host, "missing hostname") socket.try(cmdt.command, "missing command") local f = open(cmdt.host, cmdt.port, cmdt.create) f:greet() f:login(cmdt.user, cmdt.password) f.try(f.tp:command(cmdt.command, cmdt.argument)) if cmdt.check then f.try(f.tp:check(cmdt.check)) end f:quit() return f:close() end) get = socket.protect(function(gett) if base.type(gett) == "string" then return sget(gett) else return tget(gett) end end)
gpl-2.0
hawkthorne/hawkthorne-server-lua
src/items/recipes.lua
2
1039
----------------------------------------- -- recipes.lua -- Contains all the crafting recipies that the player can use -- Created by HazardousPeach ----------------------------------------- return { { { type='material', name='rock' }, { type='material', name='stick' }, { type='weapon', name='throwingknife' } }, { { type='material', name='bone' }, { type='material', name='crystal' }, { type='weapon', name='icicle' } }, { { type='material', name='rock' }, { type='material', name='rock' }, { type='weapon', name='mace' } }, { { type='material', name='leaf' }, { type='material', name='leaf' }, { type='weapon', name='torch' } }, { { type='material', name='stick' }, { type='material', name='stick' }, { type='weapon', name='sword' } }, { { type='material', name='leaf' }, { type='material', name='rock' }, { type='weapon', name='mallet' } }, }
mit
hynnet/hiwifi-openwrt-HC5661-HC5761
staging_dir/target-mipsel_r2_uClibc-0.9.33.2/root-ralink/usr/lib/lua/ltn12.lua
127
8177
----------------------------------------------------------------------------- -- LTN12 - Filters, sources, sinks and pumps. -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: ltn12.lua,v 1.31 2006/04/03 04:45:42 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module ----------------------------------------------------------------------------- local string = require("string") local table = require("table") local base = _G module("ltn12") filter = {} source = {} sink = {} pump = {} -- 2048 seems to be better in windows... BLOCKSIZE = 2048 _VERSION = "LTN12 1.0.1" ----------------------------------------------------------------------------- -- Filter stuff ----------------------------------------------------------------------------- -- returns a high level filter that cycles a low-level filter function filter.cycle(low, ctx, extra) base.assert(low) return function(chunk) local ret ret, ctx = low(ctx, chunk, extra) return ret end end -- chains a bunch of filters together -- (thanks to Wim Couwenberg) function filter.chain(...) local n = table.getn(arg) local top, index = 1, 1 local retry = "" return function(chunk) retry = chunk and retry while true do if index == top then chunk = arg[index](chunk) if chunk == "" or top == n then return chunk elseif chunk then index = index + 1 else top = top+1 index = top end else chunk = arg[index](chunk or "") if chunk == "" then index = index - 1 chunk = retry elseif chunk then if index == n then return chunk else index = index + 1 end else base.error("filter returned inappropriate nil") end end end end end ----------------------------------------------------------------------------- -- Source stuff ----------------------------------------------------------------------------- -- create an empty source local function empty() return nil end function source.empty() return empty end -- returns a source that just outputs an error function source.error(err) return function() return nil, err end end -- creates a file source function source.file(handle, io_err) if handle then return function() local chunk = handle:read(BLOCKSIZE) if not chunk then handle:close() end return chunk end else return source.error(io_err or "unable to open file") end end -- turns a fancy source into a simple source function source.simplify(src) base.assert(src) return function() local chunk, err_or_new = src() src = err_or_new or src if not chunk then return nil, err_or_new else return chunk end end end -- creates string source function source.string(s) if s then local i = 1 return function() local chunk = string.sub(s, i, i+BLOCKSIZE-1) i = i + BLOCKSIZE if chunk ~= "" then return chunk else return nil end end else return source.empty() end end -- creates rewindable source function source.rewind(src) base.assert(src) local t = {} return function(chunk) if not chunk then chunk = table.remove(t) if not chunk then return src() else return chunk end else table.insert(t, chunk) end end end function source.chain(src, f) base.assert(src and f) local last_in, last_out = "", "" local state = "feeding" local err return function() if not last_out then base.error('source is empty!', 2) end while true do if state == "feeding" then last_in, err = src() if err then return nil, err end last_out = f(last_in) if not last_out then if last_in then base.error('filter returned inappropriate nil') else return nil end elseif last_out ~= "" then state = "eating" if last_in then last_in = "" end return last_out end else last_out = f(last_in) if last_out == "" then if last_in == "" then state = "feeding" else base.error('filter returned ""') end elseif not last_out then if last_in then base.error('filter returned inappropriate nil') else return nil end else return last_out end end end end end -- creates a source that produces contents of several sources, one after the -- other, as if they were concatenated -- (thanks to Wim Couwenberg) function source.cat(...) local src = table.remove(arg, 1) return function() while src do local chunk, err = src() if chunk then return chunk end if err then return nil, err end src = table.remove(arg, 1) end end end ----------------------------------------------------------------------------- -- Sink stuff ----------------------------------------------------------------------------- -- creates a sink that stores into a table function sink.table(t) t = t or {} local f = function(chunk, err) if chunk then table.insert(t, chunk) end return 1 end return f, t end -- turns a fancy sink into a simple sink function sink.simplify(snk) base.assert(snk) return function(chunk, err) local ret, err_or_new = snk(chunk, err) if not ret then return nil, err_or_new end snk = err_or_new or snk return 1 end end -- creates a file sink function sink.file(handle, io_err) if handle then return function(chunk, err) if not chunk then handle:close() return 1 else return handle:write(chunk) end end else return sink.error(io_err or "unable to open file") end end -- creates a sink that discards data local function null() return 1 end function sink.null() return null end -- creates a sink that just returns an error function sink.error(err) return function() return nil, err end end -- chains a sink with a filter function sink.chain(f, snk) base.assert(f and snk) return function(chunk, err) if chunk ~= "" then local filtered = f(chunk) local done = chunk and "" while true do local ret, snkerr = snk(filtered, err) if not ret then return nil, snkerr end if filtered == done then return 1 end filtered = f(done) end else return 1 end end end ----------------------------------------------------------------------------- -- Pump stuff ----------------------------------------------------------------------------- -- pumps one chunk from the source to the sink function pump.step(src, snk) local chunk, src_err = src() local ret, snk_err = snk(chunk, src_err) if chunk and ret then return 1 else return nil, src_err or snk_err end end -- pumps all data from a source to a sink, using a step function function pump.all(src, snk, step) base.assert(src and snk) step = step or pump.step while true do local ret, err = step(src, snk) if not ret then if err then return nil, err else return 1 end end end end
gpl-2.0
FalacerSelene/vim-commentable
test/lua-modules/utils.lua
1
4139
local M = {} local function maybe_require (modname) local mod = nil pcall(function () mod = require(modname) end) return mod end local lfs = maybe_require('lfs') --[========================================================================]-- --[ extendtable (first, second) {{{ ]-- --[ ]-- --[ Description: ]-- --[ Extend the first table with all the elements of the second. ]-- --[ ]-- --[ Returns nothing. ]-- --[========================================================================]-- M.extendtable = function (first, second) local _, e for _, e in ipairs(second) do first[#first+1] = e end end --[========================================================================]-- --[ }}} ]-- --[========================================================================]-- --[========================================================================]-- --[ isdir (dirname) {{{ ]-- --[ ]-- --[ Description: ]-- --[ Does the specified directory exist, and is it a directory? ]-- --[ ]-- --[ Params: ]-- --[ 1) dirname - dir to check ]-- --[ ]-- --[ Returns: ]-- --[ 1) true/false ]-- --[========================================================================]-- M.isdir = function (dirname) local isdir = false local diratts if lfs then diratts = lfs.attributes(dirname) isdir = diratts and diratts.mode == 'directory' elseif os.execute('[ -d "' .. dirname .. '" ]') then isdir = true end return isdir end --[========================================================================]-- --[ }}} ]-- --[========================================================================]-- --[========================================================================]-- --[ isfile (filename) {{{ ]-- --[ ]-- --[ Description: ]-- --[ Does the specified file exist, and is it a normal file? ]-- --[ ]-- --[ Params: ]-- --[ 1) filename - file to check ]-- --[ ]-- --[ Returns: ]-- --[ 1) true/false ]-- --[========================================================================]-- M.isfile = function (filename) local isfile = false local fileatts if lfs then fileatts = lfs.attributes(filename) isfile = fileatts and fileatts.mode == 'file' elseif os.execute('[ -f "' .. filename .. '" ]') then isfile = true end return isfile end --[========================================================================]-- --[ }}} ]-- --[========================================================================]-- M.patternescape = function (str) return str:gsub("([][()$^%%*+?-])","%%%1") end return M
unlicense
chrisballinger/ChatSecure-Mac
LuaService/prosody/lib/prosody/util/pluginloader.lua
3
1717
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local dir_sep, path_sep = package.config:match("^(%S+)%s(%S+)"); local plugin_dir = {}; for path in (CFG_PLUGINDIR or "./plugins/"):gsub("[/\\]", dir_sep):gmatch("[^"..path_sep.."]+") do path = path..dir_sep; -- add path separator to path end path = path:gsub(dir_sep..dir_sep.."+", dir_sep); -- coalesce multiple separaters plugin_dir[#plugin_dir + 1] = path; end local io_open = io.open; local envload = require "util.envload".envload; module "pluginloader" function load_file(names) local file, err, path; for i=1,#plugin_dir do for j=1,#names do path = plugin_dir[i]..names[j]; file, err = io_open(path); if file then local content = file:read("*a"); file:close(); return content, path; end end end return file, err; end function load_resource(plugin, resource) resource = resource or "mod_"..plugin..".lua"; local names = { "mod_"..plugin..dir_sep..plugin..dir_sep..resource; -- mod_hello/hello/mod_hello.lua "mod_"..plugin..dir_sep..resource; -- mod_hello/mod_hello.lua plugin..dir_sep..resource; -- hello/mod_hello.lua resource; -- mod_hello.lua }; return load_file(names); end function load_code(plugin, resource, env) local content, err = load_resource(plugin, resource); if not content then return content, err; end local path = err; local f, err = envload(content, "@"..path, env); if not f then return f, err; end return f, path; end return _M;
mpl-2.0
ZeeBeast/AeiaOTS
data/npc/scripts/runes.lua
5
8209
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) local talkState = {} 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 local shopModule = ShopModule:new() npcHandler:addModule(shopModule) shopModule:addBuyableItem({'spellbook'}, 2175, 150, 'spellbook') shopModule:addBuyableItem({'magic lightwand'}, 2163, 400, 'magic lightwand') shopModule:addBuyableItem({'small health'}, 8704, 20, 1, 'small health potion') shopModule:addBuyableItem({'health potion'}, 7618, 45, 1, 'health potion') shopModule:addBuyableItem({'mana potion'}, 7620, 50, 1, 'mana potion') shopModule:addBuyableItem({'strong health'}, 7588, 100, 1, 'strong health potion') shopModule:addBuyableItem({'strong mana'}, 7589, 80, 1, 'strong mana potion') shopModule:addBuyableItem({'great health'}, 7591, 190, 1, 'great health potion') shopModule:addBuyableItem({'great mana'}, 7590, 120, 1, 'great mana potion') shopModule:addBuyableItem({'great spirit'}, 8472, 190, 1, 'great spirit potion') shopModule:addBuyableItem({'ultimate health'}, 8473, 310, 1, 'ultimate health potion') shopModule:addBuyableItem({'antidote potion'}, 8474, 50, 1, 'antidote potion') shopModule:addSellableItem({'normal potion flask', 'normal flask'}, 7636, 5, 'empty small potion flask') shopModule:addSellableItem({'strong potion flask', 'strong flask'}, 7634, 10, 'empty strong potion flask') shopModule:addSellableItem({'great potion flask', 'great flask'}, 7635, 15, 'empty great potion flask') shopModule:addBuyableItem({'instense healing'}, 2265, 95, 1, 'intense healing rune') shopModule:addBuyableItem({'ultimate healing'}, 2273, 175, 1, 'ultimate healing rune') shopModule:addBuyableItem({'magic wall'}, 2293, 350, 3, 'magic wall rune') shopModule:addBuyableItem({'destroy field'}, 2261, 45, 3, 'destroy field rune') shopModule:addBuyableItem({'light magic missile'}, 2287, 40, 10, 'light magic missile rune') shopModule:addBuyableItem({'heavy magic missile'}, 2311, 120, 10, 'heavy magic missile rune') shopModule:addBuyableItem({'great fireball'}, 2304, 180, 4, 'great fireball rune') shopModule:addBuyableItem({'explosion'}, 2313, 250, 6, 'explosion rune') shopModule:addBuyableItem({'sudden death'}, 2268, 350, 3, 'sudden death rune') shopModule:addBuyableItem({'death arrow'}, 2263, 300, 3, 'death arrow rune') shopModule:addBuyableItem({'paralyze'}, 2278, 700, 1, 'paralyze rune') shopModule:addBuyableItem({'animate dead'}, 2316, 375, 1, 'animate dead rune') shopModule:addBuyableItem({'convince creature'}, 2290, 80, 1, 'convince creature rune') shopModule:addBuyableItem({'chameleon'}, 2291, 210, 1, 'chameleon rune') shopModule:addBuyableItem({'desintegrate'}, 2310, 80, 3, 'desintegreate rune') shopModule:addBuyableItemContainer({'bp slhp'}, 2000, 8704, 400, 1, 'backpack of small health potions') shopModule:addBuyableItemContainer({'bp hp'}, 2000, 7618, 900, 1, 'backpack of health potions') shopModule:addBuyableItemContainer({'bp mp'}, 2001, 7620, 1000, 1, 'backpack of mana potions') shopModule:addBuyableItemContainer({'bp shp'}, 2000, 7588, 2000, 1, 'backpack of strong health potions') shopModule:addBuyableItemContainer({'bp smp'}, 2001, 7589, 1600, 1, 'backpack of strong mana potions') shopModule:addBuyableItemContainer({'bp ghp'}, 2000, 7591, 3800, 1, 'backpack of great health potions') shopModule:addBuyableItemContainer({'bp gmp'}, 2001, 7590, 2400, 1, 'backpack of great mana potions') shopModule:addBuyableItemContainer({'bp gsp'}, 1999, 8472, 3800, 1, 'backpack of great spirit potions') shopModule:addBuyableItemContainer({'bp uhp'}, 2000, 8473, 6200, 1, 'backpack of ultimate health potions') shopModule:addBuyableItemContainer({'bp ap'}, 2002, 8474, 2000, 1, 'backpack of antidote potions') shopModule:addBuyableItem({'wand of vortex', 'vortex'}, 2190, 500, 'wand of vortex') shopModule:addBuyableItem({'wand of dragonbreath', 'dragonbreath'}, 2191, 1000, 'wand of dragonbreath') shopModule:addBuyableItem({'wand of decay', 'decay'}, 2188, 5000, 'wand of decay') shopModule:addBuyableItem({'wand of draconia', 'draconia'}, 8921, 7500, 'wand of draconia') shopModule:addBuyableItem({'wand of cosmic energy', 'cosmic energy'}, 2189, 10000, 'wand of cosmic energy') shopModule:addBuyableItem({'wand of inferno', 'inferno'}, 2187, 15000, 'wand of inferno') shopModule:addBuyableItem({'wand of starstorm', 'starstorm'}, 8920, 18000, 'wand of starstorm') shopModule:addBuyableItem({'wand of voodoo', 'voodoo'}, 8922, 22000, 'wand of voodoo') shopModule:addBuyableItem({'snakebite rod', 'snakebite'}, 2182, 500, 'snakebite rod') shopModule:addBuyableItem({'moonlight rod', 'moonlight'}, 2186, 1000, 'moonlight rod') shopModule:addBuyableItem({'necrotic rod', 'necrotic'}, 2185, 5000, 'necrotic rod') shopModule:addBuyableItem({'northwind rod', 'northwind'}, 8911, 7500, 'northwind rod') shopModule:addBuyableItem({'terra rod', 'terra'}, 2181, 10000, 'terra rod') shopModule:addBuyableItem({'hailstorm rod', 'hailstorm'}, 2183, 15000, 'hailstorm rod') shopModule:addBuyableItem({'springsprout rod', 'springsprout'}, 8912, 18000, 'springsprout rod') shopModule:addBuyableItem({'underworld rod', 'underworld'}, 8910, 22000, 'underworld rod') shopModule:addSellableItem({'wand of vortex', 'vortex'}, 2190, 250, 'wand of vortex') shopModule:addSellableItem({'wand of dragonbreath', 'dragonbreath'}, 2191, 500, 'wand of dragonbreath') shopModule:addSellableItem({'wand of decay', 'decay'}, 2188, 2500, 'wand of decay') shopModule:addSellableItem({'wand of draconia', 'draconia'}, 8921, 3750, 'wand of draconia') shopModule:addSellableItem({'wand of cosmic energy', 'cosmic energy'}, 2189, 5000, 'wand of cosmic energy') shopModule:addSellableItem({'wand of inferno', 'inferno'},2187, 7500, 'wand of inferno') shopModule:addSellableItem({'wand of starstorm', 'starstorm'}, 8920, 9000, 'wand of starstorm') shopModule:addSellableItem({'wand of voodoo', 'voodoo'}, 8922, 11000, 'wand of voodoo') shopModule:addSellableItem({'snakebite rod', 'snakebite'}, 2182, 250,'snakebite rod') shopModule:addSellableItem({'moonlight rod', 'moonlight'}, 2186, 500, 'moonlight rod') shopModule:addSellableItem({'necrotic rod', 'necrotic'}, 2185, 2500, 'necrotic rod') shopModule:addSellableItem({'northwind rod', 'northwind'}, 8911, 3750, 'northwind rod') shopModule:addSellableItem({'terra rod', 'terra'}, 2181, 5000, 'terra rod') shopModule:addSellableItem({'hailstorm rod', 'hailstorm'}, 2183, 7500, 'hailstorm rod') shopModule:addSellableItem({'springsprout rod', 'springsprout'}, 8912, 9000, 'springsprout rod') shopModule:addSellableItem({'underworld rod', 'underworld'}, 8910, 11000, 'underworld rod') local items = {[1] = 2190, [2] = 2182, [5] = 2190, [6] = 2182} function creatureSayCallback(cid, type, msg) if(not npcHandler:isFocused(cid)) then return false end local talkUser = NPCHANDLER_CONVBEHAVIOR == CONVERSATION_DEFAULT and 0 or cid if(msgcontains(msg, 'first rod') or msgcontains(msg, 'first wand')) then if(isSorcerer(cid) or isDruid(cid)) then if(getPlayerStorageValue(cid, 30002) <= 0) then selfSay('So you ask me for a {' .. getItemNameById(items[getPlayerVocation(cid)]) .. '} to begin your advanture?', cid) talkState[talkUser] = 1 else selfSay('What? I have already gave you one {' .. getItemNameById(items[getPlayerVocation(cid)]) .. '}!', cid) end else selfSay('Sorry, you aren\'t a druid either a sorcerer.', cid) end elseif(msgcontains(msg, 'yes')) then if(talkState[talkUser] == 1) then doPlayerAddItem(cid, items[getPlayerVocation(cid)], 1) selfSay('Here you are young adept, take care yourself.', cid) setPlayerStorageValue(cid, 30002, 1) end talkState[talkUser] = 0 elseif(msgcontains(msg, 'no') and isInArray({1}, talkState[talkUser])) then selfSay('Ok then.', cid) talkState[talkUser] = 0 end return true end npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
agpl-3.0
tmbr54/Kingmaker
game/dota_addons/castle_wars/scripts/vscripts/buildings/race6/upgrade_to_special_1.lua
1
1382
--Undead Special Spawner function cast_upgrade(event) local iPlayerID = event.caster:GetMainControllingPlayer() --print("iPlayerID", iPlayerID) local hero = PlayerResource:GetSelectedHeroEntity(iPlayerID) --print("hero name: ",PlayerResource:GetSelectedHeroName(iPlayerID)) local iTeamNumber = hero:GetTeamNumber() local vPosition = event.caster:GetAbsOrigin() if RemoveGold(iPlayerID, 100, 7) == true then local barracks = CreateUnitByName("race_6_special_building_1", vPosition, false, hero, hero, iTeamNumber) barracks:SetControllableByPlayer(iPlayerID, true) local particlePosition = barracks:GetAbsOrigin() local upgradeParticle = ParticleManager:CreateParticle("particles/units/heroes/hero_bristleback/bristleback_quill_spray_ring_dust.vpcf", PATTACH_ABSORIGIN_FOLLOW, barracks) ParticleManager:SetParticleControl(upgradeParticle, 0, barracks:GetAbsOrigin()) local claimParticle = ParticleManager:CreateParticleForPlayer("particles/econ/courier/courier_baekho/courier_baekho_ambient.vpcf", PATTACH_OVERHEAD_FOLLOW, barracks, PlayerResource:GetPlayer(iPlayerID)) ParticleManager:SetParticleControl(claimParticle, 0, particlePosition - Vector(50,0,0)) currentTeam = barracks:GetTeam() ParticleManager:SetParticleControl(claimParticle, 15, race_color_table[currentTeam]) UTIL_Remove(event.caster) AddUnitToSelection(barracks) end end
apache-2.0
aj-gh/pdns
pdns/dnsdistconf.lua
9
4478
-- == Generic Configuration == -- only accept queries (Do53, DNSCrypt, DoT or DoH) from a few subnets -- see https://dnsdist.org/advanced/acl.html for more details -- please be careful when dnsdist is deployed in front of a server -- server granting access based on the source IP, as all queries will -- seem to originate from dnsdist, which might be especially relevant for -- AXFR, IXFR, NOTIFY and UPDATE -- https://dnsdist.org/advanced/axfr.html -- setACL({'192.0.2.0/28', '2001:DB8:1::/56'}) -- listen for console connection with the given secret key -- https://dnsdist.org/guides/console.html -- controlSocket("127.0.0.1:5900") -- setKey("please generate a fresh private key with makeKey()") -- start the web server on port 8083, using password 'set a random password here' -- https://dnsdist.org/guides/webserver.html -- webserver("127.0.0.1:8083", "set a random password here") -- send statistics to PowerDNS metronome server https://metronome1.powerdns.com/ -- https://dnsdist.org/guides/carbon.html -- carbonServer("37.252.122.50", 'unique-name') -- accept plain DNS (Do53) queries on UDP/5200 and TCP/5200 -- addLocal("127.0.0.1:5200") -- accept DNSCrypt queries on UDP/8443 and TCP/8443 -- https://dnsdist.org/guides/dnscrypt.html -- addDNSCryptBind("127.0.0.1:8443", "2.provider.name", "DNSCryptResolver.cert", "DNSCryptResolver.key") -- accept DNS over TLS (DoT) queries on TCP/9443 -- https://dnsdist.org/guides/dns-over-tls.html -- addTLSLocal("127.0.0.1:9443", {"server.crt"}, {"server.key"}, { provider="openssl" }) -- accept DNS over HTTPS (DoH) queries on TCP/443 -- https://dnsdist.org/guides/dns-over-https.html -- addDOHLocal("127.0.0.1:443", {"server.crt"}, {"server.key"}) -- define downstream servers, aka backends -- https://dnsdist.org/guides/downstreams.html -- https://dnsdist.org/guides/serverpools.html -- https://dnsdist.org/guides/serverselection.html -- newServer("192.0.2.1") -- newServer({address="192.0.2.1:5300", pool="abuse"}) -- == Tuning == -- Increase the in-memory rings size (the default, 10000, is only one second at 10k qps) used by -- live-traffic inspection features like grepq, and use 100 shards to improve performance -- setRingBuffersSize(1000000, 100) -- increase the number of TCP workers, each one being capable of handling a large number -- of TCP connections since 1.4.0 -- setMaxTCPClientThreads(20) -- == Sample Actions == -- https://dnsdist.org/rules-actions.html -- send the queries for selected domain suffixes to the servers -- in the 'abuse' pool -- addAction({"abuse.example.org.", "xxx."}, PoolAction("abuse")) -- drop queries for this exact qname -- addAction(QNameRule("drop-me.example.org."), DropAction()) -- send the queries from a selected subnet to the -- abuse pool -- addAction("192.0.2.0/24", PoolAction("abuse")) -- Refuse incoming AXFR, IXFR, NOTIFY and UPDATE -- Add trusted sources (slaves, masters) explicitely in front of this rule -- addAction(OrRule({OpcodeRule(DNSOpcode.Notify), OpcodeRule(DNSOpcode.Update), QTypeRule(DNSQType.AXFR), QTypeRule(DNSQType.IXFR)}), RCodeAction(DNSRCode.REFUSED)) -- == Dynamic Blocks == -- define a dynamic block rules group object, set a few limits and apply it -- see https://dnsdist.org/guides/dynblocks.html for more details -- local dbr = dynBlockRulesGroup() -- dbr:setQueryRate(30, 10, "Exceeded query rate", 60) -- dbr:setRCodeRate(dnsdist.NXDOMAIN, 20, 10, "Exceeded NXD rate", 60) -- dbr:setRCodeRate(dnsdist.SERVFAIL, 20, 10, "Exceeded ServFail rate", 60) -- dbr:setQTypeRate(dnsdist.ANY, 5, 10, "Exceeded ANY rate", 60) -- dbr:setResponseByteRate(10000, 10, "Exceeded resp BW rate", 60) -- function maintenance() -- dbr:apply() -- end -- == Logging == -- connect to a remote protobuf logger and export queries and responses -- https://dnsdist.org/reference/protobuf.html -- rl = newRemoteLogger('127.0.0.1:4242') -- addAction(AllRule(), RemoteLogAction(rl)) -- addResponseAction(AllRule(), RemoteLogResponseAction(rl)) -- DNSTAP is also supported -- https://dnsdist.org/reference/dnstap.html -- fstr = newFrameStreamUnixLogger(/path/to/unix/socket) -- or -- fstr = newFrameStreamTcpLogger('192.0.2.1:4242') -- addAction(AllRule(), DnstapLogAction(fstr)) -- addResponseAction(AllRule(), DnstapLogResponseAction(fstr)) -- == Caching == -- https://dnsdist.org/guides/cache.html -- create a packet cache of at most 100k entries, -- and apply it to the default pool -- pc = newPacketCache(100000) -- getPool(""):setCache(pc)
gpl-2.0
notcake/wire
lua/wire/stools/gpu.lua
9
7423
WireToolSetup.setCategory( "Chips, Gates", "Visuals/Screens", "Advanced" ) WireToolSetup.open( "gpu", "GPU", "gmod_wire_gpu", nil, "GPUs" ) if CLIENT then language.Add("Tool.wire_gpu.name", "GPU Tool (Wire)") language.Add("Tool.wire_gpu.desc", "Spawns a graphics processing unit") language.Add("Tool.wire_gpu.0", "Primary: create/reflash ZGPU or other hispeed device, Secondary: open editor and/or attach debugger to the ZGPU") language.Add("ToolWiregpu_Model", "Model:" ) end WireToolSetup.BaseLang() WireToolSetup.SetupMax( 7 ) TOOL.ClientConVar = { model = "models/cheeze/wires/cpu.mdl", filename = "", memorymodel = "64k", } if CLIENT then ------------------------------------------------------------------------------ -- Make sure firing animation is displayed clientside ------------------------------------------------------------------------------ function TOOL:LeftClick() return true end function TOOL:Reload() return true end function TOOL:RightClick() return false end end if SERVER then util.AddNetworkString("ZGPU_RequestCode") util.AddNetworkString("ZGPU_OpenEditor") ------------------------------------------------------------------------------ -- Reload: wipe ROM/RAM and reset memory model ------------------------------------------------------------------------------ function TOOL:Reload(trace) if trace.Entity:IsPlayer() then return false end local player = self:GetOwner() if (trace.Entity:IsValid()) and (trace.Entity:GetClass() == "gmod_wire_gpu") then trace.Entity:SetMemoryModel(self:GetClientInfo("memorymodel")) return true end end -- Left click: spawn GPU or upload current program into it function TOOL:CheckHitOwnClass(trace) return trace.Entity:IsValid() and (trace.Entity:GetClass() == self.WireClass or trace.Entity.WriteCell) end function TOOL:LeftClick_Update(trace) CPULib.SetUploadTarget(trace.Entity, self:GetOwner()) net.Start("ZGPU_RequestCode") net.Send(self:GetOwner()) end function TOOL:MakeEnt(ply, model, Ang, trace) local ent = WireLib.MakeWireEnt(ply, {Class = self.WireClass, Pos=trace.HitPos, Angle=Ang, Model=model}) ent:SetMemoryModel(self:GetClientInfo("memorymodel")) self:LeftClick_Update(trace) return ent end function TOOL:RightClick(trace) net.Start("ZGPU_OpenEditor") net.Send(self:GetOwner()) return true end end if CLIENT then ------------------------------------------------------------------------------ -- Compiler callbacks on the compiling state ------------------------------------------------------------------------------ local function compile_success() CPULib.Upload() end local function compile_error(errorText) print(errorText) GAMEMODE:AddNotify(errorText,NOTIFY_GENERIC,7) end ------------------------------------------------------------------------------ -- Request code to be compiled (called remotely from server) ------------------------------------------------------------------------------ function ZGPU_RequestCode() if ZGPU_Editor then CPULib.Debugger.SourceTab = ZGPU_Editor:GetActiveTab() CPULib.Compile(ZGPU_Editor:GetCode(),ZGPU_Editor:GetChosenFile(),compile_success,compile_error,"GPU") end end net.Receive("ZGPU_RequestCode", ZGPU_RequestCode) ------------------------------------------------------------------------------ -- Open ZGPU editor ------------------------------------------------------------------------------ function ZGPU_OpenEditor() if not ZGPU_Editor then ZGPU_Editor = vgui.Create("Expression2EditorFrame") ZGPU_Editor:Setup("ZGPU Editor", "gpuchip", "GPU") end ZGPU_Editor:Open() end net.Receive("ZGPU_OpenEditor", ZGPU_OpenEditor) ------------------------------------------------------------------------------ -- Build tool control panel ------------------------------------------------------------------------------ function TOOL.BuildCPanel(panel) local Button = vgui.Create("DButton" , panel) panel:AddPanel(Button) Button:SetText("Online ZGPU documentation") Button.DoClick = function(button) CPULib.ShowDocumentation("ZGPU") end ---------------------------------------------------------------------------- local currentDirectory local FileBrowser = vgui.Create("wire_expression2_browser" , panel) panel:AddPanel(FileBrowser) FileBrowser:Setup("GPUChip") FileBrowser:SetSize(235,400) function FileBrowser:OnFileOpen(filepath, newtab) if not ZGPU_Editor then ZGPU_Editor = vgui.Create("Expression2EditorFrame") ZGPU_Editor:Setup("ZGPU Editor", "gpuchip", "GPU") end ZGPU_Editor:Open(filepath, nil, newtab) end ---------------------------------------------------------------------------- local New = vgui.Create("DButton" , panel) panel:AddPanel(New) New:SetText("New file") New.DoClick = function(button) ZGPU_OpenEditor() ZGPU_Editor:AutoSave() ZGPU_Editor:NewScript(false) end panel:AddControl("Label", {Text = ""}) ---------------------------------------------------------------------------- local OpenEditor = vgui.Create("DButton", panel) panel:AddPanel(OpenEditor) OpenEditor:SetText("Open Editor") OpenEditor.DoClick = ZGPU_OpenEditor ---------------------------------------------------------------------------- local modelPanel = WireDermaExts.ModelSelect(panel, "wire_gpu_model", list.Get("WireScreenModels"), 3) modelPanel:SetModelList(list.Get("Wire_gate_Models"),"wire_gpu_model") panel:AddControl("Label", {Text = ""}) ---------------------------------------------------------------------------- panel:AddControl("ComboBox", { Label = "Memory model", Options = { ["128K"] = {wire_gpu_memorymodel = "128k"}, ["128K chip"] = {wire_gpu_memorymodel = "128kc"}, ["256K"] = {wire_gpu_memorymodel = "256k"}, ["256K chip"] = {wire_gpu_memorymodel = "256kc"}, ["512K"] = {wire_gpu_memorymodel = "512k"}, ["512K chip"] = {wire_gpu_memorymodel = "512kc"}, ["1024K"] = {wire_gpu_memorymodel = "1024k"}, ["1024K chip"] = {wire_gpu_memorymodel = "1024kc"}, ["2048K"] = {wire_gpu_memorymodel = "2048k"}, ["2048K chip"] = {wire_gpu_memorymodel = "2048kc"}, ["64K (compatibility mode)"] = {wire_gpu_memorymodel = "64k"}, ["64K chip"] = {wire_gpu_memorymodel = "64kc"}, } }) panel:AddControl("Label", {Text = "Memory model selects GPU memory size and its operation mode"}) ---------------------------------------------------------------------------- -- panel:AddControl("Button", { -- Text = "ZGPU documentation (online)" -- }) -- panel:AddControl("Label", { -- Text = "Loads online GPU documentation and tutorials" -- }) end ------------------------------------------------------------------------------ -- Tool screen ------------------------------------------------------------------------------ function TOOL:DrawToolScreen(width, height) CPULib.RenderCPUTool(1,"ZGPU") end end
apache-2.0
jameshegarty/rigel
misc/compare/hist.lua
1
1504
require "comparecommon" if type(arg[2])~="string" then print("usage: hist.lua image.raw image.metadata.lua buckets") os.exit(1) end dataPtr, metadata, pixelCount = loadRigelImage(arg[1],arg[2]) -- build histogram local buckets = tonumber(arg[3]) --print("BUCKETS",buckets) local maxValue, minValue local sum = 0 local fractionalCount = 0 local maxFracBits = 0 local infcnt = 0 local nancnt = 0 for i=0,pixelCount-1 do local px = dataPtr[i] if px~=px then nancnt = nancnt+1 elseif px==(1/0) or px==(-1/0) then infcnt = infcnt+1 else sum = sum + px if maxValue==nil or px>maxValue then maxValue=px end if minValue==nil or px<minValue then minValue=px end if px~=math.floor(px) then fractionalCount = fractionalCount + 1 end local fracBits = 0 local fpx = px while fpx~=math.floor(fpx) do fracBits=fracBits+1; fpx = fpx*2 end if fracBits>maxFracBits then maxFracBits=fracBits end end end local function pct(x,y) return "("..tostring( math.ceil((x/y)*100)).."%)" end print("Max Value",maxValue) print("Min Value",minValue) print("SUM",sum) print("Pixel Count",pixelCount) print("# of non-integer pixels",fractionalCount,pct(fractionalCount,pixelCount)) print("Max Fractional Bits",maxFracBits) local maxabs = math.max( math.abs(maxValue), math.abs(minValue) ) print("Max Integer Bits", math.ceil(math.log(maxabs)/math.log(2)) ) print("INF Count:",infcnt,pct(infcnt,pixelCount)) print("NAN Count:",nancnt,pct(nancnt,pixelCount))
mit
notcake/wire
lua/entities/gmod_wire_egp/lib/init.lua
18
1289
EGP = {} -------------------------------------------------------- -- Include all other files -------------------------------------------------------- function EGP:Initialize() local Folder = "entities/gmod_wire_egp/lib/egplib/" local entries = file.Find( Folder .. "*.lua", "LUA") for _, entry in ipairs( entries ) do if (SERVER) then AddCSLuaFile( Folder .. entry ) end include( Folder .. entry ) end end EGP:Initialize() local EGP = EGP EGP.ConVars = {} EGP.ConVars.MaxObjects = CreateConVar( "wire_egp_max_objects", 300, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } ) EGP.ConVars.MaxPerSec = CreateConVar( "wire_egp_max_bytes_per_sec", 10000, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } ) -- Keep between 2500-40000 EGP.ConVars.MaxVertices = CreateConVar( "wire_egp_max_poly_vertices", 1024, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } ) EGP.ConVars.AllowEmitter = CreateConVar( "wire_egp_allow_emitter", 1, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } ) EGP.ConVars.AllowHUD = CreateConVar( "wire_egp_allow_hud", 1, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } ) EGP.ConVars.AllowScreen = CreateConVar( "wire_egp_allow_screen", 1, { FCVAR_NOTIFY, FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE } )
apache-2.0
ZeeBeast/AeiaOTS
data/spells/scripts/newspells/d250.lua
1
4755
-- SpellCreator generated. -- =============== COMBAT VARS =============== -- Areas/Combat for 0ms local combat0_Brush = createCombatObject() setCombatParam(combat0_Brush, COMBAT_PARAM_EFFECT, CONST_ME_POFF) setCombatParam(combat0_Brush, COMBAT_PARAM_TYPE, COMBAT_PHYSICALDAMAGE) setCombatArea(combat0_Brush,createCombatArea({{2}})) function getDmg_Brush(cid, level, maglevel) return (10)*-1,(20)*-1 end setCombatCallback(combat0_Brush, CALLBACK_PARAM_LEVELMAGICVALUE, "getDmg_Brush") local con___combat0_Brush = createConditionObject(0+CONDITION_PARALYZE) setCombatCondition(combat0_Brush, con___combat0_Brush)local combat0_Brush_2 = createCombatObject() setCombatParam(combat0_Brush_2, COMBAT_PARAM_EFFECT, CONST_ME_SOUND_WHITE) setCombatParam(combat0_Brush_2, COMBAT_PARAM_TYPE, COMBAT_PHYSICALDAMAGE) setCombatArea(combat0_Brush_2,createCombatArea({{1, 1, 1}, {1, 2, 1}, {1, 1, 1}})) function getDmg_Brush_2(cid, level, maglevel) return (maglevel*20)*-1,(maglevel*70)*-1 end setCombatCallback(combat0_Brush_2, CALLBACK_PARAM_LEVELMAGICVALUE, "getDmg_Brush_2") -- Areas/Combat for 200ms local combat2_Brush = createCombatObject() setCombatParam(combat2_Brush, COMBAT_PARAM_EFFECT, CONST_ME_POFF) setCombatParam(combat2_Brush, COMBAT_PARAM_TYPE, COMBAT_PHYSICALDAMAGE) setCombatArea(combat2_Brush,createCombatArea({{2}})) function getDmg_Brush(cid, level, maglevel) return (10)*-1,(20)*-1 end setCombatCallback(combat2_Brush, CALLBACK_PARAM_LEVELMAGICVALUE, "getDmg_Brush") local con___combat2_Brush = createConditionObject(0+CONDITION_PARALYZE) setCombatCondition(combat2_Brush, con___combat2_Brush)local combat2_Brush_2 = createCombatObject() setCombatParam(combat2_Brush_2, COMBAT_PARAM_EFFECT, CONST_ME_SOUND_WHITE) setCombatParam(combat2_Brush_2, COMBAT_PARAM_TYPE, COMBAT_PHYSICALDAMAGE) setCombatArea(combat2_Brush_2,createCombatArea({{1, 1, 1, 1, 1}, {1, 0, 0, 0, 1}, {1, 0, 2, 0, 1}, {1, 0, 0, 0, 1}, {1, 1, 1, 1, 1}})) function getDmg_Brush_2(cid, level, maglevel) return (maglevel*20)*-1,(maglevel*70)*-1 end setCombatCallback(combat2_Brush_2, CALLBACK_PARAM_LEVELMAGICVALUE, "getDmg_Brush_2") -- Areas/Combat for 400ms local combat4_Brush = createCombatObject() setCombatParam(combat4_Brush, COMBAT_PARAM_EFFECT, CONST_ME_POFF) setCombatParam(combat4_Brush, COMBAT_PARAM_TYPE, COMBAT_PHYSICALDAMAGE) setCombatArea(combat4_Brush,createCombatArea({{2}})) function getDmg_Brush(cid, level, maglevel) return (10)*-1,(20)*-1 end setCombatCallback(combat4_Brush, CALLBACK_PARAM_LEVELMAGICVALUE, "getDmg_Brush") local con___combat4_Brush = createConditionObject(0+CONDITION_PARALYZE) setCombatCondition(combat4_Brush, con___combat4_Brush)local combat4_Brush_2 = createCombatObject() setCombatParam(combat4_Brush_2, COMBAT_PARAM_EFFECT, CONST_ME_SOUND_WHITE) setCombatParam(combat4_Brush_2, COMBAT_PARAM_TYPE, COMBAT_PHYSICALDAMAGE) setCombatArea(combat4_Brush_2,createCombatArea({{1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 0, 0, 1, 1}, {1, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 2, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1}})) function getDmg_Brush_2(cid, level, maglevel) return (maglevel*20)*-1,(maglevel*70)*-1 end setCombatCallback(combat4_Brush_2, CALLBACK_PARAM_LEVELMAGICVALUE, "getDmg_Brush_2") -- Areas/Combat for 500ms local combat5_Brush_2 = createCombatObject() setCombatParam(combat5_Brush_2, COMBAT_PARAM_EFFECT, CONST_ME_SOUND_WHITE) setCombatParam(combat5_Brush_2, COMBAT_PARAM_TYPE, COMBAT_PHYSICALDAMAGE) setCombatArea(combat5_Brush_2,createCombatArea({{1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 2, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 0, 0, 0, 0, 0, 0, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1}})) function getDmg_Brush_2(cid, level, maglevel) return (maglevel*20)*-1,(maglevel*70)*-1 end setCombatCallback(combat5_Brush_2, CALLBACK_PARAM_LEVELMAGICVALUE, "getDmg_Brush_2") -- =============== CORE FUNCTIONS =============== local function RunPart(c,cid,var,dirList,dirEmitPos) -- Part if (isCreature(cid)) then doCombat(cid, c, var) if (dirList ~= nil) then -- Emit distance effects local i = 2; while (i < #dirList) do doSendDistanceShoot(dirEmitPos,{x=dirEmitPos.x-dirList[i],y=dirEmitPos.y-dirList[i+1],z=dirEmitPos.z},dirList[1]) i = i + 2 end end end end function onCastSpell(cid, var) local startPos = getCreaturePosition(cid) RunPart(combat0_Brush,cid,var) RunPart(combat0_Brush_2,cid,var) addEvent(RunPart,200,combat2_Brush,cid,var) addEvent(RunPart,200,combat2_Brush_2,cid,var) addEvent(RunPart,400,combat4_Brush,cid,var) addEvent(RunPart,400,combat4_Brush_2,cid,var) addEvent(RunPart,500,combat5_Brush_2,cid,var) return true end
agpl-3.0
mobinantispam/botuzz
plugins/gnuplot.lua
622
1813
--[[ * Gnuplot plugin by psykomantis * dependencies: * - gnuplot 5.00 * - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html * ]] -- Gnuplot needs absolute path for the plot, so i run some commands to find where we are local outputFile = io.popen("pwd","r") io.input(outputFile) local _pwd = io.read("*line") io.close(outputFile) local _absolutePlotPath = _pwd .. "/data/plot.png" local _scriptPath = "./data/gnuplotScript.gpl" do local function gnuplot(msg, fun) local receiver = get_receiver(msg) -- We generate the plot commands local formattedString = [[ set grid set terminal png set output "]] .. _absolutePlotPath .. [[" plot ]] .. fun local file = io.open(_scriptPath,"w"); file:write(formattedString) file:close() os.execute("gnuplot " .. _scriptPath) os.remove (_scriptPath) return _send_photo(receiver, _absolutePlotPath) end -- Check all dependencies before executing local function checkDependencies() local status = os.execute("gnuplot -h") if(status==true) then status = os.execute("gnuplot -e 'set terminal png'") if(status == true) then return 0 -- OK ready to go! else return 1 -- missing libgd2-xpm-dev end else return 2 -- missing gnuplot end end local function run(msg, matches) local status = checkDependencies() if(status == 0) then return gnuplot(msg,matches[1]) elseif(status == 1) then return "It seems that this bot miss a dependency :/" else return "It seems that this bot doesn't have gnuplot :/" end end return { description = "use gnuplot through telegram, only plot single variable function", usage = "!gnuplot [single variable function]", patterns = {"^!gnuplot (.+)$"}, run = run } end
gpl-2.0
m13790115/selfi
plugins/google.lua
3
1060
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="" for key,val in ipairs(results) do stringresults=stringresults..val[1].." - "..val[2].."\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searches Google and send results", usage = "!google [terms]: Searches Google and send results", patterns = { "^!google (.*)$", "^!سرچ (.*)$", "^%.[g|G]oogle (.*)$" }, run = run }
gpl-2.0
mobinantispam/botuzz
plugins/quotes.lua
651
1630
local quotes_file = './data/quotes.lua' local quotes_table function read_quotes_file() local f = io.open(quotes_file, "r+") if f == nil then print ('Created a new quotes file on '..quotes_file) serialize_to_file({}, quotes_file) else print ('Quotes loaded: '..quotes_file) f:close() end return loadfile (quotes_file)() end function save_quote(msg) local to_id = tostring(msg.to.id) if msg.text:sub(11):isempty() then return "Usage: !addquote quote" end if quotes_table == nil then quotes_table = {} end if quotes_table[to_id] == nil then print ('New quote key to_id: '..to_id) quotes_table[to_id] = {} end local quotes = quotes_table[to_id] quotes[#quotes+1] = msg.text:sub(11) serialize_to_file(quotes_table, quotes_file) return "done!" end function get_quote(msg) local to_id = tostring(msg.to.id) local quotes_phrases quotes_table = read_quotes_file() quotes_phrases = quotes_table[to_id] return quotes_phrases[math.random(1,#quotes_phrases)] end function run(msg, matches) if string.match(msg.text, "!quote$") then return get_quote(msg) elseif string.match(msg.text, "!addquote (.+)$") then quotes_table = read_quotes_file() return save_quote(msg) end end return { description = "Save quote", description = "Quote plugin, you can create and retrieve random quotes", usage = { "!addquote [msg]", "!quote", }, patterns = { "^!addquote (.+)$", "^!quote$", }, run = run }
gpl-2.0
ga526321/prat
modules/ChannelSticky.lua
2
11429
--------------------------------------------------------------------------------- -- -- Prat - A framework for World of Warcraft chat mods -- -- Copyright (C) 2006-2007 Prat Development Team -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to: -- -- Free Software Foundation, Inc., -- 51 Franklin Street, Fifth Floor, -- Boston, MA 02110-1301, USA. -- -- ------------------------------------------------------------------------------- --[[ Name: PratChannelSticky Revision: $Revision: 80710 $ Author(s): Curney (asml8ed@gmail.com) Krtek (krtek4@gmail.com) Sylvanaar (sylvanaar@mindspring.com) Inspired by: idChat2_StickyChannels by Industrial Website: http://www.wowace.com/files/index.php?path=Prat/ Documentation: http://www.wowace.com/wiki/Prat/Integrated_Modules#ChannelSticky Subversion: http://svn.wowace.com/wowace/trunk/Prat/ Discussions: http://groups.google.com/group/wow-prat Issues and feature requests: http://code.google.com/p/prat/issues/list Description: Module for Prat that toggles sticky of different chat channel types on and off (default=on). Dependencies: Prat ]] Prat:AddModuleToLoad(function() local PRAT_MODULE = Prat:RequestModuleName("ChannelSticky") if PRAT_MODULE == nil then return end local L = Prat:GetLocalizer({}) --@debug@ L:AddLocale("enUS", { ["ChannelSticky"] = true, ["Chat channel sticky options."] = true, ["ChatType"] = true, ["Per chat type options."] = true, ["Channel"] = true, ["Sticky %s"] = true, ["Toggles sticky on and off for %s."] = true, ["smartgroup_name"] = "Smart Groups", ["smartgroup_desc"] = "Adds a /gr command which automatically picks the correct type of chat, RAID, PARTY, or BATTLEGROUND", ["Sticky Per Chat Frame"] = true, ["Toggle remembering the chat type last used per chat frame."] = true, }) --@end-debug@ -- These Localizations are auto-generated. To help with localization -- please go to http://www.wowace.com/projects/prat-3-0/localization/ --[===[@non-debug@ L:AddLocale("enUS", --@localization(locale="enUS", format="lua_table", same-key-is-true=true, namespace="ChannelSticky")@ ) L:AddLocale("frFR", --@localization(locale="frFR", format="lua_table", same-key-is-true=true, namespace="ChannelSticky")@ ) L:AddLocale("deDE", --@localization(locale="deDE", format="lua_table", same-key-is-true=true, namespace="ChannelSticky")@ ) L:AddLocale("koKR", --@localization(locale="koKR", format="lua_table", same-key-is-true=true, namespace="ChannelSticky")@ ) L:AddLocale("esMX", --@localization(locale="esMX", format="lua_table", same-key-is-true=true, namespace="ChannelSticky")@ ) L:AddLocale("ruRU", --@localization(locale="ruRU", format="lua_table", same-key-is-true=true, namespace="ChannelSticky")@ ) L:AddLocale("zhCN", --@localization(locale="zhCN", format="lua_table", same-key-is-true=true, namespace="ChannelSticky")@ ) L:AddLocale("esES", --@localization(locale="esES", format="lua_table", same-key-is-true=true, namespace="ChannelSticky")@ ) L:AddLocale("zhTW", --@localization(locale="zhTW", format="lua_table", same-key-is-true=true, namespace="ChannelSticky")@ ) --@end-non-debug@]===] -- chat channel list local chatList = { "SAY", "WHISPER", "YELL", "PARTY", "GUILD", "OFFICER", "RAID", "RAID_WARNING", "BATTLEGROUND", "CHANNEL", "EMOTE", } local module = Prat:NewModule(PRAT_MODULE, "AceEvent-3.0", "AceTimer-3.0", "AceHook-3.0") Prat:SetModuleDefaults(module, { profile = { on = true, say = true, whisper = true, yell = true, party = true, guild = true, officer = true, raid = true, raid_warning = true, battleground = true, channel = true, emote = true, perframe = false, smartgroup = false, } } ) local chatTypePlugins = { ctype = {} } Prat:SetModuleOptions(module, { name = L["ChannelSticky"], desc = L["Chat channel sticky options."], type = "group", plugins = chatTypePlugins, args = { perframe = { name = L["Sticky Per Chat Frame"], desc = L["Toggle remembering the chat type last used per chat frame."], type = "toggle", }, smartgroup = { name = L["smartgroup_name"], desc = L["smartgroup_desc"], type = "toggle", } } } ) --[[------------------------------------------------ Module Event Functions ------------------------------------------------]]-- function module:OnModuleEnable() self:BuildChannelList() self:RegisterEvent("UPDATE_CHAT_COLOR") local prof = self.db.profile -- sticky each channel based on db settings self:Stickum("SAY",prof.say) self:Stickum("WHISPER",prof.whisper) self:Stickum("YELL",prof.yell) self:Stickum("PARTY",prof.party) self:Stickum("GUILD",prof.guild) self:Stickum("OFFICER",prof.officer) self:Stickum("RAID",prof.raid) self:Stickum("RAID_WARNING",prof.raid_warning) self:Stickum("BATTLEGROUND",prof.battleground) self:Stickum("CHANNEL",prof.channel) self:Stickum("EMOTE",prof.emote) self:StickyFrameChan(prof.perframe) Prat.RegisterChatEvent(self, "Prat_OutboundChat") if prof.smartgroup then self:RegisterSmartGroup() end end function module:OnModuleDisable() -- dont sticky no mo! self:Stickum("SAY",false) self:Stickum("WHISPER",false) self:Stickum("YELL",false) self:Stickum("PARTY",false) self:Stickum("GUILD",false) self:Stickum("OFFICER",false) self:Stickum("RAID",false) self:Stickum("RAID_WARNING",false) self:Stickum("BATTLEGROUND",false) self:Stickum("CHANNEL",false) self:Stickum("EMOTE",false) -- forget about per chat frame stickying self:StickyFrameChan(false) -- unregister events self:UnregisterAllEvents() Prat.UnregisterAllChatEvents(self) end --[[------------------------------------------------ Core Functions ------------------------------------------------]]-- -- rebuild options menu is chat colors change function module:UPDATE_CHAT_COLOR() self:ScheduleTimer("BuildChannelList", 1) end function module:StickyFrameChan(enabled) if not enabled then self:UnhookAll() else self.perframe = {} self.perframechannum = {} self:RawHook("ChatFrame_OpenChat", true) self:SecureHook("ChatEdit_OnEscapePressed") self:SecureHook("SendChatMessage") self:SecureHook("ChatEdit_OnEnterPressed") end end function module:ChatFrame_OpenChat(text, chatFrame) if ( not chatFrame ) then chatFrame = SELECTED_CHAT_FRAME end local eb = chatFrame.editBox if eb == nil then return self.hooks["ChatFrame_OpenChat"](text, chatFrame) end local chatFrameN = chatFrame:GetName() --Prat.Print(eb:GetAttribute("chatType")) if eb:GetAttribute("chatType") == "WHISPER" then -- NADA -- elseif eb:GetAttribute("chatType") == "GROUPSAY" then -- eb:SetAttribute("origchatType", "GROUPSAY"); elseif self.perframe[chatFrameN] then eb:SetAttribute("channelTarget", self.perframechannum[chatFrameN]); eb:SetAttribute("chatType", self.perframe[chatFrameN]); eb:SetAttribute("stickyType", self.perframe[chatFrameN]); end self.hooks["ChatFrame_OpenChat"](text, chatFrame) end function module:SendChatMessage(msg, chatType, language, channel) if self.memoNext then self.perframe[self.memoNext] = chatType self.perframechannum[self.memoNext] = channel end end function module:ChatEdit_OnEscapePressed(this) self.memoNext = nil end function module:ChatEdit_OnEnterPressed(this) this = this or _G.this local chatFrameN = SELECTED_CHAT_FRAME:GetName() local chatType = this:GetAttribute("chatType") local channel = this:GetAttribute("channelTarget") self.perframe[chatFrameN] = chatType self.perframechannum[chatFrameN] = channel self.memoNext = nil end function module:Stickum(channel, stickied) ChatTypeInfo[channel:upper()].sticky = stickied and 1 or 0 end --[[------------------------------------------------ Menu Builder Functions ------------------------------------------------]]-- local CLR = Prat.CLR local function StkyChatType(text, type) return CLR:Colorize(module:GetChatCLR(type), text) end function module:BuildChannelList() local o = chatTypePlugins["ctype"] for _,va in ipairs(chatList) do local val = va:lower() local chan if va ~= "CHANNEL" then chan = TEXT(getglobal("CHAT_MSG_"..va)) else chan = L["Channel"] end o[val] = o[val] or { type = "toggle", } o[val].name = (L["Sticky %s"]):format(StkyChatType(chan:gsub(" ", ""), va)) o[val].desc = (L["Toggles sticky on and off for %s."]):format(chan) end end function module:OnValueChanged(info, b) local o = info[#info] if o == "smartgroup" then if b then self:RegisterSmartGroup() end elseif o == "perframe" then self:StickyFrameChan(b) else self:Stickum(o, b) end end function module:GetChatCLR(name) local info = ChatTypeInfo[name]; if not info then return CLR.COLOR_NONE end return CLR:GetHexColor(info) end function module:RegisterSmartGroup() if not self.smart_group then self:SecureHook("ChatEdit_SendText", function(this) if self.groupsay then this:SetAttribute("chatType", "GROUPSAY") self.groupsay=nil end end) self.smart_group = true SlashCmdList["SLASH_GROUPSAY"] = function(text) if text:trim():len() > 0 then local _,pvp = IsInInstance() if pvp == "pvp" then SendChatMessage(text, "BATTLEGROUND") elseif GetNumRaidMembers() > 0 then SendChatMessage(text, "RAID") elseif GetNumPartyMembers() > 0 then SendChatMessage(text, "PARTY") end end end SLASH_GROUPSAY1 = "/gr" SLASH_GROUPSAY2 = "/group" ChatTypeInfo["GROUPSAY"] = { r=0.5, g=0.9, b=0.9, sticky = 1 } CHAT_GROUPSAY_SEND = "SmartGroup:\32 " CHAT_GROUPSAY_GET = "SmartGroup: %1\32 " end end function module:SmartGroupChatType() local _,pvp = IsInInstance() if pvp == "pvp" then return "BATTLEGROUND" elseif GetNumRaidMembers() > 0 then return "RAID" elseif GetNumPartyMembers() > 0 then return "PARTY" end return "SAY" end function module:Prat_OutboundChat(arg, m) if m.CTYPE == "GROUPSAY" then self.groupsay = true m.CTYPE = self:SmartGroupChatType() end end return end ) -- Prat:AddModuleToLoad
gpl-3.0
maciek134/Logistics-Railway
stdlib/entity/entity.lua
5
3482
--- Entity module -- @module entity require 'stdlib/core' require 'stdlib/surface' require 'stdlib/area/area' Entity = {} --- Converts an entity and its selection_box to the area around it -- @param entity to convert to an area -- @return area that entity selection_box is valid for function Entity.to_selection_area(entity) fail_if_missing(entity, "missing entity argument") local pos = entity.position local bb = entity.prototype.selection_box return Area.offset(bb, pos) end --- Converts an entity and its selection_box to the area around it -- @param entity to convert to an area -- @return area that entity selection_box is valid for function Entity.to_collision_area(entity) fail_if_missing(entity, "missing entity argument") local pos = entity.position local bb = entity.prototype.collision_box return Area.offset(bb, pos) end --- Tests whether an entity has access to the field -- @param entity to test field access -- @param field_name that should be tested for -- @return true if the entity has access to the field, false if the entity threw an exception accessing the field function Entity.has(entity, field_name) fail_if_missing(entity, "missing entity argument") fail_if_missing(field_name, "missing field name argument") local status = pcall(function() return entity[field_name]; end) return status end --- Gets user data from the entity, stored in a mod's global data. --- <p> The data will persist between loads, and will be removed for an entity when it becomes invalid</p> -- @param entity the entity to look up data for -- @return the data, or nil if no data exists for the entity function Entity.get_data(entity) fail_if_missing(entity, "missing entity argument") if not global._entity_data then return nil end local entity_name = entity.name if not global._entity_data[entity_name] then return nil end local entity_category = global._entity_data[entity_name] for _, entity_data in pairs(entity_category) do if entity_data.entity == entity then return entity_data.data end end return nil end --- Sets user data on the entity, stored in a mod's global data. --- <p> The data will persist between loads, and will be removed for an entity when it becomes invalid</p> -- @param entity the entity to set data for -- @param data the data to set, or nil to delete the data associated with the entity -- @return the previous data associated with the entity, or nil if the entity had no previous data function Entity.set_data(entity, data) fail_if_missing(entity, "missing entity argument") if not global._entity_data then global._entity_data = {} end local entity_name = entity.name if not global._entity_data[entity_name] then global._entity_data[entity_name] = { pos_data = {}, data = {} } end local entity_category = global._entity_data[entity_name] for i = #entity_category, 1, -1 do local entity_data = entity_category[i] if not entity_data.entity.valid then table.remove(entity_category, i) end if entity_data.entity == entity then local prev = entity_data.data if data then entity_data.data = data else table.remove(entity_category, i) end return prev end end table.insert(entity_category, { entity = entity, data = data }) return nil end return Entity
mit
ahmedtaleb93/ahmed.t.h
plugins/addsudo.lua
6
1411
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY jOker ▀▄ ▄▀ ▀▄ ▄▀ BY joker (@fuck_8_you) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY joker ▀▄ ▄▀ ▀▄ ▄▀ broadcast : اضف مطور ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do local function callback(extra, success, result) vardump(success) vardump(result) end local function run(msg, matches) if matches[1] == 'add dev' then chat = 'chat#'..msg.to.id user1 = 'user#'..164118057 chat_add_user(chat, user1, callback, false) return "sudo added in tihs group" end if matches[1] == 'add dev' then chat = 'chat#'..msg.to.id user2 = 'user#'..164118057 chat_add_user(chat, user2, callback, false) return "sudo added in tihs group" end end return { description = "Invite Sudo and Admin", usage = { "/addsudo : invite Bot Sudo", }, patterns = { "^(اضف مطور)", "^(اضف مطور)", "^(add dev)", "^(add dev)", }, run = run, } end
gpl-3.0
aajjbb/lain
util/menu_iterator.lua
2
4997
--[[ Licensed under GNU General Public License v2 * (c) 2017, Simon Désaulniers <sim.desaulniers@gmail.com> * (c) 2017, Uli Schlachter * (c) 2017, Jeferson Siqueira <jefersonlsiq@gmail.com> --]] -- Menu iterator with Naughty notifications -- lain.util.menu_iterator local naughty = require("naughty") local helpers = require("lain.helpers") local atable = require("awful.util").table local assert = assert local pairs = pairs local tconcat = table.concat local unpack = unpack or table.unpack -- lua 5.1 retro-compatibility local state = { cid = nil } local function naughty_destroy_callback(reason) local closed = naughty.notificationClosedReason if reason == closed.expired or reason == closed.dismissedByUser then local actions = state.index and state.menu[state.index - 1][2] if actions then for _,action in pairs(actions) do -- don't try to call nil callbacks if action then action() end end state.index = nil end end end -- Iterates over a menu. -- After the timeout, callbacks associated to the last visited choice are -- executed. Inputs: -- * menu: a list of {label, {callbacks}} pairs -- * timeout: time to wait before confirming the menu selection -- * icon: icon to display in the notification of the chosen label local function iterate(menu, timeout, icon) timeout = timeout or 4 -- default timeout for each menu entry icon = icon or nil -- icon to display on the menu -- Build the list of choices if not state.index then state.menu = menu state.index = 1 end -- Select one and display the appropriate notification local label local next = state.menu[state.index] state.index = state.index + 1 if not next then label = "Cancel" state.index = nil else label, _ = unpack(next) end state.cid = naughty.notify({ text = label, icon = icon, timeout = timeout, screen = mouse.screen, replaces_id = state.cid, destroy = naughty_destroy_callback }).id end -- Generates a menu compatible with the first argument of `iterate` function and -- suitable for the following cases: -- * all possible choices individually (partition of singletons); -- * all possible subsets of the set of choices (powerset). -- -- Inputs: -- * args: an array containing the following members: -- * choices: Array of choices (string) on which the menu will be -- generated. -- * name: Displayed name of the menu (in the form "name: choices"). -- * selected_cb: Callback to execute for each selected choice. Takes -- the choice as a string argument. Can be `nil` (no action -- to execute). -- * rejected_cb: Callback to execute for each rejected choice (possible -- choices which are not selected). Takes the choice as a -- string argument. Can be `nil` (no action to execute). -- * extra_choices: An array of extra { choice_str, callback_fun } pairs to be -- added to the menu. Each callback_fun can be `nil`. -- * combination: The combination of choices to generate. Possible values: -- "powerset" and "single" (default). -- Output: -- * m: menu to be iterated over. local function menu(args) local choices = assert(args.choices or args[1]) local name = assert(args.name or args[2]) local selected_cb = args.selected_cb local rejected_cb = args.rejected_cb local extra_choices = args.extra_choices or {} local ch_combinations = args.combination == "powerset" and helpers.powerset(choices) or helpers.trivial_partition_set(choices) for _, c in pairs(extra_choices) do ch_combinations = atable.join(ch_combinations, {{c[1]}}) end local m = {} -- the menu for _,c in pairs(ch_combinations) do if #c > 0 then local cbs = {} -- selected choices for _,ch in pairs(c) do if atable.hasitem(choices, ch) then cbs[#cbs + 1] = selected_cb and function() selected_cb(ch) end or nil end end -- rejected choices for _,ch in pairs(choices) do if not atable.hasitem(c, ch) and atable.hasitem(choices, ch) then cbs[#cbs + 1] = rejected_cb and function() rejected_cb(ch) end or nil end end -- add user extra choices (like the choice "None" for example) for _,x in pairs(extra_choices) do if x[1] == c[1] then cbs[#cbs + 1] = x[2] end end m[#m + 1] = { name .. ": " .. tconcat(c, " + "), cbs } end end return m end return { iterate = iterate, menu = menu }
gpl-2.0
sjznxd/lc-20121230
modules/admin-mini/luasrc/model/cbi/mini/luci.lua
81
1335
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require "luci.config" local fs = require "nixio.fs" m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>.")) -- force reload of global luci config namespace to reflect the changes function m.commit_handler(self) package.loaded["luci.config"] = nil require "luci.config" end c = m:section(NamedSection, "main", "core", translate("General")) l = c:option(ListValue, "lang", translate("Language")) l:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then l:value(k, v) end end t = c:option(ListValue, "mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then t:value(v, k) end end return m
apache-2.0
gdevillele/dockercraft
world/Plugins/APIDump/Hooks/OnKilling.lua
36
1190
return { HOOK_KILLING = { CalledWhen = "A player or a mob is dying.", DefaultFnName = "OnKilling", -- also used as pagename Desc = [[ This hook is called whenever a {{cPawn|pawn}}'s (a player's or a mob's) health reaches zero. This means that the pawn is about to be killed, unless a plugin "revives" them by setting their health back to a positive value. ]], Params = { { Name = "Victim", Type = "{{cPawn}}", Notes = "The player or mob that is about to be killed" }, { Name = "Killer", Type = "{{cEntity}}", Notes = "The entity that has caused the victim to lose the last point of health. May be nil for environment damage" }, { Name = "TDI", Type = "{{TakeDamageInfo}}", Notes = "The damage type, cause and effects." }, }, Returns = [[ If the function returns false or no value, Cuberite calls other plugins with this event. If the function returns true, no other plugin is called for this event.</p> <p> In either case, the victim's health is then re-checked and if it is greater than zero, the victim is "revived" with that health amount. If the health is less or equal to zero, the victim is killed. ]], }, -- HOOK_KILLING }
apache-2.0
alirezaSO/cpumb
plugins/Dictionary.lua
58
1663
--[[ -- Translate text using Google Translate. -- http://translate.google.com/translate_a/single?client=t&ie=UTF-8&oe=UTF-8&hl=en&dt=t&tl=en&sl=auto&text=hello --]] do function translate(source_lang, target_lang, text) local path = "http://translate.google.com/translate_a/single" -- URL query parameters local params = { client = "t", ie = "UTF-8", oe = "UTF-8", hl = "en", dt = "t", tl = target_lang or "fa", sl = source_lang or "auto", text = URL.escape(text) } local query = format_http_params(params, true) local url = path..query local res, code = https.request(url) -- Return nil if error if code > 200 then return nil end local trans = res:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "") return trans end function run(msg, matches) -- Third pattern if #matches == 1 then print("First") local text = matches[1] return translate(nil, nil, text) end -- Second pattern if #matches == 2 then print("Second") local target = matches[1] local text = matches[2] return translate(nil, target, text) end -- First pattern if #matches == 3 then print("Third") local source = matches[1] local target = matches[2] local text = matches[3] return translate(source, target, text) end end return { description = "Translate Text, Default Persian", usage = { "/dic (txt) : translate txt en to fa", "/dic (lang) (txt) : translate en to other", "/dic (lang1,lang2) (txt) : translate lang1 to lang2", }, patterns = { "^[!/]dic ([%w]+),([%a]+) (.+)", "^[!/]dic ([%w]+) (.+)", "^[!/]dic (.+)", }, run = run } end
gpl-2.0
ibr773/TPBOT
plugins/kickall.lua
2
1742
--[[ _____ ____ ____ ___ _____ |_ _| _ \ | __ ) / _ \_ _| | | | |_) | | _ \| | | || | | | | __/ | |_) | |_| || | |_| |_| |____/ \___/ |_| KASPER TP (BY @kasper_dev) _ __ _ ____ ____ _____ ____ _____ ____ | |/ / / \ / ___|| _ \| ____| _ \ |_ _| _ \ | ' / / _ \ \___ \| |_) | _| | |_) | | | | |_) | | . \ / ___ \ ___) | __/| |___| _ < | | | __/ |_|\_\/_/ \_\____/|_| |_____|_| \_\ |_| |_| --]] local function kick_all(cb_extra, success, result) local receiver = cb_extra.receiver local msg = cb_extra.msg local deleted = 0 if success == 0 then send_large_msg(receiver, "للمطورين فقط :/") end for k,v in pairs(result) do kick_user(v.peer_id,msg.to.id) end send_large_msg(receiver, "دفرتهم الك :)") end local function run(msg, matches) if is_owner(msg) then local receiver = get_receiver(msg) channel_get_users(receiver, kick_all,{receiver = receiver, msg = msg}) end end return { patterns = { "^/(tp)$", "^(طرد الكل)$", }, run = run, } --[[ _____ ____ ____ ___ _____ |_ _| _ \ | __ ) / _ \_ _| | | | |_) | | _ \| | | || | | | | __/ | |_) | |_| || | |_| |_| |____/ \___/ |_| KASPER TP (BY @kasper_dev) _ __ _ ____ ____ _____ ____ _____ ____ | |/ / / \ / ___|| _ \| ____| _ \ |_ _| _ \ | ' / / _ \ \___ \| |_) | _| | |_) | | | | |_) | | . \ / ___ \ ___) | __/| |___| _ < | | | __/ |_|\_\/_/ \_\____/|_| |_____|_| \_\ |_| |_| --]]
gpl-2.0
Bobbyjoness/Ben10Game
conf.lua
1
3451
function love.conf(t) t.identity = "Ben10Game" -- The name of the save directory (string) t.version = "0.10.1" -- The LÖVE version this game was made for (string) t.console = false -- Attach a console (boolean, Windows only) t.accelerometerjoystick = true -- Enable the accelerometer on iOS and Android by exposing it as a Joystick (boolean) t.gammacorrect = false -- Enable gamma-correct rendering, when supported by the system (boolean) t.internalStorage = false t.window.title = "Untitled" -- The window title (string) t.window.icon = nil -- Filepath to an image to use as the window's icon (string) t.window.width = 800 -- The window width (number) t.window.height = 600 -- The window height (number) t.window.borderless = false -- Remove all border visuals from the window (boolean) t.window.resizable = false -- Let the window be user-resizable (boolean) t.window.minwidth = 1 -- Minimum window width if the window is resizable (number) t.window.minheight = 1 -- Minimum window height if the window is resizable (number) t.window.fullscreen = false -- Enable fullscreen (boolean) t.window.fullscreentype = "desktop" -- Choose between "desktop" fullscreen or "exclusive" fullscreen mode (string) t.window.vsync = false -- Enable vertical sync (boolean) t.window.msaa = 4 -- The number of samples to use with multi-sampled antialiasing (number) t.window.display = 1 -- Index of the monitor to show the window in (number) t.window.highdpi = false -- Enable high-dpi mode for the window on a Retina display (boolean) t.window.x = nil -- The x-coordinate of the window's position in the specified display (number) t.window.y = nil -- The y-coordinate of the window's position in the specified display (number) t.modules.audio = true -- Enable the audio module (boolean) t.modules.event = true -- Enable the event module (boolean) t.modules.graphics = true -- Enable the graphics module (boolean) t.modules.image = true -- Enable the image module (boolean) t.modules.joystick = true -- Enable the joystick module (boolean) t.modules.keyboard = true -- Enable the keyboard module (boolean) t.modules.math = true -- Enable the math module (boolean) t.modules.mouse = true -- Enable the mouse module (boolean) t.modules.physics = true -- Enable the physics module (boolean) t.modules.sound = true -- Enable the sound module (boolean) t.modules.system = true -- Enable the system module (boolean) t.modules.timer = true -- Enable the timer module (boolean), Disabling it will result 0 delta time in love.update t.modules.video = true -- Enable the video module (boolean) t.modules.window = true -- Enable the window module (boolean) t.modules.thread = true -- Enable the thread module (boolean) end -- Add folders to require search path love.filesystem.setRequirePath(love.filesystem.getRequirePath().. ";libs/?.lua;libs/?/init.lua") io.stdout:setvbuf("no")
mit
LazyZhu/openwrt-luci-trunk-mod
applications/luci-app-radicale/luasrc/model/cbi/radicale.lua
39
27698
-- Copyright 2015 Christian Schoenebeck <christian dot schoenebeck at gmail dot com> -- Licensed under the Apache License, Version 2.0 local NXFS = require("nixio.fs") local DISP = require("luci.dispatcher") local DTYP = require("luci.cbi.datatypes") local HTTP = require("luci.http") local UTIL = require("luci.util") local UCI = require("luci.model.uci") local SYS = require("luci.sys") local TOOLS = require("luci.controller.radicale") -- this application's controller and multiused functions -- ################################################################################################# -- takeover arguments if any -- ################################################ -- then show/edit selected file if arg[1] then local argument = arg[1] local filename = "" -- SimpleForm ------------------------------------------------ local ft = SimpleForm("_text") ft.title = TOOLS.app_title_back() ft.description = TOOLS.app_description() ft.redirect = DISP.build_url("admin", "services", "radicale") .. "#cbi-radicale-" .. argument if argument == "logger" then ft.reset = false ft.submit = translate("Reload") local uci = UCI.cursor() filename = uci:get("radicale", "logger", "file_path") or "/var/log/radicale" uci:unload("radicale") filename = filename .. "/radicale" elseif argument == "auth" then ft.submit = translate("Save") filename = "/etc/radicale/users" elseif argument == "rights" then ft.submit = translate("Save") filename = "/etc/radicale/rights" else error("Invalid argument given as section") end if argument ~= "logger" and not NXFS.access(filename) then NXFS.writefile(filename, "") end -- SimpleSection --------------------------------------------- local fs = ft:section(SimpleSection) if argument == "logger" then fs.title = translate("Log-file Viewer") fs.description = translate("Please press [Reload] button below to reread the file.") elseif argument == "auth" then fs.title = translate("Authentication") fs.description = translate("Place here the 'user:password' pairs for your users which should have access to Radicale.") .. [[<br /><strong>]] .. translate("Keep in mind to use the correct hashing algorithm !") .. [[</strong>]] else -- rights fs.title = translate("Rights") fs.description = translate("Authentication login is matched against the 'user' key, " .. "and collection's path is matched against the 'collection' key.") .. " " .. translate("You can use Python's ConfigParser interpolation values %(login)s and %(path)s.") .. " " .. translate("You can also get groups from the user regex in the collection with {0}, {1}, etc.") .. [[<br />]] .. translate("For example, for the 'user' key, '.+' means 'authenticated user'" .. " " .. "and '.*' means 'anybody' (including anonymous users).") .. [[<br />]] .. translate("Section names are only used for naming the rule.") .. [[<br />]] .. translate("Leading or ending slashes are trimmed from collection's path.") end -- TextValue ------------------------------------------------- local tt = fs:option(TextValue, "_textvalue") tt.rmempty = true if argument == "logger" then tt.readonly = true tt.rows = 30 function tt.write() HTTP.redirect(DISP.build_url("admin", "services", "radicale", "edit", argument)) end else tt.rows = 15 function tt.write(self, section, value) if not value then value = "" end NXFS.writefile(filename, value:gsub("\r\n", "\n")) return true --HTTP.redirect(DISP.build_url("admin", "services", "radicale", "edit") .. "#cbi-radicale-" .. argument) end end function tt.cfgvalue() return NXFS.readfile(filename) or string.format(translate("File '%s' not found !"), filename) end return ft end -- ################################################################################################# -- Error handling if not installed or wrong version -- ######################### if not TOOLS.service_ok() then local f = SimpleForm("_no_config") f.title = TOOLS.app_title_main() f.description = TOOLS.app_description() f.submit = false f.reset = false local s = f:section(SimpleSection) local v = s:option(DummyValue, "_update_needed") v.rawhtml = true if TOOLS.service_installed() == "0" then v.value = [[<h3><strong><br /><font color="red">&nbsp;&nbsp;&nbsp;&nbsp;]] .. translate("Software package '" .. TOOLS.service_name() .. "' is not installed.") .. [[</font><br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;]] .. translate("required") .. [[: ]] .. TOOLS.service_name() .. [[ ]] .. TOOLS.service_required() .. [[<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;]] .. [[<a href="]] .. DISP.build_url("admin", "system", "packages") ..[[">]] .. translate("Please install current version !") .. [[</a><br />&nbsp;</strong></h3>]] else v.value = [[<h3><strong><br /><font color="red">&nbsp;&nbsp;&nbsp;&nbsp;]] .. translate("Software package '" .. TOOLS.service_name() .. "' is outdated.") .. [[</font><br /><br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;]] .. translate("installed") .. [[: ]] .. TOOLS.service_name() .. [[ ]] .. TOOLS.service_installed() .. [[<br />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;]] .. translate("required") .. [[: ]] .. TOOLS.service_name() .. [[ ]] .. TOOLS.service_required() .. [[<br /><br />&nbsp;&nbsp;&nbsp;&nbsp;]] .. [[<a href="]] .. DISP.build_url("admin", "system", "packages") ..[[">]] .. translate("Please update to current version !") .. [[</a><br />&nbsp;</strong></h3>]] end return f end -- ################################################################################################# -- Error handling if no config, create an empty one -- ######################### if not NXFS.access("/etc/config/radicale") then NXFS.writefile("/etc/config/radicale", "") end -- cbi-map -- ################################################################## local m = Map("radicale") m.title = TOOLS.app_title_main() m.description = TOOLS.app_description() function m.commit_handler(self) if self.changed then -- changes ? os.execute("/etc/init.d/radicale reload &") -- reload configuration end end -- cbi-section "System" -- ##################################################### local sys = m:section( NamedSection, "_system" ) sys.title = translate("System") sys.description = nil function sys.cfgvalue(self, section) return "_dummysection" end -- start/stop button ----------------------------------------------------------- local btn = sys:option(DummyValue, "_startstop") btn.template = "radicale/btn_startstop" btn.inputstyle = nil btn.rmempty = true btn.title = translate("Start / Stop") btn.description = translate("Start/Stop Radicale server") function btn.cfgvalue(self, section) local pid = TOOLS.get_pid(true) if pid > 0 then btn.inputtitle = "PID: " .. pid btn.inputstyle = "reset" btn.disabled = false else btn.inputtitle = translate("Start") btn.inputstyle = "apply" btn.disabled = false end return true end -- enabled --------------------------------------------------------------------- local ena = sys:option(Flag, "_enabled") ena.title = translate("Auto-start") ena.description = translate("Enable/Disable auto-start of Radicale on system start-up and interface events") ena.orientation = "horizontal" -- put description under the checkbox ena.rmempty = false -- we need write function ena.cfgvalue(self, section) return (SYS.init.enabled("radicale")) and "1" or "0" end function ena.write(self, section, value) if value == "1" then return SYS.init.enable("radicale") else return SYS.init.disable("radicale") end end -- cbi-section "Server" -- ##################################################### local srv = m:section( NamedSection, "server", "setting" ) srv.title = translate("Server") srv.description = nil function srv.cfgvalue(self, section) if not self.map:get(section) then -- section might not exist self.map:set(section, nil, self.sectiontype) end return self.map:get(section) end -- hosts ----------------------------------------------------------------------- local sh = srv:option( DynamicList, "hosts" ) sh.title = translate("Address:Port") sh.description = translate("'Hostname:Port' or 'IPv4:Port' or '[IPv6]:Port' Radicale should listen on") .. [[<br /><strong>]] .. translate("Port numbers below 1024 (Privileged ports) are not supported") .. [[</strong>]] sh.placeholder = "0.0.0.0:5232" sh.rmempty = true -- realm ----------------------------------------------------------------------- local alm = srv:option( Value, "realm" ) alm.title = translate("Logon message") alm.description = translate("Message displayed in the client when a password is needed.") alm.default = "Radicale - Password Required" alm.rmempty = false function alm.parse(self, section) AbstractValue.parse(self, section, "true") -- otherwise unspecific validate error end function alm.validate(self, value) if value then return value else return self.default end end function alm.write(self, section, value) if value ~= self.default then return self.map:set(section, self.option, value) else return self.map:del(section, self.option) end end -- ssl ------------------------------------------------------------------------- local ssl = srv:option( Flag, "ssl" ) ssl.title = translate("Enable HTTPS") ssl.description = nil ssl.rmempty = false function ssl.parse(self, section) TOOLS.flag_parse(self, section) end function ssl.write(self, section, value) if value == "0" then -- delete all if not https enabled self.map:del(section, "protocol") -- protocol self.map:del(section, "certificate") -- certificate self.map:del(section, "key") -- private key self.map:del(section, "ciphers") -- ciphers return self.map:del(section, self.option) else return self.map:set(section, self.option, value) end end -- protocol -------------------------------------------------------------------- local prt = srv:option( ListValue, "protocol" ) prt.title = translate("SSL Protocol") prt.description = translate("'AUTO' selects the highest protocol version that client and server support.") prt.widget = "select" prt.default = "PROTOCOL_SSLv23" prt:depends ("ssl", "1") prt:value ("PROTOCOL_SSLv23", translate("AUTO")) prt:value ("PROTOCOL_SSLv2", "SSL v2") prt:value ("PROTOCOL_SSLv3", "SSL v3") prt:value ("PROTOCOL_TLSv1", "TLS v1") prt:value ("PROTOCOL_TLSv1_1", "TLS v1.1") prt:value ("PROTOCOL_TLSv1_2", "TLS v1.2") -- certificate ----------------------------------------------------------------- local crt = srv:option( Value, "certificate" ) crt.title = translate("Certificate file") crt.description = translate("Full path and file name of certificate") crt.placeholder = "/etc/radicale/ssl/server.crt" crt.rmempty = false -- force validate/write crt:depends ("ssl", "1") function crt.parse(self, section) local _ssl = ssl:formvalue(section) or "0" local novld = (_ssl == "0") AbstractValue.parse(self, section, novld) -- otherwise unspecific validate error end function crt.validate(self, value) local _ssl = ssl:formvalue(srv.section) or "0" if _ssl == "0" then return "" -- ignore if not https enabled end if value then -- otherwise errors in datatype check if DTYP.file(value) then return value else return nil, self.title .. " - " .. translate("File not found !") end else return nil, self.title .. " - " .. translate("Path/File required !") end end function crt.write(self, section, value) if not value or #value == 0 then return self.map:del(section, self.option) else return self.map:set(section, self.option, value) end end -- key ------------------------------------------------------------------------- local key = srv:option( Value, "key" ) key.title = translate("Private key file") key.description = translate("Full path and file name of private key") key.placeholder = "/etc/radicale/ssl/server.key" key.rmempty = false -- force validate/write key:depends ("ssl", "1") function key.parse(self, section) local _ssl = ssl:formvalue(section) or "0" local novld = (_ssl == "0") AbstractValue.parse(self, section, novld) -- otherwise unspecific validate error end function key.validate(self, value) local _ssl = ssl:formvalue(srv.section) or "0" if _ssl == "0" then return "" -- ignore if not https enabled end if value then -- otherwise errors in datatype check if DTYP.file(value) then return value else return nil, self.title .. " - " .. translate("File not found !") end else return nil, self.title .. " - " .. translate("Path/File required !") end end function key.write(self, section, value) if not value or #value == 0 then return self.map:del(section, self.option) else return self.map:set(section, self.option, value) end end -- ciphers --------------------------------------------------------------------- --local cip = srv:option( Value, "ciphers" ) --cip.title = translate("Ciphers") --cip.description = translate("OPTIONAL: See python's ssl module for available ciphers") --cip.rmempty = true --cip:depends ("ssl", "1") -- cbi-section "Authentication" -- ############################################# local aut = m:section( NamedSection, "auth", "setting" ) aut.title = translate("Authentication") aut.description = translate("Authentication method to allow access to Radicale server.") function aut.cfgvalue(self, section) if not self.map:get(section) then -- section might not exist self.map:set(section, nil, self.sectiontype) end return self.map:get(section) end -- type ----------------------------------------------------------------------- local aty = aut:option( ListValue, "type" ) aty.title = translate("Authentication method") aty.description = nil aty.widget = "select" aty.default = "None" aty:value ("None", translate("None")) aty:value ("htpasswd", translate("htpasswd file")) --aty:value ("IMAP", "IMAP") -- The IMAP authentication module relies on the imaplib module. --aty:value ("LDAP", "LDAP") -- The LDAP authentication module relies on the python-ldap module. --aty:value ("PAM", "PAM") -- The PAM authentication module relies on the python-pam module. --aty:value ("courier", "courier") --aty:value ("HTTP", "HTTP") -- The HTTP authentication module relies on the requests module --aty:value ("remote_user", "remote_user") --aty:value ("custom", translate("custom")) function aty.write(self, section, value) if value ~= "htpasswd" then self.map:del(section, "htpasswd_encryption") elseif value ~= "IMAP" then self.map:del(section, "imap_hostname") self.map:del(section, "imap_port") self.map:del(section, "imap_ssl") end if value ~= self.default then return self.map:set(section, self.option, value) else return self.map:del(section, self.option) end end -- htpasswd_encryption --------------------------------------------------------- local hte = aut:option( ListValue, "htpasswd_encryption" ) hte.title = translate("Encryption method") hte.description = nil hte.widget = "select" hte.default = "crypt" hte:depends ("type", "htpasswd") hte:value ("crypt", translate("crypt")) hte:value ("plain", translate("plain")) hte:value ("sha1", translate("SHA-1")) hte:value ("ssha", translate("salted SHA-1")) -- htpasswd_file (dummy) ------------------------------------------------------- local htf = aut:option( DummyValue, "_htf" ) htf.title = translate("htpasswd file") htf.description = [[<strong>]] .. translate("Read only!") .. [[</strong> ]] .. translate("Radicale uses '/etc/radicale/users' as htpasswd file.") .. [[<br /><a href="]] .. DISP.build_url("admin", "services", "radicale", "edit") .. [[/auth]] .. [[">]] .. translate("To edit the file follow this link!") .. [[</a>]] htf.keylist = {} -- required by template htf.vallist = {} -- required by template htf.template = "radicale/ro_value" htf.readonly = true htf:depends ("type", "htpasswd") function htf.cfgvalue() return "/etc/radicale/users" end -- cbi-section "Rights" -- ##################################################### local rig = m:section( NamedSection, "rights", "setting" ) rig.title = translate("Rights") rig.description = translate("Control the access to data collections.") function rig.cfgvalue(self, section) if not self.map:get(section) then -- section might not exist self.map:set(section, nil, self.sectiontype) end return self.map:get(section) end -- type ----------------------------------------------------------------------- local rty = rig:option( ListValue, "type" ) rty.title = translate("Rights backend") rty.description = nil rty.widget = "select" rty.default = "None" rty:value ("None", translate("Full access for everybody (including anonymous)")) rty:value ("authenticated", translate("Full access for authenticated Users") ) rty:value ("owner_only", translate("Full access for Owner only") ) rty:value ("owner_write", translate("Owner allow write, authenticated users allow read") ) rty:value ("from_file", translate("Rights are based on a regexp-based file") ) --rty:value ("custom", "Custom handler") function rty.write(self, section, value) if value ~= "custom" then self.map:del(section, "custom_handler") end if value ~= self.default then return self.map:set(section, self.option, value) else return self.map:del(section, self.option) end end -- from_file (dummy) ----------------------------------------------------------- local rtf = rig:option( DummyValue, "_rtf" ) rtf.title = translate("RegExp file") rtf.description = [[<strong>]] .. translate("Read only!") .. [[</strong> ]] .. translate("Radicale uses '/etc/radicale/rights' as regexp-based file.") .. [[<br /><a href="]] .. DISP.build_url("admin", "services", "radicale", "edit") .. [[/rights]] .. [[">]] .. translate("To edit the file follow this link!") .. [[</a>]] rtf.keylist = {} -- required by template rtf.vallist = {} -- required by template rtf.template = "radicale/ro_value" rtf.readonly = true rtf:depends ("type", "from_file") function rtf.cfgvalue() return "/etc/radicale/rights" end -- cbi-section "Storage" -- #################################################### local sto = m:section( NamedSection, "storage", "setting" ) sto.title = translate("Storage") sto.description = nil function sto.cfgvalue(self, section) if not self.map:get(section) then -- section might not exist self.map:set(section, nil, self.sectiontype) end return self.map:get(section) end -- type ----------------------------------------------------------------------- local sty = sto:option( ListValue, "type" ) sty.title = translate("Storage backend") sty.description = translate("WARNING: Only 'File-system' is documented and tested by Radicale development") sty.widget = "select" sty.default = "filesystem" sty:value ("filesystem", translate("File-system")) --sty:value ("multifilesystem", translate("") ) --sty:value ("database", translate("Database") ) --sty:value ("custom", translate("Custom") ) function sty.write(self, section, value) if value ~= "filesystem" then self.map:del(section, "filesystem_folder") end if value ~= self.default then return self.map:set(section, self.option, value) else return self.map:del(section, self.option) end end --filesystem_folder ------------------------------------------------------------ local sfi = sto:option( Value, "filesystem_folder" ) sfi.title = translate("Directory") sfi.description = nil sfi.default = "/srv/radicale" sfi.rmempty = false -- force validate/write sfi:depends ("type", "filesystem") function sfi.parse(self, section) local _typ = sty:formvalue(sto.section) or "" local novld = (_typ ~= "filesystem") AbstractValue.parse(self, section, novld) -- otherwise unspecific validate error end function sfi.validate(self, value) local _typ = sty:formvalue(sto.section) or "" if _typ ~= "filesystem" then return "" -- ignore if not htpasswd end if value then -- otherwise errors in datatype check if DTYP.directory(value) then return value else return nil, self.title .. " - " .. translate("Directory not exists/found !") end else return nil, self.title .. " - " .. translate("Directory required !") end end -- cbi-section "Logging" -- #################################################### local log = m:section( NamedSection, "logger", "logging" ) log.title = translate("Logging") log.description = nil function log.cfgvalue(self, section) if not self.map:get(section) then -- section might not exist self.map:set(section, nil, self.sectiontype) end return self.map:get(section) end -- console_level --------------------------------------------------------------- local lco = log:option( ListValue, "console_level" ) lco.title = translate("Console Log level") lco.description = nil lco.widget = "select" lco.default = "ERROR" lco:value ("DEBUG", translate("Debug")) lco:value ("INFO", translate("Info") ) lco:value ("WARNING", translate("Warning") ) lco:value ("ERROR", translate("Error") ) lco:value ("CRITICAL", translate("Critical") ) function lco.write(self, section, value) if value ~= self.default then return self.map:set(section, self.option, value) else return self.map:del(section, self.option) end end -- syslog_level ---------------------------------------------------------------- local lsl = log:option( ListValue, "syslog_level" ) lsl.title = translate("Syslog Log level") lsl.description = nil lsl.widget = "select" lsl.default = "WARNING" lsl:value ("DEBUG", translate("Debug")) lsl:value ("INFO", translate("Info") ) lsl:value ("WARNING", translate("Warning") ) lsl:value ("ERROR", translate("Error") ) lsl:value ("CRITICAL", translate("Critical") ) function lsl.write(self, section, value) if value ~= self.default then return self.map:set(section, self.option, value) else return self.map:del(section, self.option) end end -- file_level ------------------------------------------------------------------ local lfi = log:option( ListValue, "file_level" ) lfi.title = translate("File Log level") lfi.description = nil lfi.widget = "select" lfi.default = "INFO" lfi:value ("DEBUG", translate("Debug")) lfi:value ("INFO", translate("Info") ) lfi:value ("WARNING", translate("Warning") ) lfi:value ("ERROR", translate("Error") ) lfi:value ("CRITICAL", translate("Critical") ) function lfi.write(self, section, value) if value ~= self.default then return self.map:set(section, self.option, value) else return self.map:del(section, self.option) end end -- file_path ------------------------------------------------------------------- local lfp = log:option( Value, "file_path" ) lfp.title = translate("Log-file directory") lfp.description = translate("Directory where the rotating log-files are stored") .. [[<br /><a href="]] .. DISP.build_url("admin", "services", "radicale", "edit") .. [[/logger]] .. [[">]] .. translate("To view latest log file follow this link!") .. [[</a>]] lfp.default = "/var/log/radicale" function lfp.write(self, section, value) if value ~= self.default then return self.map:set(section, self.option, value) else return self.map:del(section, self.option) end end -- file_maxbytes --------------------------------------------------------------- local lmb = log:option( Value, "file_maxbytes" ) lmb.title = translate("Log-file size") lmb.description = translate("Maximum size of each rotation log-file.") .. [[<br /><strong>]] .. translate("Setting this parameter to '0' will disable rotation of log-file.") .. [[</strong>]] lmb.default = "8196" lmb.rmempty = false function lmb.validate(self, value) if value then -- otherwise errors in datatype check if DTYP.uinteger(value) then return value else return nil, self.title .. " - " .. translate("Value is not an Integer >= 0 !") end else return nil, self.title .. " - " .. translate("Value required ! Integer >= 0 !") end end function lmb.write(self, section, value) if value ~= self.default then return self.map:set(section, self.option, value) else return self.map:del(section, self.option) end end -- file_backupcount ------------------------------------------------------------ local lbc = log:option( Value, "file_backupcount" ) lbc.title = translate("Log-backup Count") lbc.description = translate("Number of backup files of log to create.") .. [[<br /><strong>]] .. translate("Setting this parameter to '0' will disable rotation of log-file.") .. [[</strong>]] lbc.default = "1" lbc.rmempty = false function lbc.validate(self, value) if value then -- otherwise errors in datatype check if DTYP.uinteger(value) then return value else return nil, self.title .. " - " .. translate("Value is not an Integer >= 0 !") end else return nil, self.title .. " - " .. translate("Value required ! Integer >= 0 !") end end function lbc.write(self, section, value) if value ~= self.default then return self.map:set(section, self.option, value) else return self.map:del(section, self.option) end end -- cbi-section "Encoding" -- ################################################### local enc = m:section( NamedSection, "encoding", "setting" ) enc.title = translate("Encoding") enc.description = translate("Change here the encoding Radicale will use instead of 'UTF-8' " .. "for responses to the client and/or to store data inside collections.") function enc.cfgvalue(self, section) if not self.map:get(section) then -- section might not exist self.map:set(section, nil, self.sectiontype) end return self.map:get(section) end -- request --------------------------------------------------------------------- local enr = enc:option( Value, "request" ) enr.title = translate("Response Encoding") enr.description = translate("Encoding for responding requests.") enr.default = "utf-8" enr.optional = true -- stock ----------------------------------------------------------------------- local ens = enc:option( Value, "stock" ) ens.title = translate("Storage Encoding") ens.description = translate("Encoding for storing local collections.") ens.default = "utf-8" ens.optional = true -- cbi-section "Headers" -- #################################################### local hea = m:section( NamedSection, "headers", "setting" ) hea.title = translate("Additional HTTP headers") hea.description = translate("Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts, JavaScript, etc.) " .. "on a web page to be requested from another domain outside the domain from which the resource originated.") function hea.cfgvalue(self, section) if not self.map:get(section) then -- section might not exist self.map:set(section, nil, self.sectiontype) end return self.map:get(section) end -- Access_Control_Allow_Origin ------------------------------------------------- local heo = hea:option( DynamicList, "Access_Control_Allow_Origin" ) heo.title = translate("Access-Control-Allow-Origin") heo.description = nil heo.default = "*" heo.optional = true -- Access_Control_Allow_Methods ------------------------------------------------ local hem = hea:option( DynamicList, "Access_Control_Allow_Methods" ) hem.title = translate("Access-Control-Allow-Methods") hem.description = nil hem.optional = true -- Access_Control_Allow_Headers ------------------------------------------------ local heh = hea:option( DynamicList, "Access_Control_Allow_Headers" ) heh.title = translate("Access-Control-Allow-Headers") heh.description = nil heh.optional = true -- Access_Control_Expose_Headers ----------------------------------------------- local hee = hea:option( DynamicList, "Access_Control_Expose_Headers" ) hee.title = translate("Access-Control-Expose-Headers") hee.description = nil hee.optional = true return m
apache-2.0
Sewerbird/Helios2400
src/AssetLoader.lua
1
5065
require "lib/Tserial" inspect = require 'lib/inspect' local anim8 = require "lib/anim8" local class = require 'lib/30log' local Sprite = require 'src/datatype/Sprite' local Animation = require 'src/datatype/Animation' local AssetLoader = class("AssetLoader", { assets = {}, specs = {}, rootPath = "", errorPrefix = "ERROR: " }) function AssetLoader:loadAssets(rootPath) self.rootPath = rootPath for i,v in ipairs(love.filesystem.getDirectoryItems(self.rootPath)) do if self.isAsset(v) then local filePath = self.rootPath .. v local file = love.filesystem.read(filePath) local asset = Tserial.unpack(file,false) self:loadAsset(asset) end end return self end function AssetLoader:loadAsset(asset) if(asset.assetId == nil) then error(self.errorPrefix .. " asset is missing assetId") return end if(asset.assetType == nil) then error(self.errorPrefix .. " asset is missing assetType") return end if self.assets[asset.assetId] ~= nil then error(self.errorPrefix.. "assetId " .. asset.assetId .. " is not unique") return end if asset.assetType == "gameData" then self:loadGameData(asset) return end if asset.assetType == "spriteSheet" then self:loadSpriteSheet(asset) return end if asset.assetType == "sprite" then self:loadSprite(asset) return end if asset.assetType == "audio" then self:loadAudio(asset) return end error(self.errorPrefix .. "incorrect asset type " .. asset.assetType " for " .. asset.assetId) end function AssetLoader:loadSpriteSheet(spriteSheet) self.assets[spriteSheet.assetId] = love.graphics.newImage(self.rootPath .. spriteSheet.assetPath) for i,asset in ipairs(spriteSheet.data) do if asset.assetType == "sprite" then self:loadSprite(asset,spriteSheet.assetId) elseif asset.assetType == "animation" then self:loadAnimation(asset,spriteSheet.assetId) else error(self.errorPrefix .. "incorrect asset type " .. asset.assetType " for " .. asset.assetId .. " in spritesheet " .. spriteSheet.assetId) end end end function AssetLoader:loadSprite(sprite,spriteSheetId) if(sprite.width == nil) then error(self.errorPrefix .. " sprite width is not defined for " .. sprite.assetId) return end if(sprite.height == nil) then error(self.errorPrefix .. " sprite height is not defined for " .. sprite.assetId) return end local spriteSheet = self:getAsset(spriteSheetId) self.assets[sprite.assetId] = Sprite:new( spriteSheet, love.graphics.newQuad( sprite.x or 0, sprite.y or 0, sprite.width, sprite.height, spriteSheet:getDimensions() ) ) end function AssetLoader:loadAnimation(animation,spriteSheetId) if(animation.frameWidth == nil) then error(self.errorPrefix .. " animation frameWidth is not defined for " .. animation.assetId) return end if(animation.frameHeight == nil) then error(self.errorPrefix .. " animation frameHeight is not defined for " .. animation.assetId) return end if(animation.amountOfFrames == nil) then error(self.errorPrefix .. " animation amountOfFrames is not defined for " .. animation.assetId) return end if(animation.frameTime == nil) then error(self.errorPrefix .. " animation frameTime is not defined for " .. animation.assetId) return end local spriteSheet = self:getAsset(spriteSheetId) local grid = anim8.newGrid(animation.frameWidth,animation.frameHeight,spriteSheet:getWidth(), spriteSheet:getHeight(), animation.x or 0, animation.y or 0) local anim = anim8.newAnimation(grid('1-'..animation.amountOfFrames, 1),{['1-'..animation.amountOfFrames]=animation.frameTime}) self.assets[animation.assetId] = Animation:new(anim, spriteSheet) end function AssetLoader:loadAudio(audio) self.assets[audio.assetId] = love.audio.newSource(self.rootPath .. audio.assetPath) end function AssetLoader:loadGameData(gamedatasheet) for i, datum in ipairs(gamedatasheet.data) do self.specs[datum.specId] = datum end end function AssetLoader.isAsset(String) return ".asset"=='' or string.sub(String,-string.len(".asset"))==".asset" or string.sub(String,-string.len(".spec"))==".spec" end function AssetLoader:getAsset(assetId) if self.assets[assetId] == nil then error(self.errorPrefix .. assetId .. " is not loaded or incorrect") end return self.assets[assetId] end local function copy(obj, seen) if type(obj) ~= 'table' then return obj end if seen and seen[obj] then return seen[obj] end local s = seen or {} local res = setmetatable({}, getmetatable(obj)) s[obj] = res for k, v in pairs(obj) do res[copy(k, s)] = copy(v, s) end return res end function AssetLoader:getSpec(specId) if self.specs[specId] == nil then error(self.errorPrefix .. specId .. " is not loaded or incorrect") end return copy(self.specs[specId]) end function AssetLoader:getAllPlayerUnitSpecs() local specs = {} for i, spec in pairs(self.specs) do if spec.available_to_players then table.insert(specs, copy(spec)) end end return specs end function AssetLoader:printAllAssets() print("Assets:") for k,v in pairs(self.assets) do print("\t- \"" .. k .. "\"",v) end end return AssetLoader
mit
LazyZhu/openwrt-luci-trunk-mod
modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/fstab/mount.lua
29
3928
-- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" local util = require "nixio.util" local has_fscheck = fs.access("/usr/sbin/e2fsck") local block = io.popen("block info", "r") local ln, dev, devices = nil, nil, {} repeat ln = block:read("*l") dev = ln and ln:match("^/dev/(.-):") if dev then local e, s, key, val = { } for key, val in ln:gmatch([[(%w+)="(.-)"]]) do e[key:lower()] = val end s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev))) e.dev = "/dev/%s" % dev e.size = s and math.floor(s / 2048) devices[#devices+1] = e end until not ln block:close() m = Map("fstab", translate("Mount Points - Mount Entry")) m.redirect = luci.dispatcher.build_url("admin/system/fstab") if not arg[1] or m.uci:get("fstab", arg[1]) ~= "mount" then luci.http.redirect(m.redirect) return end mount = m:section(NamedSection, arg[1], "mount", translate("Mount Entry")) mount.anonymous = true mount.addremove = false mount:tab("general", translate("General Settings")) mount:tab("advanced", translate("Advanced Settings")) mount:taboption("general", Flag, "enabled", translate("Enable this mount")).rmempty = false o = mount:taboption("general", Value, "uuid", translate("UUID"), translate("If specified, mount the device by its UUID instead of a fixed device node")) for i, d in ipairs(devices) do if d.uuid and d.size then o:value(d.uuid, "%s (%s, %d MB)" %{ d.uuid, d.dev, d.size }) elseif d.uuid then o:value(d.uuid, "%s (%s)" %{ d.uuid, d.dev }) end end o:value("", translate("-- match by label --")) o = mount:taboption("general", Value, "label", translate("Label"), translate("If specified, mount the device by the partition label instead of a fixed device node")) o:depends("uuid", "") for i, d in ipairs(devices) do if d.label and d.size then o:value(d.label, "%s (%s, %d MB)" %{ d.label, d.dev, d.size }) elseif d.label then o:value(d.label, "%s (%s)" %{ d.label, d.dev }) end end o:value("", translate("-- match by device --")) o = mount:taboption("general", Value, "device", translate("Device"), translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)")) o:depends({ uuid = "", label = "" }) for i, d in ipairs(devices) do if d.size then o:value(d.dev, "%s (%d MB)" %{ d.dev, d.size }) else o:value(d.dev) end end o = mount:taboption("general", Value, "target", translate("Mount point"), translate("Specifies the directory the device is attached to")) o:value("/", translate("Use as root filesystem (/)")) o:value("/overlay", translate("Use as external overlay (/overlay)")) o = mount:taboption("general", DummyValue, "__notice", translate("Root preparation")) o:depends("target", "/") o.rawhtml = true o.default = [[ <p>%s</p><pre>mkdir -p /tmp/introot mkdir -p /tmp/extroot mount --bind / /tmp/introot mount /dev/sda1 /tmp/extroot tar -C /tmp/intproot -cvf - . | tar -C /tmp/extroot -xf - umount /tmp/introot umount /tmp/extroot</pre> ]] %{ translate("Make sure to clone the root filesystem using something like the commands below:"), } o = mount:taboption("advanced", Value, "fstype", translate("Filesystem"), translate("The filesystem that was used to format the memory (<abbr title=\"for example\">e.g.</abbr> <samp><abbr title=\"Third Extended Filesystem\">ext3</abbr></samp>)")) o:value("", "auto") local fs for fs in io.lines("/proc/filesystems") do fs = fs:match("%S+") if fs ~= "nodev" then o:value(fs) end end o = mount:taboption("advanced", Value, "options", translate("Mount options"), translate("See \"mount\" manpage for details")) o.placeholder = "defaults" if has_fscheck then o = mount:taboption("advanced", Flag, "enabled_fsck", translate("Run filesystem check"), translate("Run a filesystem check before mounting the device")) end return m
apache-2.0
mraosee/AOSEE_H3
plugins/lock-bot.lua
1
2914
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY AOSEE ▀▄ ▄▀ ▀▄ ▄▀ BY AOSEE (@AOSEE_THT) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY AOSEE ▀▄ ▄▀ ▀▄ ▄▀ ANTI BOT : منع بوتات ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] local function isAntiBotEnabled (chatId) local hash = 'bot:lock:'..chatId local lock = redis:get(hash) return lock end local function enableAntiBot (chatId) local hash = 'bot:lock:'..chatId redis:set(hash, true) end local function disableAntiBot (chatId) local hash = 'bot:lock:'..chatId redis:del(hash) end local function isABot (user) local binFlagIsBot = 4096 local result = bit32.band(user.flags, binFlagIsBot) return result == binFlagIsBot end local function isABotBadWay (user) local username = user.username or '' return username:match("[Bb]ot$") end local function kickUser(userId, chatId) local channel = 'channel#id'..chatId local user = 'user#id'..userId channel_kick_user(channel, user, function (data, success, result) if success ~= 1 then print('I can\'t kick '..data.user..' but should be kicked') end end, {chat=chat, user=user}) end local function run (msg, matches) if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then if msg.to.type ~= 'chat' and msg.to.type ~= 'channel' then return nil end end local chatId = msg.to.id if matches[1] == 'قفل البوتات' then enableAntiBot(chatId) return 'تـمِ ✔️ قـفِلَ أضــأفهَ ألــبوَتَِــأت 🔐✋🏻' end if matches[1] == 'فتح البوتات' then disableAntiBot(chatId) return 'تـمِ ✔️ فَتـحَ أضــأفهَ ألــبوَتَِــأت 🔓👍' end if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then local user = msg.action.user or msg.from if isABotBadWay(user) then print("It' a bot!") if isAntiBotEnabled(chatId) then print('bot is locked') local userId = user.id if not isBotAllowed(userId, chatId) then kickUser(userId, chatId) else print('') end end end end end return { description = 'Anti bot create by Mustafa ip', usage = { '/bot lock: locked add bots to supergroup', '/bot unlock: unlock add bots to supergroup' }, patterns = { '^(قفل البوتات)$', '^(فتح البوتات)$', '^!!tgservice (chat_add_user)$', '^!!tgservice (chat_add_user_link)$' }, run = run }
gpl-2.0
sose12/AOS_SHARO56
plugins/getlink.lua
4
28101
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY faeder ▀▄ ▄▀ ▀▄ ▄▀ BY faeder (@xXxDev_iqxXx) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY faeder ▀▄ ▄▀ ▀▄ ▄▀ A SPECiAL LINK : الرابط خاص ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function 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 == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name if success == -1 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' then print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'rem' then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) end if matches[1] == 'chat_del_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end if matches[1] == 'newlink' then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'الرابط خاص' then if not is_momod(msg) then return "👌🏻لتلعَب بكَيفك فقَطَ المدير او الاداري يحَق لهَ✔️" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "❓يرجئ ارسال [/تغير الرابط] لانشاء رابط المجموعه👍🏻✔️" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") send_large_msg('user#id'..msg.from.id, "⁉️ رابط مجموعة 👥 "..msg.to.title..'\n'..group_link) return "تم ارسال الرابط الى الخاص 😚👍" end if matches[1] == 'setowner' then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'help' then if not is_momod(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end end return { patterns = { "^(الرابط خاص)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end -- arabic : @xXxDev_iqxXx
gpl-2.0
oskar456/packages
net/dynapoint/src/dynapoint.lua
20
6015
#!/usr/bin/lua --[[ Copyright (C) 2016 Tobias Ilte <tobias.ilte@campus.tu-berlin.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] require "uci" require "ubus" require "uloop" log = require "nixio" --open sys-logging log.openlog("DynaPoint", "ndelay", "cons", "nowait"); local uci_cursor = uci.cursor() -- get all config sections with the given type function getConfType(conf_file,type) local ifce={} uci_cursor:foreach(conf_file,type,function(s) ifce[s[".index"]]=s end) return ifce end ubus = ubus.connect() if not ubus then error("Failed to connect to ubusd") end ubus:call("network", "reload", {}) local interval = uci_cursor:get("dynapoint", "internet", "interval") local timeout = uci_cursor:get("dynapoint", "internet", "timeout") local offline_threshold = tonumber(uci_cursor:get("dynapoint", "internet", "offline_threshold")) local hosts = uci_cursor:get("dynapoint", "internet", "hosts") local numhosts = #hosts local curl = tonumber(uci_cursor:get("dynapoint", "internet", "use_curl")) if (curl == 1) then curl_interface = uci_cursor:get("dynapoint", "internet", "curl_interface") end if (tonumber(uci_cursor:get("dynapoint", "internet", "add_hostname_to_ssid")) == 1 ) then localhostname = uci_cursor:get("system", "system", "hostname") end local table_names_rule = {} local table_names_not_rule = {} local ssids_with_hostname = {} local ssids_not_rule = {} function get_dynapoint_sections(t) for pos,val in pairs(t) do if (type(val)=="table") then get_dynapoint_sections(val); elseif (type(val)=="string") then if (pos == "dynapoint_rule") then if (val == "internet") then table_names_rule[#table_names_rule+1] = t[".name"] elseif (val == "!internet") then table_names_not_rule[#table_names_not_rule+1] = t[".name"] if (localhostname) then ssids_not_rule[#ssids_not_rule+1] = t[".ssid"] ssids_with_hostname[#ssids_with_hostname+1] = t[".ssid"].."_"..localhostname end end end end end end --print(table.getn(hosts)) get_dynapoint_sections(getConfType("wireless","wifi-iface")) -- revert all non-persistent ssid uci-changes regarding sections affecting dynapoint for i = 1, #table_names_not_rule do uci_cursor:revert("wireless", table_names_not_rule[i], "ssid") end local online = true if (#table_names_rule > 0) then if (tonumber(uci_cursor:get("wireless", table_names_rule[1], "disabled")) == 1) then online = false end else log.syslog("info","Not properly configured. Please add <option dynapoint_rule 'internet'> to /etc/config/wireless") end local timer local offline_counter = 0 uloop.init() function do_internet_check(host) if (curl == 1 ) then if (curl_interface) then result = os.execute("curl -s -m "..timeout.." --max-redirs 0 --interface "..curl_interface.." --head "..host.." > /dev/null") else result = os.execute("curl -s -m "..timeout.." --max-redirs 0 --head "..host.." > /dev/null") end else result = os.execute("wget -q --timeout="..timeout.." --spider "..host) end if (result == 0) then return true else return false end end function change_wireless_config(switch_to_offline) if (switch_to_offline == 1) then log.syslog("info","Switched to OFFLINE") for i = 1, #table_names_not_rule do uci_cursor:set("wireless",table_names_not_rule[i], "disabled", "0") if (localhostname) then uci_cursor:set("wireless", table_names_not_rule[i], "ssid", ssids_with_hostname[i]) log.syslog("info","Bring up new AP "..ssids_with_hostname[i]) else log.syslog("info","Bring up new AP "..ssids_not_rule[i]) end end for i = 1, #table_names_rule do uci_cursor:set("wireless",table_names_rule[i], "disabled", "1") end else log.syslog("info","Switched to ONLINE") for i = 1, #table_names_not_rule do uci_cursor:set("wireless",table_names_not_rule[i], "disabled", "1") if (localhostname) then uci_cursor:set("wireless", table_names_not_rule[i], "ssid", ssids_not_rule[i]) end end for i = 1, #table_names_rule do uci_cursor:set("wireless",table_names_rule[i], "disabled", "0") log.syslog("info","Bring up new AP "..uci_cursor:get("wireless", table_names_rule[i], "ssid")) end end uci_cursor:save("wireless") ubus:call("network", "reload", {}) end local hostindex = 1 function check_internet_connection() print("checking "..hosts[hostindex].."...") if (do_internet_check(hosts[hostindex]) == true) then -- online print("...seems to be online") offline_counter = 0 hostindex = 1 if (online == false) then print("changed state to online") online = true change_wireless_config(0) end else --offline print("...seems to be offline") hostindex = hostindex + 1 if (hostindex <= numhosts) then check_internet_connection() else hostindex = 1 -- and activate offline-mode print("all hosts offline") if (online == true) then offline_counter = offline_counter + 1 if (offline_counter == offline_threshold) then print("changed state to offline") online = false change_wireless_config(1) end end end end timer:set(interval * 1000) end timer = uloop.timer(check_internet_connection) timer:set(interval * 1000) uloop.run()
gpl-2.0
Botnexxx/aryanalireza
plugins/inpm.lua
243
3007
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_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*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
PenguinToast/PenguinGUI
penguingui/HorizontalLayout.lua
1
1977
--- Lays out components horizontally. -- @classmod HorizontalLayout -- @usage -- -- Create a horizontal layout manager with padding of 2. -- local layout = HorizontalLayout(2) HorizontalLayout = class() --- Padding between contained components. HorizontalLayout.padding = nil --- Vertical alignment of contained components. -- Default center. HorizontalLayout.vAlignment = Align.CENTER --- Horizontal alignment of contained components. -- Default left. HorizontalLayout.hAlignment = Align.LEFT --- Constructor -- @section --- Constructs a HorizontalLayout. -- -- @param[opt=0] padding The padding between components within this layout. -- @param[opt=Align.LEFT] hAlign The horizontal alignment of the components. -- @param[opt=Align.CENTER] vAlign The vertical alignment of the components. function HorizontalLayout:_init(padding, hAlign, vAlign) self.padding = padding or 0 if hAlign then self.hAlignment = hAlign end if vAlign then self.vAlignment = vAlign end end --- @section end function HorizontalLayout:layout() local vAlign = self.vAlignment local hAlign = self.hAlignment local padding = self.padding local container = self.container local components = container.children local totalWidth = 0 for _,component in ipairs(components) do totalWidth = totalWidth + component.width end totalWidth = totalWidth + (#components - 1) * padding local startX if hAlign == Align.LEFT then startX = 0 elseif hAlign == Align.CENTER then startX = (container.width - totalWidth) / 2 else -- ALIGN_RIGHT startX = container.width - totalWidth end for _,component in ipairs(components) do component.x = startX if vAlign == Align.TOP then component.y = container.height - component.height elseif vAlign == Align.CENTER then component.y = (container.height - component.height) / 2 else -- ALIGN_BOTTOM component.y = 0 end startX = startX + component.width + padding end end
apache-2.0
gdevillele/dockercraft
world/Plugins/Core/spawn.lua
5
2174
function HandleSpawnCommand(Split, Player) local WorldIni = cIniFile() WorldIni:ReadFile(Player:GetWorld():GetIniFileName()) local SpawnX = WorldIni:GetValue("SpawnPosition", "X") local SpawnY = WorldIni:GetValue("SpawnPosition", "Y") local SpawnZ = WorldIni:GetValue("SpawnPosition", "Z") local flag = 0 if (#Split == 2 and Split[2] ~= Player:GetName()) then if Player:HasPermission("core.spawn.others") then local FoundPlayerCallback = function(OtherPlayer) if (OtherPlayer:GetName() == Split[2]) then World = OtherPlayer:GetWorld() local OnAllChunksAvaliable = function() OtherPlayer:TeleportToCoords(SpawnX, SpawnY, SpawnZ) SendMessageSuccess( Player, "Returned " .. OtherPlayer:GetName() .. " to world spawn" ) flag=1 end World:ChunkStay({{SpawnX/16, SpawnZ/16}}, OnChunkAvailable, OnAllChunksAvaliable) end end cRoot:Get():FindAndDoWithPlayer(Split[2], FoundPlayerCallback) if flag == 0 then SendMessageFailure( Player, "Player " .. Split[2] .. " not found!" ) end else SendMessageFailure( Player, "You need core.spawn.others permission to do that!" ) end else World = Player:GetWorld() local OnAllChunksAvaliable = function() Player:TeleportToCoords(SpawnX, SpawnY, SpawnZ) SendMessageSuccess( Player, "Returned to world spawn" ) end World:ChunkStay({{SpawnX/16, SpawnZ/16}}, OnChunkAvailable, OnAllChunksAvaliable) end return true end function HandleSetSpawnCommand(Split, Player) local WorldIni = cIniFile() WorldIni:ReadFile(Player:GetWorld():GetIniFileName()) local PlayerX = Player:GetPosX() local PlayerY = Player:GetPosY() local PlayerZ = Player:GetPosZ() WorldIni:DeleteValue("SpawnPosition", "X") WorldIni:DeleteValue("SpawnPosition", "Y") WorldIni:DeleteValue("SpawnPosition", "Z") WorldIni:SetValue("SpawnPosition", "X", PlayerX) WorldIni:SetValue("SpawnPosition", "Y", PlayerY) WorldIni:SetValue("SpawnPosition", "Z", PlayerZ) WorldIni:WriteFile(Player:GetWorld():GetIniFileName()) SendMessageSuccess( Player, string.format("Changed spawn position to [X:%i Y:%i Z:%i]", PlayerX, PlayerY, PlayerZ) ) return true end
apache-2.0
auntieNeo/asterisk-testsuite
tests/channels/SIP/handle_response_refer/test.lua
5
3276
require "watcher" function sipp_exec(scenario, name, host, port) host = host or "127.0.0.1" port = port or "5060" local inf = "data.csv" local p = proc.exec_io("sipp", "127.0.0.1", "-m", "1", "-sf", scenario, "-inf", "sipp/" .. inf, "-infindex", inf, "0", "-i", host, "-p", port, "-timeout", "30", "-timeout_error", "-set", "user", name, "-set", "file", inf ) posix.sleep(1) return p end function sipp_exec_and_wait(scenario, name, host, port) return sipp_check_error(sipp_exec(scenario, name, host, port), scenario) end function sipp_check_error(p, scenario) local res, err = p:wait() if not res then error(err) end if res ~= 0 then error("error while executing " .. scenario .. " sipp scenario (sipp exited with status " .. res .. ")\n" .. p.stderr:read("*a")) end return res, err end function mcheck(msg, res, err) check(msg, res, err) if res["Response"] ~= "Success" then error(msg .. " (got '" .. tostring(res["Response"]) .. "' expected 'Success'): " .. tostring(res["Message"])) end return res, err end function wait_for_event(m, result) local e = watcher.event.new("UserEvent") e["UserEvent"] = "TransferComplete" e["TRANSFERSTATUS"] = function(value) if result ~= value then print("Got '" .. value .. "' for TRANSFERSTATUS, expected '" .. result .. "'") return false end return true end local etree = watcher.etree:new(e) local res, err = check("error waiting for UserEvent", watcher.watch(m, etree, 10000)) end function do_call(scenario, key, result) local action = ast.manager.action local a = ast.new() a:load_config("configs/ast1/sip.conf") a:load_config("configs/ast1/extensions.conf") a:generate_manager_conf() a:spawn() local m = a:manager_connect() mcheck("error logging into manager", m(action.login())) local t1 = sipp_exec(scenario, key, "127.0.0.2") local o = action.new("Originate") o["Channel"] = "sip/test1@127.0.0.2" o["Context"] = "transfer" o["Exten"] = "s" o["Priority"] = 1 mcheck("error originating call", m(o)) wait_for_event(m, result) sipp_check_error(t1, scenario) proc.perror(a:term_or_kill()) end tests = { -- {description, -- scenario, -- resp key, TRANSFERSTATUS} {"Testing response 202", "sipp/wait-refer-202-notify.xml", "202", "SUCCESS"}, {"Testing response 202 with a provisional response", "sipp/wait-refer-202-notify-provisional.xml", "202", "SUCCESS"}, {"Testing response 200", "sipp/wait-refer-200-notify.xml", "200", "FAILURE"}, {"Testing response 202 followed by a 603 notify", "sipp/wait-refer-202-notify.xml", "202-603", "FAILURE"}, {"Testing response 202 followed by a 603 notify with a provisional resposne", "sipp/wait-refer-202-notify-provisional.xml", "202-603", "FAILURE"}, {"Testing response 202 followed by a 500 notify", "sipp/wait-refer-202-notify.xml", "202-500", "FAILURE"}, {"Testing response 400", "sipp/wait-refer-400.xml", "400", "FAILURE"}, {"Testing response 500", "sipp/wait-refer-500.xml", "500", "FAILURE"}, {"Testing response 603", "sipp/wait-refer-603.xml", "603", "FAILURE"}, {"Testing response 202 with buggy notify", "sipp/wait-refer-202-error.xml", "202-err", "FAILURE"}, } for _, t in ipairs(tests) do print(t[1]) do_call(t[2], t[3], t[4]) end
gpl-2.0
sose12/AOS_SHARO56
plugins/inpm.lua
4
9512
local function pre_process(msg) local to = msg.to.type local service = msg.service if to == 'user' and msg.fwd_from then if not is_support(msg.from.id) and not is_admin1(msg) then return end local user = 'user#id'..msg.from.id local from_id = msg.fwd_from.peer_id if msg.fwd_from.first_name then from_first_name = msg.fwd_from.first_name:gsub("_", " ") else from_first_name = "None" end if msg.fwd_from.last_name then from_last_name = msg.fwd_from.last_name:gsub("_", " ") else from_last_name = "None" end if msg.fwd_from.username then from_username = "@"..msg.fwd_from.username else from_username = "@[none]" end text = "User From Info:\n\nID: "..from_id.."\nFirst: "..from_first_name.."\nLast: "..from_last_name.."\nUsername: "..from_username send_large_msg(user, text) end return msg end local function chat_list(msg) i = 1 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*Use #join (ID) to join*\n\n' for k,v in pairsByKeys(data[tostring(groups)]) do local group_id = v if data[tostring(group_id)] then settings = data[tostring(group_id)]['settings'] end if settings then if not settings.public then public = 'no' else public = settings.public end end for m,n in pairsByKeys(settings) do --if m == 'public' then --public = n --end if public == 'no' then group_info = "" elseif m == 'set_name' and public == 'yes' then name = n:gsub("", "") chat_name = name:gsub("‮", "") group_name_id = name .. '\n(ID: ' ..group_id.. ')\n\n' if name:match("[\216-\219][\128-\191]") then group_info = i..' - \n'..group_name_id else group_info = i..' - '..group_name_id end i = i + 1 end end message = message..group_info end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end function super_help() local help_text = tostring(_config.help_text_super) return help_text end local function run(msg, matches) local to = msg.to.type local service = msg.service local name_log = user_print_name(msg.from) if to == 'user' or service or is_admin1(msg) and to == "chat" or to == "channel" then if is_gbanned(msg.from.id) then return 'You are globally banned.' end if matches[1] == 'join' then local data = load_data(_config.moderation.data) if matches[2]:lower() == 'english' and matches[3]:lower() == 'support' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to join English support") local target = 259142888 local long_id = data[tostring(target)]['long_id'] if is_banned(msg.from.id, tostring(target)) then return 'You are banned.' end if data[tostring(target)]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, tostring(target)) then return 'Group is private.' end if is_admin1(msg) then user_type = 'admin' else user_type = "regular" end group_name = data[tostring(target)]['settings']['set_name'] local chat = long_id local channel = long_id local user = msg.from.peer_id chat_add_user(chat, user, ok_cb, false) channel_invite(channel, user, ok_cb, false) elseif matches[2]:lower() == 'persian' and matches[3]:lower() == 'support' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to join Persian support") local target = 259142888 local long_id = data[tostring(target)]['long_id'] if is_banned(msg.from.id, tostring(target)) then return 'You are banned.' end if data[tostring(target)]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, '36088606') then return 'Group is private.' end if is_admin1(msg) then user_type = 'admin' else user_type = "regular" end group_name = data[tostring(target)]['settings']['set_name'] local chat = long_id local channel = long_id local user = msg.from.peer_id chat_add_user(chat, user, ok_cb, false) channel_invite(channel, user, ok_cb, false) elseif string.match(matches[2], '^%d+$') then local long_id = tostring(data[tostring(matches[2])]['long_id']) if not data[tostring(matches[2])] then return "Chat not found." end group_name = data[tostring(matches[2])]['settings']['set_name'] if is_admin1(msg) then user_type = 'admin' local receiver = get_receiver(msg) local chat = long_id local channel = long_id local user = msg.from.peer_id chat_add_user(chat, user, ok_cb, false) channel_set_admin(channel, user, ok_cb, false) end if is_support(msg.from.id) and not is_admin1(msg) and not is_owner2(msg.fom.id, matches[2]) then user_type = "support" local receiver = get_receiver(msg) local chat = long_id local channel = long_id local user = msg.from.peer_id chat_add_user(chat, user, ok_cb, false) channel_set_mod(channel, user, ok_cb, false) end if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end if not is_support(msg.from.id) and not is_admin1(msg) then user_type = "regular" local chat = long_id local channel = long_id local user = msg.from.peer_id chat_add_user(chat, user, ok_cb, false) channel_invite(channel, user, ok_cb, false) end end end end if msg.service and user_type == "support" and msg.action.type == "chat_add_user" and msg.from.id == 0 then local user_id = msg.action.user.id local user_name = msg.action.user.print_name local username = msg.action.user.username local group_name = string.gsub(msg.to.print_name, '_', ' ') savelog(msg.from.id, "Added Support member "..user_name.." to chat "..group_name.." (ID:"..msg.to.id..")") if username then send_large_msg("user#id"..user_id, "Added support member\n@"..username.."["..user_id.."] to chat:\n 👥 "..group_name.." (ID:"..msg.to.id..")" ) else send_large_msg("user#id"..user_id, "Added support member\n["..user_id.."] to chat:\n 👥 "..group_name.." (ID:"..msg.to.id..")" ) end end if msg.service and user_type == "admin" and msg.action.type == "chat_add_user" and msg.from.id == 0 then local user_id = msg.action.user.id local user_name = msg.action.user.print_name local username = msg.action.user.username savelog(msg.from.id, "Added Admin "..user_name.." "..user_id.." to chat "..group_name.." (ID:"..msg.to.id..")") if username then send_large_msg("user#id"..user_id, "Added admin\n@"..username.."["..user_id.."] to chat:\n 👥 "..group_name.." (ID:"..msg.to.id..")" ) else send_large_msg("user#id"..user_id, "Added admin:\n["..user_id.."] to chat:\n 👥 "..group_name.." (ID:"..msg.to.id..")" ) end end if msg.service and user_type == "regular" and msg.action.type == "chat_add_user" and msg.from.id == 0 then local user_id = msg.action.user.id local user_name = msg.action.user.print_name print("Added "..user_id.." to chat "..msg.to.print_name.." (ID:"..msg.to.id..")") savelog(msg.from.id, "Added "..user_name.." to chat "..msg.to.print_name.." (ID:"..msg.to.id..")") send_large_msg("user#id"..user_id, "Added you to chat:\n\n"..group_name.." (ID:"..msg.to.id..")") end if matches[1] == 'helpp' and msg.to.type == 'user' or matches[1] == 'pmhelp' and is_admin1(msg) and msg.to.type ~= 'user' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] used pm help") text = "Welcome to TeleSeed!\n\nTo get a list of TeleSeed groups use /chats or /chatlist for a document list of chats.\n\nTo get a new TeleSeed group, contact a support group:\n\nFor English support, use: /join English support\n\nFor Persian support, use: /join Persian support\n\nFor more information, check out our channels:\n\n@TeleseedCH [English]\n@Iranseed [Persian]\n\nThanks for using @TeleSeed!" return text end if matches[1] == 'superhelp' and is_admin1(msg)then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp") return super_help() elseif matches[1] == 'superhelp' and to == "user" then local name_log = user_print_name(msg.from) savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp") return super_help() end if matches[1] == 'chats' and is_admin1(msg)then return chat_list(msg) elseif matches[1] == 'chats' and to == 'user' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /chats") return chat_list(msg) end if matches[1] == 'chatlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /chatlist") if is_admin1(msg) and msg.to.type == 'chat' or msg.to.type == 'channel' then chat_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/listed_groups.txt", ok_cb, false) send_document("channel#id"..msg.to.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type == 'user' then chat_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end return { patterns = { "^[#!/](help)$", "^[#!/](pmhelp)$", "^[#!/](superhelp)$", "^[#!/](chats)$", "^[#!/](chatlist)$", "^[#!/](join) (%d+)$", "^[#!/](join) (.*) (support)$", "^[#!/](kickme) (.*)$", "^!!tgservice (chat_add_user)$", }, run = run, pre_process = pre_process }
gpl-2.0
ibr773/TPBOT
plugins/anti_spam.lua
2
7100
--[[ _____ ____ ____ ___ _____ |_ _| _ \ | __ ) / _ \_ _| | | | |_) | | _ \| | | || | | | | __/ | |_) | |_| || | |_| |_| |____/ \___/ |_| KASPER TP (BY @kasper_dev) _ __ _ ____ ____ _____ ____ _____ ____ | |/ / / \ / ___|| _ \| ____| _ \ |_ _| _ \ | ' / / _ \ \___ \| |_) | _| | |_) | | | | |_) | | . \ / ___ \ ___) | __/| |___| _ < | | | __/ |_|\_\/_/ \_\____/|_| |_____|_| \_\ |_| |_| --]] kicktable = {} do local TIME_CHECK = 2 -- seconds -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then return msg end if msg.from.id == our_id then return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Save stats on Redis if msg.to.type == 'channel' then -- User is on channel local hash = 'channel:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end if msg.to.type == 'user' then -- User is on chat local hash = 'PM:'..msg.from.id redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) --Load moderation data local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then --Check if flood is on or off if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then return msg end end -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) local data = load_data(_config.moderation.data) local NUM_MSG_MAX = 5 if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity end end local max_msg = NUM_MSG_MAX * 1 if msgs > max_msg then local user = msg.from.id local chat = msg.to.id local whitelist = "whitelist" local is_whitelisted = redis:sismember(whitelist, user) -- Ignore mods,owner and admins if is_momod(msg) then return msg end if is_whitelisted == true then return msg end local receiver = get_receiver(msg) if msg.to.type == 'user' then local max_msg = 7 * 1 print(msgs) if msgs >= max_msg then print("Pass2") send_large_msg("user#id"..msg.from.id, "User ["..msg.from.id.."] blocked for spam.") savelog(msg.from.id.." PM", "User ["..msg.from.id.."] blocked for spam.") block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private end end if kicktable[user] == true then return end delete_msg(msg.id, ok_cb, false) kick_user(user, chat) local username = msg.from.username local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", "") if msg.to.type == 'chat' or msg.to.type == 'channel' then if username then savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] الـمـطـ{👞}ـروديـن بـسـ(‼️)ـبـب تـفـلـ{🙀}ـيـش") send_large_msg(receiver , "تـ{✅}ـم كـتـ(‼️)ـشـافـ» تـفـلـ{🙀}ـيـش\nاسـم الـمـشـ(☠)ـتـبـه "..msg.from.first_name.."\nتـ{✅}ـم طـ(👞)ـرده\n#user : @"..(msg.from.username or "error").."\n") else savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "تـ{✅}ـم كـتـ(‼️)ـشـافـ» تـفـلـ{🙀}ـيـش\nاسـم الـمـشـ(☠)ـتـبـه "..msg.from.first_name.."\nتـ{✅}ـم طـ(👞)ـرده\n#user : @"..(msg.from.username or "error").."\n") end end -- incr it on redis local gbanspam = 'gban:spam'..msg.from.id redis:incr(gbanspam) local gbanspam = 'gban:spam'..msg.from.id local gbanspamonredis = redis:get(gbanspam) --Check if user has spammed is group more than 4 times if gbanspamonredis then if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then --Global ban that user banall_user(msg.from.id) local gbanspam = 'gban:spam'..msg.from.id --reset the counter redis:set(gbanspam, 0) if msg.from.username ~= nil then username = msg.from.username else username = "---" end local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") --Send this to that chat send_large_msg("chat#id"..msg.to.id, "تـ{✅}ـم كـتـ(‼️)ـشـافـ» تـفـلـ{🙀}ـيـش\nاسـم الـمـشـ(☠)ـتـبـه "..msg.from.first_name.."\nتـ{✅}ـم طـ(👞)ـرده\n#user : @"..(msg.from.username or "error").."\n") send_large_msg("channel#id"..msg.to.id, "تـ{✅}ـم كـتـ(‼️)ـشـافـ» تـفـلـ{🙀}ـيـش\nاسـم الـمـشـ(☠)ـتـبـه "..msg.from.first_name.."\nتـ{✅}ـم طـ(👞)ـرده\n#user : @"..(msg.from.username or "error").."\n") local GBan_log = 'GBan_log' local GBan_log = data[tostring(GBan_log)] for k,v in pairs(GBan_log) do log_SuperGroup = v gban_text = "تـ{✅}ـم كـتـ(‼️)ـشـافـ» تـفـلـ{🙀}ـيـش\nاسـم الـمـشـ(☠)ـتـبـه "..msg.from.first_name.."\nتـ{✅}ـم طـ(👞)ـرده\n#user : @"..(msg.from.username or "error").."\n" --send it to log group/channel send_large_msg(log_SuperGroup, gban_text) end end end kicktable[user] = true msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function cron() --clear that table on the top of the plugins kicktable = {} end return { patterns = {}, cron = cron, pre_process = pre_process } end --[[ _____ ____ ____ ___ _____ |_ _| _ \ | __ ) / _ \_ _| | | | |_) | | _ \| | | || | | | | __/ | |_) | |_| || | |_| |_| |____/ \___/ |_| KASPER TP (BY @kasper_dev) _ __ _ ____ ____ _____ ____ _____ ____ | |/ / / \ / ___|| _ \| ____| _ \ |_ _| _ \ | ' / / _ \ \___ \| |_) | _| | |_) | | | | |_) | | . \ / ___ \ ___) | __/| |___| _ < | | | __/ |_|\_\/_/ \_\____/|_| |_____|_| \_\ |_| |_| --]]
gpl-2.0
andyvand/cardpeek
dot_cardpeek_dir/scripts/calypso/c250n901.lua
17
4373
-- -- This file is part of Cardpeek, the smartcard reader utility. -- -- Copyright 2009-2013 by 'L1L1' -- -- Cardpeek 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. -- -- Cardpeek 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 Cardpeek. If not, see <http://www.gnu.org/licenses/>. -- --------------------------------------------------------------------- -- Most of the data and coding ideas in this file -- was contributed by 'Pascal Terjan', based on location -- data from 'Aurélien Baro'. --------------------------------------------------------------------- require('lib.strict') require('etc.paris-metro') require('etc.paris-rer') SERVICE_PROVIDERS = { [2] = "SNCF", [3] = "RATP" } TRANSPORT_LIST = { [1] = "Urban Bus", [2] = "Interurban Bus", [3] = "Metro", [4] = "Tram", [5] = "Train", [8] = "Parking" } TRANSITION_LIST = { [1] = "Entry", [2] = "Exit", [4] = "Inspection", [6] = "Interchange (entry)", [7] = "Interchange (exit)" } function navigo_process_events(cardenv,node_label) local event_node local record_node local ref_node local code_value local code_transport local code_transition local code_transport_string local code_transition_string local code_string local service_provider_value local location_id_value local sector_id local station_id local location_string event_node = cardenv:find_first({label=node_label, parsed="true"}) if event_node==nil then log.print(log.WARNING,"No " .. node_label .. " found in card") return 0 end for record_node in event_node:find({label="record"}) do -- is it RATP or SNCF ? ref_node = record_node:find_first({label="EventServiceProvider"}) service_provider_value = bytes.tonumber(ref_node:get_attribute("val")) ref_node:set_attribute("alt",SERVICE_PROVIDERS[service_provider_value]) ref_node = record_node:find_first({label="EventCode"}) code_value = bytes.tonumber(ref_node:get_attribute("val")) -- is it a bus, a tram, a metro, ... ? code_transport = bit.SHR(code_value,4) code_transport_string = TRANSPORT_LIST[code_transport] if code_transport_string==nil then code_transport_string = code_transport end -- is it an entry, an exit, ... ? code_transition = bit.AND(code_value,0xF) code_transition_string = TRANSITION_LIST[code_transition] if (code_transition_string==nil) then code_transition_string = code_transition end ref_node:set_attribute("alt",code_transport_string.." - "..code_transition_string) -- service_provider_value == RATP and code_transport in { metro, tram, train } ? if (service_provider_value==3 or service_provider_value==2) and code_transport>=3 and code_transport<=5 then ref_node = record_node:find_first({label="EventLocationId"}) location_id_value = bytes.tonumber(ref_node:get_attribute("val")) sector_id = bit.SHR(location_id_value,9) station_id = bit.AND(bit.SHR(location_id_value,4),0x1F) if code_transport==5 and BANLIEUE_LIST[sector_id] and BANLIEUE_LIST[sector_id][station_id] then location_string = "secteur "..sector_id.." - station "..BANLIEUE_LIST[sector_id][station_id] else if METRO_LIST[sector_id]~=nil then location_string = "secteur "..METRO_LIST[sector_id]['name'].." - station " if METRO_LIST[sector_id][station_id]==nil then location_string = location_string .. station_id else location_string = location_string .. METRO_LIST[sector_id][station_id] end else location_string = "secteur "..sector_id.." - station "..station_id end end ref_node:set_attribute("alt",location_string) end end end navigo_process_events(CARD,"Event logs") navigo_process_events(CARD,"Special events")
gpl-3.0
akaStiX/premake-core
tests/actions/vstudio/vc2010/test_imagexex_settings.lua
16
1100
-- -- tests/actions/vstudio/vc2010/test_compile_settings.lua -- Validate Xbox 360 XEX image settings in Visual Studio 2010 C/C++ projects. -- Copyright (c) 2011-2013 Jason Perkins and the Premake project -- local suite = test.declare("vstudio_vs2010_imagexex_settings") local vc2010 = premake.vstudio.vc2010 local project = premake.project -- -- Setup -- local wks, prj function suite.setup() wks, prj = test.createWorkspace() platforms "xbox360" end local function prepare(platform) local cfg = test.getconfig(prj, "Debug", "xbox360") vc2010.imageXex(cfg) end -- -- Test default ImageXex settings -- function suite.defaultSettings() prepare() test.capture [[ <ImageXex> <ConfigurationFile> </ConfigurationFile> <AdditionalSections> </AdditionalSections> </ImageXex> ]] end -- -- Ensure configuration file is output in ImageXex block -- function suite.defaultSettings() configfile "testconfig.xml" prepare() test.capture [[ <ImageXex> <ConfigurationFile>testconfig.xml</ConfigurationFile> <AdditionalSections> </AdditionalSections> </ImageXex> ]] end
bsd-3-clause
alcherk/mal
lua/step7_quote.lua
40
4344
#!/usr/bin/env lua local table = require('table') local readline = require('readline') local utils = require('utils') local types = require('types') local reader = require('reader') local printer = require('printer') local Env = require('env') local core = require('core') local List, Vector, HashMap = types.List, types.Vector, types.HashMap -- read function READ(str) return reader.read_str(str) end -- eval function is_pair(x) return types._sequential_Q(x) and #x > 0 end function quasiquote(ast) if not is_pair(ast) then return types.List:new({types.Symbol:new("quote"), ast}) elseif types._symbol_Q(ast[1]) and ast[1].val == 'unquote' then return ast[2] elseif is_pair(ast[1]) and types._symbol_Q(ast[1][1]) and ast[1][1].val == 'splice-unquote' then return types.List:new({types.Symbol:new("concat"), ast[1][2], quasiquote(ast:slice(2))}) else return types.List:new({types.Symbol:new("cons"), quasiquote(ast[1]), quasiquote(ast:slice(2))}) end end function eval_ast(ast, env) if types._symbol_Q(ast) then return env:get(ast) elseif types._list_Q(ast) then return List:new(utils.map(function(x) return EVAL(x,env) end,ast)) elseif types._vector_Q(ast) then return Vector:new(utils.map(function(x) return EVAL(x,env) end,ast)) elseif types._hash_map_Q(ast) then local new_hm = {} for k,v in pairs(ast) do new_hm[EVAL(k, env)] = EVAL(v, env) end return HashMap:new(new_hm) else return ast end end function EVAL(ast, env) while true do --print("EVAL: "..printer._pr_str(ast,true)) if not types._list_Q(ast) then return eval_ast(ast, env) end local a0,a1,a2,a3 = ast[1], ast[2],ast[3],ast[4] local a0sym = types._symbol_Q(a0) and a0.val or "" if 'def!' == a0sym then return env:set(a1, EVAL(a2, env)) elseif 'let*' == a0sym then local let_env = Env:new(env) for i = 1,#a1,2 do let_env:set(a1[i], EVAL(a1[i+1], let_env)) end env = let_env ast = a2 -- TCO elseif 'quote' == a0sym then return a1 elseif 'quasiquote' == a0sym then ast = quasiquote(a1) -- TCO elseif 'do' == a0sym then local el = eval_ast(ast:slice(2,#ast-1), env) ast = ast[#ast] -- TCO elseif 'if' == a0sym then local cond = EVAL(a1, env) if cond == types.Nil or cond == false then if a3 then ast = a3 else return types.Nil end -- TCO else ast = a2 -- TCO end elseif 'fn*' == a0sym then return types.MalFunc:new(function(...) return EVAL(a2, Env:new(env, a1, arg)) end, a2, env, a1) else local args = eval_ast(ast, env) local f = table.remove(args, 1) if types._malfunc_Q(f) then ast = f.ast env = Env:new(f.env, f.params, args) -- TCO else return f(unpack(args)) end end end end -- print function PRINT(exp) return printer._pr_str(exp, true) end -- repl local repl_env = Env:new() function rep(str) return PRINT(EVAL(READ(str),repl_env)) end -- core.lua: defined using Lua for k,v in pairs(core.ns) do repl_env:set(types.Symbol:new(k), v) end repl_env:set(types.Symbol:new('eval'), function(ast) return EVAL(ast, repl_env) end) repl_env:set(types.Symbol:new('*ARGV*'), types.List:new(types.slice(arg,2))) -- core.mal: defined using mal rep("(def! not (fn* (a) (if a false true)))") rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))") if #arg > 0 and arg[1] == "--raw" then readline.raw = true table.remove(arg,1) end if #arg > 0 then rep("(load-file \""..arg[1].."\")") os.exit(0) end while true do line = readline.readline("user> ") if not line then break end xpcall(function() print(rep(line)) end, function(exc) if exc then if types._malexception_Q(exc) then exc = printer._pr_str(exc.val, true) end print("Error: " .. exc) print(debug.traceback()) end end) end
mpl-2.0
nuko8/awesome
lib/gears/filesystem.lua
2
5618
--------------------------------------------------------------------------- --- Filesystem module for gears -- -- @module gears.filesystem --------------------------------------------------------------------------- -- Grab environment we need local Gio = require("lgi").Gio local gstring = require("gears.string") local gtable = require("gears.table") local filesystem = {} local function make_directory(gfile) local success, err = gfile:make_directory_with_parents() if success then return true end if err.domain == Gio.IOErrorEnum and err.code == "EXISTS" then -- Directory already exists, let this count as success return true end return false, err end --- Create a directory, including all missing parent directories. -- @tparam string dir The directory. -- @return (true, nil) on success, (false, err) on failure function filesystem.make_directories(dir) return make_directory(Gio.File.new_for_path(dir)) end function filesystem.mkdir(dir) require("gears.debug").deprecate("gears.filesystem.make_directories", {deprecated_in=5}) return filesystem.make_directories(dir) end --- Create all parent directories for a given path. -- @tparam string path The path whose parents should be created. -- @return (true, nil) on success, (false, err) on failure function filesystem.make_parent_directories(path) return make_directory(Gio.File.new_for_path(path):get_parent()) end --- Check if a file exists, is readable and not a directory. -- @tparam string filename The file path. -- @treturn boolean True if file exists and is readable. function filesystem.file_readable(filename) local gfile = Gio.File.new_for_path(filename) local gfileinfo = gfile:query_info("standard::type,access::can-read", Gio.FileQueryInfoFlags.NONE) return gfileinfo and gfileinfo:get_file_type() ~= "DIRECTORY" and gfileinfo:get_attribute_boolean("access::can-read") end --- Check if a path exists, is readable and a directory. -- @tparam string path The directory path. -- @treturn boolean True if path exists and is readable. function filesystem.dir_readable(path) local gfile = Gio.File.new_for_path(path) local gfileinfo = gfile:query_info("standard::type,access::can-read", Gio.FileQueryInfoFlags.NONE) return gfileinfo and gfileinfo:get_file_type() == "DIRECTORY" and gfileinfo:get_attribute_boolean("access::can-read") end --- Check if a path is a directory. -- @tparam string path The directory path -- @treturn boolean True if path exists and is a directory. function filesystem.is_dir(path) return Gio.File.new_for_path(path):query_file_type({}) == "DIRECTORY" end --- Get the config home according to the XDG basedir specification. -- @return the config home (XDG_CONFIG_HOME) with a slash at the end. function filesystem.get_xdg_config_home() return (os.getenv("XDG_CONFIG_HOME") or os.getenv("HOME") .. "/.config") .. "/" end --- Get the cache home according to the XDG basedir specification. -- @return the cache home (XDG_CACHE_HOME) with a slash at the end. function filesystem.get_xdg_cache_home() return (os.getenv("XDG_CACHE_HOME") or os.getenv("HOME") .. "/.cache") .. "/" end --- Get the data home according to the XDG basedir specification. -- @treturn string the data home (XDG_DATA_HOME) with a slash at the end. function filesystem.get_xdg_data_home() return (os.getenv("XDG_DATA_HOME") or os.getenv("HOME") .. "/.local/share") .. "/" end --- Get the data dirs according to the XDG basedir specification. -- @treturn table the data dirs (XDG_DATA_DIRS) with a slash at the end of each entry. function filesystem.get_xdg_data_dirs() local xdg_data_dirs = os.getenv("XDG_DATA_DIRS") or "/usr/share:/usr/local/share" return gtable.map( function(dir) return dir .. "/" end, gstring.split(xdg_data_dirs, ":")) end --- Get the path to the user's config dir. -- This is the directory containing the configuration file ("rc.lua"). -- @return A string with the requested path with a slash at the end. function filesystem.get_configuration_dir() return awesome.conffile:match(".*/") or "./" end --- Get the path to a directory that should be used for caching data. -- @return A string with the requested path with a slash at the end. function filesystem.get_cache_dir() local result = filesystem.get_xdg_cache_home() .. "awesome/" filesystem.make_directories(result) return result end --- Get the path to the directory where themes are installed. -- @return A string with the requested path with a slash at the end. function filesystem.get_themes_dir() return (os.getenv('AWESOME_THEMES_PATH') or awesome.themes_path) .. "/" end --- Get the path to the directory where our icons are installed. -- @return A string with the requested path with a slash at the end. function filesystem.get_awesome_icon_dir() return (os.getenv('AWESOME_ICON_PATH') or awesome.icon_path) .. "/" end --- Get the user's config or cache dir. -- It first checks XDG_CONFIG_HOME / XDG_CACHE_HOME, but then goes with the -- default paths. -- @param d The directory to get (either "config" or "cache"). -- @return A string containing the requested path. function filesystem.get_dir(d) if d == "config" then -- No idea why this is what is returned, I recommend everyone to use -- get_configuration_dir() instead return filesystem.get_xdg_config_home() .. "awesome/" elseif d == "cache" then return filesystem.get_cache_dir() end end return filesystem
gpl-2.0
Duesterwald/Generals
lua/misc.lua
1
2006
<< map_size = wesnoth.get_variable("GN_LOCAL_MAP_SIZE") global_map_size = {wesnoth.get_map_size()} hex_area = 3 * (map_size * map_size + map_size) num_villages = hex_area * wesnoth.get_variable("GN_LOCAL_VILLAGE_DENSITY") / 1000 keep_size = wesnoth.get_variable("GN_LOCAL_KEEP_SIZE") function round(x) return math.floor(x+0.5) end function ran_int(ran, n) ran = ran * n n = math.ceil(ran) if n-ran == 0 then print("ran_int: Random bits depleted") end return n, n - ran end function ran_element(ran, array) local n = #array n,ran = ran_int(ran, n) return array[n], ran end function weighted_key(ran, array) local totalweight = 0 for i, w in ipairs(array) do totalweight = totalweight + w end local r = ran * totalweight for i, wi in ipairs(array) do r = r - wi if r < 0 then return i, -r/wi end end return nil, ran end function sawtooth(maximum, deviation, direction) if maximum == nil or deviation == nil then return 1 end if deviation < 0 then direction = (direction + 3) % 6 deviation = -deviation end local x = math.abs(direction - maximum) return math.max(deviation - x, deviation / 12, x + deviation - 6) end function correlation(bias, bias_deviation, correlation_strength) local corr_matrix = {} for last_dir = 1, 6 do corr_matrix[last_dir] = {} local sum = 0 for direction = 1, 6 do --if ( direction - last_dir + 6 ) % 6 == 3 then corr_matrix[last_dir][direction] = 0 --else corr_matrix[last_dir][direction] = sawtooth(bias, bias_deviation, direction) * sawtooth(last_dir, correlation_strength, direction) --end sum = sum + corr_matrix[last_dir][direction] end corr_matrix[last_dir].sum = sum end corr_matrix[0] = {} local sum = 0 for direction = 1, 6 do corr_matrix[0][direction] = sawtooth(bias, bias_deviation, direction) sum = sum + corr_matrix[0][direction] end corr_matrix[0].sum = sum return corr_matrix end print("misc.lua loaded.") >>
gpl-2.0
smartwifi/stores-rd
meshdesk/MESHdesk/libs/rdSystem.lua
1
4400
require( "class" ) ------------------------------------------------------------------------------- -- Class used to set up the system settings handed from the config server ----- -- For now it only is the system password and hostname ------------------------ -- It will only do something if there was a change ---------------------------- ------------------------------------------------------------------------------- class "rdSystem" --Init function for object function rdSystem:rdSystem() require('rdLogger') local uci = require('uci') self.version = "1.0.1" self.tag = "MESHdesk" self.debug = true self.json = require("json") self.logger = rdLogger() self.x = uci.cursor(nil,'/var/state') self.s = "/etc/shadow" self.t = "/tmp/t" end function rdSystem:getVersion() return self.version end function rdSystem:configureFromJson(file) self:log("==Configure System from JSON file "..file.."==") self:__configureFromJson(file) end function rdSystem:configureFromTable(tbl) self:log("==Configure System from Lua table==") self:__configureFromTable(tbl) end function rdSystem:log(m,p) if(self.debug)then self.logger:log(m,p) end end --[[-- ======================================================== === Private functions start here ======================= ======================================================== --]]-- function rdSystem.__configureFromJson(self,json_file) self:log("Configuring System from a JSON file") local contents = self:__readAll(json_file) local o = self.json.decode(contents) if(o.config_settings.system ~= nil)then self:log("Found System settings - completing it") self:__configureFromTable(o.config_settings.system) else self:log("No System settings found, please check JSON file") end end function rdSystem.__configureFromTable(self,tbl) --First we do the password local c_pw = self:__getCurrentPassword() if(c_pw)then local new_pw = tbl.password_hash if(new_pw)then if(c_pw ~= new_pw)then self:__replacePassword(new_pw,'root') end end end --Then we do the hostname local c_hn = self:__getCurrentHostname() if(c_hn)then local new_hn = tbl.hostname if(new_hn)then if(c_hn ~= new_hn)then self:__setHostname(new_hn) end end end --Heartbeat interval local c_hb = self.x.get('meshdesk', 'settings', 'heartbeat_interval') if(c_hb)then local new_hb = tbl.heartbeat_interval if(new_hb)then if(c_hb ~= new_hb)then self.x.set('meshdesk', 'settings', 'heartbeat_interval',new_hb) self.x.commit('meshdesk') end end end --Hearbeat dead after local c_hbd = self.x.get('meshdesk', 'settings', 'heartbeat_dead_after') if(c_hbd)then local new_hbd = tbl.heartbeat_dead_after if(new_hbd)then if(c_hbd ~= new_hbd)then self.x.set('meshdesk', 'settings', 'heartbeat_dead_after',new_hbd) self.x.commit('meshdesk') end end end end function rdSystem.__getCurrentPassword(self,user) if(user == nil)then user = 'root' end local enc = nil for line in io.lines(self.s) do if(string.find(line,'^'..user..":.*"))then line = string.gsub(line, '^'..user..":", "") line = string.gsub(line, ":.*", "") --return line enc = line break end end return enc end function rdSystem.__replacePassword(self,password,user) if(user == nil)then user = 'root' end local new_shadow = ''; for line in io.lines(self.s) do if(string.find(line,'^'..user..":.*"))then line = string.gsub(line, '^'..user..":.-:", "") line = user..":"..password..":"..line --Replace this line end new_shadow = new_shadow ..line.."\n" end local f,err = io.open(self.t,"w") if not f then return print(err) end f:write(new_shadow) f:close() os.execute("cp "..self.t.." "..self.s) os.remove(self.t) end function rdSystem.__getCurrentHostname(self) local hostname = nil self.x.foreach('system','system', function(a) hostname = self.x.get('system', a['.name'], 'hostname') end) return hostname end function rdSystem.__setHostname(self,hostname) self.x.foreach('system','system', function(a) self.x.set('system', a['.name'], 'hostname',hostname) end) self.x.commit('system') --Activate it os.execute("echo "..hostname.." > /proc/sys/kernel/hostname") end function rdSystem.__readAll(self,file) local f = io.open(file,"rb") local content = f:read("*all") f:close() return content end
gpl-2.0
LuttyYang/luci
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/nut.lua
18
2897
-- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.nut",package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) local voltages = { title = "%H: Voltages on UPS \"%pi\"", vlabel = "V", number_format = "%5.1lfV", data = { instances = { voltage = { "battery", "input", "output" } }, options = { voltage_output = { color = "00e000", title = "Output voltage", noarea=true, overlay=true }, voltage_battery = { color = "0000ff", title = "Battery voltage", noarea=true, overlay=true }, voltage_input = { color = "ffb000", title = "Input voltage", noarea=true, overlay=true } } } } local currents = { title = "%H: Current on UPS \"%pi\"", vlabel = "A", number_format = "%5.3lfA", data = { instances = { current = { "battery", "output" } }, options = { current_output = { color = "00e000", title = "Output current", noarea=true, overlay=true }, current_battery = { color = "0000ff", title = "Battery current", noarea=true, overlay=true } } } } local percentage = { title = "%H: Battery charge/load on UPS \"%pi\"", vlabel = "Percent", y_min = "0", y_max = "100", number_format = "%5.1lf%%", data = { instances = { percent = { "charge", "load" } }, options = { percent_charge = { color = "00ff00", title = "Charge level" }, percent_load = { color = "ff0000", title = "Load" } } } } -- Note: This is in ISO8859-1 for rrdtool. Welcome to the 20th century. local temperature = { title = "%H: Battery temperature on UPS \"%pi\"", vlabel = "\176C", number_format = "%5.1lf\176C", data = { instances = { temperature = "battery" }, options = { temperature_battery = { color = "ffb000", title = "Battery temperature" } } } } local timeleft = { title = "%H: Time left on UPS \"%pi\"", vlabel = "Minutes", number_format = "%.1lfm", data = { instances = { timeleft = { "battery" } }, options = { timeleft_battery = { color = "0000ff", title = "Time left", transform_rpn = "60,/", noarea=true } } } } local power = { title = "%H: Power on UPS \"%pi\"", vlabel = "Power", number_format = "%5.1lf%%", data = { instances = { power = { "ups" } }, options = { power_ups = { color = "00ff00", title = "Power level" } } } } local frequencies = { title = "%H: Frequencies on UPS \"%pi\"", vlabel = "Hz", number_format = "%5.1lfHz", data = { instances = { frequency = { "input", "output" } }, options = { frequency_output = { color = "00e000", title = "Output frequency", noarea=true, overlay=true }, frequency_input = { color = "ffb000", title = "Input frequency", noarea=true, overlay=true } } } } return { voltages, currents, percentage, temperature, timeleft, power, frequencies } end
apache-2.0
gdevillele/dockercraft
world/Plugins/APIDump/Hooks/OnEntityAddEffect.lua
36
1593
return { HOOK_ENTITY_ADD_EFFECT = { CalledWhen = "An entity effect is about to get added to an entity.", DefaultFnName = "OnEntityAddEffect", -- also used as pagename Desc = [[ This hook is called whenever an entity effect is about to be added to an entity. The plugin may disallow the addition by returning true.</p> <p>Note that this hook only fires for adding the effect, but not for the actual effect application. See also the {{OnEntityRemoveEffect|HOOK_ENTITY_REMOVE_EFFECT}} for notification about effects expiring / removing, and {{OnEntityApplyEffect|HOOK_ENTITY_APPLY_EFFECT}} for the actual effect application to the entity. ]], Params = { { Name = "Entity", Type = "{{cEntity}}", Notes = "The entity to which the effect is about to be added" }, { Name = "EffectType", Type = "number", Notes = "The type of the effect to be added. One of the effXXX constants." }, { Name = "EffectDuration", Type = "number", Notes = "The duration of the effect to be added, in ticks." }, { Name = "EffectIntensity", Type = "number", Notes = "The intensity (level) of the effect to be added. " }, { Name = "DistanceModifier", Type = "number", Notes = "The modifier for the effect intensity, based on distance. Used mainly for splash potions." }, }, Returns = [[ If the plugin returns true, the effect will not be added and none of the remaining hook handlers will be called. If the plugin returns false, Cuberite calls all the remaining hook handlers and finally the effect is added to the entity. ]], }, -- HOOK_EXECUTE_COMMAND }
apache-2.0
LuttyYang/luci
applications/luci-app-freifunk-widgets/luasrc/model/cbi/freifunk/widgets/widget.lua
68
1039
-- Copyright 2012 Manuel Munz <freifunk at somakoma dot de> -- Licensed to the public under the Apache License 2.0. local uci = require "luci.model.uci".cursor() local dsp = require "luci.dispatcher" local utl = require "luci.util" local widget = uci:get("freifunk-widgets", arg[1], "template") local title = uci:get("freifunk-widgets", arg[1], "title") or "" m = Map("freifunk-widgets", translate("Widget")) m.redirect = luci.dispatcher.build_url("admin/freifunk/widgets") if not arg[1] or m.uci:get("freifunk-widgets", arg[1]) ~= "widget" then luci.http.redirect(m.redirect) return end wdg = m:section(NamedSection, arg[1], "widget", translate("Widget") .. " " .. title) wdg.anonymous = true wdg.addremove = false local en = wdg:option(Flag, "enabled", translate("Enable")) en.rmempty = false local title = wdg:option(Value, "title", translate("Title")) title.rmempty = true local form = loadfile( utl.libpath() .. "/model/cbi/freifunk/widgets/%s.lua" % widget ) if form then setfenv(form, getfenv(1))(m, wdg) end return m
apache-2.0
valkjsaaa/sl4a
lua/src/test/sort.lua
889
1494
-- two implementations of a sort function -- this is an example only. Lua has now a built-in function "sort" -- extracted from Programming Pearls, page 110 function qsort(x,l,u,f) if l<u then local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u x[l],x[m]=x[m],x[l] -- swap pivot to first position local t=x[l] -- pivot value m=l local i=l+1 while i<=u do -- invariant: x[l+1..m] < t <= x[m+1..i-1] if f(x[i],t) then m=m+1 x[m],x[i]=x[i],x[m] -- swap x[i] and x[m] end i=i+1 end x[l],x[m]=x[m],x[l] -- swap pivot to a valid place -- x[l+1..m-1] < x[m] <= x[m+1..u] qsort(x,l,m-1,f) qsort(x,m+1,u,f) end end function selectionsort(x,n,f) local i=1 while i<=n do local m,j=i,i+1 while j<=n do if f(x[j],x[m]) then m=j end j=j+1 end x[i],x[m]=x[m],x[i] -- swap x[i] and x[m] i=i+1 end end function show(m,x) io.write(m,"\n\t") local i=1 while x[i] do io.write(x[i]) i=i+1 if x[i] then io.write(",") end end io.write("\n") end function testsorts(x) local n=1 while x[n] do n=n+1 end; n=n-1 -- count elements show("original",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort",x) selectionsort(x,n,function (x,y) return x>y end) show("after reverse selection sort",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort again",x) end -- array to be sorted x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"} testsorts(x)
apache-2.0
DeNA/redis
deps/lua/test/sort.lua
889
1494
-- two implementations of a sort function -- this is an example only. Lua has now a built-in function "sort" -- extracted from Programming Pearls, page 110 function qsort(x,l,u,f) if l<u then local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u x[l],x[m]=x[m],x[l] -- swap pivot to first position local t=x[l] -- pivot value m=l local i=l+1 while i<=u do -- invariant: x[l+1..m] < t <= x[m+1..i-1] if f(x[i],t) then m=m+1 x[m],x[i]=x[i],x[m] -- swap x[i] and x[m] end i=i+1 end x[l],x[m]=x[m],x[l] -- swap pivot to a valid place -- x[l+1..m-1] < x[m] <= x[m+1..u] qsort(x,l,m-1,f) qsort(x,m+1,u,f) end end function selectionsort(x,n,f) local i=1 while i<=n do local m,j=i,i+1 while j<=n do if f(x[j],x[m]) then m=j end j=j+1 end x[i],x[m]=x[m],x[i] -- swap x[i] and x[m] i=i+1 end end function show(m,x) io.write(m,"\n\t") local i=1 while x[i] do io.write(x[i]) i=i+1 if x[i] then io.write(",") end end io.write("\n") end function testsorts(x) local n=1 while x[n] do n=n+1 end; n=n-1 -- count elements show("original",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort",x) selectionsort(x,n,function (x,y) return x>y end) show("after reverse selection sort",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort again",x) end -- array to be sorted x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"} testsorts(x)
bsd-3-clause
nuko8/awesome
tests/examples/wibox/awidget/prompt/highlight.lua
5
2543
local parent = ... --DOC_NO_USAGE --DOC_HIDE local wibox = require( "wibox" ) --DOC_HIDE local awful = { prompt = require("awful.prompt") }--DOC_HIDE local beautiful = require( "beautiful" ) --DOC_HIDE local amp = "&amp"..string.char(0x3B) local quot = "&quot"..string.char(0x3B) local atextbox = wibox.widget.textbox() -- Create a shortcut function local function echo_test() awful.prompt.run { prompt = "<b>Echo: </b>", text = 'a_very "nice" $SHELL && command', --DOC_HIDE bg_cursor = "#ff0000", -- To use the default `rc.lua` prompt: --textbox = mouse.screen.mypromptbox.widget, textbox = atextbox, highlighter = function(b, a) -- Add a random marker to delimitate the cursor local cmd = b.."ZZZCURSORZZZ"..a -- Find shell variables local sub = "<span foreground='#CFBA5D'>%1</span>" cmd = cmd:gsub("($[A-Za-z][a-zA-Z0-9]*)", sub) -- Highlight " && " sub = "<span foreground='#159040'>%1</span>" cmd = cmd:gsub("( "..amp..amp..")", sub) -- Highlight double quotes local quote_pos = cmd:find("[^\\]"..quot) while quote_pos do local old_pos = quote_pos quote_pos = cmd:find("[^\\]"..quot, old_pos+2) if quote_pos then local content = cmd:sub(old_pos+1, quote_pos+6) cmd = table.concat({ cmd:sub(1, old_pos), "<span foreground='#2977CF'>", content, "</span>", cmd:sub(quote_pos+7, #cmd) }, "") quote_pos = cmd:find("[^\\]"..quot, old_pos+38) end end -- Split the string back to the original content -- (ignore the recursive and escaped ones) local pos = cmd:find("ZZZCURSORZZZ") b,a = cmd:sub(1, pos-1), cmd:sub(pos+12, #cmd) return b,a end, } end echo_test() --DOC_HIDE parent:add( wibox.widget { --DOC_HIDE atextbox, --DOC_HIDE bg = beautiful.bg_normal, --DOC_HIDE widget = wibox.container.background --DOC_HIDE }) --DOC_HIDE
gpl-2.0
sjznxd/lc-20121230
applications/luci-statistics/luasrc/model/cbi/luci_statistics/rrdtool.lua
80
3431
--[[ Luci configuration model for statistics - collectd rrdtool plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("RRDTool Plugin Configuration"), translate( "The rrdtool plugin stores the collected data in rrd database " .. "files, the foundation of the diagrams.<br /><br />" .. "<strong>Warning: Setting the wrong values will result in a very " .. "high memory consumption in the temporary directory. " .. "This can render the device unusable!</strong>" )) -- collectd_rrdtool config section s = m:section( NamedSection, "collectd_rrdtool", "luci_statistics" ) -- collectd_rrdtool.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 1 -- collectd_rrdtool.datadir (DataDir) datadir = s:option( Value, "DataDir", translate("Storage directory") ) datadir.default = "/tmp" datadir.rmempty = true datadir.optional = true datadir:depends( "enable", 1 ) -- collectd_rrdtool.stepsize (StepSize) stepsize = s:option( Value, "StepSize", translate("RRD step interval"), translate("Seconds") ) stepsize.default = 30 stepsize.isinteger = true stepsize.rmempty = true stepsize.optional = true stepsize:depends( "enable", 1 ) -- collectd_rrdtool.heartbeat (HeartBeat) heartbeat = s:option( Value, "HeartBeat", translate("RRD heart beat interval"), translate("Seconds") ) heartbeat.default = 60 heartbeat.isinteger = true heartbeat.rmempty = true heartbeat.optional = true heartbeat:depends( "enable", 1 ) -- collectd_rrdtool.rrasingle (RRASingle) rrasingle = s:option( Flag, "RRASingle", translate("Only create average RRAs"), translate("reduces rrd size") ) rrasingle.default = true rrasingle.rmempty = true rrasingle.optional = true rrasingle:depends( "enable", 1 ) -- collectd_rrdtool.rratimespans (RRATimespan) rratimespans = s:option( Value, "RRATimespans", translate("Stored timespans"), translate("seconds; multiple separated by space") ) rratimespans.default = "600 86400 604800 2678400 31622400" rratimespans.rmempty = true rratimespans.optional = true rratimespans:depends( "enable", 1 ) -- collectd_rrdtool.rrarows (RRARows) rrarows = s:option( Value, "RRARows", translate("Rows per RRA") ) rrarows.isinteger = true rrarows.default = 100 rrarows.rmempty = true rrarows.optional = true rrarows:depends( "enable", 1 ) -- collectd_rrdtool.xff (XFF) xff = s:option( Value, "XFF", translate("RRD XFiles Factor") ) xff.default = 0.1 xff.isnumber = true xff.rmempty = true xff.optional = true xff:depends( "enable", 1 ) -- collectd_rrdtool.cachetimeout (CacheTimeout) cachetimeout = s:option( Value, "CacheTimeout", translate("Cache collected data for"), translate("Seconds") ) cachetimeout.isinteger = true cachetimeout.default = 100 cachetimeout.rmempty = true cachetimeout.optional = true cachetimeout:depends( "enable", 1 ) -- collectd_rrdtool.cacheflush (CacheFlush) cacheflush = s:option( Value, "CacheFlush", translate("Flush cache after"), translate("Seconds") ) cacheflush.isinteger = true cacheflush.default = 100 cacheflush.rmempty = true cacheflush.optional = true cacheflush:depends( "enable", 1 ) return m
apache-2.0
mathiasDJ/OpenComputers-Projects
Big Reactor/client.lua
1
4192
local component = require("component") local event = require("event") local keyboard = require("keyboard") local serialization = require("serialization") local term = require("term") local visual = require("reactorVisual") local modem local getServerTimerID local serverAdress local port = 54598 local updateSpeed = 1 local maxRF local maxFuel local maxCaseHeat local maxCoreHeat local RF local fuel local caseHeat local coreHeat local running local mode local capacitor = false local capacitorRF = 0 local capacitorMax --****Helper functions****-- function srlz(myTable) return serialization.serialize(myTable) end function unsrlz(myString) return serialization.unserialize(myString) end function round(num, idp) local mult = 10^(idp or 0) return math.floor(num * mult + 0.5) / mult end function send(myTable) modem.send(serverAdress, port, srlz(myTable)) end function serverNotFound() print("Could not find a server on port "..port) os.exit(false) end function setMode(newMode) send({action="set", value=newMode}) end function getMaxes() send({action="get", value="init"}) end function setMaxes(info) maxRF = info.maxRF maxFuel = info.maxFuel maxCoreHeat = info.maxCoreHeat maxCaseHeat = info.maxCaseHeat running = info.running if (info.capacitorMax ~= nil) then capacitor = true capacitorMax = info.capacitorMax print("Capacitor found with "..capacitorMax.."RF capacity.") print("Initializing right-click menu") visual.setupRightMenu(setMode) visual.clear() end end function updateValues(info) RF = info.RF fuel = info.fuel coreHeat = info.coreHeat caseHeat = info.caseHeat running = info.running visual.clear() visual.drawBar("fuel", fuel, "mB", fuel/maxFuel) visual.drawBar("caseTemp", caseHeat, "°C", caseHeat/maxCaseHeat) visual.drawBar("fuelTemp", coreHeat, "°C", coreHeat/maxCoreHeat) visual.drawBar("RF", math.ceil(RF/1000), "kRF", RF/maxRF) if capacitor then capacitorRF = info.capacitor capacitorFlux = info.capacitorFlux visual.drawCapacitor(capacitorRF, capacitorMax, capacitorFlux) end local reactivity = info.reactivity local fuelFlux = info.fuelFlux local RFFlux = info.RFFlux visual.drawExtra(reactivity, fuelFlux, RFFlux, math.ceil(100*RF/maxRF)) visual.drawRight(mode) end --**EVENTS**-- local eventHandlers = setmetatable({}, {__index = function() return unknownEvent end}) function eventHandlers.modem_message(to, from, port, distance, data) data = unsrlz(data) --LUA y u no have switch case local action = data.action local value = data.value if (action == "hello") then serverAdress = from event.cancel(getServerTimerID) print("Server "..from.." found "..(round(distance, 2)).." meters away.") getMaxes() elseif (action == "goodbye") then print("Server shutdown, goodbye!") os.exit() elseif (action == "answer") then if (value == "init") then setMaxes(data.info) os.sleep(.5) timerID = event.timer(updateSpeed, update, math.huge) elseif (value == "data") then updateValues(data.info) elseif (value == "set") then mode = data.mode end end end function eventHandlers.key_down(_, char, _, _) if (char == require("string").byte("w")) then event.cancel(getServerTimerID) event.cancel(timerID) event.ignore('touch', visual.tabletTouched) os.exit() end end function handleEvent(eventID, ...) if (eventID) then eventHandlers[eventID](...) end end function unknownEvent() end -- Check if computer is setup for the program function init() term.setCursor(1,2) -- Check if computer has (wireless) network card if (component.isAvailable("modem")) then modem = component.modem -- Open port if closed if (not modem.isOpen(port)) then modem.open(port) end else print("Please insert a (Wireless) Network Card") os.exit(false) end modem.broadcast(port, srlz({action="hello"})) print("Finding server...") getServerTimerID = event.timer(10, serverNotFound) end function update() send({action="get", value="data"}) visual.drawDate() end visual.init() init() while true do handleEvent(event.pull()) end
gpl-2.0
liangxiegame/BitCasual
Client/src/framework/crypto.lua
20
4963
--[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] -------------------------------- -- @module crypto --[[-- 加解密、数据编码 ]] local crypto = {} -- start -- -------------------------------- -- 使用 AES256 算法加密内容 -- @function [parent=#crypto] encryptAES256 -- @param string plaintext 明文字符串 -- @param string key 密钥字符串 -- @return string#string ret (return value: string) 加密后的字符串 -- end -- function crypto.encryptAES256(plaintext, key) plaintext = tostring(plaintext) key = tostring(key) return cc.Crypto:encryptAES256(plaintext, string.len(plaintext), key, string.len(key)) end -- start -- -------------------------------- -- 使用 AES256 算法解密内容 -- @function [parent=#crypto] decryptAES256 -- @param string ciphertext 加密后的字符串 -- @param string key 密钥字符串 -- @return string#string ret (return value: string) 明文字符串 -- end -- function crypto.decryptAES256(ciphertext, key) ciphertext = tostring(ciphertext) key = tostring(key) return cc.Crypto:decryptAES256(ciphertext, string.len(ciphertext), key, string.len(key)) end -- start -- -------------------------------- -- 使用 XXTEA 算法加密内容 -- @function [parent=#crypto] encryptXXTEA -- @param string plaintext 明文字符串 -- @param string key 密钥字符串 -- @return string#string ret (return value: string) 加密后的字符串 -- end -- function crypto.encryptXXTEA(plaintext, key) plaintext = tostring(plaintext) key = tostring(key) return cc.Crypto:encryptXXTEA(plaintext, string.len(plaintext), key, string.len(key)) end -- start -- -------------------------------- -- 使用 XXTEA 算法解密内容 -- @function [parent=#crypto] decryptXXTEA -- @param string ciphertext 加密后的字符串 -- @param string key 密钥字符串 -- @return string#string ret (return value: string) 明文字符串 -- end -- function crypto.decryptXXTEA(ciphertext, key) ciphertext = tostring(ciphertext) key = tostring(key) return cc.Crypto:decryptXXTEA(ciphertext, string.len(ciphertext), key, string.len(key)) end -- start -- -------------------------------- -- 使用 BASE64 算法编码内容 -- @function [parent=#crypto] encodeBase64 -- @param string plaintext 原文字符串 -- @return string#string ret (return value: string) 编码后的字符串 -- end -- function crypto.encodeBase64(plaintext) plaintext = tostring(plaintext) return cc.Crypto:encodeBase64(plaintext, string.len(plaintext)) end -- start -- -------------------------------- -- 使用 BASE64 算法解码内容 -- @function [parent=#crypto] decodeBase64 -- @param string ciphertext 编码后的字符串 -- @return string#string ret (return value: string) 原文字符串 -- end -- function crypto.decodeBase64(ciphertext) ciphertext = tostring(ciphertext) return cc.Crypto:decodeBase64(ciphertext) end -- start -- -------------------------------- -- 计算内容的 MD5 码 -- @function [parent=#crypto] md5 -- @param string input 内容字符串 -- @param boolean isRawOutput 是否返回二进制 MD5 码 -- @return string#string ret (return value: string) MD5 字符串 -- end -- function crypto.md5(input, isRawOutput) input = tostring(input) if type(isRawOutput) ~= "boolean" then isRawOutput = false end return cc.Crypto:MD5(input, isRawOutput) end -- start -- -------------------------------- -- 计算文件的 MD5 码 -- @function [parent=#crypto] md5file -- @param string path 文件路径 -- @return string#string ret (return value: string) MD5 字符串 -- end -- function crypto.md5file(path) if not path then printError("crypto.md5file() - invalid filename") return nil end path = tostring(path) if DEBUG > 1 then printInfo("crypto.md5file() - filename: %s", path) end return cc.Crypto:MD5File(path) end return crypto
mit
sjznxd/lc-20121230
applications/luci-diag-devinfo/luasrc/controller/luci_diag/netdiscover_common.lua
76
3146
--[[ Luci diag - Diagnostics controller module (c) 2009 Daniel Dickinson 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 ]]-- module("luci.controller.luci_diag.netdiscover_common", package.seeall) require("luci.i18n") require("luci.util") require("luci.sys") require("luci.cbi") require("luci.model.uci") local translate = luci.i18n.translate local DummyValue = luci.cbi.DummyValue local SimpleSection = luci.cbi.SimpleSection function index() return -- no-op end function get_params() local netdiscover_uci = luci.model.uci.cursor() netdiscover_uci:load("luci_devinfo") local nettable = netdiscover_uci:get_all("luci_devinfo") local i local subnet local netdout local outnets = {} i = next(nettable, nil) while (i) do if (netdiscover_uci:get("luci_devinfo", i) == "netdiscover_scannet") then local scannet = netdiscover_uci:get_all("luci_devinfo", i) if scannet["subnet"] and (scannet["subnet"] ~= "") and scannet["enable"] and ( scannet["enable"] == "1") then local output = "" local outrow = {} outrow["interface"] = scannet["interface"] outrow["timeout"] = 10 local timeout = tonumber(scannet["timeout"]) if timeout and ( timeout > 0 ) then outrow["timeout"] = scannet["timeout"] end outrow["repeat_count"] = 1 local repcount = tonumber(scannet["repeat_count"]) if repcount and ( repcount > 0 ) then outrow["repeat_count"] = scannet["repeat_count"] end outrow["sleepreq"] = 100 local repcount = tonumber(scannet["sleepreq"]) if repcount and ( repcount > 0 ) then outrow["sleepreq"] = scannet["sleepreq"] end outrow["subnet"] = scannet["subnet"] outrow["output"] = output outnets[i] = outrow end end i = next(nettable, i) end return outnets end function command_function(outnets, i) local interface = luci.controller.luci_diag.devinfo_common.get_network_device(outnets[i]["interface"]) return "/usr/bin/netdiscover-to-devinfo " .. outnets[i]["subnet"] .. " " .. interface .. " " .. outnets[i]["timeout"] .. " -r " .. outnets[i]["repeat_count"] .. " -s " .. outnets[i]["sleepreq"] .. " </dev/null" end function action_links(netdiscovermap, mini) s = netdiscovermap:section(SimpleSection, "", translate("Actions")) b = s:option(DummyValue, "_config", translate("Configure Scans")) b.value = "" if (mini) then b.titleref = luci.dispatcher.build_url("mini", "network", "netdiscover_devinfo_config") else b.titleref = luci.dispatcher.build_url("admin", "network", "diag_config", "netdiscover_devinfo_config") end b = s:option(DummyValue, "_scans", translate("Repeat Scans (this can take a few minutes)")) b.value = "" if (mini) then b.titleref = luci.dispatcher.build_url("mini", "diag", "netdiscover_devinfo") else b.titleref = luci.dispatcher.build_url("admin", "status", "netdiscover_devinfo") end end
apache-2.0
sjznxd/lc-20121230
applications/luci-firewall/luasrc/model/cbi/firewall/forwards.lua
85
3942
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2010-2012 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local ds = require "luci.dispatcher" local ft = require "luci.tools.firewall" m = Map("firewall", translate("Firewall - Port Forwards"), translate("Port forwarding allows remote computers on the Internet to \ connect to a specific computer or service within the \ private LAN.")) -- -- Port Forwards -- s = m:section(TypedSection, "redirect", translate("Port Forwards")) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true s.sortable = true s.extedit = ds.build_url("admin/network/firewall/forwards/%s") s.template_addremove = "firewall/cbi_addforward" function s.create(self, section) local n = m:formvalue("_newfwd.name") local p = m:formvalue("_newfwd.proto") local E = m:formvalue("_newfwd.extzone") local e = m:formvalue("_newfwd.extport") local I = m:formvalue("_newfwd.intzone") local a = m:formvalue("_newfwd.intaddr") local i = m:formvalue("_newfwd.intport") if p == "other" or (p and a) then created = TypedSection.create(self, section) self.map:set(created, "target", "DNAT") self.map:set(created, "src", E or "wan") self.map:set(created, "dest", I or "lan") self.map:set(created, "proto", (p ~= "other") and p or "all") self.map:set(created, "src_dport", e) self.map:set(created, "dest_ip", a) self.map:set(created, "dest_port", i) self.map:set(created, "name", n) end if p ~= "other" then created = nil end end function s.parse(self, ...) TypedSection.parse(self, ...) if created then m.uci:save("firewall") luci.http.redirect(ds.build_url( "admin/network/firewall/redirect", created )) end end function s.filter(self, sid) return (self.map:get(sid, "target") ~= "SNAT") end ft.opt_name(s, DummyValue, translate("Name")) local function forward_proto_txt(self, s) return "%s-%s" %{ translate("IPv4"), ft.fmt_proto(self.map:get(s, "proto"), self.map:get(s, "icmp_type")) or "TCP+UDP" } end local function forward_src_txt(self, s) local z = ft.fmt_zone(self.map:get(s, "src"), translate("any zone")) local a = ft.fmt_ip(self.map:get(s, "src_ip"), translate("any host")) local p = ft.fmt_port(self.map:get(s, "src_port")) local m = ft.fmt_mac(self.map:get(s, "src_mac")) if p and m then return translatef("From %s in %s with source %s and %s", a, z, p, m) elseif p or m then return translatef("From %s in %s with source %s", a, z, p or m) else return translatef("From %s in %s", a, z) end end local function forward_via_txt(self, s) local a = ft.fmt_ip(self.map:get(s, "src_dip"), translate("any router IP")) local p = ft.fmt_port(self.map:get(s, "src_dport")) if p then return translatef("Via %s at %s", a, p) else return translatef("Via %s", a) end end match = s:option(DummyValue, "match", translate("Match")) match.rawhtml = true match.width = "50%" function match.cfgvalue(self, s) return "<small>%s<br />%s<br />%s</small>" % { forward_proto_txt(self, s), forward_src_txt(self, s), forward_via_txt(self, s) } end dest = s:option(DummyValue, "dest", translate("Forward to")) dest.rawhtml = true dest.width = "40%" function dest.cfgvalue(self, s) local z = ft.fmt_zone(self.map:get(s, "dest"), translate("any zone")) local a = ft.fmt_ip(self.map:get(s, "dest_ip"), translate("any host")) local p = ft.fmt_port(self.map:get(s, "dest_port")) or ft.fmt_port(self.map:get(s, "src_dport")) if p then return translatef("%s, %s in %s", a, p, z) else return translatef("%s in %s", a, z) end end ft.opt_enabled(s, Flag, translate("Enable")).width = "1%" return m
apache-2.0
gdevillele/dockercraft
world/Plugins/Core/web_players.lua
6
12958
-- web_players.lua -- Implements the Players tab in the webadmin local ins = table.insert local con = table.concat --- Enumerates all players currently connected to the server -- Returns an array-table in which each item has PlayerName, PlayerUUID and WorldName local function EnumAllPlayers() local res = {} -- Insert each player into the table: cRoot:Get():ForEachPlayer( function(a_Player) ins(res, { PlayerName = a_Player:GetName(), PlayerUUID = a_Player:GetUUID(), WorldName = a_Player:GetWorld():GetName(), EntityID = a_Player:GetUniqueID() }) end ) return res end --- Returns the HTML for a single table row describing the specified player -- a_Player is the player item, a table containing PlayerName, PlayerUUID, WorldName and EntityID, as -- returned by EnumAllPlayers local function GetPlayerRow(a_Player) -- Check params: assert(type(a_Player) == "table") assert(type(a_Player.PlayerName) == "string") assert(type(a_Player.PlayerUUID) == "string") assert(type(a_Player.WorldName) == "string") assert(type(a_Player.EntityID) == "number") local Row = {"<tr>"} -- First column: player name: ins(Row, "<td>") ins(Row, cWebAdmin:GetHTMLEscapedString(a_Player.PlayerName)) ins(Row, "</td>") -- Second column: rank: local RankName = cWebAdmin:GetHTMLEscapedString(cRankManager:GetPlayerRankName(a_Player.PlayerUUID)) if (RankName == "") then RankName = cWebAdmin:GetHTMLEscapedString(cRankManager:GetDefaultRank()) end ins(Row, "<td>") ins(Row, RankName) ins(Row, "</td>") -- Third row: actions: local PlayerIdent = { WorldName = a_Player.WorldName, EntityID = a_Player.EntityID, PlayerName = a_Player.PlayerName, PlayerUUID = a_Player.PlayerUUID, } ins(Row, "<td><form method='GET' style='float: left'>") ins(Row, GetFormButton("details", "View details", PlayerIdent)) ins(Row, "</form> <form method='GET' style='float: left'>") ins(Row, GetFormButton("sendpm", "Send PM", PlayerIdent)) ins(Row, "</form> <form method='POST' style='float: left'>") ins(Row, GetFormButton("kick", "Kick", PlayerIdent)) ins(Row, "</form></td>") -- Finish the row: ins(Row, "</tr>") return con(Row) end --- Displays the Position details table in the Player details page local function GetPositionDetails(a_PlayerIdent) -- Get the player info: local PlayerInfo = {} local World = cRoot:Get():GetWorld(a_PlayerIdent.WorldName) if (World == nil) then return HTMLError("Error querying player position details - no world.") end World:DoWithEntityByID(a_PlayerIdent.EntityID, function(a_Entity) if not(a_Entity:IsPlayer()) then return end local Player = tolua.cast(a_Entity, "cPlayer") PlayerInfo.Pos = Player:GetPosition() PlayerInfo.LastBedPos = Player:GetLastBedPos() PlayerInfo.Found = true -- TODO: Other info? end ) -- If the player is not present (disconnected in the meantime), display no info: if not(PlayerInfo.Found) then return "" end -- Display the current world and coords: local Page = { "<table><tr><th>Current world</th><td>", cWebAdmin:GetHTMLEscapedString(a_PlayerIdent.WorldName), "</td></tr><tr><th>Position</th><td>X: ", tostring(math.floor(PlayerInfo.Pos.x * 1000) / 1000), "<br/>Y: ", tostring(math.floor(PlayerInfo.Pos.y * 1000) / 1000), "<br/>Z: ", tostring(math.floor(PlayerInfo.Pos.z * 1000) / 1000), "</td></tr><tr><th>Last bed position</th><td>X: ", tostring(PlayerInfo.LastBedPos.x), "<br/>Y: ", tostring(PlayerInfo.LastBedPos.y), "<br/>Z: ", tostring(PlayerInfo.LastBedPos.z), "</td></tr></table>" --[[ -- TODO -- Add teleport control page: "<h4>Teleport control</h4><table><th>Spawn</th><td><form method='POST'>", GetFormButton("teleportcoord", "Teleport to spawn", a_PlayerIdent) --]] } return con(Page) end --- Displays the Rank details table in the Player details page local function GetRankDetails(a_PlayerIdent) -- Display the current rank and its permissions: local RankName = cWebAdmin:GetHTMLEscapedString(cRankManager:GetPlayerRankName(a_PlayerIdent.PlayerUUID)) if (RankName == "") then RankName = cWebAdmin:GetHTMLEscapedString(cRankManager:GetDefaultRank()) end local Permissions = cRankManager:GetPlayerPermissions(a_PlayerIdent.PlayerUUID) table.sort(Permissions) local Page = { "<h4>Rank</h4><table><tr><th>Current rank</th><td>", RankName, "</td></tr><tr><th>Permissions</th><td>", con(Permissions, "<br/>"), "</td></tr>", } -- Let the admin change the rank using a combobox: ins(Page, "<tr><th>Change rank</th><td><form method='POST'><select name='RankName'>") local AllRanks = cRankManager:GetAllRanks() table.sort(AllRanks) for _, rank in ipairs(AllRanks) do local HTMLRankName = cWebAdmin:GetHTMLEscapedString(rank) ins(Page, "<option value='") ins(Page, HTMLRankName) if (HTMLRankName == RankName) then ins(Page, "' selected>") else ins(Page, "'>") end ins(Page, HTMLRankName) ins(Page, "</option>") end ins(Page, "</select>") ins(Page, GetFormButton("setrank", "Change rank", a_PlayerIdent)) ins(Page, "</form></td></tr></table>") return con(Page) end --- Displays the main Players page -- Contains a per-world tables of all the players connected to the server local function ShowMainPlayersPage(a_Request) -- Get all players: local AllPlayers = EnumAllPlayers() -- Get all worlds: local PerWorldPlayers = {} -- Contains a map: WorldName -> {Players} local WorldNames = {} -- Contains an array of world names cRoot:Get():ForEachWorld( function(a_World) local WorldName = a_World:GetName() PerWorldPlayers[WorldName] = {} ins(WorldNames, WorldName) end ) table.sort(WorldNames) -- Translate the list into a per-world list: for _, player in ipairs(AllPlayers) do local PerWorld = PerWorldPlayers[player.WorldName] ins(PerWorld, player) end -- For each world, display a table of players: local Page = {} for _, worldname in ipairs(WorldNames) do ins(Page, "<h4>") ins(Page, worldname) ins(Page, "</h4><table><tr><th>Player</th><th>Rank</th><th>Actions</th></tr>") table.sort(PerWorldPlayers[worldname], function (a_Player1, a_Player2) return (a_Player1.PlayerName < a_Player2.PlayerName) end ) for _, player in ipairs(PerWorldPlayers[worldname]) do ins(Page, GetPlayerRow(player)) end ins(Page, "</table><p>Total players in world: ") ins(Page, tostring(#PerWorldPlayers[worldname])) ins(Page, "</p>") end return con(Page) end --- Displays the player details page local function ShowDetailsPage(a_Request) -- Check params: local WorldName = a_Request.PostParams["WorldName"] local EntityID = a_Request.PostParams["EntityID"] local PlayerName = a_Request.PostParams["PlayerName"] local PlayerUUID = a_Request.PostParams["PlayerUUID"] if ((WorldName == nil) or (EntityID == nil) or (PlayerName == nil) or (PlayerUUID == nil)) then return HTMLError("Bad request, missing parameters.") end -- Stuff the parameters into a table: local PlayerIdent = { PlayerName = PlayerName, WorldName = WorldName, EntityID = EntityID, PlayerUUID = PlayerUUID, } -- Add the header: local Page = { "<p>Back to <a href='/", a_Request.Path, "'>player list</a>.</p>", } -- Display the position details: ins(Page, GetPositionDetails(PlayerIdent)) -- Display the rank details: ins(Page, GetRankDetails(PlayerIdent)) return con(Page) end --- Handles the KickPlayer button in the main page -- Kicks the player and redirects the admin back to the player list local function ShowKickPlayerPage(a_Request) -- Check params: local WorldName = a_Request.PostParams["WorldName"] local EntityID = a_Request.PostParams["EntityID"] local PlayerName = a_Request.PostParams["PlayerName"] if ((WorldName == nil) or (EntityID == nil) or (PlayerName == nil)) then return HTMLError("Bad request, missing parameters.") end -- Get the world: local World = cRoot:Get():GetWorld(WorldName) if (World == nil) then return HTMLError("Bad request, no such world.") end -- Kick the player: World:DoWithEntityByID(EntityID, function(a_Entity) if (a_Entity:IsPlayer()) then local Client = tolua.cast(a_Entity, "cPlayer"):GetClientHandle() if (Client ~= nil) then Client:Kick(a_Request.PostParams["Reason"] or "Kicked from webadmin") else LOG("Client is nil") end end end ) -- Redirect the admin back to the player list: return "<p>Player kicked. <a href='/" .. a_Request.Path .. "'>Return to player list</a>.</p>" end --- Displays the SendPM subpage allowing the admin to send a PM to the player local function ShowSendPMPage(a_Request) -- Check params: local WorldName = a_Request.PostParams["WorldName"] local EntityID = a_Request.PostParams["EntityID"] local PlayerName = a_Request.PostParams["PlayerName"] if ((WorldName == nil) or (EntityID == nil) or (PlayerName == nil)) then return HTMLError("Bad request, missing parameters.") end -- Show the form for entering the message: local PlayerIdent = { PlayerName = PlayerName, WorldName = WorldName, EntityID = EntityID, } return table.concat({ "<h4>Send a message</h4><table><tr><th>Player</th><td>", cWebAdmin:GetHTMLEscapedString(PlayerName), "</td></tr><tr><th>Message</th><td><form method='POST'><input type='text' name='Msg' size=50/>", "</td></tr><tr><th/><td>", GetFormButton("sendpmproc", "Send message", PlayerIdent), "</td></tr></table>" }) end --- Handles the message form from the SendPM page -- Sends the PM, redirects the admin back to the player list local function ShowSendPMProcPage(a_Request) -- Check params: local WorldName = a_Request.PostParams["WorldName"] local EntityID = a_Request.PostParams["EntityID"] local PlayerName = a_Request.PostParams["PlayerName"] local Msg = a_Request.PostParams["Msg"] if ((WorldName == nil) or (EntityID == nil) or (PlayerName == nil) or (Msg == nil)) then return HTMLError("Bad request, missing parameters.") end -- Send the PM: local World = cRoot:Get():GetWorld(WorldName) if (World ~= nil) then World:DoWithEntityByID(EntityID, function(a_Entity) if (a_Entity:IsPlayer()) then SendMessage(tolua.cast(a_Entity, "cPlayer"), Msg) end end ) end -- Redirect the admin back to the player list: return "<p>Message sent. <a href='/" .. a_Request.Path .. "'>Return to player list</a>.</p>" end --- Processes the SetRank form in the player details page -- Sets the player's rank and redirects the admin back to the player details page local function ShowSetRankPage(a_Request) -- Check params: local WorldName = a_Request.PostParams["WorldName"] local EntityID = a_Request.PostParams["EntityID"] local PlayerName = a_Request.PostParams["PlayerName"] local PlayerUUID = a_Request.PostParams["PlayerUUID"] local RankName = a_Request.PostParams["RankName"] if ((WorldName == nil) or (EntityID == nil) or (PlayerName == nil) or (PlayerUUID == nil) or (RankName == nil)) then return HTMLError("Bad request, missing parameters.") end -- Change the player's rank: cRankManager:SetPlayerRank(PlayerUUID, PlayerName, RankName) -- Update each in-game player: cRoot:Get():ForEachPlayer( function(a_CBPlayer) if (a_CBPlayer:GetName() == PlayerName) then a_CBPlayer:SendMessage("You were assigned the rank " .. RankName .. " by webadmin.") a_CBPlayer:LoadRank() end end ) -- Redirect the admin back to the player list: return con({ "<p>Rank changed. <a href='/", a_Request.Path, "?subpage=details&PlayerName=", cWebAdmin:GetHTMLEscapedString(PlayerName), "&PlayerUUID=", cWebAdmin:GetHTMLEscapedString(PlayerUUID), "&WorldName=", cWebAdmin:GetHTMLEscapedString(WorldName), "&EntityID=", cWebAdmin:GetHTMLEscapedString(EntityID), "'>Return to player details</a>.</p>" }) end --- Handlers for the individual subpages in this tab -- Each item maps a subpage name to a handler function that receives a HTTPRequest object and returns the HTML to return local g_SubpageHandlers = { [""] = ShowMainPlayersPage, ["details"] = ShowDetailsPage, ["kick"] = ShowKickPlayerPage, ["sendpm"] = ShowSendPMPage, ["sendpmproc"] = ShowSendPMProcPage, ["setrank"] = ShowSetRankPage, } --- Handles the web request coming from MCS -- Returns the entire tab's HTML contents, based on the player's request function HandleRequest_Players(a_Request) local Subpage = (a_Request.PostParams["subpage"] or "") local Handler = g_SubpageHandlers[Subpage] if (Handler == nil) then return HTMLError("An internal error has occurred, no handler for subpage " .. Subpage .. ".") end local PageContent = Handler(a_Request) --[[ -- DEBUG: Save content to a file for debugging purposes: local f = io.open("players.html", "wb") if (f ~= nil) then f:write(PageContent) f:close() end --]] return PageContent end
apache-2.0
nimaghorbani/dozdi10
plugins/Moderation.lua
4
10016
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then local username = v.username data[tostring(msg.to.id)] = { moderators = {[tostring(member_id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as moderator for this group.') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) else if data[tostring(msg.to.id)] then return 'Group is already added.' end if msg.from.username then username = msg.from.username else username = msg.from.print_name end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={[tostring(msg.from.id)] = username}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added, and @'..username..' has been promoted as moderator for this group.' end end local function gpadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not Global admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'no', lock_photo = 'no', lock_member = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added.' end local function gprem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not Global admin" end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if not data[tostring(msg.to.id)] then return 'Group is not added.' end data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return 'Group has been removed' end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function admin_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 Global 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 Global admin.') end local function admin_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 Global admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Global 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 == 'mpromote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'mdemote' then return demote(receiver, member_username, member_id) elseif mod_cmd == 'gprom' then return admin_promote(receiver, member_username, member_id) elseif mod_cmd == 'gdem' then return admin_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = 'List of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message .. '- '..v..' [' ..k.. '] \n' end return message end local function admin_list(msg) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if next(data['admins']) == nil then --fix way return 'No admin available.' end local message = 'List for Bot admins:\n' for k,v in pairs(data['admins']) do message = message .. '- ' .. v ..' ['..k..'] \n' end return message end function run(msg, matches) if matches[1] == 'debug' then return debugs(msg) end if not is_chat_msg(msg) then return "Only works on group" end local mod_cmd = matches[1] local receiver = get_receiver(msg) if matches[1] == 'gpadd' then return modadd(msg) end if matches[1] == 'gprem' then return modrem(msg) end if matches[1] == 'mpromote' and matches[2] then if not is_momod(msg) then return "Only moderator can promote member" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'mdemote' and matches[2] then if not is_momod(msg) then return "Only moderator can demote member" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then return modlist(msg) end if matches[1] == 'gprom' then if not is_admin(msg) then return "Only sudo can promote user as global admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'gdem' then if not is_admin(msg) then return "Only sudo can promote user as admin" end local member = string.gsub(matches[2], "@", "") chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'adminlist' then if not is_admin(msg) then return 'Admin only!' end return admin_list(msg) end if matches[1] == 'chat_add_user' and msg.action.user.id == our_id then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end end return { description = "Moderation plugin", usage = { moderator = { "!promote <username> : Promote user as moderator", "!demote <username> : Demote user from moderator", "!modlist : List of moderators", }, admin = { "!gpadd : Add group to moderation list", "!gprem : Remove group from moderation list", }, sudo = { "!adminprom <username> : Promote user as admin (must be done from a group)", "!admindem <username> : Demote user from admin (must be done from a group)", }, }, patterns = { "^!(gpadd)$", "^!(gpadd)$", "^!(mpromote) (.*)$", "^!(mdemote) (.*)$", "^!(modlist)$", "^!(gprom) (.*)$", -- sudoers only "^!(gdem) (.*)$", -- sudoers only "^!(adminlist)$", "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_created)$", }, run = run, } end
gpl-2.0
connectFree/lev
lib/lev/querystring.lua
1
1891
--[[ Copyright 2012 The Luvit Authors. Copyright 2012 connectFree k.k. and the lev authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] -- querystring helpers local querystring = {} local string = require('string') local find = string.find local gsub = string.gsub local char = string.char local byte = string.byte local format = string.format local match = string.match local gmatch = string.gmatch function querystring.urldecode(str) str = gsub(str, '+', ' ') str = gsub(str, '%%(%x%x)', function(h) return char(tonumber(h, 16)) end) str = gsub(str, '\r\n', '\n') return str end function querystring.urlencode(str) if str then str = gsub(str, '\n', '\r\n') str = gsub(str, '([^%w ])', function(c) return format('%%%02X', byte(c)) end) str = gsub(str, ' ', '+') end return str end -- parse querystring into table. urldecode tokens function querystring.parse(str, sep, eq) if not sep then sep = '&' end if not eq then eq = '=' end local vars = {} for pair in gmatch(tostring(str), '[^' .. sep .. ']+') do if not find(pair, eq) then vars[querystring.urldecode(pair)] = '' else local key, value = match(pair, '([^' .. eq .. ']*)' .. eq .. '(.*)') if key then vars[querystring.urldecode(key)] = querystring.urldecode(value) end end end return vars end -- module return querystring
apache-2.0
aajjbb/lain
layout/centerwork.lua
2
7866
--[[ Licensed under GNU General Public License v2 * (c) 2018, Eugene Pakhomov * (c) 2016, Henrik Antonsson * (c) 2015, Joerg Jaspert * (c) 2014, projektile * (c) 2013, Luca CPZ * (c) 2010-2012, Peter Hofmann --]] local floor, max, mouse, mousegrabber, screen = math.floor, math.max, mouse, mousegrabber, screen local centerwork = { name = "centerwork", horizontal = { name = "centerworkh" } } local function arrange(p, layout) local t = p.tag or screen[p.screen].selected_tag local wa = p.workarea local cls = p.clients if #cls == 0 then return end local g = {} -- Main column, fixed width and height local mwfact = t.master_width_factor local mainhei = floor(wa.height * mwfact) local mainwid = floor(wa.width * mwfact) local slavewid = wa.width - mainwid local slaveLwid = floor(slavewid / 2) local slaveRwid = slavewid - slaveLwid local slavehei = wa.height - mainhei local slaveThei = floor(slavehei / 2) local slaveBhei = slavehei - slaveThei local nbrFirstSlaves = floor(#cls / 2) local nbrSecondSlaves = floor((#cls - 1) / 2) local slaveFirstDim, slaveSecondDim = 0, 0 if layout.name == "centerwork" then -- vertical if nbrFirstSlaves > 0 then slaveFirstDim = floor(wa.height / nbrFirstSlaves) end if nbrSecondSlaves > 0 then slaveSecondDim = floor(wa.height / nbrSecondSlaves) end g.height = wa.height g.width = mainwid g.x = wa.x + slaveLwid g.y = wa.y else -- horizontal if nbrFirstSlaves > 0 then slaveFirstDim = floor(wa.width / nbrFirstSlaves) end if nbrSecondSlaves > 0 then slaveSecondDim = floor(wa.width / nbrSecondSlaves) end g.height = mainhei g.width = wa.width g.x = wa.x g.y = wa.y + slaveThei end g.width = max(g.width, 1) g.height = max(g.height, 1) p.geometries[cls[1]] = g -- Auxiliary clients if #cls <= 1 then return end for i = 2, #cls do g = {} local idxChecker, dimToAssign local rowIndex = floor(i/2) if layout.name == "centerwork" then if i % 2 == 0 then -- left slave g.x = wa.x g.y = wa.y + (rowIndex - 1) * slaveFirstDim g.width = slaveLwid idxChecker, dimToAssign = nbrFirstSlaves, slaveFirstDim else -- right slave g.x = wa.x + slaveLwid + mainwid g.y = wa.y + (rowIndex - 1) * slaveSecondDim g.width = slaveRwid idxChecker, dimToAssign = nbrSecondSlaves, slaveSecondDim end -- if last slave in row, use remaining space for it if rowIndex == idxChecker then g.height = wa.y + wa.height - g.y else g.height = dimToAssign end else if i % 2 == 0 then -- top slave g.x = wa.x + (rowIndex - 1) * slaveFirstDim g.y = wa.y g.height = slaveThei idxChecker, dimToAssign = nbrFirstSlaves, slaveFirstDim else -- bottom slave g.x = wa.x + (rowIndex - 1) * slaveSecondDim g.y = wa.y + slaveThei + mainhei g.height = slaveBhei idxChecker, dimToAssign = nbrSecondSlaves, slaveSecondDim end -- if last slave in row, use remaining space for it if rowIndex == idxChecker then g.width = wa.x + wa.width - g.x else g.width = dimToAssign end end g.width = max(g.width, 1) g.height = max(g.height, 1) p.geometries[cls[i]] = g end end local function mouse_resize_handler(c, _, _, _, orientation) local wa = c.screen.workarea local mwfact = c.screen.selected_tag.master_width_factor local g = c:geometry() local offset = 0 local cursor = "cross" local corner_coords if orientation == 'vertical' then if g.height + 15 >= wa.height then offset = g.height * .5 cursor = "sb_h_double_arrow" elseif not (g.y + g.height + 15 > wa.y + wa.height) then offset = g.height end corner_coords = { x = wa.x + wa.width * (1 - mwfact) / 2, y = g.y + offset } else if g.width + 15 >= wa.width then offset = g.width * .5 cursor = "sb_v_double_arrow" elseif not (g.x + g.width + 15 > wa.x + wa.width) then offset = g.width end corner_coords = { y = wa.y + wa.height * (1 - mwfact) / 2, x = g.x + offset } end mouse.coords(corner_coords) local prev_coords = {} mousegrabber.run(function(_mouse) if not c.valid then return false end for _, v in ipairs(_mouse.buttons) do if v then prev_coords = { x = _mouse.x, y = _mouse.y } local new_mwfact if orientation == 'vertical' then new_mwfact = 1 - (_mouse.x - wa.x) / wa.width * 2 else new_mwfact = 1 - (_mouse.y - wa.y) / wa.height * 2 end c.screen.selected_tag.master_width_factor = math.min(math.max(new_mwfact, 0.01), 0.99) return true end end return prev_coords.x == _mouse.x and prev_coords.y == _mouse.y end, cursor) end function centerwork.arrange(p) return arrange(p, centerwork) end function centerwork.horizontal.arrange(p) return arrange(p, centerwork.horizontal) end function centerwork.mouse_resize_handler(c, corner, x, y) return mouse_resize_handler(c, corner, x, y, 'vertical') end function centerwork.horizontal.mouse_resize_handler(c, corner, x, y) return mouse_resize_handler(c, corner, x, y, 'horizontal') end ------------------------------------------------------------------------------- -- make focus.byidx and swap.byidx behave more consistently with other layouts local awful = require("awful") local gears = require("gears") local function compare_position(a, b) if a.x == b.x then return a.y < b.y else return a.x < b.x end end local function clients_by_position() local this = client.focus if this then local sorted = client.focus.first_tag:clients() table.sort(sorted, compare_position) local idx = 0 for i, that in ipairs(sorted) do if this.window == that.window then idx = i end end if idx > 0 then return { sorted = sorted, idx = idx } end end return {} end local function in_centerwork() return client.focus and client.focus.first_tag.layout.name == "centerwork" end centerwork.focus = {} --[[ Drop in replacements for awful.client.focus.byidx and awful.client.swap.byidx that behaves consistently with other layouts --]] function centerwork.focus.byidx(i) if in_centerwork() then local cls = clients_by_position() if cls.idx then local target = cls.sorted[gears.math.cycle(#cls.sorted, cls.idx + i)] awful.client.focus.byidx(0, target) end else awful.client.focus.byidx(i) end end centerwork.swap = {} function centerwork.swap.byidx(i) if in_centerwork() then local cls = clients_by_position() if cls.idx then local target = cls.sorted[gears.math.cycle(#cls.sorted, cls.idx + i)] client.focus:swap(target) end else awful.client.swap.byidx(i) end end return centerwork
gpl-2.0
PedroAlvesV/LuaMidi
src/LuaMidi/bit/numberlua.lua
1
13400
--[[ LUA MODULE bit.numberlua - Bitwise operations implemented in pure Lua as numbers, with Lua 5.2 'bit32' and (LuaJIT) LuaBitOp 'bit' compatibility interfaces. SYNOPSIS local bit = require 'bit.numberlua' print(bit.band(0xff00ff00, 0x00ff00ff)) --> 0xffffffff -- Interface providing strong Lua 5.2 'bit32' compatibility local bit32 = require 'bit.numberlua'.bit32 assert(bit32.band(-1) == 0xffffffff) -- Interface providing strong (LuaJIT) LuaBitOp 'bit' compatibility local bit = require 'bit.numberlua'.bit assert(bit.tobit(0xffffffff) == -1) DESCRIPTION This library implements bitwise operations entirely in Lua. This module is typically intended if for some reasons you don't want to or cannot install a popular C based bit library like BitOp 'bit' [1] (which comes pre-installed with LuaJIT) or 'bit32' (which comes pre-installed with Lua 5.2) but want a similar interface. This modules represents bit arrays as non-negative Lua numbers. [1] It can represent 32-bit bit arrays when Lua is compiled with lua_Number as double-precision IEEE 754 floating point. The module is nearly the most efficient it can be but may be a few times slower than the C based bit libraries and is orders or magnitude slower than LuaJIT bit operations, which compile to native code. Therefore, this library is inferior in performane to the other modules. The `xor` function in this module is based partly on Roberto Ierusalimschy's post in http://lua-users.org/lists/lua-l/2002-09/msg00134.html . The included BIT.bit32 and BIT.bit sublibraries aims to provide 100% compatibility with the Lua 5.2 "bit32" and (LuaJIT) LuaBitOp "bit" library. This compatbility is at the cost of some efficiency since inputted numbers are normalized and more general forms (e.g. multi-argument bitwise operators) are supported. STATUS WARNING: Not all corner cases have been tested and documented. Some attempt was made to make these similar to the Lua 5.2 [2] and LuaJit BitOp [3] libraries, but this is not fully tested and there are currently some differences. Addressing these differences may be improved in the future but it is not yet fully determined how to resolve these differences. The BIT.bit32 library passes the Lua 5.2 test suite (bitwise.lua) http://www.lua.org/tests/5.2/ . The BIT.bit library passes the LuaBitOp test suite (bittest.lua). However, these have not been tested on platforms with Lua compiled with 32-bit integer numbers. API BIT.tobit(x) --> z Similar to function in BitOp. BIT.tohex(x, n) Similar to function in BitOp. BIT.band(x, y) --> z Similar to function in Lua 5.2 and BitOp but requires two arguments. BIT.bor(x, y) --> z Similar to function in Lua 5.2 and BitOp but requires two arguments. BIT.bxor(x, y) --> z Similar to function in Lua 5.2 and BitOp but requires two arguments. BIT.bnot(x) --> z Similar to function in Lua 5.2 and BitOp. BIT.lshift(x, disp) --> z Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift), BIT.rshift(x, disp) --> z Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift), BIT.extract(x, field [, width]) --> z Similar to function in Lua 5.2. BIT.replace(x, v, field, width) --> z Similar to function in Lua 5.2. BIT.bswap(x) --> z Similar to function in Lua 5.2. BIT.rrotate(x, disp) --> z BIT.ror(x, disp) --> z Similar to function in Lua 5.2 and BitOp. BIT.lrotate(x, disp) --> z BIT.rol(x, disp) --> z Similar to function in Lua 5.2 and BitOp. BIT.arshift Similar to function in Lua 5.2 and BitOp. BIT.btest Similar to function in Lua 5.2 with requires two arguments. BIT.bit32 This table contains functions that aim to provide 100% compatibility with the Lua 5.2 "bit32" library. bit32.arshift (x, disp) --> z bit32.band (...) --> z bit32.bnot (x) --> z bit32.bor (...) --> z bit32.btest (...) --> true | false bit32.bxor (...) --> z bit32.extract (x, field [, width]) --> z bit32.replace (x, v, field [, width]) --> z bit32.lrotate (x, disp) --> z bit32.lshift (x, disp) --> z bit32.rrotate (x, disp) --> z bit32.rshift (x, disp) --> z BIT.bit This table contains functions that aim to provide 100% compatibility with the LuaBitOp "bit" library (from LuaJIT). bit.tobit(x) --> y bit.tohex(x [,n]) --> y bit.bnot(x) --> y bit.bor(x1 [,x2...]) --> y bit.band(x1 [,x2...]) --> y bit.bxor(x1 [,x2...]) --> y bit.lshift(x, n) --> y bit.rshift(x, n) --> y bit.arshift(x, n) --> y bit.rol(x, n) --> y bit.ror(x, n) --> y bit.bswap(x) --> y DEPENDENCIES None (other than Lua 5.1 or 5.2). DOWNLOAD/INSTALLATION If using LuaRocks: luarocks install lua-bit-numberlua Otherwise, download <https://github.com/davidm/lua-bit-numberlua/zipball/master>. Alternately, if using git: git clone git://github.com/davidm/lua-bit-numberlua.git cd lua-bit-numberlua Optionally unpack: ./util.mk or unpack and install in LuaRocks: ./util.mk install REFERENCES [1] http://lua-users.org/wiki/FloatingPoint [2] http://www.lua.org/manual/5.2/ [3] http://bitop.luajit.org/ LICENSE (c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (end license) --]] local M = {_TYPE='module', _NAME='bit.numberlua', _VERSION='0.3.1.20120131'} local floor = math.floor local MOD = 2^32 local MODM = MOD-1 local function memoize(f) local mt = {} local t = setmetatable({}, mt) function mt:__index(k) local v = f(k); t[k] = v return v end return t end local function make_bitop_uncached(t, m) local function bitop(a, b) local res,p = 0,1 while a ~= 0 and b ~= 0 do local am, bm = a%m, b%m res = res + t[am][bm]*p a = (a - am) / m b = (b - bm) / m p = p*m end res = res + (a+b)*p return res end return bitop end local function make_bitop(t) local op1 = make_bitop_uncached(t,2^1) local op2 = memoize(function(a) return memoize(function(b) return op1(a, b) end) end) return make_bitop_uncached(op2, 2^(t.n or 1)) end -- ok? probably not if running on a 32-bit int Lua number type platform function M.tobit(x) return x % 2^32 end M.bxor = make_bitop {[0]={[0]=0,[1]=1},[1]={[0]=1,[1]=0}, n=4} local bxor = M.bxor function M.bnot(a) return MODM - a end local bnot = M.bnot function M.band(a,b) return ((a+b) - bxor(a,b))/2 end local band = M.band function M.bor(a,b) return MODM - band(MODM - a, MODM - b) end local bor = M.bor local lshift, rshift -- forward declare function M.rshift(a,disp) -- Lua5.2 insipred if disp < 0 then return lshift(a,-disp) end return floor(a % 2^32 / 2^disp) end rshift = M.rshift function M.lshift(a,disp) -- Lua5.2 inspired if disp < 0 then return rshift(a,-disp) end return (a * 2^disp) % 2^32 end lshift = M.lshift function M.tohex(x, n) -- BitOp style n = n or 8 local up if n <= 0 then if n == 0 then return '' end up = true n = - n end x = band(x, 16^n-1) return ('%0'..n..(up and 'X' or 'x')):format(x) end local tohex = M.tohex function M.extract(n, field, width) -- Lua5.2 inspired width = width or 1 return band(rshift(n, field), 2^width-1) end local extract = M.extract function M.replace(n, v, field, width) -- Lua5.2 inspired width = width or 1 local mask1 = 2^width-1 v = band(v, mask1) -- required by spec? local mask = bnot(lshift(mask1, field)) return band(n, mask) + lshift(v, field) end local replace = M.replace function M.bswap(x) -- BitOp style local a = band(x, 0xff); x = rshift(x, 8) local b = band(x, 0xff); x = rshift(x, 8) local c = band(x, 0xff); x = rshift(x, 8) local d = band(x, 0xff) return lshift(lshift(lshift(a, 8) + b, 8) + c, 8) + d end local bswap = M.bswap function M.rrotate(x, disp) -- Lua5.2 inspired disp = disp % 32 local low = band(x, 2^disp-1) return rshift(x, disp) + lshift(low, 32-disp) end local rrotate = M.rrotate function M.lrotate(x, disp) -- Lua5.2 inspired return rrotate(x, -disp) end local lrotate = M.lrotate M.rol = M.lrotate -- LuaOp inspired M.ror = M.rrotate -- LuaOp insipred function M.arshift(x, disp) -- Lua5.2 inspired local z = rshift(x, disp) if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end return z end local arshift = M.arshift function M.btest(x, y) -- Lua5.2 inspired return band(x, y) ~= 0 end -- -- Start Lua 5.2 "bit32" compat section. -- M.bit32 = {} -- Lua 5.2 'bit32' compatibility local function bit32_bnot(x) return (-1 - x) % MOD end M.bit32.bnot = bit32_bnot local function bit32_bxor(a, b, c, ...) local z if b then a = a % MOD b = b % MOD z = bxor(a, b) if c then z = bit32_bxor(z, c, ...) end return z elseif a then return a % MOD else return 0 end end M.bit32.bxor = bit32_bxor local function bit32_band(a, b, c, ...) local z if b then a = a % MOD b = b % MOD z = ((a+b) - bxor(a,b)) / 2 if c then z = bit32_band(z, c, ...) end return z elseif a then return a % MOD else return MODM end end M.bit32.band = bit32_band local function bit32_bor(a, b, c, ...) local z if b then a = a % MOD b = b % MOD z = MODM - band(MODM - a, MODM - b) if c then z = bit32_bor(z, c, ...) end return z elseif a then return a % MOD else return 0 end end M.bit32.bor = bit32_bor function M.bit32.btest(...) return bit32_band(...) ~= 0 end function M.bit32.lrotate(x, disp) return lrotate(x % MOD, disp) end function M.bit32.rrotate(x, disp) return rrotate(x % MOD, disp) end function M.bit32.lshift(x,disp) if disp > 31 or disp < -31 then return 0 end return lshift(x % MOD, disp) end function M.bit32.rshift(x,disp) if disp > 31 or disp < -31 then return 0 end return rshift(x % MOD, disp) end function M.bit32.arshift(x,disp) x = x % MOD if disp >= 0 then if disp > 31 then return (x >= 0x80000000) and MODM or 0 else local z = rshift(x, disp) if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end return z end else return lshift(x, -disp) end end function M.bit32.extract(x, field, ...) local width = ... or 1 if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end x = x % MOD return extract(x, field, ...) end function M.bit32.replace(x, v, field, ...) local width = ... or 1 if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end x = x % MOD v = v % MOD return replace(x, v, field, ...) end -- -- Start LuaBitOp "bit" compat section. -- M.bit = {} -- LuaBitOp "bit" compatibility function M.bit.tobit(x) x = x % MOD if x >= 0x80000000 then x = x - MOD end return x end local bit_tobit = M.bit.tobit function M.bit.tohex(x, ...) return tohex(x % MOD, ...) end function M.bit.bnot(x) return bit_tobit(bnot(x % MOD)) end local function bit_bor(a, b, c, ...) if c then return bit_bor(bit_bor(a, b), c, ...) elseif b then return bit_tobit(bor(a % MOD, b % MOD)) else return bit_tobit(a) end end M.bit.bor = bit_bor local function bit_band(a, b, c, ...) if c then return bit_band(bit_band(a, b), c, ...) elseif b then return bit_tobit(band(a % MOD, b % MOD)) else return bit_tobit(a) end end M.bit.band = bit_band local function bit_bxor(a, b, c, ...) if c then return bit_bxor(bit_bxor(a, b), c, ...) elseif b then return bit_tobit(bxor(a % MOD, b % MOD)) else return bit_tobit(a) end end M.bit.bxor = bit_bxor function M.bit.lshift(x, n) return bit_tobit(lshift(x % MOD, n % 32)) end function M.bit.rshift(x, n) return bit_tobit(rshift(x % MOD, n % 32)) end function M.bit.arshift(x, n) return bit_tobit(arshift(x % MOD, n % 32)) end function M.bit.rol(x, n) return bit_tobit(lrotate(x % MOD, n % 32)) end function M.bit.ror(x, n) return bit_tobit(rrotate(x % MOD, n % 32)) end function M.bit.bswap(x) return bit_tobit(bswap(x % MOD)) end return M
mit
sjznxd/lc-20121230
applications/luci-radvd/luasrc/model/cbi/radvd/dnssl.lua
82
2276
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: rdnss.lua 6715 2011-01-13 20:03:40Z jow $ ]]-- local sid = arg[1] local utl = require "luci.util" m = Map("radvd", translatef("Radvd - DNSSL"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) m.redirect = luci.dispatcher.build_url("admin/network/radvd") if m.uci:get("radvd", sid) ~= "dnssl" then luci.http.redirect(m.redirect) return end s = m:section(NamedSection, sid, "interface", translate("DNSSL Configuration")) s.addremove = false -- -- General -- o = s:option(Flag, "ignore", translate("Enable")) o.rmempty = false function o.cfgvalue(...) local v = Flag.cfgvalue(...) return v == "1" and "0" or "1" end function o.write(self, section, value) Flag.write(self, section, value == "1" and "0" or "1") end o = s:option(Value, "interface", translate("Interface"), translate("Specifies the logical interface name this section belongs to")) o.template = "cbi/network_netlist" o.nocreate = true o.optional = false function o.formvalue(...) return Value.formvalue(...) or "-" end function o.validate(self, value) if value == "-" then return nil, translate("Interface required") end return value end function o.write(self, section, value) m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "interface", value) end o = s:option(DynamicList, "suffix", translate("Suffix"), translate("Advertised Domain Suffixes")) o.optional = false o.rmempty = false o.datatype = "hostname" function o.cfgvalue(self, section) local l = { } local v = m.uci:get_list("radvd", section, "suffix") for v in utl.imatch(v) do l[#l+1] = v end return l end o = s:option(Value, "AdvDNSSLLifetime", translate("Lifetime"), translate("Specifies the maximum duration how long the DNSSL entries are used for name resolution.")) o.datatype = 'or(uinteger,"infinity")' o.placeholder = 1200 return m
apache-2.0
akaStiX/premake-core
tests/api/test_string_kind.lua
9
1397
-- -- tests/api/test_string_kind.lua -- Tests the string API value type. -- Copyright (c) 2012 Jason Perkins and the Premake project -- T.api_string_kind = {} local suite = T.api_string_kind local api = premake.api -- -- Setup and teardown -- function suite.setup() api.register { name = "testapi", kind = "string", scope = "project", allowed = { "One", "Two", "Three" }, } test.createWorkspace() end function suite.teardown() testapi = nil end -- -- String values should be stored as-is. -- function suite.storesString_onStringValue() testapi "One" test.isequal("One", api.scope.project.testapi) end -- -- New values should overwrite old ones. -- function suite.overwritesPreviousValues() testapi "One" testapi "Two" test.isequal("Two", api.scope.project.testapi) end -- -- An error occurs if a table value is assigned to a string field. -- function suite.raisesError_onTableValue() ok, err = pcall(function () testapi { "One", "Two" } end) test.isfalse(ok) end -- -- Raises an error on a disallowed value. -- function suite.raisesError_onDisallowedValue() ok, err = pcall(function () testapi "NotAllowed" end) test.isfalse(ok) end -- -- If allowed values present, converts to provided case. -- function suite.convertsCase_onAllowedValue() testapi "oNe" test.isequal("One", api.scope.project.testapi) end
bsd-3-clause
ga526321/prat
modules/Experimental.lua
2
1316
Prat:AddModuleToLoad(function() local PRAT_MODULE = Prat:RequestModuleName("Experimental") if PRAT_MODULE == nil then return end PE = Prat:NewModule(PRAT_MODULE, "AceHook-3.0") function PE:OnModuleEnable() CHAT_CONFIG_CHAT_RIGHT[7] = { text = CHAT_MSG_WHISPER_INFORM, type = "WHISPER_INFORM", checked = function () return IsListeningForMessageType("WHISPER"); end; func = function (checked) ToggleChatMessageGroup(checked, "WHISPER"); end; } CHAT_CONFIG_CHAT_LEFT[#CHAT_CONFIG_CHAT_LEFT].text = CHAT_MSG_WHISPER Prat.RegisterChatEvent(self, Prat.Events.ENABLED, function() Prat:Print("|cffff4040EXPERIMENTAL MODULE ENABLED|r") end ) end --local function DBG_FONT(...) DBG:Debug("FONT", ...) end --local function DUMP_FONT(...) DBG:Dump("FONT", ...) end function PE:OnModuleDisable() end PE.lines = {} function PE:GetLines() wipe(self.lines) self:AddLines(self.lines, ChatFrame1:GetRegions()) end function PE:AddLines(lines, ...) for i=select("#", ...),1,-1 do local x = select(i, ...) if x:GetObjectType() == "FontString" and not x:GetName() then table.insert(lines, x) end end end --[[------------------------------------------------ Core Functions ------------------------------------------------]]-- return end ) -- Prat:AddModuleToLoad
gpl-3.0
aqasaeed/creed
plugins/welcome.lua
190
3526
local add_user_cfg = load_from_file('data/add_user_cfg.lua') local function template_add_user(base, to_username, from_username, chat_name, chat_id) base = base or '' to_username = '@' .. (to_username or '') from_username = '@' .. (from_username or '') chat_name = string.gsub(chat_name, '_', ' ') or '' chat_id = "chat#id" .. (chat_id or '') if to_username == "@" then to_username = '' end if from_username == "@" then from_username = '' end base = string.gsub(base, "{to_username}", to_username) base = string.gsub(base, "{from_username}", from_username) base = string.gsub(base, "{chat_name}", chat_name) base = string.gsub(base, "{chat_id}", chat_id) return base end function chat_new_user_link(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.from.username local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')' local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end function chat_new_user(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.action.user.username local from_username = msg.from.username local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end local function description_rules(msg, nama) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then local about = "" local rules = "" if data[tostring(msg.to.id)]["description"] then about = data[tostring(msg.to.id)]["description"] about = "\nAbout :\n"..about.."\n" end if data[tostring(msg.to.id)]["rules"] then rules = data[tostring(msg.to.id)]["rules"] rules = "\nRules :\n"..rules.."\n" end local sambutan = "Hi "..nama.."\nWelcome to '"..string.gsub(msg.to.print_name, "_", " ").."'\nYou can use /help for see bot commands\n" local text = sambutan..about..rules.."\n" local receiver = get_receiver(msg) send_large_msg(receiver, text, ok_cb, false) end end local function run(msg, matches) if not msg.service then return "Are you trying to troll me?" end --vardump(msg) if matches[1] == "chat_add_user" then if not msg.action.user.username then nama = string.gsub(msg.action.user.print_name, "_", " ") else nama = "@"..msg.action.user.username end chat_new_user(msg) description_rules(msg, nama) elseif matches[1] == "chat_add_user_link" then if not msg.from.username then nama = string.gsub(msg.from.print_name, "_", " ") else nama = "@"..msg.from.username end chat_new_user_link(msg) description_rules(msg, nama) elseif matches[1] == "chat_del_user" then local bye_name = msg.action.user.first_name return 'Bye '..bye_name end end return { description = "Welcoming Message", usage = "send message to new member", patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$", "^!!tgservice (chat_del_user)$", }, run = run }
gpl-2.0
LazyZhu/openwrt-luci-trunk-mod
applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/netlink.lua
68
2502
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. require("luci.sys") local devices = luci.sys.net.devices() m = Map("luci_statistics", translate("Netlink Plugin Configuration"), translate( "The netlink plugin collects extended informations like " .. "qdisc-, class- and filter-statistics for selected interfaces." )) -- collectd_netlink config section s = m:section( NamedSection, "collectd_netlink", "luci_statistics" ) -- collectd_netlink.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_netlink.interfaces (Interface) interfaces = s:option( MultiValue, "Interfaces", translate("Basic monitoring") ) interfaces.widget = "select" interfaces.optional = true interfaces.size = #devices + 1 interfaces:depends( "enable", 1 ) interfaces:value("") for i, v in ipairs(devices) do interfaces:value(v) end -- collectd_netlink.verboseinterfaces (VerboseInterface) verboseinterfaces = s:option( MultiValue, "VerboseInterfaces", translate("Verbose monitoring") ) verboseinterfaces.widget = "select" verboseinterfaces.optional = true verboseinterfaces.size = #devices + 1 verboseinterfaces:depends( "enable", 1 ) verboseinterfaces:value("") for i, v in ipairs(devices) do verboseinterfaces:value(v) end -- collectd_netlink.qdiscs (QDisc) qdiscs = s:option( MultiValue, "QDiscs", translate("Qdisc monitoring") ) qdiscs.widget = "select" qdiscs.optional = true qdiscs.size = #devices + 1 qdiscs:depends( "enable", 1 ) qdiscs:value("") for i, v in ipairs(devices) do qdiscs:value(v) end -- collectd_netlink.classes (Class) classes = s:option( MultiValue, "Classes", translate("Shaping class monitoring") ) classes.widget = "select" classes.optional = true classes.size = #devices + 1 classes:depends( "enable", 1 ) classes:value("") for i, v in ipairs(devices) do classes:value(v) end -- collectd_netlink.filters (Filter) filters = s:option( MultiValue, "Filters", translate("Filter class monitoring") ) filters.widget = "select" filters.optional = true filters.size = #devices + 1 filters:depends( "enable", 1 ) filters:value("") for i, v in ipairs(devices) do filters:value(v) end -- collectd_netlink.ignoreselected (IgnoreSelected) ignoreselected = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") ) ignoreselected.default = 0 ignoreselected:depends( "enable", 1 ) return m
apache-2.0
thinkry/some-mmorpg
3rd/skynet/lualib/snax/gateserver.lua
1
3433
-- 官方提供的gateserver -- 这里注册了PTYPE_SOCKET类型消息的处理函数,所以socket消息会通过netpack.filter处理后,交给MSG来处理 -- 这里的MSG主要做了连接数管理、nodelay管理、有多个消息时调用多次这些“额外操作”,让handler更简化了 local skynet = require "skynet" local netpack = require "netpack" local socketdriver = require "socketdriver" local gateserver = {} local socket -- listen socket local queue -- message queue local maxclient -- max client local client_number = 0 local CMD = setmetatable({}, { __gc = function() netpack.clear(queue) end }) local nodelay = false local connection = {} function gateserver.openclient(fd) if connection[fd] then socketdriver.start(fd) end end function gateserver.closeclient(fd) local c = connection[fd] if c then connection[fd] = false socketdriver.close(fd) end end function gateserver.start(handler) assert(handler.message) assert(handler.connect) function CMD.open( source, conf ) assert(not socket) local address = conf.address or "0.0.0.0" local port = assert(conf.port) maxclient = conf.maxclient or 1024 nodelay = conf.nodelay skynet.error(string.format("Listen on %s:%d", address, port)) socket = socketdriver.listen(address, port) socketdriver.start(socket) if handler.open then return handler.open(source, conf) end end function CMD.close() assert(socket) socketdriver.close(socket) socket = nil end local MSG = {} local function dispatch_msg(fd, msg, sz) if connection[fd] then handler.message(fd, msg, sz) else skynet.error(string.format("Drop message from fd (%d) : %s", fd, netpack.tostring(msg,sz))) end end MSG.data = dispatch_msg local function dispatch_queue() local fd, msg, sz = netpack.pop(queue) if fd then -- may dispatch even the handler.message blocked -- If the handler.message never block, the queue should be empty, so only fork once and then exit. skynet.fork(dispatch_queue) dispatch_msg(fd, msg, sz) for fd, msg, sz in netpack.pop, queue do dispatch_msg(fd, msg, sz) end end end MSG.more = dispatch_queue function MSG.open(fd, msg) if client_number >= maxclient then socketdriver.close(fd) return end if nodelay then socketdriver.nodelay(fd) end connection[fd] = true client_number = client_number + 1 handler.connect(fd, msg) end local function close_fd(fd) local c = connection[fd] if c ~= nil then connection[fd] = nil client_number = client_number - 1 end end function MSG.close(fd) if handler.disconnect then handler.disconnect(fd) end close_fd(fd) end function MSG.error(fd, msg) if handler.error then handler.error(fd, msg) end close_fd(fd) end function MSG.warning(fd, size) if handler.warning then handler.warning(fd, size) end end skynet.register_protocol { name = "socket", id = skynet.PTYPE_SOCKET, -- PTYPE_SOCKET = 6 unpack = function ( msg, sz ) return netpack.filter( queue, msg, sz) end, dispatch = function (_, _, q, type, ...) queue = q if type then MSG[type](...) end end } skynet.start(function() skynet.dispatch("lua", function (_, address, cmd, ...) local f = CMD[cmd] if f then skynet.ret(skynet.pack(f(address, ...))) else skynet.ret(skynet.pack(handler.command(cmd, address, ...))) end end) end) end return gateserver
mit
liangxiegame/BitCasual
Client/src/app/utils/QTimer.lua
1
1851
--[[ 定时器类 ]] QTimer = { m_scheduler = cc.Director:getInstance():getScheduler(), m_timers = {} } --[[ 启动定时器 @param callback 回调方法 @param interval 间隔 @param runCount 运行次数 @param data 数据 @return timerId ]] function QTimer:start(callback, interval, runCount, data) local timerId local onTick = function(dt) callback(dt, data, timerId) if runCount ~= nil then runCount = runCount - 1; if runCount <= 0 then -- 达到指定运行次数,杀掉 self:kill(timerId) end end end timerId = self.m_scheduler:scheduleScriptFunc(onTick, interval, false) self.m_timers[timerId] = 1; return timerId end --[[ 启动无限定时器 ]] function QTimer:forever(callback,interval) local timerId local onTick = function(dt) callback(dt,timerId) end timerId = self.m_scheduler:scheduleScriptFunc(onTick, interval, false) self.m_timers[timerId] = 1 return timerId end --[[ 启动一个只执行一次的定时器 @param callback 回调方法 @param data 数据 ]] function QTimer:runOnce(callback, data) self:start(callback, 0, 1, data) end --[[ 杀掉指定定时器 @param timerId 定时器ID ]] function QTimer:kill(timerId) self.m_scheduler:unscheduleScriptEntry(timerId) self.m_timers[timerId] = nil; end ccDrawQuadBezier(origin, control, destination, segments) --[[ 杀掉所有定时器 ]] function QTimer:killAll() for timerId, flag in pairs(self.m_timers) do self:kill(timerId) end end --[[ 用于测量效率的 ]] local time = 0 function QTimer:beganTime( ) time = os.clock() end function QTimer:endTime(name) if name == nil then name = "time clock" end print(name,string.format("%f",os.clock() - time)) end
mit
LuttyYang/luci
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/proto_ahcp.lua
84
2006
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local device, apn, service, pincode, username, password local ipv6, maxwait, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand mca = s:taboption("ahcp", Value, "multicast_address", translate("Multicast address")) mca.optional = true mca.placeholder = "ff02::cca6:c0f9:e182:5359" mca.datatype = "ip6addr" mca:depends("proto", "ahcp") port = s:taboption("ahcp", Value, "port", translate("Port")) port.optional = true port.placeholder = 5359 port.datatype = "port" port:depends("proto", "ahcp") fam = s:taboption("ahcp", ListValue, "_family", translate("Protocol family")) fam:value("", translate("IPv4 and IPv6")) fam:value("ipv4", translate("IPv4 only")) fam:value("ipv6", translate("IPv6 only")) fam:depends("proto", "ahcp") function fam.cfgvalue(self, section) local v4 = m.uci:get_bool("network", section, "ipv4_only") local v6 = m.uci:get_bool("network", section, "ipv6_only") if v4 then return "ipv4" elseif v6 then return "ipv6" end return "" end function fam.write(self, section, value) if value == "ipv4" then m.uci:set("network", section, "ipv4_only", "true") m.uci:delete("network", section, "ipv6_only") elseif value == "ipv6" then m.uci:set("network", section, "ipv6_only", "true") m.uci:delete("network", section, "ipv4_only") end end function fam.remove(self, section) m.uci:delete("network", section, "ipv4_only") m.uci:delete("network", section, "ipv6_only") end nodns = s:taboption("ahcp", Flag, "no_dns", translate("Disable DNS setup")) nodns.optional = true nodns.enabled = "true" nodns.disabled = "false" nodns.default = nodns.disabled nodns:depends("proto", "ahcp") ltime = s:taboption("ahcp", Value, "lease_time", translate("Lease validity time")) ltime.optional = true ltime.placeholder = 3666 ltime.datatype = "uinteger" ltime:depends("proto", "ahcp")
apache-2.0
MustaphaTR/MustaphaTR-s-D2K-Mod
mods/mtrsd2k/maps/ordos-04/ordos04.lua
1
5415
Base = { Harkonnen = { HRefinery, SHeavyFactory, SLightFactory, HGunTurret1, HGunTurret2, HGunTurret3, HGunTurret4, HGunTurret5, SBarracks, HPower1, HPower2, HPower3, HPower4 }, Smugglers = { SOutpost, SHeavyFactory, SLightFactory, SGunTurret1, SGunTurret2, SGunTurret3, SGunTurret4, SBarracks, SPower1, SPower2, SPower3 } } HarkonnenLightInfantryRushers = { easy = { "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf" }, normal = { "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf" }, hard = { "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "light_inf" } } HarkonnenAttackDelay = { easy = DateTime.Minutes(3) + DateTime.Seconds(30), normal = DateTime.Minutes(2) + DateTime.Seconds(30), hard = DateTime.Minutes(1) + DateTime.Seconds(30) } InitialReinforcements = { Harkonnen = { "combat_tank_h", "combat_tank_h", "quad.mg", "quad.mg" }, Smugglers = { "light_inf", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper" } } LightInfantryRushersPaths = { { HarkonnenEntry1.Location, HarkonnenRally1.Location }, { HarkonnenEntry2.Location, HarkonnenRally2.Location }, { HarkonnenEntry3.Location, HarkonnenRally3.Location } } InitialReinforcementsPaths = { Harkonnen = { HarkonnenEntry4.Location, HarkonnenRally4.Location }, Smugglers = { SmugglerEntry.Location, SmugglerRally.Location } } OrdosReinforcements = { "light_inf", "light_inf", "light_inf", "light_inf" } OrdosPath = { OrdosEntry.Location, OrdosRally.Location } SendHarkonnen = function(path) Trigger.AfterDelay(HarkonnenAttackDelay[Difficulty], function() if player.IsObjectiveCompleted(KillHarkonnen) then return end local units = Reinforcements.ReinforceWithTransport(harkonnen, "carryall.reinforce", HarkonnenLightInfantryRushers[Difficulty], path, { path[1] })[2] Utils.Do(units, function(unit) unit.AttackMove(HarkonnenAttackLocation) IdleHunt(unit) end) end) end Hunt = function(house) Trigger.OnAllKilledOrCaptured(Base[house.Name], function() Utils.Do(house.GetGroundAttackers(), IdleHunt) end) end CheckHarvester = function(house) if DateTime.GameTime % DateTime.Seconds(30) and HarvesterKilled[house.Name] then local units = house.GetActorsByType("harvester") if #units > 0 then HarvesterKilled[house.Name] = false ProtectHarvester(units[1], house) end end end Tick = function() if player.HasNoRequiredUnits() then harkonnen.MarkCompletedObjective(KillOrdosH) smuggler.MarkCompletedObjective(KillOrdosS) smuggler.MarkCompletedObjective(DefendOutpost) end if harkonnen.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillHarkonnen) then Media.DisplayMessage("The Harkonnen have been annihilated!", "Mentat") player.MarkCompletedObjective(KillHarkonnen) end CheckHarvester(harkonnen) CheckHarvester(smuggler) if SOutpost.IsDead then player.MarkFailedObjective(CaptureOutpost) end if SOutpost.Owner == player then player.MarkCompletedObjective(CaptureOutpost) smuggler.MarkFailedObjective(DefendOutpost) end end WorldLoaded = function() harkonnen = Player.GetPlayer("Harkonnen") smuggler = Player.GetPlayer("Smugglers") player = Player.GetPlayer("Ordos") Difficulty = Map.LobbyOption("difficulty") InitObjectives() Camera.Position = OConyard.CenterPosition HarkonnenAttackLocation = OConyard.Location Hunt(harkonnen) Hunt(smuggler) SendHarkonnen(LightInfantryRushersPaths[1]) SendHarkonnen(LightInfantryRushersPaths[2]) SendHarkonnen(LightInfantryRushersPaths[3]) ActivateAI() Actor.Create("upgrade.barracks", true, { Owner = harkonnen }) Actor.Create("upgrade.light", true, { Owner = harkonnen }) Actor.Create("upgrade.barracks", true, { Owner = smuggler }) Actor.Create("upgrade.light", true, { Owner = smuggler }) Trigger.AfterDelay(HarkonnenAttackDelay[Difficulty] - DateTime.Seconds(5), function() Media.PlaySpeechNotification(player, "Reinforce") Reinforcements.Reinforce(player, OrdosReinforcements, OrdosPath) end) Trigger.AfterDelay(HarkonnenAttackDelay[Difficulty], function() Media.DisplayMessage("WARNING: Large force approaching!", "Mentat") end) end InitObjectives = function() Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) KillOrdosH = harkonnen.AddPrimaryObjective("Kill all Ordos units.") KillOrdosS = smuggler.AddSecondaryObjective("Kill all Ordos units.") DefendOutpost = smuggler.AddPrimaryObjective("Don't let the outpost to be captured or destroyed.") CaptureOutpost = player.AddPrimaryObjective("Capture the Smuggler Outpost.") KillHarkonnen = player.AddSecondaryObjective("Destroy the Harkonnen.") Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerLost(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "Lose") end) end) Trigger.OnPlayerWon(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "Win") end) end) end
gpl-3.0
dev-Maximus/ProtectionTeam
libs/lua-redis.lua
580
35599
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
gpl-3.0
sose12/AOS_SHARO56
libs/lua-redis.lua
580
35599
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
gpl-2.0
viszkoktamas/OpenRA
lua/sandbox.lua
84
5098
local sandbox = { _VERSION = "sandbox 0.5", _DESCRIPTION = "A pure-lua solution for running untrusted Lua code.", _URL = "https://github.com/kikito/sandbox.lua", _LICENSE = [[ MIT LICENSE Copyright (c) 2013 Enrique García Cota Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] } -- The base environment is merged with the given env option (or an empty table, if no env provided) -- local BASE_ENV = {} -- List of non-safe packages/functions: -- -- * string.rep: can be used to allocate millions of bytes in 1 operation -- * {set|get}metatable: can be used to modify the metatable of global objects (strings, integers) -- * collectgarbage: can affect performance of other systems -- * dofile: can access the server filesystem -- * _G: It has access to everything. It can be mocked to other things though. -- * load{file|string}: All unsafe because they can grant acces to global env -- * raw{get|set|equal}: Potentially unsafe -- * module|require|module: Can modify the host settings -- * string.dump: Can display confidential server info (implementation of functions) -- * string.rep: Can allocate millions of bytes in one go -- * math.randomseed: Can affect the host sytem -- * io.*, os.*: Most stuff there is non-save -- Safe packages/functions below ([[ _VERSION assert error ipairs next pairs pcall select tonumber tostring type unpack xpcall coroutine.create coroutine.resume coroutine.running coroutine.status coroutine.wrap coroutine.yield math.abs math.acos math.asin math.atan math.atan2 math.ceil math.cos math.cosh math.deg math.exp math.fmod math.floor math.frexp math.huge math.ldexp math.log math.log10 math.max math.min math.modf math.pi math.pow math.rad math.sin math.sinh math.sqrt math.tan math.tanh os.clock os.difftime os.time string.byte string.char string.find string.format string.gmatch string.gsub string.len string.lower string.match string.reverse string.sub string.upper table.insert table.maxn table.remove table.sort ]]):gsub('%S+', function(id) local module, method = id:match('([^%.]+)%.([^%.]+)') if module then BASE_ENV[module] = BASE_ENV[module] or {} BASE_ENV[module][method] = _G[module][method] else BASE_ENV[id] = _G[id] end end) local function protect_module(module, module_name) return setmetatable({}, { __index = module, __newindex = function(_, attr_name, _) error('Can not modify ' .. module_name .. '.' .. attr_name .. '. Protected by the sandbox.') end }) end ('coroutine math os string table'):gsub('%S+', function(module_name) BASE_ENV[module_name] = protect_module(BASE_ENV[module_name], module_name) end) -- auxiliary functions/variables local string_rep = string.rep local function merge(dest, source) for k,v in pairs(source) do dest[k] = dest[k] or v end return dest end local function sethook(f, key, quota) if type(debug) ~= 'table' or type(debug.sethook) ~= 'function' then return end debug.sethook(f, key, quota) end local function cleanup() sethook() string.rep = string_rep end -- Public interface: sandbox.protect function sandbox.protect(f, options) if type(f) == 'string' then f = assert(loadstring(f)) end options = options or {} local quota = false if options.quota ~= false then quota = options.quota or 500000 end local env = merge(options.env or {}, BASE_ENV) env._G = env._G or env setfenv(f, env) return function(...) if quota then local timeout = function() cleanup() error('Quota exceeded: ' .. tostring(quota)) end sethook(timeout, "", quota) end string.rep = nil local ok, result = pcall(f, ...) cleanup() if not ok then error(result) end return result end end -- Public interface: sandbox.run function sandbox.run(f, options, ...) return sandbox.protect(f, options)(...) end -- make sandbox(f) == sandbox.protect(f) setmetatable(sandbox, {__call = function(_,f,o) return sandbox.protect(f,o) end}) return sandbox
gpl-3.0
ahmedtaleb93/ahmed.t.h
plugins/all.lua
16
4339
do local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.\nUse /type in the group to set type.' end return group_type end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(msg,target,receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type if group_type == "Group" or group_type == "Realm" then local settings = show_group_settingsmod(msg,target) text = text.."\n\n"..settings elseif group_type == "SuperGroup" then local settings = show_supergroup_settingsmod(msg,target) text = text..'\n\n'..settings end local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local mutes_list = mutes_list(target) text = text.."\n\n"..mutes_list local muted_user_list = muted_user_list(target) text = text.."\n\n"..muted_user_list local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end local function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(msg,target,receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) return all(msg,msg.to.id,receiver) end end return { patterns = { "^(all)$", "^(all) (%d+)$" }, run = run } end
gpl-3.0
thinkry/some-mmorpg
3rd/skynet/lualib/http/httpd.lua
101
3708
local internal = require "http.internal" local table = table local string = string local type = type local httpd = {} local http_status_msg = { [100] = "Continue", [101] = "Switching Protocols", [200] = "OK", [201] = "Created", [202] = "Accepted", [203] = "Non-Authoritative Information", [204] = "No Content", [205] = "Reset Content", [206] = "Partial Content", [300] = "Multiple Choices", [301] = "Moved Permanently", [302] = "Found", [303] = "See Other", [304] = "Not Modified", [305] = "Use Proxy", [307] = "Temporary Redirect", [400] = "Bad Request", [401] = "Unauthorized", [402] = "Payment Required", [403] = "Forbidden", [404] = "Not Found", [405] = "Method Not Allowed", [406] = "Not Acceptable", [407] = "Proxy Authentication Required", [408] = "Request Time-out", [409] = "Conflict", [410] = "Gone", [411] = "Length Required", [412] = "Precondition Failed", [413] = "Request Entity Too Large", [414] = "Request-URI Too Large", [415] = "Unsupported Media Type", [416] = "Requested range not satisfiable", [417] = "Expectation Failed", [500] = "Internal Server Error", [501] = "Not Implemented", [502] = "Bad Gateway", [503] = "Service Unavailable", [504] = "Gateway Time-out", [505] = "HTTP Version not supported", } local function readall(readbytes, bodylimit) local tmpline = {} local body = internal.recvheader(readbytes, tmpline, "") if not body then return 413 -- Request Entity Too Large end local request = assert(tmpline[1]) local method, url, httpver = request:match "^(%a+)%s+(.-)%s+HTTP/([%d%.]+)$" assert(method and url and httpver) httpver = assert(tonumber(httpver)) if httpver < 1.0 or httpver > 1.1 then return 505 -- HTTP Version not supported end local header = internal.parseheader(tmpline,2,{}) if not header then return 400 -- Bad request end local length = header["content-length"] if length then length = tonumber(length) end local mode = header["transfer-encoding"] if mode then if mode ~= "identity" and mode ~= "chunked" then return 501 -- Not Implemented end end if mode == "chunked" then body, header = internal.recvchunkedbody(readbytes, bodylimit, header, body) if not body then return 413 end else -- identity mode if length then if bodylimit and length > bodylimit then return 413 end if #body >= length then body = body:sub(1,length) else local padding = readbytes(length - #body) body = body .. padding end end end return 200, url, method, header, body end function httpd.read_request(...) local ok, code, url, method, header, body = pcall(readall, ...) if ok then return code, url, method, header, body else return nil, code end end local function writeall(writefunc, statuscode, bodyfunc, header) local statusline = string.format("HTTP/1.1 %03d %s\r\n", statuscode, http_status_msg[statuscode] or "") writefunc(statusline) if header then for k,v in pairs(header) do if type(v) == "table" then for _,v in ipairs(v) do writefunc(string.format("%s: %s\r\n", k,v)) end else writefunc(string.format("%s: %s\r\n", k,v)) end end end local t = type(bodyfunc) if t == "string" then writefunc(string.format("content-length: %d\r\n\r\n", #bodyfunc)) writefunc(bodyfunc) elseif t == "function" then writefunc("transfer-encoding: chunked\r\n") while true do local s = bodyfunc() if s then if s ~= "" then writefunc(string.format("\r\n%x\r\n", #s)) writefunc(s) end else writefunc("\r\n0\r\n\r\n") break end end else assert(t == "nil") writefunc("\r\n") end end function httpd.write_response(...) return pcall(writeall, ...) end return httpd
mit