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
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/AssetsManagerEx.lua
3
2738
-------------------------------- -- @module AssetsManagerEx -- @extend Ref -- @parent_module cc -------------------------------- -- @brief Gets the current update state. -- @function [parent=#AssetsManagerEx] getState -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @brief Check out if there is a new version of manifest.<br> -- You may use this method before updating, then let user determine whether<br> -- he wants to update resources. -- @function [parent=#AssetsManagerEx] checkUpdate -- @param self -- @return AssetsManagerEx#AssetsManagerEx self (return value: cc.AssetsManagerEx) -------------------------------- -- @brief Gets storage path. -- @function [parent=#AssetsManagerEx] getStoragePath -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @brief Update with the current local manifest. -- @function [parent=#AssetsManagerEx] update -- @param self -- @return AssetsManagerEx#AssetsManagerEx self (return value: cc.AssetsManagerEx) -------------------------------- -- @brief Function for retrieve the local manifest object -- @function [parent=#AssetsManagerEx] getLocalManifest -- @param self -- @return Manifest#Manifest ret (return value: cc.Manifest) -------------------------------- -- @brief Function for retrieve the remote manifest object -- @function [parent=#AssetsManagerEx] getRemoteManifest -- @param self -- @return Manifest#Manifest ret (return value: cc.Manifest) -------------------------------- -- @brief Reupdate all failed assets under the current AssetsManagerEx context -- @function [parent=#AssetsManagerEx] downloadFailedAssets -- @param self -- @return AssetsManagerEx#AssetsManagerEx self (return value: cc.AssetsManagerEx) -------------------------------- -- @brief Create function for creating a new AssetsManagerEx<br> -- param manifestUrl The url for the local manifest file<br> -- param storagePath The storage path for downloaded assets<br> -- warning The cached manifest in your storage path have higher priority and will be searched first,<br> -- only if it doesn't exist, AssetsManagerEx will use the given manifestUrl. -- @function [parent=#AssetsManagerEx] create -- @param self -- @param #string manifestUrl -- @param #string storagePath -- @return AssetsManagerEx#AssetsManagerEx ret (return value: cc.AssetsManagerEx) -------------------------------- -- -- @function [parent=#AssetsManagerEx] AssetsManagerEx -- @param self -- @param #string manifestUrl -- @param #string storagePath -- @return AssetsManagerEx#AssetsManagerEx self (return value: cc.AssetsManagerEx) return nil
mit
abasshacker/abbasone
plugins/banhammer.lua
106
11894
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 by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^([Bb]anall) (.*)$", "^([Bb]anall)$", "^([Bb]anlist) (.*)$", "^([Bb]anlist)$", "^([Gg]banlist)$", "^([Bb]an) (.*)$", "^([Kk]ick)$", "^([Uu]nban) (.*)$", "^([Uu]nbanall) (.*)$", "^([Uu]nbanall)$", "^([Kk]ick) (.*)$", "^([Kk]ickme)$", "^([Bb]an)$", "^([Uu]nban)$", "^([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
JarnoVgr/Mr.Green-MTA-Resources
resources/[gameplay]/achievements/convert.lua
4
1360
-- script to convert from old sqlite db to mysql with forumids results = executeSQLQuery("SELECT * FROM gcAchievements" ) local achievementList = { ["CTF: Capture two flags in one map (50 GC)"] = 1, ["CTF: Capture the winning flag (50 GC)"] = 2, } local fileHandle = fileCreate("convert.sql") fileWrite ( fileHandle, 'TRUNCATE TABLE `achievements`;\n\r') for _,row in ipairs(results) do local gcID = row.id -- outputDebugString(gcID) for __, achievement in ipairs(split(row.achievements, ',')) do -- outputDebugString(achievement) local achID = achievementList[achievement] local query = "INSERT INTO `achievements`(`forumID`, `achievementID`, `unlocked`) VALUES (" .. row.id .. ", " .. achID .. ", 1);\n\r" fileWrite(fileHandle, query) end end fileWrite ( fileHandle, 'UPDATE `achievements` SET `forumID`= (SELECT `green_coins`.`forum_id` FROM `mrgreen_gc`.`green_coins` WHERE `id` = `forumID`);\n\r') fileClose(fileHandle) function getElementResource (element) local parent = element repeat parent = getElementParent ( parent ) until not parent or getElementType(parent) == 'resource' for _, resource in ipairs(getResources()) do if getResourceRootElement(resource) == parent then return resource end end return false end function isMap(resourceElement) return #getElementsByType('spawnpoint', resourceElement) > 0 end
mit
shadoalzupedy/shadow
plugins/supergroup.lua
7
104172
--[[ # #ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ #:(( # For More Information ....! # Developer : Aziz < @TH3_GHOST > # our channel: @DevPointTeam # Version: 1.1 #:)) #ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ # ]] --Begin supergrpup.lua --Check members #Add supergroup --channel : @DevPointTeam local function check_member_super(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg if success == 0 then send_large_msg(receiver, "Promote me to admin first!") end for k,v in pairs(result) do local member_id = v.peer_id if member_id ~= our_id then -- SuperGroup configuration data[tostring(msg.to.id)] = { group_type = 'SuperGroup', long_id = msg.to.peer_id, moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.title, '_', ' '), lock_arabic = 'no', lock_link = "no", flood = 'yes', lock_spam = 'yes', lock_sticker = 'no', member = 'no', public = 'no', lock_rtl = 'no', lock_tgservice = 'yes', lock_contacts = 'no', strict = 'no' } } 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) local text = 'bot has been added ✅ in Group🔹'..msg.to.title return reply_msg(msg.id, text, ok_cb, false) end end end --Check Members #rem supergroup local function check_member_superrem(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) 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) local text = 'bot has been removed ❎ in Group🔹'..msg.to.title return reply_msg(msg.id, text, ok_cb, false) end end end --Function to Add supergroup local function superadd(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg}) end --Function to remove supergroup local function superrem(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg}) end --Get and output admins and bots in supergroup local function callback(cb_extra, success, result) local i = 1 local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ") local member_type = cb_extra.member_type local text = member_type.." for "..chat_name..":\n" for k,v in pairsByKeys(result) do if not v.first_name then name = " " else vname = v.first_name:gsub("‮", "") name = vname:gsub("_", " ") end text = text.."\n"..i.." - "..name.."["..v.peer_id.."]" i = i + 1 end send_large_msg(cb_extra.receiver, text) end --Get and output info about supergroup local function callback_info(cb_extra, success, result) local title ="Info for SuperGroup: ["..result.title.."]\n\n" local admin_num = "Admin count: "..result.admins_count.."\n" local user_num = "User count: "..result.participants_count.."\n" local kicked_num = "Kicked user count: "..result.kicked_count.."\n" local channel_id = "ID: "..result.peer_id.."\n" if result.username then channel_username = "Username: @"..result.username else channel_username = "" end local text = title..admin_num..user_num..kicked_num..channel_id..channel_username send_large_msg(cb_extra.receiver, text) end --Get and output members of supergroup local function callback_who(cb_extra, success, result) local text = "Members for "..cb_extra.receiver local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then username = " @"..v.username else username = "" end text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n" --text = text.."\n"..username Channel : @DevPointTeam i = i + 1 end local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false) post_msg(cb_extra.receiver, text, ok_cb, false) end --Get and output list of kicked users for supergroup local function callback_kicked(cb_extra, success, result) --vardump(result) local text = "Kicked Members for SuperGroup "..cb_extra.receiver.."\n\n" local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then name = name.." @"..v.username end text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n" i = i + 1 end local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false) --send_large_msg(cb_extra.receiver, text) end --Begin supergroup locks local function lock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Links is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Links has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Links is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Links has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_all(msg, data, target) if not is_momod(msg) then return end local group_all_lock = data[tostring(target)]['settings']['all'] if group_all_lock == 'yes' then return 'all settings is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['all'] = 'yes' save_data(_config.moderation.data, data) return 'all settings has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_all(msg, data, target) if not is_momod(msg) then return end local group_all_lock = data[tostring(target)]['settings']['all'] if group_all_lock == 'no' then return 'all settings is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['all'] = 'no' save_data(_config.moderation.data, data) return 'all settings has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_etehad(msg, data, target) if not is_momod(msg) then return end local group_etehad_lock = data[tostring(target)]['settings']['etehad'] if group_etehad_lock == 'yes' then return 'etehad setting is already locked' else data[tostring(target)]['settings']['etehad'] = 'yes' save_data(_config.moderation.data, data) return 'etehad setting has been locked' end end local function unlock_group_etehad(msg, data, target) if not is_momod(msg) then return end local group_etehad_lock = data[tostring(target)]['settings']['etehad'] if group_etehad_lock == 'no' then return 'etehad setting is not locked' else data[tostring(target)]['settings']['etehad'] = 'no' save_data(_config.moderation.data, data) return 'etehad setting has been unlocked' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return end local group_leave_lock = data[tostring(target)]['settings']['leave'] if group_leave_lock == 'yes' then return 'leave is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['leave'] = 'yes' save_data(_config.moderation.data, data) return 'leave has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return end local group_leave_lock = data[tostring(target)]['settings']['leave'] if group_leave_lock == 'no' then return 'leave is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['leave'] = 'no' save_data(_config.moderation.data, data) return 'leave has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_operator(msg, data, target) if not is_momod(msg) then return end local group_operator_lock = data[tostring(target)]['settings']['operator'] if group_operator_lock == 'yes' then return 'operator is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['operator'] = 'yes' save_data(_config.moderation.data, data) return 'operator has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_operator(msg, data, target) if not is_momod(msg) then return end local group_operator_lock = data[tostring(target)]['settings']['operator'] if group_operator_lock == 'no' then return 'operator is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['operator'] = 'no' save_data(_config.moderation.data, data) return 'operator has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_reply(msg, data, target) if not is_momod(msg) then return end local group_reply_lock = data[tostring(target)]['settings']['reply'] if group_reply_lock == 'yes' then return 'Reply is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['reply'] = 'yes' save_data(_config.moderation.data, data) return 'Reply has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_reply(msg, data, target) if not is_momod(msg) then return end local group_reply_lock = data[tostring(target)]['settings']['reply'] if group_reply_lock == 'no' then return 'Reply is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['reply'] = 'no' save_data(_config.moderation.data, data) return 'Reply has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_username(msg, data, target) if not is_momod(msg) then return end local group_username_lock = data[tostring(target)]['settings']['username'] if group_username_lock == 'yes' then return 'Username is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['username'] = 'yes' save_data(_config.moderation.data, data) return 'Username has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_username(msg, data, target) if not is_momod(msg) then return end local group_username_lock = data[tostring(target)]['settings']['username'] if group_username_lock == 'no' then return 'Username is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['username'] = 'no' save_data(_config.moderation.data, data) return 'Username has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_media(msg, data, target) if not is_momod(msg) then return end local group_media_lock = data[tostring(target)]['settings']['media'] if group_media_lock == 'yes' then return 'Media is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['media'] = 'yes' save_data(_config.moderation.data, data) return 'Media has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_media(msg, data, target) if not is_momod(msg) then return end local group_media_lock = data[tostring(target)]['settings']['media'] if group_media_lock == 'no' then return 'Media is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['media'] = 'no' save_data(_config.moderation.data, data) return 'Media has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_fosh(msg, data, target) if not is_momod(msg) then return end local group_fosh_lock = data[tostring(target)]['settings']['fosh'] if group_fosh_lock == 'yes' then return 'badword is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['fosh'] = 'yes' save_data(_config.moderation.data, data) return 'badword has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_fosh(msg, data, target) if not is_momod(msg) then return end local group_fosh_lock = data[tostring(target)]['settings']['fosh'] if group_fosh_lock == 'no' then return 'badword is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['fosh'] = 'no' save_data(_config.moderation.data, data) return 'badword has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_join(msg, data, target) if not is_momod(msg) then return end local group_join_lock = data[tostring(target)]['settings']['join'] if group_join_lock == 'yes' then return 'join is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['join'] = 'yes' save_data(_config.moderation.data, data) return 'join has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_join(msg, data, target) if not is_momod(msg) then return end local group_join_lock = data[tostring(target)]['settings']['join'] if group_join_lock == 'no' then return 'join is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['join'] = 'no' save_data(_config.moderation.data, data) return 'join has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_fwd(msg, data, target) if not is_momod(msg) then return end local group_fwd_lock = data[tostring(target)]['settings']['fwd'] if group_fwd_lock == 'yes' then return 'fwd is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['fwd'] = 'yes' save_data(_config.moderation.data, data) return 'fwd has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_fwd(msg, data, target) if not is_momod(msg) then return end local group_fwd_lock = data[tostring(target)]['settings']['fwd'] if group_fwd_lock == 'no' then return 'fwd is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['fwd'] = 'no' save_data(_config.moderation.data, data) return 'fwd has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_english(msg, data, target) if not is_momod(msg) then return end local group_english_lock = data[tostring(target)]['settings']['english'] if group_english_lock == 'yes' then return 'English is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['english'] = 'yes' save_data(_config.moderation.data, data) return 'English has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_english(msg, data, target) if not is_momod(msg) then return end local group_english_lock = data[tostring(target)]['settings']['english'] if group_english_lock == 'no' then return 'English is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['english'] = 'no' save_data(_config.moderation.data, data) return 'English has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_emoji(msg, data, target) if not is_momod(msg) then return end local group_emoji_lock = data[tostring(target)]['settings']['emoji'] if group_emoji_lock == 'yes' then return 'Emoji is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['emoji'] = 'yes' save_data(_config.moderation.data, data) return 'Emoji has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_emoji(msg, data, target) if not is_momod(msg) then return end local group_emoji_lock = data[tostring(target)]['settings']['emoji'] if group_emoji_lock == 'no' then return 'Emoji is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['emoji'] = 'no' save_data(_config.moderation.data, data) return 'Emoji has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return end local group_tag_lock = data[tostring(target)]['settings']['tag'] if group_tag_lock == 'yes' then return 'tag is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['tag'] = 'yes' save_data(_config.moderation.data, data) return 'tag has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return end local group_tag_lock = data[tostring(target)]['settings']['tag'] if group_tag_lock == 'no' then return 'tag is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['tag'] = 'no' save_data(_config.moderation.data, data) return 'tag has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_all(msg, data, target) if not is_momod(msg) then return end local group_all_lock = data[tostring(target)]['settings']['all'] if group_all_lock == 'no' then return 'all settings is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['all'] = 'no' save_data(_config.moderation.data, data) return 'all settings has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_spam(msg, data, target) if not is_momod(msg) then return end if not is_owner(msg) then return "Owners only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return 'Spam is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'Spam has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_spam(msg, data, target) if not is_momod(msg) then return end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return 'Spam is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'Spam has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Flood is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Flood has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Flood is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Flood has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Members are already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Members has been locked 🔐\n👮 Order by :️ @'..msg.from.username end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Members are not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Members has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_tgservice(msg, data, target) if not is_momod(msg) then return end local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice'] if group_tgservice_lock == 'yes' then return 'Tgservice is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_tgservice'] = 'yes' save_data(_config.moderation.data, data) return 'Tgservice has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_tgservice(msg, data, target) if not is_momod(msg) then return end local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice'] if group_tgservice_lock == 'no' then return 'Tgservice is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_tgservice'] = 'no' save_data(_config.moderation.data, data) return 'Tgservice has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots has been locked 🔐\n👮 Order by :️ @'..msg.from.username end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username 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 is already locked 🔐\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) return 'Contact has been locked 🔐\n👮 Order by :️ @'..msg.from.username 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 is not locked 🔓\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) return 'Contact has been unlocked 🔓\n👮 Order by :️ @'..msg.from.username end end local function enable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'yes' then return 'Settings are already strictly enforced 🛡\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['strict'] = 'yes' save_data(_config.moderation.data, data) return 'Settings will be strictly enforced 🛡\n👮 Order by :️ @'..msg.from.username end end local function disable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'no' then return 'Settings are not strictly enforced 🛡\n👮 Order by :️ @'..msg.from.username else data[tostring(target)]['settings']['strict'] = 'no' save_data(_config.moderation.data, data) return 'Settings will not be strictly enforced 🛡\n👮 Order by :️ @'..msg.from.username end end --End supergroup locks --'Set supergroup rules' function local function set_rulesmod(msg, data, target) if not is_momod(msg) then return end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'SuperGroup rules set' end --'Get supergroup rules' function 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 group_name = data[tostring(msg.to.id)]['settings']['set_name'] local rules = group_name..' rules:\n\n'..rules:gsub("/n", " ") return rules end --Set supergroup to public or not public function local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' data[tostring(target)]['long_id'] = msg.to.long_id save_data(_config.moderation.data, data) return 'SuperGroup is now: not public' end end --Show supergroup settings; function function show_supergroup_settingsmod(msg, target) if not is_momod(msg) then return end 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 bots_protection = "Yes" if data[tostring(target)]['settings']['lock_bots'] then bots_protection = data[tostring(target)]['settings']['lock_bots'] 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_tgservice'] then data[tostring(target)]['settings']['lock_tgservice'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['tag'] then data[tostring(target)]['settings']['tag'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['emoji'] then data[tostring(target)]['settings']['emoji'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['english'] then data[tostring(target)]['settings']['english'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['fwd'] then data[tostring(target)]['settings']['fwd'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['reply'] then data[tostring(target)]['settings']['reply'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['join'] then data[tostring(target)]['settings']['join'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['fosh'] then data[tostring(target)]['settings']['fosh'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['username'] then data[tostring(target)]['settings']['username'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['media'] then data[tostring(target)]['settings']['media'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['leave'] then data[tostring(target)]['settings']['leave'] = '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 if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['all'] then data[tostring(target)]['settings']['all'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['operator'] then data[tostring(target)]['settings']['operator'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['etehad'] then data[tostring(target)]['settings']['etehad'] = 'no' end end local gp_type = data[tostring(msg.to.id)]['group_type'] local settings = data[tostring(target)]['settings'] local text = "🎗➖➖➖🎗➖➖➖🎗\nℹ️SuperGroups Settings: ⬇️\n💟Group name : "..msg.to.title.."\n🎗➖➖➖🎗➖➖➖🎗\n🔗lock links : "..settings.lock_link.."\n📵Lock contacts: "..settings.lock_contacts.."\n🔐Lock flood: "..settings.flood.."\n👾Flood sensitivity : "..NUM_MSG_MAX.."\n📊Lock spam: "..settings.lock_spam.."\n🆎Lock Arabic: "..settings.lock_arabic.."\n🔠Lock english: "..settings.english.."\n👤Lock Member: "..settings.lock_member.."\n📌Lock RTL: "..settings.lock_rtl.."\n🔯Lock Tgservice: "..settings.lock_tgservice.."\n🎡Lock sticker: "..settings.lock_sticker.."\n➕Lock tag(#): "..settings.tag.."\n😃Lock emoji: "..settings.emoji.."\n🤖Lock bots: "..bots_protection.."\n↩️Lock fwd(forward): "..settings.fwd.."\n🔃lock reply: "..settings.reply.."\n🚷Lock join: "..settings.join.."\n♏️Lock username(@): "..settings.username.."\n🆘Lock media: "..settings.media.."\n🏧Lock badword: "..settings.fosh.."\n🚶Lock leave: "..settings.leave.."\n🔕Lock all: "..settings.all.."\n🎗➖➖➖🎗➖➖➖🎗\nℹ️About Group: ⬇️\n🎗➖➖➖🎗➖➖➖🎗\n⚠️Group type: "..gp_type.."\n✳️Public: "..settings.public.."\n⛔️Strict settings: "..settings.strict.."\n🎗➖➖➖🎗➖➖➖🎗\nℹ️bot version : v1.1\n\n🌐 DEV🎗POINT🎗TEAM 🌐" return text end local function promote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) end local function demote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) end local function promote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return send_large_msg(receiver, 'SuperGroup is not added.') end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been promoted.') end local function demote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been demoted.') end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'SuperGroup is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then 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 -- Start by reply actions function get_message_callback(extra, success, result) local get_cmd = extra.get_cmd local msg = extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") if get_cmd == "id" and not result.action then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]") id1 = send_large_msg(channel, result.from.peer_id) elseif get_cmd == 'id' and result.action then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id else user_id = result.peer_id end local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]") id1 = send_large_msg(channel, user_id) end elseif get_cmd == "idfrom" then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]") id2 = send_large_msg(channel, result.fwd_from.peer_id) elseif get_cmd == 'channel_block' and not result.action then local member_id = result.from.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end --savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply") kick_user(member_id, channel_id) elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then local user_id = result.action.user.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.") kick_user(user_id, channel_id) elseif get_cmd == "del" then delete_msg(result.id, ok_cb, false) savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply") elseif get_cmd == "setadmin" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." set as an admin" else text = "[ "..user_id.." ]set as an admin" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "demoteadmin" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id if is_admin2(result.from.peer_id) then return send_large_msg(channel_id, "You can't demote global admins!") end channel_demote(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." has been demoted from admin" else text = "[ "..user_id.." ] has been demoted from admin" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "setowner" then local group_owner = data[tostring(result.to.peer_id)]['set_owner'] if group_owner then local channel_id = 'channel#id'..result.to.peer_id if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(channel_id, user, ok_cb, false) end local user_id = "user#id"..result.from.peer_id channel_set_admin(channel_id, user_id, ok_cb, false) data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply") if result.from.username then text = "@"..result.from.username.." [ "..result.from.peer_id.." ] added as owner" else text = "[ "..result.from.peer_id.." ] added as owner" end send_large_msg(channel_id, text) end elseif get_cmd == "promote" then local receiver = result.to.peer_id local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id if result.to.peer_type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply") promote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_set_mod(channel_id, user, ok_cb, false) end elseif get_cmd == "demote" then local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id --local user = "user#id"..result.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted mod: @"..member_username.."["..result.from.peer_id.."] by reply") demote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_demote(channel_id, user, ok_cb, false) elseif get_cmd == 'mute_user' then if result.service then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id end end if action == 'chat_add_user_link' then if result.from then user_id = result.from.peer_id end end else user_id = result.from.peer_id end local receiver = extra.receiver local chat_id = msg.to.id print(user_id) print(chat_id) if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] removed from the muted user list") elseif is_admin1(msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to the muted user list") end end end -- End by reply actions --By ID actions local function cb_user_info(extra, success, result) local receiver = extra.receiver local user_id = result.peer_id local get_cmd = extra.get_cmd local data = load_data(_config.moderation.data) --[[if get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" else text = "[ "..result.peer_id.." ] has been set as an admin" end send_large_msg(receiver, text)]] if get_cmd == "demoteadmin" then if is_admin2(result.peer_id) then return send_large_msg(receiver, "You can't demote global admins!") end local user_id = "user#id"..result.peer_id channel_demote(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(receiver, text) else text = "[ "..result.peer_id.." ] has been demoted from admin" send_large_msg(receiver, text) end elseif get_cmd == "promote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end promote2(receiver, member_username, user_id) elseif get_cmd == "demote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end demote2(receiver, member_username, user_id) end end -- Begin resolve username actions local function callbackres(extra, success, result) local member_id = result.peer_id local member_username = "@"..result.username local get_cmd = extra.get_cmd if get_cmd == "res" then local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local channel = 'channel#id'..extra.channelid send_large_msg(channel, user..'\n'..name) return user elseif get_cmd == "id" then local user = result.peer_id local channel = 'channel#id'..extra.channelid send_large_msg(channel, user) return user elseif get_cmd == "invite" then local receiver = extra.channel local user_id = "user#id"..result.peer_id channel_invite(receiver, user_id, ok_cb, false) --[[elseif get_cmd == "channel_block" then local user_id = result.peer_id local channel_id = extra.channelid local sender = extra.sender if member_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end kick_user(user_id, channel_id) elseif get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel channel_set_admin(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been set as an admin" send_large_msg(channel_id, text) end elseif Dev = Point elseif get_cmd == "setowner" then local receiver = extra.channel local channel = string.gsub(receiver, 'channel#id', '') local from_id = extra.from_id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then local user = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(result.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username") if result.username then text = member_username.." [ "..result.peer_id.." ] added as owner" else text = "[ "..result.peer_id.." ] added as owner" end send_large_msg(receiver, text) end]] elseif get_cmd == "promote" then local receiver = extra.channel local user_id = result.peer_id --local user = "user#id"..result.peer_id promote2(receiver, member_username, user_id) --channel_set_mod(receiver, user, ok_cb, false) elseif get_cmd == "demote" then local receiver = extra.channel local user_id = result.peer_id local user = "user#id"..result.peer_id demote2(receiver, member_username, user_id) elseif get_cmd == "demoteadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel if is_admin2(result.peer_id) then return send_large_msg(channel_id, "You can't demote global admins!") end channel_demote(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been demoted from admin" send_large_msg(channel_id, text) end local receiver = extra.channel local user_id = result.peer_id demote_admin(receiver, member_username, user_id) elseif get_cmd == 'mute_user' then local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] removed from muted user list") elseif is_owner(extra.msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to muted user list") end end end --End resolve username actions --Begin non-channel_invite username actions local function in_channel_cb(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local msg = cb_extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(cb_extra.msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local member = cb_extra.username local memberid = cb_extra.user_id if member then text = 'No user @'..member..' in this SuperGroup.' else text = 'No user ['..memberid..'] in this SuperGroup.' end if get_cmd == "channel_block" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = v.peer_id local channel_id = cb_extra.msg.to.id local sender = cb_extra.msg.from.id if user_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(user_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(user_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end if v.username then text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]") else text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]") end kick_user(user_id, channel_id) return end end elseif get_cmd == "setadmin" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = "user#id"..v.peer_id local channel_id = "channel#id"..cb_extra.msg.to.id channel_set_admin(channel_id, user_id, ok_cb, false) if v.username then text = "@"..v.username.." ["..v.peer_id.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]") else text = "["..v.peer_id.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id) end if v.username then member_username = "@"..v.username else member_username = string.gsub(v.print_name, '_', ' ') end local receiver = channel_id local user_id = v.peer_id promote_admin(receiver, member_username, user_id) end send_large_msg(channel_id, text) return end elseif get_cmd == 'setowner' then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..v.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(v.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username") if result.username then text = member_username.." ["..v.peer_id.."] added as owner" else text = "["..v.peer_id.."] added as owner" end end elseif memberid and vusername ~= member and vpeer_id ~= memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end data[tostring(channel)]['set_owner'] = tostring(memberid) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username") text = "["..memberid.."] added as owner" end end end end send_large_msg(receiver, text) end --End non-channel_invite username actions --'Set supergroup photo' function local function set_supergroup_photo(msg, success, result) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return end local receiver = get_receiver(msg) if success then local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) channel_set_photo(receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file 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 --Run function local function DevPointTeam(msg, matches) if msg.to.type == 'chat' then if matches[1] == 'tosuper' then if not is_admin1(msg) then return end local receiver = get_receiver(msg) chat_upgrade(receiver, ok_cb, false) end elseif msg.to.type == 'channel'then if matches[1] == 'tosuper' then if not is_admin1(msg) then return end return "Already a SuperGroup" end end if msg.to.type == 'channel' then local support_id = msg.from.id local receiver = get_receiver(msg) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local data = load_data(_config.moderation.data) if matches[1] == 'addbot' and not matches[2] then if not is_admin1(msg) and not is_support(support_id) then return end if is_super_group(msg) then local iDev1 = "is already added !" return send_large_msg(receiver, iDev1) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup") superadd(msg) set_mutes(msg.to.id) channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false) end if matches[1] == 'addbot' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then local iDev1 = "This Group not added 🤖 OK I will add this Group" return send_large_msg(receiver, iDev1) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed") superrem(msg) rem_mutes(msg.to.id) end if matches[1] == 'rembot' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then return reply_msg(msg.id, 'SuperGroup is not added.', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed") superrem(msg) rem_mutes(msg.to.id) end if not data[tostring(msg.to.id)] then return end--@DevPointTeam = Dont Remove if matches[1] == "gpinfo" then if not is_owner(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info") channel_info(receiver, callback_info, {receiver = receiver, msg = msg}) end if matches[1] == "admins" then if not is_owner(msg) and not is_support(msg.from.id) then return end member_type = 'Admins' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list") admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type}) 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 SuperGroup" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "SuperGroup owner is ["..group_owner..']' end if matches[1] == "modlist" then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) -- channel_get_admins(receiver,callback, {receiver = receiver}) end if matches[1] == "bots" and is_momod(msg) then member_type = 'Bots' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list") channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == "who" and not matches[2] and is_momod(msg) then local user_id = msg.from.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list") channel_get_users(receiver, callback_who, {receiver = receiver}) end if matches[1] == "kicked" and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list") channel_get_kicked(receiver, callback_kicked, {receiver = receiver}) end if matches[1] == 'del' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'del', msg = msg } delete_msg(msg.id, ok_cb, false) get_message(msg.reply_id, get_message_callback, cbreply_extra) end end if matches[1] == 'bb' or matches[1] == 'kick' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'channel_block', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'bb' or matches[1] == 'kick' and string.match(matches[2], '^%d+$') then --[[local user_id = matches[2] local channel_id = msg.to.id Dev = Point if is_momod2(user_id, channel_id) and not is_admin2(user_id) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end @DevPointTeam savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]") kick_user(user_id, channel_id)]] local get_cmd = 'channel_block' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif msg.text:match("@[%a%d]") then --[[local cbres_extra = { channelid = msg.to.id, get_cmd = 'channel_block', sender = msg.from.id Dev = Point } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'channel_block' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'id' then if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then local cbreply_extra = { get_cmd = 'id', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then local cbreply_extra = { get_cmd = 'idfrom', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif msg.text:match("@[%a%d]") then local cbres_extra = { channelid = msg.to.id, get_cmd = 'id' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username) resolve_username(username, callbackres, cbres_extra) else savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID") local text = "♍️- Name: " ..string.gsub(msg.from.print_name, "_", " ").. "\n♑️- Username: @"..(msg.from.username or '----').."\n🆔- ID: "..msg.from.id.."\n💟- Group Name: " ..string.gsub(msg.to.print_name, "_", " ").. "\nℹ️- Group ID: "..msg.to.id return reply_msg(msg.id, text, ok_cb, false) end end if matches[1] == 'kickme' then if msg.to.type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme") channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if matches[1] == 'newlink' and is_momod(msg)then local function callback_link (extra , success, result) local receiver = get_receiver(msg) if success == 0 then send_large_msg(receiver, '*Error: Failed to retrieve link* \nReason: Not creator.\n\nIf you have the link, please use /setlink to set it') data[tostring(msg.to.id)]['settings']['set_link'] = nil save_data(_config.moderation.data, data) else send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link") export_channel_link(receiver, callback_link, false) end if matches[1] == 'setlink' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send the new group link now' end if msg.text then if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = msg.text save_data(_config.moderation.data, data) return "New link set" end end if matches[1] == 'link' 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 "Create a link using /newlink first!\n\nOr if I am not creator use /setlink to set your link" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "link Group ["..msg.to.title.."] :\n"..group_link end if matches[1] == "invite" and is_sudo(msg) then local cbres_extra = { channel = get_receiver(msg), get_cmd = "invite" } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username) resolve_username(username, callbackres, cbres_extra) end if matches[1] == 'res' and is_owner(msg) then local cbres_extra = { channelid = msg.to.id, get_cmd = 'res' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username) resolve_username(username, callbackres, cbres_extra) end --[[if matches[1] == 'kick' and is_momod(msg) then local receiver = channel..matches[3] local user = "user#id"..matches[2] chaannel_kick(receiver, user, ok_cb, false) @DevPointTeam end]] if matches[1] == 'setadmin' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setadmin', msg = msg } setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'setadmin' and string.match(matches[2], '^%d+$') then --[[] local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'setadmin' Dev = Point user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]] local get_cmd = 'setadmin' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'setadmin' and not string.match(matches[2], '^%d+$') then --[[local cbres_extra = { channel = get_receiver(msg), get_cmd = 'setadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'setadmin' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'demoteadmin' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demoteadmin', msg = msg } demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'demoteadmin' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demoteadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'demoteadmin' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demoteadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username) resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'setowner' and is_owner(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setowner', msg = msg } setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'setowner' and string.match(matches[2], '^%d+$') then --[[ local group_owner = data[tostring(msg.to.id)]['set_owner'] if group_owner then local receiver = get_receiver(msg) local user_id = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user_id, ok_cb, false) end local user = "user#id"..matches[2] channel_set_admin(receiver, user, ok_cb, false) data[tostring(msg.to.id)]['set_owner'] = tostring(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 Dev = Point end]] local get_cmd = 'setowner' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'setowner' and not string.match(matches[2], '^%d+$') then local get_cmd = 'setowner' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'promote' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'promote', msg = msg } promote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'promote' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'promote' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'promote', } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'mp' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_set_mod(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'md' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_demote(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'demote' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner/support/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demote', msg = msg } demote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'demote' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demote' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == "setname" and is_momod(msg) then local receiver = get_receiver(msg) local set_name = string.gsub(matches[2], '_', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2]) rename_channel(receiver, set_name, ok_cb, false) end if msg.service and msg.action.type == 'chat_rename' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title) data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title save_data(_config.moderation.data, data) end if matches[1] == "setabout" and is_momod(msg) then local receiver = get_receiver(msg) local about_text = matches[2] local data_cat = 'description' local target = msg.to.id data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text) channel_set_about(receiver, about_text, ok_cb, false) return "Description has been set.\n\nSelect the chat again to see the changes." end if matches[1] == "setusername" and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username Set.\n\nSelect the chat again to see the changes.") elseif success == 0 then send_large_msg(receiver, "Failed to set SuperGroup username.\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.") end end local username = string.gsub(matches[2], '@', '') channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end if matches[1] == 'setrules' and is_momod(msg) then rules = matches[2] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]") return set_rulesmod(msg, data, target) end if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo") load_photo(msg.id, set_supergroup_photo, msg) return end 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) savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo") return 'Please send the new group photo now' end if matches[1] == 'clean' then if not is_momod(msg) then return end if not is_momod(msg) then return "Only owner can clean" end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'No moderator(s) in this SuperGroup.' end 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") return 'Modlist has been cleaned' end if matches[2] == 'rules' then local data_cat = 'rules' if data[tostring(msg.to.id)][data_cat] == nil then return "Rules have not been set" end 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") return 'Rules have been cleaned' end if matches[2] == 'about' then local receiver = get_receiver(msg) local about_text = ' ' local data_cat = 'description' if data[tostring(msg.to.id)][data_cat] == nil then return 'About is not set' end 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") channel_set_about(receiver, about_text, ok_cb, false) return "About has been cleaned" end if matches[2] == 'silentlist' then chat_id = msg.to.id local hash = 'mute_user:'..chat_id redis:del(hash) return "silentlist Cleaned" end if matches[2] == 'username' and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username cleaned.") elseif success == 0 then send_large_msg(receiver, "Failed to clean SuperGroup username.") end end local username = "" channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end end if matches[1] == 'lock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'all' then local safemode ={ lock_group_links(msg, data, target), lock_group_tag(msg, data, target), lock_group_spam(msg, data, target), lock_group_flood(msg, data, target), lock_group_arabic(msg, data, target), lock_group_membermod(msg, data, target), lock_group_rtl(msg, data, target), lock_group_tgservice(msg, data, target), lock_group_sticker(msg, data, target), lock_group_contacts(msg, data, target), lock_group_english(msg, data, target), lock_group_fwd(msg, data, target), lock_group_reply(msg, data, target), lock_group_join(msg, data, target), lock_group_emoji(msg, data, target), lock_group_username(msg, data, target), lock_group_fosh(msg, data, target), lock_group_media(msg, data, target), lock_group_leave(msg, data, target), lock_group_bots(msg, data, target), lock_group_operator(msg, data, target), } return lock_group_all(msg, data, target), safemode end if matches[2] == 'etehad' then local etehad ={ unlock_group_links(msg, data, target), lock_group_tag(msg, data, target), lock_group_spam(msg, data, target), lock_group_flood(msg, data, target), unlock_group_arabic(msg, data, target), lock_group_membermod(msg, data, target), unlock_group_rtl(msg, data, target), lock_group_tgservice(msg, data, target), lock_group_sticker(msg, data, target), unlock_group_contacts(msg, data, target), unlock_group_english(msg, data, target), unlock_group_fwd(msg, data, target), unlock_group_reply(msg, data, target), lock_group_join(msg, data, target), unlock_group_emoji(msg, data, target), unlock_group_username(msg, data, target), lock_group_fosh(msg, data, target), unlock_group_media(msg, data, target), lock_group_leave(msg, data, target), lock_group_bots(msg, data, target), unlock_group_operator(msg, data, target), } return lock_group_etehad(msg, data, target), etehad end if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ") return lock_group_links(msg, data, target) end if matches[2] == 'join' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked join ") return lock_group_join(msg, data, target) end if matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag ") return lock_group_tag(msg, data, target) end if matches[2] == 'spam' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ") return lock_group_spam(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_flood(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] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2]:lower() == 'rtl' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names") return lock_group_rtl(msg, data, target) end if matches[2] == 'tgservice' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked Tgservice Actions") return lock_group_tgservice(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting") return lock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting") return lock_group_contacts(msg, data, target) end if matches[2] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings") return enable_strict_rules(msg, data, target) end if matches[2] == 'english' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked english") return lock_group_english(msg, data, target) end if matches[2] == 'fwd' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked fwd") return lock_group_fwd(msg, data, target) end if matches[2] == 'reply' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked reply") return lock_group_reply(msg, data, target) end if matches[2] == 'emoji' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked emoji") return lock_group_emoji(msg, data, target) end if matches[2] == 'badword' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked fosh") return lock_group_fosh(msg, data, target) end if matches[2] == 'media' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked media") return lock_group_media(msg, data, target) end if matches[2] == 'username' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked username") return lock_group_username(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leave") return lock_group_leave(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots") return lock_group_bots(msg, data, target) end if matches[2] == 'operator' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked operator") return lock_group_operator(msg, data, target) end end if matches[1] == 'unlock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'all' then local dsafemode ={ unlock_group_links(msg, data, target), unlock_group_tag(msg, data, target), unlock_group_spam(msg, data, target), unlock_group_flood(msg, data, target), unlock_group_arabic(msg, data, target), unlock_group_membermod(msg, data, target), unlock_group_rtl(msg, data, target), unlock_group_tgservice(msg, data, target), unlock_group_sticker(msg, data, target), unlock_group_contacts(msg, data, target), unlock_group_english(msg, data, target), unlock_group_fwd(msg, data, target), unlock_group_reply(msg, data, target), unlock_group_join(msg, data, target), unlock_group_emoji(msg, data, target), unlock_group_username(msg, data, target), unlock_group_fosh(msg, data, target), unlock_group_media(msg, data, target), unlock_group_leave(msg, data, target), unlock_group_bots(msg, data, target), unlock_group_operator(msg, data, target), } return unlock_group_all(msg, data, target), dsafemode end if matches[2] == 'etehad' then local detehad ={ lock_group_links(msg, data, target), unlock_group_tag(msg, data, target), lock_group_spam(msg, data, target), lock_group_flood(msg, data, target), unlock_group_arabic(msg, data, target), unlock_group_membermod(msg, data, target), unlock_group_rtl(msg, data, target), unlock_group_tgservice(msg, data, target), unlock_group_sticker(msg, data, target), unlock_group_contacts(msg, data, target), unlock_group_english(msg, data, target), unlock_group_fwd(msg, data, target), unlock_group_reply(msg, data, target), unlock_group_join(msg, data, target), unlock_group_emoji(msg, data, target), unlock_group_username(msg, data, target), unlock_group_fosh(msg, data, target), unlock_group_media(msg, data, target), unlock_group_leave(msg, data, target), unlock_group_bots(msg, data, target), unlock_group_operator(msg, data, target), } return unlock_group_etehad(msg, data, target), detehad end if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting") return unlock_group_links(msg, data, target) end if matches[2] == 'join' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked join") return unlock_group_join(msg, data, target) end if matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag") return unlock_group_tag(msg, data, target) end if matches[2] == 'spam' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam") return unlock_group_spam(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood") return unlock_group_flood(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] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2]:lower() == 'rtl' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[2] == 'tgservice' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tgservice actions") return unlock_group_tgservice(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting") return unlock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting") return unlock_group_contacts(msg, data, target) end if matches[2] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings") return disable_strict_rules(msg, data, target) end if matches[2] == 'english' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked english") return unlock_group_english(msg, data, target) end if matches[2] == 'fwd' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked fwd") return unlock_group_fwd(msg, data, target) end if matches[2] == 'reply' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked reply") return unlock_group_reply(msg, data, target) end if matches[2] == 'emoji' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled emoji") return unlock_group_emoji(msg, data, target) end if matches[2] == 'badword' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked fosh") return unlock_group_fosh(msg, data, target) end if matches[2] == 'media' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked media") return unlock_group_media(msg, data, target) end if matches[2] == 'username' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled username") return unlock_group_username(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leave") return unlock_group_leave(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots") return unlock_group_bots(msg, data, target) end if matches[2] == 'operator' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked operator") return unlock_group_operator(msg, data, target) end end if matches[1] == 'setflood' then if not is_momod(msg) then return 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 'Flood has been set to: '..matches[2] end if matches[1] == 'public' and is_momod(msg) then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: not public") return unset_public_membermod(msg, data, target) end end if matches[1] == 'mute' and is_owner(msg) then local chat_id = msg.to.id if matches[2] == 'audio' then local msg_type = 'Audio' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'Audio has been muted 🎵🔐\n👮 Order by :️ @'..msg.from.username else return 'Audio is already muted 🎵🔐\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'photo' then local msg_type = 'Photo' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'Photo has been muted 🎡🔐\n👮 Order by :️ @'..msg.from.username else return 'Photo is already muted 🎡🔐\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'video' then local msg_type = 'Video' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'Video has been muted 🎥🔐\n👮 Order by :️ @'..msg.from.username else return 'Video is already muted 🎥🔐\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'gifs' then local msg_type = 'Gifs' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'Gifs has been muted 🎆🔐\n👮 Order by :️ @'..msg.from.username else return 'Gifs is already muted 🎆🔐\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'doc' then local msg_type = 'Documents' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'documents has been muted 📂🔐\n👮 Order by :️ @'..msg.from.username else return 'documents is already muted 📂🔐\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'text' then local msg_type = 'Text' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'Text has been muted 📝🔐\n👮 Order by :️ @'..msg.from.username else return 'Text is already muted 📝🔐\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'all' then local msg_type = 'All' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return 'Mute all has been enabled 🔕\n👮 Order by :️ @'..msg.from.username else return 'Mute all is already enabled 🔕\n👮 Order by :️ @'..msg.from.username end end end if matches[1] == 'unmute' and is_momod(msg) then local chat_id = msg.to.id if matches[2] == 'audio' then local msg_type = 'Audio' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return 'Audio has been unmuted 🎵🔓\n👮 Order by :️ @'..msg.from.username else return 'Audio is already unmuted 🎵🔓\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'photo' then local msg_type = 'Photo' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return 'Photo has been unmuted 🎡🔓\n👮 Order by :️ @'..msg.from.username else return 'Photo is already unmuted 🎡🔓\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'video' then local msg_type = 'Video' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return 'Video has been unmuted 🎥🔓\n👮 Order by :️ @'..msg.from.username else return 'Video is already unmuted 🎥🔓\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'gifs' then local msg_type = 'Gifs' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return 'Gifs has been unmuted 🎆🔓\n👮 Order by :️ @'..msg.from.username else return 'Gifs is already unmuted 🎆🔓\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'doc' then local msg_type = 'Documents' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return 'documents has been unmuted 📂🔓\n👮 Order by :️ @'..msg.from.username else return 'documents is already unmuted 📂🔓\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'text' then local msg_type = 'Text' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message") unmute(chat_id, msg_type) return 'Text has been unmuted 📝🔓\n👮 Order by :️ @'..msg.from.username else return 'Text is already unmuted 📝🔓\n👮 Order by :️ @'..msg.from.username end end if matches[2] == 'all' then local msg_type = 'All' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return 'Mute all has been disabled 🔔\n👮 Order by :️ @'..msg.from.username else return 'Mute all is already disabled 🔔\n👮 Order by :️ @'..msg.from.username end end end if matches[1] == "silent" or matches[1] == "unsilent" and is_momod(msg) then local chat_id = msg.to.id local hash = "mute_user"..chat_id local user_id = "" if type(msg.reply_id) ~= "nil" then local receiver = get_receiver(msg) local get_cmd = "mute_user" muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg}) elseif matches[1] == "silent" or matches[1] == "unsilent" and string.match(matches[2], '^%d+$') then local user_id = matches[2] if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list") return "["..user_id.."] removed from the muted users list" elseif is_momod(msg) then mute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list") return "["..user_id.."] added to the muted user list" end elseif matches[1] == "silent" or matches[1] == "unsilent" and not string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local get_cmd = "mute_user" local username = matches[2] local username = string.gsub(matches[2], '@', '') resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg}) end end if matches[1] == "muteslist" and is_momod(msg) then local chat_id = msg.to.id if not has_mutes(chat_id) then set_mutes(chat_id) return mutes_list(chat_id) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist") return mutes_list(chat_id) end if matches[1] == "silentlist" and is_momod(msg) then local chat_id = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist") return muted_user_list(chat_id) end if matches[1] == 'settings' and is_momod(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ") return show_supergroup_settingsmod(msg, target) 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] == 'help' and not is_owner(msg) then text = "Only managers 😐⛔️" reply_msg(msg.id, text, ok_cb, false) elseif matches[1] == 'help' and is_owner(msg) 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] == 'peer_id' and is_admin1(msg)then text = msg.to.peer_id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end if matches[1] == 'msg.to.id' and is_admin1(msg) then text = msg.to.id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end --Admin Join Service Message if msg.service then local action = msg.action.type if action == 'chat_add_user_link' then if is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.from.id) and not is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup") channel_set_mod(receiver, user, ok_cb, false) end end if action == 'chat_add_user' then if is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_mod(receiver, user, ok_cb, false) end end end if matches[1] == 'msg.to.peer_id' then post_large_msg(receiver, msg.to.peer_id) end end end local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end return { patterns = { "^[#!/]([Aa]ddbot)$", "^[#!/]([Rr]embot)$", "^[#!/]([Mm]ove) (.*)$", "^[#!/]([Gg]pinfo)$", "^[#!/]([Aa]dmins)$", "^[#!/]([Oo]wner)$", "^[#!/]([Mm]odlist)$", "^[#!/]([Bb]ots)$", "^[#!/]([Ww]ho)$", "^[#!/]([Kk]icked)$", "^[#!/]([Bb]b) (.*)", "^[#!/]([Bb]b)", "^[#!/]([Kk]ick) (.*)", "^[#!/]([Kk]ick)", "^[#!/]([Tt]osuper)$", "^[#!/]([Ii][Dd])$", "^[#!/]([Ii][Dd]) (.*)$", "^[#!/]([Kk]ickme)$", "^[#!/]([Nn]ewlink)$", "^[#!/]([Ss]etlink)$", "^[#!/]([Ll]ink)$", "^[#!/]([Rr]es) (.*)$", "^[#!/]([Ss]etadmin) (.*)$", "^[#!/]([Ss]etadmin)", "^[#!/]([Dd]emoteadmin) (.*)$", "^[#!/]([Dd]emoteadmin)", "^[#!/]([Ss]etowner) (.*)$", "^[#!/]([Ss]etowner)$", "^[#!/]([Pp]romote) (.*)$", "^[#!/]([Pp]romote)", "^[#!/]([Dd]emote) (.*)$", "^[#!/]([Dd]emote)", "^[#!/]([Ss]etname) (.*)$", "^[#!/]([Ss]etabout) (.*)$", "^[#!/]([Ss]etrules) (.*)$", "^[#!/]([Ss]etphoto)$", "^[#!/]([Ss]etusername) (.*)$", "^[#!/]([Dd]el)$", "^[#!/]([Ll]ock) (.*)$", "^[#!/]([Uu]nlock) (.*)$", "^[#!/]([Mm]ute) ([^%s]+)$", "^[#!/]([Uu]nmute) ([^%s]+)$", "^[#!/]([Ss]ilent)$", "^[#!/]([Ss]ilent) (.*)$", "^[#!/]([Uu]nsilent)$", "^[#!/]([Uu]nsilent) (.*)$", "^[#!/]([Pp]ublic) (.*)$", "^[#!/]([Ss]ettings)$", "^[#!/]([Rr]ules)$", "^[#!/]([Ss]etflood) (%d+)$", "^[#!/]([Cc]lean) (.*)$", "^[#!/]([Hh]elp)$", "^[#!/]([Mm]uteslist)$", "^[#!/]([Ss]ilentlist)$", "[#!/](mp) (.*)", "[#!/](md) (.*)", "^(https://telegram.me/joinchat/%S+)$", "msg.to.peer_id", "%[(document)%]", "%[(photo)%]", "%[(video)%]", "%[(audio)%]", "%[(contact)%]", "^!!tgservice (.+)$", }, run = DevPointTeam, pre_process = pre_process } --@DevPointTeam --@TH3_GHOST
gpl-2.0
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/script/framework/extends/MenuEx.lua
57
1228
--[[ 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. ]] local Menu = cc.Menu local MenuItem = cc.MenuItem function MenuItem:onClicked(callback) self:registerScriptTapHandler(callback) return self end
mit
daurnimator/lua-http
http/client.lua
1
3165
local ca = require "cqueues.auxlib" local cs = require "cqueues.socket" local http_tls = require "http.tls" local http_util = require "http.util" local connection_common = require "http.connection_common" local onerror = connection_common.onerror local new_h1_connection = require "http.h1_connection".new local new_h2_connection = require "http.h2_connection".new local openssl_ssl = require "openssl.ssl" local openssl_ctx = require "openssl.ssl.context" local openssl_verify_param = require "openssl.x509.verify_param" -- Create a shared 'default' TLS context local default_ctx = http_tls.new_client_context() local function negotiate(s, options, timeout) s:onerror(onerror) local tls = options.tls local version = options.version if tls then local ctx = options.ctx or default_ctx local ssl = openssl_ssl.new(ctx) local host = options.host local host_is_ip = host and http_util.is_ip(host) local sendname = options.sendname if sendname == nil and not host_is_ip and host then sendname = host end if sendname then -- false indicates no sendname wanted ssl:setHostName(sendname) end if http_tls.has_alpn then if version == nil then ssl:setAlpnProtos({"h2", "http/1.1"}) elseif version == 1.1 then ssl:setAlpnProtos({"http/1.1"}) elseif version == 2 then ssl:setAlpnProtos({"h2"}) end end if version == 2 then ssl:setOptions(openssl_ctx.OP_NO_TLSv1 + openssl_ctx.OP_NO_TLSv1_1) end if host and http_tls.has_hostname_validation then local params = openssl_verify_param.new() if host_is_ip then params:setIP(host) else params:setHost(host) end -- Allow user defined params to override local old = ssl:getParam() old:inherit(params) ssl:setParam(old) end local ok, err, errno = s:starttls(ssl, timeout) if not ok then return nil, err, errno end end if version == nil then local ssl = s:checktls() if ssl then if http_tls.has_alpn and ssl:getAlpnSelected() == "h2" then version = 2 else version = 1.1 end else -- TODO: attempt upgrading http1 to http2 version = 1.1 end end if version < 2 then return new_h1_connection(s, "client", version) elseif version == 2 then return new_h2_connection(s, "client", options.h2_settings) else error("Unknown HTTP version: " .. tostring(version)) end end local function connect(options, timeout) local bind = options.bind if bind ~= nil then assert(type(bind) == "string") local bind_address, bind_port = bind:match("^(.-):(%d+)$") if bind_address then bind_port = tonumber(bind_port, 10) else bind_address = bind end local ipv6 = bind_address:match("^%[([:%x]+)%]$") if ipv6 then bind_address = ipv6 end bind = { address = bind_address; port = bind_port; } end local s, err, errno = ca.fileresult(cs.connect { family = options.family; host = options.host; port = options.port; path = options.path; bind = bind; sendname = false; v6only = options.v6only; nodelay = true; }) if s == nil then return nil, err, errno end return negotiate(s, options, timeout) end return { negotiate = negotiate; connect = connect; }
mit
snowplow/snowplow-lua-tracker
spec/unit/lib/json_spec.lua
1
2293
--- json_spec.lua -- -- Copyright (c) 2013 - 2022 Snowplow Analytics Ltd. All rights reserved. -- -- This program is licensed to you under the Apache License Version 2.0, -- and you may not use this file except in compliance with the Apache License Version 2.0. -- You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the Apache License Version 2.0 is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. local json = require("src.snowplow..lib.json") describe("json", function() it("should JSON-encode Lua tables correctly", function() local data_table = { { "INPUT", "EXPECTED", }, { {}, "[]", }, { { name = "John", age = 23 }, '{"age":23,"name":"John"}', }, { { my_temp = 23.3, my_unit = "celsius" }, '{"my_temp":23.3,"my_unit":"celsius"}', }, { { event = "page_ping", mobile = true, properties = { min_x_INT = 0, max_x = 960, min_y = -12, max_y = 1080 }, }, '{"event":"page_ping","mobile":true,"properties":{"max_x":960,"max_y":1080,"min_x_INT":0,"min_y":-12}}', }, { { event = "basket_change", product_id = "PBZ000345", price = 23.39, quantity = -2, visitor = nil, -- Sadly this doesn't make it through as "visitor": null tstamp_TM = 1678023000, }, '{"event":"basket_change","price":23.39,"product_id":"PBZ000345","quantity":-2,"tstamp_TM":1678023000}', }, } for i, v in ipairs(data_table) do if i > 1 then local expected = json:encode(v[1]) assert.are.equal(v[2], expected) end end end) it("should error on nil or other datatypes", function() local bad_values = { nil, "", 1, "temp => 23.C", true, false, 34.5 } for _, v in ipairs(bad_values) do assert.has_error(function() json:encode(v) end) end end) end)
apache-2.0
opentechinstitute/luci
applications/luci-statistics/luasrc/model/cbi/luci_statistics/netlink.lua
78
2765
--[[ Luci configuration model for statistics - collectd netlink plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") 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
osa1/language-lua
lua-5.3.1-tests/api.lua
4
31491
-- $Id: api.lua,v 1.141 2015/05/15 12:25:38 roberto Exp $ if T==nil then (Message or print)('\n >>> testC not active: skipping API tests <<<\n') return end local debug = require "debug" local pack = table.pack function tcheck (t1, t2) assert(t1.n == (t2.n or #t2) + 1) for i = 2, t1.n do assert(t1[i] == t2[i - 1]) end end local function checkerr (msg, f, ...) local stat, err = pcall(f, ...) assert(not stat and string.find(err, msg)) end print('testing C API') a = T.testC("pushvalue R; return 1") assert(a == debug.getregistry()) -- absindex assert(T.testC("settop 10; absindex -1; return 1") == 10) assert(T.testC("settop 5; absindex -5; return 1") == 1) assert(T.testC("settop 10; absindex 1; return 1") == 1) assert(T.testC("settop 10; absindex R; return 1") < -10) -- testing alignment a = T.d2s(12458954321123.0) assert(a == string.pack("d", 12458954321123.0)) assert(T.s2d(a) == 12458954321123.0) a,b,c = T.testC("pushnum 1; pushnum 2; pushnum 3; return 2") assert(a == 2 and b == 3 and not c) f = T.makeCfunc("pushnum 1; pushnum 2; pushnum 3; return 2") a,b,c = f() assert(a == 2 and b == 3 and not c) -- test that all trues are equal a,b,c = T.testC("pushbool 1; pushbool 2; pushbool 0; return 3") assert(a == b and a == true and c == false) a,b,c = T.testC"pushbool 0; pushbool 10; pushnil;\ tobool -3; tobool -3; tobool -3; return 3" assert(a==false and b==true and c==false) a,b,c = T.testC("gettop; return 2", 10, 20, 30, 40) assert(a == 40 and b == 5 and not c) t = pack(T.testC("settop 5; gettop; return .", 2, 3)) tcheck(t, {n=4,2,3}) t = pack(T.testC("settop 0; settop 15; return 10", 3, 1, 23)) assert(t.n == 10 and t[1] == nil and t[10] == nil) t = pack(T.testC("remove -2; gettop; return .", 2, 3, 4)) tcheck(t, {n=2,2,4}) t = pack(T.testC("insert -1; gettop; return .", 2, 3)) tcheck(t, {n=2,2,3}) t = pack(T.testC("insert 3; gettop; return .", 2, 3, 4, 5)) tcheck(t, {n=4,2,5,3,4}) t = pack(T.testC("replace 2; gettop; return .", 2, 3, 4, 5)) tcheck(t, {n=3,5,3,4}) t = pack(T.testC("replace -2; gettop; return .", 2, 3, 4, 5)) tcheck(t, {n=3,2,3,5}) t = pack(T.testC("remove 3; gettop; return .", 2, 3, 4, 5)) tcheck(t, {n=3,2,4,5}) t = pack(T.testC("copy 3 4; gettop; return .", 2, 3, 4, 5)) tcheck(t, {n=4,2,3,3,5}) t = pack(T.testC("copy -3 -1; gettop; return .", 2, 3, 4, 5)) tcheck(t, {n=4,2,3,4,3}) do -- testing 'rotate' local t = {10, 20, 30, 40, 50, 60} for i = -6, 6 do local s = string.format("rotate 2 %d; return 7", i) local t1 = pack(T.testC(s, 10, 20, 30, 40, 50, 60)) tcheck(t1, t) table.insert(t, 1, table.remove(t)) end t = pack(T.testC("rotate -2 1; gettop; return .", 10, 20, 30, 40)) tcheck(t, {10, 20, 40, 30}) t = pack(T.testC("rotate -2 -1; gettop; return .", 10, 20, 30, 40)) tcheck(t, {10, 20, 40, 30}) -- some corner cases t = pack(T.testC("rotate -1 0; gettop; return .", 10, 20, 30, 40)) tcheck(t, {10, 20, 30, 40}) t = pack(T.testC("rotate -1 1; gettop; return .", 10, 20, 30, 40)) tcheck(t, {10, 20, 30, 40}) t = pack(T.testC("rotate 5 -1; gettop; return .", 10, 20, 30, 40)) tcheck(t, {10, 20, 30, 40}) end -- testing non-function message handlers do local f = T.makeCfunc[[ getglobal error pushstring bola pcall 1 1 1 # call 'error' with given handler pushstatus return 2 # return error message and status ]] local msg, st = f({}) -- invalid handler assert(st == "ERRERR" and string.find(msg, "error handling")) local msg, st = f(nil) -- invalid handler assert(st == "ERRERR" and string.find(msg, "error handling")) local a = setmetatable({}, {__call = function (_, x) return x:upper() end}) local msg, st = f(a) -- callable handler assert(st == "ERRRUN" and msg == "BOLA") end t = pack(T.testC("insert 3; pushvalue 3; remove 3; pushvalue 2; remove 2; \ insert 2; pushvalue 1; remove 1; insert 1; \ insert -2; pushvalue -2; remove -3; gettop; return .", 2, 3, 4, 5, 10, 40, 90)) tcheck(t, {n=7,2,3,4,5,10,40,90}) t = pack(T.testC("concat 5; gettop; return .", "alo", 2, 3, "joao", 12)) tcheck(t, {n=1,"alo23joao12"}) -- testing MULTRET t = pack(T.testC("call 2,-1; gettop; return .", function (a,b) return 1,2,3,4,a,b end, "alo", "joao")) tcheck(t, {n=6,1,2,3,4,"alo", "joao"}) do -- test returning more results than fit in the caller stack local a = {} for i=1,1000 do a[i] = true end; a[999] = 10 local b = T.testC([[pcall 1 -1 0; pop 1; tostring -1; return 1]], table.unpack, a) assert(b == "10") end -- testing globals _G.a = 14; _G.b = "a31" local a = {T.testC[[ getglobal a; getglobal b; getglobal b; setglobal a; gettop; return . ]]} assert(a[2] == 14 and a[3] == "a31" and a[4] == nil and _G.a == "a31") -- testing arith assert(T.testC("pushnum 10; pushnum 20; arith /; return 1") == 0.5) assert(T.testC("pushnum 10; pushnum 20; arith -; return 1") == -10) assert(T.testC("pushnum 10; pushnum -20; arith *; return 1") == -200) assert(T.testC("pushnum 10; pushnum 3; arith ^; return 1") == 1000) assert(T.testC("pushnum 10; pushstring 20; arith /; return 1") == 0.5) assert(T.testC("pushstring 10; pushnum 20; arith -; return 1") == -10) assert(T.testC("pushstring 10; pushstring -20; arith *; return 1") == -200) assert(T.testC("pushstring 10; pushstring 3; arith ^; return 1") == 1000) assert(T.testC("arith /; return 1", 2, 0) == 10.0/0) a = T.testC("pushnum 10; pushint 3; arith \\; return 1") assert(a == 3.0 and math.type(a) == "float") a = T.testC("pushint 10; pushint 3; arith \\; return 1") assert(a == 3 and math.type(a) == "integer") a = assert(T.testC("pushint 10; pushint 3; arith +; return 1")) assert(a == 13 and math.type(a) == "integer") a = assert(T.testC("pushnum 10; pushint 3; arith +; return 1")) assert(a == 13 and math.type(a) == "float") a,b,c = T.testC([[pushnum 1; pushstring 10; arith _; pushstring 5; return 3]]) assert(a == 1 and b == -10 and c == "5") mt = {__add = function (a,b) return setmetatable({a[1] + b[1]}, mt) end, __mod = function (a,b) return setmetatable({a[1] % b[1]}, mt) end, __unm = function (a) return setmetatable({a[1]* 2}, mt) end} a,b,c = setmetatable({4}, mt), setmetatable({8}, mt), setmetatable({-3}, mt) x,y,z = T.testC("arith +; return 2", 10, a, b) assert(x == 10 and y[1] == 12 and z == nil) assert(T.testC("arith %; return 1", a, c)[1] == 4%-3) assert(T.testC("arith _; arith +; arith %; return 1", b, a, c)[1] == 8 % (4 + (-3)*2)) -- errors in arithmetic checkerr("divide by zero", T.testC, "arith \\", 10, 0) checkerr("%%0", T.testC, "arith %", 10, 0) -- testing lessthan and lessequal assert(T.testC("compare LT 2 5, return 1", 3, 2, 2, 4, 2, 2)) assert(T.testC("compare LE 2 5, return 1", 3, 2, 2, 4, 2, 2)) assert(not T.testC("compare LT 3 4, return 1", 3, 2, 2, 4, 2, 2)) assert(T.testC("compare LE 3 4, return 1", 3, 2, 2, 4, 2, 2)) assert(T.testC("compare LT 5 2, return 1", 4, 2, 2, 3, 2, 2)) assert(not T.testC("compare LT 2 -3, return 1", "4", "2", "2", "3", "2", "2")) assert(not T.testC("compare LT -3 2, return 1", "3", "2", "2", "4", "2", "2")) -- non-valid indices produce false assert(not T.testC("compare LT 1 4, return 1")) assert(not T.testC("compare LE 9 1, return 1")) assert(not T.testC("compare EQ 9 9, return 1")) local b = {__lt = function (a,b) return a[1] < b[1] end} local a1,a3,a4 = setmetatable({1}, b), setmetatable({3}, b), setmetatable({4}, b) assert(T.testC("compare LT 2 5, return 1", a3, 2, 2, a4, 2, 2)) assert(T.testC("compare LE 2 5, return 1", a3, 2, 2, a4, 2, 2)) assert(T.testC("compare LT 5 -6, return 1", a4, 2, 2, a3, 2, 2)) a,b = T.testC("compare LT 5 -6, return 2", a1, 2, 2, a3, 2, 20) assert(a == 20 and b == false) a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a3, 2, 20) assert(a == 20 and b == false) a,b = T.testC("compare LE 5 -6, return 2", a1, 2, 2, a1, 2, 20) assert(a == 20 and b == true) -- testing length local t = setmetatable({x = 20}, {__len = function (t) return t.x end}) a,b,c = T.testC([[ len 2; Llen 2; objsize 2; return 3 ]], t) assert(a == 20 and b == 20 and c == 0) t.x = "234"; t[1] = 20 a,b,c = T.testC([[ len 2; Llen 2; objsize 2; return 3 ]], t) assert(a == "234" and b == 234 and c == 1) t.x = print; t[1] = 20 a,c = T.testC([[ len 2; objsize 2; return 2 ]], t) assert(a == print and c == 1) -- testing __concat a = setmetatable({x="u"}, {__concat = function (a,b) return a.x..'.'..b.x end}) x,y = T.testC([[ pushnum 5 pushvalue 2; pushvalue 2; concat 2; pushvalue -2; return 2; ]], a, a) assert(x == a..a and y == 5) -- concat with 0 elements assert(T.testC("concat 0; return 1") == "") -- concat with 1 element assert(T.testC("concat 1; return 1", "xuxu") == "xuxu") -- testing lua_is function B(x) return x and 1 or 0 end function count (x, n) n = n or 2 local prog = [[ isnumber %d; isstring %d; isfunction %d; iscfunction %d; istable %d; isuserdata %d; isnil %d; isnull %d; return 8 ]] prog = string.format(prog, n, n, n, n, n, n, n, n) local a,b,c,d,e,f,g,h = T.testC(prog, x) return B(a)+B(b)+B(c)+B(d)+B(e)+B(f)+B(g)+(100*B(h)) end assert(count(3) == 2) assert(count('alo') == 1) assert(count('32') == 2) assert(count({}) == 1) assert(count(print) == 2) assert(count(function () end) == 1) assert(count(nil) == 1) assert(count(io.stdin) == 1) assert(count(nil, 15) == 100) -- testing lua_to... function to (s, x, n) n = n or 2 return T.testC(string.format("%s %d; return 1", s, n), x) end assert(to("tostring", {}) == nil) assert(to("tostring", "alo") == "alo") assert(to("tostring", 12) == "12") assert(to("tostring", 12, 3) == nil) assert(to("objsize", {}) == 0) assert(to("objsize", {1,2,3}) == 3) assert(to("objsize", "alo\0\0a") == 6) assert(to("objsize", T.newuserdata(0)) == 0) assert(to("objsize", T.newuserdata(101)) == 101) assert(to("objsize", 124) == 0) assert(to("objsize", true) == 0) assert(to("tonumber", {}) == 0) assert(to("tonumber", "12") == 12) assert(to("tonumber", "s2") == 0) assert(to("tonumber", 1, 20) == 0) assert(to("topointer", 10) == 0) assert(to("topointer", true) == 0) assert(to("topointer", T.pushuserdata(20)) == 20) assert(to("topointer", io.read) ~= 0) -- light C function assert(to("topointer", type) ~= 0) -- "heavy" C function assert(to("topointer", function () end) ~= 0) -- Lua function assert(to("func2num", 20) == 0) assert(to("func2num", T.pushuserdata(10)) == 0) assert(to("func2num", io.read) ~= 0) -- light C function assert(to("func2num", type) ~= 0) -- "heavy" C function (with upvalue) a = to("tocfunction", math.deg) assert(a(3) == math.deg(3) and a == math.deg) print("testing panic function") do -- trivial error assert(T.checkpanic("pushstring hi; error") == "hi") -- using the stack inside panic assert(T.checkpanic("pushstring hi; error;", [[checkstack 5 XX pushstring ' alo' pushstring ' mundo' concat 3]]) == "hi alo mundo") -- "argerror" without frames assert(T.checkpanic("loadstring 4") == "bad argument #4 (string expected, got no value)") -- memory error T.totalmem(T.totalmem()+10000) -- set low memory limit (+10k) assert(T.checkpanic("newuserdata 20000") == "not enough memory") T.totalmem(0) -- restore high limit -- stack error if not _soft then local msg = T.checkpanic[[ pushstring "function f() f() end" loadstring -1; call 0 0 getglobal f; call 0 0 ]] assert(string.find(msg, "stack overflow")) end end -- testing deep C stack if not _soft then print("testing stack overflow") collectgarbage("stop") checkerr("XXXX", T.testC, "checkstack 1000023 XXXX") -- too deep -- too deep (with no message) checkerr("^stack overflow$", T.testC, "checkstack 1000023 ''") local s = string.rep("pushnil;checkstack 1 XX;", 1000000) checkerr("XX", T.testC, s) collectgarbage("restart") print'+' end local lim = _soft and 500 or 12000 local prog = {"checkstack " .. (lim * 2 + 100) .. "msg", "newtable"} for i = 1,lim do prog[#prog + 1] = "pushnum " .. i prog[#prog + 1] = "pushnum " .. i * 10 end prog[#prog + 1] = "rawgeti R 2" -- get global table in registry prog[#prog + 1] = "insert " .. -(2*lim + 2) for i = 1,lim do prog[#prog + 1] = "settable " .. -(2*(lim - i + 1) + 1) end prog[#prog + 1] = "return 2" prog = table.concat(prog, ";") local g, t = T.testC(prog) assert(g == _G) for i = 1,lim do assert(t[i] == i*10); t[i] = nil end assert(next(t) == nil) prog, g, t = nil -- testing errors a = T.testC([[ loadstring 2; pcall 0 1 0; pushvalue 3; insert -2; pcall 1 1 0; pcall 0 0 0; return 1 ]], "x=150", function (a) assert(a==nil); return 3 end) assert(type(a) == 'string' and x == 150) function check3(p, ...) local arg = {...} assert(#arg == 3) assert(string.find(arg[3], p)) end check3(":1:", T.testC("loadstring 2; gettop; return .", "x=")) check3("%.", T.testC("loadfile 2; gettop; return .", ".")) check3("xxxx", T.testC("loadfile 2; gettop; return .", "xxxx")) -- test errors in non protected threads function checkerrnopro (code, msg) local th = coroutine.create(function () end) -- create new thread local stt, err = pcall(T.testC, th, code) -- run code there assert(not stt and string.find(err, msg)) end if not _soft then checkerrnopro("pushnum 3; call 0 0", "attempt to call") print"testing stack overflow in unprotected thread" function f () f() end checkerrnopro("getglobal 'f'; call 0 0;", "stack overflow") end print"+" -- testing table access do -- getp/setp local a = {} T.testC("rawsetp 2 1", a, 20) assert(a[T.pushuserdata(1)] == 20) assert(T.testC("rawgetp 2 1; return 1", a) == 20) end a = {x=0, y=12} x, y = T.testC("gettable 2; pushvalue 4; gettable 2; return 2", a, 3, "y", 4, "x") assert(x == 0 and y == 12) T.testC("settable -5", a, 3, 4, "x", 15) assert(a.x == 15) a[a] = print x = T.testC("gettable 2; return 1", a) -- table and key are the same object! assert(x == print) T.testC("settable 2", a, "x") -- table and key are the same object! assert(a[a] == "x") b = setmetatable({p = a}, {}) getmetatable(b).__index = function (t, i) return t.p[i] end k, x = T.testC("gettable 3, return 2", 4, b, 20, 35, "x") assert(x == 15 and k == 35) getmetatable(b).__index = function (t, i) return a[i] end getmetatable(b).__newindex = function (t, i,v ) a[i] = v end y = T.testC("insert 2; gettable -5; return 1", 2, 3, 4, "y", b) assert(y == 12) k = T.testC("settable -5, return 1", b, 3, 4, "x", 16) assert(a.x == 16 and k == 4) a[b] = 'xuxu' y = T.testC("gettable 2, return 1", b) assert(y == 'xuxu') T.testC("settable 2", b, 19) assert(a[b] == 19) -- testing next a = {} t = pack(T.testC("next; gettop; return .", a, nil)) tcheck(t, {n=1,a}) a = {a=3} t = pack(T.testC("next; gettop; return .", a, nil)) tcheck(t, {n=3,a,'a',3}) t = pack(T.testC("next; pop 1; next; gettop; return .", a, nil)) tcheck(t, {n=1,a}) -- testing upvalues do local A = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]] t, b, c = A([[pushvalue U0; pushvalue U1; pushvalue U2; return 3]]) assert(b == 10 and c == 20 and type(t) == 'table') a, b = A([[tostring U3; tonumber U4; return 2]]) assert(a == nil and b == 0) A([[pushnum 100; pushnum 200; replace U2; replace U1]]) b, c = A([[pushvalue U1; pushvalue U2; return 2]]) assert(b == 100 and c == 200) A([[replace U2; replace U1]], {x=1}, {x=2}) b, c = A([[pushvalue U1; pushvalue U2; return 2]]) assert(b.x == 1 and c.x == 2) T.checkmemory() end -- testing absent upvalues from C-function pointers assert(T.testC[[isnull U1; return 1]] == true) assert(T.testC[[isnull U100; return 1]] == true) assert(T.testC[[pushvalue U1; return 1]] == nil) local f = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]] assert(T.upvalue(f, 1) == 10 and T.upvalue(f, 2) == 20 and T.upvalue(f, 3) == nil) T.upvalue(f, 2, "xuxu") assert(T.upvalue(f, 2) == "xuxu") -- large closures do local A = "checkstack 300 msg;" .. string.rep("pushnum 10;", 255) .. "pushcclosure 255; return 1" A = T.testC(A) for i=1,255 do assert(A(("pushvalue U%d; return 1"):format(i)) == 10) end assert(A("isnull U256; return 1")) assert(not A("isnil U256; return 1")) end -- testing get/setuservalue -- bug in 5.1.2 checkerr("got number", debug.setuservalue, 3, {}) checkerr("got nil", debug.setuservalue, nil, {}) checkerr("got light userdata", debug.setuservalue, T.pushuserdata(1), {}) local b = T.newuserdata(0) assert(debug.getuservalue(b) == nil) for _, v in pairs{true, false, 4.56, print, {}, b, "XYZ"} do assert(debug.setuservalue(b, v) == b) assert(debug.getuservalue(b) == v) end assert(debug.getuservalue(4) == nil) debug.setuservalue(b, function () return 10 end) collectgarbage() -- function should not be collected assert(debug.getuservalue(b)() == 10) debug.setuservalue(b, 134) collectgarbage() -- number should not be a problem for collector assert(debug.getuservalue(b) == 134) -- test barrier for uservalues T.gcstate("atomic") assert(T.gccolor(b) == "black") debug.setuservalue(b, {x = 100}) T.gcstate("pause") -- complete collection assert(debug.getuservalue(b).x == 100) -- uvalue should be there -- long chain of userdata for i = 1, 1000 do local bb = T.newuserdata(0) debug.setuservalue(bb, b) b = bb end collectgarbage() -- nothing should not be collected for i = 1, 1000 do b = debug.getuservalue(b) end assert(debug.getuservalue(b).x == 100) b = nil -- testing locks (refs) -- reuse of references local i = T.ref{} T.unref(i) assert(T.ref{} == i) Arr = {} Lim = 100 for i=1,Lim do -- lock many objects Arr[i] = T.ref({}) end assert(T.ref(nil) == -1 and T.getref(-1) == nil) T.unref(-1); T.unref(-1) for i=1,Lim do -- unlock all them T.unref(Arr[i]) end function printlocks () local f = T.makeCfunc("gettable R; return 1") local n = f("n") print("n", n) for i=0,n do print(i, f(i)) end end for i=1,Lim do -- lock many objects Arr[i] = T.ref({}) end for i=1,Lim,2 do -- unlock half of them T.unref(Arr[i]) end assert(type(T.getref(Arr[2])) == 'table') assert(T.getref(-1) == nil) a = T.ref({}) collectgarbage() assert(type(T.getref(a)) == 'table') -- colect in cl the `val' of all collected userdata tt = {} cl = {n=0} A = nil; B = nil local F F = function (x) local udval = T.udataval(x) table.insert(cl, udval) local d = T.newuserdata(100) -- cria lixo d = nil assert(debug.getmetatable(x).__gc == F) assert(load("table.insert({}, {})"))() -- cria mais lixo collectgarbage() -- forca coleta de lixo durante coleta! assert(debug.getmetatable(x).__gc == F) -- coleta anterior nao melou isso? local dummy = {} -- cria lixo durante coleta if A ~= nil then assert(type(A) == "userdata") assert(T.udataval(A) == B) debug.getmetatable(A) -- just acess it end A = x -- ressucita userdata B = udval return 1,2,3 end tt.__gc = F -- test whether udate collection frees memory in the right time do collectgarbage(); collectgarbage(); local x = collectgarbage("count"); local a = T.newuserdata(5001) assert(T.testC("objsize 2; return 1", a) == 5001) assert(collectgarbage("count") >= x+4) a = nil collectgarbage(); assert(collectgarbage("count") <= x+1) -- udata without finalizer x = collectgarbage("count") collectgarbage("stop") for i=1,1000 do T.newuserdata(0) end assert(collectgarbage("count") > x+10) collectgarbage() assert(collectgarbage("count") <= x+1) -- udata with finalizer collectgarbage() x = collectgarbage("count") collectgarbage("stop") a = {__gc = function () end} for i=1,1000 do debug.setmetatable(T.newuserdata(0), a) end assert(collectgarbage("count") >= x+10) collectgarbage() -- this collection only calls TM, without freeing memory assert(collectgarbage("count") >= x+10) collectgarbage() -- now frees memory assert(collectgarbage("count") <= x+1) collectgarbage("restart") end collectgarbage("stop") -- create 3 userdatas with tag `tt' a = T.newuserdata(0); debug.setmetatable(a, tt); na = T.udataval(a) b = T.newuserdata(0); debug.setmetatable(b, tt); nb = T.udataval(b) c = T.newuserdata(0); debug.setmetatable(c, tt); nc = T.udataval(c) -- create userdata without meta table x = T.newuserdata(4) y = T.newuserdata(0) checkerr("FILE%* expected, got userdata", io.input, a) checkerr("FILE%* expected, got userdata", io.input, x) assert(debug.getmetatable(x) == nil and debug.getmetatable(y) == nil) d=T.ref(a); e=T.ref(b); f=T.ref(c); t = {T.getref(d), T.getref(e), T.getref(f)} assert(t[1] == a and t[2] == b and t[3] == c) t=nil; a=nil; c=nil; T.unref(e); T.unref(f) collectgarbage() -- check that unref objects have been collected assert(#cl == 1 and cl[1] == nc) x = T.getref(d) assert(type(x) == 'userdata' and debug.getmetatable(x) == tt) x =nil tt.b = b -- create cycle tt=nil -- frees tt for GC A = nil b = nil T.unref(d); n5 = T.newuserdata(0) debug.setmetatable(n5, {__gc=F}) n5 = T.udataval(n5) collectgarbage() assert(#cl == 4) -- check order of collection assert(cl[2] == n5 and cl[3] == nb and cl[4] == na) collectgarbage"restart" a, na = {}, {} for i=30,1,-1 do a[i] = T.newuserdata(0) debug.setmetatable(a[i], {__gc=F}) na[i] = T.udataval(a[i]) end cl = {} a = nil; collectgarbage() assert(#cl == 30) for i=1,30 do assert(cl[i] == na[i]) end na = nil for i=2,Lim,2 do -- unlock the other half T.unref(Arr[i]) end x = T.newuserdata(41); debug.setmetatable(x, {__gc=F}) assert(T.testC("objsize 2; return 1", x) == 41) cl = {} a = {[x] = 1} x = T.udataval(x) collectgarbage() -- old `x' cannot be collected (`a' still uses it) assert(#cl == 0) for n in pairs(a) do a[n] = nil end collectgarbage() assert(#cl == 1 and cl[1] == x) -- old `x' must be collected -- testing lua_equal assert(T.testC("compare EQ 2 4; return 1", print, 1, print, 20)) assert(T.testC("compare EQ 3 2; return 1", 'alo', "alo")) assert(T.testC("compare EQ 2 3; return 1", nil, nil)) assert(not T.testC("compare EQ 2 3; return 1", {}, {})) assert(not T.testC("compare EQ 2 3; return 1")) assert(not T.testC("compare EQ 2 3; return 1", 3)) -- testing lua_equal with fallbacks do local map = {} local t = {__eq = function (a,b) return map[a] == map[b] end} local function f(x) local u = T.newuserdata(0) debug.setmetatable(u, t) map[u] = x return u end assert(f(10) == f(10)) assert(f(10) ~= f(11)) assert(T.testC("compare EQ 2 3; return 1", f(10), f(10))) assert(not T.testC("compare EQ 2 3; return 1", f(10), f(20))) t.__eq = nil assert(f(10) ~= f(10)) end print'+' -- testing changing hooks during hooks _G.t = {} T.sethook([[ # set a line hook after 3 count hooks sethook 4 0 ' getglobal t; pushvalue -3; append -2 pushvalue -2; append -2 ']], "c", 3) local a = 1 -- counting a = 1 -- counting a = 1 -- count hook (set line hook) a = 1 -- line hook a = 1 -- line hook debug.sethook() t = _G.t assert(t[1] == "line") line = t[2] assert(t[3] == "line" and t[4] == line + 1) assert(t[5] == "line" and t[6] == line + 2) assert(t[7] == nil) ------------------------------------------------------------------------- do -- testing errors during GC local a = {} for i=1,20 do a[i] = T.newuserdata(i) -- creates several udata end for i=1,20,2 do -- mark half of them to raise errors during GC debug.setmetatable(a[i], {__gc = function (x) error("error inside gc") end}) end for i=2,20,2 do -- mark the other half to count and to create more garbage debug.setmetatable(a[i], {__gc = function (x) load("A=A+1")() end}) end _G.A = 0 a = 0 while 1 do local stat, msg = pcall(collectgarbage) if stat then break -- stop when no more errors else a = a + 1 assert(string.find(msg, "__gc")) end end assert(a == 10) -- number of errors assert(A == 10) -- number of normal collections end ------------------------------------------------------------------------- -- test for userdata vals do local a = {}; local lim = 30 for i=0,lim do a[i] = T.pushuserdata(i) end for i=0,lim do assert(T.udataval(a[i]) == i) end for i=0,lim do assert(T.pushuserdata(i) == a[i]) end for i=0,lim do a[a[i]] = i end for i=0,lim do a[T.pushuserdata(i)] = i end assert(type(tostring(a[1])) == "string") end ------------------------------------------------------------------------- -- testing multiple states T.closestate(T.newstate()); L1 = T.newstate() assert(L1) assert(T.doremote(L1, "X='a'; return 'a'") == 'a') assert(#pack(T.doremote(L1, "function f () return 'alo', 3 end; f()")) == 0) a, b = T.doremote(L1, "return f()") assert(a == 'alo' and b == '3') T.doremote(L1, "_ERRORMESSAGE = nil") -- error: `sin' is not defined a, _, b = T.doremote(L1, "return sin(1)") assert(a == nil and b == 2) -- 2 == run-time error -- error: syntax error a, b, c = T.doremote(L1, "return a+") assert(a == nil and c == 3 and type(b) == "string") -- 3 == syntax error T.loadlib(L1) a, b, c = T.doremote(L1, [[ string = require'string' a = require'_G'; assert(a == _G and require("_G") == a) io = require'io'; assert(type(io.read) == "function") assert(require("io") == io) a = require'table'; assert(type(a.insert) == "function") a = require'debug'; assert(type(a.getlocal) == "function") a = require'math'; assert(type(a.sin) == "function") return string.sub('okinama', 1, 2) ]]) assert(a == "ok") T.closestate(L1); L1 = T.newstate() T.loadlib(L1) T.doremote(L1, "a = {}") T.testC(L1, [[getglobal "a"; pushstring "x"; pushint 1; settable -3]]) assert(T.doremote(L1, "return a.x") == "1") T.closestate(L1) L1 = nil print('+') ------------------------------------------------------------------------- -- testing memory limits ------------------------------------------------------------------------- checkerr("block too big", T.newuserdata, math.maxinteger) collectgarbage() T.totalmem(T.totalmem()+5000) -- set low memory limit (+5k) checkerr("not enough memory", load"local a={}; for i=1,100000 do a[i]=i end") T.totalmem(0) -- restore high limit -- test memory errors; increase memory limit in small steps, so that -- we get memory errors in different parts of a given task, up to there -- is enough memory to complete the task without errors function testamem (s, f) collectgarbage(); collectgarbage() local M = T.totalmem() local oldM = M local a,b = nil while 1 do M = M+7 -- increase memory limit in small steps T.totalmem(M) a, b = pcall(f) T.totalmem(0) -- restore high limit if a and b then break end -- stop when no more errors collectgarbage() if not a and not -- `real' error? (string.find(b, "memory") or string.find(b, "overflow")) then error(b, 0) -- propagate it end end print("\nlimit for " .. s .. ": " .. M-oldM) return b end -- testing memory errors when creating a new state b = testamem("state creation", T.newstate) T.closestate(b); -- close new state -- testing threads -- get main thread from registry (at index LUA_RIDX_MAINTHREAD == 1) mt = T.testC("rawgeti R 1; return 1") assert(type(mt) == "thread" and coroutine.running() == mt) function expand (n,s) if n==0 then return "" end local e = string.rep("=", n) return string.format("T.doonnewstack([%s[ %s;\n collectgarbage(); %s]%s])\n", e, s, expand(n-1,s), e) end G=0; collectgarbage(); a =collectgarbage("count") load(expand(20,"G=G+1"))() assert(G==20); collectgarbage(); -- assert(gcinfo() <= a+1) testamem("thread creation", function () return T.doonnewstack("x=1") == 0 -- try to create thread end) -- testing memory x compiler testamem("loadstring", function () return load("x=1") -- try to do load a string end) local testprog = [[ local function foo () return end local t = {"x"} a = "aaa" for i = 1, #t do a=a..t[i] end return true ]] -- testing memory x dofile _G.a = nil local t =os.tmpname() local f = assert(io.open(t, "w")) f:write(testprog) f:close() testamem("dofile", function () local a = loadfile(t) return a and a() end) assert(os.remove(t)) assert(_G.a == "aaax") -- other generic tests testamem("string creation", function () local a, b = string.gsub("alo alo", "(a)", function (x) return x..'b' end) return (a == 'ablo ablo') end) testamem("dump/undump", function () local a = load(testprog) local b = a and string.dump(a) a = b and load(b) return a and a() end) local t = os.tmpname() testamem("file creation", function () local f = assert(io.open(t, 'w')) assert (not io.open"nomenaoexistente") io.close(f); return not loadfile'nomenaoexistente' end) assert(os.remove(t)) testamem("table creation", function () local a, lim = {}, 10 for i=1,lim do a[i] = i; a[i..'a'] = {} end return (type(a[lim..'a']) == 'table' and a[lim] == lim) end) testamem("constructors", function () local a = {10, 20, 30, 40, 50; a=1, b=2, c=3, d=4, e=5} return (type(a) == 'table' and a.e == 5) end) local a = 1 close = nil testamem("closure creation", function () function close (b,c) return function (x) return a+b+c+x end end return (close(2,3)(4) == 10) end) testamem("coroutines", function () local a = coroutine.wrap(function () coroutine.yield(string.rep("a", 10)) return {} end) assert(string.len(a()) == 10) return a() end) print'+' -- testing some auxlib functions local function gsub (a, b, c) a, b = T.testC("gsub 2 3 4; gettop; return 2", a, b, c) assert(b == 5) return a end assert(gsub("alo.alo.uhuh.", ".", "//") == "alo//alo//uhuh//") assert(gsub("alo.alo.uhuh.", "alo", "//") == "//.//.uhuh.") assert(gsub("", "alo", "//") == "") assert(gsub("...", ".", "/.") == "/././.") assert(gsub("...", "...", "") == "") -- testing luaL_newmetatable local mt_xuxu, res, top = T.testC("newmetatable xuxu; gettop; return 3") assert(type(mt_xuxu) == "table" and res and top == 3) local d, res, top = T.testC("newmetatable xuxu; gettop; return 3") assert(mt_xuxu == d and not res and top == 3) d, res, top = T.testC("newmetatable xuxu1; gettop; return 3") assert(mt_xuxu ~= d and res and top == 3) x = T.newuserdata(0); y = T.newuserdata(0); T.testC("pushstring xuxu; gettable R; setmetatable 2", x) assert(getmetatable(x) == mt_xuxu) -- testing luaL_testudata -- correct metatable local res1, res2, top = T.testC([[testudata -1 xuxu testudata 2 xuxu gettop return 3]], x) assert(res1 and res2 and top == 4) -- wrong metatable res1, res2, top = T.testC([[testudata -1 xuxu1 testudata 2 xuxu1 gettop return 3]], x) assert(not res1 and not res2 and top == 4) -- non-existent type res1, res2, top = T.testC([[testudata -1 xuxu2 testudata 2 xuxu2 gettop return 3]], x) assert(not res1 and not res2 and top == 4) -- userdata has no metatable res1, res2, top = T.testC([[testudata -1 xuxu testudata 2 xuxu gettop return 3]], y) assert(not res1 and not res2 and top == 4) -- erase metatables do local r = debug.getregistry() assert(r.xuxu == mt_xuxu and r.xuxu1 == d) r.xuxu = nil; r.xuxu1 = nil end print'OK'
bsd-3-clause
opentechinstitute/luci
applications/luci-pbx/luasrc/model/cbi/pbx-users.lua
146
5623
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx 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. luci-pbx 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 luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end modulename = "pbx-users" modulenamecalls = "pbx-calls" modulenameadvanced = "pbx-advanced" m = Map (modulename, translate("User Accounts"), translate("Here you must configure at least one SIP account, that you \ will use to register with this service. Use this account either in an Analog Telephony \ Adapter (ATA), or in a SIP software like CSipSimple, Linphone, or Sipdroid on your \ smartphone, or Ekiga, Linphone, or X-Lite on your computer. By default, all SIP accounts \ will ring simultaneously if a call is made to one of your VoIP provider accounts or GV \ numbers.")) -- Recreate the config, and restart services after changes are commited to the configuration. function m.on_after_commit(self) luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null") end externhost = m.uci:get(modulenameadvanced, "advanced", "externhost") bindport = m.uci:get(modulenameadvanced, "advanced", "bindport") ipaddr = m.uci:get("network", "lan", "ipaddr") ----------------------------------------------------------------------------- s = m:section(NamedSection, "server", "user", translate("Server Setting")) s.anonymous = true if ipaddr == nil or ipaddr == "" then ipaddr = "(IP address not static)" end if bindport ~= nil then just_ipaddr = ipaddr ipaddr = ipaddr .. ":" .. bindport end s:option(DummyValue, "ipaddr", translate("Server Setting for Local SIP Devices"), translate("Enter this IP (or IP:port) in the Server/Registrar setting of SIP devices you will \ use ONLY locally and never from a remote location.")).default = ipaddr if externhost ~= nil then if bindport ~= nil then just_externhost = externhost externhost = externhost .. ":" .. bindport end s:option(DummyValue, "externhost", translate("Server Setting for Remote SIP Devices"), translate("Enter this hostname (or hostname:port) in the Server/Registrar setting of SIP \ devices you will use from a remote location (they will work locally too).") ).default = externhost end if bindport ~= nil then s:option(DummyValue, "bindport", translate("Port Setting for SIP Devices"), translatef("If setting Server/Registrar to %s or %s does not work for you, try setting \ it to %s or %s and entering this port number in a separate field that specifies the \ Server/Registrar port number. Beware that some devices have a confusing \ setting that sets the port where SIP requests originate from on the SIP \ device itself (the bind port). The port specified on this page is NOT this bind port \ but the port this service listens on.", ipaddr, externhost, just_ipaddr, just_externhost)).default = bindport end ----------------------------------------------------------------------------- s = m:section(TypedSection, "local_user", translate("SIP Device/Softphone Accounts")) s.anonymous = true s.addremove = true s:option(Value, "fullname", translate("Full Name"), translate("You can specify a real name to show up in the Caller ID here.")) du = s:option(Value, "defaultuser", translate("User Name"), translate("Use (four to five digit) numeric user name if you are connecting normal telephones \ with ATAs to this system (so they can dial user names).")) du.datatype = "uciname" pwd = s:option(Value, "secret", translate("Password"), translate("Your password disappears when saved for your protection. It will be changed \ only when you enter a value different from the saved one.")) pwd.password = true pwd.rmempty = false -- We skip reading off the saved value and return nothing. function pwd.cfgvalue(self, section) return "" end -- We check the entered value against the saved one, and only write if the entered value is -- something other than the empty string, and it differes from the saved value. function pwd.write(self, section, value) local orig_pwd = m:get(section, self.option) if value and #value > 0 and orig_pwd ~= value then Value.write(self, section, value) end end p = s:option(ListValue, "ring", translate("Receives Incoming Calls")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" p = s:option(ListValue, "can_call", translate("Makes Outgoing Calls")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" return m
apache-2.0
cyberz-eu/octopus
extensions/core/src/fileutil.lua
1
3474
local lfs = require "lfs" local exception = require "exception" local util = require "util" local function noBackDirectory (path) if path == ".." or path:find("/..", 1, true) or path:find("../", 1, true) then exception("no back directory allowed") end end local function countBackDirectories (path) local uris = util.split(path, "/") if uris[#uris] == ".." or uris[#uris] == "." or uris[#uris] == "" then exception("invalid path") end local back, entry = 0, 0 for i=1, #uris-1 do if uris[i] == ".." then back = back + 1 if uris[i+1] ~= ".." then -- end of pair if entry < back then exception("invalid path") else back, entry = 0, 0 end end elseif uris[i] ~= "." and uris[i] ~= "" then entry = entry + 1 end end end local function remove (file) local attr, err = lfs.attributes(file) if not attr then return end -- cannot obtain information from file / file does not exist if attr.mode == "directory" then local dir = file for entry in lfs.dir(dir) do if entry ~= "." and entry ~= ".." then local path if dir ~= "/" then path = dir .. "/" .. entry else path = "/" .. entry end local attr = lfs.attributes(path) if not attr then attr = lfs.symlinkattributes(path) end if not attr then exception(path .. " has no attributes") elseif attr.mode == "directory" then remove(path) else local ok, err = os.remove(path) if not ok then exception(err) end end end end local ok, err = os.remove(dir) if not ok then exception(err) end else local ok, err = os.remove(file) if not ok then exception(err) end end end local function filterFiles (dir, f) if dir then for entry in lfs.dir(dir) do if entry ~= "." and entry ~= ".." then local path if dir ~= "/" then path = dir .. "/" .. entry else path = "/" .. entry end local attr = lfs.attributes(path) if attr and attr.mode == "file" then f(path) end end end end end local function createDirectory (path) local ok, err = lfs.mkdir(path) if not ok then exception(err) end end local function quoteCommandlineArgument (str) if str then return [[']] .. str:replace([[']], [['\'']], true) .. [[']] else return "" end end local specialCharacters = { [[\]], -- must be first [[`]], [[~]], [[!]], [[@]], [[#]], [[$]], [[%]], [[^]], [[&]], [[*]], [[(]], [[)]], [=[]]=], [=[[]=], [[{]], [[}]], [[:]], [[;]], [["]], [[']], [[|]], [[>]], [[<]], [[.]], [[,]], [[?]], [[/]], [[ ]], -- space must be last } local function escapeCommandlineSpecialCharacters (str) if str then for i=1,#specialCharacters do str = str:replace(specialCharacters[i], "\\" .. specialCharacters[i], true) end return str else return "" end end local function noCommandlineSpecialCharacters (str) if str then for i=1,#specialCharacters do if str:find(specialCharacters[i], 1, true) then exception("no command line special characters") end end end end return { noBackDirectory = noBackDirectory, countBackDirectories = countBackDirectories, remove = remove, removeFile = remove, removeDirectory = remove, createDirectory = createDirectory, filterFiles = filterFiles, quoteCommandlineArgument = quoteCommandlineArgument, escapeCommandlineSpecialCharacters = escapeCommandlineSpecialCharacters, noCommandlineSpecialCharacters = noCommandlineSpecialCharacters, }
bsd-2-clause
DuffsDevice/winds
arm9/data/program.calculator.lua
1
9257
--FILE_ICON = %APPDATA%/CalcIcon.bmp --AUTHOR = WinDS --FILE_NAME = Calculator --WND_TITLE = Calculator --VERSION = 1.1 --DESC = Basic Calculator --COPYRIGHT = (C) 2014 --LANG = neutral using "System.Event" using "Drawing.Bitmap" using "Drawing.Font" using "Drawing.Color" using "UI.Gadget" using "UI.Button" using "UI.Label" using "UI.MainFrame" local wnd local btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0 local btnClear, btnBackspace, btnEqual, btnComma, btnAdd, btnSub, btnMul, btnDiv, btnSqrt, btnSign local label local CURNUMBER = "0" local OPERAND_FIRST = nil local OPERAND_SECOND = nil local OPERATOR = nil -- Calculator State: -- 1: Entering First Number -- 2: Operator Set -- 3: Entering Second Number local calcState = 1 function main() local btnStartX = 1 local btnStartY = 12 local btnWidth = 17 local btnHeight = 12 local btnWidthEx = btnWidth + 1; local btnHeightEx = btnHeight + 1; local winWidth = btnStartX + btnWidthEx * 4 + 2 local winHeight = btnStartY + btnHeightEx * 5 + 11 -- Create Window wnd = System.getMainFrame( winWidth , winHeight , "notResizeable | draggable" ) wnd.icon = getLogo() -- Create Label label = Label( 1 , 1 , winWidth - 4 , 10 , CURNUMBER ) label.align = "right" label.ellipsis = true label.bgColor = Color.fromRGB( 27 , 29 , 31 ) -------------------- -- Create Buttons -- -------------------- -- First row btnClear = Button( btnStartX , btnStartY , btnWidth , btnHeight , "C" ) btnBackspace = Button( btnStartX + btnWidthEx * 1 , btnStartY , btnWidth , btnHeight , "←" ) btnAdd = Button( btnStartX + btnWidthEx * 2 , btnStartY , btnWidth , btnHeight , "+" ) btnSub = Button( btnStartX + btnWidthEx * 3 , btnStartY , btnWidth , btnHeight , "-" ) -- Second btn1 = Button( btnStartX , btnStartY + btnHeightEx * 1 , btnWidth , btnHeight , "1" , "clickRepeat" ) btn2 = Button( btnStartX + btnWidthEx * 1 , btnStartY + btnHeightEx * 1 , btnWidth , btnHeight , "2" , "clickRepeat" ) btn3 = Button( btnStartX + btnWidthEx * 2 , btnStartY + btnHeightEx * 1 , btnWidth , btnHeight , "3" , "clickRepeat" ) btnMul = Button( btnStartX + btnWidthEx * 3 , btnStartY + btnHeightEx * 1 , btnWidth , btnHeight , "×" ) -- Third btn4 = Button( btnStartX , btnStartY + btnHeightEx * 2 , btnWidth , btnHeight , "4" , "clickRepeat" ) btn5 = Button( btnStartX + btnWidthEx * 1 , btnStartY + btnHeightEx * 2 , btnWidth , btnHeight , "5" , "clickRepeat" ) btn6 = Button( btnStartX + btnWidthEx * 2 , btnStartY + btnHeightEx * 2 , btnWidth , btnHeight , "6" , "clickRepeat" ) btnDiv = Button( btnStartX + btnWidthEx * 3 , btnStartY + btnHeightEx * 2 , btnWidth , btnHeight , "÷" ) -- Fourth btn7 = Button( btnStartX , btnStartY + btnHeightEx * 3 , btnWidth , btnHeight , "7" , "clickRepeat" ) btn8 = Button( btnStartX + btnWidthEx * 1 , btnStartY + btnHeightEx * 3 , btnWidth , btnHeight , "8" , "clickRepeat" ) btn9 = Button( btnStartX + btnWidthEx * 2 , btnStartY + btnHeightEx * 3 , btnWidth , btnHeight , "9" , "clickRepeat" ) btnSqrt = Button( btnStartX + btnWidthEx * 3 , btnStartY + btnHeightEx * 3 , btnWidth , btnHeight , "√" ) -- Fifth btnSign = Button( btnStartX , btnStartY + btnHeightEx * 4 , btnWidth , btnHeight , "±" ) btn0 = Button( btnStartX + btnWidthEx * 1 , btnStartY + btnHeightEx * 4 , btnWidth , btnHeight , "0" , "clickRepeat" ) btnComma = Button( btnStartX + btnWidthEx * 2 , btnStartY + btnHeightEx * 4 , btnWidth , btnHeight , "." ) btnEqual = Button( btnStartX + btnWidthEx * 3 , btnStartY + btnHeightEx * 4 , btnWidth , btnHeight , "=" ) -- Add Buttons wnd.addChild( btn0 ) wnd.addChild( btn1 ) wnd.addChild( btn2 ) wnd.addChild( btn3 ) wnd.addChild( btn4 ) wnd.addChild( btn5 ) wnd.addChild( btn5 ) wnd.addChild( btn6 ) wnd.addChild( btn7 ) wnd.addChild( btn8 ) wnd.addChild( btn9 ) wnd.addChild( btnComma ) wnd.addChild( btnAdd ) wnd.addChild( btnSub ) wnd.addChild( btnMul ) wnd.addChild( btnDiv ) wnd.addChild( btnBackspace ) wnd.addChild( btnClear ) wnd.addChild( btnEqual ) wnd.addChild( btnSqrt ) wnd.addChild( btnSign ) btn1.setUserEventHandler( "onMouseClick" , numberHandler ) btn2.setUserEventHandler( "onMouseClick" , numberHandler ) btn3.setUserEventHandler( "onMouseClick" , numberHandler ) btn4.setUserEventHandler( "onMouseClick" , numberHandler ) btn5.setUserEventHandler( "onMouseClick" , numberHandler ) btn6.setUserEventHandler( "onMouseClick" , numberHandler ) btn7.setUserEventHandler( "onMouseClick" , numberHandler ) btn8.setUserEventHandler( "onMouseClick" , numberHandler ) btn9.setUserEventHandler( "onMouseClick" , numberHandler ) btn0.setUserEventHandler( "onMouseClick" , numberHandler ) btnComma.setUserEventHandler( "onMouseClick" , numberHandler ) btnAdd.setUserEventHandler( "onMouseClick" , stuffHandler ) btnSub.setUserEventHandler( "onMouseClick" , stuffHandler ) btnMul.setUserEventHandler( "onMouseClick" , stuffHandler ) btnDiv.setUserEventHandler( "onMouseClick" , stuffHandler ) btnSqrt.setUserEventHandler( "onMouseClick" , stuffHandler ) btnBackspace.setUserEventHandler( "onMouseClick" , stuffHandler ) btnClear.setUserEventHandler( "onMouseClick" , stuffHandler ) btnEqual.setUserEventHandler( "onMouseClick" , stuffHandler ) btnSign.setUserEventHandler( "onMouseClick" , stuffHandler ) -- Add Label wnd.addChild( label ) end function numberHandler( event ) local number = event.gadget.text -- If an operator was set: store last entered number as OPERAND_FIRST if calcState == 2 then OPERAND_FIRST = tonumber( CURNUMBER ) CURNUMBER = "" calcState = 3 end if number == "." and string.find( CURNUMBER , "." , 1 , true ) ~= nil then return "use_internal" end -- Concat Number CURNUMBER = CURNUMBER .. number -- Ensure no leading '0' if string.sub( CURNUMBER , 1 , 1 ) == "0" and string.sub( CURNUMBER , 2 , 2 ) ~= "." then CURNUMBER = string.sub( CURNUMBER , 2 ) end -- Apply to label label.text = CURNUMBER return "use_internal" end function stuffHandler( event ) -- Fetch gadget of event local gadget = event.gadget if gadget == btnAdd then set_operator( op_add ) elseif gadget == btnSub then set_operator( op_sub ) elseif gadget == btnMul then set_operator( op_mul ) elseif gadget == btnDiv then set_operator( op_div ) elseif gadget == btnSign then if calcState == 2 then calcState = 1 OPERATOR = nil end CURNUMBER = tostring( 0 - tonumber(CURNUMBER) ) -- Apply to label label.text = CURNUMBER elseif gadget == btnClear then --reset calcState calcState = 1 OPERAND_FIRST = nil OPERAND_SECOND = nil OPERATOR = nil CURNUMBER = "0" label.text = "0" elseif gadget == btnSqrt then if calcState == 3 then solve() -- Solve equitation first, then build square root out of result end -- build number OPERAND_FIRST = tonumber( CURNUMBER ) -- compute and apply OPERAND_FIRST = math.sqrt( OPERAND_FIRST ) CURNUMBER = tostring( OPERAND_FIRST ) label.text = CURNUMBER -- reset calcState calcState = 1 OPERAND_FIRST = nil OPERATOR = nil elseif gadget == btnEqual then if calcState == 3 then -- When both operands and operator are set: compute! solve() end calcState = 1 elseif gadget == btnBackspace then removeNumber() end end function set_operator( op ) -- If we already have a valid expression: -- solve equitation and continue with the next operand if calcState == 3 then solve() end -- Set operator OPERATOR = op calcState = 2 end function removeNumber() -- Remove Operator if calcState == 2 then OPERATOR = nil calcState = 1 end -- Write '0' instead of '' if #CURNUMBER == 1 then CURNUMBER = "0" else CURNUMBER = string.sub( CURNUMBER , 1 , -2 ) end -- Write '0' instead of '-' if CURNUMBER == "-" then CURNUMBER = "0" end label.text = CURNUMBER end function solve() -- Check if all necessary things have been assembled if calcState == 3 then OPERAND_SECOND = tonumber(CURNUMBER) -- Build Seocnd operand from current displayed number OPERAND_FIRST = OPERATOR( OPERAND_FIRST , OPERAND_SECOND ) -- Write result CURNUMBER = tostring(OPERAND_FIRST) label.text = CURNUMBER -- reset OPERAND_FIRST = nil OPERATOR = nil OPERAND_SECOND = nil calcState = 1 end end function getLogo() local col = Color.fromRGB( 27 , 27 , 0 ) local logo = Bitmap( 6 , 6 , "black" ) logo.drawVerticalLine( 1 , 0 , 6 , col ) logo.drawHorizontalLine( 2 , 0 , 2 , col ) logo.drawPixel( 0 , 3 , col ) logo.drawPixel( 4 , 3 , col ) logo.drawPixel( 3 , 2 , col ) logo.drawPixel( 5 , 4 , col ) logo.drawPixel( 3 , 4 , col ) logo.drawPixel( 5 , 2 , col ) return logo end -- Basic Operations function op_add( first , second ) return first + second end function op_sub( first , second ) return first - second end function op_mul( first , second ) return first * second end function op_div( first , second ) return first / second end
mit
abasshacker/abbasone
plugins/google.lua
336
1323
do local function googlethat(query) local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&' local parameters = 'q='..(URL.escape(query) or '') -- Do the request local res, code = https.request(url..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='' i = 0 for key,val in ipairs(results) do i = i+1 stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n' end return stringresults end local function run(msg, matches) -- comment this line if you want this plugin works in private message. if not is_chat_msg(msg) then return nil end local results = googlethat(matches[1]) return stringlinks(results) end return { description = 'Returns five results from Google. Safe search is enabled by default.', usage = ' !google [terms]: Searches Google and send results', patterns = { '^!google (.*)$', '^%.[g|G]oogle (.*)$' }, run = run } end
gpl-2.0
ioiasff/khp
plugins/chat.lua
6
1252
local function run(msg) if msg.text == "hi" then return "سلام" end if msg.text == "Hi" then return "سلام جیگر" end if msg.text == "Hello" then return "سلاممم" end if msg.text == "hello" then return "سسلامم" end if msg.text == "Salam" then return "سلام علیکم " end if msg.text == "salam" then return "سلام " end if msg.text == "ارش" then return "با بابایم چیکار داری؟" end if msg.text == "arash" then return "با بابایم چیکار داری؟" end if msg.text == "Arash" then return "با بابایم چیکار داری؟" end if msg.text == "مرگ" then return "ها؟" end if msg.text == "Death" then return "ها " end if msg.text == "death" then return "ها ؟؟" end if msg.text == "DEATH" then return "ها ؟؟؟" end if msg.text == "?" then return "هممم " end if msg.text == "Bye" then return "بای" end if msg.text == "bye" then return "بای بای" end end return { description = "Chat With Robot Server", usage = "chat with robot", patterns = { "^[Hh]i$", "^[Hh]ello$", "^[Aa]rash$", "^ارش$", "^مرگ$", "^[Dd]eath$", "^[Bb]ye$", "^?$", "^[Ss]alam$", }, run = run, --privileged = true, pre_process = pre_process }
gpl-2.0
alfredtofu/thrift
lib/lua/TTransport.lua
115
2800
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- require 'Thrift' TTransportException = TException:new { UNKNOWN = 0, NOT_OPEN = 1, ALREADY_OPEN = 2, TIMED_OUT = 3, END_OF_FILE = 4, INVALID_FRAME_SIZE = 5, INVALID_TRANSFORM = 6, INVALID_CLIENT_TYPE = 7, errorCode = 0, __type = 'TTransportException' } function TTransportException:__errorCodeToString() if self.errorCode == self.NOT_OPEN then return 'Transport not open' elseif self.errorCode == self.ALREADY_OPEN then return 'Transport already open' elseif self.errorCode == self.TIMED_OUT then return 'Transport timed out' elseif self.errorCode == self.END_OF_FILE then return 'End of file' elseif self.errorCode == self.INVALID_FRAME_SIZE then return 'Invalid frame size' elseif self.errorCode == self.INVALID_TRANSFORM then return 'Invalid transform' elseif self.errorCode == self.INVALID_CLIENT_TYPE then return 'Invalid client type' else return 'Default (unknown)' end end TTransportBase = __TObject:new{ __type = 'TTransportBase' } function TTransportBase:isOpen() end function TTransportBase:open() end function TTransportBase:close() end function TTransportBase:read(len) end function TTransportBase:readAll(len) local buf, have, chunk = '', 0 while have < len do chunk = self:read(len - have) have = have + string.len(chunk) buf = buf .. chunk if string.len(chunk) == 0 then terror(TTransportException:new{ errorCode = TTransportException.END_OF_FILE }) end end return buf end function TTransportBase:write(buf) end function TTransportBase:flush() end TServerTransportBase = __TObject:new{ __type = 'TServerTransportBase' } function TServerTransportBase:listen() end function TServerTransportBase:accept() end function TServerTransportBase:close() end TTransportFactoryBase = __TObject:new{ __type = 'TTransportFactoryBase' } function TTransportFactoryBase:getTransport(trans) return trans end
apache-2.0
JarnoVgr/Mr.Green-MTA-Resources
resources/[gameplay]/gcshop/maps/maps_client.lua
1
13703
PRICE = 1000 lastWinnerPrice = 500 local main_window local tab_panel local tab = {} local aGamemodeMapTable = {} function createNextmapWindow(tabPanel) tab = {} tab.mainBuyPanel = guiCreateTab('Maps-Center', tabPanel) tab_panel = guiCreateTabPanel ( 0.01, 0.05, 0.98, 0.95, true, tab.mainBuyPanel ) tab.maps = guiCreateTab ( "All Maps", tab_panel) tab.qmaps = guiCreateTab ( "Queued Maps", tab_panel) tab.MapListSearch = guiCreateEdit ( 0.03, 0.225, 0.31, 0.05, "", true, tab.maps ) guiCreateStaticImage ( 0.34, 0.225, 0.035, 0.05, "nextmap/search.png", true, tab.maps ) tab.MapList = guiCreateGridList ( 0.03, 0.30, 0.94, 0.55, true, tab.maps ) guiGridListSetSortingEnabled(tab.MapList, false) guiGridListAddColumn( tab.MapList, "Map Name", 0.55) guiGridListAddColumn( tab.MapList, "Author", 0.5) guiGridListAddColumn( tab.MapList, "Resource Name", 1) guiGridListAddColumn( tab.MapList, "Gamemode", 0.5) tab.NextMap = guiCreateButton ( 0.49, 0.91, 0.30, 0.04, "Buy selected map", true, tab.maps ) tab.RefreshList = guiCreateButton ( 0.03, 0.91, 0.35, 0.04, "Refresh list", true, tab.maps ) addEventHandler ("onClientGUIClick", tab.NextMap, guiClickBuy, false) addEventHandler ("onClientGUIClick", tab.RefreshList, guiClickRefresh, false) addEventHandler ("onClientGUIChanged", tab.MapListSearch, guiChanged) tab.QueueList = guiCreateGridList (0.02, 0.04, 0.97, 0.92, true, tab.qmaps ) guiGridListSetSortingEnabled(tab.QueueList, false) guiGridListAddColumn( tab.QueueList, "Priority", 0.15) guiGridListAddColumn( tab.QueueList, "Map Name", 2) tab.label1 = guiCreateLabel(0.40, 0.05, 0.50, 0.11, "This is the Maps-Center. Here you can buy maps.", true, tab.maps) tab.label2 = guiCreateLabel(0.40, 0.13, 0.50, 0.12, "Select a map you like and click \"Buy selected map\"", true, tab.maps) tab.label3 = guiCreateLabel(0.40, 0.18, 0.50, 0.17, "The map will be added to the Server Queue, where all bought maps are stored until they're played", true, tab.maps) guiLabelSetHorizontalAlign(tab.label3, "left", true) -- tab.label4 = guiCreateLabel(0.40, 0.28, 0.50, 0.13, "The queued maps will have priority against the usual server map cycler!", true, tab.maps) -- guiLabelSetHorizontalAlign(tab.label4, "left", true) tab.label5 = guiCreateLabel(0.125, 0.1, 0.50, 0.12, "Price: " .. PRICE .. " GC", true, tab.maps) tab.label6 = guiCreateLabel(0.125, 0.14, 0.50, 0.08, "Price will be " .. lastWinnerPrice .. " GC \nafter you win a map", true, tab.maps) guiLabelSetColor( tab.label5, 0, 255, 0 ) guiLabelSetColor( tab.label6, 255, 0, 0 ) guiSetFont( tab.label5, "default-bold-small" ) guiSetFont( tab.label6, "default-bold-small" ) triggerServerEvent('refreshServerMaps', localPlayer) end addEventHandler('onShopInit', getResourceRootElement(), createNextmapWindow ) function loadMaps(gamemodeMapTable, queuedList) if gamemodeMapTable then aGamemodeMapTable = gamemodeMapTable for id,gamemode in pairs (gamemodeMapTable) do guiGridListSetItemText ( tab.MapList, guiGridListAddRow ( tab.MapList ), 1, gamemode.name, true, false ) if #gamemode.maps == 0 and gamemode.name ~= "no gamemode" and gamemode.name ~= "deleted maps" then local row = guiGridListAddRow ( tab.MapList ) guiGridListSetItemText ( tab.MapList, row, 1, gamemode.name, true, false ) guiGridListSetItemText ( tab.MapList, row, 2, gamemode.resname, true, false ) guiGridListSetItemText ( tab.MapList, row, 3, gamemode.resname, true, false ) else for id,map in ipairs (gamemode.maps) do local row = guiGridListAddRow ( tab.MapList ) if map.author then guiGridListSetItemText ( tab.MapList, row, 2, map.author, false, false ) end guiGridListSetItemText ( tab.MapList, row, 1, map.name, false, false ) guiGridListSetItemText ( tab.MapList, row, 3, map.resname, false, false ) guiGridListSetItemText ( tab.MapList, row, 4, gamemode.resname, false, false ) end end end for priority, mapName in ipairs(queuedList) do local row_ = guiGridListAddRow ( tab.QueueList ) guiGridListSetItemText ( tab.QueueList, row_, 1, priority, false, false ) guiGridListSetItemText ( tab.QueueList, row_, 2, queuedList[priority][1], false, false ) end end end addEvent("sendMapsToBuy", true) addEventHandler("sendMapsToBuy", getLocalPlayer(), loadMaps) addEvent('onTellClientPlayerBoughtMap', true) addEventHandler('onTellClientPlayerBoughtMap', root, function(mapName, priority) local row_ = guiGridListAddRow ( tab.QueueList ) guiGridListSetItemText ( tab.QueueList, row_, 1, priority, false, false ) guiGridListSetItemText ( tab.QueueList, row_, 2, mapName, false, false ) end) addEventHandler('onClientMapStarting', root, function(mapinfo) local name = mapinfo.name local firstQueue = guiGridListGetItemText( tab.QueueList, 0, 2) if name == firstQueue then local rows = guiGridListGetRowCount(tab.QueueList) guiGridListRemoveRow(tab.QueueList, 0) guiGridListSetItemText(tab.QueueList, 0, 1, "1", false, false) local i for i = 1, rows-1 do --local oldPriority = tonumber(guiGridListGetItemText(tab.QueueList, i, 1)) --oldPriority = tostring(oldPriority - 1) guiGridListSetItemText(tab.QueueList, i, 1, tostring(i+1), false, false) end end end) function guiClickBuy(button) if button == "left" then if not guiGridListGetSelectedItem ( tab.MapList ) == -1 then return end local mapName = guiGridListGetItemText ( tab.MapList, guiGridListGetSelectedItem( tab.MapList ), 1 ) local mapResName = guiGridListGetItemText ( tab.MapList, guiGridListGetSelectedItem( tab.MapList ), 3 ) local gamemode = guiGridListGetItemText ( tab.MapList, guiGridListGetSelectedItem( tab.MapList ), 4 ) triggerServerEvent("sendPlayerNextmapChoice", getLocalPlayer(), { mapName, mapResName, gamemode, getPlayerName(localPlayer) }) end end function guiClickRefresh(button) if button == "left" then guiGridListClear(tab.MapList) guiGridListClear(tab.QueueList) triggerServerEvent('refreshServerMaps', localPlayer) end end function guiChanged() guiGridListClear(tab.MapList) local text = string.lower(guiGetText(source)) if ( text == "" ) then for id,gamemode in pairs (aGamemodeMapTable) do guiGridListSetItemText ( tab.MapList, guiGridListAddRow ( tab.MapList ), 1, gamemode.name, true, false ) if #gamemode.maps == 0 and gamemode.name ~= "no gamemode" and gamemode.name ~= "deleted maps" then local row = guiGridListAddRow ( tab.MapList ) guiGridListSetItemText ( tab.MapList, row, 1, gamemode.name, false, false ) if map.author then guiGridListSetItemText ( tab.MapList, row, 2, map.author, false, false ) end guiGridListSetItemText ( tab.MapList, row, 3, gamemode.resname, false, false ) guiGridListSetItemText ( tab.MapList, row, 4, gamemode.resname, false, false ) else for id,map in ipairs (gamemode.maps) do local row = guiGridListAddRow ( tab.MapList ) guiGridListSetItemText ( tab.MapList, row, 1, map.name, false, false ) if map.author then guiGridListSetItemText ( tab.MapList, row, 2, map.author, false, false ) end guiGridListSetItemText ( tab.MapList, row, 3, map.resname, false, false ) guiGridListSetItemText ( tab.MapList, row, 4, gamemode.resname, false, false ) end end end else for id,gamemode in pairs (aGamemodeMapTable) do local gameModeRow = guiGridListAddRow ( tab.MapList ) local noMaps = true guiGridListSetItemText ( tab.MapList, gameModeRow, 1, gamemode.name, true, false ) if #gamemode.maps == 0 and gamemode.name ~= "no gamemode" and gamemode.name ~= "deleted maps" then if string.find(string.lower(gamemode.name.." "..gamemode.resname), text, 1, true) then local row = guiGridListAddRow ( tab.MapList ) guiGridListSetItemText ( tab.MapList, row, 1, gamemode.name, false, false ) if map.author then guiGridListSetItemText ( tab.MapList, row, 2, map.author, false, false ) end guiGridListSetItemText ( tab.MapList, row, 3, gamemode.resname, false, false ) guiGridListSetItemText ( tab.MapList, row, 4, gamemode.resname, false, false ) noMaps = false end else for id,map in ipairs (gamemode.maps) do if not map.author then compareTo = string.lower(map.name.." "..map.resname) else compareTo = string.lower(map.name.." "..map.resname.." "..map.author) end if string.find(compareTo, text, 1, true) then local row = guiGridListAddRow ( tab.MapList ) guiGridListSetItemText ( tab.MapList, row, 1, map.name, false, false ) if map.author then guiGridListSetItemText ( tab.MapList, row, 2, map.author, false, false ) end guiGridListSetItemText ( tab.MapList, row, 3, map.resname, false, false ) guiGridListSetItemText ( tab.MapList, row, 4, gamemode.resname, false, false ) noMaps = false end end end if noMaps then guiGridListRemoveRow(tab.MapList, gameModeRow) end end end end addEvent('onGCShopWinnerDiscount', true) addEventHandler('onGCShopWinnerDiscount', root, function() if source == localPlayer then guiLabelSetColor( tab.label5, 255, 0, 0 ) guiSetText(tab.label5, "Winner Discount Price: " .. lastWinnerPrice .. " GC" ) else guiLabelSetColor( tab.label5, 0, 255, 0 ) guiSetText(tab.label5, "Price: " .. PRICE .. " GC" ) end end) function var_dump(...) -- default options local verbose = false local firstLevel = true local outputDirectly = true local noNames = false local indentation = "\t\t\t\t\t\t" local depth = nil local name = nil local output = {} for k,v in ipairs(arg) do -- check for modifiers if type(v) == "string" and k < #arg and v:sub(1,1) == "-" then local modifiers = v:sub(2) if modifiers:find("v") ~= nil then verbose = true end if modifiers:find("s") ~= nil then outputDirectly = false end if modifiers:find("n") ~= nil then verbose = false end if modifiers:find("u") ~= nil then noNames = true end local s,e = modifiers:find("d%d+") if s ~= nil then depth = tonumber(string.sub(modifiers,s+1,e)) end -- set name if appropriate elseif type(v) == "string" and k < #arg and name == nil and not noNames then name = v else if name ~= nil then name = ""..name..": " else name = "" end local o = "" if type(v) == "string" then table.insert(output,name..type(v).."("..v:len()..") \""..v.."\"") elseif type(v) == "userdata" then local elementType = "no valid MTA element" if isElement(v) then elementType = getElementType(v) end table.insert(output,name..type(v).."("..elementType..") \""..tostring(v).."\"") elseif type(v) == "table" then local count = 0 for key,value in pairs(v) do count = count + 1 end table.insert(output,name..type(v).."("..count..") \""..tostring(v).."\"") if verbose and count > 0 and (depth == nil or depth > 0) then table.insert(output,"\t{") for key,value in pairs(v) do -- calls itself, so be careful when you change anything local newModifiers = "-s" if depth == nil then newModifiers = "-sv" elseif depth > 1 then local newDepth = depth - 1 newModifiers = "-svd"..newDepth end local keyString, keyTable = var_dump(newModifiers,key) local valueString, valueTable = var_dump(newModifiers,value) if #keyTable == 1 and #valueTable == 1 then table.insert(output,indentation.."["..keyString.."]\t=>\t"..valueString) elseif #keyTable == 1 then table.insert(output,indentation.."["..keyString.."]\t=>") for k,v in ipairs(valueTable) do table.insert(output,indentation..v) end elseif #valueTable == 1 then for k,v in ipairs(keyTable) do if k == 1 then table.insert(output,indentation.."["..v) elseif k == #keyTable then table.insert(output,indentation..v.."]") else table.insert(output,indentation..v) end end table.insert(output,indentation.."\t=>\t"..valueString) else for k,v in ipairs(keyTable) do if k == 1 then table.insert(output,indentation.."["..v) elseif k == #keyTable then table.insert(output,indentation..v.."]") else table.insert(output,indentation..v) end end for k,v in ipairs(valueTable) do if k == 1 then table.insert(output,indentation.." => "..v) else table.insert(output,indentation..v) end end end end table.insert(output,"\t}") end else table.insert(output,name..type(v).." \""..tostring(v).."\"") end name = nil end end local string = "" for k,v in ipairs(output) do if outputDirectly then outputConsole(v) end string = string..v end return string, output end addEvent("mapstop100_refresh",true) function mapstop100_refresh() guiGridListClear(tab.MapList) guiGridListClear(tab.QueueList) end addEventHandler("mapstop100_refresh",root,mapstop100_refresh) -- [number "85"] => -- table(3) "table: 2805A560" -- { -- [string(7) "resname"] => string(15) "shooter-stadium" -- [string(6) "author"] => string(11) "salvadorc17" -- [string(4) "name"] => string(15) "Shooter-Stadiu
mit
1lann/Convorse
luaclient/launcher.lua
1
9007
local theme = { background = colors.white, accent = colors.blue, text = colors.black, header = colors.white, input = colors.white, inputText = colors.gray, placeholder = colors.lightGray, err = colors.red, } if not term.isColor() then theme = { background = colors.white, accent = colors.black, text = colors.black, header = colors.white, input = colors.white, inputText = colors.black, placeholder = colors.black, err = colors.black, } end local t = { bg = term.setBackgroundColor, tc = term.setTextColor, p = term.setCursorPos, gp = term.getCursorPos, c = term.clear, cl = term.clearLine, w = term.write, nl = function(num) if not num then num = 1 end local x, y = term.getCursorPos() term.setCursorPos(1, y + num) end, o = function() term.setCursorPos(1, 1) end, db = function(height) local x, y = term.getCursorPos() for i = 1, height do term.setCursorPos(1, y + i - 1) term.clearLine() end term.setCursorPos(x, y) end } local w, h = term.getSize() local function textField(startX, startY, length, startingText, placeholder, shouldHideText, eventCallback) local horizontalScroll = 1 local cursorPosition = 1 local data = startingText local eventCallbackResponse = nil local method = "enter" if not data then data = "" else cursorPosition = data:len() + 1 end while true do term.setCursorBlink(true) term.setBackgroundColor(theme.background) term.setTextColor(theme.inputText) term.setCursorPos(startX, startY) term.write(string.rep(" ", length)) term.setCursorPos(startX, startY) local text = data if shouldHideText then text = string.rep("*", #data) end term.write(text:sub(horizontalScroll, horizontalScroll + length - 1)) if #data == 0 and placeholder then term.setTextColor(theme.placeholder) term.write(placeholder) end term.setCursorPos(startX + cursorPosition - horizontalScroll, startY) local event = {os.pullEvent()} if eventCallback then local shouldReturn, response = eventCallback(event) if shouldReturn then eventCallbackResponse = response method = "callback" break end end local isMouseEvent = event[1] == "mouse_click" or event[1] == "mouse_drag" if isMouseEvent then local inHorizontalBounds = event[3] >= startX and event[3] < startX + length local inVerticalBounds = event[4] == startY if inHorizontalBounds and inVerticalBounds then local previousX = term.getCursorPos() local position = cursorPosition - (previousX - event[3]) cursorPosition = math.min(position, #data + 1) end elseif event[1] == "char" then if term.getCursorPos() >= startX + length - 1 then horizontalScroll = horizontalScroll + 1 end cursorPosition = cursorPosition + 1 local before = data:sub(1, cursorPosition - 1) local after = data:sub(cursorPosition, -1) data = before .. event[2] .. after elseif event[1] == "key" then if event[2] == keys.enter then break elseif event[2] == keys.left and cursorPosition > 1 then cursorPosition = cursorPosition - 1 if cursorPosition <= horizontalScroll and horizontalScroll > 1 then local amount = ((horizontalScroll - cursorPosition) + 1) horizontalScroll = horizontalScroll - amount end elseif event[2] == keys.right and cursorPosition <= data:len() then cursorPosition = cursorPosition + 1 if 1 >= length - (cursorPosition - horizontalScroll) + 1 then horizontalScroll = horizontalScroll + 1 end elseif event[2] == keys.backspace and cursorPosition > 1 then data = data:sub(1, cursorPosition - 2) .. data:sub(cursorPosition, -1) cursorPosition = cursorPosition - 1 if cursorPosition <= horizontalScroll and horizontalScroll > 1 then local amount = ((horizontalScroll - cursorPosition) + 1) horizontalScroll = horizontalScroll - amount end end end end term.setCursorBlink(false) return method, data, eventCallbackResponse end local centerField = function(width, placeholder) local x, y = t.gp() t.p(math.floor(w / 2 - width / 2) + 1, y) t.bg(theme.input) t.tc(theme.placeholder) t.w(placeholder .. string.rep(" ", width - #placeholder)) t.p(1, y + 1) return {math.floor(w / 2 - width / 2) + 1, y} end local center = function(text) local x, y = t.gp() t.p(math.floor(w / 2 - text:len() / 2) + 1, y) t.w(text) t.p(1, y + 1) return {math.floor(w / 2 - text:len() / 2) + 1, y} end local centerButton = function(width, text) local x, y = t.gp() t.p(math.floor(w / 2 - width / 2) + 1, y) t.bg(theme.accent) t.tc(theme.header) t.w(string.rep(" ", width)) center(text) return {math.floor(w / 2 - width / 2) + 1, y} end local usernameFieldStart, passwordFieldStart, buttonTopLeft, registerStart, backStart local function drawHeader() t.bg(theme.background) t.c() t.o() t.tc(theme.header) t.bg(theme.accent) t.db(4) t.nl() center("- Convorse -") center("A web chat client") t.nl() end local function drawLogin(errorMessage, username) drawHeader() if errorMessage then t.bg(theme.err) t.tc(theme.header) t.db(3) t.nl() center(errorMessage) t.nl() end t.tc(theme.text) t.bg(theme.background) t.nl() center("Welcome Back") t.nl() usernameFieldStart = centerField(20, "Username") center("--------------------") passwordFieldStart = centerField(20, "Password") center("--------------------") t.nl() loginStart = centerButton(20, "Login") t.nl() t.tc(theme.accent) t.bg(theme.background) registerStart = center("Need an account? ") end local function drawRegister() drawHeader() t.tc(theme.text) t.bg(theme.background) t.nl() center("You can register an ") center("account online at ") center("http://convorse.tk ") t.nl() center("Registering in game ") center("is currently not ") center("supported ") t.nl() t.tc(theme.accent) backStart = center("< Back ") end local activeField = "username" local username = "" local password = "" local errorMessage = nil local loginFocusManager local function register() drawRegister() while true do local event, mouse, x, y = os.pullEvent() if event == "mouse_click" then if y == backStart[2] and x >= backStart[1] and x <= backStart[1] + 5 then return end elseif event == "key" then return end end end local errorSubmitURL = "http://convorse.tk/api/error" local function login() drawHeader() t.nl(5) t.tc(theme.accent) t.bg(theme.background) center("Logging in...") sleep(3) errorMessage = "Username required" return end -- local function textField(posX, posY, length, curData, placeholder, handler) function loginFocusManager() local activeField = "username" while true do local function textHandler(events) if events[1] == "mouse_click" then if (events[4] == usernameFieldStart[2] or events[4] == usernameFieldStart[2] + 1) and events[3] >= usernameFieldStart[1] and events[3] <= usernameFieldStart[1] + 19 then if activeField ~= "username" then return true, {"username", unpack(events)} end elseif (events[4] == passwordFieldStart[2] or events[4] == passwordFieldStart[2] + 1) and events[3] >= passwordFieldStart[1] and events[3] <= passwordFieldStart[1] + 19 then if activeField ~= "password" then return true, {"password", unpack(events)} end elseif events[4] == loginStart[2] and events[3] >= loginStart[1] and events[3] <= loginStart[1] + 19 then return true, {"login", unpack(events)} elseif events[4] == registerStart[2] and events[3] >= registerStart[1] and events[3] <= registerStart[1] + 16 then return true, {"register", unpack(events)} else return true, {"nothing", unpack(events)} end end end if activeField == "nothing" then while true do local resp resp, callbackResponse = textHandler({os.pullEvent()}) if resp then activeField = callbackResponse[1] break end end elseif activeField == "username" then local resp, data, callback = textField(usernameFieldStart[1], usernameFieldStart[2], 20, username, "Username", false, textHandler) if resp == "enter" then activeField = "password" username = data else activeField = callback[1] username = data os.queueEvent(callback[2], callback[3], callback[4], callback[5]) end elseif activeField == "password" then local resp, data, callback = textField(passwordFieldStart[1], passwordFieldStart[2], 20, password, "Password", true, textHandler) if resp == "enter" then activeField = "nothing" password = data login() else activeField = callback[1] password = data os.queueEvent(callback[2], callback[3], callback[4], callback[5]) end elseif activeField == "login" then login() drawLogin(errorMessage) password = "" activeField = "username" elseif activeField == "register" then register() drawLogin() password = "" activeField = "username" end end end drawLogin() loginFocusManager()
mit
JarnoVgr/Mr.Green-MTA-Resources
resources/[admin]/censorship/censorship_s.lua
1
1356
-- Frequent advertisements: local ads = { "vk.com", "new_era_mta", "vk.com/newˍeraˍmta", 'Dayz Mod "New Era"' } function resourceStart() --outputDebugString("Hello world!",0) end addEventHandler('onResourceStart', getResourceRootElement(),resourceStart) function onPlayerChat_s(msg, msgType) if not isBanMsg(msg) then return end cancelEvent() local playerName = string.gsub(getPlayerName(source), "#%x%x%x%x%x%x", "") outputServerLog("[CANCELED]CHAT: " .. getPlayerName(source) .. ": " .. msg) outputDebugString("[CANCELED]CHAT: " .. playerName .. ": " .. msg,3) local ip = getPlayerIP(source) local serial = getPlayerSerial(source) local timeMs = 60*60*24*30 if hasObjectPermissionTo(source, "command.ban") then timeMs = 60*30 end --addBan(ip, nil, serial, getRootElement(), "Advertising", timeMs) outputDebugString("Banned player: " .. playerName .. " IP: " .. ip .. " Serial: " .. serial,3) end addEventHandler("onPlayerChat", root, onPlayerChat_s) function isBanMsg(msg) msg = string.gsub(msg, "#%x%x%x%x%x%x", "") msg = string.lower(msg) for a,b in ipairs(ads) do b = string.lower(b) end for a,b in ipairs(ads) do local s,e = string.find(msg, b) if not (s == nil) and not (e == nil) then return true end end return false end function isBlockedMsg(msg) if isBanMsg(msg) then return true end return false end
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/tests/lua-tests/src/ClickAndMoveTest/ClickAndMoveTest.lua
17
2052
local size = cc.Director:getInstance():getWinSize() local layer = nil local kTagSprite = 1 local function initWithLayer() local sprite = cc.Sprite:create(s_pPathGrossini) local bgLayer = cc.LayerColor:create(cc.c4b(255,255,0,255)) layer:addChild(bgLayer, -1) layer:addChild(sprite, 0, kTagSprite) sprite:setPosition(cc.p(20,150)) sprite:runAction(cc.JumpTo:create(4, cc.p(300,48), 100, 4)) bgLayer:runAction(cc.RepeatForever:create(cc.Sequence:create( cc.FadeIn:create(1), cc.FadeOut:create(1)))) local function onTouchBegan(touch, event) return true end local function onTouchEnded(touch, event) local location = touch:getLocation() local s = layer:getChildByTag(kTagSprite) s:stopAllActions() s:runAction(cc.MoveTo:create(1, cc.p(location.x, location.y))) local posX, posY = s:getPosition() local o = location.x - posX local a = location.y - posY local at = math.atan(o / a) / math.pi * 180.0 if a < 0 then if o < 0 then at = 180 + math.abs(at) else at = 180 - math.abs(at) end end s:runAction(cc.RotateTo:create(1, at)) end local listener = cc.EventListenerTouchOneByOne:create() listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN ) listener:registerScriptHandler(onTouchEnded,cc.Handler.EVENT_TOUCH_ENDED ) local eventDispatcher = layer:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) return layer end -------------------------------- -- Click And Move Test -------------------------------- function ClickAndMoveTest() cclog("ClickAndMoveTest") local scene = cc.Scene:create() layer = cc.Layer:create() initWithLayer() scene:addChild(layer) scene:addChild(CreateBackMenuItem()) return scene end
mit
robbie-cao/mooncake
uvth.lua
1
1376
local uv = require('luv') local step = 10 hare = function (step, ...) local uv = require('luv') while step > 0 do print("+ Hare ran step " .. tostring(step), ...) step = step - 1 uv.sleep(1000) end print("** Hare done running!") end tortoise = function (step, msg, ...) local uv = require('luv') while step > 0 do print("- Tortoise ran step " .. tostring(step), msg, ...) step = step - 1 uv.sleep(500) end print("** Tortoise done running!") end snail = function (step, ...) local uv = require('luv') while step > 0 do print("- Snail ran step " .. tostring(step), ...) step = step - 1 uv.sleep(1500) end print("** Snail done running!") end -- only the fist two params are necessary local hare_id = uv.new_thread(hare, step, true, 'abcd', 'false') local tortoise_id = uv.new_thread(tortoise, step, 'abcd', 'false') local snail_id = uv.new_thread(snail, step) do -- evaluate print("hare_id:", hare_id, type(hare_id)) print("tortoise_id:", tortoise_id, type(tortoise_id)) print("snail_id:", snail_id, type(snail_id)) print(hare_id == hare_id, uv.thread_equal(hare_id, hare_id)) print(tortoise_id == hare_id, uv.thread_equal(tortoise_id, hare_id)) end uv.thread_join(hare_id) uv.thread_join(tortoise_id) uv.thread_join(snail_id)
mit
ashkanpj/fire
bot/utils.lua
356
14963
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has superuser privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- user has admins privileges function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- user has moderator privileges function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) -- Berfungsi utk mengecek user jika plugin moderated = true if plugin.moderated and not is_momod(msg) then --Cek apakah user adalah momod if plugin.moderated and not is_admin(msg) then -- Cek apakah user adalah admin if plugin.moderated and not is_sudo(msg) then -- Cek apakah user adalah sudoers return false end end end -- Berfungsi mengecek user jika plugin privileged = true if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end
gpl-2.0
lizh06/premake-core
modules/xcode/tests/test_xcode4_project.lua
8
2372
--- -- tests/actions/xcode/test_xcode4_project.lua -- Automated test suite for Xcode project generation. -- Copyright (c) 2011-2015 Jason Perkins and the Premake project --- local suite = test.declare("xcode4_proj") local xcode = premake.modules.xcode -- -- Replacement for xcode.newid(). Creates a synthetic ID based on the node name, -- its intended usage (file ID, build ID, etc.) and its place in the tree. This -- makes it easier to tell if the right ID is being used in the right places. -- xcode.used_ids = {} xcode.newid = function(node, usage) local name = node if usage then name = name .. ":" .. usage end if xcode.used_ids[name] then local count = xcode.used_ids[name] + 1 xcode.used_ids[name] = count name = name .. "(" .. count .. ")" else xcode.used_ids[name] = 1 end return "[" .. name .. "]" end --------------------------------------------------------------------------- -- Setup/Teardown --------------------------------------------------------------------------- local tr, wks function suite.teardown() tr = nil end function suite.setup() _OS = "macosx" _ACTION = "xcode4" io.eol = "\n" xcode.used_ids = { } -- reset the list of generated IDs wks = test.createWorkspace() end local function prepare() wks = premake.oven.bakeWorkspace(wks) xcode.prepareWorkspace(wks) local prj = premake.workspace.getproject(wks, 1) tr = xcode.buildprjtree(prj) end --------------------------------------------------------------------------- -- XCBuildConfiguration_Project tests --------------------------------------------------------------------------- function suite.XCBuildConfigurationProject_OnSymbols() symbols "On" prepare() xcode.XCBuildConfiguration_Project(tr, tr.configs[1]) test.capture [[ [MyProject:Debug(2)] /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ARCHS = "$(NATIVE_ARCH_ACTUAL)"; CONFIGURATION_BUILD_DIR = "$(SYMROOT)"; CONFIGURATION_TEMP_DIR = "$(OBJROOT)"; COPY_PHASE_STRIP = NO; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_ENABLE_FIX_AND_CONTINUE = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_ABOUT_RETURN_TYPE = YES; GCC_WARN_UNUSED_VARIABLE = YES; OBJROOT = obj/Debug; ONLY_ACTIVE_ARCH = YES; SYMROOT = bin/Debug; }; name = Debug; }; ]] end
bsd-3-clause
lizh06/premake-core
tests/actions/vstudio/vc200x/test_project.lua
16
4148
-- -- tests/actions/vstudio/vc200x/test_project.lua -- Validate generation of the opening <VisualStudioProject> element. -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- local suite = test.declare("vstudio_vs200x_project") local vc200x = premake.vstudio.vc200x -- -- Setup -- local wks, prj function suite.setup() _ACTION = 'vs2008' wks = test.createWorkspace() uuid "AE61726D-187C-E440-BD07-2556188A6565" end local function prepare() prj = test.getproject(wks, 1) vc200x.visualStudioProject(prj) end -- -- Verify the version numbers for each action. -- function suite.hasCorrectVersion_on2005() _ACTION = 'vs2005' prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="8.00" ]] end function suite.hasCorrectVersion_on2008() _ACTION = 'vs2008' prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" ]] end -- -- Check the structure with the default project values. -- function suite.structureIsCorrect_onDefaultValues() prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="Win32Proj" TargetFrameworkVersion="0" > ]] end -- -- Use the correct keyword for Managed C++ projects. -- function suite.keywordIsCorrect_onManagedC() clr "On" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="ManagedCProj" ]] end -- -- Omit Keyword and RootNamespace for non-Windows projects. -- function suite.noKeyword_onNotWindows() system "Linux" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" TargetFrameworkVersion="196613" > ]] end -- -- Include Keyword and RootNamespace for mixed system projects. -- function suite.includeKeyword_onMixedConfigs() filter "Debug" system "Windows" filter "Release" system "Linux" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="Win32Proj" TargetFrameworkVersion="0" > ]] end -- -- Makefile projects set new keyword. It should also drop the root -- namespace, but I need to figure out a better way to test for -- empty configurations in the project first. -- function suite.keywordIsCorrect_onMakefile() kind "Makefile" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="MakeFileProj" TargetFrameworkVersion="196613" > ]] end function suite.keywordIsCorrect_onNone() kind "None" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="MakeFileProj" TargetFrameworkVersion="196613" > ]] end --- -- Makefile projects which do not support all of the solution configurations -- add back the RootNamespace element. --- function suite.keywordIsCorrect_onMakefileWithMixedConfigs() removeconfigurations { "Release" } kind "Makefile" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="MakeFileProj" TargetFrameworkVersion="196613" > ]] end function suite.keywordIsCorrect_onNoneWithMixedConfigs() removeconfigurations { "Release" } kind "None" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="MakeFileProj" TargetFrameworkVersion="196613" > ]] end
bsd-3-clause
robbie-cao/mooncake
json-dk.lua
1
4901
local json = require ("dkjson") local P = print if true or arg[1] == "off" then print0 = function (...) end end local tbl = { animals = { "dog", "cat", "aardvark" }, instruments = { "violin", "trombone", "theremin" }, bugs = json.null, trees = nil } local str = json.encode (tbl, { indent = true }) print (str) local tbl = { title = "Hello JSON", id = math.random(10000), arr1 = { 123, "abc", { ["key"] = "K", ["val"] = 5678 }, ["ext"] = { 4, 5, 7 }, }, arr2 = { "xxx", "yyy", "zzz" }, arr3 = { a = "xxx", b = "yyy", "zzz", }, bugs = json.null, trees = nil } local str = json.encode (tbl, { indent = true }) print (str) local str = [[ { "numbers": [ 2, 3, -20.23e+2, -4 ], "currency": "\u20AC" } ]] local obj, pos, err = json.decode (str, 1, nil) if err then print ("Error:", err) else print ("currency", obj.currency) for i = 1, #obj.numbers do print(i, obj.numbers[i]) end end local str = [[ { "glossary": { "Title": "example glossary", "GlossDiv": { "Title": "S", "GlossList": { "GlossEntry": { "ID": "SGML", "SortAs": "SGML", "GlossTerm": "Standard Generalized Markup Language", "Acronym": "SGML", "Abbrev": "ISO 8879:1986", "GlossDef": { "Para": "A meta-markup language, used to create markup languages such as DocBook.", "GlossSeeAlso": ["GML", "XML"] }, "GlossSee": "markup" } } } } } ]] local obj, pos, err = json.decode (str, 1, nil) if err then print ("Error:", err) else print ("glossary", obj.glossary) do inspect = require("inspect") print(inspect(getmetatable(obj.glossary))) end print(obj.glossary.Title) print(obj.glossary.GlossDiv.Title) print(obj.glossary.GlossDiv.GlossList.GlossEntry.ID) print(obj.glossary.GlossDiv.GlossList.GlossEntry.SortAs) print(obj.glossary.GlossDiv.GlossList.GlossEntry.GlossTerm) print(obj.glossary.GlossDiv.GlossList.GlossEntry.Acronym) print(obj.glossary.GlossDiv.GlossList.GlossEntry.Abbrev) print(obj.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.Para) for i = 1, #obj.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso do print(obj.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso[i]) end print(obj.glossary.GlossDiv.GlossList.GlossEntry.GlossSee) end local str = [[ { "menu": { "id": "file", "value": "File", "popup": { "menuitem": [ {"value": "New", "onclick": "CreateNewDoc()"}, {"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"} ] } } } ]] local obj, pos, err = json.decode (str, 1, nil) if err then print ("Error:", err) else print ("menu", obj.menu) do inspect = require("inspect") print(inspect(getmetatable(obj.menu))) end print(obj.menu.id) print(obj.menu.value) for i = 1, #obj.menu.popup.menuitem do print(obj.menu.popup.menuitem[i].value, obj.menu.popup.menuitem[i].onclick) end end local str = [[ { "widget": { "debug": "on", "window": { "title": "Sample Konfabulator Widget", "name": "main_window", "width": 500, "height": 500 }, "image": { "src": "Images/Sun.png", "name": "sun1", "hOffset": 250, "vOffset": 250, "alignment": "center" }, "text": { "data": "Click Here", "size": 36, "style": "bold", "name": "text1", "hOffset": 250, "vOffset": 100, "alignment": "center", "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;" } } } ]] local obj, pos, err = json.decode (str, 1, nil) if err then print ("Error:", err) else print ("widget", obj.widget) do inspect = require("inspect") print(inspect(getmetatable(obj.widget))) end print(obj.widget.debug) print(obj.widget.window.title, obj.widget.window.name, obj.widget.window.width, obj.widget.window.height) print(obj.widget.image.src, obj.widget.image.name, obj.widget.image.hOffset, obj.widget.image.vOffset, obj.widget.image.alignment) print(obj.widget.text.data, obj.widget.text.size, obj.widget.text.style, obj.widget.text.name, obj.widget.text.hOffset, obj.widget.text.vOffset, obj.widget.text.alignment, obj.widget.text.onMouseUp) require("pl") pretty.dump(obj) end print = P
mit
cooljeanius/CEGUI
cegui/src/ScriptingModules/LuaScriptModule/support/tolua++bin/lua/function.lua
1
19227
-- tolua: function class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- $Id$ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- CEGUILua mod -- exception handling -- patch from Tov -- modded by Lindquist exceptionDefs = exceptionDefs or {} exceptionDefs["std::exception"] = {} exceptionDefs["std::exception"]["var"] = "&e" exceptionDefs["std::exception"]["c_str"] = "e.what()" exceptionDefs["any"] = {} exceptionDefs["any"]["var"] = "" exceptionDefs["any"]["c_str"] = '"Unknown"' exceptionMessageBufferSize = 512 function outputExceptionError(f,e,errBuf) -- if the exception is not "..." then use the "c_str" info the get a real exception message local messageC_str = true if e.name == "any" then messageC_str = false end -- make a default e.ret if empty if not e.ret or e.ret == "" then e.ret = "nil,message" end -- create a default exceptionDef if we dont have one if not exceptionDefs[e.name] then exceptionDefs[e.name] = {} exceptionDefs[e.name].var = "&e" exceptionDefs[e.name].c_str = '"Unknown"' end -- print catch header local nameToEcho = e.name if nameToEcho == "any" then nameToEcho = "..." end if e.ret == "nil" then output("catch(",nameToEcho," CEGUIDeadException(",exceptionDefs[e.name].var,"))\n{\n") else output("catch(",nameToEcho,exceptionDefs[e.name].var,")\n{\n") end -- if just a nil if e.ret == "nil" then output("return 0;\n") -- if error should be raised elseif string.find(e.ret,"error") then if messageC_str then output("snprintf(errorBuffer,"..exceptionMessageBufferSize..",\"Exception of type '"..e.name.."' was thrown by function '"..f.."'\\nMessage: %s\","..exceptionDefs[e.name].c_str..");\n") else output("snprintf(errorBuffer,"..exceptionMessageBufferSize..",\"Unknown exception thrown by function '"..f.."'\");\n") end output("errorDoIt = true;\n") -- else go through the returns else -- buffer for message if string.find(e.ret,"message") and messageC_str and errBuf == false then output("char errorBuffer["..exceptionMessageBufferSize.."];\n") end local numrets = 0 local retpat = "(%w+),?" local i,j,retval = string.find(e.ret,retpat) while i do local code = "" -- NIL if retval == "nil" then code = "tolua_pushnil(tolua_S);\n" -- MESSAGE elseif retval == "message" then if messageC_str then code = "snprintf(errorBuffer,"..exceptionMessageBufferSize..",\"Exception of type '"..e.name.."' was thrown by function '"..f.."'\\nMessage: %s\","..exceptionDefs[e.name].c_str..");\ntolua_pushstring(tolua_S,errorBuffer);\n" else code = "tolua_pushstring(tolua_S,\"Unknown exception thrown by function '"..f.."'\");\n" end -- TRUE elseif retval == "true" then code = "tolua_pushboolean(tolua_S, 1);\n" -- FALSE elseif retval == "false" then code = "tolua_pushboolean(tolua_S, 0);\n" end -- print code for this return value if code ~= "" then output(code) numrets = numrets + 1 end -- next return value i,j,retval = string.find(e.ret,retpat,j+1) end output("return ",numrets,";\n") end -- print catch footer output("}\n") end function outputExceptionCatchBlocks(func,throws,err) for i=1,table.getn(throws) do outputExceptionError(func, throws[i], err) end -- if an error should be raised, we do it here if err then output("if (errorDoIt) {\n") output("luaL_error(tolua_S,errorBuffer);\n") output("}\n") end end -- Function class -- Represents a function or a class method. -- The following fields are stored: -- mod = type modifiers -- type = type -- ptr = "*" or "&", if representing a pointer or a reference -- name = name -- lname = lua name -- args = list of argument declarations -- const = if it is a method receiving a const "this". classFunction = { mod = '', type = '', ptr = '', name = '', args = {n=0}, const = '', } classFunction.__index = classFunction setmetatable(classFunction,classFeature) -- declare tags function classFunction:decltype () self.type = typevar(self.type) if strfind(self.mod,'const') then self.type = 'const '..self.type self.mod = gsub(self.mod,'const','') end local i=1 while self.args[i] do self.args[i]:decltype() i = i+1 end end -- Write binding function -- Outputs C/C++ binding function. function classFunction:supcode (local_constructor) local overload = strsub(self.cname,-2,-1) - 1 -- indicate overloaded func local nret = 0 -- number of returned values local class = self:inclass() local _,_,static = strfind(self.mod,'^%s*(static)') if class then if self.name == 'new' and self.parent.flags.pure_virtual then -- no constructor for classes with pure virtual methods return end if local_constructor then output("/* method: new_local of class ",class," */") else output("/* method:",self.name," of class ",class," */") end else output("/* function:",self.name," */") end if local_constructor then output("#ifndef TOLUA_DISABLE_"..self.cname.."_local") output("\nstatic int",self.cname.."_local","(lua_State* tolua_S)") else output("#ifndef TOLUA_DISABLE_"..self.cname) output("\nstatic int",self.cname,"(lua_State* tolua_S)") end output("{") -- check types if overload < 0 then output('#ifndef TOLUA_RELEASE\n') end output(' tolua_Error tolua_err;') output(' if (\n') -- check self local narg if class then narg=2 else narg=1 end if class then local func = 'tolua_isusertype' local type = self.parent.type if self.name=='new' or static~=nil then func = 'tolua_isusertable' type = self.parent.type end if self.const ~= '' then type = "const "..type end output(' !'..func..'(tolua_S,1,"'..type..'",0,&tolua_err) ||\n') end -- check args if self.args[1].type ~= 'void' then local i=1 while self.args[i] do local btype = isbasic(self.args[i].type) if btype ~= 'value' and btype ~= 'state' then output(' !'..self.args[i]:outchecktype(narg)..' ||\n') end if btype ~= 'state' then narg = narg+1 end i = i+1 end end -- check end of list output(' !tolua_isnoobj(tolua_S,'..narg..',&tolua_err)\n )') output(' goto tolua_lerror;') output(' else\n') if overload < 0 then output('#endif\n') end output(' {') -- declare self, if the case local narg if class then narg=2 else narg=1 end if class and self.name~='new' and static==nil then output(' ',self.const,self.parent.type,'*','self = ') output('(',self.const,self.parent.type,'*) ') output('tolua_tousertype(tolua_S,1,0);') elseif static then _,_,self.mod = strfind(self.mod,'^%s*static%s%s*(.*)') end -- declare parameters if self.args[1].type ~= 'void' then local i=1 while self.args[i] do self.args[i]:declare(narg) if isbasic(self.args[i].type) ~= "state" then narg = narg+1 end i = i+1 end end -- check self if class and self.name~='new' and static==nil then output('#ifndef TOLUA_RELEASE\n') output(' if (!self) tolua_error(tolua_S,"invalid \'self\' in function \''..self.name..'\'",NULL);'); output('#endif\n') end -- get array element values if class then narg=2 else narg=1 end if self.args[1].type ~= 'void' then local i=1 while self.args[i] do self.args[i]:getarray(narg) narg = narg+1 i = i+1 end end -------------------------------------------------- -- CEGUILua mod -- init exception handling local throws = false do local pattern = "tolua_throws|.*|" local i,j = string.find(self.mod, pattern) if i then throws = {} -- ensure table is empty. Used to be: table.setn(throws,0) for x in pairs(throws) do throws[x] = nil end local excepts = string.sub(self.mod, i+12,j) local epattern = "|.-|" local i,j = string.find(excepts, epattern) while i do local e = string.sub(excepts,i+1,j-1) local _,_,name,rest = string.find(e, "([%w:_]+),?(.*)") table.insert(throws,{name=name, ret=rest}) i,j = string.find(excepts, epattern, j) end self.mod = string.gsub(self.mod, pattern, "") end end local exRaiseError = false -------------------------------------------------- local out = string.find(self.mod, "tolua_outside") --------------- -- CEGUILua mod -- remove "tolua_outside" from self.mod if out then self.mod = string.gsub(self.mod, "tolua_outside", "") end -- call function if class and self.name=='delete' then output(' delete self;') elseif class and self.name == 'operator&[]' then if flags['1'] then -- for compatibility with tolua5 ? output(' self->operator[](',self.args[1].name,'-1) = ',self.args[2].name,';') else output(' self->operator[](',self.args[1].name,') = ',self.args[2].name,';') end else -- CEGUILua mod begin- throws if throws then for i=1,table.getn(throws) do if string.find(throws[i].ret, "error") then output("char errorBuffer["..exceptionMessageBufferSize.."];\n") output("bool errorDoIt = false;\n") exRaiseError = true break end end output("try\n") end -- CEGUILua mod end - throws output(' {') if self.type ~= '' and self.type ~= 'void' then output(' ',self.mod,self.type,self.ptr,'tolua_ret = ') output('(',self.mod,self.type,self.ptr,') ') else output(' ') end if class and self.name=='new' then output('new',self.type,'(') elseif class and static then if out then output(self.name,'(') else output(class..'::'..self.name,'(') end elseif class then if out then output(self.name,'(') else if self.cast_operator then output('static_cast<',self.mod,self.type,self.ptr,'>(*self') else output('self->'..self.name,'(') end end else output(self.name,'(') end if out and not static then output('self') if self.args[1] and self.args[1].name ~= '' then output(',') end end -- write parameters local i=1 while self.args[i] do self.args[i]:passpar() i = i+1 if self.args[i] then output(',') end end if class and self.name == 'operator[]' and flags['1'] then output('-1);') else output(');') end -- return values if self.type ~= '' and self.type ~= 'void' then nret = nret + 1 local t,ct = isbasic(self.type) if t then if self.cast_operator and _basic_raw_push[t] then output(' ',_basic_raw_push[t],'(tolua_S,(',ct,')tolua_ret);') else output(' tolua_push'..t..'(tolua_S,(',ct,')tolua_ret);') end else t = self.type new_t = string.gsub(t, "const%s+", "") if self.ptr == '' then output(' {') output('#ifdef __cplusplus\n') output(' void* tolua_obj = new',new_t,'(tolua_ret);') output(' tolua_pushusertype_and_takeownership(tolua_S,tolua_obj,"',t,'");') output('#else\n') output(' void* tolua_obj = tolua_copy(tolua_S,(void*)&tolua_ret,sizeof(',t,'));') output(' tolua_pushusertype_and_takeownership(tolua_S,tolua_obj,"',t,'");') output('#endif\n') output(' }') elseif self.ptr == '&' then output(' tolua_pushusertype(tolua_S,(void*)&tolua_ret,"',t,'");') else if local_constructor then output(' tolua_pushusertype_and_takeownership(tolua_S,(void *)tolua_ret,"',t,'");') else output(' tolua_pushusertype(tolua_S,(void*)tolua_ret,"',t,'");') end end end end local i=1 while self.args[i] do nret = nret + self.args[i]:retvalue() i = i+1 end output(' }') ------------------------------------------ -- CEGUILua mod -- finish exception handling -- catch if throws then outputExceptionCatchBlocks(self.name, throws, exRaiseError) end ------------------------------------------ -- set array element values if class then narg=2 else narg=1 end if self.args[1].type ~= 'void' then local i=1 while self.args[i] do self.args[i]:setarray(narg) narg = narg+1 i = i+1 end end -- free dynamically allocated array if self.args[1].type ~= 'void' then local i=1 while self.args[i] do self.args[i]:freearray() i = i+1 end end end output(' }') output(' return '..nret..';') -- call overloaded function or generate error if overload < 0 then output('#ifndef TOLUA_RELEASE\n') output('tolua_lerror:\n') output(' tolua_error(tolua_S,"#ferror in function \''..self.lname..'\'.",&tolua_err);') output(' return 0;') output('#endif\n') else local _local = "" if local_constructor then _local = "_local" end output('tolua_lerror:\n') output(' return '..strsub(self.cname,1,-3)..format("%02d",overload).._local..'(tolua_S);') end output('}') output('#endif //#ifndef TOLUA_DISABLE\n') output('\n') -- recursive call to write local constructor if class and self.name=='new' and not local_constructor then self:supcode(1) end end -- register function function classFunction:register (pre) if not self:check_public_access() then return end if self.name == 'new' and self.parent.flags.pure_virtual then -- no constructor for classes with pure virtual methods return end output(pre..'tolua_function(tolua_S,"'..self.lname..'",'..self.cname..');') if self.name == 'new' then output(pre..'tolua_function(tolua_S,"new_local",'..self.cname..'_local);') output(pre..'tolua_function(tolua_S,".call",'..self.cname..'_local);') --output(' tolua_set_call_event(tolua_S,'..self.cname..'_local, "'..self.parent.type..'");') end end -- Print method function classFunction:print (ident,close) print(ident.."Function{") print(ident.." mod = '"..self.mod.."',") print(ident.." type = '"..self.type.."',") print(ident.." ptr = '"..self.ptr.."',") print(ident.." name = '"..self.name.."',") print(ident.." lname = '"..self.lname.."',") print(ident.." const = '"..self.const.."',") print(ident.." cname = '"..self.cname.."',") print(ident.." lname = '"..self.lname.."',") print(ident.." args = {") local i=1 while self.args[i] do self.args[i]:print(ident.." ",",") i = i+1 end print(ident.." }") print(ident.."}"..close) end -- check if it returns an object by value function classFunction:requirecollection (t) local r = false if self.type ~= '' and not isbasic(self.type) and self.ptr=='' then local type = gsub(self.type,"%s*const%s+","") t[type] = "tolua_collect_" .. clean_template(type) r = true end local i=1 while self.args[i] do r = self.args[i]:requirecollection(t) or r i = i+1 end return r end -- determine lua function name overload function classFunction:overload () return self.parent:overload(self.lname) end function param_object(par) -- returns true if the parameter has an object as its default value if not string.find(par, '=') then return false end -- it has no default value local _,_,def = string.find(par, "=(.*)$") if string.find(par, "|") then -- a list of flags return true end if string.find(par, "%*") then -- it's a pointer with a default value if string.find(par, '=%s*new') then -- it's a pointer with an instance as default parameter.. is that valid? return true end return false -- default value is 'NULL' or something end if string.find(par, "[%(&]") then return true end -- default value is a constructor call (most likely for a const reference) --if string.find(par, "&") then -- if string.find(def, ":") or string.find(def, "^%s*new%s+") then -- -- it's a reference with default to something like Class::member, or 'new Class' -- return true -- end --end return false -- ? end function strip_last_arg(all_args, last_arg) -- strips the default value from the last argument local _,_,s_arg = string.find(last_arg, "^([^=]+)") last_arg = string.gsub(last_arg, "([%%%(%)])", "%%%1"); all_args = string.gsub(all_args, "%s*,%s*"..last_arg.."%s*%)%s*$", ")") return all_args, s_arg end -- Internal constructor function _Function (t) setmetatable(t,classFunction) if t.const ~= 'const' and t.const ~= '' then error("#invalid 'const' specification") end append(t) if t:inclass() then --print ('t.name is '..t.name..', parent.name is '..t.parent.name) if string.gsub(t.name, "%b<>", "") == string.gsub(t.parent.original_name or t.parent.name, "%b<>", "") then t.name = 'new' t.lname = 'new' t.parent._new = true t.type = t.parent.name t.ptr = '*' elseif string.gsub(t.name, "%b<>", "") == '~'..string.gsub(t.parent.original_name or t.parent.name, "%b<>", "") then t.name = 'delete' t.lname = 'delete' t.parent._delete = true end end t.cname = t:cfuncname("tolua")..t:overload(t) return t end -- Constructor -- Expects three strings: one representing the function declaration, -- another representing the argument list, and the third representing -- the "const" or empty string. function Function (d,a,c) --local t = split(strsub(a,2,-2),',') -- eliminate braces --local t = split_params(strsub(a,2,-2)) if not flags['W'] and string.find(a, "%.%.%.%s*%)") then warning("Functions with variable arguments (`...') are not supported. Ignoring "..d..a..c) return nil end local i=1 local l = {n=0} a = string.gsub(a, "%s*([%(%)])%s*", "%1") local t,strip,last = strip_pars(strsub(a,2,-2)); if strip then --local ns = string.sub(strsub(a,1,-2), 1, -(string.len(last)+1)) local ns = join(t, ",", 1, last-1) ns = "("..string.gsub(ns, "%s*,%s*$", "")..')' --ns = strip_defaults(ns) Function(d, ns, c) for i=1,last do t[i] = string.gsub(t[i], "=.*$", "") end end while t[i] do l.n = l.n+1 l[l.n] = Declaration(t[i],'var',true) i = i+1 end local f = Declaration(d,'func') f.args = l f.const = c return _Function(f) end function join(t, sep, first, last) first = first or 1 last = last or table.getn(t) local lsep = "" local ret = "" local loop = false for i = first,last do ret = ret..lsep..t[i] lsep = sep loop = true end if not loop then return "" end return ret end function strip_pars(s) local t = split_c_tokens(s, ',') local strip = false local last for i=t.n,1,-1 do if not strip and param_object(t[i]) then last = i strip = true end --if strip then -- t[i] = string.gsub(t[i], "=.*$", "") --end end return t,strip,last end function strip_defaults(s) s = string.gsub(s, "^%(", "") s = string.gsub(s, "%)$", "") local t = split_c_tokens(s, ",") local sep, ret = "","" for i=1,t.n do t[i] = string.gsub(t[i], "=.*$", "") ret = ret..sep..t[i] sep = "," end return "("..ret..")" end
gpl-3.0
Zefiros-Software/ZPM
test/extern/luacov/runner.lua
2
21877
--------------------------------------------------- -- Statistics collecting module. -- Calling the module table is a shortcut to calling the `init` function. -- @class module -- @name luacov.runner local runner = {} --- LuaCov version in `MAJOR.MINOR.PATCH` format. runner.version = "0.12.0" local stats = require("stats") local util = require("util") runner.defaults = require("defaults") local debug = require("debug") local raw_os_exit = os.exit local new_anchor = newproxy or function() return {} end -- luacheck: compat -- Returns an anchor that runs fn when collected. local function on_exit_wrap(fn) local anchor = new_anchor() debug.setmetatable(anchor, {__gc = fn}) return anchor end runner.data = {} runner.paused = true runner.initialized = false runner.tick = false -- Checks if a string matches at least one of patterns. -- @param patterns array of patterns or nil -- @param str string to match -- @param on_empty return value in case of empty pattern array local function match_any(patterns, str, on_empty) if not patterns or not patterns[1] then return on_empty end for _, pattern in ipairs(patterns) do if string.match(str, pattern) then return true end end return false end -------------------------------------------------- -- Uses LuaCov's configuration to check if a file is included for -- coverage data collection. -- @param filename name of the file. -- @return true if file is included, false otherwise. function runner.file_included(filename) -- Normalize file names before using patterns. filename = string.gsub(filename, "\\", "/") filename = string.gsub(filename, "%.lua$", "") -- If include list is empty, everything is included by default. -- If exclude list is empty, nothing is excluded by default. return match_any(runner.configuration.include, filename, true) and not match_any(runner.configuration.exclude, filename, false) end -------------------------------------------------- -- Adds stats to an existing file stats table. -- @param old_stats stats to be updated. -- @param extra_stats another stats table, will be broken during update. function runner.update_stats(old_stats, extra_stats) old_stats.max = math.max(old_stats.max, extra_stats.max) -- Remove string keys so that they do not appear when iterating -- over 'extra_stats'. extra_stats.max = nil extra_stats.max_hits = nil for line_nr, run_nr in pairs(extra_stats) do old_stats[line_nr] = (old_stats[line_nr] or 0) + run_nr old_stats.max_hits = math.max(old_stats.max_hits, old_stats[line_nr]) end end -- Adds accumulated stats to existing stats file or writes a new one, then resets data. function runner.save_stats() local loaded = stats.load(runner.configuration.statsfile) or {} for name, file_data in pairs(runner.data) do if loaded[name] then runner.update_stats(loaded[name], file_data) else loaded[name] = file_data end end stats.save(runner.configuration.statsfile, loaded) runner.data = {} end local cluacov_ok = pcall(require, "cluacov.version") -------------------------------------------------- -- Debug hook set by LuaCov. -- Acknowledges that a line is executed, but does nothing -- if called manually before coverage gathering is started. -- @param _ event type, should always be "line". -- @param line_nr line number. -- @param[opt] level passed to debug.getinfo to get name of processed file, -- 2 by default. Increase it if this function is called manually -- from another debug hook. -- @usage -- local function custom_hook(_, line) -- runner.debug_hook(_, line, 3) -- extra_processing(line) -- end -- @function debug_hook runner.debug_hook = require(cluacov_ok and "cluacov.hook" or "hook").new(runner) ------------------------------------------------------ -- Runs the reporter specified in configuration. -- @param[opt] configuration if string, filename of config file (used to call `load_config`). -- If table then config table (see file `luacov.default.lua` for an example). -- If `configuration.reporter` is not set, runs the default reporter; -- otherwise, it must be a module name in 'luacov.reporter' namespace. -- The module must contain 'report' function, which is called without arguments. function runner.run_report(configuration) configuration = runner.load_config(configuration) local reporter = "reporter" if configuration.reporter then reporter = reporter .. "." .. configuration.reporter end require("test.extern.luacov.reporter").report() end local on_exit_run_once = false local function on_exit() -- Lua >= 5.2 could call __gc when user call os.exit -- so this method could be called twice if on_exit_run_once then return end on_exit_run_once = true runner.save_stats() if runner.configuration.runreport then runner.run_report(runner.configuration) end end local dir_sep = package.config:sub(1, 1) local wildcard_expansion = "[^/]+" if not dir_sep:find("[/\\]") then dir_sep = "/" end local function escape_module_punctuation(ch) if ch == "." then return "/" elseif ch == "*" then return wildcard_expansion else return "%" .. ch end end local function reversed_module_name_parts(name) local parts = {} for part in name:gmatch("[^%.]+") do table.insert(parts, 1, part) end return parts end -- This function is used for sorting module names. -- More specific names should come first. -- E.g. rule for 'foo.bar' should override rule for 'foo.*', -- rule for 'foo.*' should override rule for 'foo.*.*', -- and rule for 'a.b' should override rule for 'b'. -- To be more precise, because names become patterns that are matched -- from the end, the name that has the first (from the end) literal part -- (and the corresponding part for the other name is not literal) -- is considered more specific. local function compare_names(name1, name2) local parts1 = reversed_module_name_parts(name1) local parts2 = reversed_module_name_parts(name2) for i = 1, math.max(#parts1, #parts2) do if not parts1[i] then return false end if not parts2[i] then return true end local is_literal1 = not parts1[i]:find("%*") local is_literal2 = not parts2[i]:find("%*") if is_literal1 ~= is_literal2 then return is_literal1 end end -- Names are at the same level of specificness, -- fall back to lexicographical comparison. return name1 < name2 end -- Sets runner.modules using runner.configuration.modules. -- Produces arrays of module patterns and filenames and sets -- them as runner.modules.patterns and runner.modules.filenames. -- Appends these patterns to the include list. local function acknowledge_modules() runner.modules = {patterns = {}, filenames = {}} if not runner.configuration.modules then return end if not runner.configuration.include then runner.configuration.include = {} end local names = {} for name in pairs(runner.configuration.modules) do table.insert(names, name) end table.sort(names, compare_names) for _, name in ipairs(names) do local pattern = name:gsub("%p", escape_module_punctuation) .. "$" local filename = runner.configuration.modules[name]:gsub("[/\\]", dir_sep) table.insert(runner.modules.patterns, pattern) table.insert(runner.configuration.include, pattern) table.insert(runner.modules.filenames, filename) if filename:match("init%.lua$") then pattern = pattern:gsub("$$", "/init$") table.insert(runner.modules.patterns, pattern) table.insert(runner.configuration.include, pattern) table.insert(runner.modules.filenames, filename) end end end -------------------------------------------------- -- Returns real name for a source file name -- using `luacov.defaults.modules` option. -- @param filename name of the file. function runner.real_name(filename) local orig_filename = filename -- Normalize file names before using patterns. filename = filename:gsub("\\", "/"):gsub("%.lua$", "") for i, pattern in ipairs(runner.modules.patterns) do local match = filename:match(pattern) if match then local new_filename = runner.modules.filenames[i] if pattern:find(wildcard_expansion, 1, true) then -- Given a prefix directory, join it -- with matched part of source file name. if not new_filename:match("/$") then new_filename = new_filename .. "/" end new_filename = new_filename .. match .. ".lua" end -- Switch slashes back to native. return (new_filename:gsub("[/\\]", dir_sep)) end end return orig_filename end -- Always exclude luacov's own files. local luacov_excludes = { "luacov$", "luacov/hook$", "luacov/reporter$", "luacov/reporter/default$", "luacov/defaults$", "luacov/runner$", "luacov/stats$", "luacov/tick$", "luacov/util$", "cluacov/version$" } local function is_absolute(path) if path:sub(1, 1) == dir_sep or path:sub(1, 1) == "/" then return true end if dir_sep == "\\" and path:find("^%a:") then return true end return false end local function get_cur_dir() local pwd_cmd = dir_sep == "\\" and "cd 2>nul" or "pwd 2>/dev/null" local handler = io.popen(pwd_cmd, "r") local cur_dir = handler:read("*a") handler:close() cur_dir = cur_dir:gsub("\r?\n$", "") if cur_dir:sub(-1) ~= dir_sep and cur_dir:sub(-1) ~= "/" then cur_dir = cur_dir .. dir_sep end return cur_dir end -- Sets configuration. If some options are missing, default values are used instead. local function set_config(configuration) runner.configuration = {} for option, default_value in pairs(runner.defaults) do runner.configuration[option] = default_value end for option, value in pairs(configuration) do runner.configuration[option] = value end -- Program using LuaCov may change directory during its execution. -- Convert path options to absolute paths to use correct paths anyway. local cur_dir for _, option in ipairs({"statsfile", "reportfile"}) do local path = runner.configuration[option] if not is_absolute(path) then runner.configuration[option] = _WORKING_DIR .. "/" .. path end end acknowledge_modules() for _, patt in ipairs(luacov_excludes) do table.insert(runner.configuration.exclude, patt) end runner.tick = runner.tick or runner.configuration.tick end local function load_config_file(name, is_default) local conf = setmetatable({}, {__index = _G}) local ok, ret, error_msg = util.load_config(name, conf) if ok then if type(ret) == "table" then for key, value in pairs(ret) do if conf[key] == nil then conf[key] = value end end end return conf end local error_type = ret if error_type == "read" and is_default then return nil end io.stderr:write(("Error: couldn't %s config file %s: %s\n"):format(error_type, name, error_msg)) raw_os_exit(1) end local default_config_file = ".luacov" ------------------------------------------------------ -- Loads a valid configuration. -- @param[opt] configuration user provided config (config-table or filename) -- @return existing configuration if already set, otherwise loads a new -- config from the provided data or the defaults. -- When loading a new config, if some options are missing, default values -- from `luacov.defaults` are used instead. function runner.load_config(configuration) if not runner.configuration then if not configuration then -- Nothing provided, load from default location if possible. set_config(load_config_file(default_config_file, true) or runner.defaults) elseif type(configuration) == "string" then set_config(load_config_file(configuration)) elseif type(configuration) == "table" then set_config(configuration) else error("Expected filename, config table or nil. Got " .. type(configuration)) end end return runner.configuration end -------------------------------------------------- -- Pauses saving data collected by LuaCov's runner. -- Allows other processes to write to the same stats file. -- Data is still collected during pause. function runner.pause() runner.paused = true end -------------------------------------------------- -- Resumes saving data collected by LuaCov's runner. function runner.resume() runner.paused = false end local hook_per_thread -- Determines whether debug hooks are separate for each thread. local function has_hook_per_thread() if hook_per_thread == nil then local old_hook, old_mask, old_count = debug.gethook() local noop = function() end debug.sethook(noop, "l") local thread_hook = coroutine.wrap(function() return debug.gethook() end)() hook_per_thread = thread_hook ~= noop debug.sethook(old_hook, old_mask, old_count) end return hook_per_thread end -------------------------------------------------- -- Wraps a function, enabling coverage gathering in it explicitly. -- LuaCov gathers coverage using a debug hook, and patches coroutine -- library to set it on created threads when under standard Lua, where each -- coroutine has its own hook. If a coroutine is created using Lua C API -- or before the monkey-patching, this wrapper should be applied to the -- main function of the coroutine. Under LuaJIT this function is redundant, -- as there is only one, global debug hook. -- @param f a function -- @return a function that enables coverage gathering and calls the original function. -- @usage -- local coro = coroutine.create(runner.with_luacov(func)) function runner.with_luacov(f) return function(...) if has_hook_per_thread() then debug.sethook(runner.debug_hook, "l") end return f(...) end end -------------------------------------------------- -- Initializes LuaCov runner to start collecting data. -- @param[opt] configuration if string, filename of config file (used to call `load_config`). -- If table then config table (see file `luacov.default.lua` for an example) function runner.init(configuration) runner.configuration = runner.load_config(configuration) -- metatable trick on filehandle won't work if Lua exits through -- os.exit() hence wrap that with exit code as well os.exit = function(...) -- luacheck: no global on_exit() raw_os_exit(...) end debug.sethook(runner.debug_hook, "l") if has_hook_per_thread() then -- debug must be set for each coroutine separately -- hence wrap coroutine function to set the hook there -- as well local rawcoroutinecreate = coroutine.create coroutine.create = function(...) -- luacheck: no global local co = rawcoroutinecreate(...) debug.sethook(co, runner.debug_hook, "l") return co end -- Version of assert which handles non-string errors properly. local function safeassert(ok, ...) if ok then return ... else error(..., 0) end end coroutine.wrap = function(...) -- luacheck: no global local co = rawcoroutinecreate(...) debug.sethook(co, runner.debug_hook, "l") return function(...) return safeassert(coroutine.resume(co, ...)) end end end if not runner.tick then runner.on_exit_trick = on_exit_wrap(on_exit) end runner.initialized = true runner.paused = false end -------------------------------------------------- -- Shuts down LuaCov's runner. -- This should only be called from daemon processes or sandboxes which have -- disabled os.exit and other hooks that are used to determine shutdown. function runner.shutdown() on_exit() end -- Gets the sourcefilename from a function. -- @param func function to lookup. -- @return sourcefilename or nil when not found. local function getsourcefile(func) assert(type(func) == "function") local d = debug.getinfo(func).source if d and d:sub(1, 1) == "@" then return d:sub(2) end end -- Looks for a function inside a table. -- @param searched set of already checked tables. local function findfunction(t, searched) if searched[t] then return end searched[t] = true for _, v in pairs(t) do if type(v) == "function" then return v elseif type(v) == "table" then local func = findfunction(v, searched) if func then return func end end end end -- Gets source filename from a file name, module name, function or table. -- @param name string; filename, -- string; modulename as passed to require(), -- function; where containing file is looked up, -- table; module table where containing file is looked up -- @raise error message if could not find source filename. -- @return source filename. local function getfilename(name) if type(name) == "function" then local sourcefile = getsourcefile(name) if not sourcefile then error("Could not infer source filename") end return sourcefile elseif type(name) == "table" then local func = findfunction(name, {}) if not func then error("Could not find a function within " .. tostring(name)) end return getfilename(func) else if type(name) ~= "string" then error("Bad argument: " .. tostring(name)) end if util.file_exists(name) then return name end local success, result = pcall(require, name) if not success then error("Module/file '" .. name .. "' was not found") end if type(result) ~= "table" and type(result) ~= "function" then error("Module '" .. name .. "' did not return a result to lookup its file name") end return getfilename(result) end end -- Escapes a filename. -- Escapes magic pattern characters, removes .lua extension -- and replaces dir seps by '/'. local function escapefilename(name) return name:gsub("%.lua$", ""):gsub("[%%%^%$%.%(%)%[%]%+%*%-%?]","%%%0"):gsub("\\", "/") end local function addfiletolist(name, list) local f = "^"..escapefilename(getfilename(name)).."$" table.insert(list, f) return f end local function addtreetolist(name, level, list) local f = escapefilename(getfilename(name)) if level or f:match("/init$") then -- chop the last backslash and everything after it f = f:match("^(.*)/") or f end local t = "^"..f.."/" -- the tree behind the file f = "^"..f.."$" -- the file table.insert(list, f) table.insert(list, t) return f, t end -- Returns a pcall result, with the initial 'true' value removed -- and 'false' replaced with nil. local function checkresult(ok, ...) if ok then return ... -- success, strip 'true' value else return nil, ... -- failure; nil + error end end ------------------------------------------------------------------- -- Adds a file to the exclude list (see `luacov.defaults`). -- If passed a function, then through debuginfo the source filename is collected. In case of a table -- it will recursively search the table for a function, which is then resolved to a filename through debuginfo. -- If the parameter is a string, it will first check if a file by that name exists. If it doesn't exist -- it will call `require(name)` to load a module by that name, and the result of require (function or -- table expected) is used as described above to get the sourcefile. -- @param name -- * string; literal filename, -- * string; modulename as passed to require(), -- * function; where containing file is looked up, -- * table; module table where containing file is looked up -- @return the pattern as added to the list, or nil + error function runner.excludefile(name) return checkresult(pcall(addfiletolist, name, runner.configuration.exclude)) end ------------------------------------------------------------------- -- Adds a file to the include list (see `luacov.defaults`). -- @param name see `excludefile` -- @return the pattern as added to the list, or nil + error function runner.includefile(name) return checkresult(pcall(addfiletolist, name, runner.configuration.include)) end ------------------------------------------------------------------- -- Adds a tree to the exclude list (see `luacov.defaults`). -- If `name = 'luacov'` and `level = nil` then -- module 'luacov' (luacov.lua) and the tree 'luacov' (containing `luacov/runner.lua` etc.) is excluded. -- If `name = 'pl.path'` and `level = true` then -- module 'pl' (pl.lua) and the tree 'pl' (containing `pl/path.lua` etc.) is excluded. -- NOTE: in case of an 'init.lua' file, the 'level' parameter will always be set -- @param name see `excludefile` -- @param level if truthy then one level up is added, including the tree -- @return the 2 patterns as added to the list (file and tree), or nil + error function runner.excludetree(name, level) return checkresult(pcall(addtreetolist, name, level, runner.configuration.exclude)) end ------------------------------------------------------------------- -- Adds a tree to the include list (see `luacov.defaults`). -- @param name see `excludefile` -- @param level see `includetree` -- @return the 2 patterns as added to the list (file and tree), or nil + error function runner.includetree(name, level) return checkresult(pcall(addtreetolist, name, level, runner.configuration.include)) end return setmetatable(runner, {__call = function(_, configfile) runner.init(configfile) end})
mit
ioiasff/khp
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
aqasaeed/spartacus
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
adib1380/antispam
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
merlokk/proxmark3
client/scripts/lf_bulk_program.lua
5
4681
-- -- lf_bulk_program.lua - A tool to clone a large number of tags at once. -- Updated 2017-04-18 -- -- The getopt-functionality is loaded from pm3/client/lualibs/getopt.lua -- Have a look there for further details getopt = require('getopt') bit32 = require('bit32') usage = [[ script run lf_bulk_program.lua -f facility -b base_id_num -c count e.g: script run lf_bulk_program.lua -f 1 -b 1000 -c 10 ]] author = "Brian Redbeard" desc =[[ Perform bulk enrollment of 26 bit H10301 style RFID Tags For more info, check the comments in the code ]] --[[Implement a function to simply visualize the bitstream in a text format --This is especially helpful for troubleshooting bitwise math issues]]-- function toBits(num,bits) -- returns a table of bits, most significant first. bits = bits or math.max(1, select(2, math.frexp(num))) local t = {} -- will contain the bits for b = bits, 1, -1 do t[b] = math.fmod(num, 2) num = math.floor((num - t[b]) / 2) end return table.concat(t) end --[[Likely, I'm an idiot, but I couldn't find any parity functions in Lua This can also be done with a combination of bitwise operations (in fact, is the canonically "correct" way to do it, but my brain doesn't just default to this and so counting some ones is good enough for me]]-- local function evenparity(s) local _, count = string.gsub(s, "1", "") local p = count % 2 if (p == 0) then return(false) else return(true) end end local function isempty(s) return s == nil or s == '' end --[[The Proxmark3 "clone" functions expect the data to be in hex format so take the card id number and facility ID as arguments and construct the hex. This should be easy enough to extend to non 26bit formats]]-- local function cardHex(i,f) fac = bit32.lshift(f,16) id = bit32.bor(i, fac) stream=toBits(id,24) --As the function defaults to even parity and returns a boolean, --perform a 'not' function to get odd parity high = evenparity(string.sub(stream,1,12)) and 1 or 0 low = not evenparity(string.sub(stream,13)) and 1 or 0 bits = bit32.bor(bit32.lshift(id,1), low) bits = bit32.bor(bits, bit32.lshift(high,25)) --Since the lua library bit32 is (obviously) 32 bits and we need to --encode 36 bits to properly do a 26 bit tag with the preamble we need --to create a higher order and lower order component which we will --then assemble in the return. The math above defines the proper --encoding as per HID/Weigand/etc. These bit flips are due to the --format length check on bit 38 (cmdlfhid.c:64) and --bit 31 (cmdlfhid.c:66). preamble = bit32.bor(0, bit32.lshift(1,5)) bits = bit32.bor(bits, bit32.lshift(1,26)) return ("%04x%08x"):format(preamble,bits) end local function main(args) --I really wish a better getopt function would be brought in supporting --long arguments, but it seems this library was chosen for BSD style --compatibility for o, a in getopt.getopt(args, 'f:b:c:h') do if o == 'f' then if isempty(a) then print("You did not supply a facility code, using 0") facility = 0 else facility = a end elseif o == 'b' then if isempty(a) then print("You must supply the flag -b (base id)") return else baseid = a end elseif o == 'c' then if isempty(a) then print("You must supply the flag -c (count)") return else count = a end elseif o == 'h' then print(desc) print(usage) return end end --Due to my earlier complaints about how this specific getopt library --works, specifying ":" does not enforce supplying a value, thus we --need to do these checks all over again. if isempty(baseid) then print("You must supply the flag -b (base id)") print(usage) return end if isempty(count) then print("You must supply the flag -c (count)") print(usage) return end --If the facility ID is non specified, ensure we code it as zero if isempty(facility) then print("Using 0 for the facility code as -f was not supplied") facility = 0 end --The next baseid + count function presents a logic/UX conflict --where users specifying -c 1 (count = 1) would try to program two --tags. This makes it so that -c 0 & -c 1 both code one tag, and all --other values encode the expected amount. if tonumber(count) > 0 then count = count -1 end endid = baseid + count for cardnum = baseid,endid do local card = cardHex(cardnum, facility) print("Press enter to program card "..cardnum..":"..facility.." (hex: "..card..")") --This would be better with "press any key", but we'll take --what we can get. io.read() core.console( ('lf hid clone %s'):format(card) ) end end main(args)
gpl-2.0
mehrdadneyazy78/-S-Bot
plugins/lyrics.lua
695
2113
do local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs' local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5' local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect' local function getInfo(query) print('Getting info of ' .. query) local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY ..'&q='..URL.escape(query) local b, c = http.request(url) if c ~= 200 then return nil end local result = json:decode(b) local artist = result[1].artist.name local track = result[1].title return artist, track end local function getLyrics(query) local artist, track = getInfo(query) if artist and track then local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist) ..'&song='..URL.escape(track) local b, c = http.request(url) if c ~= 200 then return nil end local xml = require("xml") local result = xml.load(b) if not result then return nil end if xml.find(result, 'LyricSong') then track = xml.find(result, 'LyricSong')[1] end if xml.find(result, 'LyricArtist') then artist = xml.find(result, 'LyricArtist')[1] end local lyric if xml.find(result, 'Lyric') then lyric = xml.find(result, 'Lyric')[1] else lyric = nil end local cover if xml.find(result, 'LyricCovertArtUrl') then cover = xml.find(result, 'LyricCovertArtUrl')[1] else cover = nil end return artist, track, lyric, cover else return nil end end local function run(msg, matches) local artist, track, lyric, cover = getLyrics(matches[1]) if track and artist and lyric then if cover then local receiver = get_receiver(msg) send_photo_from_url(receiver, cover) end return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric else return 'Oops! Lyrics not found or something like that! :/' end end return { description = 'Getting lyrics of a song', usage = '!lyrics [track or artist - track]: Search and get lyrics of the song', patterns = { '^!lyrics? (.*)$' }, run = run } end
gpl-2.0
kyuu/dynrpg-rpgss
assets/Scripts/extensions/pathfinder/interface.lua
1
4317
------------------------------------------------------------------------------- -- Sets the pathfinder search mode. -- -- @param mode (String) The new search mode. Possible values are -- "orthogonal" (4-way movement) and "diagonal" -- (8-way movement). ------------------------------------------------------------------------------- function set_search_mode(mode) assert(mode == "orthogonal" or mode == "diagonal", "invalid mode") PathFinder:setSearchMode(mode) end ------------------------------------------------------------------------------- -- Sets the walkable terrains. -- -- @param (...) (Number) Variable number of terrain IDs to set as -- walkable. -- For instance, set_walkable_terrains(1, 2, 3) -- will set the terrain IDs 1, 2 and 3 as -- walkable. ------------------------------------------------------------------------------- function set_walkable_terrains(...) local walkable = {} for _, tid in ipairs(arg) do table.insert(walkable, tid) end PathFinder:setWalkableTerrains(walkable) end ------------------------------------------------------------------------------- -- Determines if a particular position on the map is walkable, taking into -- account the currently set walkable terrains, the hero position and the -- positions of events that are at the same level as hero. -- -- @param x, y (Number) The map position to test for walkability. -- @param vresult (Number) The ID of the variable that will hold the -- boolean result (1 for walkable, 0 otherwise). ------------------------------------------------------------------------------- function is_walkable(x, y, vresult) game.variables[vresult] = PathFinder:isWalkable(x, y) end ------------------------------------------------------------------------------- -- Looks for a path from the current position of a character to the position -- specified by (x, y) and, if found moves the character on the path. -- -- @param name (String) The name of the character to move. Possible -- values are "hero" to move the hero, or the -- name of an existing event to move the event. -- @param x, y (Number) The map position to move the character to. -- @param frequency (Number) Optional frequency (speed) at which to move -- the character, in the range 1 (slowest) to -- 8 (fastest). Defaults to 8. -- @param maxmoves (Number) Optional upper limit for the number of moves -- performed. If you don't care, either pass 0 -- (or any smaller number), or leave out. -- @param allownearest (Number) Optional flag that determines (in case a path -- to the specified position could not be found) -- if a path to the nearest position is also -- acceptable. Pass 1 if acceptable, 0 otherwise. -- If left out, a path to the nearest position -- is assumed as inacceptable. -- @param vresult (Number) Optional ID of the variable that will hold the -- result of the operation (1 for path found, -- 0 otherwise). ------------------------------------------------------------------------------- function move_character(name, x, y, frequency, maxmoves, allownearest, vresult) assert(type(name) == "string" and #name > 0, "invalid name") frequency = frequency or 8 maxmoves = maxmoves or -1 allownearest = allownearest == 1 and true or false local character if name == "hero" then character = game.map.hero else character = game.map.findEvent(name) end if character == nil then error("character '"..name.."' does not exist") end local path, length = PathFinder:move(character, x, y, frequency, maxmoves, allownearest) if vresult then game.variables[vresult] = path and 1 or 0 end end
mit
mobarski/sandbox
scite/old/wscite_zzz/lexers/notused/cpp.lua
4
2938
-- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE. -- C++ LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local M = {_NAME = 'cpp'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local line_comment = '//' * l.nonnewline_esc^0 local block_comment = '/*' * (l.any - '*/')^0 * P('*/')^-1 local comment = token(l.COMMENT, line_comment + block_comment) -- Strings. local sq_str = P('L')^-1 * l.delimited_range("'", true) local dq_str = P('L')^-1 * l.delimited_range('"', true) local string = token(l.STRING, sq_str + dq_str) -- Numbers. local number = token(l.NUMBER, l.float + l.integer) -- Preprocessor. local preproc_word = word_match{ 'define', 'elif', 'else', 'endif', 'error', 'if', 'ifdef', 'ifndef', 'import', 'line', 'pragma', 'undef', 'using', 'warning' } local preproc = #l.starts_line('#') * (token(l.PREPROCESSOR, '#' * S('\t ')^0 * preproc_word) + token(l.PREPROCESSOR, '#' * S('\t ')^0 * 'include') * (token(l.WHITESPACE, S('\t ')^1) * token(l.STRING, l.delimited_range('<>', true, true)))^-1) -- Keywords. local keyword = token(l.KEYWORD, word_match{ 'asm', 'auto', 'break', 'case', 'catch', 'class', 'const', 'const_cast', 'continue', 'default', 'delete', 'do', 'dynamic_cast', 'else', 'explicit', 'export', 'extern', 'false', 'for', 'friend', 'goto', 'if', 'inline', 'mutable', 'namespace', 'new', 'operator', 'private', 'protected', 'public', 'register', 'reinterpret_cast', 'return', 'sizeof', 'static', 'static_cast', 'switch', 'template', 'this', 'throw', 'true', 'try', 'typedef', 'typeid', 'typename', 'using', 'virtual', 'volatile', 'while', -- Operators 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not', 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq', -- C++11 'alignas', 'alignof', 'constexpr', 'decltype', 'final', 'noexcept', 'override', 'static_assert', 'thread_local' }) -- Types. local type = token(l.TYPE, word_match{ 'bool', 'char', 'double', 'enum', 'float', 'int', 'long', 'short', 'signed', 'struct', 'union', 'unsigned', 'void', 'wchar_t', -- C++11 'char16_t', 'char32_t', 'nullptr' }) -- Identifiers. local identifier = token(l.IDENTIFIER, l.word) -- Operators. local operator = token(l.OPERATOR, S('+-/*%<>!=^&|?~:;,.()[]{}')) M._rules = { {'whitespace', ws}, {'keyword', keyword}, {'type', type}, {'identifier', identifier}, {'string', string}, {'comment', comment}, {'number', number}, {'preproc', preproc}, {'operator', operator}, } M._foldsymbols = { _patterns = {'%l+', '[{}]', '/%*', '%*/', '//'}, [l.PREPROCESSOR] = { region = 1, endregion = -1, ['if'] = 1, ifdef = 1, ifndef = 1, endif = -1 }, [l.OPERATOR] = {['{'] = 1, ['}'] = -1}, [l.COMMENT] = {['/*'] = 1, ['*/'] = -1, ['//'] = l.fold_line_comments('//')} } return M
mit
lizh06/premake-core
tests/actions/vstudio/cs2005/test_debug_props.lua
6
2015
-- -- tests/actions/vstudio/cs2005/test_debug_props.lua -- Test debugging and optimization flags block of a Visual Studio 2005+ C# project. -- Copyright (c) 2012-2013 Jason Perkins and the Premake project -- local suite = test.declare("vstudio_cs2005_debug_props") local cs2005 = premake.vstudio.cs2005 local project = premake.project -- -- Setup and teardown -- local wks, prj function suite.setup() premake.action.set("vs2005") wks, prj = test.createWorkspace() end local function prepare() local cfg = test.getconfig(prj, "Debug") cs2005.debugProps(cfg) end -- -- Check the handling of the Symbols flag. -- function suite.debugSymbols_onNoSymbolsFlag() prepare() test.capture [[ <DebugType>pdbonly</DebugType> <Optimize>false</Optimize> ]] end function suite.debugSymbols_onSymbolsFlag() symbols "On" prepare() test.capture [[ <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> ]] end --- --- Check handling of debug parameters. --- function suite.debugCommandParameters() debugargs "foobar" local cfg = test.getconfig(prj, "Debug") cs2005.debugCommandParameters(cfg) test.capture [[ <Commandlineparameters>foobar</Commandlineparameters> ]] end function suite.debugStartArguments() debugargs "foobar" local cfg = test.getconfig(prj, "Debug") cs2005.localDebuggerCommandArguments(cfg) test.capture [[ <StartArguments>foobar</StartArguments> ]] end -- -- Check handling of optimization flags. -- function suite.optimize_onOptimizeFlag() optimize "On" prepare() test.capture [[ <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> ]] end function suite.optimize_onOptimizeSizeFlag() optimize "Size" prepare() test.capture [[ <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> ]] end function suite.optimize_onOptimizeSpeedFlag() optimize "Speed" prepare() test.capture [[ <DebugType>pdbonly</DebugType> <Optimize>true</Optimize> ]] end
bsd-3-clause
mattico/planets
quickie/input.lua
15
3335
--[[ Copyright (c) 2012 Matthias Richter 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. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local BASE = (...):match("(.-)[^%.]+$") local core = require(BASE .. 'core') local group = require(BASE .. 'group') local mouse = require(BASE .. 'mouse') local keyboard = require(BASE .. 'keyboard') local utf8 = require(BASE .. 'utf8') -- {info = {text = "", cursor = text:len()}, pos = {x, y}, size={w, h}, widgetHit=widgetHit, draw=draw} return function(w) assert(type(w) == "table" and type(w.info) == "table", "Invalid argument") w.info.text = w.info.text or "" w.info.cursor = math.min(w.info.cursor or w.info.text:len(), w.info.text:len()) local id = w.id or core.generateID() local pos, size = group.getRect(w.pos, w.size) mouse.updateWidget(id, pos, size, w.widgetHit) keyboard.makeCyclable(id) if mouse.isActive(id) then keyboard.setFocus(id) end if not keyboard.hasFocus(id) then --[[nothing]] -- editing elseif keyboard.key == 'backspace' and w.info.cursor > 0 then w.info.cursor = math.max(0, w.info.cursor-1) local left, right = utf8.split(w.info.text, w.info.cursor) w.info.text = left .. utf8.sub(right, 2) elseif keyboard.key == 'delete' then local left, right = utf8.split(w.info.text, w.info.cursor) w.info.text = left .. utf8.sub(right, 2) w.info.cursor = math.min(w.info.text:len(), w.info.cursor) -- movement elseif keyboard.key == 'left' then w.info.cursor = math.max(0, w.info.cursor-1) elseif keyboard.key == 'right' then w.info.cursor = math.min(w.info.text:len(), w.info.cursor+1) elseif keyboard.key == 'home' then w.info.cursor = 0 elseif keyboard.key == 'end' then w.info.cursor = w.info.text:len() -- info elseif keyboard.key == 'return' then keyboard.clearFocus() keyboard.pressed('', -1) elseif keyboard.str then local left, right = utf8.split(w.info.text, w.info.cursor) w.info.text = left .. keyboard.str .. right w.info.cursor = w.info.cursor + 1 end core.registerDraw(id, w.draw or core.style.Input, w.info.text, w.info.cursor, pos[1],pos[2], size[1],size[2]) return mouse.releasedOn(id) or keyboard.pressedOn(id, 'return') end
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/FadeOutBLTiles.lua
11
1263
-------------------------------- -- @module FadeOutBLTiles -- @extend FadeOutTRTiles -- @parent_module cc -------------------------------- -- brief Create the action with the grid size and the duration.<br> -- param duration Specify the duration of the FadeOutBLTiles action. It's a value in seconds.<br> -- param gridSize Specify the size of the grid.<br> -- return If the creation success, return a pointer of FadeOutBLTiles action; otherwise, return nil. -- @function [parent=#FadeOutBLTiles] create -- @param self -- @param #float duration -- @param #size_table gridSize -- @return FadeOutBLTiles#FadeOutBLTiles ret (return value: cc.FadeOutBLTiles) -------------------------------- -- -- @function [parent=#FadeOutBLTiles] clone -- @param self -- @return FadeOutBLTiles#FadeOutBLTiles ret (return value: cc.FadeOutBLTiles) -------------------------------- -- -- @function [parent=#FadeOutBLTiles] testFunc -- @param self -- @param #size_table pos -- @param #float time -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#FadeOutBLTiles] FadeOutBLTiles -- @param self -- @return FadeOutBLTiles#FadeOutBLTiles self (return value: cc.FadeOutBLTiles) return nil
mit
mobarski/sandbox
scite/old/wscite_zzz/lexers/notused/vcard.lua
4
3521
-- Copyright (c) 2015-2017 Piotr Orzechowski [drzewo.org]. See LICENSE. -- vCard 2.1, 3.0 and 4.0 LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local M = {_NAME = 'vcard'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Required properties. local required_property = token(l.KEYWORD, word_match({ 'BEGIN', 'END', 'FN', 'N' --[[ Not required in v4.0. ]], 'VERSION' }, nil, true)) * #P(':') -- Supported properties. local supported_property = token(l.TYPE, word_match({ 'ADR', 'AGENT' --[[ Not supported in v4.0. ]], 'ANNIVERSARY' --[[ Supported in v4.0 only. ]], 'BDAY', 'CALADRURI' --[[ Supported in v4.0 only. ]], 'CALURI' --[[ Supported in v4.0 only. ]], 'CATEGORIES', 'CLASS' --[[ Supported in v3.0 only. ]], 'CLIENTPIDMAP' --[[ Supported in v4.0 only. ]], 'EMAIL', 'END', 'FBURL' --[[ Supported in v4.0 only. ]], 'GENDER' --[[ Supported in v4.0 only. ]], 'GEO', 'IMPP' --[[ Not supported in v2.1. ]], 'KEY', 'KIND' --[[ Supported in v4.0 only. ]], 'LABEL' --[[ Not supported in v4.0. ]], 'LANG' --[[ Supported in v4.0 only. ]], 'LOGO', 'MAILER' --[[ Not supported in v4.0. ]], 'MEMBER' --[[ Supported in v4.0 only. ]], 'NAME' --[[ Supported in v3.0 only. ]], 'NICKNAME' --[[ Not supported in v2.1. ]], 'NOTE', 'ORG', 'PHOTO', 'PRODID' --[[ Not supported in v2.1. ]], 'PROFILE' --[[ Not supported in v4.0. ]], 'RELATED' --[[ Supported in v4.0 only. ]], 'REV', 'ROLE', 'SORT-STRING' --[[ Not supported in v4.0. ]], 'SOUND', 'SOURCE', 'TEL', 'TITLE', 'TZ', 'UID', 'URL', 'XML' --[[ Supported in v4.0 only. ]] }, nil, true)) * #S(':;') local identifier = l.alpha^1 * l.digit^0 * (P('-') * l.alnum^1)^0 -- Extension. local extension = token(l.TYPE, l.starts_line(S('xX') * P('-') * identifier * #S(':;'))) -- Parameter. local parameter = token(l.IDENTIFIER, l.starts_line(identifier * #S(':='))) + token(l.STRING, identifier) * #S(':=') -- Operators. local operator = token(l.OPERATOR, S('.:;=')) -- Group and property. local group_sequence = token(l.CONSTANT, l.starts_line(identifier)) * token(l.OPERATOR, P('.')) * (required_property + supported_property + l.token(l.TYPE, S('xX') * P('-') * identifier) * #S(':;')) -- Begin vCard, end vCard. local begin_sequence = token(l.KEYWORD, P('BEGIN')) * token(l.OPERATOR, P(':')) * token(l.COMMENT, P('VCARD')) local end_sequence = token(l.KEYWORD, P('END')) * token(l.OPERATOR, P(':')) * token(l.COMMENT, P('VCARD')) -- vCard version (in v3.0 and v4.0 must appear immediately after BEGIN:VCARD). local version_sequence = token(l.KEYWORD, P('VERSION')) * token(l.OPERATOR, P(':')) * token(l.CONSTANT, l.digit^1 * (P('.') * l.digit^1)^-1) -- Data. local data = token(l.IDENTIFIER, l.any) -- Rules. M._rules = { {'whitespace', ws}, {'begin_sequence', begin_sequence}, {'end_sequence', end_sequence}, {'version_sequence', version_sequence}, {'group_sequence', group_sequence}, {'required_property', required_property}, {'supported_property', supported_property}, {'extension', extension}, {'parameter', parameter}, {'operator', operator}, {'data', data}, } -- Folding. M._foldsymbols = { _patterns = {'BEGIN', 'END'}, [l.KEYWORD] = {['BEGIN'] = 1, ['END'] = -1} } return M
mit
ctfuckme/asasasas
plugins/invite.lua
17
1595
-- Invite other user to the chat group. -- Use !invite name User_name or !invite id id_number -- The User_name is the print_name (there are no spaces but _) do local function res_user_callback(cb_extra, success, result) local receiver = cb_extra.receiver local user = 'user#id'..result.id local chat = 'chat#id'..cb_extra.chat_id if success == 0 then return send_large_msg(receiver, "Can't invite user to this group.") end chat_add_user(chat, user, cb_ok, false) end local function run(msg, matches) -- The message must come from a chat group if msg.to.type == 'chat' then local chat = 'chat#id'..msg.to.id local user = matches[2] -- User submitted a name if matches[1] == "name" then user = string.gsub(user," ","_") chat_add_user(chat, user, callback, false) end -- User submitted a user name if matches[1] == "username" then username = string.gsub(user,"@","") msgr = res_user(username, res_user_callback, {receiver=receiver, chat_id=msg.to.id}) end -- User submitted an id if matches[1] == "id" then user = 'user#id'..user chat_add_user(chat, user, callback, false) end return "Add "..user.." to "..chat else return "This isn't a chat group!" end end return { description = "Invite other user to the chat group", usage = { "!invite name [name]", "!invite username [user_name]", "!invite id [user_id]" }, patterns = { "^!invite (name) (.*)$", "^!invite (username) (.*)$", "^!invite (id) (%d+)$" }, run = run, moderation = true } end
gpl-2.0
LuaDist2/oil
lua/oil/kernel/base/Dispatcher.lua
6
4253
-------------------------------------------------------------------------------- ------------------------------ ##### ## ------------------------------ ------------------------------ ## ## # ## ------------------------------ ------------------------------ ## ## ## ## ------------------------------ ------------------------------ ## ## # ## ------------------------------ ------------------------------ ##### ### ###### ------------------------------ -------------------------------- -------------------------------- ----------------------- An Object Request Broker in Lua ------------------------ -------------------------------------------------------------------------------- -- Project: OiL - ORB in Lua: An Object Request Broker in Lua -- -- Release: 0.5 -- -- Title : Object Request Dispatcher -- -- Authors: Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- -- dispatcher:Facet -- success:boolean, [except:table]|results... dispatch(key:string, operation:string|function, params...) -------------------------------------------------------------------------------- local luapcall = pcall local setmetatable = setmetatable local type = type local select = select local unpack = unpack local table = require "loop.table" local oo = require "oil.oo" local Exception = require "oil.Exception" --[[VERBOSE]] local verbose = require "oil.verbose" module("oil.kernel.base.Dispatcher", oo.class) pcall = luapcall context = false -------------------------------------------------------------------------------- -- Dispatcher facet function dispatch(self, request) local object, operation = request:preinvoke() if object then object = self.context.servants:retrieve(object) if object then local method = object[operation] if method then --[[VERBOSE]] verbose:dispatcher("dispatching operation ",object,":",operation,request:params()) request:results(self.pcall(method, object, request:params())) else --[[VERBOSE]] verbose:dispatcher("missing implementation of ",opname) request:results(false, Exception{ reason = "noimplement", message = "no implementation for operation of object with key", operation = operation, object = object, key = key, }) end else --[[VERBOSE]] verbose:dispatcher("got illegal object ",key) request:results(false, Exception{ reason = "badkey", message = "no object with key", key = key, }) end end end -------------------------------------------------------------------------------- --[[VERBOSE]] function verbose.custom:dispatcher(...) --[[VERBOSE]] local params --[[VERBOSE]] for i = 1, select("#", ...) do --[[VERBOSE]] local value = select(i, ...) --[[VERBOSE]] local type = type(value) --[[VERBOSE]] if params == true then --[[VERBOSE]] params = "(" --[[VERBOSE]] if type == "string" then --[[VERBOSE]] self.viewer.output:write(value) --[[VERBOSE]] else --[[VERBOSE]] self.viewer:write(value) --[[VERBOSE]] end --[[VERBOSE]] elseif type == "string" then --[[VERBOSE]] if params then --[[VERBOSE]] self.viewer.output:write(params) --[[VERBOSE]] params = ", " --[[VERBOSE]] self.viewer:write((value:gsub("[^%w%p%s]", "?"))) --[[VERBOSE]] else --[[VERBOSE]] self.viewer.output:write(value) --[[VERBOSE]] if value == ":" then params = true end --[[VERBOSE]] end --[[VERBOSE]] else --[[VERBOSE]] if params then --[[VERBOSE]] self.viewer.output:write(params) --[[VERBOSE]] params = ", " --[[VERBOSE]] end --[[VERBOSE]] self.viewer:write(value) --[[VERBOSE]] end --[[VERBOSE]] end --[[VERBOSE]] if params then --[[VERBOSE]] self.viewer.output:write(params == "(" and "()" or ")") --[[VERBOSE]] end --[[VERBOSE]] end
mit
Telecat-full/-Telecat-Full
plugins/LinkPv.lua
2
31045
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] == 'linkpv' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") send_large_msg('user#id'..msg.from.id, "Group link:\n"..group_link) 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 = { "^([Ll][Ii][Nn][Kk][Pp][Vv])$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
hfjgjfg/amir2
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
meirfaraj/tiproject
finance/src/finance/tmv/cours/mathfi/gen/SwapDeTaux.lua
1
12204
-------------------------------------------------------------------------- -- cours exported from SwapDeTaux.txt -------------------------------------------------------------------------- SwapDeTaux = Tmv(SWAP_DE_TAUX_TITLE_ID,SWAP_DE_TAUX_TITLE_HEADER_ID) function SwapDeTaux:widgetsInit() self:add(-1,{"cours","Exemple: valorisation et risue swap vanille","Exemple: valorisation de swap","Exemple: swap avec taux forward"},"curTtl",true) end function SwapDeTaux:performCalc() self.operation = "" if varValue["curTtl"] == "cours" then self:appendToResult("") self:appendTitleToResult("Swap vanille") self:appendToResult("Swap taux fixe contre taux variable ou taux fixe donneur:swap emprunteur ") self:appendMathToResult("M * Di*[TV-TF]") self:appendToResult(".") self:appendToResult("Swap taux variable contre taux fixe ou taux fixe receveur:swap preteur ") self:appendMathToResult("M * Di*[TF-TV]") self:appendToResult(".") self:appendToResult("Swap taux fixe k donneur: ") self:appendMathToResult("S(r-k)") self:appendToResult(" s'analyse comme un emprunt "..a_grave.." taux fixe k combin"..e_acute.." "..a_grave.." ") self:appendToResult("un pret "..a_grave.." taux variable r, long actif Ar et court actik Ak: ") self:appendMathToResult("S(r-k)=Ar-Ak") self:appendToResult(" et vis versa pour ") self:appendMathToResult("S(k-r)") self:appendToResult(".") self:appendToResult("") self:appendMathToResult("S(k-r)=ak-ar") self:appendToResult(": jambe fixe -jambe variable ou bien ") self:appendMathToResult("S(k-r)=Ak-Ar") self:appendToResult(": composante fixe - composante variable ") self:appendToResult("Deux m"..e_acute.."thodes de valorisation des swap: d"..e_acute.."mant"..e_grave.."lement et "..e_acute.."quivalence.") self:appendToResult("pour d"..e_acute.."ment"..e_grave.."lement on actualise en utilisant les taux ZC extrait des gamme des taux swap k(t)") self:appendToResult("\n\n") return end if varValue["curTtl"] == "Exemple: valorisation et risue swap vanille" then self:appendToResult("") self:appendTitleToResult("Exemple: valorisation et risue swap vanille") self:appendToResult("swap preteur(tx fixe receveur) de 4 ans de dur"..e_acute.."e le 01/10/n-1, N=100M,") self:appendToResult("jambe variable E6R(coupon semestriel 01-04 et 01-10) et jambe fixe coupon annuel k=5% vers"..e_acute.." le 01/10/n,n+1,n+2,n+3") self:appendToResult("dates reset et les gammes de tx plates de la ") self:appendBoldToResult("Jv") self:appendToResult(" ainse que Nj(t-1,t):\n") self:appendToResult("01/10/n-1 tx plat: 5,5%, 01/4/n: 5%(182), 01/10/n=5.5%(183), 01/04/n+1: 5.5%(182), 01/10/n+1: 5%(183) \n") self:appendToResult("1)01/10/n+1 (apr"..e_grave.."s versement de coupon): gamme des taux plate 5% (taux fixe BTAN 4 ans et tx fixe swap 4 ans)\n") self:appendToResult("valeur march"..e_acute.." du swap V=0 car composantes fixes et variables au pair\n") self:appendToResult("2)31/3/n:gamme plate et tous les tx "..e_acute.."gaux "..a_grave.." 6%, donc juste avant versement de coupon V(S(k-r):\n") self:appendToResult("le coupon variable du 01/04/n = ") self:appendMathToResult(" Cn=100000*5.5%*182/360=2780.5K ") self:appendToResult(" donc V(Ar) = 100000+Cn=102780.5K \n") self:appendToResult("") self:appendMathToResult(" V(Ak)=100000 * (1.06)^1/2 * ( "..sum_sym.."((0.05/1.06^t)+100*1/1.06^4) = 99388.8 K ,t,1,4)") self:appendToResult(" \n") self:appendToResult("Donc ") self:appendMathToResult("V(S(k-r))=-3391.7K") self:appendToResult(" \n ") self:appendToResult("3) 01/10/n : (apr"..e_grave.."s coupons) tous les ts sont 5.5% calcul de la valeur des swaps par 2 m"..e_acute.."thodes: \n") self:appendToResult("M"..e_acute.."thode d"..e_acute.."mant"..e_grave.."lement: V(Ar)=100000K\n") self:appendToResult("") self:appendMathToResult(" V(Ak)=100000 * ( "..sum_sym.."((0.05/1.055^t)+100*1/1.055^3) = 98651.033 K ,t,1,3)") self:appendToResult(" \n ") self:appendToResult("Donc V(S(k-r))=-1348.966K \n ") self:appendToResult("M"..e_acute.."thode "..e_acute.."quivalence: ") self:appendMathToResult(" V(S(k-r))=100000 (5%-5.5%) * ( "..sum_sym.."((1/1.055^t)) = -1348.966K ,t,1,3)") self:appendToResult(" \n ") self:appendToResult("4) le 30/12/n-1, E(3mois)=5% aainsi que tous les autres tx. Calculons incidence d'une hausse des tx de 0.2% le 30/12/n-1 \n") self:appendToResult("On la formule ") self:appendMathToResult("dV(S(k-r))/dr=dV(A(k))/dr - dV(A(r))/dr ") self:appendToResult(" et ") self:appendMathToResult("A(r)=F * D/(1+rD)^2") self:appendToResult(" donc ") self:appendMathToResult("dV(A(r))/dr= -FD/(1+rD)^2") self:appendToResult(" \n") self:appendToResult("Le 30/12/n-1, les tx sont tous "..e_acute.."gaux "..a_grave.." 5%, d"..e_grave.."s lors une variation DELTA(r)=0.2% implique au premier ordre :\n") self:appendToResult("") self:appendMathToResult(" DELTA(V(Ar))=-DELTA(r) * F * D/(1+rD)^2 = -0.002 * 102780.5 * 0.25 / (1+0.25*0.05)^2 = -50.129K ") self:appendToResult(" \n") self:appendToResult("") self:appendMathToResult(" V(Ak)="..sum_sym.."((Fi/(1+r)^t-0.25) ,t,1,4)") self:appendToResult(" donc ") self:appendMathToResult("dV(A(k))/dr= - "..sum_sym.."(((t-0.25)Fi/(1+r)^t+0.75) ,t,1,4)") self:appendToResult(" au premier ordre :\n") self:appendToResult("") self:appendMathToResult(" DELTA(V(Ak))= DELTA(r) * dV(A(k))/dr = -0.002 * 334845.004 = -669.69K ") self:appendToResult(" \n") self:appendToResult("Donc DELTA(r) = 0.2% implique DELTA(V(S))=-669.69+50.129=-619.56K ") self:appendToResult("\n\n") return end if varValue["curTtl"] == "Exemple: valorisation de swap" then self:appendToResult("") self:appendTitleToResult("Exemple: valorisation de swap") self:appendToResult("Le 1/1/n date(0), courbe des swap plate "..a_grave.." 4%(quelque soit la matu, k=4%)") self:appendToResult("swap preteur X de 100M, 4 ann"..e_acute.."es "..a_grave.." courir, taux fixe receveur/L-3mois r"..e_acute.."visable donneur, contract"..e_acute.."") self:appendToResult(""..a_grave.." une date ant"..e_acute.."rieure au taux fixe 5%, coupons r"..e_acute.."visable pay"..e_acute.."s trimestriellement(31/3,30/6,30/9,31/12)") self:appendToResult("et le coupon fixe le 31/12. L3-mois(30/9/n-1)=4%(dern"..e_grave.."re date de reset)") self:appendToResult("On calcule valeur du swap le 1/1/n selon 2 m"..e_acute.."thodes, puis sa valeur le 30/12/n-1:") self:appendToResult("\n") self:appendToResult("a)1/1/n(0+, juste apr"..e_grave.."s le r"..e_grave.."glement)") self:appendToResult("\n") self:appendToResult("M"..e_acute.."thode d"..e_acute.."mant"..e_grave.."lement:V0(S(k-r))=V0+(A(k)) - V0+(A(r))") self:appendToResult("A(r) "..e_acute.."tant au pair V0+(A(r))=100") self:appendToResult("Courbe des taux plate donc taux ZC utilis"..e_acute.."s pour actualis"..e_acute.." A(k) sont "..e_acute.."gaux aux taux fixe swap(courbe plate)") self:appendToResult("") self:appendMathToResult("V0+(A(k))=5*"..sum_sym.."((1/1.04^t)+100*1/1.04^4=103.63,t,1,4)") self:appendToResult("donc ") self:appendMathToResult("V0(S(k-r))=3.63M") self:appendToResult(" Euro") self:appendToResult("\n") self:appendToResult("M"..e_acute.."thode "..e_acute.."quivalence:") self:appendMathToResult("V0+(S(k-r))=(5-4)"..sum_sym.."((1/1.04^t)=3.63,t,1,4)") self:appendToResult("M Euro") self:appendToResult("\n") self:appendToResult("b) valeur le 30/12/n-1 en 0-, juste avant r"..e_grave.."glement:") self:appendToResult("\n") self:appendToResult("rajouter pour chaque composante le coupon(annuel pour le fixe et semestriel pour le variable(") self:appendMathToResult("D = Nj/Na = 0.25") self:appendToResult(")") self:appendToResult("") self:appendMathToResult("V0-(A(k))=103.63+5=108.63") self:appendToResult(", ") self:appendMathToResult("V0-(A(r))=100 + 4 * 0.25=101") self:appendToResult(" donc ") self:appendMathToResult("V0-(S(k-r))=7.63") self:appendToResult("M Euro") self:appendToResult("\n") self:appendToResult("") self:appendBoldToResult("B.") self:appendToResult(" Un an plus tard 1/1/n+1(donc le Swap lui reste 3 ans), la gamme des taux fixe swap(k("..c_theta..")) "..e_acute.."volue") self:appendToResult("1an: 6%, 2ans: 6.5%, 3ans=7%, 4ans: 7.2%") self:appendToResult("\n") self:appendToResult("on commence par calciler la gamme ZC 1,2 et 3 ans implicite puis on calcule la valeur du swap(L-3mois contre 5%)") self:appendToResult("\n") self:appendToResult("a)calcul des prix b("..c_theta..") et des ZC "..a_grave.." partier de k("..c_theta..")") self:appendToResult("\n") self:appendToResult("") self:appendMathToResult("r1=k1=6%") self:appendToResult("donc ") self:appendMathToResult("b1=1/1.06=0.9434") self:appendToResult("; En "..e_acute.."crivant q'un titre "..a_grave.." 2 ans de coupon k2 est au pair, il vient:") self:appendToResult("") self:appendMathToResult("1=k2b1+(1+k2)b2=0.065*0.9434+1.065b2") self:appendToResult(", soit ") self:appendMathToResult("b2=0.8814") self:appendToResult(" donc ") self:appendMathToResult("r2=6.516%") self:appendToResult(" (") self:appendMathToResult("b2 = 1/(1+r2)^2") self:appendToResult(")") self:appendToResult("de m"..e_circ .."me pour 3 ans k3:1=k(3)b(1)+k(3)b(2)+(1+k(3))b(3) donc b(3)=0.8152 et r3=7.048%") self:appendToResult("b)valeur du swap le 1/1:n+1: par d"..e_acute.."mant"..e_grave.."lement=") self:appendMathToResult("V0+(A(r))=100M") self:appendToResult(",") self:appendMathToResult("V0+(A(k))=5*(b(1)+b(2))+105*b(3)=94.72") self:appendToResult("M") self:appendToResult("") self:appendMathToResult("V0+(S(k-r))=-5.28M") self:appendToResult("; Par "..e_acute.."quivalence: ") self:appendMathToResult("V0+(S(k-r))=(5-7)*(b1+b2+b3)=-5.28") self:appendMathToResult("M") self:appendToResult("\n") return end if varValue["curTtl"] == "Exemple: swap avec taux forward" then self:appendToResult("") self:appendTitleToResult("Exemple: swap avec taux forward") self:appendToResult("taux actuariels ZC r("..c_theta..") exrait des courbes taux fixes des swaps vanille le 1/4/n") self:appendToResult("3mois: 5%, 6mois: 5.3%, 9mois=5.4%, 12mois: 5.5%, 15mois: 5.6%") self:appendToResult("On se situe le 1/4/n, swap L-6mois contre taux fixe 6%, 15mois de vie "..a_grave.." courir avec 3 echeances semestrielles") self:appendToResult("situ"..e_acute.."s les 1/7/n, 1/1/n+1 et 1/7/n+1 et jambe fixe 1/7/n et 1/7/n+1; N=100M et le 1/1/n L-6mois=4%") self:appendToResult("On raisonne avec semestre = 0.5 et trimestre 0.25") self:appendToResult("M"..e_acute.."thode des taux forward:") self:appendToResult("") self:appendMathToResult("(1+f(3,6))^0.5= (1+r(9))^0.75/(1+r(3))^0.25 ") self:appendToResult(" soit ") self:appendMathToResult("f(3,6)=5.6%") self:appendToResult(" ; ") self:appendMathToResult("(1+f(9,6))^0.5=(1+r(15))^1.25/(1+r(9))^0.75") self:appendToResult(" soit ") self:appendMathToResult("f(9,6)=5.91%") self:appendToResult(" \n") self:appendToResult("") self:appendBoldToResult("Jambe fixe") self:appendToResult(" =: ") self:appendMathToResult("V(a(k))=6*(1/1.05^0.25+1/1.056^1.25)=11.89") self:appendToResult("M") self:appendToResult("") self:appendBoldToResult("Jambe variable") self:appendToResult(": on actualise le premier coupon connu(0.5*4%*100=2) et les "..e_acute.."quivalents certains des suivants(tx forward*100)") self:appendToResult("") self:appendMathToResult("V(a(r))=2*1/1.05^0.25+(5.6/1.054^0.75+5.91/1.056^1.25)=") self:appendToResult(" \n") self:appendToResult("donc valeur du ") self:appendMathToResult("swap=V(a(k))-V(a(r))") self:appendToResult("\n") self:appendToResult("M"..e_acute.."thode d"..e_acute.."mant"..e_grave.."lement:\n") self:appendToResult("") self:appendMathToResult("V(A(k))=6*(1/1.05^0.25+1/1.056^1.25)+100/1.056^1.25=105.3") self:appendToResult(" et ") self:appendMathToResult("V(A(r))=102/1.05^0.25=100.76") self:appendToResult(" \n") self:appendToResult("") self:appendMathToResult("Vswap=V(A(k))-V(A(r))") self:appendToResult("\n") return end end
apache-2.0
opentechinstitute/luci
libs/nixio/docsrc/nixio.TLSSocket.lua
173
2926
--- TLS Socket Object. -- TLS Sockets contain the underlying socket and context in the fields -- "socket" and "context". -- @cstyle instance module "nixio.TLSSocket" --- Initiate the TLS handshake as client with the server. -- @class function -- @name TLSSocket.connect -- @usage This function calls SSL_connect(). -- @usage You have to call either connect or accept before transmitting data. -- @see TLSSocket.accept -- @return true --- Wait for a TLS handshake from a client. -- @class function -- @name TLSSocket.accept -- @usage This function calls SSL_accept(). -- @usage You have to call either connect or accept before transmitting data. -- @see TLSSocket.connect -- @return true --- Send a message to the socket. -- @class function -- @name TLSSocket.send -- @usage This function calls SSL_write(). -- @usage <strong>Warning:</strong> It is not guaranteed that all data -- in the buffer is written at once. -- You have to check the return value - the number of bytes actually written - -- or use the safe IO functions in the high-level IO utility module. -- @usage Unlike standard Lua indexing the lowest offset and default is 0. -- @param buffer Buffer holding the data to be written. -- @param offset Offset to start reading the buffer from. (optional) -- @param length Length of chunk to read from the buffer. (optional) -- @return number of bytes written --- Send a message on the socket (This is an alias for send). -- See the send description for a detailed description. -- @class function -- @name TLSSocket.write -- @param buffer Buffer holding the data to be written. -- @param offset Offset to start reading the buffer from. (optional) -- @param length Length of chunk to read from the buffer. (optional) -- @see TLSSocket.send -- @return number of bytes written --- Receive a message on the socket. -- @class function -- @name TLSSocket.recv -- @usage This function calls SSL_read(). -- @usage <strong>Warning:</strong> It is not guaranteed that all requested data -- is read at once. -- You have to check the return value - the length of the buffer actually read - -- or use the safe IO functions in the high-level IO utility module. -- @usage The length of the return buffer is limited by the (compile time) -- nixio buffersize which is <em>nixio.const.buffersize</em> (8192 by default). -- Any read request greater than that will be safely truncated to this value. -- @param length Amount of data to read (in Bytes). -- @return buffer containing data successfully read --- Receive a message on the socket (This is an alias for recv). -- See the recv description for more details. -- @class function -- @name TLSSocket.read -- @param length Amount of data to read (in Bytes). -- @see TLSSocket.recv -- @return buffer containing data successfully read --- Shut down the TLS connection. -- @class function -- @name TLSSocket.shutdown -- @usage This function calls SSL_shutdown(). -- @return true
apache-2.0
HEYAHONG/nodemcu-firmware
lua_examples/irsend.lua
7
1852
------------------------------------------------------------------------------ -- IR send module -- -- LICENCE: http://opensource.org/licenses/MIT -- Vladimir Dronnikov <dronnikov@gmail.com> -- -- Example: -- dofile("irsend.lua").nec(4, 0x00ff00ff) ------------------------------------------------------------------------------ local M do -- const -- luacheck: push no unused local NEC_PULSE_US = 1000000 / 38000 local NEC_HDR_MARK = 9000 local NEC_HDR_SPACE = 4500 local NEC_BIT_MARK = 560 local NEC_ONE_SPACE = 1600 local NEC_ZERO_SPACE = 560 local NEC_RPT_SPACE = 2250 -- luacheck: pop -- cache local gpio, bit = gpio, bit local mode, write = gpio.mode, gpio.write local waitus = tmr.delay local isset = bit.isset -- NB: poorman 38kHz PWM with 1/3 duty. Touch with care! ) local carrier = function(pin, c) c = c / NEC_PULSE_US while c > 0 do write(pin, 1) write(pin, 0) c = c + 0 c = c + 0 c = c + 0 c = c + 0 c = c + 0 c = c + 0 c = c * 1 c = c * 1 c = c * 1 c = c - 1 end end -- tsop signal simulator local pull = function(pin, c) write(pin, 0) waitus(c) write(pin, 1) end -- NB: tsop mode allows to directly connect pin -- inplace of TSOP input local nec = function(pin, code, tsop) local pulse = tsop and pull or carrier -- setup transmitter mode(pin, 1) write(pin, tsop and 1 or 0) -- header pulse(pin, NEC_HDR_MARK) waitus(NEC_HDR_SPACE) -- sequence, lsb first for i = 31, 0, -1 do pulse(pin, NEC_BIT_MARK) waitus(isset(code, i) and NEC_ONE_SPACE or NEC_ZERO_SPACE) end -- trailer pulse(pin, NEC_BIT_MARK) -- done transmitter --mode(pin, 0, tsop and 1 or 0) end -- expose M = { nec = nec, } end return M
mit
mattico/planets
quickie/init.lua
17
1815
--[[ Copyright (c) 2012 Matthias Richter 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. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local BASE = (...) .. '.' assert(not BASE:match('%.init%.$'), "Invalid require path `"..(...).."' (drop the `.init').") return { core = require(BASE .. 'core'), group = require(BASE .. 'group'), mouse = require(BASE .. 'mouse'), keyboard = require(BASE .. 'keyboard'), Button = require(BASE .. 'button'), Slider = require(BASE .. 'slider'), Slider2D = require(BASE .. 'slider2d'), Label = require(BASE .. 'label'), Input = require(BASE .. 'input'), Checkbox = require(BASE .. 'checkbox') }
mit
JarnoVgr/Mr.Green-MTA-Resources
resources/[gameplay]/-shaders-contrast/c_contrast.lua
4
10222
-- -- c_contrast.lua -- bEffectEnabled = false Settings = {} Settings.var = {} -------------------------------- -- Switch effect on -------------------------------- function enableContrast() if bEffectEnabled then return end -- Version check if getVersion ().sortable < "1.1.0" then outputChatBox( "Resource is not compatible with this client." ) return end -- Input texture myScreenSourceFull = dxCreateScreenSource( scx, scy ) -- Shaders contrastShader = dxCreateShader( "fx/contrast.fx" ) bloomCombineShader = dxCreateShader( "fx/bloom_combine.fx" ) bloomExtractShader = dxCreateShader( "fx/bloom_extract.fx" ) blurHShader = dxCreateShader( "fx/blurH.fx" ) blurVShader = dxCreateShader( "fx/blurV.fx" ) modulationShader = dxCreateShader( "fx/modulation.fx" ) -- 1 pixel render target to store the result of scene luminance calculations lumTarget = dxCreateRenderTarget( 1, 1 ) nextLumSampleTime = 0 -- Overlay texture textureVignette = dxCreateTexture ( "images/vignette1.dds" ); -- Get list of all elements used effectParts = { myScreenSourceFull, contrastShader, bloomCombineShader, bloomExtractShader, blurHShader, blurVShader, modulationShader, lumTarget, textureVignette } -- Check list of all elements used bAllValid = true for _,part in ipairs(effectParts) do bAllValid = part and bAllValid end setEffectType1 () bEffectEnabled = true if not bAllValid then outputChatBox( "Could not create some things" ) disableContrast() end end -------------------------------- -- Switch effect off -------------------------------- function disableContrast() if not bEffectEnabled then return end -- Destroy all shaders for _,part in ipairs(effectParts) do if part then destroyElement( part ) end end effectParts = {} bAllValid = false RTPool.clear() -- Flag effect as stopped bEffectEnabled = false end --------------------------------- -- Settings for effect --------------------------------- function setEffectType1() local v = Settings.var v.Brightness=0.32 v.Contrast=2.24 v.ExtractThreshold=0.72 v.DownSampleSteps=2 v.GBlurHBloom=1.68 v.GBlurVBloom=1.52 v.BloomIntensity=0.94 v.BloomSaturation=1.66 v.BaseIntensity=0.94 v.BaseSaturation=-0.38 v.LumSpeed=51 v.LumChangeAlpha=27 v.MultAmount=0.46 v.Mult=0.70 v.Add=0.10 v.ModExtraFrom=0.11 v.ModExtraTo=0.58 v.ModExtraMult=4 v.MulBlend=0.82 v.BloomBlend=0.25 v.Vignette=0.47 -- Debugging v.PreviewEnable=0 v.PreviewPosY=0 v.PreviewPosX=100 v.PreviewSize=70 end ---------------------------------------------------------------- -- Render ---------------------------------------------------------------- addEventHandler( "onClientHUDRender", root, function() if not bAllValid or not Settings.var then return end -- Bypass effect if left alt and num_7 are held if getKeyState("lalt") and getKeyState("num_7") then return end local v = Settings.var RTPool.frameStart() DebugResults.frameStart() dxUpdateScreenSource( myScreenSourceFull ) -- Get source textures local current1 = myScreenSourceFull local current2 = myScreenSourceFull local sceneLuminance = lumTarget -- Effect path 1 (contrast) current1 = applyModulation( current1, sceneLuminance, v.MultAmount, v.Mult, v.Add, v.ModExtraFrom, v.ModExtraTo, v.ModExtraMult ) current1 = applyContrast( current1, v.Brightness, v.Contrast ) -- Effect path 2 (bloom) current2 = applyBloomExtract( current2, sceneLuminance, v.ExtractThreshold ) current2 = applyDownsampleSteps( current2, v.DownSampleSteps ) current2 = applyGBlurH( current2, v.GBlurHBloom ) current2 = applyGBlurV( current2, v.GBlurVBloom ) current2 = applyBloomCombine( current2, current1, v.BloomIntensity, v.BloomSaturation, v.BaseIntensity, v.BaseSaturation ) -- Update texture used to calculate the scene luminance level updateLumSource( current1, v.LumSpeed, v.LumChangeAlpha ) -- Final output dxSetRenderTarget() dxDrawImage( 0, 0, scx, scy, current1, 0, 0, 0, tocolor(255,255,255,v.MulBlend*255) ) dxDrawImage( 0, 0, scx, scy, current2, 0, 0, 0, tocolor(255,255,255,v.BloomBlend*255) ) -- Draw border texture dxDrawImage( 0, 0, scx, scy, textureVignette, 0, 0, 0, tocolor(255,255,255,v.Vignette*255) ) -- Debug stuff if v.PreviewEnable > 0.5 then DebugResults.drawItems ( v.PreviewSize, v.PreviewPosX, v.PreviewPosY ) end end ) ---------------------------------------------------------------- -- post process items ---------------------------------------------------------------- function applyBloomCombine( src, base, sBloomIntensity, sBloomSaturation, sBaseIntensity, sBaseSaturation ) if not src or not base then return nil end local mx,my = dxGetMaterialSize( base ) local newRT = RTPool.GetUnused(mx,my) if not newRT then return nil end dxSetRenderTarget( newRT, true ) dxSetShaderValue( bloomCombineShader, "sBloomTexture", src ) dxSetShaderValue( bloomCombineShader, "sBaseTexture", base ) dxSetShaderValue( bloomCombineShader, "sBloomIntensity", sBloomIntensity ) dxSetShaderValue( bloomCombineShader, "sBloomSaturation", sBloomSaturation ) dxSetShaderValue( bloomCombineShader, "sBaseIntensity", sBaseIntensity ) dxSetShaderValue( bloomCombineShader, "sBaseSaturation", sBaseSaturation ) dxDrawImage( 0, 0, mx,my, bloomCombineShader ) DebugResults.addItem( newRT, "BloomCombine" ) return newRT end function applyBloomExtract( src, sceneLuminance, sBloomThreshold ) if not src or not sceneLuminance then return nil end local mx,my = dxGetMaterialSize( src ) local newRT = RTPool.GetUnused(mx,my) if not newRT then return nil end dxSetRenderTarget( newRT, true ) dxSetShaderValue( bloomExtractShader, "sBaseTexture", src ) dxSetShaderValue( bloomExtractShader, "sBloomThreshold", sBloomThreshold ) dxSetShaderValue( bloomExtractShader, "sLumTexture", sceneLuminance ) dxDrawImage( 0, 0, mx,my, bloomExtractShader ) DebugResults.addItem( newRT, "BloomExtract" ) return newRT end function applyContrast( src, Brightness, Contrast ) if not src then return nil end local mx,my = dxGetMaterialSize( src ) local newRT = RTPool.GetUnused(mx,my) if not newRT then return nil end dxSetRenderTarget( newRT ) dxSetShaderValue( contrastShader, "sBaseTexture", src ) dxSetShaderValue( contrastShader, "sBrightness", Brightness ) dxSetShaderValue( contrastShader, "sContrast", Contrast ) dxDrawImage( 0, 0, mx, my, contrastShader ) DebugResults.addItem( newRT, "Contrast" ) return newRT end function applyModulation( src, sceneLuminance, MultAmount, Mult, Add, ExtraFrom, ExtraTo, ExtraMult ) if not src or not sceneLuminance then return nil end local mx,my = dxGetMaterialSize( src ) local newRT = RTPool.GetUnused(mx,my) if not newRT then return nil end dxSetRenderTarget( newRT ) dxSetShaderValue( modulationShader, "sBaseTexture", src ) dxSetShaderValue( modulationShader, "sMultAmount", MultAmount ) dxSetShaderValue( modulationShader, "sMult", Mult ) dxSetShaderValue( modulationShader, "sAdd", Add ) dxSetShaderValue( modulationShader, "sLumTexture", sceneLuminance ) dxSetShaderValue( modulationShader, "sExtraFrom", ExtraFrom ) dxSetShaderValue( modulationShader, "sExtraTo", ExtraTo ) dxSetShaderValue( modulationShader, "sExtraMult", ExtraMult ) dxDrawImage( 0, 0, mx, my, modulationShader ) DebugResults.addItem( newRT, "Modulation" ) return newRT end function applyResize( src, tx, ty ) if not src then return nil end local newRT = RTPool.GetUnused(tx, ty) if not newRT then return nil end dxSetRenderTarget( newRT ) dxDrawImage( 0, 0, tx, ty, src ) DebugResults.addItem( newRT, "Resize" ) return newRT end function applyDownsampleSteps( src, steps ) if not src then return nil end for i=1,steps do src = applyDownsample ( src ) end return src end function applyDownsample( src ) if not src then return nil end local mx,my = dxGetMaterialSize( src ) mx = mx / 2 my = my / 2 local newRT = RTPool.GetUnused(mx,my) if not newRT then return nil end dxSetRenderTarget( newRT ) dxDrawImage( 0, 0, mx, my, src ) DebugResults.addItem( newRT, "Downsample" ) return newRT end function applyGBlurH( src, bloom ) if not src then return nil end local mx,my = dxGetMaterialSize( src ) local newRT = RTPool.GetUnused(mx,my) if not newRT then return nil end dxSetRenderTarget( newRT, true ) dxSetShaderValue( blurHShader, "tex0", src ) dxSetShaderValue( blurHShader, "tex0size", mx,my ) dxSetShaderValue( blurHShader, "bloom", bloom ) dxDrawImage( 0, 0, mx,my, blurHShader ) DebugResults.addItem( newRT, "GBlurH" ) return newRT end function applyGBlurV( src, bloom ) if not src then return nil end local mx,my = dxGetMaterialSize( src ) local newRT = RTPool.GetUnused(mx,my) if not newRT then return nil end dxSetRenderTarget( newRT, true ) dxSetShaderValue( blurVShader, "tex0", src ) dxSetShaderValue( blurVShader, "tex0size", mx,my ) dxSetShaderValue( blurVShader, "bloom", bloom ) dxDrawImage( 0, 0, mx,my, blurVShader ) DebugResults.addItem( newRT, "GBlurV" ) return newRT end function updateLumSource( current, changeRate, changeAlpha ) if not current then return nil end changeRate = changeRate or 50 local mx,my = dxGetMaterialSize( current ); local size = 1 while ( size < mx / 2 or size < my / 2 ) do size = size * 2 end current = applyResize( current, size, size ) while ( size > 1 ) do size = size / 2 current = applyDownsample( current, 2 ) end if getTickCount() > nextLumSampleTime then nextLumSampleTime = getTickCount() + changeRate dxSetRenderTarget( lumTarget ) dxDrawImage( 0, 0, 1, 1, current, 0,0,0, tocolor(255,255,255,changeAlpha) ) end current = applyResize( lumTarget, 1, 1 ) return lumTarget end ---------------------------------------------------------------- -- Avoid errors messages when memory is low ---------------------------------------------------------------- _dxDrawImage = dxDrawImage function xdxDrawImage(posX, posY, width, height, image, ... ) if not image then return false end return _dxDrawImage( posX, posY, width, height, image, ... ) end
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/CCBAnimationManager.lua
1
8608
-------------------------------- -- @module CCBAnimationManager -- @extend Ref -- @parent_module cc -------------------------------- -- -- @function [parent=#CCBAnimationManager] moveAnimationsFromNode -- @param self -- @param #cc.Node fromNode -- @param #cc.Node toNode -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getSequence -- @param self -- @param #int nSequenceId -- @return CCBSequence#CCBSequence ret (return value: cc.CCBSequence) -------------------------------- -- -- @function [parent=#CCBAnimationManager] setAutoPlaySequenceId -- @param self -- @param #int autoPlaySequenceId -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getDocumentCallbackNames -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- -- @function [parent=#CCBAnimationManager] actionForSoundChannel -- @param self -- @param #cc.CCBSequenceProperty channel -- @return Sequence#Sequence ret (return value: cc.Sequence) -------------------------------- -- -- @function [parent=#CCBAnimationManager] setBaseValue -- @param self -- @param #cc.Value value -- @param #cc.Node pNode -- @param #string propName -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getDocumentOutletNodes -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getLastCompletedSequenceName -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#CCBAnimationManager] setRootNode -- @param self -- @param #cc.Node pRootNode -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] runAnimationsForSequenceNamedTweenDuration -- @param self -- @param #char pName -- @param #float fTweenDuration -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] addDocumentOutletName -- @param self -- @param #string name -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getSequences -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getRootContainerSize -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- -- @function [parent=#CCBAnimationManager] setDocumentControllerName -- @param self -- @param #string name -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] setObject -- @param self -- @param #cc.Ref obj -- @param #cc.Node pNode -- @param #string propName -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getContainerSize -- @param self -- @param #cc.Node pNode -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- -- @function [parent=#CCBAnimationManager] actionForCallbackChannel -- @param self -- @param #cc.CCBSequenceProperty channel -- @return Sequence#Sequence ret (return value: cc.Sequence) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getDocumentOutletNames -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- -- @function [parent=#CCBAnimationManager] addDocumentCallbackControlEvents -- @param self -- @param #int eventType -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getKeyframeCallbacks -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getDocumentCallbackControlEvents -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- -- @function [parent=#CCBAnimationManager] setRootContainerSize -- @param self -- @param #size_table rootContainerSize -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] runAnimationsForSequenceIdTweenDuration -- @param self -- @param #int nSeqId -- @param #float fTweenDuraiton -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getRunningSequenceName -- @param self -- @return char#char ret (return value: char) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getAutoPlaySequenceId -- @param self -- @return int#int ret (return value: int) -------------------------------- -- -- @function [parent=#CCBAnimationManager] addDocumentCallbackName -- @param self -- @param #string name -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getRootNode -- @param self -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- -- @function [parent=#CCBAnimationManager] addDocumentOutletNode -- @param self -- @param #cc.Node node -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getSequenceDuration -- @param self -- @param #char pSequenceName -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#CCBAnimationManager] addDocumentCallbackNode -- @param self -- @param #cc.Node node -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] runAnimationsForSequenceNamed -- @param self -- @param #char pName -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getSequenceId -- @param self -- @param #char pSequenceName -- @return int#int ret (return value: int) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getDocumentCallbackNodes -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- -- @function [parent=#CCBAnimationManager] setSequences -- @param self -- @param #array_table seq -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] debug -- @param self -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) -------------------------------- -- -- @function [parent=#CCBAnimationManager] getDocumentControllerName -- @param self -- @return string#string ret (return value: string) -------------------------------- -- js ctor -- @function [parent=#CCBAnimationManager] CCBAnimationManager -- @param self -- @return CCBAnimationManager#CCBAnimationManager self (return value: cc.CCBAnimationManager) return nil
mit
durandtibo/wsl.resnet.torch
opts.lua
1
5417
local M = { } function M.parse(arg) local cmd = torch.CmdLine() cmd:text() cmd:text('Torch-7 - Training script') cmd:text() cmd:text('Options:') ------------ General options -------------------- cmd:option('-data', '', 'Path to dataset') cmd:option('-dataset', 'voc2007-cls', 'Options: voc2007-cls') cmd:option('-manualSeed', 2, 'Manually set RNG seed') cmd:option('-backend', 'cudnn', 'Options: cudnn | cunn | nn') cmd:option('-cudnn', 'default', 'Options: fastest | default | deterministic') cmd:option('-gen', 'gen', 'Path to save generated files') cmd:option('-verbose', 'false', 'verbose') cmd:option('-save', 'true', 'save model at each epoch') ------------- Data options ------------------------ cmd:option('-nThreads', 1, 'number of data loading threads') cmd:option('-nGPU', 1, 'Number of GPUs to use by default') ------------- Training options -------------------- cmd:option('-nEpochs', 0, 'Number of total epochs to run') cmd:option('-epochNumber', 1, 'Manual epoch number (useful on restarts)') cmd:option('-batchSize', 32, 'mini-batch size (1 = pure stochastic)') cmd:option('-imageSize', 224, 'image size') cmd:option('-testOnly', 'false', 'Run on test set only') cmd:option('-trainOnly', 'false', 'No test') ------------- Checkpointing options --------------- cmd:option('-save', 'checkpoints', 'Directory in which to save checkpoints') cmd:option('-resume', 'none', 'Resume from the latest checkpoint in this directory') ---------- Optimization options ---------------------- cmd:option('-optim', 'sgd', 'optimization algorithm') cmd:option('-LR', 0.001, 'initial learning rate') cmd:option('-LRp', 1, 'learning rate for pretrained layers') cmd:option('-momentum', 0.9, 'momentum') cmd:option('-weightDecay', 1e-4, 'weight decay') ---------- Model options ---------------------------------- cmd:option('-netType', 'resnet', 'Options: resnet | preresnet') cmd:option('-netInit', '', 'Path to inital model') cmd:option('-depth', 34, 'ResNet depth: 18 | 34 | 50 | 101 | ...', 'number') cmd:option('-shortcutType', '', 'Options: A | B | C') cmd:option('-retrain', 'none', 'Path to model to retrain with') cmd:option('-optimState', 'none', 'Path to an optimState to reload from') cmd:option('-loss', 'CrossEntropy', 'loss') ---------- Model options ---------------------------------- cmd:option('-shareGradInput', 'false', 'Share gradInput tensors to reduce memory usage') cmd:option('-optnet', 'false', 'Use optnet to reduce memory usage') cmd:option('-resetClassifier', 'false', 'Reset the fully connected layer for fine-tuning') cmd:option('-nClasses', 0, 'Number of classes in the dataset') ---------- My options ---------------------------------- cmd:option('-preprocessing', 'warp', 'image preprocessing') cmd:option('-results', '', 'path to write results') cmd:option('-localization', 'false', 'path to write results') cmd:option('-train', 'multiclass', 'train with [multiclass | multilabel]') cmd:option('-k', 1, 'number of regions in weldon model') cmd:option('-alpha', 1.0, 'alpha') cmd:option('-features', '', 'save features') cmd:text() local opt = cmd:parse(arg or {}) opt.verbose = opt.verbose ~= 'false' opt.resetClassifier = opt.resetClassifier ~= 'false' opt.trainOnly = opt.trainOnly ~= 'false' opt.testOnly = opt.testOnly ~= 'false' opt.optnet = opt.optnet ~= 'false' opt.shareGradInput = opt.shareGradInput ~= 'false' opt.localization = opt.localization ~= 'false' opt.nEpochs = opt.nEpochs == 0 and 90 or opt.nEpochs if opt.dataset == 'imagenet' or opt.dataset == 'imagenet2' then -- Handle the most common case of missing -data flag local trainDir = paths.concat(opt.data, 'train') if not paths.dirp(opt.data) then cmd:error('error: missing ImageNet data directory') elseif not paths.dirp(trainDir) then cmd:error('error: ImageNet missing `train` directory: ' .. trainDir) end -- Default shortcutType=B and nEpochs=90 opt.shortcutType = opt.shortcutType == '' and 'B' or opt.shortcutType opt.nEpochs = opt.nEpochs == 0 and 90 or opt.nEpochs end if opt.backend == 'nn' then opt.nGPU = 0 end if not paths.dirp(opt.save) and not paths.mkdir(opt.save) then cmd:error('error: unable to create checkpoint directory: ' .. opt.save .. '\n') end if opt.resetClassifier then if opt.nClasses == 0 then cmd:error('-nClasses required when resetClassifier is set') end end if opt.shareGradInput and opt.optnet then cmd:error('error: cannot use both -shareGradInput and -optnet') end opt.pathResults = '' return opt end return M
mit
vipteam1/VIP_TEAM_EN11
libs/XMLElement.lua
569
4025
-- Copyright 2009 Leo Ponomarev. Distributed under the BSD Licence. -- updated for module-free world of lua 5.3 on April 2 2015 -- Not documented at all, but not interesting enough to warrant documentation anyway. local setmetatable, pairs, ipairs, type, getmetatable, tostring, error = setmetatable, pairs, ipairs, type, getmetatable, tostring, error local table, string = table, string local XMLElement={} local mt XMLElement.new = function(lom) return setmetatable({lom=lom or {}}, mt) end local function filter(filtery_thing, lom) filtery_thing=filtery_thing or '*' for i, thing in ipairs(type(filtery_thing)=='table' and filtery_thing or {filtery_thing}) do if thing == "text()" then if type(lom)=='string' then return true end elseif thing == '*' then if type(lom)=='table' then return true end else if type(lom)=='table' and string.lower(lom.tag)==string.lower(thing) then return true end end end return nil end mt ={ __index = { getAttr = function(self, attribute) if type(attribute) ~= "string" then return nil, "attribute name must be a string." end return self.lom.attr[attribute] end, setAttr = function(self, attribute, value) if type(attribute) ~= "string" then return nil, "attribute name must be a string." end if value == nil then return self:removeAttr(attribute) end self.lom.attr[attribute]=tostring(value) return self end, removeAttr = function(self, attribute) local lom = self.lom if type(attribute) ~= "string" then return nil, "attribute name must be a string." end if not lom.attr[attribute] then return self end for i,v in ipairs(lom.attr) do if v == attribute then table.remove(lom.attr, i) break end end lom.attr[attribute]=nil end, removeAllAttributes = function(self) local attr = self.lom.attr for i, v in pairs(self.lom.attr) do attr[i]=nil end return self end, getAttributes = function(self) local attr = {} for i, v in ipairs(self.lom.attr) do table.insert(attr,v) end return attr end, getXML = function(self) local function getXML(lom) local attr, inner = {}, {} for i, attribute in ipairs(lom.attr) do table.insert(attr, string.format('%s=%q', attribute, lom.attr[attribute])) end for i, v in ipairs(lom) do local t = type(v) if t == "string" then table.insert(inner, v) elseif t == "table" then table.insert(inner, getXML(v)) else error("oh shit") end end local tagcontents = table.concat(inner) local attrstring = #attr>0 and (" " .. table.concat(attr, " ")) or "" if #tagcontents>0 then return string.format("<%s%s>%s</%s>", lom.tag, attrstring, tagcontents, lom.tag) else return string.format("<%s%s />", lom.tag, attrstring) end end return getXML(self.lom) end, getText = function(self) local function getText(lom) local inner = {} for i, v in ipairs(lom) do local t = type(v) if t == "string" then table.insert(inner, v) elseif t == "table" then table.insert(inner, getText(v)) end end return table.concat(inner) end return getText(self.lom) end, getChildren = function(self, filter_thing) local res = {} for i, node in ipairs(self.lom) do if filter(filter_thing, node) then table.insert(res, type(node)=='table' and XMLElement.new(node) or node) end end return res end, getDescendants = function(self, filter_thing) local res = {} local function descendants(lom) for i, child in ipairs(lom) do if filter(filter_thing, child) then table.insert(res, type(child)=='table' and XMLElement.new(child) or child) if type(child)=='table' then descendants(child) end end end end descendants(self.lom) return res end, getChild = function(self, filter_thing) for i, node in ipairs(self.lom) do if filter(filter_thing, node) then return type(node)=='table' and XMLElement.new(node) or node end end end, getTag = function(self) return self.lom.tag end }} return XMLElement
gpl-2.0
wartman4404/everybody-draw
src/test/unibrushes/fail-lua-runtime/neko.lua
1
7224
local kStop = 0 -- Jare is cleaning. local kJare = 1 local kKaki = 2 -- Kaki is scratching the ear. local kAkubi = 3 -- Akubi is yawning. local kSleep = 4 local kAwake = 5 local kMoveUp = 6 local kMoveDown = 7 local kMoveLeft = 8 local kMoveRight = 9 local kMoveUpLeft = 10 local kMoveUpRight = 11 local kMoveDownLeft = 12 local kMoveDownRight = 13 -- Togi is scratching the borders. local kTogiUp = 14 local kTogiDown = 15 local kTogiLeft = 16 local kTogiRight = 17 local kSpeed = 16 -- Originally 16 local mHalfImage = 16 local kSinEighthPIM = 383 -- sin(pi/8) * 1000 local kSinThreeEighthsPIM = 924 -- sin(pi * 3/8) * 1000 local mNeko = {x = 200, y = 200, mTickCount = 0, mStateCount = 0, mState = 0} local mMickey = {x = 200, y = 200} local mStateNames = { [0] = "kStop", -- 0; -- Jare is cleaning. "kJare", -- 1; -- Kaki is scratching the ear. "kKaki", -- 2; -- Akubi is yawning. "kAkubi", -- 3; "kSleep", -- 4; "kAwake", -- 5; "kMoveUp", -- 6; "kMoveDown", -- 7 "kMoveLeft", -- 8 "kMoveRight", -- 9 "kMoveUpLeft", -- 10 "kMoveUpRight", -- 11 "kMoveDownLeft", -- 12 "kMoveDownRight", -- 13 -- Togi is scratching the borders. "kTogiUp", -- 14 "kTogiDown", -- 15 "kTogiLeft", -- 16 "kTogiRight" -- 17; } local kImageIndexes = { [0] = 0, 1, 2, 4, 5, 7, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 } local kStateCountLimits = { [0] = 4, 10, 4, 3, 0, 3, 0, 0, 0, 0, -- Moves 0, 0, 0, 0, -- Diagonal moves 10, 10, 10, 10 -- Togis } function calculateDeltas(neko, mickey) local deltaX = mickey.x - neko.x local deltaY = mickey.y - neko.y local lengthSquared = deltaX * deltaX + deltaY * deltaY if (lengthSquared == 0) then return 0, 0 else local length = math.sqrt(lengthSquared) if (length <= kSpeed) then return deltaX, deltaY else local mMoveDeltaX = math.floor((kSpeed * deltaX) / length) local mMoveDeltaY = math.floor((kSpeed * deltaY) / length) return mMoveDeltaX, mMoveDeltaY end end end function direction(neko, mMoveDeltaX, mMoveDeltaY) local newState if (mMoveDeltaX == 0 and mMoveDeltaY == 0) then newState = kStop else local length = math.floor(math.sqrt( mMoveDeltaX * mMoveDeltaX + mMoveDeltaY * mMoveDeltaY)) local sinThetaM = math.floor(-(mMoveDeltaY * 1000) / length) if (mMoveDeltaX >= 0) then if (sinThetaM > kSinThreeEighthsPIM) then newState = kMoveUp elseif (sinThetaM <= kSinThreeEighthsPIM and sinThetaM > kSinEighthPIM) then newState = kMoveUpRight elseif (sinThetaM <= kSinEighthPIM and sinThetaM > -kSinEighthPIM) then newState = kMoveRight elseif (sinThetaM <= -kSinEighthPIM and sinThetaM > -kSinThreeEighthsPIM) then newState = kMoveDownRight else newState = kMoveDown end else if (sinThetaM > kSinThreeEighthsPIM) then newState = kMoveUp elseif (sinThetaM <= kSinThreeEighthsPIM and sinThetaM > kSinEighthPIM) then newState = kMoveUpLeft elseif (sinThetaM <= kSinEighthPIM and sinThetaM > -kSinEighthPIM) then newState = kMoveLeft elseif (sinThetaM <= -kSinEighthPIM and sinThetaM > -kSinThreeEighthsPIM) then newState = kMoveDownLeft else newState = kMoveDown end end end if not (newState == neko.mState) then setState(neko, newState) end end function setState(neko, state) loglua("setting state to " .. mStateNames[state]) neko.mTickCount = 0 neko.mStateCount = 0 neko.mState = state end function bound() return false end function getImageIndex(mState, mTickCount) local index = kImageIndexes[mState] if (mState == kJare) then return index - (mTickCount % 2) elseif not (mState == kStop or mState == kAkubi or mState == kAwake) then return index + mTickCount % 2 end return index end function think(neko, mickey, mWidth, mHeight) neko.mTickCount = neko.mTickCount + 1 if (neko.mTickCount % 2 == 0) then neko.mStateCount = neko.mStateCount + 1 end local mMoveDeltaX, mMoveDeltaY = calculateDeltas(neko, mickey) local mState = neko.mState if mState == kStop then if not (mMoveDeltaX == 0 and mMoveDeltaY == 0) then setState(neko, kAwake) elseif (neko.mStateCount < kStateCountLimits[mState]) then -- will it parse?? else if (--[[mMoveDeltaX < 0 and ]] neko.x <= mHalfImage) then setState(neko, kTogiLeft) elseif (--[[mMoveDeltaX > 0 and ]] neko.x >= (mWidth - 1 - mHalfImage)) then setState(neko, kTogiRight) elseif (--[[mMoveDeltaY < 0 and ]] neko.y <= mHalfImage) then setState(neko, kTogiUp) elseif (--[[mMoveDeltaY > 0 and ]] neko.y >= (mHeight - 1 - mHalfImage)) then setState(neko, kTogiDown) else setState(neko, kJare) end end elseif mState == kJare then if not (mMoveDeltaX == 0 and mMoveDeltaY == 0) then setState(neko, kAwake) elseif (neko.mStateCount >= kStateCountLimits[mState]) then setState(neko, kKaki) end elseif mState == kKaki then if not (mMoveDeltaX == 0 and mMoveDeltaY == 0) then setState(neko, kAwake) elseif (neko.mStateCount >= kStateCountLimits[mState]) then setState(neko, kAkubi) end elseif mState == kAkubi then if not (mMoveDeltaX == 0 and mMoveDeltaY == 0) then setState(neko, kAwake) elseif (neko.mStateCount >= kStateCountLimits[mState]) then setState(neko, kSleep) end elseif mState == kSleep then if not (mMoveDeltaX == 0 and mMoveDeltaY == 0) then setState(neko, kAwake) end elseif mState == kAwake then if (neko.mStateCount >= kStateCountLimits[mState]) then direction(neko, mMoveDeltaX, mMoveDeltaY) end elseif mState == kMoveUp or mState == kMoveDown or mState == kMoveUp or mState == kMoveDown or mState == kMoveLeft or mState == kMoveRight or mState == kMoveUpLeft or mState == kMoveUpRight or mState == kMoveDownLeft or mState == kMoveDownRight then neko.x = neko.x + mMoveDeltaX neko.y = neko.y + mMoveDeltaY direction(neko, mMoveDeltaX, mMoveDeltaY) if (bound()) then setState(neko, kStop) end elseif mState == kTogiUp or mState == kTogiDown or mState == kTogiLeft or mState == kTogiRight then if not (mMoveDeltaX == 0 and mMoveDeltaY == 0) then setState(neko, kAwake) elseif (neko.mStateCount >= kStateCountLimits[mState]) then setState(neko, kKaki) end end local imgIndex = getImageIndex(neko.mState, neko.mTickCount) return neko.x, neko.y, imgIndex end function onframe(x, y, points) fail_at_runtime() local nekoX, nekoY, imgIndex = think(mNeko, mMickey, x, y) local imgX = imgIndex % 4 local imgY = math.floor(imgIndex / 4) local nekopoint = ShaderPaintPoint(nekoX, nekoY, 0, 0, imgX / 4, imgY / 9, 0, 0) local mickeypoint = ShaderPaintPoint(mMickey.x, mMickey.y, 0, 0, 3/4, 8/9, 0, 0) --loglua("neko is at " .. mNeko.x .. ", " .. mNeko.y .. "; state: " .. mStateNames[mNeko.mState]) clearlayer(points, 1) pushpoint(points, 1, mickeypoint) pushpoint(points, 1, nekopoint) end function main(a, b, x, y, points) mMickey.x = a.x mMickey.y = a.y end function onup(pointer, output) -- don't copy neko down end
apache-2.0
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/EaseBounceInOut.lua
9
1317
-------------------------------- -- @module EaseBounceInOut -- @extend EaseBounce -- @parent_module cc -------------------------------- -- brief Create the action with the inner action.<br> -- param action The pointer of the inner action.<br> -- return A pointer of EaseBounceInOut action. If creation failed, return nil. -- @function [parent=#EaseBounceInOut] create -- @param self -- @param #cc.ActionInterval action -- @return EaseBounceInOut#EaseBounceInOut ret (return value: cc.EaseBounceInOut) -------------------------------- -- -- @function [parent=#EaseBounceInOut] clone -- @param self -- @return EaseBounceInOut#EaseBounceInOut ret (return value: cc.EaseBounceInOut) -------------------------------- -- -- @function [parent=#EaseBounceInOut] update -- @param self -- @param #float time -- @return EaseBounceInOut#EaseBounceInOut self (return value: cc.EaseBounceInOut) -------------------------------- -- -- @function [parent=#EaseBounceInOut] reverse -- @param self -- @return EaseBounceInOut#EaseBounceInOut ret (return value: cc.EaseBounceInOut) -------------------------------- -- -- @function [parent=#EaseBounceInOut] EaseBounceInOut -- @param self -- @return EaseBounceInOut#EaseBounceInOut self (return value: cc.EaseBounceInOut) return nil
mit
pratik2709/RayCasting-Engine
game/minimap.lua
1
1095
function drawMiniMap() for y = 0, mapHeight-1, 1 do for x = 0, mapWidth-1, 1 do local wall = map[y][x] if wall > 0 then local xs = x * miniMapScale local ys = y * miniMapScale love.graphics.setColor(153, 0, 0) love.graphics.rectangle( "fill", xs, ys, miniMapScale, miniMapScale ) end end end end function updateMiniMap() love.graphics.setColor(255, 255, 255) love.graphics.line(player.x * miniMapScale, player.y * miniMapScale, (player.x + math.cos(player.rot) * 4) * miniMapScale, (player.y + math.sin(player.rot) * 4) * miniMapScale) end -- todo: check if width comes first or height and fix floor map function drawFloorMiniMap() local wall for x=0,mapWidth-1, 1 do for y=0,mapHeight-1, 1 do wall=celda(x,y) if (wall > 0) then love.graphics.setColor( wall,wall,wall) love.graphics.rectangle( "fill", x * miniMapScale, y * miniMapScale, miniMapScale,miniMapScale ) end end end end
mit
sumefsp/zile
lib/zz/commands/macro.lua
1
2447
-- Macro facility commands. -- -- Copyright (c) 2010-2014 Free Software Foundation, Inc. -- -- This file is part of GNU Zile. -- -- 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, 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 <htt://www.gnu.org/licenses/>. local eval = require "zz.eval" local Defun = eval.Defun Defun ("start_kbd_macro", [[ Record subsequent keyboard input, defining a keyboard macro. The commands are recorded even as they are executed. Use @kbd{C-x )} to finish recording and make the macro available. ]], true, function () if thisflag.defining_macro then minibuf_error ('Already defining a keyboard macro') return false end if cur_mp ~= nil then cancel_kbd_macro () end minibuf_write ('Defining keyboard macro...') thisflag.defining_macro = true cur_mp = {} end ) Defun ("end_kbd_macro", [[ Finish defining a keyboard macro. The definition was started by @kbd{C-x (}. The macro is now available for use via @kbd{C-x e}. ]], true, function () if not thisflag.defining_macro then minibuf_error ('Not defining a keyboard macro') return false end thisflag.defining_macro = false end ) Defun ("call_last_kbd_macro", [[ Call the last keyboard macro that you defined with @kbd{C-x (}. A prefix argument serves as a repeat count. ]], true, function () if cur_mp == nil then minibuf_error ('No kbd macro has been defined') return false end -- FIXME: Call execute_kbd_macro (needs a way to reverse keystrtovec) macro_keys = cur_mp execute_with_uniarg (true, current_prefix_arg, call_macro) end ) Defun ("execute_kbd_macro", [[ Execute macro as string of editor command characters. ]], false, function (keystr) local keys = keystrtovec (keystr) if keys ~= nil then macro_keys = keys execute_with_uniarg (true, current_prefix_arg, call_macro) return true end end )
gpl-3.0
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/tests/lua-tests/src/ExtensionTest/ExtensionTest.lua
2
48384
require "ExtensionTest/CocosBuilderTest" require "ExtensionTest/WebProxyTest" local LINE_SPACE = 40 local kItemTagBasic = 1000 local ExtensionTestEnum = { TEST_NOTIFICATIONCENTER = 0, TEST_CCCONTROLBUTTON = 1, TEST_COCOSBUILDER = 2, TEST_WEBSOCKET = 3, TEST_EDITBOX = 4, TEST_TABLEVIEW = 5, TEST_SCROLLVIEW = 6, TEST_MAX_COUNT = 7, } local testsName = { "NotificationCenterTest", "CCControlButtonTest", "CocosBuilderTest", "WebSocketTest", "EditBoxTest", "TableViewTest", "ScrollViewTest", } --Create toMainLayr MenuItem function CreateExtensionsBasicLayerMenu(pMenu) if nil == pMenu then return end local function toMainLayer() local pScene = ExtensionsTestMain() if pScene ~= nil then cc.Director:getInstance():replaceScene(pScene) end end --Create BackMneu cc.MenuItemFont:setFontName("Arial") cc.MenuItemFont:setFontSize(24) local pMenuItemFont = cc.MenuItemFont:create("Back") pMenuItemFont:setPosition(cc.p(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25)) pMenuItemFont:registerScriptTapHandler(toMainLayer) pMenu:addChild(pMenuItemFont) end ------------------------------------- --Notification Center Test ------------------------------------- local NotificationCenterParam = { kTagLight = 100, kTagConnect = 200, MSG_SWITCH_STATE = "SwitchState" } local function runNotificationCenterTest() local pNewScene = cc.Scene:create() local pNewLayer = cc.Layer:create() local function BaseInitSceneLayer(pLayer) if nil == pLayer then return end local s = cc.Director:getInstance():getWinSize() local function toggleSwitch(tag,menuItem) local toggleItem = menuItem local nIndex = toggleItem:getSelectedIndex() local selectedItem = toggleItem:getSelectedItem() if 0 == nIndex then selectedItem = nil end cc.NotificationCenter:getInstance():postNotification(NotificationCenterParam.MSG_SWITCH_STATE,selectedItem) end local switchlabel1 = cc.Label:createWithSystemFont("switch off", "Marker Felt", 26) local switchlabel2 = cc.Label:createWithSystemFont("switch on", "Marker Felt", 26) local switchitem1 = cc.MenuItemLabel:create(switchlabel1) local switchitem2 = cc.MenuItemLabel:create(switchlabel2) local switchitem = cc.MenuItemToggle:create(switchitem1) switchitem:addSubItem(switchitem2) switchitem:registerScriptTapHandler(toggleSwitch) --turn on switchitem:setSelectedIndex(1) local menu = cc.Menu:create() menu:addChild(switchitem) menu:setPosition(cc.p(s.width/2+100, s.height/2)) pLayer:addChild(menu) local menuConnect = cc.Menu:create() menuConnect:setPosition(cc.p(0,0)) pLayer:addChild(menuConnect) local i = 1 local bSwitchOn = false local bConnectArray = { false, false, false } local lightArray = {} local function updateLightState() for i = 1, 3 do if bSwitchOn and bConnectArray[i] then lightArray[i]:setOpacity(255) else lightArray[i]:setOpacity(50) end end end local function switchStateChanged() local nIndex = switchitem:getSelectedIndex() if 0 == nIndex then bSwitchOn = false else bSwitchOn = true end updateLightState() end local function setIsConnectToSwitch(pLight,bConnect,nIdx) bConnectArray[nIdx] = bConnect if bConnect then cc.NotificationCenter:getInstance():registerScriptObserver(pLight, switchStateChanged,NotificationCenterParam.MSG_SWITCH_STATE) else cc.NotificationCenter:getInstance():unregisterScriptObserver(pLight,NotificationCenterParam.MSG_SWITCH_STATE) end updateLightState() end for i = 1, 3 do lightArray[i] = cc.Sprite:create("Images/Pea.png") lightArray[i]:setTag(NotificationCenterParam.kTagLight + i) lightArray[i]:setPosition(cc.p(100, s.height / 4 * i) ) pLayer:addChild(lightArray[i]) local connectlabel1 = cc.Label:createWithSystemFont("not connected", "Marker Felt", 26) local connectlabel2 = cc.Label:createWithSystemFont("connected", "Marker Felt", 26) local connectitem1 = cc.MenuItemLabel:create(connectlabel1) local connectitem2 = cc.MenuItemLabel:create(connectlabel2) local connectitem = cc.MenuItemToggle:create(connectitem1) connectitem:addSubItem(connectitem2) connectitem:setTag(NotificationCenterParam.kTagConnect+i) local function connectToSwitch(tag,menuItem) local connectMenuitem = menuItem local bConnected = true if connectMenuitem:getSelectedIndex() == 0 then bConnected = false end local nIdx = connectMenuitem:getTag()-NotificationCenterParam.kTagConnect setIsConnectToSwitch(lightArray[nIdx],bConnected,nIdx) end connectitem:registerScriptTapHandler(connectToSwitch) local nX,nY = lightArray[i]:getPosition() connectitem:setPosition(cc.p(nX,nY+50)) menuConnect:addChild(connectitem, 0,connectitem:getTag()) if i == 2 then connectitem:setSelectedIndex(1) end bConnectArray[i] = false if 1 == connectitem:getSelectedIndex() then bConnectArray[i] = true end end for i = 1, 3 do setIsConnectToSwitch(lightArray[i],bConnectArray[i],i) end local toggleSelectIndex = switchitem:getSelectedIndex() local toggleSelectedItem = switchitem:getSelectedItem() if 0 == toggleSelectIndex then toggleSelectedItem = nil end cc.NotificationCenter:getInstance():postNotification(NotificationCenterParam.MSG_SWITCH_STATE, toggleSelectedItem) --for testing removeAllObservers */ local function doNothing() end cc.NotificationCenter:getInstance():registerScriptObserver(pNewLayer,doNothing, "random-observer1") cc.NotificationCenter:getInstance():registerScriptObserver(pNewLayer,doNothing, "random-observer2") cc.NotificationCenter:getInstance():registerScriptObserver(pNewLayer,doNothing, "random-observer3") local function CreateToMainMenu(pMenu) if nil == pMenu then return end local function toMainLayer() local numObserversRemoved = cc.NotificationCenter:getInstance():removeAllObservers(pNewLayer) if 3 ~= numObserversRemoved then print("All observers were not removed!") end for i = 1 , 3 do if bConnectArray[i] then cc.NotificationCenter:getInstance():unregisterScriptObserver(lightArray[i],NotificationCenterParam.MSG_SWITCH_STATE) end end local pScene = ExtensionsTestMain() if pScene ~= nil then cc.Director:getInstance():replaceScene(pScene) end end --Create BackMneu cc.MenuItemFont:setFontName("Arial") cc.MenuItemFont:setFontSize(24) local pMenuItemFont = cc.MenuItemFont:create("Back") pMenuItemFont:setPosition(cc.p(VisibleRect:rightBottom().x - 50, VisibleRect:rightBottom().y + 25)) pMenuItemFont:registerScriptTapHandler(toMainLayer) pMenu:addChild(pMenuItemFont) end --Add Menu local pToMainMenu = cc.Menu:create() CreateToMainMenu(pToMainMenu) pToMainMenu:setPosition(cc.p(0, 0)) pLayer:addChild(pToMainMenu,10) end BaseInitSceneLayer(pNewLayer) pNewScene:addChild(pNewLayer) return pNewScene end ------------------------------------- -- Control Extensions Test ------------------------------------- local ControlExtensionsTestEnum = { kCCControlSliderTest = 0, kCCControlColourPickerTest = 1, kCCControlSwitchTest = 2, kCCControlButtonTest_HelloVariableSize = 3, kCCControlButtonTest_Event = 4, kCCControlButtonTest_Styling = 5, kCCControlPotentiometerTest = 6, kCCControlStepperTest = 7, kCCControlTestMax = 8 } local ControlExtensionsTestArray = { "CCControlSliderTest", "ControlColourPickerTest", "ControlSwitchTest", "ControlButtonTest_HelloVariableSize", "ControlButtonTest_Event", "ControlButtonTest_Styling", "ControlPotentiometerTest", "CCControlStepperTest", } local function runCCControlTest() local nMaxCases = ControlExtensionsTestEnum.kCCControlTestMax --kCCControlSliderTest local nCurCase = ControlExtensionsTestEnum.kCCControlSliderTest local pSceneTitleLabel = nil local function GetSceneTitleLabel() return pSceneTitleLabel end local function SetSceneTitleLabel(pLabel) pSceneTitleLabel = pLabel end local function GetControlExtensionsTitle() return ControlExtensionsTestArray[nCurCase + 1] end local pNewScene = cc.Scene:create() local function CreateBasicMenu(pMenu) if nil == pMenu then return end local function backCallback() nCurCase = nCurCase - 1 if nCurCase < 0 then nCurCase = nCurCase + nMaxCases end CurrentControlScene() end local function restartCallback() CurrentControlScene() end local function nextCallback() nCurCase = nCurCase + 1 --No check nMaxCases nCurCase = nCurCase % nMaxCases CurrentControlScene() end local size = cc.Director:getInstance():getWinSize() local item1 = cc.MenuItemImage:create(s_pPathB1, s_pPathB2) item1:registerScriptTapHandler(backCallback) pMenu:addChild(item1,kItemTagBasic) local item2 = cc.MenuItemImage:create(s_pPathR1, s_pPathR2) item2:registerScriptTapHandler(restartCallback) pMenu:addChild(item2,kItemTagBasic) local item3 = cc.MenuItemImage:create(s_pPathF1, s_pPathF2) pMenu:addChild(item3,kItemTagBasic) item3:registerScriptTapHandler(nextCallback) local size = cc.Director:getInstance():getWinSize() item1:setPosition(cc.p(size.width / 2 - item2:getContentSize().width * 2, item2:getContentSize().height / 2)) item2:setPosition(cc.p(size.width / 2, item2:getContentSize().height / 2)) item3:setPosition(cc.p(size.width / 2 + item2:getContentSize().width * 2, item2:getContentSize().height / 2)) end local function BaseInitSceneLayer(pLayer,pStrTitle) if nil == pLayer then return end --Add Menu local pToMainMenu = cc.Menu:create() CreateExtensionsBasicLayerMenu(pToMainMenu) pToMainMenu:setPosition(cc.p(0, 0)) pLayer:addChild(pToMainMenu,10) --Add the generated background local pBackground = cc.Sprite:create("extensions/background.png") pBackground:setPosition(VisibleRect:center()) pLayer:addChild(pBackground) --Add the ribbon local pRibbon = cc.Scale9Sprite:create("extensions/ribbon.png", cc.rect(1, 1, 48, 55)) pRibbon:setContentSize(cc.size(VisibleRect:getVisibleRect().width, 57)) pRibbon:setPosition(cc.p(VisibleRect:center().x, VisibleRect:top().y - pRibbon:getContentSize().height / 2.0)) pLayer:addChild(pRibbon) --Add the title pSceneTitleLabel = cc.Label:createWithSystemFont("Title", "Arial", 12) pSceneTitleLabel:setPosition(cc.p (VisibleRect:center().x, VisibleRect:top().y - pSceneTitleLabel:getContentSize().height / 2 - 5)) pLayer:addChild(pSceneTitleLabel, 1) pSceneTitleLabel:setString(pStrTitle) local pOperateMenu = cc.Menu:create() CreateBasicMenu(pOperateMenu) pOperateMenu:setPosition(cc.p(0, 0)) pLayer:addChild(pOperateMenu,1) end local function InitSliderTest(pLayer) if nil == pLayer then return end local screenSize = cc.Director:getInstance():getWinSize() --Add a label in which the slider value will be displayed local pDisplayValueLabel = cc.Label:createWithSystemFont("Move the slider thumb!\nThe lower slider is restricted." ,"Marker Felt", 32) pDisplayValueLabel:retain() pDisplayValueLabel:setAnchorPoint(cc.p(0.5, -1.0)) pDisplayValueLabel:setPosition(cc.p(screenSize.width / 1.7, screenSize.height / 2.0)) pLayer:addChild(pDisplayValueLabel) local function valueChanged(pSender) if nil == pSender or nil == pDisplayValueLabel then return end local pControl = pSender local strFmt = nil if pControl:getTag() == 1 then strFmt = string.format("Upper slider value = %.02f",pControl:getValue()) elseif pControl:getTag() == 2 then strFmt = string.format("Lower slider value = %.02f",pControl:getValue()) end if nil ~= strFmt then pDisplayValueLabel:setString(strFmt) end end --Add the slider local pSlider = cc.ControlSlider:create("extensions/sliderTrack.png","extensions/sliderProgress.png" ,"extensions/sliderThumb.png") pSlider:setAnchorPoint(cc.p(0.5, 1.0)) pSlider:setMinimumValue(0.0) pSlider:setMaximumValue(5.0) pSlider:setPosition(cc.p(screenSize.width / 2.0, screenSize.height / 2.0 + 16)) pSlider:setTag(1) --When the value of the slider will change, the given selector will be call pSlider:registerControlEventHandler(valueChanged, cc.CONTROL_EVENTTYPE_VALUE_CHANGED) local pRestrictSlider = cc.ControlSlider:create("extensions/sliderTrack.png","extensions/sliderProgress.png" ,"extensions/sliderThumb.png") pRestrictSlider:setAnchorPoint(cc.p(0.5, 1.0)) pRestrictSlider:setMinimumValue(0.0) pRestrictSlider:setMaximumValue(5.0) pRestrictSlider:setMaximumAllowedValue(4.0) pRestrictSlider:setMinimumAllowedValue(1.5) pRestrictSlider:setValue(3.0) pRestrictSlider:setPosition(cc.p(screenSize.width / 2.0, screenSize.height / 2.0 - 24)) pRestrictSlider:setTag(2) --same with restricted pRestrictSlider:registerControlEventHandler(valueChanged, cc.CONTROL_EVENTTYPE_VALUE_CHANGED) pLayer:addChild(pSlider) pLayer:addChild(pRestrictSlider) end --ColourPickerTest local function InitColourPickerTest(pLayer) if nil == pLayer then return end local screenSize = cc.Director:getInstance():getWinSize() local pColorLabel = nil local pNode = cc.Node:create() pNode:setPosition(cc.p (screenSize.width / 2, screenSize.height / 2)) pLayer:addChild(pNode, 1) local dLayer_width = 0 --Create the colour picker,pStrEventName not use local function colourValueChanged(pSender) if nil == pSender or nil == pColorLabel then return end local pPicker = pSender local strFmt = string.format("#%02X%02X%02X",pPicker:getColor().r, pPicker:getColor().g, pPicker:getColor().b) pColorLabel:setString(strFmt) end local pColourPicker = cc.ControlColourPicker:create() pColourPicker:setColor(cc.c3b(37, 46, 252)) pColourPicker:setPosition(cc.p (pColourPicker:getContentSize().width / 2, 0)) pColourPicker:registerControlEventHandler(colourValueChanged, cc.CONTROL_EVENTTYPE_VALUE_CHANGED) pNode:addChild(pColourPicker) dLayer_width = dLayer_width + pColourPicker:getContentSize().width --Add the black background for the text local pBackground = cc.Scale9Sprite:create("extensions/buttonBackground.png") pBackground:setContentSize(cc.size(150, 50)) pBackground:setPosition(cc.p(dLayer_width + pBackground:getContentSize().width / 2.0, 0)) pNode:addChild(pBackground) dLayer_width = dLayer_width + pBackground:getContentSize().width pColorLabel = cc.Label:createWithSystemFont("#color", "Marker Felt", 30) pColorLabel:retain() pColorLabel:setPosition(pBackground:getPosition()) pNode:addChild(pColorLabel) --Set the layer size pNode:setContentSize(cc.size(dLayer_width, 0)) pNode:setAnchorPoint(cc.p (0.5, 0.5)) --Update the color text colourValueChanged(pColourPicker) end --SwitchTest local function InitSwitchTest(pLayer) if nil == pLayer then return end local screenSize = cc.Director:getInstance():getWinSize() local pNode = cc.Node:create() pNode:setPosition(cc.p (screenSize.width / 2, screenSize.height / 2)) pLayer:addChild(pNode, 1) local dLayer_width = 0 --Add the black background for the text local pBackground = cc.Scale9Sprite:create("extensions/buttonBackground.png") pBackground:setContentSize(cc.size(80, 50)) pBackground:setPosition(cc.p(dLayer_width + pBackground:getContentSize().width / 2.0, 0)) pNode:addChild(pBackground) dLayer_width = dLayer_width + pBackground:getContentSize().width local pDisplayValueLabel = cc.Label:createWithSystemFont("#color" ,"Marker Felt" ,30) pDisplayValueLabel:retain() pDisplayValueLabel:setPosition(pBackground:getPosition()) pNode:addChild(pDisplayValueLabel) --Create the switch local function valueChanged(pSender) if nil == pDisplayValueLabel or nil == pSender then return end local pControl = pSender if pControl:isOn() then pDisplayValueLabel:setString("On") else pDisplayValueLabel:setString("Off") end end local pSwitchControl = cc.ControlSwitch:create( cc.Sprite:create("extensions/switch-mask.png"), cc.Sprite:create("extensions/switch-on.png"), cc.Sprite:create("extensions/switch-off.png"), cc.Sprite:create("extensions/switch-thumb.png"), cc.Label:createWithSystemFont("On", "Arial-BoldMT", 16), cc.Label:createWithSystemFont("Off", "Arial-BoldMT", 16) ) pSwitchControl:setPosition(cc.p (dLayer_width + 10 + pSwitchControl:getContentSize().width / 2, 0)) pNode:addChild(pSwitchControl) pSwitchControl:registerControlEventHandler(valueChanged, cc.CONTROL_EVENTTYPE_VALUE_CHANGED) --Set the layer size pNode:setContentSize(cc.size(dLayer_width, 0)) pNode:setAnchorPoint(cc.p (0.5, 0.5)) --Update the value label valueChanged(pSwitchControl) end --Hvs:HelloVariableSize local function HvsStandardButtonWithTitle(pStrTitle) -- Creates and return a button with a default background and title color. local pBackgroundButton = cc.Scale9Sprite:create("extensions/button.png") local pBackgroundHighlightedButton = cc.Scale9Sprite:create("extensions/buttonHighlighted.png") pTitleButton = cc.Label:createWithSystemFont(pStrTitle, "Marker Felt", 30) pTitleButton:setColor(cc.c3b(159, 168, 176)) local pButton = cc.ControlButton:create(pTitleButton, pBackgroundButton) pButton:setBackgroundSpriteForState(pBackgroundHighlightedButton, cc.CONTROL_STATE_HIGH_LIGHTED ) pButton:setTitleColorForState(cc.c3b(255,255,255), cc.CONTROL_STATE_HIGH_LIGHTED ) return pButton end local function InitHelloVariableSize(pLayer) if nil == pLayer then return end local screenSize = cc.Director:getInstance():getWinSize() local strArray = {"Hello", "Variable", "Size", "!"} local pNode = cc.Node:create() pLayer:addChild(pNode,1) local dTotalWidth = 0 local dHeight = 0 local pObj = nil local i = 0 local nLen = table.getn(strArray) for i = 0, nLen - 1 do --Creates a button with pLayer string as title local pButton = HvsStandardButtonWithTitle(strArray[i + 1]) pButton:setPosition(cc.p (dTotalWidth + pButton:getContentSize().width / 2, pButton:getContentSize().height / 2)) pNode:addChild(pButton) --Compute the size of the layer dHeight = pButton:getContentSize().height dTotalWidth = dTotalWidth + pButton:getContentSize().width end pNode:setAnchorPoint(cc.p (0.5, 0.5)) pNode:setContentSize(cc.size(dTotalWidth, dHeight)) pNode:setPosition(cc.p(screenSize.width / 2.0, screenSize.height / 2.0)) --Add the black background local pBackground = cc.Scale9Sprite:create("extensions/buttonBackground.png") pBackground:setContentSize(cc.size(dTotalWidth + 14, dHeight + 14)) pBackground:setPosition(cc.p(screenSize.width / 2.0, screenSize.height / 2.0)) pLayer:addChild(pBackground) end local function StylingStandardButtonWithTitle(pStrTitle) local pBackgroundButton = cc.Scale9Sprite:create("extensions/button.png") pBackgroundButton:setPreferredSize(cc.size(45, 45)) local pBackgroundHighlightedButton = cc.Scale9Sprite:create("extensions/buttonHighlighted.png") pBackgroundHighlightedButton:setPreferredSize(cc.size(45, 45)) local pTitleButton = cc.Label:createWithSystemFont(pStrTitle, "Marker Felt", 30) pTitleButton:setColor(cc.c3b(159, 168, 176)) local pButton = cc.ControlButton:create(pTitleButton, pBackgroundButton,false) pButton:setBackgroundSpriteForState(pBackgroundHighlightedButton, cc.CONTROL_STATE_HIGH_LIGHTED ) pButton:setTitleColorForState(cc.c3b(255,255,255), cc.CONTROL_STATE_HIGH_LIGHTED ) return pButton end local function InitStyling(pLayer) if nil == pLayer then return end local screenSize = cc.Director:getInstance():getWinSize() local pNode = cc.Node:create() pLayer:addChild(pNode, 1) local nSpace = 10 local nMax_w = 0 local nMax_h = 0 local i = 0 local j = 0 for i = 0, 2 do for j = 0, 2 do --Add the buttons local strFmt = string.format("%d",math.random(0,32767) % 30) local pButton = StylingStandardButtonWithTitle(strFmt) pButton:setAdjustBackgroundImage(false) pButton:setPosition(cc.p (pButton:getContentSize().width / 2 + (pButton:getContentSize().width + nSpace) * i, pButton:getContentSize().height / 2 + (pButton:getContentSize().height + nSpace) * j)) pNode:addChild(pButton) nMax_w = math.max(pButton:getContentSize().width * (i + 1) + nSpace * i, nMax_w) nMax_h = math.max(pButton:getContentSize().height * (j + 1) + nSpace * j, nMax_h) end end pNode:setAnchorPoint(cc.p (0.5, 0.5)) pNode:setContentSize(cc.size(nMax_w, nMax_h)) pNode:setPosition(cc.p(screenSize.width / 2.0, screenSize.height / 2.0)) --Add the black background local pBackgroundButton = cc.Scale9Sprite:create("extensions/buttonBackground.png") pBackgroundButton:setContentSize(cc.size(nMax_w + 14, nMax_h + 14)) pBackgroundButton:setPosition(cc.p(screenSize.width / 2.0, screenSize.height / 2.0)) pLayer:addChild(pBackgroundButton) end local function InitButtonTestEvent(pLayer) if nil == pLayer then return end local screenSize = cc.Director:getInstance():getWinSize() --Add a label in which the button events will be displayed local pDisplayValueLabel = nil pDisplayValueLabel = cc.Label:createWithSystemFont("No Event", "Marker Felt", 32) pDisplayValueLabel:setAnchorPoint(cc.p(0.5, -1)) pDisplayValueLabel:setPosition(cc.p(screenSize.width / 2.0, screenSize.height / 2.0)) pLayer:addChild(pDisplayValueLabel, 1) --Add the button local pBackgroundButton = cc.Scale9Sprite:create("extensions/button.png") local pBackgroundHighlightedButton = cc.Scale9Sprite:create("extensions/buttonHighlighted.png") local pTitleButtonLabel = cc.Label:createWithSystemFont("Touch Me!", "Marker Felt", 30) pTitleButtonLabel:setColor(cc.c3b(159, 168, 176)) local pControlButton = cc.ControlButton:create(pTitleButtonLabel, pBackgroundButton) local function touchDownAction() if nil == pDisplayValueLabel then return end pDisplayValueLabel:setString("Touch Down" ) end local function touchDragInsideAction() if nil == pDisplayValueLabel then return end pDisplayValueLabel:setString("Drag Inside") end local function touchDragOutsideAction() if nil == pDisplayValueLabel then return end pDisplayValueLabel:setString("Drag Outside") end local function touchDragEnterAction() if nil == pDisplayValueLabel then return end pDisplayValueLabel:setString("Drag Enter") end local function touchDragExitAction() if nil == pDisplayValueLabel then return end pDisplayValueLabel:setString("Drag Exit") end local function touchUpInsideAction() if nil == pDisplayValueLabel then return end pDisplayValueLabel:setString("Touch Up Inside.") end local function touchUpOutsideAction() if nil == pDisplayValueLabel then return end pDisplayValueLabel:setString("Touch Up Outside.") end local function touchCancelAction() if nil == pDisplayValueLabel then return end pDisplayValueLabel:setString("Touch Cancel") end pControlButton:setBackgroundSpriteForState(pBackgroundHighlightedButton, cc.CONTROL_STATE_HIGH_LIGHTED ) pControlButton:setTitleColorForState(cc.c3b(255, 255, 255), cc.CONTROL_STATE_HIGH_LIGHTED ) pControlButton:setAnchorPoint(cc.p(0.5, 1)) pControlButton:setPosition(cc.p(screenSize.width / 2.0, screenSize.height / 2.0)) pControlButton:registerControlEventHandler(touchDownAction,cc.CONTROL_EVENTTYPE_TOUCH_DOWN ) pControlButton:registerControlEventHandler(touchDragInsideAction,cc.CONTROL_EVENTTYPE_DRAG_INSIDE) pControlButton:registerControlEventHandler(touchDragOutsideAction,cc.CONTROL_EVENTTYPE_DRAG_OUTSIDE) pControlButton:registerControlEventHandler(touchDragEnterAction,cc.CONTROL_EVENTTYPE_DRAG_ENTER) pControlButton:registerControlEventHandler(touchDragExitAction,cc.CONTROL_EVENTTYPE_DRAG_EXIT) pControlButton:registerControlEventHandler(touchUpInsideAction,cc.CONTROL_EVENTTYPE_TOUCH_UP_INSIDE) pControlButton:registerControlEventHandler(touchUpOutsideAction,cc.CONTROL_EVENTTYPE_TOUCH_UP_OUTSIDE) pControlButton:registerControlEventHandler(touchCancelAction,cc.CONTROL_EVENTTYPE_TOUCH_CANCEL) pLayer:addChild(pControlButton, 1) --Add the black background local pBackgroundButton = cc.Scale9Sprite:create("extensions/buttonBackground.png") pBackgroundButton:setContentSize(cc.size(300, 170)) pBackgroundButton:setPosition(cc.p(screenSize.width / 2.0, screenSize.height / 2.0)) pLayer:addChild(pBackgroundButton) end --PotentiometerTest local function InitPotentiometerTest(pLayer) if nil == pLayer then return end local screenSize = cc.Director:getInstance():getWinSize() local pNode = cc.Node:create() pNode:setPosition(cc.p (screenSize.width / 2, screenSize.height / 2)) pLayer:addChild(pNode, 1) local dLayer_width = 0 -- Add the black background for the text local pBackground = cc.Scale9Sprite:create("extensions/buttonBackground.png") pBackground:setContentSize(cc.size(80, 50)) pBackground:setPosition(cc.p(dLayer_width + pBackground:getContentSize().width / 2.0, 0)) pNode:addChild(pBackground) dLayer_width = dLayer_width + pBackground:getContentSize().width local pDisplayValueLabel = cc.Label:createWithSystemFont("", "HelveticaNeue-Bold", 30) pDisplayValueLabel:setPosition(pBackground:getPosition()) pNode:addChild(pDisplayValueLabel) -- Add the slider local function valueChanged(pSender) if nil == pSender then return end local pControl = pSender local strFmt = string.format("%0.2f",pControl:getValue()) pDisplayValueLabel:setString(strFmt ) end local pPotentiometer = cc.ControlPotentiometer:create("extensions/potentiometerTrack.png","extensions/potentiometerProgress.png" ,"extensions/potentiometerButton.png") pPotentiometer:setPosition(cc.p (dLayer_width + 10 + pPotentiometer:getContentSize().width / 2, 0)) -- When the value of the slider will change, the given selector will be call pPotentiometer:registerControlEventHandler(valueChanged, cc.CONTROL_EVENTTYPE_VALUE_CHANGED) pNode:addChild(pPotentiometer) dLayer_width = dLayer_width + pPotentiometer:getContentSize().width -- Set the layer size pNode:setContentSize(cc.size(dLayer_width, 0)) pNode:setAnchorPoint(cc.p (0.5, 0.5)) -- Update the value label valueChanged(pPotentiometer) end local function InitStepperTest(pLayer) if nil == pLayer then return end local screenSize = cc.Director:getInstance():getWinSize() local pNode = cc.Node:create() pNode:setPosition(cc.p (screenSize.width / 2, screenSize.height / 2)) pLayer:addChild(pNode, 1) local layer_width = 0 -- Add the black background for the text local background = cc.Scale9Sprite:create("extensions/buttonBackground.png") background:setContentSize(cc.size(100, 50)) background:setPosition(cc.p(layer_width + background:getContentSize().width / 2.0, 0)) pNode:addChild(background) local pDisplayValueLabel = cc.Label:createWithSystemFont("0", "HelveticaNeue-Bold", 30) pDisplayValueLabel:setPosition(background:getPosition()) pNode:addChild(pDisplayValueLabel) layer_width = layer_width + background:getContentSize().width local minusSprite = cc.Sprite:create("extensions/stepper-minus.png") local plusSprite = cc.Sprite:create("extensions/stepper-plus.png") local function valueChanged(pSender) if nil == pDisplayValueLabel or nil == pSender then return end local pControl = pSender local strFmt = string.format("%0.02f",pControl:getValue() ) pDisplayValueLabel:setString(strFmt ) end local stepper = cc.ControlStepper:create(minusSprite, plusSprite) stepper:setPosition(cc.p (layer_width + 10 + stepper:getContentSize().width / 2, 0)) stepper:registerControlEventHandler(valueChanged, cc.CONTROL_EVENTTYPE_VALUE_CHANGED) pNode:addChild(stepper) layer_width = layer_width + stepper:getContentSize().width -- Set the layer size pNode:setContentSize(cc.size(layer_width, 0)) pNode:setAnchorPoint(cc.p (0.5, 0.5)) -- Update the value label valueChanged(stepper) end local function InitSpecialSceneLayer(pLayer) if ControlExtensionsTestEnum.kCCControlSliderTest == nCurCase then InitSliderTest(pLayer) elseif ControlExtensionsTestEnum.kCCControlColourPickerTest == nCurCase then InitColourPickerTest(pLayer) elseif ControlExtensionsTestEnum.kCCControlSwitchTest == nCurCase then InitSwitchTest(pLayer) elseif ControlExtensionsTestEnum.kCCControlButtonTest_HelloVariableSize == nCurCase then InitHelloVariableSize(pLayer) elseif ControlExtensionsTestEnum.kCCControlButtonTest_Event == nCurCase then InitButtonTestEvent(pLayer) elseif ControlExtensionsTestEnum.kCCControlButtonTest_Styling == nCurCase then InitStyling(pLayer) elseif ControlExtensionsTestEnum.kCCControlPotentiometerTest == nCurCase then InitPotentiometerTest(pLayer) elseif ControlExtensionsTestEnum.kCCControlStepperTest == nCurCase then InitStepperTest(pLayer) end end function CurrentControlScene() pNewScene = nil pNewScene = cc.Scene:create() local pNewLayer = cc.Layer:create() BaseInitSceneLayer(pNewLayer,GetControlExtensionsTitle()) InitSpecialSceneLayer(pNewLayer) pNewScene:addChild(pNewLayer) if nil ~= pNewScene then cc.Director:getInstance():replaceScene(pNewScene) end end local pNewLayer = cc.Layer:create() BaseInitSceneLayer(pNewLayer,GetControlExtensionsTitle()) InitSpecialSceneLayer(pNewLayer) pNewScene:addChild(pNewLayer) return pNewScene end local function runEditBoxTest() local newScene = cc.Scene:create() local newLayer = cc.Layer:create() local visibleOrigin = cc.Director:getInstance():getVisibleOrigin() local visibleSize = cc.Director:getInstance():getVisibleSize() local pBg = cc.Sprite:create("Images/HelloWorld.png") pBg:setPosition(cc.p(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height/2)) newLayer:addChild(pBg) local TTFShowEditReturn = cc.Label:createWithSystemFont("No edit control return!", "", 30) TTFShowEditReturn:setPosition(cc.p(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y + visibleSize.height - 50)) newLayer:addChild(TTFShowEditReturn) -- Back Menu local pToMainMenu = cc.Menu:create() CreateExtensionsBasicLayerMenu(pToMainMenu) pToMainMenu:setPosition(cc.p(0, 0)) newLayer:addChild(pToMainMenu,10) local editBoxSize = cc.size(visibleSize.width - 100, 60) local EditName = nil local EditPassword = nil local EditEmail = nil local function editBoxTextEventHandle(strEventName,pSender) local edit = pSender local strFmt if strEventName == "began" then strFmt = string.format("editBox %p DidBegin !", edit) print(strFmt) elseif strEventName == "ended" then strFmt = string.format("editBox %p DidEnd !", edit) print(strFmt) elseif strEventName == "return" then strFmt = string.format("editBox %p was returned !",edit) if edit == EditName then TTFShowEditReturn:setString("Name EditBox return !") elseif edit == EditPassword then TTFShowEditReturn:setString("Password EditBox return !") elseif edit == EditEmail then TTFShowEditReturn:setString("Email EditBox return !") end print(strFmt) elseif strEventName == "changed" then strFmt = string.format("editBox %p TextChanged, text: %s ", edit, edit:getText()) print(strFmt) end end -- top EditName = cc.EditBox:create(editBoxSize, cc.Scale9Sprite:create("extensions/green_edit.png")) EditName:setPosition(cc.p(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height*3/4)) local targetPlatform = cc.Application:getInstance():getTargetPlatform() if kTargetIphone == targetPlatform or kTargetIpad == targetPlatform then EditName:setFontName("Paint Boy") else EditName:setFontName("fonts/Paint Boy.ttf") end EditName:setFontSize(25) EditName:setFontColor(cc.c3b(255,0,0)) EditName:setPlaceHolder("Name:") EditName:setPlaceholderFontColor(cc.c3b(255,255,255)) EditName:setMaxLength(8) EditName:setReturnType(cc.KEYBOARD_RETURNTYPE_DONE ) --Handler EditName:registerScriptEditBoxHandler(editBoxTextEventHandle) newLayer:addChild(EditName) --middle EditPassword = cc.EditBox:create(editBoxSize, cc.Scale9Sprite:create("extensions/orange_edit.png")) EditPassword:setPosition(cc.p(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height/2)) if kTargetIphone == targetPlatform or kTargetIpad == targetPlatform then EditPassword:setFont("American Typewriter", 30) else EditPassword:setFont("fonts/American Typewriter.ttf", 30) end EditPassword:setFontColor(cc.c3b(0,255,0)) EditPassword:setPlaceHolder("Password:") EditPassword:setMaxLength(6) EditPassword:setInputFlag(cc.EDITBOX_INPUT_FLAG_PASSWORD) EditPassword:setInputMode(cc.EDITBOX_INPUT_MODE_SINGLELINE) EditPassword:registerScriptEditBoxHandler(editBoxTextEventHandle) newLayer:addChild(EditPassword) --bottom EditEmail = cc.EditBox:create(cc.size(editBoxSize.width, editBoxSize.height), cc.Scale9Sprite:create("extensions/yellow_edit.png")) EditEmail:setPosition(cc.p(visibleOrigin.x+visibleSize.width/2, visibleOrigin.y+visibleSize.height/4)) EditEmail:setAnchorPoint(cc.p(0.5, 1.0)) EditEmail:setPlaceHolder("Email:") EditEmail:setInputMode(cc.EDITBOX_INPUT_MODE_EMAILADDR) EditEmail:registerScriptEditBoxHandler(editBoxTextEventHandle) newLayer:addChild(EditEmail) newLayer:setPosition(cc.p(10, 20)) newScene:addChild(newLayer) return newScene end local TableViewTestLayer = class("TableViewTestLayer") TableViewTestLayer.__index = TableViewTestLayer function TableViewTestLayer.extend(target) local t = tolua.getpeer(target) if not t then t = {} tolua.setpeer(target, t) end setmetatable(t, TableViewTestLayer) return target end function TableViewTestLayer.scrollViewDidScroll(view) print("scrollViewDidScroll") end function TableViewTestLayer.scrollViewDidZoom(view) print("scrollViewDidZoom") end function TableViewTestLayer.tableCellTouched(table,cell) print("cell touched at index: " .. cell:getIdx()) end function TableViewTestLayer.cellSizeForTable(table,idx) return 60,60 end function TableViewTestLayer.tableCellAtIndex(table, idx) local strValue = string.format("%d",idx) local cell = table:dequeueCell() local label = nil if nil == cell then cell = cc.TableViewCell:new() local sprite = cc.Sprite:create("Images/Icon.png") sprite:setAnchorPoint(cc.p(0,0)) sprite:setPosition(cc.p(0, 0)) cell:addChild(sprite) label = cc.Label:createWithSystemFont(strValue, "Helvetica", 20.0) label:setPosition(cc.p(0,0)) label:setAnchorPoint(cc.p(0,0)) label:setTag(123) cell:addChild(label) else label = cell:getChildByTag(123) if nil ~= label then label:setString(strValue) end end return cell end function TableViewTestLayer.numberOfCellsInTableView(table) return 25 end function TableViewTestLayer:init() local winSize = cc.Director:getInstance():getWinSize() local tableView = cc.TableView:create(cc.size(600,60)) tableView:setDirection(cc.SCROLLVIEW_DIRECTION_HORIZONTAL) tableView:setPosition(cc.p(20, winSize.height / 2 - 150)) tableView:setDelegate() self:addChild(tableView) --registerScriptHandler functions must be before the reloadData funtion tableView:registerScriptHandler(TableViewTestLayer.numberOfCellsInTableView,cc.NUMBER_OF_CELLS_IN_TABLEVIEW) tableView:registerScriptHandler(TableViewTestLayer.scrollViewDidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) tableView:registerScriptHandler(TableViewTestLayer.scrollViewDidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) tableView:registerScriptHandler(TableViewTestLayer.tableCellTouched,cc.TABLECELL_TOUCHED) tableView:registerScriptHandler(TableViewTestLayer.cellSizeForTable,cc.TABLECELL_SIZE_FOR_INDEX) tableView:registerScriptHandler(TableViewTestLayer.tableCellAtIndex,cc.TABLECELL_SIZE_AT_INDEX) tableView:reloadData() tableView = cc.TableView:create(cc.size(60, 350)) tableView:setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL) tableView:setPosition(cc.p(winSize.width - 150, winSize.height / 2 - 150)) tableView:setDelegate() tableView:setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN) self:addChild(tableView) tableView:registerScriptHandler(TableViewTestLayer.scrollViewDidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) tableView:registerScriptHandler(TableViewTestLayer.scrollViewDidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) tableView:registerScriptHandler(TableViewTestLayer.tableCellTouched,cc.TABLECELL_TOUCHED) tableView:registerScriptHandler(TableViewTestLayer.cellSizeForTable,cc.TABLECELL_SIZE_FOR_INDEX) tableView:registerScriptHandler(TableViewTestLayer.tableCellAtIndex,cc.TABLECELL_SIZE_AT_INDEX) tableView:registerScriptHandler(TableViewTestLayer.numberOfCellsInTableView,cc.NUMBER_OF_CELLS_IN_TABLEVIEW) tableView:reloadData() -- Back Menu local pToMainMenu = cc.Menu:create() CreateExtensionsBasicLayerMenu(pToMainMenu) pToMainMenu:setPosition(cc.p(0, 0)) self:addChild(pToMainMenu,10) return true end function TableViewTestLayer.create() local layer = TableViewTestLayer.extend(cc.Layer:create()) if nil ~= layer then layer:init() end return layer end local function runTableViewTest() local newScene = cc.Scene:create() local newLayer = TableViewTestLayer.create() newScene:addChild(newLayer) return newScene end local function runScrollViewTest() local newScene = cc.Scene:create() local newLayer = cc.Layer:create() -- Back Menu local pToMainMenu = cc.Menu:create() CreateExtensionsBasicLayerMenu(pToMainMenu) pToMainMenu:setPosition(cc.p(0, 0)) newLayer:addChild(pToMainMenu,10) local layerColor = cc.LayerColor:create(cc.c4b(128,64,0,255)) newLayer:addChild(layerColor) local scrollView1 = cc.ScrollView:create() local screenSize = cc.Director:getInstance():getWinSize() local function scrollView1DidScroll() print("scrollView1DidScroll") end local function scrollView1DidZoom() print("scrollView1DidZoom") end if nil ~= scrollView1 then scrollView1:setViewSize(cc.size(screenSize.width / 2,screenSize.height)) scrollView1:setPosition(cc.p(0,0)) scrollView1:setScale(1.0) scrollView1:ignoreAnchorPointForPosition(true) local flowersprite1 = cc.Sprite:create("ccb/flower.jpg") if nil ~= flowersprite1 then scrollView1:setContainer(flowersprite1) scrollView1:updateInset() end scrollView1:setDirection(cc.SCROLLVIEW_DIRECTION_BOTH ) scrollView1:setClippingToBounds(true) scrollView1:setBounceable(true) scrollView1:setDelegate() scrollView1:registerScriptHandler(scrollView1DidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) scrollView1:registerScriptHandler(scrollView1DidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) end newLayer:addChild(scrollView1) local scrollView2 = cc.ScrollView:create() local function scrollView2DidScroll() print("scrollView2DidScroll") end local function scrollView2DidZoom() print("scrollView2DidZoom") end if nil ~= scrollView2 then scrollView2:setViewSize(cc.size(screenSize.width / 2,screenSize.height)) scrollView2:setPosition(cc.p(screenSize.width / 2,0)) scrollView2:setScale(1.0) scrollView2:ignoreAnchorPointForPosition(true) local flowersprite2 = cc.Sprite:create("ccb/flower.jpg") if nil ~= flowersprite2 then scrollView2:setContainer(flowersprite2) scrollView2:updateInset() end scrollView2:setDirection(cc.SCROLLVIEW_DIRECTION_BOTH ) scrollView2:setClippingToBounds(true) scrollView2:setBounceable(true) scrollView2:setDelegate() scrollView2:registerScriptHandler(scrollView2DidScroll,cc.SCROLLVIEW_SCRIPT_SCROLL) scrollView2:registerScriptHandler(scrollView2DidZoom,cc.SCROLLVIEW_SCRIPT_ZOOM) end newLayer:addChild(scrollView2) newScene:addChild(newLayer) return newScene end local CreateExtensionsTestTable = { runNotificationCenterTest, runCCControlTest, runCocosBuilder, runWebSocketTest, runEditBoxTest, runTableViewTest, runScrollViewTest, } local function ExtensionsMainLayer() local s = cc.Director:getInstance():getWinSize() local function CreateExtensionsTestScene(nPerformanceNo) local pNewscene = CreateExtensionsTestTable[nPerformanceNo]() return pNewscene end local function menuCallback(tag, pMenuItem) local scene = nil local nIdx = pMenuItem:getLocalZOrder() - kItemTagBasic local ExtensionsTestScene = CreateExtensionsTestScene(nIdx) if nil ~= ExtensionsTestScene then cc.Director:getInstance():replaceScene(ExtensionsTestScene) end end local layer = cc.Layer:create() local menu = cc.Menu:create() menu:setPosition(cc.p(0, 0)) cc.MenuItemFont:setFontName("Arial") cc.MenuItemFont:setFontSize(24) local targetPlatform = cc.Application:getInstance():getTargetPlatform() local bSupportWebSocket = false if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) or (cc.PLATFORM_OS_ANDROID == targetPlatform) or (cc.PLATFORM_OS_WINDOWS == targetPlatform) or (cc.PLATFORM_OS_MAC == targetPlatform) then bSupportWebSocket = true end local bSupportEdit = false if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) or (cc.PLATFORM_OS_ANDROID == targetPlatform) or (cc.PLATFORM_OS_WINDOWS == targetPlatform) or (cc.PLATFORM_OS_MAC == targetPlatform) or (cc.PLATFORM_OS_TIZEN == targetPlatform) then bSupportEdit = true end for i = 1, ExtensionTestEnum.TEST_MAX_COUNT do local item = cc.MenuItemFont:create(testsName[i]) item:registerScriptTapHandler(menuCallback) item:setPosition(s.width / 2, s.height - i * LINE_SPACE) menu:addChild(item, kItemTagBasic + i) if ((i == ExtensionTestEnum.TEST_WEBSOCKET + 1) and (false == bSupportWebSocket)) or ((i == ExtensionTestEnum.TEST_EDITBOX + 1) and (false == bSupportEdit)) or (i == ExtensionTestEnum.TEST_NOTIFICATIONCENTER + 1)then item:setEnabled(false) end end layer:addChild(menu) -- handling touch events local beginPos = {x = 0, y = 0} local function onTouchesBegan(touches, event) beginPos = touches[1]:getLocation() end local function onTouchesMoved(touches, event) local location = touches[1]:getLocation() local nMoveY = location.y - beginPos.y local curPosx, curPosy = menu:getPosition() local nextPosy = curPosy + nMoveY local winSize = cc.Director:getInstance():getWinSize() if nextPosy < 0 then menu:setPosition(0, 0) return end if nextPosy > ((ExtensionTestEnum.TEST_MAX_COUNT + 1) * LINE_SPACE - winSize.height) then menu:setPosition(0, ((ExtensionTestEnum.TEST_MAX_COUNT + 1) * LINE_SPACE - winSize.height)) return end menu:setPosition(curPosx, nextPosy) beginPos = {x = location.x, y = location.y} end local listener = cc.EventListenerTouchAllAtOnce:create() listener:registerScriptHandler(onTouchesBegan,cc.Handler.EVENT_TOUCHES_BEGAN ) listener:registerScriptHandler(onTouchesMoved,cc.Handler.EVENT_TOUCHES_MOVED ) local eventDispatcher = layer:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listener, layer) return layer end ------------------------------------- -- Extensions Test ------------------------------------- function ExtensionsTestMain() local scene = cc.Scene:create() scene:addChild(ExtensionsMainLayer()) scene:addChild(CreateBackMenuItem()) return scene end
mit
parsanoe160/aqil1381
bot.lua
2
7294
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' .. ';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' -- @MuteTeam tdcli = dofile('tdcli.lua') redis = (loadfile "./libs/redis.lua")() sudo_users = { 105616381, 0 } -- Print message format. Use serpent for prettier result. function vardump(value, depth, key) local linePrefix = '' local spaces = '' if key ~= nil then linePrefix = key .. ' = ' end if depth == nil then depth = 0 else depth = depth + 1 for i=1, depth do spaces = spaces .. ' ' end end if type(value) == 'table' then mTable = getmetatable(value) if mTable == nil then print(spaces .. linePrefix .. '(table) ') else print(spaces .. '(metatable) ') value = mTable end for tableKey, tableValue in pairs(value) do vardump(tableValue, depth, tableKey) end elseif type(value) == 'function' or type(value) == 'thread' or type(value) == 'userdata' or value == nil then --@MuteTeam print(spaces .. tostring(value)) elseif type(value) == 'string' then print(spaces .. linePrefix .. '"' .. tostring(value) .. '",') else print(spaces .. linePrefix .. tostring(value) .. ',') end end -- Print callback function dl_cb(arg, data) vardump(arg) vardump(data) end function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(sudo_users) do if user == msg.sender_user_id_ then var = true end end return var end function tdcli_update_callback(data) vardump(data) if (data.ID == "UpdateNewMessage") then local msg = data.message_ local input = msg.content_.text_ local chat_id = msg.chat_id_ local user_id = msg.sender_user_id_ local reply_id = msg.reply_to_message_id_ vardump(msg) if msg.content_.ID == "MessageText" then if input == "ping" then tdcli.sendMessage(chat_id, msg.id_, 1, '<code>pong</code>', 1, 'html') end if input == "PING" then tdcli.sendMessage(chat_id, msg.id_, 1, '<b>PONG</b>', 1, 'html') end if input:match("^[#!/][Ii][Dd]$") then tdcli.sendMessage(chat_id, msg.id_, 1, '<b>SuperGroup ID : </b><code>'..string.sub(chat_id, 5,14)..'</code>\n<b>User ID : </b><code>'..user_id..'</code>\n<b>Channel : </b>@MuteTeam', 1, 'html') end if input:match("^[#!/][Pp][Ii][Nn]") and reply_id then tdcli.sendMessage(chat_id, msg.id_, 1, '<b>Message Pinned</b>', 1, 'html') tdcli.pinChannelMessage(chat_id, reply_id, 1) end if input:match("^[#!/][Uu][Nn][Pp][Ii][Nn]") and reply_id then tdcli.sendMessage(chat_id, msg.id_, 1, '<b>Message UnPinned</b>', 1, 'html') tdcli.unpinChannelMessage(chat_id, reply_id, 1) end if input:match("^[#!/][Ll]ock links$") and is_sudo(msg) then if redis:get('lock_linkstg:'..chat_id) then tdcli.sendMessage(chat_id, msg.id_, 1, '<b>Link posting is already locked</b>', 1, 'html') else -- @MuteTeam redis:set('lock_linkstg:'..chat_id, true) tdcli.sendMessage(chat_id, msg.id_, 1, '<b>Link posting has been locked</b>', 1, 'html') end end if input:match("^[#!/][Uu]nlock links$") and is_sudo(msg) then if not redis:get('lock_linkstg:'..chat_id) then tdcli.sendMessage(chat_id, msg.id_, 1, '<b>Link posting is not locked</b>', 1, 'html') else redis:del('lock_linkstg:'..chat_id) tdcli.sendMessage(chat_id, msg.id_, 1, '<b>Link posting has been unlocked</b>', 1, 'html') end end if redis:get('lock_linkstg:'..chat_id) and input:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") then tdcli.deleteMessages(chat_id, {[0] = msg.id_}) end if input:match("^[#!/][Mm]ute all$") and is_sudo(msg) then if redis:get('mute_alltg:'..chat_id) then tdcli.sendMessage(chat_id, msg.id_, 1, '<b>Mute All is already on</b>', 1, 'html') else -- @MuteTeam redis:set('mute_alltg:'..chat_id, true) tdcli.sendMessage(chat_id, msg.id_, 1, '<b>Mute All has been enabled</b>', 1, 'html') end end if input:match("^[#!/][Uu]nmute all$") and is_sudo(msg) then if not redis:get('mute_alltg:'..chat_id) then tdcli.sendMessage(chat_id, msg.id_, 1, '<b>Mute All is already disabled</b>', 1, 'html') else -- @MuteTeam redis:del('mute_alltg:'..chat_id) tdcli.sendMessage(chat_id, msg.id_, 1, '<b>Mute All has been disabled</b>', 1, 'html') end end local links = 'lock_linkstg:'..chat_id if redis:get(links) then Links = "yes" else Links = "no" end -- @MuteTeam local all = 'mute_alltg:'..chat_id if redis:get(all) then All = "yes" else All = "no" end if input:match("^[#!/][Ss]ettings$") and is_sudo(msg) then tdcli.sendMessage(chat_id, msg.id_, 1, '<i>SuperGroup Settings:</i>\n<b>__________________</b>\n\n<b>Lock Links : </b><code>'..Links..'</code>\n\n<b>Mute All : </b><code>'..All..'</code>\n', 1, 'html') -- @MuteTeam end if input:match("^[#!/][Ff]wd$") then tdcli.forwardMessages(chat_id, chat_id,{[0] = reply_id}, 0) end if input:match("^[#!/][Uu]sername") and is_sudo(msg) then tdcli.changeUsername(string.sub(input, 11)) tdcli.sendMessage(chat_id, msg.id_, 1,'<b>Username Changed To </b>@'..string.sub(input, 11), 1, 'html') end if input:match("^[#!/][Ee]cho") then tdcli.sendMessage(chat_id, msg.id_, 1, string.sub(input, 7), 1, 'html') end if input:match("^[#!/][Ss]etname") then tdcli.changeChatTitle(chat_id, string.sub(input, 10), 1) tdcli.sendMessage(chat_id, msg.id_, 1,'<b>SuperGroup Name Changed To </b><code>'..string.sub(input, 10)..'</code>', 1, 'html') end if input:match("^[#!/][Ee]dit") then tdcli.editMessageText(chat_id, reply_id, nil, string.sub(input, 7), 'html') end if input:match("^[#!/][Cc]hangename") and is_sudo(msg) then tdcli.changeName(string.sub(input, 13), nil, 1) tdcli.sendMessage(chat_id, msg.id_, 1,'<b>Bot Name Changed To </b><code>'..string.sub(input, 13)..'</code>', 1, 'html') end if input:match("^[#!/][Ii]nvite") and is_sudo(msg) then tdcli.addChatMember(chat_id, string.sub(input, 9), 20) end if input:match("^[#!/][Cc]reatesuper") and is_sudo(msg) then tdcli.createNewChannelChat(string.sub(input, 14), 1, 'My Supergroup, my rules') tdcli.sendMessage(chat_id, msg.id_, 1,'<b>SuperGroup </b>'..string.sub(input, 14)..' <b>Created</b>', 1, 'html') end if input:match("^[#!/]view") then tdcli.viewMessages(chat_id, {[0] = msg.id_}) tdcli.sendMessage(chat_id, msg.id_, 1,'<b>Messages Viewed</b>', 1, 'html') end end if redis:get('mute_alltg:'..chat_id) and msg then tdcli.deleteMessages(chat_id, {[0] = msg.id_}) end elseif (data.ID == "UpdateOption" and data.name_ == "my_id") then -- @MuteTeam tdcli_function ({ ID="GetChats", offset_order_="9223372036854775807", offset_chat_id_=0, limit_=20 }, dl_cb, nil) end end
agpl-3.0
darkdukey/sdkbox-facebook-sample-v2
scripting/lua/luajit/LuaJIT-2.0.1/dynasm/dasm_mips.lua
74
28080
------------------------------------------------------------------------------ -- DynASM MIPS module. -- -- Copyright (C) 2005-2013 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "mips", description = "DynASM MIPS module", version = "1.3.0", vernum = 10300, release = "2012-01-23", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable = assert, setmetatable local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch = _s.match, _s.gmatch local concat, sort = table.concat, table.sort local bit = bit or require("bit") local band, shl, sar, tohex = bit.band, bit.lshift, bit.arshift, bit.tohex -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "IMM", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(0xff000000 + w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n >= 0xff000000 then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. local map_archdef = { sp="r29", ra="r31" } -- Ext. register name -> int. name. local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) if s == "r29" then return "sp" elseif s == "r31" then return "ra" end return s end ------------------------------------------------------------------------------ -- Template strings for MIPS instructions. local map_op = { -- First-level opcodes. j_1 = "08000000J", jal_1 = "0c000000J", b_1 = "10000000B", beqz_2 = "10000000SB", beq_3 = "10000000STB", bnez_2 = "14000000SB", bne_3 = "14000000STB", blez_2 = "18000000SB", bgtz_2 = "1c000000SB", addi_3 = "20000000TSI", li_2 = "24000000TI", addiu_3 = "24000000TSI", slti_3 = "28000000TSI", sltiu_3 = "2c000000TSI", andi_3 = "30000000TSU", lu_2 = "34000000TU", ori_3 = "34000000TSU", xori_3 = "38000000TSU", lui_2 = "3c000000TU", beqzl_2 = "50000000SB", beql_3 = "50000000STB", bnezl_2 = "54000000SB", bnel_3 = "54000000STB", blezl_2 = "58000000SB", bgtzl_2 = "5c000000SB", lb_2 = "80000000TO", lh_2 = "84000000TO", lwl_2 = "88000000TO", lw_2 = "8c000000TO", lbu_2 = "90000000TO", lhu_2 = "94000000TO", lwr_2 = "98000000TO", sb_2 = "a0000000TO", sh_2 = "a4000000TO", swl_2 = "a8000000TO", sw_2 = "ac000000TO", swr_2 = "b8000000TO", cache_2 = "bc000000NO", ll_2 = "c0000000TO", lwc1_2 = "c4000000HO", pref_2 = "cc000000NO", ldc1_2 = "d4000000HO", sc_2 = "e0000000TO", swc1_2 = "e4000000HO", sdc1_2 = "f4000000HO", -- Opcode SPECIAL. nop_0 = "00000000", sll_3 = "00000000DTA", movf_2 = "00000001DS", movf_3 = "00000001DSC", movt_2 = "00010001DS", movt_3 = "00010001DSC", srl_3 = "00000002DTA", rotr_3 = "00200002DTA", sra_3 = "00000003DTA", sllv_3 = "00000004DTS", srlv_3 = "00000006DTS", rotrv_3 = "00000046DTS", srav_3 = "00000007DTS", jr_1 = "00000008S", jalr_1 = "0000f809S", jalr_2 = "00000009DS", movz_3 = "0000000aDST", movn_3 = "0000000bDST", syscall_0 = "0000000c", syscall_1 = "0000000cY", break_0 = "0000000d", break_1 = "0000000dY", sync_0 = "0000000f", mfhi_1 = "00000010D", mthi_1 = "00000011S", mflo_1 = "00000012D", mtlo_1 = "00000013S", mult_2 = "00000018ST", multu_2 = "00000019ST", div_2 = "0000001aST", divu_2 = "0000001bST", add_3 = "00000020DST", move_2 = "00000021DS", addu_3 = "00000021DST", sub_3 = "00000022DST", negu_2 = "00000023DT", subu_3 = "00000023DST", and_3 = "00000024DST", or_3 = "00000025DST", xor_3 = "00000026DST", not_2 = "00000027DS", nor_3 = "00000027DST", slt_3 = "0000002aDST", sltu_3 = "0000002bDST", tge_2 = "00000030ST", tge_3 = "00000030STZ", tgeu_2 = "00000031ST", tgeu_3 = "00000031STZ", tlt_2 = "00000032ST", tlt_3 = "00000032STZ", tltu_2 = "00000033ST", tltu_3 = "00000033STZ", teq_2 = "00000034ST", teq_3 = "00000034STZ", tne_2 = "00000036ST", tne_3 = "00000036STZ", -- Opcode REGIMM. bltz_2 = "04000000SB", bgez_2 = "04010000SB", bltzl_2 = "04020000SB", bgezl_2 = "04030000SB", tgei_2 = "04080000SI", tgeiu_2 = "04090000SI", tlti_2 = "040a0000SI", tltiu_2 = "040b0000SI", teqi_2 = "040c0000SI", tnei_2 = "040e0000SI", bltzal_2 = "04100000SB", bal_1 = "04110000B", bgezal_2 = "04110000SB", bltzall_2 = "04120000SB", bgezall_2 = "04130000SB", synci_1 = "041f0000O", -- Opcode SPECIAL2. madd_2 = "70000000ST", maddu_2 = "70000001ST", mul_3 = "70000002DST", msub_2 = "70000004ST", msubu_2 = "70000005ST", clz_2 = "70000020DS=", clo_2 = "70000021DS=", sdbbp_0 = "7000003f", sdbbp_1 = "7000003fY", -- Opcode SPECIAL3. ext_4 = "7c000000TSAM", -- Note: last arg is msbd = size-1 ins_4 = "7c000004TSAM", -- Note: last arg is msb = pos+size-1 wsbh_2 = "7c0000a0DT", seb_2 = "7c000420DT", seh_2 = "7c000620DT", rdhwr_2 = "7c00003bTD", -- Opcode COP0. mfc0_2 = "40000000TD", mfc0_3 = "40000000TDW", mtc0_2 = "40800000TD", mtc0_3 = "40800000TDW", rdpgpr_2 = "41400000DT", di_0 = "41606000", di_1 = "41606000T", ei_0 = "41606020", ei_1 = "41606020T", wrpgpr_2 = "41c00000DT", tlbr_0 = "42000001", tlbwi_0 = "42000002", tlbwr_0 = "42000006", tlbp_0 = "42000008", eret_0 = "42000018", deret_0 = "4200001f", wait_0 = "42000020", -- Opcode COP1. mfc1_2 = "44000000TG", cfc1_2 = "44400000TG", mfhc1_2 = "44600000TG", mtc1_2 = "44800000TG", ctc1_2 = "44c00000TG", mthc1_2 = "44e00000TG", bc1f_1 = "45000000B", bc1f_2 = "45000000CB", bc1t_1 = "45010000B", bc1t_2 = "45010000CB", bc1fl_1 = "45020000B", bc1fl_2 = "45020000CB", bc1tl_1 = "45030000B", bc1tl_2 = "45030000CB", ["add.s_3"] = "46000000FGH", ["sub.s_3"] = "46000001FGH", ["mul.s_3"] = "46000002FGH", ["div.s_3"] = "46000003FGH", ["sqrt.s_2"] = "46000004FG", ["abs.s_2"] = "46000005FG", ["mov.s_2"] = "46000006FG", ["neg.s_2"] = "46000007FG", ["round.l.s_2"] = "46000008FG", ["trunc.l.s_2"] = "46000009FG", ["ceil.l.s_2"] = "4600000aFG", ["floor.l.s_2"] = "4600000bFG", ["round.w.s_2"] = "4600000cFG", ["trunc.w.s_2"] = "4600000dFG", ["ceil.w.s_2"] = "4600000eFG", ["floor.w.s_2"] = "4600000fFG", ["movf.s_2"] = "46000011FG", ["movf.s_3"] = "46000011FGC", ["movt.s_2"] = "46010011FG", ["movt.s_3"] = "46010011FGC", ["movz.s_3"] = "46000012FGT", ["movn.s_3"] = "46000013FGT", ["recip.s_2"] = "46000015FG", ["rsqrt.s_2"] = "46000016FG", ["cvt.d.s_2"] = "46000021FG", ["cvt.w.s_2"] = "46000024FG", ["cvt.l.s_2"] = "46000025FG", ["cvt.ps.s_3"] = "46000026FGH", ["c.f.s_2"] = "46000030GH", ["c.f.s_3"] = "46000030VGH", ["c.un.s_2"] = "46000031GH", ["c.un.s_3"] = "46000031VGH", ["c.eq.s_2"] = "46000032GH", ["c.eq.s_3"] = "46000032VGH", ["c.ueq.s_2"] = "46000033GH", ["c.ueq.s_3"] = "46000033VGH", ["c.olt.s_2"] = "46000034GH", ["c.olt.s_3"] = "46000034VGH", ["c.ult.s_2"] = "46000035GH", ["c.ult.s_3"] = "46000035VGH", ["c.ole.s_2"] = "46000036GH", ["c.ole.s_3"] = "46000036VGH", ["c.ule.s_2"] = "46000037GH", ["c.ule.s_3"] = "46000037VGH", ["c.sf.s_2"] = "46000038GH", ["c.sf.s_3"] = "46000038VGH", ["c.ngle.s_2"] = "46000039GH", ["c.ngle.s_3"] = "46000039VGH", ["c.seq.s_2"] = "4600003aGH", ["c.seq.s_3"] = "4600003aVGH", ["c.ngl.s_2"] = "4600003bGH", ["c.ngl.s_3"] = "4600003bVGH", ["c.lt.s_2"] = "4600003cGH", ["c.lt.s_3"] = "4600003cVGH", ["c.nge.s_2"] = "4600003dGH", ["c.nge.s_3"] = "4600003dVGH", ["c.le.s_2"] = "4600003eGH", ["c.le.s_3"] = "4600003eVGH", ["c.ngt.s_2"] = "4600003fGH", ["c.ngt.s_3"] = "4600003fVGH", ["add.d_3"] = "46200000FGH", ["sub.d_3"] = "46200001FGH", ["mul.d_3"] = "46200002FGH", ["div.d_3"] = "46200003FGH", ["sqrt.d_2"] = "46200004FG", ["abs.d_2"] = "46200005FG", ["mov.d_2"] = "46200006FG", ["neg.d_2"] = "46200007FG", ["round.l.d_2"] = "46200008FG", ["trunc.l.d_2"] = "46200009FG", ["ceil.l.d_2"] = "4620000aFG", ["floor.l.d_2"] = "4620000bFG", ["round.w.d_2"] = "4620000cFG", ["trunc.w.d_2"] = "4620000dFG", ["ceil.w.d_2"] = "4620000eFG", ["floor.w.d_2"] = "4620000fFG", ["movf.d_2"] = "46200011FG", ["movf.d_3"] = "46200011FGC", ["movt.d_2"] = "46210011FG", ["movt.d_3"] = "46210011FGC", ["movz.d_3"] = "46200012FGT", ["movn.d_3"] = "46200013FGT", ["recip.d_2"] = "46200015FG", ["rsqrt.d_2"] = "46200016FG", ["cvt.s.d_2"] = "46200020FG", ["cvt.w.d_2"] = "46200024FG", ["cvt.l.d_2"] = "46200025FG", ["c.f.d_2"] = "46200030GH", ["c.f.d_3"] = "46200030VGH", ["c.un.d_2"] = "46200031GH", ["c.un.d_3"] = "46200031VGH", ["c.eq.d_2"] = "46200032GH", ["c.eq.d_3"] = "46200032VGH", ["c.ueq.d_2"] = "46200033GH", ["c.ueq.d_3"] = "46200033VGH", ["c.olt.d_2"] = "46200034GH", ["c.olt.d_3"] = "46200034VGH", ["c.ult.d_2"] = "46200035GH", ["c.ult.d_3"] = "46200035VGH", ["c.ole.d_2"] = "46200036GH", ["c.ole.d_3"] = "46200036VGH", ["c.ule.d_2"] = "46200037GH", ["c.ule.d_3"] = "46200037VGH", ["c.sf.d_2"] = "46200038GH", ["c.sf.d_3"] = "46200038VGH", ["c.ngle.d_2"] = "46200039GH", ["c.ngle.d_3"] = "46200039VGH", ["c.seq.d_2"] = "4620003aGH", ["c.seq.d_3"] = "4620003aVGH", ["c.ngl.d_2"] = "4620003bGH", ["c.ngl.d_3"] = "4620003bVGH", ["c.lt.d_2"] = "4620003cGH", ["c.lt.d_3"] = "4620003cVGH", ["c.nge.d_2"] = "4620003dGH", ["c.nge.d_3"] = "4620003dVGH", ["c.le.d_2"] = "4620003eGH", ["c.le.d_3"] = "4620003eVGH", ["c.ngt.d_2"] = "4620003fGH", ["c.ngt.d_3"] = "4620003fVGH", ["add.ps_3"] = "46c00000FGH", ["sub.ps_3"] = "46c00001FGH", ["mul.ps_3"] = "46c00002FGH", ["abs.ps_2"] = "46c00005FG", ["mov.ps_2"] = "46c00006FG", ["neg.ps_2"] = "46c00007FG", ["movf.ps_2"] = "46c00011FG", ["movf.ps_3"] = "46c00011FGC", ["movt.ps_2"] = "46c10011FG", ["movt.ps_3"] = "46c10011FGC", ["movz.ps_3"] = "46c00012FGT", ["movn.ps_3"] = "46c00013FGT", ["cvt.s.pu_2"] = "46c00020FG", ["cvt.s.pl_2"] = "46c00028FG", ["pll.ps_3"] = "46c0002cFGH", ["plu.ps_3"] = "46c0002dFGH", ["pul.ps_3"] = "46c0002eFGH", ["puu.ps_3"] = "46c0002fFGH", ["c.f.ps_2"] = "46c00030GH", ["c.f.ps_3"] = "46c00030VGH", ["c.un.ps_2"] = "46c00031GH", ["c.un.ps_3"] = "46c00031VGH", ["c.eq.ps_2"] = "46c00032GH", ["c.eq.ps_3"] = "46c00032VGH", ["c.ueq.ps_2"] = "46c00033GH", ["c.ueq.ps_3"] = "46c00033VGH", ["c.olt.ps_2"] = "46c00034GH", ["c.olt.ps_3"] = "46c00034VGH", ["c.ult.ps_2"] = "46c00035GH", ["c.ult.ps_3"] = "46c00035VGH", ["c.ole.ps_2"] = "46c00036GH", ["c.ole.ps_3"] = "46c00036VGH", ["c.ule.ps_2"] = "46c00037GH", ["c.ule.ps_3"] = "46c00037VGH", ["c.sf.ps_2"] = "46c00038GH", ["c.sf.ps_3"] = "46c00038VGH", ["c.ngle.ps_2"] = "46c00039GH", ["c.ngle.ps_3"] = "46c00039VGH", ["c.seq.ps_2"] = "46c0003aGH", ["c.seq.ps_3"] = "46c0003aVGH", ["c.ngl.ps_2"] = "46c0003bGH", ["c.ngl.ps_3"] = "46c0003bVGH", ["c.lt.ps_2"] = "46c0003cGH", ["c.lt.ps_3"] = "46c0003cVGH", ["c.nge.ps_2"] = "46c0003dGH", ["c.nge.ps_3"] = "46c0003dVGH", ["c.le.ps_2"] = "46c0003eGH", ["c.le.ps_3"] = "46c0003eVGH", ["c.ngt.ps_2"] = "46c0003fGH", ["c.ngt.ps_3"] = "46c0003fVGH", ["cvt.s.w_2"] = "46800020FG", ["cvt.d.w_2"] = "46800021FG", ["cvt.s.l_2"] = "46a00020FG", ["cvt.d.l_2"] = "46a00021FG", -- Opcode COP1X. lwxc1_2 = "4c000000FX", ldxc1_2 = "4c000001FX", luxc1_2 = "4c000005FX", swxc1_2 = "4c000008FX", sdxc1_2 = "4c000009FX", suxc1_2 = "4c00000dFX", prefx_2 = "4c00000fMX", ["alnv.ps_4"] = "4c00001eFGHS", ["madd.s_4"] = "4c000020FRGH", ["madd.d_4"] = "4c000021FRGH", ["madd.ps_4"] = "4c000026FRGH", ["msub.s_4"] = "4c000028FRGH", ["msub.d_4"] = "4c000029FRGH", ["msub.ps_4"] = "4c00002eFRGH", ["nmadd.s_4"] = "4c000030FRGH", ["nmadd.d_4"] = "4c000031FRGH", ["nmadd.ps_4"] = "4c000036FRGH", ["nmsub.s_4"] = "4c000038FRGH", ["nmsub.d_4"] = "4c000039FRGH", ["nmsub.ps_4"] = "4c00003eFRGH", } ------------------------------------------------------------------------------ local function parse_gpr(expr) local tname, ovreg = match(expr, "^([%w_]+):(r[1-3]?[0-9])$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local r = match(expr, "^r([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r, tp end end werror("bad register name `"..expr.."'") end local function parse_fpr(expr) local r = match(expr, "^f([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r end end werror("bad register name `"..expr.."'") end local function parse_imm(imm, bits, shift, scale, signed) local n = tonumber(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") elseif match(imm, "^[rf]([1-3]?[0-9])$") or match(imm, "^([%w_]+):([rf][1-3]?[0-9])$") then werror("expected immediate operand, got register") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_disp(disp) local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$") if imm then local r = shl(parse_gpr(reg), 21) local extname = match(imm, "^extern%s+(%S+)$") if extname then waction("REL_EXT", map_extern[extname], nil, 1) return r else return r + parse_imm(imm, 16, 0, 0, true) end end local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local r, tp = parse_gpr(reg) if tp then waction("IMM", 32768+16*32, format(tp.ctypefmt, tailr)) return shl(r, 21) end end werror("bad displacement `"..disp.."'") end local function parse_index(idx) local rt, rs = match(idx, "^(.*)%(([%w_:]+)%)$") if rt then rt = parse_gpr(rt) rs = parse_gpr(rs) return shl(rt, 16) + shl(rs, 21) end werror("bad index `"..idx.."'") end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. map_op[".template__"] = function(params, template, nparams) if not params then return sub(template, 9) end local op = tonumber(sub(template, 1, 8), 16) local n = 1 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 2 positions (ins/ext). if secpos+2 > maxsecpos then wflush() end local pos = wpos() -- Process each character. for p in gmatch(sub(template, 9), ".") do if p == "D" then op = op + shl(parse_gpr(params[n]), 11); n = n + 1 elseif p == "T" then op = op + shl(parse_gpr(params[n]), 16); n = n + 1 elseif p == "S" then op = op + shl(parse_gpr(params[n]), 21); n = n + 1 elseif p == "F" then op = op + shl(parse_fpr(params[n]), 6); n = n + 1 elseif p == "G" then op = op + shl(parse_fpr(params[n]), 11); n = n + 1 elseif p == "H" then op = op + shl(parse_fpr(params[n]), 16); n = n + 1 elseif p == "R" then op = op + shl(parse_fpr(params[n]), 21); n = n + 1 elseif p == "I" then op = op + parse_imm(params[n], 16, 0, 0, true); n = n + 1 elseif p == "U" then op = op + parse_imm(params[n], 16, 0, 0, false); n = n + 1 elseif p == "O" then op = op + parse_disp(params[n]); n = n + 1 elseif p == "X" then op = op + parse_index(params[n]); n = n + 1 elseif p == "B" or p == "J" then local mode, n, s = parse_label(params[n], false) if p == "B" then n = n + 2048 end waction("REL_"..mode, n, s, 1) n = n + 1 elseif p == "A" then op = op + parse_imm(params[n], 5, 6, 0, false); n = n + 1 elseif p == "M" then op = op + parse_imm(params[n], 5, 11, 0, false); n = n + 1 elseif p == "N" then op = op + parse_imm(params[n], 5, 16, 0, false); n = n + 1 elseif p == "C" then op = op + parse_imm(params[n], 3, 18, 0, false); n = n + 1 elseif p == "V" then op = op + parse_imm(params[n], 3, 8, 0, false); n = n + 1 elseif p == "W" then op = op + parse_imm(params[n], 3, 0, 0, false); n = n + 1 elseif p == "Y" then op = op + parse_imm(params[n], 20, 6, 0, false); n = n + 1 elseif p == "Z" then op = op + parse_imm(params[n], 10, 6, 0, false); n = n + 1 elseif p == "=" then op = op + shl(band(op, 0xf800), 5) -- Copy D to T for clz, clo. else assert(false) end end wputpos(pos, op) end ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. map_op[".long_*"] = function(params) if not params then return "imm..." end for _,p in ipairs(params) do local n = tonumber(p) if not n then werror("bad immediate `"..p.."'") end if n < 0 then n = n + 2^32 end wputw(n) if secpos+2 > maxsecpos then wflush() end end end -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
mit
ctfuckme/asasasas
bot/bot.lua
1
6902
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '0.14.6' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) -- vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) -- See plugins/isup.lua as an example for cron _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages (our message) -- if msg.out then -- print('\27[36mNot valid: msg from us\27[39m') -- return false -- end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end -- Don't process messages from ourself -- if msg.from.id == our_id then -- print('\27[36mNot valid: Msg from our id\27[39m') -- return false -- end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then print('\27[36mNot valid: Telegram message\27[39m') return false end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then if plugins[disabled_plugin].hidden then print('Plugin '..disabled_plugin..' is disabled on this chat') else local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) end return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "banhammer", "channels", "groupmanager", "help", "id", "invite", "moderation", "plugins", "stats", "version"}, sudo_users = {140402412}, disabled_channels = {}, moderation = {data = 'data/moderation.json'} } serialize_to_file(config, './data/config.lua') print ('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) --vardump (chat) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 5 mins postpone (cron_plugins, false, 5*60.0) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
SiENcE/APE
ui_scripts/ui_pageswitch.lua
2
5526
local l_gfx = love.graphics -- big and invisible container element -- used for paged interface, useless without page controller PageSwitch = {} PageSwitch.__index = PageSwitch PageSwitch.ident = "ui_pageswitch" PageSwitch.name = "PageSwitch" PageSwitch.updateable = true PageSwitch.updateAll = false -- if true, it will try to update all the pages in it, instead of only current one PageSwitch.isContainer = true function PageSwitch:new(name) local self = {} setmetatable(self,PageSwitch) self.pages = {} self.index = 0 if name ~= nil then self.name = name end return self end setmetatable(PageSwitch,{__index = UIElement}) function PageSwitch:draw() local c = #self.pages if c>0 then self.pages[self.index]:draw() end end function PageSwitch:update(dt) local c = #self.pages if c>0 then if self.updateAll == true then for i=1,c do self.pages[i]:draw() end else self.pages[self.index]:update(dt) end end end -- to prevent input overlap, input is handled only for current page function PageSwitch:mousemoved(x,y) local c = #self.pages if c>0 then self.pages[self.index]:mousemoved(x,y) end end function PageSwitch:mousepressed(x,y,b) local c = #self.pages if c>0 then self.pages[self.index]:mousepressed(x,y,b) end end function PageSwitch:mousereleased(x,y,b) local c = #self.pages if c>0 then self.pages[self.index]:mousereleased(x,y,b) end end function PageSwitch:keypressed(key,isrepeat) local c = #self.pages if c>0 then self.pages[self.index]:keypressed(key,isrepeat) end end function PageSwitch:keyreleased(key) local c = #self.pages if c>0 then self.pages[self.index]:keyreleased(key,isrepeat) end end function PageSwitch:wheelmoved(x,y) local c = #self.pages if c>0 then self.pages[self.index]:wheelmoved(x,y) end end function PageSwitch:setPosition(x,y) if self.isContainer == true then local dx,dy = (x or self.x) - self.x, (y or self.y) - self.y local c = #self.pages if c>0 then for i=1,c do local e = self.pages[i] e:setPosition(e.x+dx,e.y+dy) end end end self.x,self.y = x or self.x, y or self.y end function PageSwitch:addPage(pg) if type(pg) == "table" then local indx = table.getn(self.pages)+1 table.insert(self.pages,pg) self.index = indx return pg elseif type(pg) == "string" or pg == nil then local indx = table.getn(self.pages)+1 local page = Page:new(pg or ("Page"..indx)) table.insert(self.pages,page) self.index = indx return page end end function PageSwitch:removePage(page) local c = #self.pages if c>0 then if page == nil then table.remove(self.pages,self.index) self:nextPage() else for i=1,c do if self.pages[i].name == page then table.remove(self.pages,i) self:nextPage() break end end end end end function PageSwitch:nextPage() local c = #self.pages self.index = self.index + 1 if self.index>c then self.index = c end end function PageSwitch:prevPage() self.index = self.index-1 if self.index <= 0 then self.index = 1 end end function PageSwitch:getItem(name) local c = #self.pages if c>0 then if page == nil then return self.pages[self.index] else for i=1,c do if self.pages[i].name == page then return self.pages[i] end end end end end -- the page is a copy of groupbox Page = {} Page.__index = Page Page.ident = "ui_page" Page.name = "Page" Page.caption = "Page" Page.showBorder = false function Page:new(name) local self = {} setmetatable(self,Page) self.items = {} self.drawList = {} self.updateList = {} self.inputList = {} if name ~= nil then self.name = name end return self end setmetatable(Page,{__index = GroupBox}) -- this element controls pageswitch if linked to one. has page flip, add and remove buttons PageSwitchController = {} PageSwitchController.__index = PageSwitchController PageSwitchController.ident = "ui_pageswitchcontroller" PageSwitchController.name = "PageSwitchController" PageSwitchController.caption_xpad = 132 PageSwitchController.caption_ypad = 8 function PageSwitchController:new(name) local self = {} setmetatable(self,PageSwitchController) if name ~= nil then self.name = name end local bnext = Button:new("ButtonNext") bnext.caption = ">" bnext:setSize(32,32) bnext:setPosition(32,0) local bprev = Button:new("ButtonPrev") bprev.caption = "<" bprev:setSize(32,32) bprev:setPosition(0,0) local badd = Button:new("ButtonAdd") badd.caption = "+" badd:setSize(32,32) badd:setPosition(64,0) local brem = Button:new("ButtonRemove") brem.caption = "-" brem:setSize(32,32) brem:setPosition(96,0) self.items = {bprev,bnext,badd,brem,labcount} self.drawList = {bprev,bnext,badd,brem,labcount} self.updateList = {} self.inputList = {bprev,bnext,badd,brem} self.w = 128 self.caption = "0/0" return self end setmetatable(PageSwitchController,{__index = GroupBox}) function PageSwitchController:setPageSwitch(pgs) if pgs.ident == "ui_pageswitch" then self.pageswitch = pgs local psc = self local bp,bn,ba,br,lc = self.items[1],self.items[2],self.items[3],self.items[4],self.items[5] function bn:click(b) if b == "l" then pgs:nextPage() psc.caption = pgs.index.."/"..#pgs.pages end end function bp:click(b) if b == "l" then pgs:prevPage() psc.caption = pgs.index.."/"..#pgs.pages end end function ba:click(b) if b == "l" then pgs:addPage() psc.caption = pgs.index.."/"..#pgs.pages end end function br:click(b) if b == "l" then pgs:removePage() psc.caption = pgs.index.."/"..#pgs.pages end end end end
mit
luanorlandi/Swift-Space-Battle
src/window/window.lua
2
4583
Window = {} Window.__index = Window function Window:new() local W = {} setmetatable(W, Window) W.ratio = 16 / 9 -- try to read from a file local resolution = readResolutionFile() W.width = resolution.x W.height = resolution.y -- if was not possible, try to get from OS if W.width == nil or W.width == 0 or W.height == nil or W.height == 0 then W.width, W.height = MOAIGfxDevice.getViewSize() -- if was not possible, create a window with default resolution if W.width == nil or W.width == 0 or W.height == nil or W.height == 0 then W.width = 1280 W.height = 720 end end if MOAIEnvironment.osBrand ~= "Android" then -- adjust the window to be in proportion (still being inside the window) if W.height / W.width < W.ratio then W.width = W.height / W.ratio else W.height = W.width * W.ratio end end W.scale = W.height / 1280 MOAISim.openWindow("Swift Space Battle", W.width, W.height) viewport = MOAIViewport.new() viewport:setSize(W.width, W.height) viewport:setScale(W.width, W.height) viewport:setOffset ( 0, 0 ) W.layer = MOAILayer2D.new() W.layer:setViewport(viewport) --MOAIEnvironment.setListener(MOAIEnvironment.EVENT_VALUE_CHANGED, onEventValueChanged) MOAIRenderMgr.pushRenderPass(W.layer) return W end function readResolutionFile() local path = locateSaveLocation() -- probably a unexpected host (like html) if path == nil then return nil end local file = io.open(path .. "/resolution.lua", "r") local resolution = Vector:new(0, 0) if file ~= nil then resolution.x = tonumber(file:read()) resolution.y = tonumber(file:read()) io.close(file) end return resolution end function writeResolutionFile(resolution) local path = locateSaveLocation() -- probably a unexpected host (like html) if path == nil then return nil end local file = io.open(path .. "/resolution.lua", "w") if file ~= nil then file:write(resolution.x .. "\n") file:write(resolution.y) io.close(file) end end function readResolutionsFile() local file = io.open("file/resolutions.lua", "r") local resolutionsTable = {} -- to avoid texts go out of the window local limit = 7 -- limit of options available if file ~= nil then repeat local width = file:read() local height = file:read() if width ~= nil and height ~= nil then table.insert(resolutionsTable, Vector:new(width, height)) end until (width == nil and height == nil) or (#resolutionsTable >= limit) io.close(file) end return resolutionsTable end function onEventValueChanged(key, value) -- callback function -- if the window size changed, it will be called if key == "horizontalResolution" then window.width = value viewport:setSize(window.width, window.height) viewport:setScale(window.width, window.height) elseif key == "verticalResolution" then window.height = value viewport:setSize(window.width, window.height) viewport:setScale(window.width, window.height) end end function showInfo() -- show a lot of information about the device print("appDisplayName", MOAIEnvironment.appDisplayName) print("appVersion", MOAIEnvironment.appVersion) print("cacheDirectory", MOAIEnvironment.cacheDirectory) print("carrierISOCountryCode", MOAIEnvironment.carrierISOCountryCode) print("carrierMobileCountryCode", MOAIEnvironment.carrierMobileCountryCode) print("carrierMobileNetworkCode", MOAIEnvironment.carrierMobileNetworkCode) print("carrierName", MOAIEnvironment.carrierName) print("connectionType", MOAIEnvironment.connectionType) print("countryCode", MOAIEnvironment.countryCode) print("cpuabi", MOAIEnvironment.cpuabi) print("devBrand", MOAIEnvironment.devBrand) print("devName", MOAIEnvironment.devName) print("devManufacturer", MOAIEnvironment.devManufacturer) print("devModel", MOAIEnvironment.devModel) print("devPlatform", MOAIEnvironment.devPlatform) print("devProduct", MOAIEnvironment.devProduct) print("documentDirectory", MOAIEnvironment.documentDirectory) print("iosRetinaDisplay", MOAIEnvironment.iosRetinaDisplay) print("languageCode", MOAIEnvironment.languageCode) print("numProcessors", MOAIEnvironment.numProcessors) print("osBrand", MOAIEnvironment.osBrand) print("osVersion", MOAIEnvironment.osVersion) print("resourceDirectory", MOAIEnvironment.resourceDirectory) print("windowDpi", MOAIEnvironment.windowDpi) print("verticalResolution", MOAIEnvironment.verticalResolution) print("horizontalResolution", MOAIEnvironment.horizontalResolution) print("udid", MOAIEnvironment.udid) print("openUdid", MOAIEnvironment.openUdid) end
gpl-3.0
opentechinstitute/luci
applications/luci-asterisk/luasrc/asterisk.lua
80
18044
--[[ LuCI - Lua Configuration Interface Asterisk PBX interface library Copyright 2009 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.asterisk", package.seeall) require("luci.asterisk.cc_idd") local _io = require("io") local uci = require("luci.model.uci").cursor() local sys = require("luci.sys") local util = require("luci.util") AST_BIN = "/usr/sbin/asterisk" AST_FLAGS = "-r -x" --- LuCI Asterisk - Resync uci context function uci_resync() uci = luci.model.uci.cursor() end --- LuCI Asterisk io interface -- Handles low level io. -- @type module io = luci.util.class() --- Execute command and return output -- @param command String containing the command to execute -- @return String containing the command output function io.exec(command) local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") local buffer = fh:read("*a") fh:close() return buffer end --- Execute command and invoke given callback for each readed line -- @param command String containing the command to execute -- @param callback Function to call back for each line -- @return Always true function io.execl(command, callback) local ln local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") repeat ln = fh:read("*l") callback(ln) until not ln fh:close() return true end --- Execute command and return an iterator that returns one line per invokation -- @param command String containing the command to execute -- @return Iterator function function io.execi(command) local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") return function() local ln = fh:read("*l") if not ln then fh:close() end return ln end end --- LuCI Asterisk - core status core = luci.util.class() --- Retrive version string. -- @return String containing the reported asterisk version function core.version(self) local version = io.exec("core show version") return version:gsub(" *\n", "") end --- LuCI Asterisk - SIP information. -- @type module sip = luci.util.class() --- Get a list of known SIP peers -- @return Table containing each SIP peer function sip.peers(self) local head = false local peers = { } for line in io.execi("sip show peers") do if not head then head = true elseif not line:match(" sip peers ") then local online, delay, id, uid local name, host, dyn, nat, acl, port, status = line:match("(.-) +(.-) +([D ]) ([N ]) (.) (%d+) +(.+)") if host == '(Unspecified)' then host = nil end if port == '0' then port = nil else port = tonumber(port) end dyn = ( dyn == 'D' and true or false ) nat = ( nat == 'N' and true or false ) acl = ( acl ~= ' ' and true or false ) online, delay = status:match("(OK) %((%d+) ms%)") if online == 'OK' then online = true delay = tonumber(delay) elseif status ~= 'Unmonitored' then online = false delay = 0 else online = nil delay = 0 end id, uid = name:match("(.+)/(.+)") if not ( id and uid ) then id = name .. "..." uid = nil end peers[#peers+1] = { online = online, delay = delay, name = id, user = uid, dynamic = dyn, nat = nat, acl = acl, host = host, port = port } end end return peers end --- Get informations of given SIP peer -- @param peer String containing the name of the SIP peer function sip.peer(peer) local info = { } local keys = { } for line in io.execi("sip show peer " .. peer) do if #line > 0 then local key, val = line:match("(.-) *: +(.*)") if key and val then key = key:gsub("^ +",""):gsub(" +$", "") val = val:gsub("^ +",""):gsub(" +$", "") if key == "* Name" then key = "Name" elseif key == "Addr->IP" then info.address, info.port = val:match("(.+) Port (.+)") info.port = tonumber(info.port) elseif key == "Status" then info.online, info.delay = val:match("(OK) %((%d+) ms%)") if info.online == 'OK' then info.online = true info.delay = tonumber(info.delay) elseif status ~= 'Unmonitored' then info.online = false info.delay = 0 else info.online = nil info.delay = 0 end end if val == 'Yes' or val == 'yes' or val == '<Set>' then val = true elseif val == 'No' or val == 'no' then val = false elseif val == '<Not set>' or val == '(none)' then val = nil end keys[#keys+1] = key info[key] = val end end end return info, keys end --- LuCI Asterisk - Internal helpers -- @type module tools = luci.util.class() --- Convert given value to a list of tokens. Split by white space. -- @param val String or table value -- @return Table containing tokens function tools.parse_list(v) local tokens = { } v = type(v) == "table" and v or { v } for _, v in ipairs(v) do if type(v) == "string" then for v in v:gmatch("(%S+)") do tokens[#tokens+1] = v end end end return tokens end --- Convert given list to a collection of hyperlinks -- @param list Table of tokens -- @param url String pattern or callback function to construct urls (optional) -- @param sep String containing the seperator (optional, default is ", ") -- @return String containing the html fragment function tools.hyperlinks(list, url, sep) local html local function mkurl(p, t) if type(p) == "string" then return p:format(t) elseif type(p) == "function" then return p(t) else return '#' end end list = list or { } url = url or "%s" sep = sep or ", " for _, token in ipairs(list) do html = ( html and html .. sep or '' ) .. '<a href="%s">%s</a>' %{ mkurl(url, token), token } end return html or '' end --- LuCI Asterisk - International Direct Dialing Prefixes -- @type module idd = luci.util.class() --- Lookup the country name for the given IDD code. -- @param country String containing IDD code -- @return String containing the country name function idd.country(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then for _, v2 in ipairs(v[3]) do if v2 == tostring(c) then return v[1] end end elseif v[3] == tostring(c) then return v[1] end end end --- Lookup the country code for the given IDD code. -- @param country String containing IDD code -- @return Table containing the country code(s) function idd.cc(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then for _, v2 in ipairs(v[3]) do if v2 == tostring(c) then return type(v[2]) == "table" and v[2] or { v[2] } end end elseif v[3] == tostring(c) then return type(v[2]) == "table" and v[2] or { v[2] } end end end --- Lookup the IDD code(s) for the given country. -- @param idd String containing the country name -- @return Table containing the IDD code(s) function idd.idd(c) for _, v in ipairs(cc_idd.CC_IDD) do if v[1]:lower():match(c:lower()) then return type(v[3]) == "table" and v[3] or { v[3] } end end end --- Populate given CBI field with IDD codes. -- @param field CBI option object -- @return (nothing) function idd.cbifill(o) for i, v in ipairs(cc_idd.CC_IDD) do o:value("_%i" % i, util.pcdata(v[1])) end o.formvalue = function(...) local val = luci.cbi.Value.formvalue(...) if val:sub(1,1) == "_" then val = tonumber((val:gsub("^_", ""))) if val then return type(cc_idd.CC_IDD[val][3]) == "table" and cc_idd.CC_IDD[val][3] or { cc_idd.CC_IDD[val][3] } end end return val end o.cfgvalue = function(...) local val = luci.cbi.Value.cfgvalue(...) if val then val = tools.parse_list(val) for i, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then if v[3][1] == val[1] then return "_%i" % i end else if v[3] == val[1] then return "_%i" % i end end end end return val end end --- LuCI Asterisk - Country Code Prefixes -- @type module cc = luci.util.class() --- Lookup the country name for the given CC code. -- @param country String containing CC code -- @return String containing the country name function cc.country(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then for _, v2 in ipairs(v[2]) do if v2 == tostring(c) then return v[1] end end elseif v[2] == tostring(c) then return v[1] end end end --- Lookup the international dialing code for the given CC code. -- @param cc String containing CC code -- @return String containing IDD code function cc.idd(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then for _, v2 in ipairs(v[2]) do if v2 == tostring(c) then return type(v[3]) == "table" and v[3] or { v[3] } end end elseif v[2] == tostring(c) then return type(v[3]) == "table" and v[3] or { v[3] } end end end --- Lookup the CC code(s) for the given country. -- @param country String containing the country name -- @return Table containing the CC code(s) function cc.cc(c) for _, v in ipairs(cc_idd.CC_IDD) do if v[1]:lower():match(c:lower()) then return type(v[2]) == "table" and v[2] or { v[2] } end end end --- Populate given CBI field with CC codes. -- @param field CBI option object -- @return (nothing) function cc.cbifill(o) for i, v in ipairs(cc_idd.CC_IDD) do o:value("_%i" % i, util.pcdata(v[1])) end o.formvalue = function(...) local val = luci.cbi.Value.formvalue(...) if val:sub(1,1) == "_" then val = tonumber((val:gsub("^_", ""))) if val then return type(cc_idd.CC_IDD[val][2]) == "table" and cc_idd.CC_IDD[val][2] or { cc_idd.CC_IDD[val][2] } end end return val end o.cfgvalue = function(...) local val = luci.cbi.Value.cfgvalue(...) if val then val = tools.parse_list(val) for i, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then if v[2][1] == val[1] then return "_%i" % i end else if v[2] == val[1] then return "_%i" % i end end end end return val end end --- LuCI Asterisk - Dialzone -- @type module dialzone = luci.util.class() --- Parse a dialzone section -- @param zone Table containing the zone info -- @return Table with parsed information function dialzone.parse(z) if z['.name'] then return { trunks = tools.parse_list(z.uses), name = z['.name'], description = z.description or z['.name'], addprefix = z.addprefix, matches = tools.parse_list(z.match), intlmatches = tools.parse_list(z.international), countrycode = z.countrycode, localzone = z.localzone, localprefix = z.localprefix } end end --- Get a list of known dial zones -- @return Associative table of zones and table of zone names function dialzone.zones() local zones = { } local znames = { } uci:foreach("asterisk", "dialzone", function(z) zones[z['.name']] = dialzone.parse(z) znames[#znames+1] = z['.name'] end) return zones, znames end --- Get a specific dial zone -- @param name Name of the dial zone -- @return Table containing zone information function dialzone.zone(n) local zone uci:foreach("asterisk", "dialzone", function(z) if z['.name'] == n then zone = dialzone.parse(z) end end) return zone end --- Find uci section hash for given zone number -- @param idx Zone number -- @return String containing the uci hash pointing to the section function dialzone.ucisection(i) local hash local index = 1 i = tonumber(i) uci:foreach("asterisk", "dialzone", function(z) if not hash and index == i then hash = z['.name'] end index = index + 1 end) return hash end --- LuCI Asterisk - Voicemailbox -- @type module voicemail = luci.util.class() --- Parse a voicemail section -- @param zone Table containing the mailbox info -- @return Table with parsed information function voicemail.parse(z) if z.number and #z.number > 0 then local v = { id = '%s@%s' %{ z.number, z.context or 'default' }, number = z.number, context = z.context or 'default', name = z.name or z['.name'] or 'OpenWrt', zone = z.zone or 'homeloc', password = z.password or '0000', email = z.email or '', page = z.page or '', dialplans = { } } uci:foreach("asterisk", "dialplanvoice", function(s) if s.dialplan and #s.dialplan > 0 and s.voicebox == v.number then v.dialplans[#v.dialplans+1] = s.dialplan end end) return v end end --- Get a list of known voicemail boxes -- @return Associative table of boxes and table of box numbers function voicemail.boxes() local vboxes = { } local vnames = { } uci:foreach("asterisk", "voicemail", function(z) local v = voicemail.parse(z) if v then local n = '%s@%s' %{ v.number, v.context } vboxes[n] = v vnames[#vnames+1] = n end end) return vboxes, vnames end --- Get a specific voicemailbox -- @param number Number of the voicemailbox -- @return Table containing mailbox information function voicemail.box(n) local box n = n:gsub("@.+$","") uci:foreach("asterisk", "voicemail", function(z) if z.number == tostring(n) then box = voicemail.parse(z) end end) return box end --- Find all voicemailboxes within the given dialplan -- @param plan Dialplan name or table -- @return Associative table containing extensions mapped to mailbox info function voicemail.in_dialplan(p) local plan = type(p) == "string" and p or p.name local boxes = { } uci:foreach("asterisk", "dialplanvoice", function(s) if s.extension and #s.extension > 0 and s.dialplan == plan then local box = voicemail.box(s.voicebox) if box then boxes[s.extension] = box end end end) return boxes end --- Remove voicemailbox and associated extensions from config -- @param box Voicemailbox number or table -- @param ctx UCI context to use (optional) -- @return Boolean indicating success function voicemail.remove(v, ctx) ctx = ctx or uci local box = type(v) == "string" and v or v.number local ok1 = ctx:delete_all("asterisk", "voicemail", {number=box}) local ok2 = ctx:delete_all("asterisk", "dialplanvoice", {voicebox=box}) return ( ok1 or ok2 ) and true or false end --- LuCI Asterisk - MeetMe Conferences -- @type module meetme = luci.util.class() --- Parse a meetme section -- @param room Table containing the room info -- @return Table with parsed information function meetme.parse(r) if r.room and #r.room > 0 then local v = { room = r.room, pin = r.pin or '', adminpin = r.adminpin or '', description = r._description or '', dialplans = { } } uci:foreach("asterisk", "dialplanmeetme", function(s) if s.dialplan and #s.dialplan > 0 and s.room == v.room then v.dialplans[#v.dialplans+1] = s.dialplan end end) return v end end --- Get a list of known meetme rooms -- @return Associative table of rooms and table of room numbers function meetme.rooms() local mrooms = { } local mnames = { } uci:foreach("asterisk", "meetme", function(r) local v = meetme.parse(r) if v then mrooms[v.room] = v mnames[#mnames+1] = v.room end end) return mrooms, mnames end --- Get a specific meetme room -- @param number Number of the room -- @return Table containing room information function meetme.room(n) local room uci:foreach("asterisk", "meetme", function(r) if r.room == tostring(n) then room = meetme.parse(r) end end) return room end --- Find all meetme rooms within the given dialplan -- @param plan Dialplan name or table -- @return Associative table containing extensions mapped to room info function meetme.in_dialplan(p) local plan = type(p) == "string" and p or p.name local rooms = { } uci:foreach("asterisk", "dialplanmeetme", function(s) if s.extension and #s.extension > 0 and s.dialplan == plan then local room = meetme.room(s.room) if room then rooms[s.extension] = room end end end) return rooms end --- Remove meetme room and associated extensions from config -- @param room Voicemailbox number or table -- @param ctx UCI context to use (optional) -- @return Boolean indicating success function meetme.remove(v, ctx) ctx = ctx or uci local room = type(v) == "string" and v or v.number local ok1 = ctx:delete_all("asterisk", "meetme", {room=room}) local ok2 = ctx:delete_all("asterisk", "dialplanmeetme", {room=room}) return ( ok1 or ok2 ) and true or false end --- LuCI Asterisk - Dialplan -- @type module dialplan = luci.util.class() --- Parse a dialplan section -- @param plan Table containing the plan info -- @return Table with parsed information function dialplan.parse(z) if z['.name'] then local plan = { zones = { }, name = z['.name'], description = z.description or z['.name'] } -- dialzones for _, name in ipairs(tools.parse_list(z.include)) do local zone = dialzone.zone(name) if zone then plan.zones[#plan.zones+1] = zone end end -- voicemailboxes plan.voicemailboxes = voicemail.in_dialplan(plan) -- meetme conferences plan.meetmerooms = meetme.in_dialplan(plan) return plan end end --- Get a list of known dial plans -- @return Associative table of plans and table of plan names function dialplan.plans() local plans = { } local pnames = { } uci:foreach("asterisk", "dialplan", function(p) plans[p['.name']] = dialplan.parse(p) pnames[#pnames+1] = p['.name'] end) return plans, pnames end --- Get a specific dial plan -- @param name Name of the dial plan -- @return Table containing plan information function dialplan.plan(n) local plan uci:foreach("asterisk", "dialplan", function(p) if p['.name'] == n then plan = dialplan.parse(p) end end) return plan end
apache-2.0
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/GLViewImpl.lua
19
1142
-------------------------------- -- @module GLViewImpl -- @extend GLView -- @parent_module cc -------------------------------- -- -- @function [parent=#GLViewImpl] createWithRect -- @param self -- @param #string viewName -- @param #rect_table rect -- @param #float frameZoomFactor -- @return GLViewImpl#GLViewImpl ret (return value: cc.GLViewImpl) -------------------------------- -- -- @function [parent=#GLViewImpl] create -- @param self -- @param #string viewname -- @return GLViewImpl#GLViewImpl ret (return value: cc.GLViewImpl) -------------------------------- -- -- @function [parent=#GLViewImpl] createWithFullScreen -- @param self -- @param #string viewName -- @return GLViewImpl#GLViewImpl ret (return value: cc.GLViewImpl) -------------------------------- -- -- @function [parent=#GLViewImpl] setIMEKeyboardState -- @param self -- @param #bool bOpen -- @return GLViewImpl#GLViewImpl self (return value: cc.GLViewImpl) -------------------------------- -- -- @function [parent=#GLViewImpl] isOpenGLReady -- @param self -- @return bool#bool ret (return value: bool) return nil
mit
vipteam1/VIP_TEAM_EN11
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
satanevil/copy-creed
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
imashkan/HAULbot
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
tianxiawuzhei/cocos-quick-cpp
publibs/libzq/auto_buildings/api/ZQImageLoader.lua
2
1288
-------------------------------- -- @module ZQImageLoader -- @parent_module zq -------------------------------- -- -- @function [parent=#ZQImageLoader] load_image -- @param self -- @param #string path -- @param #string key -- @return SpriteFrame#SpriteFrame ret (return value: cc.SpriteFrame) -------------------------------- -- -- @function [parent=#ZQImageLoader] exist -- @param self -- @param #string plist -- @param #string frame -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ZQImageLoader] clear -- @param self -- @return ZQImageLoader#ZQImageLoader self (return value: zq.ZQImageLoader) -------------------------------- -- -- @function [parent=#ZQImageLoader] cache -- @param self -- @param #string plist -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ZQImageLoader] load_frame -- @param self -- @param #string plist -- @param #string frame -- @return SpriteFrame#SpriteFrame ret (return value: cc.SpriteFrame) -------------------------------- -- -- @function [parent=#ZQImageLoader] getInstance -- @param self -- @return ZQImageLoader#ZQImageLoader ret (return value: zq.ZQImageLoader) return nil
mit
dan-f/Soundpipe
modules/data/drip.lua
3
2416
sptbl["drip"] = { files = { module = "drip.c", header = "drip.h", example = "ex_drip.c", }, func = { create = "sp_drip_create", destroy = "sp_drip_destroy", init = "sp_drip_init", compute = "sp_drip_compute", }, params = { mandatory = { { name = "dettack", type = "SPFLOAT", description = "Period of time over which all sound is stopped.", default = 0.09 }, }, optional = { { name = "num_tubes", type = "SPFLOAT", description = "Number of units.", default = 10 }, { name = "amp", type = "SPFLOAT", description = "Amplitude.", default = 0.3 }, { name = "damp", type = "SPFLOAT", description ="The damping factor. Maximum value is 2.0.", default = 0.2 }, { name = "shake_max", type = "SPFLOAT", description = "The amount of energy to add back into the system.", default = 0 }, { name = "freq", type = "SPFLOAT", description ="Main resonant frequency.", default = 450 }, { name = "freq1", type = "SPFLOAT", description ="The first resonant frequency.", default = 600 }, { name = "freq2", type = "SPFLOAT", description ="The second resonant frequency.", default = 750 }, } }, modtype = "module", description = [[Water drop physical model Physical model of the sound of dripping water. When triggered, it will produce a droplet of water.]], ninputs = 1, noutputs = 1, inputs = { { name = "trig", description = "Trigger value. When non-zero, it will re-init the drip and create a drip sound." }, }, outputs = { { name = "out", description = "Stereo left output for drip." }, } }
mit
ZeroNoFun/Gmod-Aperture-science-laboratories
lua/aperture/sounds/portal_turret_sounds.lua
2
4958
--[[ CATAPULT SOUNDS ]] AddCSLuaFile() APERTURESCIENCE.TurretShoot = { channel = CHAN_WEAPON, name = "GASL.TurretShoot", level = 60, sound = { "npc/turret/turret_fire_4x_01.wav" , "npc/turret/turret_fire_4x_02.wav" , "npc/turret/turret_fire_4x_03.wav" }, volume = 1.0, pitch = 100, } sound.Add( APERTURESCIENCE.TurretShoot ) APERTURESCIENCE.TurretActivateVO = { channel = CHAN_VOICE, name = "GASL.TurretActivateVO", level = 70, sound = { "npc/turret_floor/turret_active_1.wav" , "npc/turret_floor/turret_active_2.wav" , "npc/turret_floor/turret_active_3.wav" , "npc/turret_floor/turret_active_4.wav" , "npc/turret_floor/turret_active_5.wav" , "npc/turret_floor/turret_active_6.wav" , "npc/turret_floor/turret_active_7.wav" , "npc/turret_floor/turret_active_8.wav" }, volume = 1.0, pitch = 100, } sound.Add( APERTURESCIENCE.TurretActivateVO ) APERTURESCIENCE.TurretActivate = { channel = CHAN_WEAPON, name = "GASL.TurretActivate", level = 60, sound = "npc/turret_floor/active.wav", volume = 1.0, pitch = 100, } sound.Add( APERTURESCIENCE.TurretActivate ) APERTURESCIENCE.TurretPing = { channel = CHAN_WEAPON, name = "GASL.TurretPing", level = 60, sound = "npc/turret_floor/ping.wav", volume = 1.0, pitch = 100, } sound.Add( APERTURESCIENCE.TurretPing ) APERTURESCIENCE.TurretDeploy = { channel = CHAN_WEAPON, name = "GASL.TurretDeploy", level = 70, sound = "npc/turret_floor/deploy.wav", volume = 1.0, pitch = 100, } sound.Add( APERTURESCIENCE.TurretDeploy ) APERTURESCIENCE.TurretSearth = { channel = CHAN_VOICE, name = "GASL.TurretSearth", level = 75, sound = { "npc/turret_floor/turret_search_1.wav" , "npc/turret_floor/turret_search_2.wav" , "npc/turret_floor/turret_search_3.wav" , "npc/turret_floor/turret_search_4.wav" }, volume = 1.0, pitch = 100, } sound.Add( APERTURESCIENCE.TurretSearth ) APERTURESCIENCE.TurretAutoSearth = { channel = CHAN_VOICE, name = "GASL.TurretAutoSearth", level = 75, sound = { "npc/turret_floor/turret_autosearch_1.wav" , "npc/turret_floor/turret_autosearch_2.wav" , "npc/turret_floor/turret_autosearch_3.wav" , "npc/turret_floor/turret_autosearch_4.wav" , "npc/turret_floor/turret_autosearch_5.wav" , "npc/turret_floor/turret_autosearch_6.wav" }, volume = 1.0, pitch = 100, } sound.Add( APERTURESCIENCE.TurretAutoSearth ) APERTURESCIENCE.TurretRetract = { channel = CHAN_WEAPON, name = "GASL.TurretRetract", level = 60, sound = "npc/turret_floor/retract.wav", volume = 1.0, pitch = 100, } sound.Add( APERTURESCIENCE.TurretRetract ) APERTURESCIENCE.TurretPickup = { channel = CHAN_VOICE, name = "GASL.TurretPickup", level = 60, sound = { "npc/turret_floor/turret_pickup_1.wav" , "npc/turret_floor/turret_pickup_2.wav" , "npc/turret_floor/turret_pickup_3.wav" , "npc/turret_floor/turret_pickup_4.wav" , "npc/turret_floor/turret_pickup_5.wav" , "npc/turret_floor/turret_pickup_6.wav" , "npc/turret_floor/turret_pickup_7.wav" , "npc/turret_floor/turret_pickup_8.wav" , "npc/turret_floor/turret_pickup_9.wav" , "npc/turret_floor/turret_pickup_10.wav" }, volume = 1.0, pitch = 100, } sound.Add( APERTURESCIENCE.TurretPickup ) APERTURESCIENCE.TurretLaunch = { channel = CHAN_VOICE, name = "GASL.TurretLaunch", level = 60, sound = { "npc/turret/turretlaunched01.wav" , "npc/turret/turretlaunched02.wav" , "npc/turret/turretlaunched03.wav" , "npc/turret/turretlaunched04.wav" , "npc/turret/turretlaunched05.wav" , "npc/turret/turretlaunched06.wav" , "npc/turret/turretlaunched07.wav" , "npc/turret/turretlaunched08.wav" , "npc/turret/turretlaunched09.wav" , "npc/turret/turretlaunched010.wav" , "npc/turret/turretlaunched011.wav" }, volume = 1.0, pitch = 100, } sound.Add( APERTURESCIENCE.TurretLaunch ) APERTURESCIENCE.TurretBurn = { channel = CHAN_VOICE, name = "GASL.TurretBurn", level = 60, sound = { "npc/turret/turretshotbylaser01.wav" , "npc/turret/turretshotbylaser02.wav" , "npc/turret/turretshotbylaser03.wav" , "npc/turret/turretshotbylaser04.wav" , "npc/turret/turretshotbylaser05.wav" , "npc/turret/turretshotbylaser06.wav" , "npc/turret/turretshotbylaser07.wav" , "npc/turret/turretshotbylaser08.wav" , "npc/turret/turretshotbylaser09.wav" , "npc/turret/turretshotbylaser10.wav" }, volume = 1.0, pitch = 100, } sound.Add( APERTURESCIENCE.TurretBurn ) APERTURESCIENCE.TurretWithnessdeath = { channel = CHAN_VOICE, name = "GASL.TurretWithnessdeath", level = 60, sound = { "npc/turret/turretwitnessdeath01.wav" , "npc/turret/turretwitnessdeath02.wav" , "npc/turret/turretwitnessdeath03.wav" , "npc/turret/turretwitnessdeath04.wav" , "npc/turret/turretwitnessdeath05.wav" , "npc/turret/turretwitnessdeath06.wav" , "npc/turret/turretwitnessdeath07.wav" , "npc/turret/turretwitnessdeath08.wav" , "npc/turret/turretwitnessdeath09.wav" , "npc/turret/turretwitnessdeath10.wav" }, volume = 1.0, pitch = 100, } sound.Add( APERTURESCIENCE.TurretWithnessdeath )
mit
abasshacker/abbasone
plugins/spammer.lua
86
65983
local function run(msg) if msg.text == "[!/]killwili" then return "".. [[ kose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nv ]] end end return { description = "Spamms the group fastly", usage = "!fuck or Fuckgp or Fuck : send 10000 Spams to the group", patterns = { "^[!/]fuck$", "^fuckgp$", "^Fuck$", "^spam$", "^Fuckgp$", }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
Arashbrsh/a1wez-
plugins/sudo.lua
359
1878
function run_sh(msg) name = get_name(msg) text = '' -- if config.sh_enabled == false then -- text = '!sh command is disabled' -- else -- if is_sudo(msg) then -- bash = msg.text:sub(4,-1) -- text = run_bash(bash) -- else -- text = name .. ' you have no power here!' -- end -- end if is_sudo(msg) then bash = msg.text:sub(4,-1) text = run_bash(bash) else text = name .. ' you have no power here!' end return text end function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function on_getting_dialogs(cb_extra,success,result) if success then local dialogs={} for key,value in pairs(result) do for chatkey, chat in pairs(value.peer) do print(chatkey,chat) if chatkey=="id" then table.insert(dialogs,chat.."\n") end if chatkey=="print_name" then table.insert(dialogs,chat..": ") end end end send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false) end end function run(msg, matches) if not is_sudo(msg) then return "You aren't allowed!" end local receiver = get_receiver(msg) if string.match(msg.text, '!sh') then text = run_sh(msg) send_msg(receiver, text, ok_cb, false) return end if string.match(msg.text, '!cpu') then text = run_bash('uname -snr') .. ' ' .. run_bash('whoami') text = text .. '\n' .. run_bash('top -b |head -2') send_msg(receiver, text, ok_cb, false) return end if matches[1]=="Get dialogs" then get_dialog_list(on_getting_dialogs,{get_receiver(msg)}) return end end return { description = "shows cpuinfo", usage = "!cpu", patterns = {"^!cpu", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
UB12/y_r
plugins/sudo.lua
359
1878
function run_sh(msg) name = get_name(msg) text = '' -- if config.sh_enabled == false then -- text = '!sh command is disabled' -- else -- if is_sudo(msg) then -- bash = msg.text:sub(4,-1) -- text = run_bash(bash) -- else -- text = name .. ' you have no power here!' -- end -- end if is_sudo(msg) then bash = msg.text:sub(4,-1) text = run_bash(bash) else text = name .. ' you have no power here!' end return text end function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function on_getting_dialogs(cb_extra,success,result) if success then local dialogs={} for key,value in pairs(result) do for chatkey, chat in pairs(value.peer) do print(chatkey,chat) if chatkey=="id" then table.insert(dialogs,chat.."\n") end if chatkey=="print_name" then table.insert(dialogs,chat..": ") end end end send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false) end end function run(msg, matches) if not is_sudo(msg) then return "You aren't allowed!" end local receiver = get_receiver(msg) if string.match(msg.text, '!sh') then text = run_sh(msg) send_msg(receiver, text, ok_cb, false) return end if string.match(msg.text, '!cpu') then text = run_bash('uname -snr') .. ' ' .. run_bash('whoami') text = text .. '\n' .. run_bash('top -b |head -2') send_msg(receiver, text, ok_cb, false) return end if matches[1]=="Get dialogs" then get_dialog_list(on_getting_dialogs,{get_receiver(msg)}) return end end return { description = "shows cpuinfo", usage = "!cpu", patterns = {"^!cpu", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
mobarski/sandbox
scite/old/wscite_zzz/lexers/notused/crystal.lua
5
4723
-- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE. -- Copyright 2017 Michel Martens. -- Crystal LPeg lexer (based on Ruby). local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local M = {_NAME = 'crystal'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local line_comment = '#' * l.nonnewline_esc^0 local comment = token(l.COMMENT, line_comment) local delimiter_matches = {['('] = ')', ['['] = ']', ['{'] = '}'} local literal_delimitted = P(function(input, index) local delimiter = input:sub(index, index) if not delimiter:find('[%w\r\n\f\t ]') then -- only non alpha-numerics local match_pos, patt if delimiter_matches[delimiter] then -- Handle nested delimiter/matches in strings. local s, e = delimiter, delimiter_matches[delimiter] patt = l.delimited_range(s..e, false, false, true) else patt = l.delimited_range(delimiter) end match_pos = lpeg.match(patt, input, index) return match_pos or #input + 1 end end) -- Strings. local cmd_str = l.delimited_range('`') local sq_str = l.delimited_range("'") local dq_str = l.delimited_range('"') local heredoc = '<<' * P(function(input, index) local s, e, indented, _, delimiter = input:find('(%-?)(["`]?)([%a_][%w_]*)%2[\n\r\f;]+', index) if s == index and delimiter then local end_heredoc = (#indented > 0 and '[\n\r\f]+ *' or '[\n\r\f]+') local _, e = input:find(end_heredoc..delimiter, e) return e and e + 1 or #input + 1 end end) -- TODO: regex_str fails with `obj.method /patt/` syntax. local regex_str = #P('/') * l.last_char_includes('!%^&*([{-=+|:;,?<>~') * l.delimited_range('/', true, false) * S('iomx')^0 local string = token(l.STRING, (sq_str + dq_str + heredoc + cmd_str) * S('f')^-1) + token(l.REGEX, regex_str) local word_char = l.alnum + S('_!?') -- Numbers. local dec = l.digit^1 * ('_' * l.digit^1)^0 * S('ri')^-1 local bin = '0b' * S('01')^1 * ('_' * S('01')^1)^0 local integer = S('+-')^-1 * (bin + l.hex_num + l.oct_num + dec) -- TODO: meta, control, etc. for numeric_literal. local numeric_literal = '?' * (l.any - l.space) * -word_char local number = token(l.NUMBER, l.float * S('ri')^-1 + integer + numeric_literal) -- Keywords. local keyword = token(l.KEYWORD, word_match({ 'alias', 'begin', 'break', 'case', 'class', 'def', 'defined?', 'do', 'else', 'elsif', 'end', 'ensure', 'false', 'for', 'if', 'in', 'module', 'next', 'nil', 'not', 'redo', 'rescue', 'retry', 'return', 'self', 'super', 'then', 'true', 'undef', 'unless', 'until', 'when', 'while', 'yield', '__FILE__', '__LINE__' }, '?!')) -- Functions. local func = token(l.FUNCTION, word_match({ 'abort', 'at_exit', 'caller', 'delay', 'exit', 'fork', 'future', 'get_stack_top', 'gets', 'lazy', 'loop', 'main', 'p', 'print', 'printf', 'puts', 'raise', 'rand', 'read_line', 'require', 'sleep', 'spawn', 'sprintf', 'system', 'with_color', -- Macros 'assert_responds_to', 'debugger', 'parallel', 'pp', 'record', 'redefine_main' }, '?!')) * -S('.:|') -- Identifiers. local word = (l.alpha + '_') * word_char^0 local identifier = token(l.IDENTIFIER, word) -- Variables. local global_var = '$' * (word + S('!@L+`\'=~/\\,.;<>_*"$?:') + l.digit + '-' * S('0FadiIKlpvw')) local class_var = '@@' * word local inst_var = '@' * word local variable = token(l.VARIABLE, global_var + class_var + inst_var) -- Symbols. local symbol = token('symbol', ':' * P(function(input, index) if input:sub(index - 2, index - 2) ~= ':' then return index end end) * (word_char^1 + sq_str + dq_str)) -- Operators. local operator = token(l.OPERATOR, S('!%^&*()[]{}-=+/|:;.,?<>~')) M._rules = { {'whitespace', ws}, {'keyword', keyword}, {'function', func}, {'identifier', identifier}, {'comment', comment}, {'string', string}, {'number', number}, {'variable', variable}, {'symbol', symbol}, {'operator', operator}, } M._tokenstyles = { symbol = l.STYLE_CONSTANT } local function disambiguate(text, pos, line, s) return line:sub(1, s - 1):match('^%s*$') and not text:sub(1, pos - 1):match('\\[ \t]*\r?\n$') and 1 or 0 end M._foldsymbols = { _patterns = {'%l+', '[%(%)%[%]{}]', '#'}, [l.KEYWORD] = { begin = 1, class = 1, def = 1, ['do'] = 1, ['for'] = 1, ['module'] = 1, case = 1, ['if'] = disambiguate, ['while'] = disambiguate, ['unless'] = disambiguate, ['until'] = disambiguate, ['end'] = -1 }, [l.OPERATOR] = { ['('] = 1, [')'] = -1, ['['] = 1, [']'] = -1, ['{'] = 1, ['}'] = -1 }, [l.COMMENT] = { ['#'] = l.fold_line_comments('#') } } return M
mit
Zefiros-Software/ZPM
src/cli/install.lua
1
3301
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- 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. -- -- @endcond --]] local function _installZPM() printf("%%{greenbg white bright}Installing ZPM version '%s'!", zpm._VERSION) if not zpm or (zpm and not zpm.__isLoaded) then zpm.onLoad() zpm.__isLoaded = true end zpm.loader.install:install() end if zpm.env.getBinDirectory() ~= _PREMAKE_DIR then newaction { trigger = "install", description = "Installs packages", execute = function() local help = false if (#_ARGS == 1 and _ARGS[1] == "zpm") then _installZPM() else help = true end if help or zpm.cli.showHelp() then printf("%%{yellow}Show action must be one of the following commands:\n" .. " - zpm \t\tInstalls ZPM") end end } end newaction { trigger = "update", description = "Updates ZPM", execute = function() local help = false if #_ARGS == 1 and _ARGS[1] == "self" then zpm.loader.install:update() --zpm.loader.modules:update("*/*") elseif #_ARGS == 1 and _ARGS[1] == "bootstrap" then premake.action.call("update-bootstrap") elseif #_ARGS == 1 and _ARGS[1] == "registry" then premake.action.call("update-registry") elseif #_ARGS == 1 and _ARGS[1] == "zpm" then premake.action.call("update-zpm") elseif #_ARGS == 1 and _ARGS[1] == "modules" then zpm.loader.modules:update("*/*") else help = true end if help or zpm.cli.showHelp() then printf("%%{yellow}Show action must be one of the following commands:\n" .. " - self \tUpdates everything except modules\n" .. " - bootstrap \tUpdates the bootstrap module loader\n" .. " - registry \tUpdates the ZPM library registry\n" .. " - zpm \t\tUpdates ZPM itself\n" .. " - modules \tUpdates the installed modules") end end } if _ACTION == "install" or _ACTION == "update" then zpm.util.disableMainScript() end
mit
cleme1mp/dotfiles
hammerspoon/modes/indicator.lua
2
3992
function timer_indicator(timelen) if not indicator_used then indicator_used = hs.drawing.rectangle({0,0,0,0}) indicator_used:setStroke(false) indicator_used:setFill(true) indicator_used:setFillColor(osx_red) indicator_used:setAlpha(0.35) indicator_used:setLevel(hs.drawing.windowLevels.status) indicator_used:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces+hs.drawing.windowBehaviors.stationary) indicator_used:show() indicator_left = hs.drawing.rectangle({0,0,0,0}) indicator_left:setStroke(false) indicator_left:setFill(true) indicator_left:setFillColor(osx_green) indicator_left:setAlpha(0.35) indicator_left:setLevel(hs.drawing.windowLevels.status) indicator_left:setBehavior(hs.drawing.windowBehaviors.canJoinAllSpaces+hs.drawing.windowBehaviors.stationary) indicator_left:show() totaltime=timelen if totaltime > 45*60 then time_interval = 5 else time_interval = 1 end indict_timer = hs.timer.doEvery(time_interval,updateused) used_slice = 0 else indict_timer:stop() indicator_used:delete() indicator_used=nil indicator_left:delete() indicator_left=nil end end function updateused() local mainScreen = hs.screen.mainScreen() local mainRes = mainScreen:fullFrame() local timeslice = mainRes.w/(60*totaltime/time_interval) used_slice = used_slice + timeslice*time_interval if used_slice > mainRes.w then indict_timer:stop() indicator_used:delete() indicator_used=nil indicator_left:delete() indicator_left=nil hs.notify.new({title="Time("..totaltime.." mins) is up!", informativeText="Now is "..os.date("%X")}):send() else left_slice = mainRes.w - used_slice local used_rect = hs.geometry.rect(0,mainRes.h-5,used_slice,5) local left_rect = hs.geometry.rect(used_slice,mainRes.h-5,left_slice,5) indicator_used:setFrame(used_rect) indicator_left:setFrame(left_rect) end end timerM = hs.hotkey.modal.new() table.insert(modal_list, timerM) function timerM:entered() modal_stat('timer',tomato) if hotkeytext then hotkeytext:delete() hotkeytext=nil hotkeybg:delete() hotkeybg=nil end end function timerM:exited() if dock_launched then modal_stat('dock',black) else modal_bg:hide() modal_show:hide() end if idle_to_which == "hide" then modal_bg:hide() modal_show:hide() end if hotkeytext then hotkeytext:delete() hotkeytext=nil hotkeybg:delete() hotkeybg=nil end end timerM:bind('', 'escape', function() timerM:exit() end) timerM:bind('', 'Q', function() timerM:exit() end) timerM:bind('', 'tab', function() showavailableHotkey() end) timerM:bind('', '1', '10 minute countdown', function() timer_indicator(10) timerM:exit() end) timerM:bind('', '2', '20 minute countdown', function() timer_indicator(20) timerM:exit() end) timerM:bind('', '3', '30 minute countdown', function() timer_indicator(30) timerM:exit() end) timerM:bind('', '4', '40 minute countdown', function() timer_indicator(40) timerM:exit() end) timerM:bind('', '5', '50 minute countdown', function() timer_indicator(50) timerM:exit() end) timerM:bind('', '6', '60 minute countdown', function() timer_indicator(60) timerM:exit() end) timerM:bind('', '7', '70 minute countdown', function() timer_indicator(70) timerM:exit() end) timerM:bind('', '8', '80 minute countdown', function() timer_indicator(80) timerM:exit() end) timerM:bind('', '9', '90 minute countdown', function() timer_indicator(90) timerM:exit() end) timerM:bind('', '0', '5 minute countdown', function() timer_indicator(5) timerM:exit() end) timerM:bind('', 'return', '25 minute countdown', function() timer_indicator(25) timerM:exit() end)
mit
tomkdir/SimplifyReader
library_youku/src/main/res/raw/aes.lua
130
3338
---------------------- bit utils bit={data32={}} for i=1,32 do bit.data32[i]=2^(32-i) end function bit.d2b(arg) local tr={} for i=1,32 do if arg >= bit.data32[i] then tr[i]=1 arg=arg-bit.data32[i] else tr[i]=0 end end return tr end --bit:d2b function bit.b2d(arg) local nr=0 for i=1,32 do if arg[i] ==1 then nr=nr+2^(32-i) end end return nr end --bit:b2d function bit._xor(a,b) local op1=bit.d2b(a) local op2=bit.d2b(b) local r={} for i=1,32 do if op1[i]==op2[i] then r[i]=0 else r[i]=1 end end return bit.b2d(r) end --bit:xor function bit._and(a,b) local op1=bit.d2b(a) local op2=bit.d2b(b) local r={} for i=1,32 do if op1[i]==1 and op2[i]==1 then r[i]=1 else r[i]=0 end end return bit.b2d(r) end --bit:_and function bit._or(a,b) local op1=bit.d2b(a) local op2=bit.d2b(b) local r={} for i=1,32 do if op1[i]==1 or op2[i]==1 then r[i]=1 else r[i]=0 end end return bit.b2d(r) end --bit:_or function bit._not(a) local op1=bit.d2b(a) local r={} for i=1,32 do if op1[i]==1 then r[i]=0 else r[i]=1 end end return bit.b2d(r) end --bit:_not function bit._rshift(a,n) local op1=bit.d2b(a) local r=bit.d2b(0) if n < 32 and n > 0 then for i=1,n do for i=31,1,-1 do op1[i+1]=op1[i] end op1[1]=0 end r=op1 end return bit.b2d(r) end --bit:_rshift function bit._lshift(a,n) local op1=bit.d2b(a) local r=bit.d2b(0) if n < 32 and n > 0 then for i=1,n do for i=1,31 do op1[i]=op1[i+1] end op1[32]=0 end r=op1 end return bit.b2d(r) end --bit:_lshift function bit.print(ta) local sr="" for i=1,32 do sr=sr..ta[i] end print(sr) end -------------------------------- core y_key = {1206625642, 1092691841, 3888211297, 1403752353} t_key = {768304513, 3648063403, 1200350539, 1135324489} y_live_key = {2380375339, 3372821835, 757854091, 3417384251} t_live_key = {1307283402, 3415975219, 130748267, 1094264761} function getConfused(flag) local ftr = math.log10(1000); local ftr2 = math.log10(100); local key = {}; if flag==0 then key = y_key; elseif flag == 1 then key = t_key; elseif flag == 2 then key = y_live_key; elseif flag == 3 then key = t_live_key; end local a = math.max(key[1], ftr); local b = math.min(key[2], ftr2); local c = math.max(key[3], ftr); local d = math.min(key[4], ftr2); return a, b, c, d; end function doDec(ciphertxt, len, flag) dc = luajava.newInstance("com.decapi.Decryptions"); local L, l, R, r = getConfused(flag); ret = dc:AESDec(ciphertxt, len, math.btan2(L, l, R, r)); return ret; end function doEnc(plaintxt, flag) ec = luajava.newInstance("com.decapi.Decryptions"); local L, l, R, r = getConfused(flag); ret = ec:AESEnc(plaintxt, math.btan2(L, l, R, r)); return ret; end
apache-2.0
meirfaraj/tiproject
finance/src/ui/math/discrete/hypergeometric/hypergeometricsplcalc.lua
1
11711
-------------------------------------------------------------------------- -- loi hypergeometrique -- -------------------------------------------------------------------------- LoiHypergeometriqueSplCalc = Discrete3Params(LOI_HYPERGEOMETRIQUE_1VAR_TITLE_ID,LOI_HYPERGEOMETRIQUE_1VAR_HEADER_ID) function LoiHypergeometriqueSplCalc:checkValidity(N,n,p,k1,op1,op2,k2) if tostring(op1)=="none" and tostring(op2)=="none" then return false, ASTxt(NOTHING_TO_DO_ID).."\n" end if tostring(k2)=="" then return false, ASTxt(NOTHING_TO_DO_ID).."\n" end return true,"" end function LoiHypergeometriqueSplCalc:performEx(n,p) local calc = tostring(n).."*("..tostring(p)..")" local result1,err1 = math.evalStr(tostring(calc)) local result1b,err1b = math.evalStr("approx("..tostring(calc)..")") local res = "\\0el {E(X)="..tostring(calc).."}" if err1 then res = res.."ERROR:"..tostring(err1).."\n" end if err1b then res = res.."ERROR:"..tostring(err1b).."\n" end res = res.."\\0el {="..tostring(result1).."="..tostring(result1b).."}" return res end function LoiHypergeometriqueSplCalc:performVx(N,n,p) local calc = tostring(n).."*("..tostring(p)..")*(1-("..tostring(p).."))*(("..tostring(N).."-"..tostring(n)..")/("..tostring(N).."-1))" local result1,err1 = math.evalStr(tostring(calc)) local result1b,err1b = math.evalStr("approx("..tostring(calc)..")") local res = "\\0el {V(X)="..tostring(calc).."}" if err1 then res = res.."ERROR:"..tostring(err1).."\n" end if err1b then res = res.."ERROR:"..tostring(err1b).."\n" end res = res.."\\0el {="..tostring(result1).."="..tostring(result1b).."}" return res end function LoiHypergeometriqueSplCalc:performEqual(N,n,p,k2) local pstr = "("..tostring(p)..")" local pNstr = "("..tostring(pstr).."*"..tostring(N)..")" local qNstr = "((1-"..tostring(pstr)..")*"..tostring(N)..")" local nlessk = "("..tostring(n).."-"..tostring(k2)..")" local res = "\\0el {P(X="..tostring(k2)..")=".. "(C"..tostring(pNstr).."^"..tostring(k2).."*".. "C"..tostring(qNstr).."^"..tostring(nlessk)..")/".. "C"..tostring(N).."^"..tostring(n).."=".. "((("..tostring(pNstr).."!)/(("..tostring(pNstr).."-"..tostring(k2)..")!*"..tostring(k2).."!))*".. "(("..tostring(qNstr).."!)/(("..tostring(qNstr).."-"..tostring(nlessk)..")!*"..tostring(nlessk).."!)))/".. "(("..tostring(N).."!)/(("..tostring(N).."-"..tostring(n)..")!*"..tostring(n).."!))}" local calc1a="("..tostring(pNstr).."!)/(("..tostring(pNstr).."-"..tostring(k2)..")!*"..tostring(k2).."!)" local calc1b="("..tostring(qNstr).."!)/(("..tostring(qNstr).."-"..tostring(nlessk)..")!*"..tostring(nlessk).."!)" local calc1c="("..tostring(N).."!)/(("..tostring(N).."-"..tostring(n)..")!*"..tostring(n).."!)" local result1,err1 = math.evalStr(tostring(calc1a)) local result2,err2 = math.evalStr(tostring(calc1b)) local result3,err3 = math.evalStr(tostring(calc1c)) if err1 then res = res.."ERROR:"..tostring(err1).."\n" end if err2 then res = res.."ERROR:"..tostring(err2).."\n" end if err3 then res = res.."ERROR:"..tostring(err3).."\n" end local calc2 = "((("..tostring(result1)..")*("..tostring(result2).."))/("..tostring(result3).."))" res=res.."=\\0el {"..tostring(calc2).."}" local result4,err4 = math.evalStr(tostring(calc2)) local result4b,err4b = math.evalStr("approx("..tostring(calc2)..")") if err4 then res = res.."ERROR:"..tostring(err4).."\n" end if err4b then res = res.."ERROR:"..tostring(err4b).."\n" end res=res.."=\\0el {"..tostring(result4).."="..tostring(result4b).."}" return res,result4 end function LoiHypergeometriqueSplCalc:performGreaterOrEqual(N,n,p,k2) local res = "\\0el {P(X>="..tostring(k2)..")} = " if tonumber(n)~=nil and tonumber(k2)~=nil then if (tonumber(n)-tonumber(k2)>(tonumber(n)/2)) then res = res .. "\\0el {=1-P(X<="..(tostring(k2)-1)..")}\n" local k3=tonumber(k2)-1 local demRes,value = self:performSmallerOrEqual(N,n,p,k3) res = res .. "\\0el {P(X<="..tostring(k3)..")="..tostring(value).."} =>\n" local result1,err1 = math.evalStr("1-"..tostring(value)) res = res .. "\\0el {1-P(X<="..(tostring(k2)-1)..")="..tostring(result1) if err1 then res = res.."ERROR:"..tostring(err1).."\n" end result1,err1 = math.evalStr("approx(1-"..tostring(value)..")") res = res .. "="..tostring(result1).."}\n" res = res .. ASTxt(DEMONSTRATION_ID).."\n" res = res .. tostring(demRes) return res end end res= res.."\\0el {∑(P(X=i),i,"..tostring(k2)..","..tostring(n)..")}\n" local details1 ="" local details2 ="" if tonumber(n)~=nil and (tonumber(k2)~=nil) then for i=tonumber(k2),tonumber(n) do local dem,val=self:performEqual(N,n,p,i) if(i>tonumber(k2)) then details1=details1.."+" end details1=details1..tostring(val) details2= details2..tostring(dem).."\n" end end local result1,err1 = math.evalStr(details1) res = res .. "=\\0el {"..tostring(details1)..")="..tostring(result1).."}" if err1 then res = res.."ERROR:"..tostring(err1).."\n" end result1,err1 = math.evalStr("approx("..details1..")") res = res .. "=\\0el {"..tostring(result1).."}" if err1 then res = res.."ERROR:"..tostring(err1).."\n" end res = res .."\n".. details2 return res end function LoiHypergeometriqueSplCalc:performGreater(N,n,p,k2) local k3 = "" if(tonumber(k2)~=nil)then k3 = tonumber(k2)+1 else k3 = "("..tostring(k2).."+1)" end local res = "\\0el {P(X>"..tostring(k2)..")=P(X>="..tostring(k3).."}\n" res = res..self:performGreaterOrEqual(N,n,p,k3) return res end function LoiHypergeometriqueSplCalc:performSmallerOrEqual(n,p,k2) local res = "\\0el {P(X<="..tostring(k2)..")} = " if tonumber(n)~=nil and tonumber(k2)~=nil then if (tonumber(n)-tonumber(k2)<(tonumber(n)/2)) then res = res .. "\\0el {=1-P(X>="..(tostring(k2)+1)..")}\n" local calc = "binomCdf("..tostring(n)..",("..tostring(p).."),"..tostring(tonumber(k2)+1)..","..tostring(n)..")" local result1,err1 = math.evalStr(tostring(calc)) if err1 then res = res.."ERROR:"..tostring(err1).."\n" end res = res .. "\\0el {P(X>="..(tostring(k2)+1)..")="..tostring(result1).."} =>\n" result1,err1 = math.evalStr("1-"..tostring(calc)) res = res .. "\\0el {1-P(X>="..(tostring(k2)+1)..")="..tostring(result1) if err1 then res = res.."ERROR:"..tostring(err1).."\n" end result1,err1 = math.evalStr("approx(1-"..tostring(calc)..")") res = res .. "="..tostring(result1).."}\n" res = res .. ASTxt(DEMONSTRATION_ID).."\n" res = res .. self:performGreaterOrEqual(n,p,k2) end end res= res.."\\0el {∑(P(X=i),i,0,"..tostring(k2)..")}\n" if (tonumber(k2)~=nil) then for i=0,tonumber(k2) do res= res..self:performEqual(N,n,p,i).."\n" end end return res end function LoiHypergeometriqueSplCalc:performSmaller(n,p,k2) local k3 = "" if(tonumber(k2)~=nil)then k3 = tonumber(k2)-1 else k3 = "("..tostring(k2).."-1)" end local res = "\\0el {P(X<"..tostring(k2).."=P(X<="..tostring(k3).."}\n" res = res..self:performSmallerOrEqual(n,p,k3) return res end function LoiHypergeometriqueSplCalc:performBetween(n,p,k1,op1,op2,k2) local res="\\0el {P("..tostring(k1)..tostring(op1).."X"..tostring(op2)..tostring(k2)..")=" --optimise if possible if (tonumber(n)~=nil and tonumber(k1)~=nil and tonumber(k2)~=nil) then -- check witch calv give less calculation: -- k2-k1 end local k3 = k1 local k4 = k2 local reprintEquality = false if op1=="<" then if tonumber(k1)~=nil then k3 = tonumber(k1) - 1 else k3 = tostring(k1).. "-1" end reprintEquality = true end if op2=="<" then if tonumber(k2)~=nil then k4 = tonumber(k2) + 1 else k4 = tostring(k2).. "+1" end reprintEquality = true end if reprintEquality then res=res.."\\0el {=P("..tostring(k3).."<=X<="..tostring(k4)..")=" end local calc = "binomCdf("..tostring(n)..",("..tostring(p).."),"..tostring(k3)..","..tostring(k4)..")" local result1,err1 = math.evalStr(tostring(calc)) res=res..tostring(result1).."}\n" if err1 then res = res.."ERROR:"..tostring(err1).."\n" end local calc2a = "binomCdf("..tostring(n)..",("..tostring(p).."),0,"..tostring(k3)..")" local calc2b = "binomCdf("..tostring(n)..",("..tostring(p).."),"..tostring(k4)..","..tostring(n)..")" local result2a,err2a = math.evalStr(tostring(calc2a)) local result2b,err2b = math.evalStr(tostring(calc2b)) res=res.."\\0el {=P(X<="..tostring(k4)..")-P(X<="..tostring(k3)..")="..tostring(result2b).."-"..tostring(result2a).."="..tostring(result1).."}\n" if err2a then res = res.."ERROR:"..tostring(err2a).."\n" end if err2b then res = res.."ERROR:"..tostring(err2b).."\n" end res = res..self:performSmallerOrEqual(n,p,k3).."\n" res = res..self:performSmallerOrEqual(n,p,k4).."\n" return res end function LoiHypergeometriqueSplCalc:performHNnP(N,n,p,k1,op1,op2,k2) local isValid,errtxt = self:checkValidity(N,n,p,k1,op1,op2,k2) if (not isValid) then return errtxt end if (op2=="=") then return self:performEqual(N,n,p,k2) end if (op1=="<" or op1=="<=") and (op2=="<" or op2=="<=") then return self:performBetween(N,n,p,k1,op1,op2,k2) end if (op2=="<" ) then return self:performSmaller(N,n,p,k2) end if (op2=="<=") then return self:performSmallerOrEqual(N,n,p,k2) end if (op2==">") then return self:performGreater(N,n,p,k2) end if (op2==">=") then return self:performGreaterOrEqual(N,n,p,k2) end return ASTxt(NOT_SUPPORTED_ID) end function LoiHypergeometriqueSplCalc:perform() print("LoiHypergeometriqueSplCalc:perform") self.font ={"sansserif", "r", 10} local bn,sn,p,k1,compare1,compare2,k2 =self:extractTxt() self.operation="" if (tostring(bn)=="nil") or tostring(bn)=="" then return self.operation end if (tostring(sn)=="nil") or tostring(sn)=="" then return self.operation end if (tostring(p)=="nil") or tostring(p)=="" then return self.operation end local ex = self:performEx(sn,p) local vx = self:performVx(bn,sn,p) local exVx=tostring(ex).."\n"..tostring(vx) self.operation=exVx if (tostring(k1)=="nil") then return self.operation end if (tostring(k2)=="nil") or tostring(k2)=="" then return self.operation end if (tostring(compare1)=="nil") or tostring(compare1)=="" then return self.operation end if (tostring(compare2)=="nil") or tostring(compare2)=="" then return self.operation end self.operation=self:performHNnP(bn,sn,p,k1,compare1,compare2,k2).."\n"..tostring(exVx) self:invalidate() return self.operation end
apache-2.0
LuaDist2/oil
lua/loop/base.lua
15
3399
-------------------------------------------------------------------------------- ---------------------- ## ##### ##### ###### ----------------------- ---------------------- ## ## ## ## ## ## ## ----------------------- ---------------------- ## ## ## ## ## ###### ----------------------- ---------------------- ## ## ## ## ## ## ----------------------- ---------------------- ###### ##### ##### ## ----------------------- ---------------------- ----------------------- ----------------------- Lua Object-Oriented Programming ------------------------ -------------------------------------------------------------------------------- -- Project: LOOP - Lua Object-Oriented Programming -- -- Release: 2.3 beta -- -- Title : Base Class Model -- -- Author : Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- -- Exported API: -- -- class(class) -- -- new(class, ...) -- -- classof(object) -- -- isclass(class) -- -- instanceof(object, class) -- -- memberof(class, name) -- -- members(class) -- -------------------------------------------------------------------------------- local pairs = pairs local unpack = unpack local rawget = rawget local setmetatable = setmetatable local getmetatable = getmetatable module "loop.base" -------------------------------------------------------------------------------- function rawnew(class, object) return setmetatable(object or {}, class) end -------------------------------------------------------------------------------- function new(class, ...) if class.__init then return class:__init(...) else return rawnew(class, ...) end end -------------------------------------------------------------------------------- function initclass(class) if class == nil then class = {} end if class.__index == nil then class.__index = class end return class end -------------------------------------------------------------------------------- local MetaClass = { __call = new } function class(class) return setmetatable(initclass(class), MetaClass) end -------------------------------------------------------------------------------- classof = getmetatable -------------------------------------------------------------------------------- function isclass(class) return classof(class) == MetaClass end -------------------------------------------------------------------------------- function instanceof(object, class) return classof(object) == class end -------------------------------------------------------------------------------- memberof = rawget -------------------------------------------------------------------------------- members = pairs
mit
tinydanbo/Impoverished-Starfighter
lib/loveframes/objects/internal/sliderbutton.lua
10
6367
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2012-2014 Kenny Shields -- --]]------------------------------------------------ -- sliderbutton class local newobject = loveframes.NewObject("sliderbutton", "loveframes_object_sliderbutton", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize(parent) self.type = "sliderbutton" self.width = 10 self.height = 20 self.staticx = 0 self.staticy = 0 self.startx = 0 self.clickx = 0 self.starty = 0 self.clicky = 0 self.intervals = true self.internal = true self.down = false self.dragging = false self.parent = parent -- apply template properties to the object loveframes.templates.ApplyToObject(self) end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the object --]]--------------------------------------------------------- function newobject:update(dt) local visible = self.visible local alwaysupdate = self.alwaysupdate if not visible then if not alwaysupdate then return end end self:CheckHover() local x, y = love.mouse.getPosition() local intervals = self.intervals local progress = 0 local nvalue = 0 local pvalue = self.parent.value local hover = self.hover local down = self.down local downobject = loveframes.downobject local parent = self.parent local slidetype = parent.slidetype local dragging = self.dragging local base = loveframes.base local update = self.Update if not hover then self.down = false if downobject == self then self.hover = true end else if downobject == self then self.down = true end end if not down and downobject == self then self.hover = true end -- move to parent if there is a parent if parent ~= base then self.x = parent.x + self.staticx self.y = parent.y + self.staticy end -- start calculations if the button is being dragged if dragging then -- calculations for horizontal sliders if slidetype == "horizontal" then self.staticx = self.startx + (x - self.clickx) progress = self.staticx/(self.parent.width - self.width) nvalue = self.parent.min + (self.parent.max - self.parent.min) * progress nvalue = loveframes.util.Round(nvalue, self.parent.decimals) -- calculations for vertical sliders elseif slidetype == "vertical" then self.staticy = self.starty + (y - self.clicky) local space = self.parent.height - self.height local remaining = (self.parent.height - self.height) - self.staticy local percent = remaining/space nvalue = self.parent.min + (self.parent.max - self.parent.min) * percent nvalue = loveframes.util.Round(nvalue, self.parent.decimals) end if nvalue > self.parent.max then nvalue = self.parent.max end if nvalue < self.parent.min then nvalue = self.parent.min end self.parent.value = nvalue if self.parent.value == -0 then self.parent.value = math.abs(self.parent.value) end if nvalue ~= pvalue and nvalue >= self.parent.min and nvalue <= self.parent.max then if self.parent.OnValueChanged then self.parent.OnValueChanged(self.parent, self.parent.value) end end loveframes.downobject = self end if slidetype == "horizontal" then if (self.staticx + self.width) > self.parent.width then self.staticx = self.parent.width - self.width end if self.staticx < 0 then self.staticx = 0 end end if slidetype == "vertical" then if (self.staticy + self.height) > self.parent.height then self.staticy = self.parent.height - self.height end if self.staticy < 0 then self.staticy = 0 end end if update then update(self, dt) end end --[[--------------------------------------------------------- - func: draw() - desc: draws the object --]]--------------------------------------------------------- function newobject:draw() local visible = self.visible if not visible then return end local skins = loveframes.skins.available local skinindex = loveframes.config["ACTIVESKIN"] local defaultskin = loveframes.config["DEFAULTSKIN"] local selfskin = self.skin local skin = skins[selfskin] or skins[skinindex] local drawfunc = skin.DrawSliderButton or skins[defaultskin].DrawSliderButton local draw = self.Draw local drawcount = loveframes.drawcount -- set the object's draw order self:SetDrawOrder() if draw then draw(self) else drawfunc(self) end end --[[--------------------------------------------------------- - func: mousepressed(x, y, button) - desc: called when the player presses a mouse button --]]--------------------------------------------------------- function newobject:mousepressed(x, y, button) local visible = self.visible if not visible then return end local hover = self.hover if hover and button == "l" then local baseparent = self:GetBaseParent() if baseparent and baseparent.type == "frame" then baseparent:MakeTop() end self.down = true self.dragging = true self.startx = self.staticx self.clickx = x self.starty = self.staticy self.clicky = y loveframes.downobject = self end end --[[--------------------------------------------------------- - func: mousereleased(x, y, button) - desc: called when the player releases a mouse button --]]--------------------------------------------------------- function newobject:mousereleased(x, y, button) local visible = self.visible if not visible then return end local down = self.down local dragging = self.dragging if dragging then local parent = self.parent local onrelease = parent.OnRelease if onrelease then onrelease(parent) end end self.down = false self.dragging = false end --[[--------------------------------------------------------- - func: MoveToX(x) - desc: moves the object to the specified x position --]]--------------------------------------------------------- function newobject:MoveToX(x) self.staticx = x end --[[--------------------------------------------------------- - func: MoveToY(y) - desc: moves the object to the specified y position --]]--------------------------------------------------------- function newobject:MoveToY(y) self.staticy = y end
mit
luanorlandi/Swift-Space-Battle
src/ship/enemyType2.lua
2
2167
local deckSize = Vector:new(50 * window.scale, 50 * window.scale) local deck = MOAIGfxQuad2D.new() deck:setTexture("texture/ship/ship9.png") deck:setRect(-deckSize.x, -deckSize.y, deckSize.x, deckSize.y) local deckDmg = MOAIGfxQuad2D.new() deckDmg:setTexture("texture/ship/ship9dmg.png") deckDmg:setRect(-deckSize.x, -deckSize.y, deckSize.x, deckSize.y) EnemyType2 = {} EnemyType2.__index = EnemyType2 function EnemyType2:new(pos) local E = {} E = Enemy:new(deck, pos) setmetatable(E, EnemyType2) E.name = "EnemyType2" E.type = 2 E.deck = deck E.deckDmg = deckDmg E.hp = 60 E.maxHp = 60 E.maxAcc = 0.1 * window.scale E.dec = E.maxAcc / 3 E.maxSpd = 1.6 * window.scale E.minSpd = E.maxAcc / 5 E.area.size = Rectangle:new(Vector:new(0, 0), deckSize) E.area:newRectangularArea(Vector:new(0, 0), Vector:new(0.4 * deckSize.x, 0.8 * deckSize.y)) E.area:newRectangularArea(Vector:new(0, -0.2 * deckSize.y), Vector:new(0.8 * deckSize.x, 0.4 * deckSize.y)) E.shotType = ShotLaserGreen E.shotSpd = 8 * window.scale E.fireRate = 0.5 table.insert(E.wpn, Vector:new(0.5 * E.area.size.size.x, 0.8 * E.area.size.size.y)) table.insert(E.wpn, Vector:new(-0.5 * E.area.size.size.x, 0.8 * E.area.size.size.y)) table.insert(E.fla, Vector:new(0.5 * E.area.size.size.x, 0.2 * E.area.size.size.y)) table.insert(E.fla, Vector:new(-0.5 * E.area.size.size.x, 0.2 * E.area.size.size.y)) E.score = 50 local spawnThread = coroutine.create(function() Ship.spawnSize(E) end) coroutine.resume(spawnThread) table.insert(E.threads, spawnThread) -- EnemyType2 attributes E.moveRange = (window.width / 2 - E.area.size.size.x) * 0.95 return E end function EnemyType2:move() if self.pos.x > self.moveRange or self.acc.x == 0 then self.acc.x = -self.maxAcc else if self.pos.x < -self.moveRange then self.acc.x = self.maxAcc end end Ship.move(self) end function EnemyType2:shoot() local prob = math.random(1, 100) if prob <= 1 then -- 1% shoot probability Ship.shoot(self, enemiesShots) end end function EnemyType2:damaged(dmg) Ship.damaged(self, dmg) end function EnemyType2:muzzleflash() Ship.muzzleflashType1(self) end
gpl-3.0
JarnoVgr/Mr.Green-MTA-Resources
resources/[race]/race/editor_support_client.lua
4
5932
-- -- editor_support_client.lua -- function isEditor() if g_IsEditor == nil then g_IsEditor = getElementData(resourceRoot,"isEditor") outputDebug ( "Client: Is editor " .. tostring(g_IsEditor == true) ) end return g_IsEditor == true end -- Hacks start here if isEditor() then -- Copy cp_next into cp_now setElementData(g_Me, 'race.editor.cp_now', getElementData(g_Me, 'race.editor.cp_next')) -- override TitleScreen.show() and don't show things TitleScreen._show = TitleScreen.show function TitleScreen.show() TitleScreen._show () hideGUIComponents('titleImage','titleText1','titleText2') end function editorInitRace() g_EditorSpawnPos = {getElementPosition(g_Vehicle)} TravelScreen.hide() TitleScreen.bringForwardFadeout(10000) -- Do fadeup and tell server client is ready setTimer(fadeCamera, 200, 1, true, 1.0) setTimer( function() triggerServerEvent('onNotifyPlayerReady', g_Me) end, 50, 1 ) bindKey('1', 'down', editorSelectCheckpoint, -10) bindKey('2', 'down', editorSelectCheckpoint, -1) bindKey('3', 'down', editorSelectCheckpoint, 1) bindKey('4', 'down', editorSelectCheckpoint, 10) bindKey('6', 'down', editorSelectCheckpoint) bindKey('8', 'down', editorSelectVehicle, -1) bindKey('9', 'down', editorSelectVehicle, 1) bindKey('0', 'down', editorSelectVehicle) bindKey('F2', 'down', editorHideHelp) editorAddHelpLine("Race editor mode keys:" ) editorAddHelpLine("1","CP - 10" ) editorAddHelpLine("2","CP - 1" ) editorAddHelpLine("3","CP + 1" ) editorAddHelpLine("4","CP + 10" ) editorAddHelpLine("5" ) local startCp = getElementData(g_Me, "race.editor.cp_now") if startCp then editorAddHelpLine( "6","Previous test run CP (" .. tostring(startCp) .. ")" ) else editorAddHelpLine( "6","Previous test run CP (n/a)" ) end editorAddHelpLine("7" ) editorAddHelpLine("8","Vehicles used in map -1" ) editorAddHelpLine("9","Vehicles used in map +1" ) editorAddHelpLine("0","Reselect last custom vehicle" ) editorAddHelpLine( "" ) editorAddHelpLine( "F1","(Create) Custom vehicle" ) editorAddHelpLine( "F2","Hide this help" ) if getElementData(g_Me, 'race.editor.hidehelp' ) then editorHideHelp() end end -- Help text editorHelpLines = {} function editorAddHelpLine(text1,text2) local idx = #editorHelpLines/2 editorHelpLines[idx*2+1] = dxText:create(text1, 10, 250 + idx * 15, false, "default-bold", 1.0, "left" ) editorHelpLines[idx*2+1]:color( 255, 250, 130, 240 ) editorHelpLines[idx*2+1]:type( "border", 1 ) editorHelpLines[idx*2+2] = dxText:create(text2 or "", 34, 250 + idx * 15, false, "default-bold", 1.0, "left" ) editorHelpLines[idx*2+2]:color( 255, 250, 250, 230 ) editorHelpLines[idx*2+2]:type( "border", 1 ) end function editorHideHelp() for key,line in pairs(editorHelpLines) do line:visible(not line:visible()) end setElementData(g_Me, 'race.editor.hidehelp', not editorHelpLines[1]:visible() ) end -- Remember last passed cp for next time addEventHandler('onClientElementDataChange', root, function(dataName, oldValue ) if source==g_Me and dataName == "race.checkpoint" then local i = getElementData(g_Me, 'race.checkpoint') if i then setElementData(g_Me, 'race.editor.cp_next', i-1 ) outputDebug ( "race.editor.cp_next " .. tostring(i-1) ) end end end ) -- Use freeroam F1 menu to change vehicle addEventHandler('onClientElementStreamIn', root, function() if not isEditor() then return end -- See if custom vehicle selected in F1 menu if getElementType(source) == "vehicle" then local vehicle = source local x,y,z = getElementPosition(g_Me) local distance = getDistanceBetweenPoints3D(x, y, z, getElementPosition(vehicle)) -- Is nearby, not mine and has no driver? if distance < 5 and vehicle ~= g_Vehicle and not getVehicleController(vehicle) then triggerServerEvent( "onEditorSelectCustomVehicle", resourceRoot, g_Me, vehicle ) end end end ) -- Handle key presses to change vehicle model function editorSelectVehicle(key, state, dir) triggerServerEvent( "onEditorSelectMapVehicle", resourceRoot, g_Me, dir ) end local getKeyState = getKeyState do local mta_getKeyState = getKeyState function getKeyState(key) if isMTAWindowActive() then return false else return mta_getKeyState(key) end end end -- Handle key presses to change current cp function editorSelectCheckpoint(key, state, dir) if not g_CurrentCheckpoint then return end local nextIndex if not dir then nextIndex = getElementData(g_Me, 'race.editor.cp_now') else if getKeyState("lshift") or getKeyState("rshift") then if math.abs(dir) < 2 then dir = dir * 10 end end nextIndex = g_CurrentCheckpoint - 1 + dir end if nextIndex >= 0 and nextIndex < #g_Checkpoints then setCurrentCheckpoint( nextIndex + 1 ) setElementData(g_Me, 'race.editor.cp_next', nextIndex ) local curpos if nextIndex == 0 then curpos = g_EditorSpawnPos -- Use spawn pos for cp #0 else curpos = g_Checkpoints[ nextIndex ].position end local nextpos = g_Checkpoints[ nextIndex + 1 ].position local rz = -math.deg( math.atan2 ( ( nextpos[1] - curpos[1] ), ( nextpos[2] - curpos[2] ) ) ) local cx,cy,cz = getCameraMatrix() local pdistance = getDistanceBetweenPoints3D ( cx,cy,cz, getElementPosition(g_Vehicle) ) setElementPosition( g_Vehicle, curpos[1], curpos[2], curpos[3] + 1 ) setElementRotation( g_Vehicle, 0,0,rz ) setTimer ( function () setVehicleTurnVelocity( g_Vehicle, 0, 0, 0 ) end, 50, 5 ) setTimer ( function () setElementVelocity( g_Vehicle, 0, 0, 0 ) end, 50, 2 ) -- hmmm, maybe this is nice or not if false then setCameraBehindVehicle( g_Vehicle, pdistance ) end triggerServerEvent( "onEditorChangeForCheckpoint", resourceRoot, g_Me, nextIndex ) end end end
mit
uonline/debut
src/day2/act6/the_end_in_scaffold.gameover.lua
1
1397
the_end_in_scaffold = room { nam = 'Конец'; dsc = [[ Что ж видимо вот оно, твоё место в этом мире -- на плахе. Есть на свете такие люди, для которых уготовано отдельное течение жизни. Оно подхватывает их и несёт в никуда, хотят они того или нет. А если они найдут в себе смелость бороться с течением, оно лишь ускорит свой ход. Можно ли причислить тебя к числу смелых и борющихся? Ты так и не находишь ответ на этот вопрос. ^ -- Вот и всё, армейский пёс, -- только и успел прошептать ты, глядя на доски эшафота. ^ Меч просвистел в воздухе и с тупым стуком вонзился в дерево плахи. Отделившись от тела твоя голова полетела на эшафот мимо заготовленной корзины. Даже в ней тебе не нашлось места. Докатившись до края, голова в последний раз явила лицо недосегаемому небу и рухнула вниз. ]]; }
gpl-3.0
tomzhang/kubernetes
test/images/echoserver/template.lua
195
17200
-- vendored from https://raw.githubusercontent.com/bungle/lua-resty-template/1f9a5c24fc7572dbf5be0b9f8168cc3984b03d24/lib/resty/template.lua -- only modification: remove / from HTML_ENTITIES to not escape it, and fix the appropriate regex. --[[ Copyright (c) 2014 - 2017 Aapo Talvensaari All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the {organization} nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --]] local setmetatable = setmetatable local loadstring = loadstring local loadchunk local tostring = tostring local setfenv = setfenv local require = require local capture local concat = table.concat local assert = assert local prefix local write = io.write local pcall = pcall local phase local open = io.open local load = load local type = type local dump = string.dump local find = string.find local gsub = string.gsub local byte = string.byte local null local sub = string.sub local ngx = ngx local jit = jit local var local _VERSION = _VERSION local _ENV = _ENV local _G = _G local HTML_ENTITIES = { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;", ["'"] = "&#39;", } local CODE_ENTITIES = { ["{"] = "&#123;", ["}"] = "&#125;", ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;", ["'"] = "&#39;", ["/"] = "&#47;" } local VAR_PHASES local ok, newtab = pcall(require, "table.new") if not ok then newtab = function() return {} end end local caching = true local template = newtab(0, 12) template._VERSION = "1.9" template.cache = {} local function enabled(val) if val == nil then return true end return val == true or (val == "1" or val == "true" or val == "on") end local function trim(s) return gsub(gsub(s, "^%s+", ""), "%s+$", "") end local function rpos(view, s) while s > 0 do local c = sub(view, s, s) if c == " " or c == "\t" or c == "\0" or c == "\x0B" then s = s - 1 else break end end return s end local function escaped(view, s) if s > 1 and sub(view, s - 1, s - 1) == "\\" then if s > 2 and sub(view, s - 2, s - 2) == "\\" then return false, 1 else return true, 1 end end return false, 0 end local function readfile(path) local file = open(path, "rb") if not file then return nil end local content = file:read "*a" file:close() return content end local function loadlua(path) return readfile(path) or path end local function loadngx(path) local vars = VAR_PHASES[phase()] local file, location = path, vars and var.template_location if sub(file, 1) == "/" then file = sub(file, 2) end if location and location ~= "" then if sub(location, -1) == "/" then location = sub(location, 1, -2) end local res = capture(concat{ location, '/', file}) if res.status == 200 then return res.body end end local root = vars and (var.template_root or var.document_root) or prefix if sub(root, -1) == "/" then root = sub(root, 1, -2) end return readfile(concat{ root, "/", file }) or path end do if ngx then VAR_PHASES = { set = true, rewrite = true, access = true, content = true, header_filter = true, body_filter = true, log = true } template.print = ngx.print or write template.load = loadngx prefix, var, capture, null, phase = ngx.config.prefix(), ngx.var, ngx.location.capture, ngx.null, ngx.get_phase if VAR_PHASES[phase()] then caching = enabled(var.template_cache) end else template.print = write template.load = loadlua end if _VERSION == "Lua 5.1" then local context = { __index = function(t, k) return t.context[k] or t.template[k] or _G[k] end } if jit then loadchunk = function(view) return assert(load(view, nil, nil, setmetatable({ template = template }, context))) end else loadchunk = function(view) local func = assert(loadstring(view)) setfenv(func, setmetatable({ template = template }, context)) return func end end else local context = { __index = function(t, k) return t.context[k] or t.template[k] or _ENV[k] end } loadchunk = function(view) return assert(load(view, nil, nil, setmetatable({ template = template }, context))) end end end function template.caching(enable) if enable ~= nil then caching = enable == true end return caching end function template.output(s) if s == nil or s == null then return "" end if type(s) == "function" then return template.output(s()) end return tostring(s) end function template.escape(s, c) if type(s) == "string" then if c then return gsub(s, "[}{\">/<'&]", CODE_ENTITIES) end return gsub(s, "[\"><'&]", HTML_ENTITIES) end return template.output(s) end function template.new(view, layout) assert(view, "view was not provided for template.new(view, layout).") local render, compile = template.render, template.compile if layout then if type(layout) == "table" then return setmetatable({ render = function(self, context) local context = context or self context.blocks = context.blocks or {} context.view = compile(view)(context) layout.blocks = context.blocks or {} layout.view = context.view or "" return layout:render() end }, { __tostring = function(self) local context = self context.blocks = context.blocks or {} context.view = compile(view)(context) layout.blocks = context.blocks or {} layout.view = context.view return tostring(layout) end }) else return setmetatable({ render = function(self, context) local context = context or self context.blocks = context.blocks or {} context.view = compile(view)(context) return render(layout, context) end }, { __tostring = function(self) local context = self context.blocks = context.blocks or {} context.view = compile(view)(context) return compile(layout)(context) end }) end end return setmetatable({ render = function(self, context) return render(view, context or self) end }, { __tostring = function(self) return compile(view)(self) end }) end function template.precompile(view, path, strip) local chunk = dump(template.compile(view), strip ~= false) if path then local file = open(path, "wb") file:write(chunk) file:close() end return chunk end function template.compile(view, key, plain) assert(view, "view was not provided for template.compile(view, key, plain).") if key == "no-cache" then return loadchunk(template.parse(view, plain)), false end key = key or view local cache = template.cache if cache[key] then return cache[key], true end local func = loadchunk(template.parse(view, plain)) if caching then cache[key] = func end return func, false end function template.parse(view, plain) assert(view, "view was not provided for template.parse(view, plain).") if not plain then view = template.load(view) if byte(view, 1, 1) == 27 then return view end end local j = 2 local c = {[[ context=... or {} local function include(v, c) return template.compile(v)(c or context) end local ___,blocks,layout={},blocks or {} ]] } local i, s = 1, find(view, "{", 1, true) while s do local t, p = sub(view, s + 1, s + 1), s + 2 if t == "{" then local e = find(view, "}}", p, true) if e then local z, w = escaped(view, s) if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end if z then i = s else c[j] = "___[#___+1]=template.escape(" c[j+1] = trim(sub(view, p, e - 1)) c[j+2] = ")\n" j=j+3 s, i = e + 1, e + 2 end end elseif t == "*" then local e = find(view, "*}", p, true) if e then local z, w = escaped(view, s) if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end if z then i = s else c[j] = "___[#___+1]=template.output(" c[j+1] = trim(sub(view, p, e - 1)) c[j+2] = ")\n" j=j+3 s, i = e + 1, e + 2 end end elseif t == "%" then local e = find(view, "%}", p, true) if e then local z, w = escaped(view, s) if z then if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end i = s else local n = e + 2 if sub(view, n, n) == "\n" then n = n + 1 end local r = rpos(view, s - 1) if i <= r then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, r) c[j+2] = "]=]\n" j=j+3 end c[j] = trim(sub(view, p, e - 1)) c[j+1] = "\n" j=j+2 s, i = n - 1, n end end elseif t == "(" then local e = find(view, ")}", p, true) if e then local z, w = escaped(view, s) if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end if z then i = s else local f = sub(view, p, e - 1) local x = find(f, ",", 2, true) if x then c[j] = "___[#___+1]=include([=[" c[j+1] = trim(sub(f, 1, x - 1)) c[j+2] = "]=]," c[j+3] = trim(sub(f, x + 1)) c[j+4] = ")\n" j=j+5 else c[j] = "___[#___+1]=include([=[" c[j+1] = trim(f) c[j+2] = "]=])\n" j=j+3 end s, i = e + 1, e + 2 end end elseif t == "[" then local e = find(view, "]}", p, true) if e then local z, w = escaped(view, s) if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end if z then i = s else c[j] = "___[#___+1]=include(" c[j+1] = trim(sub(view, p, e - 1)) c[j+2] = ")\n" j=j+3 s, i = e + 1, e + 2 end end elseif t == "-" then local e = find(view, "-}", p, true) if e then local x, y = find(view, sub(view, s, e + 1), e + 2, true) if x then local z, w = escaped(view, s) if z then if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end i = s else y = y + 1 x = x - 1 if sub(view, y, y) == "\n" then y = y + 1 end local b = trim(sub(view, p, e - 1)) if b == "verbatim" or b == "raw" then if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end c[j] = "___[#___+1]=[=[" c[j+1] = sub(view, e + 2, x) c[j+2] = "]=]\n" j=j+3 else if sub(view, x, x) == "\n" then x = x - 1 end local r = rpos(view, s - 1) if i <= r then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, r) c[j+2] = "]=]\n" j=j+3 end c[j] = 'blocks["' c[j+1] = b c[j+2] = '"]=include[=[' c[j+3] = sub(view, e + 2, x) c[j+4] = "]=]\n" j=j+5 end s, i = y - 1, y end end end elseif t == "#" then local e = find(view, "#}", p, true) if e then local z, w = escaped(view, s) if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end if z then i = s else e = e + 2 if sub(view, e, e) == "\n" then e = e + 1 end s, i = e - 1, e end end end s = find(view, "{", s + 1, true) end s = sub(view, i) if s and s ~= "" then c[j] = "___[#___+1]=[=[\n" c[j+1] = s c[j+2] = "]=]\n" j=j+3 end c[j] = "return layout and include(layout,setmetatable({view=table.concat(___),blocks=blocks},{__index=context})) or table.concat(___)" return concat(c) end function template.render(view, context, key, plain) assert(view, "view was not provided for template.render(view, context, key, plain).") return template.print(template.compile(view, key, plain)(context)) end return template
apache-2.0
juanvallejo/kubernetes
test/images/echoserver/template.lua
195
17200
-- vendored from https://raw.githubusercontent.com/bungle/lua-resty-template/1f9a5c24fc7572dbf5be0b9f8168cc3984b03d24/lib/resty/template.lua -- only modification: remove / from HTML_ENTITIES to not escape it, and fix the appropriate regex. --[[ Copyright (c) 2014 - 2017 Aapo Talvensaari All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the {organization} nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. --]] local setmetatable = setmetatable local loadstring = loadstring local loadchunk local tostring = tostring local setfenv = setfenv local require = require local capture local concat = table.concat local assert = assert local prefix local write = io.write local pcall = pcall local phase local open = io.open local load = load local type = type local dump = string.dump local find = string.find local gsub = string.gsub local byte = string.byte local null local sub = string.sub local ngx = ngx local jit = jit local var local _VERSION = _VERSION local _ENV = _ENV local _G = _G local HTML_ENTITIES = { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;", ["'"] = "&#39;", } local CODE_ENTITIES = { ["{"] = "&#123;", ["}"] = "&#125;", ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;", ["'"] = "&#39;", ["/"] = "&#47;" } local VAR_PHASES local ok, newtab = pcall(require, "table.new") if not ok then newtab = function() return {} end end local caching = true local template = newtab(0, 12) template._VERSION = "1.9" template.cache = {} local function enabled(val) if val == nil then return true end return val == true or (val == "1" or val == "true" or val == "on") end local function trim(s) return gsub(gsub(s, "^%s+", ""), "%s+$", "") end local function rpos(view, s) while s > 0 do local c = sub(view, s, s) if c == " " or c == "\t" or c == "\0" or c == "\x0B" then s = s - 1 else break end end return s end local function escaped(view, s) if s > 1 and sub(view, s - 1, s - 1) == "\\" then if s > 2 and sub(view, s - 2, s - 2) == "\\" then return false, 1 else return true, 1 end end return false, 0 end local function readfile(path) local file = open(path, "rb") if not file then return nil end local content = file:read "*a" file:close() return content end local function loadlua(path) return readfile(path) or path end local function loadngx(path) local vars = VAR_PHASES[phase()] local file, location = path, vars and var.template_location if sub(file, 1) == "/" then file = sub(file, 2) end if location and location ~= "" then if sub(location, -1) == "/" then location = sub(location, 1, -2) end local res = capture(concat{ location, '/', file}) if res.status == 200 then return res.body end end local root = vars and (var.template_root or var.document_root) or prefix if sub(root, -1) == "/" then root = sub(root, 1, -2) end return readfile(concat{ root, "/", file }) or path end do if ngx then VAR_PHASES = { set = true, rewrite = true, access = true, content = true, header_filter = true, body_filter = true, log = true } template.print = ngx.print or write template.load = loadngx prefix, var, capture, null, phase = ngx.config.prefix(), ngx.var, ngx.location.capture, ngx.null, ngx.get_phase if VAR_PHASES[phase()] then caching = enabled(var.template_cache) end else template.print = write template.load = loadlua end if _VERSION == "Lua 5.1" then local context = { __index = function(t, k) return t.context[k] or t.template[k] or _G[k] end } if jit then loadchunk = function(view) return assert(load(view, nil, nil, setmetatable({ template = template }, context))) end else loadchunk = function(view) local func = assert(loadstring(view)) setfenv(func, setmetatable({ template = template }, context)) return func end end else local context = { __index = function(t, k) return t.context[k] or t.template[k] or _ENV[k] end } loadchunk = function(view) return assert(load(view, nil, nil, setmetatable({ template = template }, context))) end end end function template.caching(enable) if enable ~= nil then caching = enable == true end return caching end function template.output(s) if s == nil or s == null then return "" end if type(s) == "function" then return template.output(s()) end return tostring(s) end function template.escape(s, c) if type(s) == "string" then if c then return gsub(s, "[}{\">/<'&]", CODE_ENTITIES) end return gsub(s, "[\"><'&]", HTML_ENTITIES) end return template.output(s) end function template.new(view, layout) assert(view, "view was not provided for template.new(view, layout).") local render, compile = template.render, template.compile if layout then if type(layout) == "table" then return setmetatable({ render = function(self, context) local context = context or self context.blocks = context.blocks or {} context.view = compile(view)(context) layout.blocks = context.blocks or {} layout.view = context.view or "" return layout:render() end }, { __tostring = function(self) local context = self context.blocks = context.blocks or {} context.view = compile(view)(context) layout.blocks = context.blocks or {} layout.view = context.view return tostring(layout) end }) else return setmetatable({ render = function(self, context) local context = context or self context.blocks = context.blocks or {} context.view = compile(view)(context) return render(layout, context) end }, { __tostring = function(self) local context = self context.blocks = context.blocks or {} context.view = compile(view)(context) return compile(layout)(context) end }) end end return setmetatable({ render = function(self, context) return render(view, context or self) end }, { __tostring = function(self) return compile(view)(self) end }) end function template.precompile(view, path, strip) local chunk = dump(template.compile(view), strip ~= false) if path then local file = open(path, "wb") file:write(chunk) file:close() end return chunk end function template.compile(view, key, plain) assert(view, "view was not provided for template.compile(view, key, plain).") if key == "no-cache" then return loadchunk(template.parse(view, plain)), false end key = key or view local cache = template.cache if cache[key] then return cache[key], true end local func = loadchunk(template.parse(view, plain)) if caching then cache[key] = func end return func, false end function template.parse(view, plain) assert(view, "view was not provided for template.parse(view, plain).") if not plain then view = template.load(view) if byte(view, 1, 1) == 27 then return view end end local j = 2 local c = {[[ context=... or {} local function include(v, c) return template.compile(v)(c or context) end local ___,blocks,layout={},blocks or {} ]] } local i, s = 1, find(view, "{", 1, true) while s do local t, p = sub(view, s + 1, s + 1), s + 2 if t == "{" then local e = find(view, "}}", p, true) if e then local z, w = escaped(view, s) if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end if z then i = s else c[j] = "___[#___+1]=template.escape(" c[j+1] = trim(sub(view, p, e - 1)) c[j+2] = ")\n" j=j+3 s, i = e + 1, e + 2 end end elseif t == "*" then local e = find(view, "*}", p, true) if e then local z, w = escaped(view, s) if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end if z then i = s else c[j] = "___[#___+1]=template.output(" c[j+1] = trim(sub(view, p, e - 1)) c[j+2] = ")\n" j=j+3 s, i = e + 1, e + 2 end end elseif t == "%" then local e = find(view, "%}", p, true) if e then local z, w = escaped(view, s) if z then if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end i = s else local n = e + 2 if sub(view, n, n) == "\n" then n = n + 1 end local r = rpos(view, s - 1) if i <= r then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, r) c[j+2] = "]=]\n" j=j+3 end c[j] = trim(sub(view, p, e - 1)) c[j+1] = "\n" j=j+2 s, i = n - 1, n end end elseif t == "(" then local e = find(view, ")}", p, true) if e then local z, w = escaped(view, s) if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end if z then i = s else local f = sub(view, p, e - 1) local x = find(f, ",", 2, true) if x then c[j] = "___[#___+1]=include([=[" c[j+1] = trim(sub(f, 1, x - 1)) c[j+2] = "]=]," c[j+3] = trim(sub(f, x + 1)) c[j+4] = ")\n" j=j+5 else c[j] = "___[#___+1]=include([=[" c[j+1] = trim(f) c[j+2] = "]=])\n" j=j+3 end s, i = e + 1, e + 2 end end elseif t == "[" then local e = find(view, "]}", p, true) if e then local z, w = escaped(view, s) if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end if z then i = s else c[j] = "___[#___+1]=include(" c[j+1] = trim(sub(view, p, e - 1)) c[j+2] = ")\n" j=j+3 s, i = e + 1, e + 2 end end elseif t == "-" then local e = find(view, "-}", p, true) if e then local x, y = find(view, sub(view, s, e + 1), e + 2, true) if x then local z, w = escaped(view, s) if z then if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end i = s else y = y + 1 x = x - 1 if sub(view, y, y) == "\n" then y = y + 1 end local b = trim(sub(view, p, e - 1)) if b == "verbatim" or b == "raw" then if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end c[j] = "___[#___+1]=[=[" c[j+1] = sub(view, e + 2, x) c[j+2] = "]=]\n" j=j+3 else if sub(view, x, x) == "\n" then x = x - 1 end local r = rpos(view, s - 1) if i <= r then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, r) c[j+2] = "]=]\n" j=j+3 end c[j] = 'blocks["' c[j+1] = b c[j+2] = '"]=include[=[' c[j+3] = sub(view, e + 2, x) c[j+4] = "]=]\n" j=j+5 end s, i = y - 1, y end end end elseif t == "#" then local e = find(view, "#}", p, true) if e then local z, w = escaped(view, s) if i < s - w then c[j] = "___[#___+1]=[=[\n" c[j+1] = sub(view, i, s - 1 - w) c[j+2] = "]=]\n" j=j+3 end if z then i = s else e = e + 2 if sub(view, e, e) == "\n" then e = e + 1 end s, i = e - 1, e end end end s = find(view, "{", s + 1, true) end s = sub(view, i) if s and s ~= "" then c[j] = "___[#___+1]=[=[\n" c[j+1] = s c[j+2] = "]=]\n" j=j+3 end c[j] = "return layout and include(layout,setmetatable({view=table.concat(___),blocks=blocks},{__index=context})) or table.concat(___)" return concat(c) end function template.render(view, context, key, plain) assert(view, "view was not provided for template.render(view, context, key, plain).") return template.print(template.compile(view, key, plain)(context)) end return template
apache-2.0
uonline/debut
src/day1/act6/tract_camp/tract_camp.room.lua
1
6024
tract_camp_to_dream = vroom('Лечь спать', 'dream'); tract_camp_to_dream:disable(); on_event('talked to black guy', function() tract_camp_to_dream:enable() end) tract_camp = room { nam = 'Стоянка повозки у тракта'; dsc = [[ -- Эй, просыпайся! -- чья-то рука грубо толкает тебя в бок. -- Если не хочешь остаться без жратвы, конечно. ^ Сознание медленно возвращается к тебе. Ты обнаруживаешь себя сидящим на земле с испариной холодного пота на лбу. В спину упирается колесо повозки. Над тобой на фоне чёрного неба возвышается здоровенный бородатый детина в панцире и с миской в руках. ^ -- Я опять пленник? -- спрашиваешь ты. Бородач нехотя усмехается. ^ -- Пока ещё нет. Доберёмся до города, а там как решит капитан, -- он кивает в сторону костра. Там сидит тот самый человек, что совсем недавно разговаривал с главарём банды урук-хай. ^ Удовлетворив своё любопытство, ты решаешь удовлетворить и голод. Жадно выхватив миску из рук здоровяка, ты обнаруживаешь на ней жареную оленину -- напоминание о твой неудачной охоте. ^ Заметив твоё замешательство, бородач было попытался забрать миску обратно, но ты вовремя опомнился. Под заунывные трели желудка ты набрасываешься на еду, не забывая поглядывать по сторонам. Уже темно, и только пламя костра освещает лица твоих новоиспечённых спутников. ]]; obj = { 'tract_guard_1'; 'tract_guard_2'; 'tract_captain'; 'tract_mystery'; }; way = { tract_camp_to_dream; }; entered = function() inv():zap(); take 'a6_the_thing' end; } tract_guard_1 = obj { nam = 'Стражник'; dsc = [[ {Бородач} подпирает повозку. Его явно клонит в сон: он всё время зевает. Он тут явно в качестве стражника. ]]; act = [[ -- Будешь задавать ещё вопросы, -- ловит твой взгляд здоровяк, -- сделаю пленником досрочно. ]]; } tract_guard_2 = obj { nam = 'Стражник'; dsc = [[ Чуть дальше стоит {ещё один стражник}. Этот сразу показался тебе каким-то странным. Как бы ты ни старался, тебе никак не удавалось увидеть его лицо -- почему-то он всё время то поворачивался спиной, то скрывался за спинами других. Сейчас он стоит перед тобой спиной к костру, так что лица опять не разобрать. ]]; act = [[ -- Удивительное это время -- ночь, -- говорит он тебе тихим, вкрадчивым голосом. -- В темноте сложно понять, где кончается явь, а где начинается сон. ^ Ты не отвечаешь: рот занят. ]]; } tract_captain = obj { nam = 'Капитан'; dsc = [[ По другую сторону от костра {капитан} сидит на ящике и подбрасывает в воздух игральные кости. ]]; act = [[ При свете костра капитан уже не кажется тебе таким молодым, каким показался в первый раз. Алые всполохи огибают морщины у глаз и у рта, оставляя на их месте чёрные тени. На висках блестит седина. Капитан выглядит задумчивым, но с его лица не сходит лёгкая и такая знакомая усмешка. ]]; } tract_mystery = obj { nam = 'Фигура в плаще'; dsc = [[ {Фигура в плаще} что-то тихо объясняет ему, иногда вскидывая ладонь своей тонкой руки с длинными пальцами, на одном из которых красуется крупный синий перстень. ]]; act = function() event 'talked to black guy' return [[ Ты начинаешь изучать своего загадочного спутника, гадая, кому может принадлежать такая привлекательная рука, да к тому же так богато украшенная. Фигура охотно поворачивается к тебе, но что-то разглядеть в чёрном провале капюшона невозможно. ^ -- Сегодня тебе выпал трудный день, -- неожиданно мелодичный голос незнакомца заставляет тебя вздрогнуть, -- но и дальше будет не легче. Тебе стоит отправиться в царство снов сейчас, если не хочешь отправиться в царство смерти завтра. ^ "Поспать -- неплохая мысль," -- думаешь ты. ]]; end; }
gpl-3.0
shadoalzupedy/shadow
plugins/shado2.lua
1
2362
--[[ # #ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ #:(( # For More Information ....! # Developer : Aziz < @TH3_GHOST > # our channel: @DevPointTeam # Version: 1.1 #:)) #ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ # ]] do local function run(msg, matches) if is_momod(msg) and matches[1]== "اوامر1" then return [[ وامر المجموعة 💢🌐 ✝/وضع اسم للمجموعة + الاسم 💢 🛐/وضع وصف للمجموعة + الوصف 🚧 🌆/وضع صورة للمجموعة : لوضع صورة🗯 💹/وضع قوانين للمجموعة : ♻️ لوضع قوانين ✅ 💠💠💠💠💠💠💠 اوامر الرفع ⌛️📡 /ارفع ادمن : لرف ادمن 🌝 /انزل ادمن : لتنزيل ادمن 😴 /ارفع اداري : لرفع اداري ✋🏿 /انزل اداري : لتنزيل اداري 😑 ❣❣❣❣❣❣❣❣❣❣ 💢/وضع الرابط : لوضع✅ رابط للمجموعة 🚸/المنشئ : لمعرفة مالك المجموعة✅ 🔵/البوتات : لاضهار البوتات في المجموعة🔕 💭/رابط المجموعة : لاضهار رابط المجموعة🗯 💟/اصنع رابط : لصنع رابط جديد💠 ♨️/قائمة الاسكات : لمعرفة المكتومين🌐 🔵/وضع عدد التكرار : + العدد من 5-20✔️ مي : لاضهار موقعك 🌐✔️ 🔵🔵🔵🔵🔵🔵🔵🔵 معلومات عن المجموعة🚧✅ 🕎/الاعضاء : اعضاء المجموعة ✔️/اعدادات المجموعة : لاضهار الاعدادات♨️ 💠/قائمة الاداريين : لاضهار ادمنية المجموعة🚧 ✝/ادمنية المجموعة : لاضهار الادمنيه 🏌/دعبلني للخروج من المجموعة 🏌 ____________________________ Dev bot ✅ @body4 ❤️ bot ✅ @shado1bot ❣]] end if not is_momod(msg) then return "Only managers 😐⛔️" end end return { description = "Help list", usage = "Help list", patterns = { "[#!/](اوامر1)" }, run = run } end
gpl-2.0
DEKHTIARJonathan/BilletterieUTC
badgingServer/Install/swigwin-3.0.7/Examples/test-suite/lua/overload_simple_runme.lua
8
1235
require("import") -- the import fn import("overload_simple") -- import code for k,v in pairs(overload_simple) do _G[k]=v end -- move to global -- lua has only one numeric type, foo(int) and foo(double) are the same -- whichever one was wrapper first will be used assert(foo(3)=="foo:int" or foo(3)=="foo:double") -- could be either assert(foo("hello")=="foo:char *") f=Foo() b=Bar() assert(foo(f)=="foo:Foo *") assert(foo(b)=="foo:Bar *") v = malloc_void(32) assert(foo(v) == "foo:void *") s = Spam() assert(s:foo(3) == "foo:int" or s:foo(3.0) == "foo:double") -- could be either assert(s:foo("hello") == "foo:char *") assert(s:foo(f) == "foo:Foo *") assert(s:foo(b) == "foo:Bar *") assert(s:foo(v) == "foo:void *") assert(Spam_bar(3) == "bar:int" or Spam_bar(3.0) == "bar:double") assert(Spam_bar("hello") == "bar:char *") assert(Spam_bar(f) == "bar:Foo *") assert(Spam_bar(b) == "bar:Bar *") assert(Spam_bar(v) == "bar:void *") -- Test constructors s = Spam() assert(s.type == "none") s = Spam(3) assert(s.type == "int" or s.type == "double") s = Spam("hello") assert(s.type == "char *") s = Spam(f) assert(s.type == "Foo *") s = Spam(b) assert(s.type == "Bar *") s = Spam(v) assert(s.type == "void *") free_void(v)
apache-2.0
JarnoVgr/Mr.Green-MTA-Resources
resources/[race]/race/edf/edf_client.lua
4
2793
g_ModelForPickupType = { nitro = 2221, repair = 2222, vehiclechange = 2223 } models = {} startTick = getTickCount() function onStart() --Callback triggered by edf for name,id in pairs(g_ModelForPickupType) do models[name] = {} models[name].txd = engineLoadTXD(':race/model/' .. name .. '.txd') engineImportTXD(models[name].txd, id) models[name].dff = engineLoadDFF(':race/model/' .. name .. '.dff', id) engineReplaceModel(models[name].dff, id) end for i,racepickup in pairs(getElementsByType"racepickup") do checkElementType(racepickup) end end function onStop() for name,id in pairs(g_ModelForPickupType) do destroyElement ( models[name].txd ) destroyElement ( models[name].dff ) end end addEventHandler ( "onClientElementPropertyChanged", root, function ( propertyName ) if getElementType(source) == "racepickup" then if propertyName == "type" then local pickupType = exports.edf:edfGetElementProperty ( source, "type" ) local object = getRepresentation(source,"object") if object then setElementModel ( object[1], g_ModelForPickupType[pickupType] or 1346 ) end end elseif getElementType(source) == "checkpoint" then if propertyName == "nextid" or propertyName == "type" then local nextID = exports.edf:edfGetElementProperty ( source, "nextid" ) local marker = getRepresentation(source,"marker") if nextID then if getMarkerType(marker) == "checkpoint" then setMarkerIcon ( marker, "arrow" ) end setMarkerTarget ( marker, exports.edf:edfGetElementPosition(nextID) ) else if getMarkerType(marker) == "checkpoint" then setMarkerIcon ( marker, "finish" ) end end end end end ) function checkElementType(element) element = element or source if getElementType(element) == "racepickup" then local pickupType = exports.edf:edfGetElementProperty ( element, "type" ) local object = getRepresentation(element,"object") if object then setElementModel ( object[1], g_ModelForPickupType[pickupType] or 1346 ) setElementAlpha ( object[2], 0 ) end end end addEventHandler("onClientElementCreate", root, checkElementType) --Pickup processing code function updatePickups() local angle = math.fmod((getTickCount() - startTick) * 360 / 2000, 360) for i,racepickup in pairs(getElementsByType"racepickup") do setElementRotation(racepickup, 0, 0, angle) end end addEventHandler('onClientRender', root, updatePickups) function getRepresentation(element,type) local elemTable = {} for i,elem in ipairs(getElementsByType(type,element)) do if elem ~= exports.edf:edfGetHandle ( elem ) then table.insert(elemTable, elem) end end if #elemTable == 0 then return false elseif #elemTable == 1 then return elemTable[1] else return elemTable end end
mit
uonline/debut
src/day2/act8/burning_quarter_part_II.room.lua
1
74608
-- Переменные локации _burning_quarter_walking_dead = false; -- Функции локации -- Функция нападения на проповедника с голыми руками burning_quarter_mad_strike = function() local mad_strike_text; walk 'burning_quarter_part_II_gameover'; -- Проверяем, есть ли у героя оружие if ( (not have(burning_quarter_knuckle)) and (not have(burning_quarter_knife)) and (not have(burning_quarter_halberd)) and (not have(burning_quarter_fight_hammer)) ) then mad_strike_text = [[ Ты прикидываешь как отвлечь внимание проповедника, чтобы отобрать у него кинжал. ]]; else mad_strike_text = [[ Ты отбрасываешь оружие в сторону, прикидывая как отвлечь проповедника, чтобы отобрать у него кинжал. ]]; end; return mad_strike_text .. [[ Подняв в воздух столб пыли, ты хватаешь с земли камень и швыряешь его прямо в оскал зубов. ^ Проповедник отмахивается от камня ладонью и подскакивает к тебе, ударяя кинжалом сверху. Ты перехватываешь его руку с клинком и пытаешься её вывернуть. Но лезвие продолжает сокращать расстояние к твоему сердцу. Скрюченные пальцы удерживают тебя за плечо, не давая убежать. ^ Тебе остаётся только наблюдать, как серая полоса металла вгрызается тебе в грудь. ]]; end; -- Функция текста исчезновения проповедника burning_quarter_priest_disappear = function() return [[ ^ -- Червь решает сражаться? -- проповедник скрывает ухмылку за руковом рясы. ^ Его тряпьё растворяется в ночи, словно разлетевшаяся стая воронов. ^ -- Хорошо, давай сыграем в эту игру, -- шипит голос проповедника, -- пусть Она позабавится! ]]; end; -- Функция оживления проповедником мёртвых burning_quarter_en_garde = function() _burning_quarter_walking_dead = true; objs('burning_quarter_fight'):del('burning_quarter_armed_corpses'); objs('burning_quarter_fight'):del('burning_quarter_priest'); objs('burning_quarter_fight'):del('burning_quarter_dagger'); objs('burning_quarter_fight'):add('burning_quarter_zombies'); objs('burning_quarter_fight'):add('burning_quarter_zombie_fighter'); objs('burning_quarter_fight'):add('burning_quarter_zombie_thug'); objs('burning_quarter_fight'):add('burning_quarter_zombie_guard'); objs('burning_quarter_fight'):del('burning_quarter_knuckle'); objs('burning_quarter_fight'):del('burning_quarter_knife'); objs('burning_quarter_fight'):del('burning_quarter_halberd'); return [[ ^ Лоскуты-тени сгущаются в чёрном небе над трупами. Вихрями спустившись вниз, они вгрызаются в лица мертвецов. ^ На твоих глазах мертвые оживают и поднимаются на ноги. ]]; end; -- Разделываемся с мертвецами burning_quarter_dmz = function() _burning_quarter_walking_dead = false; objs('burning_quarter_fight'):add('burning_quarter_priest'); objs('burning_quarter_fight'):add('burning_quarter_dagger'); objs('burning_quarter_fight'):del('burning_quarter_zombies'); objs('burning_quarter_fight'):del('burning_quarter_zombie_fighter'); objs('burning_quarter_fight'):del('burning_quarter_zombie_thug'); objs('burning_quarter_fight'):del('burning_quarter_zombie_guard'); return [[ ^ Ты поворачиваешься, чтобы разделаться со вторым мертвецом, но не сразу его находишь. ^ Труп обнаруживается лежащим на земле, с головой пригвоздённой копьём. Ты замечаешь, как по древку странным образом поднимается тень. Добравшись до конца копья, тень струйкой дыма въётся к небу, свиваясь в облако дыма. Облако приходит в движение, и закружившись спиралью, опускается вниз, приобретая очертания проповедника. ^ -- Нам, кажется, помешали, -- брезгливо вытягивает тот, -- иначе бы ты уже был мёртв. ^ Ты смотришь за спину проповедника, туда где подножие склона квартала превратилось в пылающие руины. Где-то там следи пляшущего огня, ты видишь зыбкий силуэт человека в доспехах. Он ещё далеко, но неотвратимо приближается к вам. ]]; end; -- Меняем молот на другое оружие burning_quarter_weapon_change = function() if have('burning_quarter_fight_hammer') then if have('burning_quarter_knuckle') or have('burning_quarter_knife') or have('burning_quarter_halberd') then drop 'burning_quarter_fight_hammer'; objs(burning_quarter_fight):del('burning_quarter_fight_hammer'); return [[ Уступив ноящей боли в мышцах, ты отбрасываешь молот. ^ ]]; end; end; return '' end -- Переходы локации --burning_quarter_to_lane_room = vroom('Переулок', 'lane_room'); -- Локация burning_quarter_fight = room { nam = 'Горящий квартал'; dsc = [[ Ты стоишь посреди охваченного пламенем квартала. Над тобой чёрная воронка неба впитывает в себя столбы дыма и языки огня. Грохот и треск рушащихся зданий смешивается с рёвом бушующего пожара. ]]; obj = { 'burning_quarter_away'; 'burning_quarter_priest'; 'burning_quarter_dagger'; -- 'burning_quarter_ring'; 'burning_quarter_armed_corpses'; 'burning_quarter_knuckle'; -- 'burning_quarter_zombie_fighter'; 'burning_quarter_knife'; -- 'burning_quarter_zombie_thug'; 'burning_quarter_halberd'; -- 'burning_quarter_zombie_guard'; -- 'burning_quarter_godchosen'; }; enter = function() inv():zap(); take 'burning_quarter_hands'; take 'burning_quarter_fight_hammer'; end; way = { --burning_quarter_to_lane_room; }; } -- Инвентарь -- Руки burning_quarter_hands = obj { nam = 'Руки'; inv = function() if have('burning_quarter_ring') then return [[ Ты рассматриваешь свои руки словно видишь их впервые. И хотя выглядят они как обычно, под кожей среди мышц и жил пульсирует небывалое ощущение силы. ^ В такт пульсу крови, на пальце вспыхивает кольцо, охотно отражая адскую пляску огня и прожигая кожу жаром. ]]; end; return [[ Ты с волнением смотришь на свои измождённые руки. Взмахи неприподъёмным орочьим молотом наполнили их свинцовой тяжестью. Даёт о себе знать и накопившаяся за день усталось. ]]; end; } -- Объекты локации -- Молот burning_quarter_fight_hammer = obj { nam = 'Молот урук-хай'; dsc = [[ ^ Громоздкий {молот урук-хай} у тебя под ногами будто бы врос в землю. ]]; act = [[ Ты с отвращением осматриваешь уродливый молот урук-хай. Тупой кусок железа вместо навершия и грубая металлическая рукоять. ]]; inv = [[ Ты с отвращением осматриваешь уродливый молот урук-хай. Тупой кусок железа вместо навершия и грубая металлическая рукоять. Наверняка когда-то его урук-хозяин с лёгкостью проламывал им черепа одной рукой. Но ты с трудом удерживаешь это страшилище в двух. ]]; tak = function() local s = burning_quarter_en_garde(); local pd_text = burning_quarter_priest_disappear(); return ([[ Ты наклоняешься, и выдохнув поднимаешь молот. ]] .. pd_text .. s); end; } -- Путь в переулок burning_quarter_away = obj { nam = 'Путь в переулок'; dsc = [[ Позади тебя -- {проход в переулок}, сопротивляется пожирающему всё вокруг огню. ^ ]]; act = function() -- GO10 local godchosen_present = false; -- Проверяем, есть ли на сцене Богоизбранный for k, v in pairs(objs('burning_quarter_fight')) do if v == burning_quarter_godchosen then godchosen_present = true; break; end end -- Если на сцене есть Богоизбранный, то он убивает героя, при попытке сбежать в Переулок if godchosen_present then walk 'burning_quarter_part_II_gameover'; return [[ Не долго думая, ты резко разворачиваешься на пятках и бросаешься в переулок. ^ Вспышка боли останавливает тебя. Не отрывая взгляда от окровавленного клинка меча, что торчит у тебя из груди, ты падаешь на бок и закрываешь глаза. ]]; end; -- S11 -- Проверяем есть ли на сцене "упавший Богоизбранный" local godchosen_down_present = false; for k, v in pairs(objs('burning_quarter_fight')) do if v == burning_quarter_godchosen_down then godchosen_down_present = true; end; end; -- Если есть, то спасаемся бегством в Переулок if godchosen_down_present then walk 'lane_room'; return [[ Не долго думая, ты резко разворачиваешься на пятках и бросаешься в переулок. ^ Пробираясь через завал, ты краем глаза замечаешь, что богоизбранный закинул меч на плечо и направился вслед за тобой. ]]; end; -- S2 -- Если пытаемся сразу сбежать с молотом if have('burning_quarter_fight_hammer') and (not _burning_quarter_walking_dead) then drop 'burning_quarter_fight_hammer'; objs('burning_quarter_fight'):add('burning_quarter_fight_hammer'); return [[ Не долго думая, ты резко разворачиваешься на пятках и бросаешься в переулок. Но непостижимым образом на месте чернеющего среди руин прохода, оказывается жуткая фигура проповедника в изорванной рясе. ^ С разбегу ты натыкаешься грудью на кулак, и тут же повисаешь на нём, обмякнув. Разом выпустив из лёгких весь воздух и по-рыбьи разевая рот, ты всё же удерживаешь молот в руках. И от этого безумная улыбка на бледном лице становится только шире. ^ Проповедник легонько толкает тебя в плечо, но ты летишь на землю и пару метров катишься кубарем. С гудящей головой ты встаёшь на ноги, и понимаешь, что молот вырвался из твоих пальцев, и теперь валяется где-то в грязи. ]]; end; -- in other cases, GO1 -- Умираем в Переулке walk 'burning_quarter_part_II_gameover'; return [[ Не долго думая, ты резко разворачиваешься на пятках и бросаешься в переулок. ^ Пробравшись через завал, ты видишь где-то впереди во мраке пятно, похожее на канализационную решётку. Ты отбрасываешь молот в сторону и устремляешься к спасительному спуску, не замечая как танцующие тени вокруг начинают удлинняться. ^ Резкий скрежещущий голос, заставляет тебя остановиться. ^ -- Ничтожный глупец, -- шепчет тебе в ухо проповедник, -- что может быть наивней, чем прятаться от тени в темноте! ^ Ты снова бежишь к решётке, хотя уже не видишь её в сгущающейся тьме. ^ Тонкой нитью боль неторопливо просачивается тебе под рёбра, разливая неприятное тепло в боку и вниз по ноге. Ты спотыкаешься и падаешь на колени. ^ Последнее, что ты чувствуешь: лед лезвия кинжала на горле. ]]; end; } -- Проповедник burning_quarter_priest = obj { nam = 'Проповедник'; dsc = [[ Перед тобой возвышается {проповедник}, объятый вихрем из чёрных лохмотьев. ]]; act = function() walk 'burning_quarter_priest_dlg'; end; used = function(self, what) -- GOx if what == burning_quarter_hands then return burning_quarter_mad_strike(); end; -- S4 if what == burning_quarter_fight_hammer then local s = burning_quarter_en_garde(); local pd_text = burning_quarter_priest_disappear(); return ([[ Тебя обуревает неожиданный приступ ярости. Тебе хочется взмахнуть своим тяжеленным молотом и смести этот ухмыляющийся ворох рванья. ^ Ты срываешься с места и пускаешь оружие в боковой удар, дав левой руке скользить по рукояти. Ты ожидаешь услышать звук ломающихся костей, но вместо этого молот увлекает тебя за собой. ^ Так и не столкнувшись с препятствием, оружие лишь срывает чёрные лоскуты рясы. Изорванная ткань облепляет тебя со всех сторон. ^ -- Неужели!? В тебе есть гнев? -- раздаётся ликующий возглас проповедника, сменяющийся смехом, -- пожалуй мне стоит опасаться такого свирепого противника! ^ Ты машешь рукой, пытаясь высвободиться из опутавших тебя лохмотьев, но избавившись от пут, обнаруживаешь себя в полной темноте. ^ -- Это должно остудить твою ярость, -- шепчет проповедник. ^ Ты вываливаешься из тьмы обратно в горящий квартал и затравленно озираешься по сторонам. Проповедника нигде не видно. ]] .. s); end; -- GO6 local dagger_death_text = [[ ^ Отвратительно улыбаясь, проповедник надвигается на тебя, занося клинок для удара. Ты вскидываешь руки, чтобы закрыться, но бесполезно. С чёрного неба прямо тебе на грудь пикирует хищный кинжал, без труда достигая сердца. ]]; if (what == burning_quarter_knife) then walk 'burning_quarter_part_II_gameover'; return [[ Ты набрасываешься на проповедника, размахивая орочьим ножом. Ты бьёшь снизу вверх, рассчитывая вспороть ему грудную клетку. Но появившийся на пути твоего ножа кинжал, легко отводит удар в сторону. Проповедник усмехается тебе в лицо. Выдохнув, ты наносишь новый удар, заходя с боку. Кинжал в бледной руке сталкивается с ножом урук-хай, после чего ты пятишься, пошатываясь и потирая онемевшую руку. ]] .. dagger_death_text; end; if (what == burning_quarter_halberd) then walk 'burning_quarter_part_II_gameover'; return [[ Ты набрасываешься на проповедника с алебардой на перевес. Описав широкую дугу, лезвие секиры обрушивается на клубок лохмотьев. Но выставленный кинжал с лёгкостю отражает твой удар. Ты отступаешь, пытаясь удержать в немеющих руках дрожащее древко. ]] .. dagger_death_text; end; end; } -- Диалог с проповедником burning_quarter_priest_dlg = dlg { nam = 'Проповедник'; hideinv = true; entered = function() -- Проповедник после некромантии if have('burning_quarter_knife') or have('burning_quarter_halberd') then burning_quarter_priest_dlg:pon('about_godchosen'); return [[ Ты смотришь на проповедника, ожидая увидеть на его лице признаки беспокойства. Но похоже, что ничто не может стереть его торжествующую улыбку. ]]; end; -- Проповедник до некромантии burning_quarter_priest_dlg:pon('info_source'); burning_quarter_priest_dlg:pon('why'); return [[ Ты смотришь на проповедника, но твой взгляд почти сразу падает на кольцо у него на пальце. ^ -- Это Её метка, -- безумец показывает тебе руку с кольцом, -- символ того, что между вами заключена сделка. Она дарует тебе своё расположение в обмен на вечное служение. В последнее время ты тоже должен был получить такую безделушку. ^ Внутри тебя гложет странное чувство потери. ]]; end; phr = { { tag = 'info_source'; false; 'Откуда ты столько знаешь?'; [[ -- Откуда ты столько знаешь? -- спрашиваешь ты с опаской, -- про капитана и полукровку, про подполье, про Приграничье и Режим? ^ -- Тени вездесущи. Их отбрасывает кто угодно и что угодно, -- безумец поглаживает лезвие кинжала, -- тем кто способен ходить среди теней, известно многое. ]]; function() end; }; { tag = 'why'; false; 'Почему ты хочешь убить меня?'; [[ -- Почему ты хочешь убить меня? ^ -- Любой грязный оборванец может хотеть убить кого-то, -- смеётся проповедник, -- ты когда-нибудь бывал на дне колодца? Когда весь мир сжимается в пятно белого света в кольце тьмы? Ты остаёшься один на один сам с собой. Ты и более ничего лишнего. Понимаешь о чём я? ^ Ты неуверенно мотаешь головой. ^ -- Конечно, недостаточно просто спуститься на дно колодца, -- продолжает свою мысль безумец, -- нужно пробыть там какое-то время. День или два. Тогда многие вещи в жизни начинают проясняться. Тогда бы ты рабозрался, что ты всего лишь жалкий червь, ничтожество, которое ставит себя в центр вселенной. ^ Теперь в голосе проповедника слышится откровенная злоба. ^ -- Я говорю про тебя, червь! Разве ты достоин исполнять Её волю?! Подумать смешно. Но видимо, даже боги ошибаются. И я исправлю эту случайную ошибку. ]]; function() end; }; { tag = 'about_godchosen'; false; 'Сейчас здесь будет богоизбранный!'; [[ -- Сейчас здесь будет богоизбранный! -- кричишь ты проповеднику через усиливающийся гул огненной бури. ^ -- Ещё один нелепый слепой, ведомый судьбой как поводырём, -- усмехается безумец, -- всю жизнь он пытался заглушить никчёмность своего существования в битвах, а теперь стал богоизбранным. Только послушай его сейчас: одни рассуждения о долге, правосудии и законе. Как будто за этими словами скрываются бездны смысла. ^ Внезапно проповедник смотрит на тебя, словно увидел впервые. ^ -- Вы с ним чем-то похожи, не находишь? Вечный солдат и вечный дезертир. Твой век на пике и кто ты? Бродяга без собственного угла. Мыкаешься среди других оборванцев в какой-то глуши и пъёшь дни напролёт. Когда в твои руки попадает судьба целой страны, ты опять всё сводишь к бегству. Ты не просто дезертир, ты дезертир жизни. Ты бежишь от жизни прямо в лапы смерти. ]]; function() end; }; { tag = 'go_back'; always = true; '[Отвести взгляд]'; [[ Ты переводишь взгляд с проповедника на его кинжал. ]]; function() back(); end; }; } } -- Четырёхгранный кинжал проповедника burning_quarter_dagger = obj { nam = 'Кинжал проповедника'; dsc = [[ На его белом как мел лице играет хорошо знакомая тебе безумная улыбка. Хищно мерцает {кинжал в руке}. ^ ]]; act = function() return [[ Ты бросаешь косой взгляд на его меловую руку. Длинные пальцы впиваются в рукоясь кинжала, на клинке которого виден узор, изображающий нечто вроде змеи. На одном из пальцев угольком тлеет золотое кольцо, приковывающее к себе взгляд. ^ Глядя на призрачное свечение кольца, тебе приходит в голову дерзкая мысль. Пусть проповедник и выше тебя ростом, и руки у него явно длиннее, ты можешь попробовать выбить у него кинжал. ]]; end; used = function(self, what) if what == burning_quarter_fight_hammer then drop 'burning_quarter_fight_hammer'; objs('burning_quarter_fight'):del('burning_quarter_fight_hammer'); return [[ Не отрывая глаз от кольца, странным образом притягивающего твоё внимание, ты нападаешь. Вложив в удар всю силу, ты тычешь молотом как копьём прямо в руку с кинжалом. Но удар так и не достигает цели: скрюченные пальцы проповедника крепко удерживают молот. Ты пробуешь высвободить оружие, но безумная улыбка становится только шире. ^ Кольцо проповедника начинает сиять ещё ярче. Молот покрывается сетью трещин, а его рукоять наливается теплом. Прежде чем ты успеваешь хоть что-то понять, молот рассыпается в прах, а тебе под ноги падает раскалённая рукоять. ]]; end; -- GOx if what == burning_quarter_hands then return burning_quarter_mad_strike(); end; -- S10 local priest_death_text = [[ ^ -- Довольно! -- цедит проповедник, снова натягивая на искажённое болью лицо безумную улыбку, -- прими свою участь! ^ Он расправляет плечи, вытянув шею, и разводит руки в стороны. Не зная чего ещё ожидать от этого сумасшедшего, ты инстинктивно делаешь шаг назад. ^ Но проповедник ничего больше сделать не успевает. Красный всполох бъёт по глазам, и его голова катится тебе под ноги. Тело в лохмотьях плавно оседает, а на его месте появляется воин в доспехе и с мечом в руке. ^ -- Ты дождался меня, дезертир, -- спокойно произносит богоизбранный. ]]; if what == burning_quarter_halberd then priest_death_text = [[ Ты набрасываешься на проповедника с алебардой. Твой быстрый удар-обманка был нацелен прямо в бледную гримасу сумасшествия. Кинжал отводит секиру в сторону, и тогда ты проворачиваешь древко и резко дёргаешь алебарду на себя. Лезвие рассекает костлявую руку проповедника. ^ Описав широкую дугу, лезвие секиры обрушивается на клубок лохмотьев. Кинжал запаздывает, удар алебарды вырывает его из ладони проповедника вместе с несколькими пальцами. ^ Шипя проклятья, проповедник пятится, сжавшись от боли. Теперь он уже не кажется таким высоким. ]] .. priest_death_text; end; if what == burning_quarter_knife then priest_death_text = [[ Ты набрасываешься на проповедника, размахивая орочьим ножом. Твой быстрый удар-обманка был нацелен в ногу, но как только кинжал начинает парировать этот выпад, ты резко уводишь орочий нож вверх, рассекая костяшки пальцев остриём. Ты бьёшь снова, найскось, уже без обмана, и проповедник снова пытается парировать. ^ Шипя проклятья проповедник роняет на землю кинжал и несколько пальцев. Он отходит назад, сжавшись от боли, и уже не кажется таким высоким. ]] .. priest_death_text; end; if (what == burning_quarter_halberd) or (what == burning_quarter_knife) then objs('burning_quarter_fight'):del('burning_quarter_priest'); objs('burning_quarter_fight'):del('burning_quarter_dagger'); objs('burning_quarter_fight'):add('burning_quarter_priest_dead'); objs('burning_quarter_fight'):add('burning_quarter_dagger_dead'); objs('burning_quarter_fight'):add('burning_quarter_ring'); objs('burning_quarter_fight'):add('burning_quarter_godchosen'); return priest_death_text; end; end; } -- Мёртвый проповедник burning_quarter_priest_dead = obj { nam = 'Мёртвый проповедник'; dsc = [[ У тебя под ногами лежит {труп проповедника}. ]]; act = function() return [[ Ты смотришь на обезглавленное тело в рваной рясе. Свернувшееся на земле среди лохмотьев, оно уже не кажется таким громадным. ^ Ты находишь голову неподалёку. Лицо на ней сохранило прежние ликование и спятившую улыбку. ]]; end; } -- Кинжал мёртвого проповедника burning_quarter_dagger_dead = obj { nam = 'Кинжал мёртвого проповедника'; dsc = [[ Рядом с ним валяется {кинжал} в окружении отрубленных пальцев. ]]; act = function() return [[ Ты присматриваешься к кинжалу. Тебе начинает казаться, что его рукоять отделана золотом и драгоценными камнями. Тебе остаётся лишь догадываться откуда у этого оборванца такая дорогая вешь. ]]; end; used = function(self, what) -- GO8 if what == burning_quarter_hands then walk 'burning_quarter_part_II_gameover'; return [[ Странное чувство подмывает тебя подобрать кинжал. Его металл соблазнительно мерцает серым сиянием. Поддавшись слепому желанию, ты отбрасываешь своё оружие, чтобы поднять драгоценный клинок. ^ На дожидаясь пока ты завладеешь кинжалом, молния меча поражает тебя в шею. ^ -- Правосудие свершилось, -- произносит богоизбранный, вытирая клинок о твою одежду. ^ Но ты этого уже не слышишь. ]]; end; end; } -- Кольцо проповедника burning_quarter_ring = obj { nam = 'Кольцо'; dsc = [[ На одном из них поблескивает {кольцо}. ]]; act = function() return [[ Ты внимательно смотришь на кольцо, и в памяти вспыхивает воспоминание. Тот амулет, что ты нашёл в пещере, точно так же притягивал твой взгляд. ^ Тебе начинает казаться, что руки сами тянутся за кольцом. ]]; end; inv = [[ Ты машинально щупаешь кольцо. Металл местами выщерблен и поцарапан. Ты рассматриваешь драгоценность, и не находишь в ней ничего примечательного кроме бликов пожара. ^ Ты задаёшься вопросом, чтоже могло так притягивать тебя к этой безделушке, но не находишь ответа. ]]; used = function(self, what) if what == burning_quarter_hands then local take_text = [[ Ты встаёшь на колено, чтобы подобрать кольцо, и латник заносит над тобой меч. ^ -- Вижу, ты сам ищешь правосудия, -- замечает богоизбранный. ^ Ты едва успеваешь отпрыгнуть, когда меч вонзается глубоко в землю в шаге от тебя. Во взгляде старика читается осуждение. Ты вскакиваешь, зачем-то нацепив кольцо на палец. ^ Богоизбранный с усилием выдёргивает клинок из земли и сразу же отправляет его в бой. ]]; -- GO9 if have('burning_quarter_halberd') then walk 'burning_quarter_part_II_gameover'; return take_text .. [[ Ты машинало закрываешься древком алебарды, но меч без труда разрубает его, оставив у тебя на груди кровавую полосу. Покачнувшись, ты уже не успеваешь отреагировать на следующий удар, крушащий тебе ключицу. ^ Ты падаешь на колени, ослепнув от боли и не видя занесённого над тобой меча. ]]; end; -- S11 take 'burning_quarter_ring'; objs('burning_quarter_fight'):del('burning_quarter_godchosen'); objs('burning_quarter_fight'):add('burning_quarter_godchosen_down'); return take_text .. [[ Ты машинало закрываешься ножом урук-хай, и с удивлением видишь как латник отшатывается после удара, словно его меч налетел на стену. Оправившись, он снова нападает, и полуторный меч сцепляется с орочьим ножом-переростком, высекая искры. Ухватившись за эфесы двумя руками, вы застыли в борьбе лицом к лицу. Ты смотришь как под шрамами и морщинами богоизбранного проступают вены. Твои мышцы переполняет сила, и стук крови в висках заглушает скрежет металла. Натиск латника, напротив, слабеет. ^ Неожиданно меч уступает, и ты обрушиваешь на богозибранного всю накопившуюся мощь. Закованный в броню латник как кукла летит на землю, громыхая и звеня. ^ Ты переводишь дух, глядя как старик поднимается на ноги. ]]; end; end; } -- Трупы с оружием burning_quarter_armed_corpses = obj { nam = 'Трупы'; dsc = [[ Вокруг вас раскиданы {трупы} людей и орков. Некоторые из них сжимают в окоченевших руках оружие. ]]; act = function() burning_quarter_knuckle:enable(); burning_quarter_knife:enable(); burning_quarter_halberd:enable(); burning_quarter_armed_corpses:disable(); return [[ Ты окидываешь взглядом трупы, по армейской привычке примечая какое-нибудь сносное оружие. Ближе всего к тебе покоится пара вооружённых урук-хай и стражник. ]]; end; } -- Зомби burning_quarter_zombies = obj { nam = 'Зомби'; dsc = [[ Тебя обступают покачивающиеся мертвецы с оружием в окоченевших руках. ]]; } -- Кастет урук-хай burning_quarter_knuckle = obj { nam = 'Кастет урук-хай'; dsc = [[ Чуть поодаль лежит труп здоровенного урука с {кастетом} в руке. ]]; act = function() return [[ Ты бросаешь взгляд на бандита и его странное оружие. Похоже, что орк сваял свой кастет из солдатского шлема, гвоздей и ремней. Таким приспособлением можно без страха парировать удары от мечей и топоров, или даже попытаться задержать лезвие между гвоздей-шипов. Но врядли у тебя получится провести с этой штукой хороший удар. ]]; end; inv = [[ Ты придирчиво осматриваешь кастет на своей руке. Ржавые гвозди на шлеме почернели от запёкшейся крови. Рукоять внутри шлема уже вымокла от пота. ]]; used = function(self, what) if what == burning_quarter_hands then -- Взять оружие objs('burning_quarter_fight'):del(self); inv():add(self); local s1 = burning_quarter_weapon_change(); -- Убрать одного зомбака burning_quarter_zombie_fighter:disable(); -- Поднять остальных (S4 S5 S6 S7) local s = burning_quarter_en_garde(); local pd_text = burning_quarter_priest_disappear(); return (s1 .. [[ Ты с трудом стягиваешь это подобие кастета с лапы орка, под насмешливым взглядом проповедника. Кое-как затянув ремни вокруг локтя, ты надеешься, что всё это не разлетиться после первого же удара. ]] .. pd_text .. s); end; end; } burning_quarter_knuckle:disable(); -- Зомби боец урук-хай burning_quarter_zombie_fighter = obj { nam = 'Зомби боец урук-хай'; dsc = [[ Бледный {урук-боец} не спускает с тебя взгляда неморгающих глаз. ]]; act = function() return [[ Ты ловишь пустой взгляд мертвеца. Вокруг множества ран на его теле запеклась кровь. Только сейчас ты обращаешь внимание, что на этом орке совсем нет брони. Кастет, которым орк вооружён, выдает в нём бойца. Когда урук-хай, принимают в банду неопытного урук, его заставляют драться без брони с кастетами вместо оружия. ^ Ты ещё раз осматриваешь несуразное оружие орка. Таким кастетом можно легко отводить удары мечей и кинжалов, и увечить плоть. ]]; end; used = function(self, what) -- GO3 if what == burning_quarter_knuckle then walk 'burning_quarter_part_II_gameover'; return [[ Ты пытаешься ударить мертвеца кастетом и осознаёшь, что совсем не умеешь обращаться с этим оружием. После пары неудачных замахов ты теряешь равновесие, и удар алебарды рассекает тебе артерию на шее. Смерть приходит быстро. ]]; end; -- GO4 if what == burning_quarter_knife then walk 'burning_quarter_part_II_gameover'; return [[ Ты подбегаешь к бойцу урук-хай с тесаком в руках и делаешь быстрый выпад, метя шею. Мертвец нелепо отклоняется назад и нож врезается под ему ключицу. Ты с трудом высвобождаешь оружие, едва успев подставить тесак под удар кастета. Лезвие ножа намертво застревает между шипами. Ты лишь напрасно тратишь время, в попытках вернуть своё оружие, и дав смердящему трупу схватить тебя свободной рукой за шею. Вместе с удушьем ты чувствуешь как твои пятки отрываются от земли. Брыкаясь ногами и колотя кулаком мертвецу по морде, ты не в силах ослабить хватку орочьей лапы. ^ Раскат боли от вонзившейся в спину алебарды лишает тебя чувств. ]]; end; -- S9 if what == burning_quarter_halberd then local s = burning_quarter_dmz(); return ([[ Перехватив алебарду по-удобней, ты наотмашь рубишь ближайшего мертвеца. Урук-хай делает неуклюжую попытку защититься кастетом, но секира просто срезает ему кисть и чертит ещё одну чёрную полосу на широкой груди. ^ Второй удар ты наносишь сверху вниз, и алебарда без труда раскалывает голову нерасторопного орка. Мертвец падает на землю. ]] .. s); end; -- GO2 if what == burning_quarter_hands then -- walk 'burning_quarter_part_II_gameover'; return [[ Пока ты смотришь на пошатывающегося урук-бойца, тебе в голову приходит безумная мысль попытаться выбить у него кастет из руки. ^ Но глядя на шипы, ты решаешь отказаться от этой безнадёжной затеи. ]]; end; -- GO2 if what == burning_quarter_fight_hammer then walk 'burning_quarter_part_II_gameover'; return [[ Занеся молот над головой, ты нападаешь на ближайшего мертвеца. От ужасного удара голова урук-бойца просто лопается, но твоё ликование сменяется жгучей болью в боку. Мертвец успел всадить кастет тебе под рёбра. Урук-хай с разможённой головой падает на спину и едва не увлекает тебя за собой. С криком вырвав кастет из раны, ты оказываешься на коленях, не в силах больше пошевелиться. ^ Секира алебарды прерывает твои мучения. ]]; end; end; } -- Нож головореза урук burning_quarter_knife = obj { nam = 'Нож головореза урук'; dsc = [[ Рядом распласталось тело головореза урук-хай. В его кулаке зажат {большой нож}. ]]; act = function() return [[ Ты присматриваешься к широкому лезвию орочьего ножа. По людским меркам, это полноценный короткий меч, но в руке орка оружие и вправду походит на тесак. Таким запросто можно разрубить древко копья или запястье. ]]; end; inv = [[ Ты крутишь тесак в руке на манер меча. Нож кажется тебе хорошо сбалансированным. ]]; used = function(self, what) if what == burning_quarter_hands then -- Взять оружие objs('burning_quarter_fight'):del(self); inv():add(self); local s1 = burning_quarter_weapon_change(); -- Убрать одного зомбака burning_quarter_zombie_thug:disable(); -- Поднять остальных (S4 S5 S6 S7) local s = burning_quarter_en_garde(); local pd_text = burning_quarter_priest_disappear(); return (s1 .. [[ Ты разжимаешь дубовые пальцы урук-хай и забираешь нож. Он тяжеловат, как ты и ожидал, и хорошо заточен. ]] .. pd_text .. s); end; end; } burning_quarter_knife:disable(); -- Зомби головорез урук burning_quarter_zombie_thug = obj { nam = ''; dsc = [[ Утыканный стрелами {головорез} низко опустил голову, глядя себе под ноги. ]]; act = function() return [[ Ты рассматриваешь головореза. Десяток стрел нисколько не мешает ему ковылять в твою сторону, размахивая здоровенным тесаком. ]]; end; used = function(self, what) -- GO3 if what == burning_quarter_knuckle then walk 'burning_quarter_part_II_gameover'; return [[ Обходя мертвеца с боку, ты бъёшь его кастетом в голову. Удар выходит неуклюжим, и ты едва не выворачиваешь себе кисть. На морде урук остаётся уродливый след от шипов и только. Ты повторяешь выпад, и на этот раз орк покачивается, но только для того, чтобы полоснусть тебя ножём по руке. Она повисает плетью, и отвлёкшись на боль, ты не замечаешь как второй мертвец подступает к тебе сзади. Алебарда взлетает и опускается тебе на затылок. ]]; end; -- GO5 if what == burning_quarter_halberd then walk 'burning_quarter_part_II_gameover'; return [[ Перехватив алебарду по-удобней, ты наотмашь рубишь ближайшего мертвеца. Секира врезается в мясистое плечо урук-хай, и застревает в кости. В ответ головорез одним движением перерубает древко алебарды своим тесаком. С усилием ты выдёргиваешь секиру из смердящего трупа, и вонзаешь её в уродливую морду. ^ Твой победный крик обрывает удар кастета по затылку. ]]; end; -- GO2 if what == burning_quarter_hands then walk 'burning_quarter_part_II_gameover'; return [[ Пока ты смотришь на пошатывающегося урук-головореза, тебе в голову приходит безумная мысль попытаться выбить у него тесак из руки. ^ Ты обходишь мертвеца, и хватаешь его руку в захват. Но здоровенный орк, просто сбрасывает тебя. Упав на четвереньки, ты не успеваешь увернуться от тесака головореза. ]]; end; -- GO2 if what == burning_quarter_fight_hammer then walk 'burning_quarter_part_II_gameover'; return [[ Занеся молот над головой, ты нападаешь на ближайшего мертвеца. От ужасного удара голова урук-головореза просто лопается, но твоё ликование сменяется жгучей болью в боку. Мертвец успел всадить нож тебе под рёбра. Урук-хай с разможённой головой падает на спину и едва не увлекает тебя за собой. С криком вырвав тесак из раны, ты оказываешься на коленях, не в силах больше пошевелиться. ^ Секира алебарды прерывает твои мучения. ]]; end; end; } -- Алебарда burning_quarter_halberd = obj { nam = 'Алебарда'; dsc = [[ В другой стороне валяется растерзанный стражник, так и не расставшийся со своей {алебардой}. ]]; act = function() return [[ Ты изучаешь алебарду взглядом. Прекрасное оружие, чтобы держать врага на расстоянии. Особенно, если этот враг больше тебя. ]]; end; inv = [[ Ты осматриваешь алебарду. Лезвие и древко оружия покрыто густой орочьей кровью. ]]; used = function(self, what) if what == burning_quarter_hands then -- Взять оружие objs('burning_quarter_fight'):del(self); inv():add(self); local s1 = burning_quarter_weapon_change(); -- Убрать одного зомбака burning_quarter_zombie_guard:disable(); -- Поднять остальных (S4 S5 S6 S7) local s = burning_quarter_en_garde(); local pd_text = burning_quarter_priest_disappear(); return (s1 .. [[ Ты отбираешь у мертвеца алебарду и делаешь пару пробных замахов. После пудового молота ты управляешься с ней на удивление легко. ]] .. pd_text .. s); end; end; } burning_quarter_halberd:disable(); -- Зомби стражник burning_quarter_zombie_guard = obj { nam = 'Зомби стражник'; dsc = [[ Позади тебя {выпотрошенный стражник} следит за твоими движениями, щёлкая тем, что осталось от челюстей. ]]; act = function() return [[ Ты с омерзением смотришь на изуродованного стражника. Окровавленная алебарда у него в руках до сих пор выглядит грозно. Сложно будет подобраться близко к вооружённому подобным оружием. Хотя ты помнишь, как на войне урук-хай разрубали древки копий и пик. Может быть и у тебя получится что-то подобное. ]]; end; used = function(self, what) -- GO3 if what == burning_quarter_knuckle then walk 'burning_quarter_part_II_gameover'; return [[ Ты подскакиваешь к мертвецу и бъёшь его кастетом в месиво на месте рта. Удар выходит неуклюжим, и ты едва не выворачиваешь себе кисть. Но и этого хватает, чтобы бывший стражник полетел на землю. ^ Воодушевившись, ты с разбегу врезаешься в ходячий труп головореза. Кастет крушит орочьи клыки, но тот остаётся стоять на ногах. Ты повторяешь выпад, но выбрасываешь руку слишком далеко, так что урук успевает полоснусть тебя ножём по локтю. Рука повисает плетью, и отвлёкшись на боль, ты не замечаешь как второй мертвец подползает к тебе сзади. Скрюченные пальцы смыкаются на твоей голени, и стражник со скрученной шеей дёргает тебя за ногу. Повалившись на колено, ты уже не успеваешь защититься от тесака головореза. Бурое лезвие рассекает тебе лицо, и глаза заливает кровью. ]]; end; -- S8 if what == burning_quarter_knife then local s = burning_quarter_dmz(); return ([[ Ты бросаешься на бывшего стражника с ножом в руках и рубишь наотмашь. Орочий тесак с лёгкостью разрубает древко алебарды. Мертвец замахивается на тебя секирой, но ты ныряешь ему под руку, и пинком валишь на четвереньки. Тебе приходится повозиться с ножом, чтобы угомонить труп окончательно. ]] .. s); end; -- GO2 if what == burning_quarter_hands then walk 'burning_quarter_part_II_gameover'; return [[ Ты решаешь лишить мёртвого стражника его оружия. Ухватившись за древко, ты просто выхватываешь алебарду из скрюченных пальцев. Оттолкнув мертвеца, та замахиваешься для удара, но тот внезапно напрыгивает на тебя и сбивает с ног. В твою шею впиваются остатки зубов и обломки нижней челюсти. Ты пытаешься отбиться, от обезумевшего стражника, но силы покидают тебя вместе с кровю. Чёрное небо становится всё ближе, заполняя всё вокруг. ]]; end; -- GO2 if what == burning_quarter_fight_hammer then walk 'burning_quarter_part_II_gameover'; return [[ Занеся молот над головой, ты нападаешь на ближайшего мертвеца. Удар молота сносит шатающегося стражника, раздробив ему грудную клетку. ^ Ты слышишь как сзади к тебе подбирается пара мёртвых урук-хай. Молот снова обрушивается на врага, но орк остаётся на ногах, несмотря на сломанные ключицу и рёбра. Чёрные пальцы смыкаются на рукояти молота, крепко удерживая твоё оружие. Ты разворачиваешься, чтобы поднять алебарду, но второй урук-хай оказывается неожиданно проворным. Тесак вонзается тебе под рёбра, на мгновение приподняв тебя над землёй. C засевшим в спине как крюк ножом, ты пытаешься спастись от надвигающейся смерти. Но огромная орочья лапа хватает тебя за голову, лишая зрения и возможности дышать. ]]; end; end; } -- Богоизбранный burning_quarter_godchosen = obj { nam = 'Кевраза'; dsc = [[ ^ Напротив тебя стоит закованный в доспех {богоизбранный}. ]]; act = function() walk 'burning_quarter_gochosen_dlg'; end; used = function(self, what) local killed_by_godchosen = false; local killed_by_godchosen_text; local unreal_attack_text = [[ Ты нерешительно ступаешь в сторону богоизбранного, терзаемый раздумьями, как тебе следует напасть. Но латник избавляет тебя от мучений выбора, атакуя первым. ^ Лишь на долю мгновения, рука сжимающая меч исчзает из твоего поля зрения. И этого времени вполне хватает, чтобы богоизбранный перехватил оружие и ударил под неожиданным для тебя углом. ]]; -- GO7 if (what == burning_quarter_knuckle) then killed_by_godchosen_text = unreal_attack_text .. [[ Ты успеваешь отвести удар кастетом, высекая искры из из лезвия меча. Но описав дугу клинок возвращается. Словно случайно, он едва задевает тебя по голени. После следующего взмаха меча, ты лишаешься руки с кастетом. ]]; killed_by_godchosen = true; end; if (what == burning_quarter_knife) then killed_by_godchosen_text = [[ Сорвавшись с места, ты бежишь богоизбранному за спину, стремясь подобраться к нему как можно ближе, чтобы сделать его длинный меч бесполезным. Ты рассчитываешь, что на неповоротливость латника, тот оказывается на удивление проворным. Меч сталкивается с орочьим тесаком, и поделие урук-хай оказывается легче. Нож вылетает из твоей руки, а на плече у тебя остаётся глубокая рана. Ты даже не понял, откуда она там взялась. Ты пятишься, ищя взглядом новое оружие. ^ Стремительный удар поражает тебя в бедро, от чего нога тут же отнимается. ]]; killed_by_godchosen = true; end; if (what == burning_quarter_halberd) then killed_by_godchosen_text = [[ С алебардой в руках, ты идёшь вокруг богоизбранного, выискивая уязвимое место. Хмурясь, латник не спускает с тебя глаз. ^ Секира выпрыгивает вперёд, и тут же летит вниз, обрубленная. На плече у тебя остаётся глубокая рана. Ты даже не понял, откуда она там взялась. Уронив скользкое от пота древко, ты пятишься, ищя взглядом новое оружие. ^ Стремительный удар поражает тебя в бедро, от чего нога тут же отнимается. ]]; killed_by_godchosen = true; end; if (what == burning_quarter_hands) then killed_by_godchosen_text = [[ Ты кладёшь оружие на землю и показываешь богоизбранному открытые ладони. ^ -- Не думал, что ты примешь свою судьбу так легко, -- замечает богоизбранный. ^ -- Может быть, мы сможем отложить правосудие и приговор? -- спрашиваешь ты, -- по крайней мере ещё на какое-то время. ^ Латник долго смотрит на тебя. ^ -- Итак, по твоему, я мог бы позволить тебе взять в руки оружие и встать рядом с собой? -- богоизбранный взвешивает каждое слово. Ты медленно киваешь. ^ -- Позволить тебе сражаться против этих орков? -- продолжает латник, -- чтобы ты искупил свою вину кровью? ^ Вы молча смотрите друг на друга. ^ -- Но разве появление этих орков не твоих рук дело? -- прерывает молчание старый вояка, -- сколько крови ты задолжал этому городу, погибающему теперь в огне? Такую вину тебе уже не искупить. ^ Богоизбранный шагает к тебе, занеся меч. Ты бросаешься на землю за оружием, и клинок настигает тебя. ]]; killed_by_godchosen = true; end; if (what == burning_quarter_fight_hammer) then killed_by_godchosen_text = unreal_attack_text .. [[ Ты отбиваешь молотом нацеленный в тебя клинок, но недостаточно быстро. Тебе рассекает голову, и кровь тут же заливает правую сторону лица. Следующий выпад тебе отразить уже не удаётся, лезвие входит в бедро, и тут же выскакивает назад. ]]; killed_by_godchosen = true; end; if killed_by_godchosen then walk 'burning_quarter_part_II_gameover'; return [[ ^ Ты падаешь на колени перед богоизбранным, чувствуя, как биение сердца само охотно выплёскивает из тебя жизнь. Латник отступает, оценивающе окидывая тебя взглядом. В руках у него появляется красная тряпица, и меч послушно позволяет стереть с себя твою кровь. ^ -- Я вижу в твоих глазах жажду искупления. Это глаза преступника, я могу распознать их, -- неторопливо произносит богоизбранный, -- я подарю тебе столь желаемое правосудие. ^ Ты хочешь что-то ответить, но уже не в силах говорить. Латник подходит к тебе, взявшись за меч двумя руками. Огонь, отражённый клинком, ослепляет тебя. ]]; end; end; } -- Диалог с богоизбранным burning_quarter_gochosen_dlg = dlg { nam = 'Богоибранный'; hideinv = true; entered = function() return [[ Ты внимательно осматриваешь богоизбранного с ног до лысой головы. За время вашей последней встречи на его латах появилось несколько вмятин, но их не так-то просто разглядеть под брызгами и потёками крови. Ножны богоизбранного теперь пустуют, а жуткий двуручный меч сменил полуторный бастард. ^ Ты не знаешь, как этот старик выжил там, на эшафоте, но если он лично одолел главаря орочьей банды, у тебя против него нет никаких шансов. ]]; end; phr = { { tag = 'why'; true; 'Зачем преследовать меня?'; [[ ^ -- Зачем преследовать меня? -- перекрикиваешь ты шум очередного рушащегося здания. ^ -- Ты думаешь ты один такой? -- отвечает богоизбранный не меняя серьёзного выражения лица, -- да таких ничтожеств дезертиров -- целая страна. Это из-за вас эти земли, вашу родину, пожирает сейчас другое государство. ^ -- Если нас таких много, то почему бы тебе не погнаться за кем-нибудь ещё? ^ -- Ты думаешь, это я гонюсь за тобой? -- искренне удивляется богоизбранный, -- ты пытаешься сбежать от бремени жизни. Жить -- это значит принимать решение и нести за него ответственность. Я обязался быть палачом. Это грязное дело, но я привык доводить дела до конца. ^ Он кивает на голову проповедника у тебя под ногами. ]]; function() burning_quarter_gochosen_dlg:pon('why_so_seriosly'); end; }; { tag = 'why_so_seriosly'; false; 'К чему все эти разговоры о долге и правосудии?'; [[ -- К чему все эти разговоры о долге и правосудии? -- возражаешь ты срывающимся голосом, -- разве сейчас они к месту? Этот город превратился в пылающий ад. Нужно постараться, чтобы спастись. Я могу вывести нас отсюда, я знаю безопасный путь. ^ -- В твоём возрасте я был обычным солдатом, наёмником, -- старый вояка смотрит сквозь тебя, -- для меня существовали только сражения и деньги. Но когда я стал богоизбранным, я узнал, что такое долг перед родиной и перед собой. ^ -- Если ты погибнешь здесь, ты больше не сможешь исполнять свой долг богоизбранного. ^ -- Это ещё неизвестно, -- качает головой старик, -- долг это то, на чём стоит наш хрупкий человеческий мирок. Если каждый солдат начнёт отказываться от выполнения приказа, только потому что его жизни угрожает опасность, то этот мирок рухнет. ^ Богоизбранный потрясает мечом. ^ -- Никакие уловки не помогут, дезертир. Прими свой приговор. ]]; function() burning_quarter_gochosen_dlg:pon('why'); back(); end; }; } } -- Богоизрабнный после падения burning_quarter_godchosen_down = obj { nam = 'Кевраза'; dsc = [[ ^ {Богоизбранный} устало опирается на меч. ]]; act = function() return [[ Ты внимательно смотришь на богоизбранного. Кажется, что он совершенно бездвижен. Меч, на который он облокачивается, вошёл глубоко в землю. Фигуру латника, схожую с памятником или с големом оживляют лишь глаза. ^ Они приковывают твоё внимание. Несмотря на резкие тени, избороздившие его лицо, запавшие старческие глаза богоизбранного прекрасно видно. Мутный синеватый свет, прорывается из под тяжёлых век. Ты уже видел подобный свет в глазах мага-крысы. Тебе кажется, что богоизбранный собирается колдовать. ]]; end; used = function(self, what) -- GO7 -- Используем руки if (what == burning_quarter_hands) then return [[ Тебе почему-то кажется, что богоизбранный не настроен для разговоров. Даже если ты сложишь оружие, он не станет с тобой говорить. Безумную мысль напасть на латника без оружия, ты тоже отметаешь. ]]; end; -- Используем оружие -- Надеемся, что это будет нож урук-хай if (what == burning_quarter_knife) then walk 'burning_quarter_part_II_gameover'; return [[ Надеясь, что падение не прошло бесследно, ты выступаешь против латника с тесаком урук-хай. Огромный нож приятно тяготит твою руку. ^ Стоит тебе сорваться с места, как ты чувствуешь, что воздух вокруг словно сгущается. Твои движения странным образом замедляются, а тело наливается тяжестью. Едва добравшись до неподвижного богоизбранного, ты отводишь тесак для удара. Тебе кажется, что проходит бездна времени после замаха, и теперь нож начинает приближаться ко всё ещё бездвижному латнику. ^ Но до старика орочье лезвие так и не добирается. Меч оглушительно свистит в воздухе, и ты как-то странно валишься на бок. На глаза опускается пелена. Ты не успеваешь понять, что удар богоизбранного разрубил тебя пополам. ]]; end; -- Надеемся, что это будет нож урук-хай if ( (what == burning_quarter_knuckle) or (what == burning_quarter_halberd) or (what == burning_quarter_fight_hammer) ) then walk 'burning_quarter_part_II_gameover'; return [[ Надеясь, что падение не прошло бесследно, ты выступаешь против латника. ^ Стоит тебе сорваться с места, как ты чувствуешь, что воздух вокруг словно сгущается. Твои движения странным образом замедляются, а тело наливается тяжестью. Тебе кажется, что проходит бездна времени, прежде чем тебе удаётся добраться до богоизбранного. ^ Меч оглушительно свистит в воздухе, и ты как-то странно валишься на бок. На глаза опускается пелена. Ты не успеваешь понять, что удар богоизбранного разрубил тебя пополам. ]]; end; end; }
gpl-3.0
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/EventMouse.lua
18
4781
-------------------------------- -- @module EventMouse -- @extend Event -- @parent_module cc -------------------------------- -- Returns the previous touch location in screen coordinates.<br> -- return The previous touch location in screen coordinates.<br> -- js NA -- @function [parent=#EventMouse] getPreviousLocationInView -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- Returns the current touch location in OpenGL coordinates.<br> -- return The current touch location in OpenGL coordinates. -- @function [parent=#EventMouse] getLocation -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- Get mouse button.<br> -- return The mouse button.<br> -- js getButton -- @function [parent=#EventMouse] getMouseButton -- @param self -- @return int#int ret (return value: int) -------------------------------- -- Returns the previous touch location in OpenGL coordinates.<br> -- return The previous touch location in OpenGL coordinates.<br> -- js NA -- @function [parent=#EventMouse] getPreviousLocation -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- Returns the delta of 2 current touches locations in screen coordinates.<br> -- return The delta of 2 current touches locations in screen coordinates. -- @function [parent=#EventMouse] getDelta -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- Set mouse scroll data.<br> -- param scrollX The scroll data of x axis.<br> -- param scrollY The scroll data of y axis. -- @function [parent=#EventMouse] setScrollData -- @param self -- @param #float scrollX -- @param #float scrollY -- @return EventMouse#EventMouse self (return value: cc.EventMouse) -------------------------------- -- Returns the start touch location in screen coordinates.<br> -- return The start touch location in screen coordinates.<br> -- js NA -- @function [parent=#EventMouse] getStartLocationInView -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- Returns the start touch location in OpenGL coordinates.<br> -- return The start touch location in OpenGL coordinates.<br> -- js NA -- @function [parent=#EventMouse] getStartLocation -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- Set mouse button.<br> -- param button a given mouse button.<br> -- js setButton -- @function [parent=#EventMouse] setMouseButton -- @param self -- @param #int button -- @return EventMouse#EventMouse self (return value: cc.EventMouse) -------------------------------- -- Returns the current touch location in screen coordinates.<br> -- return The current touch location in screen coordinates. -- @function [parent=#EventMouse] getLocationInView -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- Get mouse scroll data of y axis.<br> -- return The scroll data of y axis. -- @function [parent=#EventMouse] getScrollY -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Get mouse scroll data of x axis.<br> -- return The scroll data of x axis. -- @function [parent=#EventMouse] getScrollX -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Get the cursor position of x axis.<br> -- return The x coordinate of cursor position.<br> -- js getLocationX -- @function [parent=#EventMouse] getCursorX -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Get the cursor position of y axis.<br> -- return The y coordinate of cursor position.<br> -- js getLocationY -- @function [parent=#EventMouse] getCursorY -- @param self -- @return float#float ret (return value: float) -------------------------------- -- Set the cursor position.<br> -- param x The x coordinate of cursor position.<br> -- param y The y coordinate of cursor position.<br> -- js setLocation -- @function [parent=#EventMouse] setCursorPosition -- @param self -- @param #float x -- @param #float y -- @return EventMouse#EventMouse self (return value: cc.EventMouse) -------------------------------- -- Constructor.<br> -- param mouseEventCode A given mouse event type.<br> -- js ctor -- @function [parent=#EventMouse] EventMouse -- @param self -- @param #int mouseEventCode -- @return EventMouse#EventMouse self (return value: cc.EventMouse) return nil
mit
FreeScienceCommunity/PLPlot
examples/lua/x13.lua
1
2427
--[[ Pie chart demo. Copyright (C) 2008 Werner Smekal This file is part of PLplot. PLplot is free software you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation either version 2 of the License, or (at your option) any later version. PLplot 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with PLplot if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA --]] -- initialise Lua bindings for PLplot examples. dofile("plplot_examples.lua") text = { "Maurice", "Geoffrey", "Alan", "Rafael", "Vince" } -------------------------------------------------------------------------- -- main -- -- Does a simple pie chart. -------------------------------------------------------------------------- per = { 10, 32, 12, 30, 16 } -- Parse and process command line arguments pl.parseopts(arg, pl.PL_PARSE_FULL); -- Initialize plplot pl.init() pl.adv(0) -- Ensure window has aspect ratio of one so circle is -- plotted as a circle. pl.vasp(1) pl.wind(0, 10, 0, 10) pl.col0(2) -- n.b. all theta quantities scaled by 2*M_PI/500 to be integers to avoid --floating point logic problems. theta0 = 0 dthet = 1 for i = 1, 5 do x = { 5 } y = { 5 } j = 2 -- n.b. the theta quantities multiplied by 2*math.pi/500 afterward so -- in fact per is interpreted as a percentage. theta1 = theta0 + 5 * per[i] if i == 5 then theta1 = 500 end for theta = theta0, theta1, dthet do x[j] = 5 + 3 * math.cos(2*math.pi/500*theta) y[j] = 5 + 3 * math.sin(2*math.pi/500*theta) j = j + 1 thetasave=theta end pl.col0(i) pl.psty(((i + 2) % 8) + 1) pl.fill(x, y) pl.col0(1) pl.line(x, y) just = 2*math.pi/500*(theta0 + theta1)/2 dx = 0.25 * math.cos(just) dy = 0.25 * math.sin(just) if (theta0 + theta1)<250 or (theta0 + theta1)>750 then just = 0 else just = 1 end pl.ptex((x[(j-1)/2+1] + dx), (y[(j-1)/2+1] + dy), 1, 0, just, text[i]); theta0 = thetasave end pl.font(2) pl.schr(0, 1.3) pl.ptex(5, 9, 1, 0, 0.5, "Percentage of Sales") pl.plend()
lgpl-2.1
JarnoVgr/Mr.Green-MTA-Resources
resources/[gameplay]/gcshop/items/paintjob/paintjob_c.lua
1
18753
------------------------------------ --- Drawing custom paintjobs --- ------------------------------------ local client_path = 'items/paintjob/'; function onClientElementDataChange(name) if name ~= 'gcshop.custompaintjob' then return end local val = getElementData(source, 'gcshop.custompaintjob') if val ~= nil then addShaders(source, val) --outputDebugString("c add custom paintjob") else removeWorldTexture(source) --outputDebugString("c rem custom paintjob") end end addEventHandler('onClientElementDataChange', root, onClientElementDataChange) local textureVehicle = { [500] = { "vehiclegrunge256","*map*" }, [520] = "hydrabody256", [552] = { "vehiclegrunge256","*map*" }, [584] = {"petrotr92interior128","petroltr92decal256"}, [521] = "fcr90092body128", [405] = { "vehiclegrunge256","*map*" }, [585] = { "vehiclegrunge256","*map*" }, [437] = {"vehiclegrunge256","*map*","bus92decals128","coach92interior128","vehiclegeneric256"}, [453] = "vehiclegrunge256","*map*", [469] = "sparrow92body128", [485] = "vehiclegrunge256","*map*", [501] = "rcgoblin92texpage128", [522] = {"nrg50092body128","vehiclegeneric256" }, [554] = "vehiclegrunge256","*map*", [586] = {"wayfarerbody8bit128"}, [523] = "copbike92body128", [406] = "vehiclegrunge256","*map*" , [587] = "vehiclegrunge256","*map*" , [438] = { "vehiclegrunge256","*map*" }, [454] = { "vehiclegrunge256","*map*" }, [470] = { "vehiclegrunge256","*map*" }, [486] = { "vehiclegrunge256","*map*" }, [502] = { "vehiclegrunge256","*map*" }, [524] = { "vehiclegrunge256","*map*" }, [556] = "monstera92body256a", [588] = "hotdog92body256", [525] = { "vehiclegrunge256","*map*" }, [407] = { "vehiclegrunge256","*map*" }, [589] = { "vehiclegrunge256","*map*" }, [439] = { "vehiclegrunge256","*map*" }, [455] = { "vehiclegrunge256","*map*" }, [471] = { "vehiclegrunge256","*map*" }, [487] = "maverick92body128", [503] = { "vehiclegrunge256","*map*" }, [526] = { "vehiclegrunge256","*map*" }, [558] = { "vehiclegrunge256","*map*","@hite" }, [590] = "freibox92texpage256", [527] = { "vehiclegrunge256","*map*" }, [408] = { "trash92body128", "vehiclegrunge256","*map*" }, [424] = { "vehiclegrunge256","*map*" }, [440] = {"rumpo92adverts256","vehiclegrunge256"}, [456] = { "yankee92logos", "vehiclegrunge256","*map*" }, [472] = { "vehiclegrunge256","*map*" }, [488] = { "vehiclegrunge256","*map*","polmavbody128a"}, [504] = { "vehiclegrunge256","*map*" }, [528] = { "vehiclegrunge256","*map*" }, [560] = { "vehiclegrunge256","*map*","#emapsultanbody256" }, [592] = {"andromeda92wing", "andromeda92body"}, [529] = { "vehiclegrunge256","*map*" }, [409] = { "vehiclegrunge256","*map*" }, [593] = "dodo92body8bit256", [441] = "vehiclegeneric256", [457] = { "vehiclegrunge256","*map*" }, [473] = { "vehiclegrunge256","*map*" }, [489] = { "vehiclegrunge256","*map*" }, [505] = { "vehiclegrunge256","*map*" }, [530] = { "vehiclegrunge256","*map*" }, [562] = { "vehiclegrunge256","*map*" }, [594] = "rccam92pot64", [531] = { "vehiclegrunge256","*map*" }, [410] = { "vehiclegrunge256","*map*" }, [426] = { "vehiclegrunge256","*map*" }, [442] = { "vehiclegrunge256","*map*" }, [458] = { "vehiclegrunge256","*map*" }, [474] = { "vehiclegrunge256","*map*" }, [490] = { "vehiclegrunge256","*map*" }, [506] = { "vehiclegrunge256","*map*" }, [532] = "combinetexpage128", [564] = "rctiger92body128", [596] = { "vehiclegrunge256","*map*" }, [533] = { "vehiclegrunge256","*map*" }, [411] = { "vehiclegrunge256","*map*" }, [597] = { "vehiclegrunge256","*map*" }, [443] = { "vehiclegrunge256","*map*" }, [459] = { "vehiclegrunge256","*map*" }, [475] = { "vehiclegrunge256","*map*" }, [491] = { "vehiclegrunge256","*map*" }, [507] = { "vehiclegrunge256","*map*" }, [534] = { "vehiclegrunge256","*map*","*map*" }, [566] = { "vehiclegrunge256","*map*" }, [598] = { "vehiclegrunge256","*map*" }, [535] = { "vehiclegrunge256","*map*","#emapslamvan92body128" }, [567] = { "vehiclegrunge256","*map*","*map*" }, [599] = { "vehiclegrunge256","*map*" }, [444] = { "vehiclegrunge256","*map*" }, [460] = {"skimmer92body128","vehiclegrunge256","*map*"}, [476] = "rustler92body256", [492] = { "vehiclegrunge256","*map*" }, [508] = { "vehiclegrunge256","*map*" }, [536] = { "vehiclegrunge256","*map*" }, [568] = "bandito92interior128", [600] = { "vehiclegrunge256","*map*" }, [591] = { "vehiclegrunge256","*map*" }, [537] = { "vehiclegrunge256","*map*" }, [413] = { "vehiclegrunge256","*map*" }, [601] = { "vehiclegrunge256","*map*" }, [445] = { "vehiclegrunge256","*map*" }, [461] = { "vehiclegrunge256","*map*" }, [477] = { "vehiclegrunge256","*map*" }, [493] = { "vehiclegeneric256" }, [509] = { "vehiclegrunge256","*map*" }, [538] = { "vehiclegrunge256","*map*" }, [570] = { "vehiclegrunge256","*map*" }, [602] = { "vehiclegrunge256","*map*" }, [605] = { "vehiclegrunge256","*map*" }, [425] = "hunterbody8bit256a", [415] = { "vehiclegrunge256","*map*" }, [611] = { "vehiclegrunge256","*map*" }, [569] = { "vehiclegrunge256","*map*" }, [539] = { "vehiclegrunge256","*map*" }, [414] = { "vehiclegrunge256","*map*" }, [430] = {"predator92body128","vehiclegrunge256","*map*"}, [446] = { "vehiclegrunge256","*map*" }, [462] = { "vehiclegrunge256","*map*" }, [478] = { "vehiclegrunge256","*map*" }, [494] = { "vehiclegrunge256","*map*" }, [510] = { "vehiclegrunge256","*map*" }, [540] = { "vehiclegrunge256","*map*" }, [572] = { "vehiclegrunge256","*map*" }, [604] = { "vehiclegrunge256","*map*" }, [557] = "monsterb92body256a", [607] = { "vehiclegrunge256","*map*" }, [579] = { "vehiclegrunge256","*map*" }, [400] = { "vehiclegrunge256","*map*" }, [404] = { "vehiclegrunge256","*map*" }, [541] = { "vehiclegrunge256","*map*" }, [573] = { "vehiclegrunge256","*map*" }, [431] = {"vehiclegrunge256","*map*","bus92decals128","dash92interior128"}, [447] = "sparrow92body128", [463] = { "vehiclegrunge256","*map*" }, [479] = { "vehiclegrunge256","*map*" }, [495] = { "vehiclegrunge256","*map*" }, [511] = {"vehiclegrunge256","*map*","beagle256"}, [542] = { "vehiclegrunge256","*map*" }, [574] = { "vehiclegrunge256","*map*" }, [606] = { "vehiclegrunge256","*map*" }, [555] = { "vehiclegrunge256","*map*" }, [563] = "raindance92body128", [428] = { "vehiclegrunge256","*map*" }, [565] = { "vehiclegrunge256","*map*","@hite" }, [561] = { "vehiclegrunge256","*map*" }, [543] = { "vehiclegrunge256","*map*" }, [416] = { "vehiclegrunge256","*map*" }, [432] = "rhino92texpage256", [448] = { "vehiclegrunge256","*map*" }, [464] = "rcbaron92texpage64", [480] = { "vehiclegrunge256","*map*" }, [496] = { "vehiclegrunge256","*map*" }, [512] = "cropdustbody256", [544] = { "vehiclegrunge256","*map*" }, [576] = { "vehiclegrunge256","*map*" }, [608] = { "vehiclegrunge256","*map*" }, [559] = { "vehiclegrunge256","*map*" }, [429] = { "vehiclegrunge256","*map*" }, [571] = { "vehiclegrunge256","*map*" }, [427] = { "vehiclegrunge256","*map*" }, [513] = "stunt256", [545] = { "vehiclegrunge256","*map*" }, [577] = "at400_92_256", [433] = { "vehiclegrunge256","*map*" }, [449] = { "vehiclegrunge256","*map*" }, [465] = "rcraider92texpage128", [481] = "vehiclegeneric256", [497] = {"polmavbody128a", "vehiclegrunge256","*map*"}, [514] = { "vehiclegrunge256","*map*" }, [546] = { "vehiclegrunge256","*map*" }, [578] = { "vehiclegrunge256","*map*" }, [610] = { "vehiclegrunge256","*map*" }, [603] = { "vehiclegrunge256","*map*" }, [402] = { "vehiclegrunge256","*map*" }, [412] = { "vehiclegrunge256","*map*" }, [575] = { "vehiclegrunge256","*map*","remapbroadway92body128" }, [515] = { "vehiclegrunge256","*map*" }, [547] = { "vehiclegrunge256","*map*" }, [418] = { "vehiclegrunge256","*map*" }, [434] = { "hotknifebody128a", "hotknifebody128b"}, [450] = { "vehiclegrunge256","*map*" }, [466] = { "vehiclegrunge256","*map*" }, [482] = { "vehiclegrunge256","*map*" }, [498] = { "vehiclegrunge256","*map*" }, [516] = { "vehiclegrunge256","*map*" }, [548] = {"cargobob92body256" ,"vehiclegrunge256","*map*"}, [580] = { "vehiclegrunge256","*map*" }, [583] = { "vehiclegrunge256","*map*" }, [422] = { "vehiclegrunge256","*map*" }, [423] = { "vehiclegrunge256","*map*" }, [403] = { "vehiclegrunge256","*map*" }, [609] = { "vehiclegrunge256","*map*" }, [517] = { "vehiclegrunge256","*map*" }, [549] = { "vehiclegrunge256","*map*" }, [419] = { "vehiclegrunge256","*map*" }, [435] = "artict1logos", [451] = { "vehiclegrunge256","*map*" }, [467] = { "vehiclegrunge256","*map*" }, [483] = { "vehiclegrunge256","*map*" }, [499] = { "vehiclegrunge256","*map*" }, [518] = { "vehiclegrunge256","*map*" }, [550] = { "vehiclegrunge256","*map*" }, [582] = { "vehiclegrunge256","*map*" }, [421] = { "vehiclegrunge256","*map*" }, [595] = { "vehiclegrunge256","*map*" }, [553] = { "vehiclegrunge256","*map*","nevada92body256"}, [581] = "bf40092body128", [417] = "leviathnbody8bit256", [519] = "shamalbody256", [551] = { "vehiclegrunge256","*map*" }, [420] = { "vehiclegrunge256","*map*" }, [436] = { "vehiclegrunge256","*map*" }, [452] = { "vehiclegrunge256","*map*" }, [468] = { "vehiclegrunge256","*map*" }, [484] = { "vehiclegrunge256","*map*", "vehiclegeneric256","marquis92interior128" }, [401] = { "vehiclegrunge256","*map*" },} local removeTable = {} function buildRemoveTable() -- Gets all used textures and puts them in a table for a remove list. local function isTextureInTable(texture) for _,texture2 in ipairs(removeTable) do if texture == texture2 then return true end end return false end for _,texture in pairs(textureVehicle) do if type(texture) == "table" then for _,texture2 in ipairs(texture) do if not isTextureInTable(texture2) then table.insert(removeTable,texture2) end end else if not isTextureInTable(texture) then table.insert(removeTable,texture) end end end end addEventHandler("onClientResourceStart",resourceRoot,buildRemoveTable) local shaders = {} function addShaders(player, val, newUpload) local veh = getPedOccupiedVehicle(player) or nil if not veh or not val or not fileExists(client_path .. val .. '.bmp') then return end if shaders[player] then if shaders[player][3] ~= val or newUpload then -- Different PJ then before -- outputDebugString("Using Different PJ") remShaders ( player ) local texture, shader = createPJShader(val) -- outputConsole('adding shader for ' .. getPlayerName(player)) shaders[player] = {texture, shader,val} applyPJtoVehicle(shader,veh) return elseif shaders[player][3] == val then -- Same PJ as before -- outputDebugString("Using Same PJ") local texture = shaders[player][1] local shader = shaders[player][2] applyPJtoVehicle(shader,veh) return end else -- New PJ -- outputDebugString("Using New PJ") remShaders ( player ) local texture, shader = createPJShader(val) -- outputConsole('adding shader for ' .. getPlayerName(player)) shaders[player] = {texture, shader,val} applyPJtoVehicle(shader,veh) return end end function removeWorldTexture(player) if not shaders[player] then return end if not shaders[player][2] then return end local shader = shaders[player][2] if not shader then return end local veh = getPedOccupiedVehicle(player) engineRemoveShaderFromWorldTexture(shader,"vehiclegeneric256",veh) for _,texture in pairs(removeTable) do engineRemoveShaderFromWorldTexture(shader,texture,veh) end end function applyPJtoVehicle(shader,veh) if not veh then return false end if not shader then return false end local player = getVehicleOccupant(veh) if not player then return end removeWorldTexture(player,shader) local vehID = getElementModel(veh) local apply = false if type(textureVehicle[vehID]) == "table" then -- texturegrun -- textureVehicle[vehID] for _, texture in ipairs(textureVehicle[vehID]) do apply = engineApplyShaderToWorldTexture(shader,texture,veh) end else apply = engineApplyShaderToWorldTexture(shader,textureVehicle[vehID],veh) end return apply end function createPJShader(val) if not val then return false end local texture = dxCreateTexture ( client_path .. val .. '.bmp' ) local shader, tec = dxCreateShader( client_path .. "paintjob.fx" ) --bit of sanity checking if not shader then outputConsole( "Could not create shader. Please use debugscript 3" ) destroyElement( texture ) return false elseif not texture then outputConsole( "loading texture failed" ) destroyElement ( shader ) tec = nil return false end dxSetShaderValue ( shader, "gTexture", texture ) return texture,shader,tec end function remShaders ( player ) if shaders[player] and isElement(shaders[player][2]) then destroyElement(shaders[player][1]) destroyElement(shaders[player][2]) shaders[player]=nil -- outputConsole('removed shader for ' .. getPlayerName(player)) end end function refreshShaders() for _,player in pairs(shaders) do if isElement(player[1]) then destroyElement(player[1]) end if isElement(player[2]) then destroyElement(player[2]) end end shaders = {} end addEvent("clientRefreshShaderTable",true) addEventHandler("clientRefreshShaderTable",root,refreshShaders) function onGCShopLogout (forumID) remShaders ( source ) end addEventHandler("onGCShopLogout", root, onGCShopLogout) function onClientStart() triggerServerEvent('clientSendPaintjobs', root, root, localPlayer) end addEventHandler('onClientResourceStart', resourceRoot, onClientStart) -- local prev -- setTimer( function() -- local veh = getPedOccupiedVehicle(localPlayer) -- if prev then -- if not (veh and isElement(veh)) then -- prev = nil -- remShaders(localPlayer) -- elseif prev ~= getElementModel(veh) then -- prev = getElementModel(veh) -- remShaders(localPlayer) -- end -- elseif veh and getElementModel(veh) then -- prev = getElementModel(veh) -- end -- end, 50, 0) -------------------------------------- --- Uploading custom paintjobs --- -------------------------------------- local allowedExtensions = {".png",".bmp",".jpg"} function gcshopRequestPaintjob(imageMD5, forumID, filename, id) if not player_perks[4] then return outputChatBox('Buy the perk!', 255, 0, 0); end --outputDebugString('c: Requesting paintjob ' ..tostring( filename) .. ' ' .. tostring(forumID) .. ' ' .. getPlayerName(localPlayer)) if string.find(filename,".tinypic.com/") or string.find(filename,"i.imgur.com/") or string.find(filename,".postimg.org/") then -- If filename is hosting URL local forbiddenFile = 0 for _,ext in ipairs(allowedExtensions) do if string.find(filename,ext) then forbiddenFile = forbiddenFile + 1 end end if forbiddenFile ~= 1 then -- If file has forbidden extension outputChatBox('Please use a different file extension (only .png, .jpg and .bmp allowed!)', 255, 0, 0) elseif forbiddenFile == 1 then triggerServerEvent("serverReceiveHostingURL",localPlayer,filename,id) end else -- Normal upload from disk if not fileExists(filename) then -- File not found, abort --outputDebugString('c: File not found ' .. tostring(filename) .. ' ' .. tostring(forumID) .. ' ' .. getPlayerName(localPlayer)) outputChatBox('Custom paintjob image "' .. tostring(filename) .. '" not found!', 255, 0, 0) else local localMD5 = getMD5(filename) if localMD5 == imageMD5 then -- image didn't chance, tell the server to use the old custom texture --outputDebugString('c: Same image, not uploading ' .. tostring(localMD5) .. ' ' .. tostring(imageMD5) .. ' ' .. getPlayerName(localPlayer)) triggerServerEvent( 'receiveImage', localPlayer, false, id) elseif not isValidImage(filename) then outputChatBox('Custom paintjob image "' .. tostring(filename) .. '" is not a valid image!!', 255, 0, 0) else -- a new image needs to be uploaded --outputDebugString('c: New image ' .. tostring(localMD5) .. ' ' .. tostring(imageMD5) .. ' ' .. getPlayerName(localPlayer)) local file = fileOpen(filename, true) local image = fileRead(file, fileGetSize(file)) fileClose(file) triggerLatentServerEvent('receiveImage', 1000000, localPlayer, image, id) end end end end addEvent('gcshopRequestPaintjob', true) addEventHandler('gcshopRequestPaintjob', resourceRoot, gcshopRequestPaintjob) function isValidImage(image) local isImage = guiCreateStaticImage( 1.1, 1.1, 0.01, 0.01, image, true); if not isImage then return false end destroyElement(isImage); local file = fileOpen(image, true); local size = fileGetSize(file); fileClose(file); if size <= 1000000/2 then return true; end end ---------------------------------------- --- Downloading custom paintjobs --- --- from server --- ---------------------------------------- function serverPaintjobsMD5 ( md5list ) local requests = {} for forumID, playermd5list in pairs(md5list) do for pid, imageMD5 in pairs(playermd5list) do local filename = tostring(forumID) .. '-' .. pid .. '.bmp' if not fileExists(client_path .. filename) or imageMD5 ~= getMD5(client_path .. filename) then table.insert(requests, filename) --outputDebugString('c: Requesting paintjob ' .. tostring(filename) .. ' ' .. tostring(fileExists(filename) and getMD5(filename)) .. ' ' .. tostring(imageMD5) .. ' ' .. getPlayerName(localPlayer)) end end end if #requests > 0 then triggerServerEvent( 'clientRequestsPaintjobs', localPlayer, requests) end for k, player in ipairs(getElementsByType'player') do local val = getElementData(player, 'gcshop.custompaintjob') if val ~= nil then addShaders(player, val) else remShaders(player) end end end addEvent('serverPaintjobsMD5', true) addEventHandler('serverPaintjobsMD5', resourceRoot, serverPaintjobsMD5) function serverSendsPaintjobs ( files ) for filename, image in pairs(files) do local file = fileCreate(client_path .. filename) fileWrite(file, image) fileClose(file) --outputDebugString('c: Received paintjob ' .. tostring(filename) .. ' ' .. getPlayerName(localPlayer)) end if previewPJ then previewPJ() end for k, player in ipairs(getElementsByType'player') do local val = getElementData(player, 'gcshop.custompaintjob') if val ~= nil then addShaders(player, val) else remShaders(player) end end end addEvent('serverSendsPaintjobs', true) addEventHandler('serverSendsPaintjobs', resourceRoot, serverSendsPaintjobs) function getMD5 ( filename ) if not fileExists(filename) then error("getMD5: File " .. filename .. ' not found!', 2) end local file = fileOpen(filename, true) local image = fileRead(file, fileGetSize(file)) fileClose(file) return md5(image) end
mit
opentechinstitute/luci
modules/admin-full/luasrc/model/cbi/admin_system/backupfiles.lua
85
2658
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- if luci.http.formvalue("cbid.luci.1._list") then luci.http.redirect(luci.dispatcher.build_url("admin/system/flashops/backupfiles") .. "?display=list") elseif luci.http.formvalue("cbid.luci.1._edit") then luci.http.redirect(luci.dispatcher.build_url("admin/system/flashops/backupfiles") .. "?display=edit") return end m = SimpleForm("luci", translate("Backup file list")) m:append(Template("admin_system/backupfiles")) if luci.http.formvalue("display") ~= "list" then f = m:section(SimpleSection, nil, translate("This is a list of shell glob patterns for matching files and directories to include during sysupgrade. Modified files in /etc/config/ and certain other configurations are automatically preserved.")) l = f:option(Button, "_list", translate("Show current backup file list")) l.inputtitle = translate("Open list...") l.inputstyle = "apply" c = f:option(TextValue, "_custom") c.rmempty = false c.cols = 70 c.rows = 30 c.cfgvalue = function(self, section) return nixio.fs.readfile("/etc/sysupgrade.conf") end c.write = function(self, section, value) value = value:gsub("\r\n?", "\n") return nixio.fs.writefile("/etc/sysupgrade.conf", value) end else m.submit = false m.reset = false f = m:section(SimpleSection, nil, translate("Below is the determined list of files to backup. It consists of changed configuration files marked by opkg, essential base files and the user defined backup patterns.")) l = f:option(Button, "_edit", translate("Back to configuration")) l.inputtitle = translate("Close list...") l.inputstyle = "link" d = f:option(DummyValue, "_detected") d.rawhtml = true d.cfgvalue = function(s) local list = io.popen( "( find $(sed -ne '/^[[:space:]]*$/d; /^#/d; p' /etc/sysupgrade.conf " .. "/lib/upgrade/keep.d/* 2>/dev/null) -type f 2>/dev/null; " .. "opkg list-changed-conffiles ) | sort -u" ) if list then local files = { "<ul>" } while true do local ln = list:read("*l") if not ln then break else files[#files+1] = "<li>" files[#files+1] = luci.util.pcdata(ln) files[#files+1] = "</li>" end end list:close() files[#files+1] = "</ul>" return table.concat(files, "") end return "<em>" .. translate("No files found") .. "</em>" end end return m
apache-2.0
opentechinstitute/luci
libs/rpcc/luasrc/rpcc.lua
93
2227
--[[ LuCIRPCc (c) 2009 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local util = require "luci.util" local json = require "luci.json" local ltn12 = require "luci.ltn12" local nixio = require "nixio", require "nixio.util" local tostring, assert, setmetatable = tostring, assert, setmetatable local error = error --- LuCI RPC Client. -- @cstyle instance module "luci.rpcc" RQLIMIT = 32 * nixio.const.buffersize --- Create a new JSON-RPC stream client. -- @class function -- @param fd File descriptor -- @param v1 Use protocol version 1.0 -- @return RPC Client Client = util.class() function Client.__init__(self, fd, v1) self.fd = fd self.uniqueid = tostring(self):match("0x([a-f0-9]+)") self.msgid = 1 self.v1 = v1 end --- Request an RP call and get the response. -- @param method Remote method -- @param params Parameters -- @param notification Notification only? -- @return response function Client.request(self, method, params, notification) local oldchunk = self.decoder and self.decoder.chunk self.decoder = json.ActiveDecoder(self.fd:blocksource(nil, RQLIMIT)) self.decoder.chunk = oldchunk local reqid = self.msgid .. self.uniqueid local reqdata = json.Encoder({ id = (not notification) and (self.msgid .. self.uniqueid) or nil, jsonrpc = (not self.v1) and "2.0" or nil, method = method, params = params }) ltn12.pump.all(reqdata:source(), self.fd:sink()) if not notification then self.msgid = self.msgid + 1 local response = self.decoder:get() assert(response.id == reqid, "Invalid response id") if response.error then error(response.error.message or response.error) end return response.result end end --- Create a transparent RPC proxy. -- @param prefix Method prefix -- @return RPC Proxy object function Client.proxy(self, prefix) prefix = prefix or "" return setmetatable({}, { __call = function(proxy, ...) return self:request(prefix, {...}) end, __index = function(proxy, name) return self:proxy(prefix .. name .. ".") end }) end
apache-2.0
MmxBoy/newbot
plugins/isup.lua
741
3095
do local socket = require("socket") local cronned = load_from_file('data/isup.lua') local function save_cron(msg, url, delete) local origin = get_receiver(msg) if not cronned[origin] then cronned[origin] = {} end if not delete then table.insert(cronned[origin], url) else for k,v in pairs(cronned[origin]) do if v == url then table.remove(cronned[origin], k) end end end serialize_to_file(cronned, 'data/isup.lua') return 'Saved!' end local function is_up_socket(ip, port) print('Connect to', ip, port) local c = socket.try(socket.tcp()) c:settimeout(3) local conn = c:connect(ip, port) if not conn then return false else c:close() return true end end local function is_up_http(url) -- Parse URL from input, default to http local parsed_url = URL.parse(url, { scheme = 'http', authority = '' }) -- Fix URLs without subdomain not parsed properly if not parsed_url.host and parsed_url.path then parsed_url.host = parsed_url.path parsed_url.path = "" end -- Re-build URL local url = URL.build(parsed_url) local protocols = { ["https"] = https, ["http"] = http } local options = { url = url, redirect = false, method = "GET" } local response = { protocols[parsed_url.scheme].request(options) } local code = tonumber(response[2]) if code == nil or code >= 400 then return false end return true end local function isup(url) local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$' local ip,port = string.match(url, pattern) local result = nil -- !isup 8.8.8.8:53 if ip then port = port or '80' result = is_up_socket(ip, port) else result = is_up_http(url) end return result end local function cron() for chan, urls in pairs(cronned) do for k,url in pairs(urls) do print('Checking', url) if not isup(url) then local text = url..' looks DOWN from here. 😱' send_msg(chan, text, ok_cb, false) end end end end local function run(msg, matches) if matches[1] == 'cron delete' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2], true) elseif matches[1] == 'cron' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2]) elseif isup(matches[1]) then return matches[1]..' looks UP from here. 😃' else return matches[1]..' looks DOWN from here. 😱' end end return { description = "Check if a website or server is up.", usage = { "!isup [host]: Performs a HTTP request or Socket (ip:port) connection", "!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)", "!isup cron delete [host]: Disable checking that host." }, patterns = { "^!isup (cron delete) (.*)$", "^!isup (cron) (.*)$", "^!isup (.*)$", "^!ping (.*)$", "^!ping (cron delete) (.*)$", "^!ping (cron) (.*)$" }, run = run, cron = cron } end
gpl-2.0
ioiasff/khp
plugins/isup.lua
741
3095
do local socket = require("socket") local cronned = load_from_file('data/isup.lua') local function save_cron(msg, url, delete) local origin = get_receiver(msg) if not cronned[origin] then cronned[origin] = {} end if not delete then table.insert(cronned[origin], url) else for k,v in pairs(cronned[origin]) do if v == url then table.remove(cronned[origin], k) end end end serialize_to_file(cronned, 'data/isup.lua') return 'Saved!' end local function is_up_socket(ip, port) print('Connect to', ip, port) local c = socket.try(socket.tcp()) c:settimeout(3) local conn = c:connect(ip, port) if not conn then return false else c:close() return true end end local function is_up_http(url) -- Parse URL from input, default to http local parsed_url = URL.parse(url, { scheme = 'http', authority = '' }) -- Fix URLs without subdomain not parsed properly if not parsed_url.host and parsed_url.path then parsed_url.host = parsed_url.path parsed_url.path = "" end -- Re-build URL local url = URL.build(parsed_url) local protocols = { ["https"] = https, ["http"] = http } local options = { url = url, redirect = false, method = "GET" } local response = { protocols[parsed_url.scheme].request(options) } local code = tonumber(response[2]) if code == nil or code >= 400 then return false end return true end local function isup(url) local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$' local ip,port = string.match(url, pattern) local result = nil -- !isup 8.8.8.8:53 if ip then port = port or '80' result = is_up_socket(ip, port) else result = is_up_http(url) end return result end local function cron() for chan, urls in pairs(cronned) do for k,url in pairs(urls) do print('Checking', url) if not isup(url) then local text = url..' looks DOWN from here. 😱' send_msg(chan, text, ok_cb, false) end end end end local function run(msg, matches) if matches[1] == 'cron delete' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2], true) elseif matches[1] == 'cron' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2]) elseif isup(matches[1]) then return matches[1]..' looks UP from here. 😃' else return matches[1]..' looks DOWN from here. 😱' end end return { description = "Check if a website or server is up.", usage = { "!isup [host]: Performs a HTTP request or Socket (ip:port) connection", "!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)", "!isup cron delete [host]: Disable checking that host." }, patterns = { "^!isup (cron delete) (.*)$", "^!isup (cron) (.*)$", "^!isup (.*)$", "^!ping (.*)$", "^!ping (cron delete) (.*)$", "^!ping (cron) (.*)$" }, run = run, cron = cron } end
gpl-2.0
aminaleahmad/merbots
plugins/isup.lua
741
3095
do local socket = require("socket") local cronned = load_from_file('data/isup.lua') local function save_cron(msg, url, delete) local origin = get_receiver(msg) if not cronned[origin] then cronned[origin] = {} end if not delete then table.insert(cronned[origin], url) else for k,v in pairs(cronned[origin]) do if v == url then table.remove(cronned[origin], k) end end end serialize_to_file(cronned, 'data/isup.lua') return 'Saved!' end local function is_up_socket(ip, port) print('Connect to', ip, port) local c = socket.try(socket.tcp()) c:settimeout(3) local conn = c:connect(ip, port) if not conn then return false else c:close() return true end end local function is_up_http(url) -- Parse URL from input, default to http local parsed_url = URL.parse(url, { scheme = 'http', authority = '' }) -- Fix URLs without subdomain not parsed properly if not parsed_url.host and parsed_url.path then parsed_url.host = parsed_url.path parsed_url.path = "" end -- Re-build URL local url = URL.build(parsed_url) local protocols = { ["https"] = https, ["http"] = http } local options = { url = url, redirect = false, method = "GET" } local response = { protocols[parsed_url.scheme].request(options) } local code = tonumber(response[2]) if code == nil or code >= 400 then return false end return true end local function isup(url) local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$' local ip,port = string.match(url, pattern) local result = nil -- !isup 8.8.8.8:53 if ip then port = port or '80' result = is_up_socket(ip, port) else result = is_up_http(url) end return result end local function cron() for chan, urls in pairs(cronned) do for k,url in pairs(urls) do print('Checking', url) if not isup(url) then local text = url..' looks DOWN from here. 😱' send_msg(chan, text, ok_cb, false) end end end end local function run(msg, matches) if matches[1] == 'cron delete' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2], true) elseif matches[1] == 'cron' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2]) elseif isup(matches[1]) then return matches[1]..' looks UP from here. 😃' else return matches[1]..' looks DOWN from here. 😱' end end return { description = "Check if a website or server is up.", usage = { "!isup [host]: Performs a HTTP request or Socket (ip:port) connection", "!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)", "!isup cron delete [host]: Disable checking that host." }, patterns = { "^!isup (cron delete) (.*)$", "^!isup (cron) (.*)$", "^!isup (.*)$", "^!ping (.*)$", "^!ping (cron delete) (.*)$", "^!ping (cron) (.*)$" }, run = run, cron = cron } end
gpl-2.0
leonghui/packages
lang/luaexpat/files/compat-5.1r5/compat-5.1.lua
251
6391
-- -- Compat-5.1 -- Copyright Kepler Project 2004-2006 (http://www.keplerproject.org/compat) -- According to Lua 5.1 -- $Id: compat-5.1.lua,v 1.22 2006/02/20 21:12:47 carregal Exp $ -- _COMPAT51 = "Compat-5.1 R5" local LUA_DIRSEP = '/' local LUA_OFSEP = '_' local OLD_LUA_OFSEP = '' local POF = 'luaopen_' local LUA_PATH_MARK = '?' local LUA_IGMARK = ':' local assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type = assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type local find, format, gfind, gsub, sub = string.find, string.format, string.gfind, string.gsub, string.sub -- -- avoid overwriting the package table if it's already there -- package = package or {} local _PACKAGE = package package.path = LUA_PATH or os.getenv("LUA_PATH") or ("./?.lua;" .. "/usr/local/share/lua/5.0/?.lua;" .. "/usr/local/share/lua/5.0/?/?.lua;" .. "/usr/local/share/lua/5.0/?/init.lua" ) package.cpath = LUA_CPATH or os.getenv("LUA_CPATH") or "./?.so;" .. "./l?.so;" .. "/usr/local/lib/lua/5.0/?.so;" .. "/usr/local/lib/lua/5.0/l?.so" -- -- make sure require works with standard libraries -- package.loaded = package.loaded or {} package.loaded.debug = debug package.loaded.string = string package.loaded.math = math package.loaded.io = io package.loaded.os = os package.loaded.table = table package.loaded.base = _G package.loaded.coroutine = coroutine local _LOADED = package.loaded -- -- avoid overwriting the package.preload table if it's already there -- package.preload = package.preload or {} local _PRELOAD = package.preload -- -- looks for a file `name' in given path -- local function findfile (name, pname) name = gsub (name, "%.", LUA_DIRSEP) local path = _PACKAGE[pname] assert (type(path) == "string", format ("package.%s must be a string", pname)) for c in gfind (path, "[^;]+") do c = gsub (c, "%"..LUA_PATH_MARK, name) local f = io.open (c) if f then f:close () return c end end return nil -- not found end -- -- check whether library is already loaded -- local function loader_preload (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) assert (type(_PRELOAD) == "table", "`package.preload' must be a table") return _PRELOAD[name] end -- -- Lua library loader -- local function loader_Lua (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) local filename = findfile (name, "path") if not filename then return false end local f, err = loadfile (filename) if not f then error (format ("error loading module `%s' (%s)", name, err)) end return f end local function mkfuncname (name) name = gsub (name, "^.*%"..LUA_IGMARK, "") name = gsub (name, "%.", LUA_OFSEP) return POF..name end local function old_mkfuncname (name) --name = gsub (name, "^.*%"..LUA_IGMARK, "") name = gsub (name, "%.", OLD_LUA_OFSEP) return POF..name end -- -- C library loader -- local function loader_C (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) local filename = findfile (name, "cpath") if not filename then return false end local funcname = mkfuncname (name) local f, err = loadlib (filename, funcname) if not f then funcname = old_mkfuncname (name) f, err = loadlib (filename, funcname) if not f then error (format ("error loading module `%s' (%s)", name, err)) end end return f end local function loader_Croot (name) local p = gsub (name, "^([^.]*).-$", "%1") if p == "" then return end local filename = findfile (p, "cpath") if not filename then return end local funcname = mkfuncname (name) local f, err, where = loadlib (filename, funcname) if f then return f elseif where ~= "init" then error (format ("error loading module `%s' (%s)", name, err)) end end -- create `loaders' table package.loaders = package.loaders or { loader_preload, loader_Lua, loader_C, loader_Croot, } local _LOADERS = package.loaders -- -- iterate over available loaders -- local function load (name, loaders) -- iterate over available loaders assert (type (loaders) == "table", "`package.loaders' must be a table") for i, loader in ipairs (loaders) do local f = loader (name) if f then return f end end error (format ("module `%s' not found", name)) end -- sentinel local sentinel = function () end -- -- new require -- function _G.require (modname) assert (type(modname) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) local p = _LOADED[modname] if p then -- is it there? if p == sentinel then error (format ("loop or previous error loading module '%s'", modname)) end return p -- package is already loaded end local init = load (modname, _LOADERS) _LOADED[modname] = sentinel local actual_arg = _G.arg _G.arg = { modname } local res = init (modname) if res then _LOADED[modname] = res end _G.arg = actual_arg if _LOADED[modname] == sentinel then _LOADED[modname] = true end return _LOADED[modname] end -- findtable local function findtable (t, f) assert (type(f)=="string", "not a valid field name ("..tostring(f)..")") local ff = f.."." local ok, e, w = find (ff, '(.-)%.', 1) while ok do local nt = rawget (t, w) if not nt then nt = {} t[w] = nt elseif type(t) ~= "table" then return sub (f, e+1) end t = nt ok, e, w = find (ff, '(.-)%.', e+1) end return t end -- -- new package.seeall function -- function _PACKAGE.seeall (module) local t = type(module) assert (t == "table", "bad argument #1 to package.seeall (table expected, got "..t..")") local meta = getmetatable (module) if not meta then meta = {} setmetatable (module, meta) end meta.__index = _G end -- -- new module function -- function _G.module (modname, ...) local ns = _LOADED[modname] if type(ns) ~= "table" then ns = findtable (_G, modname) if not ns then error (string.format ("name conflict for module '%s'", modname)) end _LOADED[modname] = ns end if not ns._NAME then ns._NAME = modname ns._M = ns ns._PACKAGE = gsub (modname, "[^.]*$", "") end setfenv (2, ns) for i, f in ipairs (arg) do f (ns) end end
gpl-2.0
meirfaraj/tiproject
finance/src/finance/portfeuille/portefeuilleEfficientCompoXf4.lua
1
2834
-------------------------------------------------------------------------- -- Obligation -- -------------------------------------------------------------------------- require("ui/wscreen") require("finance/portfeuille/func/utilite") require("finance/portfeuille/func/portefeuille") -- obligation in fine PortefeuilleEfficientActifX = Tmv(PORTEFEUILLE_EFFICIENT_ID,PORTEFEUILLE_EFFICIENT_HEADER_ID) function PortefeuilleEfficientActifX:widgetsInit() self:add(0,"RX:" ,"RX") self:add(0,c_sigma.."X:" ,c_sigma.."X") self:add(1,"RM:" ,"RM") self:add(1,"rf:" ,"rf") self:add(2,c_sigma.."M:" ,c_sigma.."M") self:add(2,c_beta.."X",c_beta.."X") end function PortefeuilleEfficientActifX:performCalc() local rx = varValue["RX"] local volX = varValue[c_sigma.."X"] local rm = varValue["RM"] local rf = varValue["rf"] if rm ~=nil then rm = string.gsub(rm,"[%[%]]*","") end if rf ~=nil then rf = string.gsub(rf,"[%[%]]*","") end self:appendMathToResult(c_beta.."X=(Rx-rf)/(RM-rf)") self:appendToResult("\n") if rx~=nil and volX~=nil and rm~=nil and rf~=nil then local calcStr = "("..tostring(rx).."-"..tostring(rf)..")/("..tostring(rm).."-"..tostring(rf)..")" self:appendMathToResult(c_beta.."X="..tostring(calcStr)) varValue[c_beta.."X"] = tiNspire.execute(tostring(calcStr)) self:appendToResult("\n") self:appendMathToResult("="..tostring(varValue[c_beta.."X"])) self:appendMathToResult("="..tostring(tiNspire.approx(tostring(varValue[c_beta.."X"])))) end local betaX = varValue[c_beta.."X"] local sigmaM = varValue[c_sigma.."M"] if betaX ~=nil then betaX = string.gsub(betaX,"[%[%]]*","") end if sigmaM ~=nil then sigmaM = string.gsub(sigmaM,"[%[%]]*","") end if betaX~=nil and sigmaM~=nil then self:appendToResult("\nRisque systematique:\n") self:appendMathToResult("="..c_beta.."X^2*"..c_sigma.."M^2") local calcStr = "("..tostring(betaX)..")^2*("..tostring(sigmaM)..")^2" self:appendMathToResult("="..tostring(calcStr)) self:appendToResult("\n") local res = tiNspire.execute(tostring(calcStr)) self:appendMathToResult("="..tostring(res)) self:appendMathToResult("="..tostring(tiNspire.approx(tostring(res)))) self:appendToResult("\nRisque specifique:\n") self:appendMathToResult("="..c_sigma.."X^2-risqSyst") if volX~=nil then calcStr = "("..tostring(volX)..")^2-"..tostring(res) self:appendMathToResult("="..tostring(calcStr)) local res2 = tiNspire.execute(tostring(calcStr)) self:appendMathToResult("="..tostring(res2)) self:appendMathToResult("="..tostring(tiNspire.approx(tostring(res2)))) end end end
apache-2.0
AliKhodadad/zed-spam
plugins/torrent_search.lua
411
1622
--[[ NOT USED DUE TO SSL ERROR -- See https://getstrike.net/api/ local function strike_search(query) local strike_base = 'http://getstrike.net/api/v2/torrents/' local url = strike_base..'search/?phrase='..URL.escape(query) print(url) local b,c = http.request(url) print(b,c) local search = json:decode(b) vardump(search) if c ~= 200 then return search.message end vardump(search) local results = search.results local text = 'Results: '..results local results = math.min(results, 3) for i=1,results do local torrent = search.torrents[i] text = text..torrent.torrent_title ..'\n'..'Seeds: '..torrent.seeds ..' '..'Leeches: '..torrent.seeds ..'\n'..torrent.magnet_uri..'\n\n' end return text end]]-- local function search_kickass(query) local url = 'http://kat.cr/json.php?q='..URL.escape(query) local b,c = http.request(url) local data = json:decode(b) local text = 'Results: '..data.total_results..'\n\n' local results = math.min(#data.list, 5) for i=1,results do local torrent = data.list[i] local link = torrent.torrentLink link = link:gsub('%?title=.+','') text = text..torrent.title ..'\n'..'Seeds: '..torrent.seeds ..' '..'Leeches: '..torrent.leechs ..'\n'..link --..'\n magnet:?xt=urn:btih:'..torrent.hash ..'\n\n' end return text end local function run(msg, matches) local query = matches[1] return search_kickass(query) end return { description = "Search Torrents", usage = "!torrent <search term>: Search for torrent", patterns = { "^!torrent (.+)$" }, run = run }
gpl-2.0
adamflott/wargus
scripts/ai/ai_jadeite_2010.lua
1
13497
-- _________ __ __ -- / _____// |_____________ _/ |______ ____ __ __ ______ -- \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/ -- / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ \ -- /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ > -- \/ \/ \//_____/ \/ -- ______________________ ______________________ -- T H E W A R B E G I N S -- Stratagus - A free fantasy real time strategy game engine -- -- ai_jadeite.lua - Define the Jadeite AI series. -- -- (c) Copyright 2010 by Kyran Jackson -- -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -- -- This AI currently only works with humans. -- Currently doesn't support ships. local jadeite_stepping = {} -- Used to identify where the build order is up to. function AiJadeite_2010() -- Setting up the variables. if (jadeite_stepping[AiPlayer()] ~= nil) then if (jadeite_stepping[AiPlayer()] == 1) then -- Standard air attack build. AiJadeite_Flyer_2010() end if (jadeite_stepping[AiPlayer()] == 2) then -- Standard footsoldier build. AiJadeite_Soldier_2010() end if (jadeite_stepping[AiPlayer()] == 3) then -- Standard knight build. AiJadeite_Cavalry_2010() end if (jadeite_stepping[AiPlayer()] == 4) then -- Standard archer build. AiJadeite_Shooter_2010() end if (jadeite_stepping[AiPlayer()] == 5) then -- One Hall Power to Keep/Stronghold AiJadeite_Power_2010() end else jadeite_stepping[AiPlayer()] = SyncRand(5) end end function AiJadeite_Worker_2010() if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiCityCenter()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBetterCityCenter()) >= 1)) then AiSet(AiWorker(), 20) else AiSet(AiCityCenter(), 1) end end function AiJadeite_Power_2010() if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiCityCenter()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBetterCityCenter()) >= 1)) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiFarm()) >= 1) then AiSet(AiWorker(), 8) if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) >= 1) then if ((GetPlayerData(AiPlayer(), "Resources", "gold") > 5000) and (GetPlayerData(AiPlayer(), "Resources", "wood") > 1000)) then AiSet(AiSoldier(), 12) if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) >= 12) then AiForce(0, {AiSoldier(), 12}) end else AiSet(AiSoldier(), 4) if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) >= 4) then AiForce(0, {AiSoldier(), 4}) end end AiSet(AiWorker(), 15) AiSet(AiFarm(), 5) if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiWorker()) > 3) and (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBlacksmith()) == 0)) then AiSet(AiBlacksmith(), 1) else if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) >= 2) then AiSet(AiCatapult(), 1) end AiResearch(AiUpgradeWeapon1()) AiResearch(AiUpgradeArmor1()) AiResearch(AiUpgradeArmor2()) if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBetterCityCenter()) >= 1) then AiResearch(AiUpgradeWeapon2()) if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiStables()) >= 1) then if ((GetPlayerData(AiPlayer(), "Resources", "gold") > 3000) and (GetPlayerData(AiPlayer(), "Resources", "wood") > 1500)) then AiSet(AiBarracks(), 3) end if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry()) <= 3) and (GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalryMage()) <= 3)) then AiSet(AiCavalry(), 10) else if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry()) >= 7) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalryMage()) >= 7)) then AiForce(6, {AiCavalry(), (GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry()) + GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalryMage())), AiCatapult(), GetPlayerData(AiPlayer(), "UnitTypesCount", AiCatapult())}, true) AiAttackWithForce(6) elseif ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalryMage()) >= 1)) then AiForce(6, {AiCavalry(), 1}, true) AiAttackWithForce(6) end end else AiSet(AiStables(), 1) AiSet(AiLumberMill(), 1) if ((GetPlayerData(AiPlayer(), "Resources", "gold") > 3000) and (GetPlayerData(AiPlayer(), "Resources", "wood") > 1500)) then AiSet(AiFarm(), 6) end end else if ((GetPlayerData(AiPlayer(), "Resources", "gold") > 3000) and (GetPlayerData(AiPlayer(), "Resources", "wood") > 1500)) then AiSet(AiBarracks(), 2) end AiUpgradeTo(AiBetterCityCenter()) end end else AiSet(AiBarracks(), 1) if ((GetPlayerData(AiPlayer(), "Resources", "gold") > 3000) and (GetPlayerData(AiPlayer(), "Resources", "wood") > 1500)) then AiSet(AiBlacksmith(), 1) AiResearch(AiUpgradeWeapon1()) AiResearch(AiUpgradeArmor1()) AiResearch(AiUpgradeArmor2()) end end else AiSet(AiFarm(), 1) end else AiSet(AiCityCenter(), 1) end end function AiJadeite_Shooter_2010() if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiWorker()) < 5) then AiSet(AiWorker(), 8) end if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiCityCenter()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBetterCityCenter()) >= 1)) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiLumberMill()) >= 1) then AiResearch(AiUpgradeMissile1()) if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) >= 1) then if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiShooter()) >= 4) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiShooter()) >= 4)) then AiResearch(AiUpgradeMissile2()) AiForce(5, {AiShooter(), 8}, true) if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBlacksmith()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBetterCityCenter()) >= 1) then AiResearch(AiUpgradeEliteShooter()) if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiStables()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) >= 1) then AiResearch(AiUpgradeEliteShooter2()) AiResearch(AiUpgradeEliteShooter3()) else AiUpgradeTo(AiBestCityCenter()) end else AiSet(AiStables(), 1) end else AiUpgradeTo(AiBetterCityCenter()) end else AiSet(AiBlacksmith(), 1) end if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiShooter()) >= 8) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiShooter()) >= 8)) then AiAttackWithForce(5) end else AiSet(AiShooter(), 4) end else AiSet(AiBarracks(), 1) end else AiSet(AiLumberMill(), 1) end else AiSet(AiCityCenter(), 1) end end function AiJadeite_Cavalry_2010() if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiWorker()) < 5) then AiSet(AiWorker(), 8) end if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiCityCenter()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBetterCityCenter()) >= 1)) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBlacksmith()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBetterCityCenter()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiStables()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry()) >= 4) then AiResearch(AiUpgradeWeapon1()) AiResearch(AiUpgradeArmor1()) AiResearch(AiUpgradeWeapon2()) AiResearch(AiUpgradeArmor2()) if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) == 0) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiLumberMill()) >= 1) then AiUpgradeTo(AiBestCityCenter()) else AiSet(AiLumberMill(), 1) end else if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiCavalry()) >= 8) then AiAttackWithForce(4) else AiForce(4, {AiCavalry(), 10}, true) end if (GetPlayerData(AiPlayer(), "UnitTypesCount",AiTemple()) >= 1) then AiResearch(AiUpgradeCavalryMage()) AiResearch(AiCavalryMageSpell1()) else AiSet(AiTemple(), 1) end end else --AiSet(AiSoldier(), 1) AiSet(AiCavalry(), 4) end else AiSet(AiStables(), 1) end else AiUpgradeTo(AiBetterCityCenter()) end else AiSet(AiBlacksmith(), 1) end else AiSet(AiBarracks(), 1) end else AiSet(AiCityCenter(), 1) end end function AiJadeite_Soldier_2010() if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiWorker()) < 5) then AiSet(AiWorker(), 8) end if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiCityCenter()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBetterCityCenter()) >= 1)) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) >= 4) then AiForce(3, {AiSoldier(), 12}, true) if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiSoldier()) >= 8) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBlacksmith()) >= 1) then AiResearch(AiUpgradeWeapon1()) AiResearch(AiUpgradeArmor1()) AiResearch(AiUpgradeWeapon2()) AiResearch(AiUpgradeArmor2()) else AiSet(AiBlacksmith(), 1) end AiAttackWithForce(3) end else AiSet(AiSoldier(), 4) end else AiSet(AiBarracks(), 1) end else AiSet(AiCityCenter(), 1) end end function AiJadeite_Flyer_2010() if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiAirport()) >= 1) then AiSet(AiAirport(), 3) if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiFlyer()) <= 3) then AiSet(AiFlyer(), 10) else if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiFlyer()) >= 5) then AiForce(2, {AiFlyer(), 12}, true) AiAttackWithForce(2) else AiForce(2, {AiFlyer(), 2}, true) AiAttackWithForce(2) end end else if ((GetPlayerData(AiPlayer(), "UnitTypesCount", AiCityCenter()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) >= 1) or (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBetterCityCenter()) >= 1)) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBarracks()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBetterCityCenter()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiStables()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiLumberMill()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBlacksmith()) >= 1) then if (GetPlayerData(AiPlayer(), "UnitTypesCount", AiBestCityCenter()) >= 1) then AiSet(AiAirport(), 1) else AiUpgradeTo(AiBestCityCenter()) end else AiSet(AiBlacksmith(), 1) end else AiSet(AiLumberMill(), 1) end else AiSet(AiStables(), 1) end else AiUpgradeTo(AiBetterCityCenter()) end else AiSet(AiBarracks(), 1) end else AiSet(AiCityCenter(), 1) AiSet(AiWorker(), 8) end end end DefineAi("ai_jadeite_2010", "*", "ai_jadeite_2010", AiJadeite_2010) DefineAi("ai_jadeite_soldier_2010", "*", "ai_jadeite_soldier_2010", AiJadeite_Soldier_2010) DefineAi("ai_jadeite_cavalry_2010", "*", "ai_jadeite_cavalry_2010", AiJadeite_Cavalry_2010) DefineAi("ai_jadeite_shooter_2010", "*", "ai_jadeite_shooter_2010", AiJadeite_Shooter_2010) DefineAi("ai_jadeite_worker_2010", "*", "ai_jadeite_worker_2010", AiJadeite_Worker_2010) DefineAi("ai_jadeite_power_2010", "*", "ai_jadeite_power_2010", AiJadeite_Power_2010) DefineAi("ai_jadeite_flyer_2010", "*", "ai_jadeite_flyer_2010", AiJadeite_Flyer_2010)
gpl-2.0
satanevil/copy-creed
plugins/bot_on_off.lua
292
1641
-- Checks if bot was disabled on specific chat local function is_channel_disabled( receiver ) if not _config.disabled_channels then return false end if _config.disabled_channels[receiver] == nil then return false end return _config.disabled_channels[receiver] end local function enable_channel(receiver) if not _config.disabled_channels then _config.disabled_channels = {} end if _config.disabled_channels[receiver] == nil then return 'Robot is Online' end _config.disabled_channels[receiver] = false save_config() return "Robot is Online" end local function disable_channel( receiver ) if not _config.disabled_channels then _config.disabled_channels = {} end _config.disabled_channels[receiver] = true save_config() return "Robot is Offline" end local function pre_process(msg) local receiver = get_receiver(msg) -- If sender is moderator then re-enable the channel --if is_sudo(msg) then if is_momod(msg) then if msg.text == "[!/]bot on" then enable_channel(receiver) end end if is_channel_disabled(receiver) then msg.text = "" end return msg end local function run(msg, matches) local receiver = get_receiver(msg) -- Enable a channel if matches[1] == 'on' then return enable_channel(receiver) end -- Disable a channel if matches[1] == 'off' then return disable_channel(receiver) end end return { description = "Robot Switch", usage = { "/bot on : enable robot in group", "/bot off : disable robot in group" }, patterns = { "^[!/]bot? (on)", "^[!/]bot? (off)" }, run = run, privileged = true, --moderated = true, pre_process = pre_process }
gpl-2.0