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
Enignite/darkstar
scripts/zones/Phomiuna_Aqueducts/npcs/Wooden_Ladder.lua
17
3196
----------------------------------- -- Area: Phomiuna Aqueducts -- NPC: Wooden Ladder -- @pos 101.9 -1.5 -101.9 -- @pos 101.948 -1.5 -18.016 -- @pos -61.888 -1.5 -18.079 -- @pos -218.109 -1.499 18.081 -- @pos -61.903 -1.5 138.099 -- @pos 21.901 -1.5 138.096 -- @pos 101.902 -1.5 181.902 -- @pos -159.32 -2.5 60 -- @pos -159.38 -22.559 60 -- @pos 199.317 -2.5 60 -- @pos 199.38 -22.559 60 -- @pos -200.679 -8.57 60 ----------------------------------- package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Phomiuna_Aqueducts/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local X = player:getXPos(); local Y = player:getYPos(); local Z = player:getZPos(); if ((X <= 107.9 and X >= 95.9) and (Y >= -1 and Y <= 1) and (Z >= -108.9 and Z <= -98)) then player:startEvent(0x0015); elseif ((X <= 107.9 and X >= 95.9) and (Y >= -1 and Y <= 1) and (Z >= -24 and Z <= -12)) then player:startEvent(0x0016); elseif ((X <= -55.888 and X >= -67.888) and (Y >= -1 and Y <= 1) and (Z >= -24 and Z <= -12)) then player:startEvent(0x0017); elseif ((X <= -212.1 and X >= -224.1) and (Y >= -1 and Y <= 1) and (Z >= 12 and Z <= 24)) then player:startEvent(0x0018); elseif ((X <= -55.9 and X >= -67.9) and (Y >= -1 and Y <= 1) and (Z >= 132 and Z <= 144)) then player:startEvent(0x0019); elseif ((X <= 27.9 and X >= 15.9) and (Y >= -1 and Y <= 1) and (Z >= 132 and Z <= 144)) then player:startEvent(0x001a); elseif ((X <= 107.9 and X >= 95.9) and (Y >= -1 and Y <= 1) and (Z >= 175.9 and Z <= 187.9)) then player:startEvent(0x001b); elseif ((X <= -153.3 and X >= -168.3) and (Y >= -2 and Y <= 0) and (Z >= 54 and Z <= 66)) then if (player:getCurrentMission(COP) == DISTANT_BELIEFS and player:getVar("PromathiaStatus") == 1) then player:setVar("PromathiaStatus",2); player:startEvent(0x0023); else player:startEvent(0x001c); end elseif ((X <= -153.3 and X >= -168.3) and (Y >= -24 and Y <= -22) and (Z >= 54 and Z <= 66)) then player:startEvent(0x001d); elseif ((X <= 205.3 and X >= 193.3) and (Y >= -2 and Y <= 0) and (Z >= 54 and Z <= 66)) then player:startEvent(0x001e); elseif ((X <= 205.3 and X >= 193.3) and (Y >= -24 and Y <= -22) and (Z >= 54 and Z <= 66)) then player:startEvent(0x001f); elseif ((X <= -194.6 and X >= -206.6) and (Y >= -8 and Y <= -6) and (Z >= 54 and Z <= 66)) then player:messageSpecial(DOOR_SEALED_SHUT); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Enignite/darkstar
scripts/zones/Gusgen_Mines/npcs/Degga.lua
34
1186
----------------------------------- -- Area: Gusgen Mines -- NPC: Degga -- Type: Standard Info NPC -- @pos 40 -68 -259 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x000c); -- i have nothing to say to you standar dialog end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
sweeti0/dev_qollop
plugins/ar-getlink.lua
3
27430
do local function check_member(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg}) end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted.') end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name if success == -1 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' then print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'rem' then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) end if matches[1] == 'chat_del_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end if matches[1] == 'newlink' then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'الرابط خاص' then if not is_momod(msg) then return "❌✋ لتلعب بكيفك ⚠️ فقط الاداره يحق لها ❗️ ذلك 👍" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "يرجى ارسال ❗️ [تغير الرابط] ☑️ لانشاء 👍 رابط المجموعه 👥😽" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") send_large_msg('user#id'..msg.from.id, "☑️ رابط مجموعه 👥😽"..msg.to.title..'\n'..group_link) return "تم ارسال الرابط الى الخاص 😚👍" end if matches[1] == 'setowner' then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'help' then if not is_momod(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end end return { patterns = { "^(الرابط خاص)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-3.0
SouD/LessAnimeTabbing
src/MyAnimeListEndpoint.lua
1
1582
-- LessAnimeTabbing. Keep track of your anime without tabbing! -- Copyright (C) 2014 Linus Sörensen -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --- Defines the MyAnimeListEndpoint class. -- @return nil. function define_MyAnimeListEndpoint() --- MyAnimeListEndpoint class. -- Defines the MAL enpoint. -- @class MyAnimeListEndpoint MyAnimeListEndpoint = inherits(Endpoint) MyAnimeListEndpoint._new = MyAnimeListEndpoint.new --- MyAnimeListEndpoint constructor. -- Creates a new instance of @class MyAnimeListEndpoint. -- @class MyAnimeListEndpoint -- @param config Instance of @class Config. -- @return Instance of @class MyAnimeListEndpoint. function MyAnimeListEndpoint:new(config) return self._new(self, { _config = config, _name = "MyAnimeList", _prefix = "[LessAnimeTabbing MyAnimeList]: " }) end end
gpl-2.0
doofus-01/wesnoth
data/ai/micro_ais/cas/ca_recruit_random.lua
7
4529
local AH = wesnoth.require("ai/lua/ai_helper.lua") local LS = wesnoth.require "location_set" local recruit_type local ca_recruit_random = {} function ca_recruit_random:evaluation(cfg) -- Random recruiting from all the units the side has -- Check if leader is on keep local leader = wesnoth.units.find_on_map { side = wesnoth.current.side, canrecruit = 'yes' }[1] if (not leader) or (not wesnoth.terrain_types[wesnoth.current.map[leader]].keep) then return 0 end -- Find all connected castle hexes local castle_map = LS.of_pairs({ { leader.x, leader.y } }) local new_castle_hex_found = true while new_castle_hex_found do new_castle_hex_found = false local new_hexes = {} castle_map:iter(function(x, y) for xa,ya in wesnoth.current.map:iter_adjacent(x, y) do if (not castle_map:get(xa, ya)) and wesnoth.current.map:on_board(xa, ya) then local is_castle = wesnoth.terrain_types[wesnoth.current.map[{xa, ya}]].castle if is_castle then table.insert(new_hexes, { xa, ya }) new_castle_hex_found = true end end end end) for _,hex in ipairs(new_hexes) do castle_map:insert(hex[1], hex[2]) end end -- Check if there is space left for recruiting local no_space = true castle_map:iter(function(x, y) local unit = wesnoth.units.get(x, y) if (not unit) then no_space = false end end) if no_space then return 0 end -- Set up the probability array local probabilities, probability_sum = {}, 0 -- Go through all the types listed in [probability] tags (which can be comma-separated lists) for prob in wml.child_range(cfg, "probability") do local types = AH.split(prob.type, ",") for _,typ in ipairs(types) do -- 'type' is a reserved keyword in Lua -- If this type is in the recruit list, add it for _,recruit in ipairs(wesnoth.sides[wesnoth.current.side].recruit) do if (recruit == typ) then probabilities[typ] = { value = prob.probability } probability_sum = probability_sum + prob.probability break end end end end -- Now we add in all the unit types not listed in [probability] tags for _,recruit in ipairs(wesnoth.sides[wesnoth.current.side].recruit) do if (not probabilities[recruit]) then probabilities[recruit] = { value = 1 } probability_sum = probability_sum + 1 end end -- Now eliminate all those that are too expensive (unless cfg.skip_low_gold_recruiting is set) if cfg.skip_low_gold_recruiting then for typ,probability in pairs(probabilities) do -- 'type' is a reserved keyword in Lua if (wesnoth.unit_types[typ].cost > wesnoth.sides[wesnoth.current.side].gold) then probability_sum = probability_sum - probability.value probabilities[typ] = nil end end end -- Now set up the cumulative probability values for each type -- Both min and max need to be set as the order of pairs() is not guaranteed local cum_prob = 0 for typ,probability in pairs(probabilities) do probabilities[typ].p_i = cum_prob cum_prob = cum_prob + probability.value probabilities[typ].p_f = cum_prob end -- We always call the exec function, no matter if the selected unit is affordable -- The point is that this will blacklist the CA if an unaffordable recruit was -- chosen -> no cheaper recruits will be selected in subsequent calls if (cum_prob > 0) then local rand_prob = math.random(cum_prob) for typ,probability in pairs(probabilities) do if (probability.p_i < rand_prob) and (rand_prob <= probability.p_f) then recruit_type = typ break end end else recruit_type = wesnoth.sides[wesnoth.current.side].recruit[1] end return cfg.ca_score end function ca_recruit_random:execution(cfg) -- Let this function blacklist itself if the chosen recruit is too expensive if wesnoth.unit_types[recruit_type].cost <= wesnoth.sides[wesnoth.current.side].gold then AH.checked_recruit(ai, recruit_type) end end return ca_recruit_random
gpl-2.0
terojanbot/TEROJANSBOT
plugins/meme.lua
637
5791
local helpers = require "OAuth.helpers" local _file_memes = './data/memes.lua' local _cache = {} local function post_petition(url, arguments) local response_body = {} local request_constructor = { url = url, method = "POST", sink = ltn12.sink.table(response_body), headers = {}, redirect = false } local source = arguments if type(arguments) == "table" then local source = helpers.url_encode_arguments(arguments) end request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded" request_constructor.headers["Content-Length"] = tostring(#source) request_constructor.source = ltn12.source.string(source) local ok, response_code, response_headers, response_status_line = http.request(request_constructor) if not ok then return nil end response_body = json:decode(table.concat(response_body)) return response_body end local function upload_memes(memes) local base = "http://hastebin.com/" local pet = post_petition(base .. "documents", memes) if pet == nil then return '', '' end local key = pet.key return base .. key, base .. 'raw/' .. key end local function analyze_meme_list() local function get_m(res, n) local r = "<option.*>(.*)</option>.*" local start = string.find(res, "<option.*>", n) if start == nil then return nil, nil end local final = string.find(res, "</option>", n) + #"</option>" local sub = string.sub(res, start, final) local f = string.match(sub, r) return f, final end local res, code = http.request('http://apimeme.com/') local r = "<option.*>(.*)</option>.*" local n = 0 local f, n = get_m(res, n) local ult = {} while f ~= nil do print(f) table.insert(ult, f) f, n = get_m(res, n) end return ult end local function get_memes() local memes = analyze_meme_list() return { last_time = os.time(), memes = memes } end local function load_data() local data = load_from_file(_file_memes) if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then data = get_memes() -- Upload only if changed? link, rawlink = upload_memes(table.concat(data.memes, '\n')) data.link = link data.rawlink = rawlink serialize_to_file(data, _file_memes) end return data end local function match_n_word(list1, list2) local n = 0 for k,v in pairs(list1) do for k2, v2 in pairs(list2) do if v2:find(v) then n = n + 1 end end end return n end local function match_meme(name) local _memes = load_data() local name = name:lower():split(' ') local max = 0 local id = nil for k,v in pairs(_memes.memes) do local n = match_n_word(name, v:lower():split(' ')) if n > 0 and n > max then max = n id = v end end return id end local function generate_meme(id, textup, textdown) local base = "http://apimeme.com/meme" local arguments = { meme=id, top=textup, bottom=textdown } return base .. "?" .. helpers.url_encode_arguments(arguments) end local function get_all_memes_names() local _memes = load_data() local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n' for k, v in pairs(_memes.memes) do text = text .. '- ' .. v .. '\n' end text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/' return text end local function callback_send(cb_extra, success, data) if success == 0 then send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false) end end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == 'list' then local _memes = load_data() return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link elseif matches[1] == 'listall' then if not is_sudo(msg) then return "You can't list this way, use \"!meme list\"" else return get_all_memes_names() end elseif matches[1] == "search" then local meme_id = match_meme(matches[2]) if meme_id == nil then return "I can't match that search with any meme." end return "With that search your meme is " .. meme_id end local searchterm = string.gsub(matches[1]:lower(), ' ', '') local meme_id = _cache[searchterm] or match_meme(matches[1]) if not meme_id then return 'I don\'t understand the meme name "' .. matches[1] .. '"' end _cache[searchterm] = meme_id print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3]) local url_gen = generate_meme(meme_id, matches[2], matches[3]) send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen}) return nil end return { description = "Generate a meme image with up and bottom texts.", usage = { "!meme search (name): Return the name of the meme that match.", "!meme list: Return the link where you can see the memes.", "!meme listall: Return the list of all memes. Only admin can call it.", '!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.', '!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.', }, patterns = { "^!meme (search) (.+)$", '^!meme (list)$', '^!meme (listall)$', '^!meme (.+) "(.*)" "(.*)"$', '^!meme "(.+)" "(.*)" "(.*)"$', "^!meme (.+) %- (.*) %- (.*)$" }, run = run }
gpl-2.0
DipColor/mehrabon2
plugins/meme.lua
637
5791
local helpers = require "OAuth.helpers" local _file_memes = './data/memes.lua' local _cache = {} local function post_petition(url, arguments) local response_body = {} local request_constructor = { url = url, method = "POST", sink = ltn12.sink.table(response_body), headers = {}, redirect = false } local source = arguments if type(arguments) == "table" then local source = helpers.url_encode_arguments(arguments) end request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded" request_constructor.headers["Content-Length"] = tostring(#source) request_constructor.source = ltn12.source.string(source) local ok, response_code, response_headers, response_status_line = http.request(request_constructor) if not ok then return nil end response_body = json:decode(table.concat(response_body)) return response_body end local function upload_memes(memes) local base = "http://hastebin.com/" local pet = post_petition(base .. "documents", memes) if pet == nil then return '', '' end local key = pet.key return base .. key, base .. 'raw/' .. key end local function analyze_meme_list() local function get_m(res, n) local r = "<option.*>(.*)</option>.*" local start = string.find(res, "<option.*>", n) if start == nil then return nil, nil end local final = string.find(res, "</option>", n) + #"</option>" local sub = string.sub(res, start, final) local f = string.match(sub, r) return f, final end local res, code = http.request('http://apimeme.com/') local r = "<option.*>(.*)</option>.*" local n = 0 local f, n = get_m(res, n) local ult = {} while f ~= nil do print(f) table.insert(ult, f) f, n = get_m(res, n) end return ult end local function get_memes() local memes = analyze_meme_list() return { last_time = os.time(), memes = memes } end local function load_data() local data = load_from_file(_file_memes) if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then data = get_memes() -- Upload only if changed? link, rawlink = upload_memes(table.concat(data.memes, '\n')) data.link = link data.rawlink = rawlink serialize_to_file(data, _file_memes) end return data end local function match_n_word(list1, list2) local n = 0 for k,v in pairs(list1) do for k2, v2 in pairs(list2) do if v2:find(v) then n = n + 1 end end end return n end local function match_meme(name) local _memes = load_data() local name = name:lower():split(' ') local max = 0 local id = nil for k,v in pairs(_memes.memes) do local n = match_n_word(name, v:lower():split(' ')) if n > 0 and n > max then max = n id = v end end return id end local function generate_meme(id, textup, textdown) local base = "http://apimeme.com/meme" local arguments = { meme=id, top=textup, bottom=textdown } return base .. "?" .. helpers.url_encode_arguments(arguments) end local function get_all_memes_names() local _memes = load_data() local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n' for k, v in pairs(_memes.memes) do text = text .. '- ' .. v .. '\n' end text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/' return text end local function callback_send(cb_extra, success, data) if success == 0 then send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false) end end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == 'list' then local _memes = load_data() return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link elseif matches[1] == 'listall' then if not is_sudo(msg) then return "You can't list this way, use \"!meme list\"" else return get_all_memes_names() end elseif matches[1] == "search" then local meme_id = match_meme(matches[2]) if meme_id == nil then return "I can't match that search with any meme." end return "With that search your meme is " .. meme_id end local searchterm = string.gsub(matches[1]:lower(), ' ', '') local meme_id = _cache[searchterm] or match_meme(matches[1]) if not meme_id then return 'I don\'t understand the meme name "' .. matches[1] .. '"' end _cache[searchterm] = meme_id print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3]) local url_gen = generate_meme(meme_id, matches[2], matches[3]) send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen}) return nil end return { description = "Generate a meme image with up and bottom texts.", usage = { "!meme search (name): Return the name of the meme that match.", "!meme list: Return the link where you can see the memes.", "!meme listall: Return the list of all memes. Only admin can call it.", '!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.', '!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.', }, patterns = { "^!meme (search) (.+)$", '^!meme (list)$', '^!meme (listall)$', '^!meme (.+) "(.*)" "(.*)"$', '^!meme "(.+)" "(.*)" "(.*)"$', "^!meme (.+) %- (.*) %- (.*)$" }, run = run }
gpl-2.0
aqasaeed/telebot
plugins/meme.lua
637
5791
local helpers = require "OAuth.helpers" local _file_memes = './data/memes.lua' local _cache = {} local function post_petition(url, arguments) local response_body = {} local request_constructor = { url = url, method = "POST", sink = ltn12.sink.table(response_body), headers = {}, redirect = false } local source = arguments if type(arguments) == "table" then local source = helpers.url_encode_arguments(arguments) end request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded" request_constructor.headers["Content-Length"] = tostring(#source) request_constructor.source = ltn12.source.string(source) local ok, response_code, response_headers, response_status_line = http.request(request_constructor) if not ok then return nil end response_body = json:decode(table.concat(response_body)) return response_body end local function upload_memes(memes) local base = "http://hastebin.com/" local pet = post_petition(base .. "documents", memes) if pet == nil then return '', '' end local key = pet.key return base .. key, base .. 'raw/' .. key end local function analyze_meme_list() local function get_m(res, n) local r = "<option.*>(.*)</option>.*" local start = string.find(res, "<option.*>", n) if start == nil then return nil, nil end local final = string.find(res, "</option>", n) + #"</option>" local sub = string.sub(res, start, final) local f = string.match(sub, r) return f, final end local res, code = http.request('http://apimeme.com/') local r = "<option.*>(.*)</option>.*" local n = 0 local f, n = get_m(res, n) local ult = {} while f ~= nil do print(f) table.insert(ult, f) f, n = get_m(res, n) end return ult end local function get_memes() local memes = analyze_meme_list() return { last_time = os.time(), memes = memes } end local function load_data() local data = load_from_file(_file_memes) if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then data = get_memes() -- Upload only if changed? link, rawlink = upload_memes(table.concat(data.memes, '\n')) data.link = link data.rawlink = rawlink serialize_to_file(data, _file_memes) end return data end local function match_n_word(list1, list2) local n = 0 for k,v in pairs(list1) do for k2, v2 in pairs(list2) do if v2:find(v) then n = n + 1 end end end return n end local function match_meme(name) local _memes = load_data() local name = name:lower():split(' ') local max = 0 local id = nil for k,v in pairs(_memes.memes) do local n = match_n_word(name, v:lower():split(' ')) if n > 0 and n > max then max = n id = v end end return id end local function generate_meme(id, textup, textdown) local base = "http://apimeme.com/meme" local arguments = { meme=id, top=textup, bottom=textdown } return base .. "?" .. helpers.url_encode_arguments(arguments) end local function get_all_memes_names() local _memes = load_data() local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n' for k, v in pairs(_memes.memes) do text = text .. '- ' .. v .. '\n' end text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/' return text end local function callback_send(cb_extra, success, data) if success == 0 then send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false) end end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == 'list' then local _memes = load_data() return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link elseif matches[1] == 'listall' then if not is_sudo(msg) then return "You can't list this way, use \"!meme list\"" else return get_all_memes_names() end elseif matches[1] == "search" then local meme_id = match_meme(matches[2]) if meme_id == nil then return "I can't match that search with any meme." end return "With that search your meme is " .. meme_id end local searchterm = string.gsub(matches[1]:lower(), ' ', '') local meme_id = _cache[searchterm] or match_meme(matches[1]) if not meme_id then return 'I don\'t understand the meme name "' .. matches[1] .. '"' end _cache[searchterm] = meme_id print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3]) local url_gen = generate_meme(meme_id, matches[2], matches[3]) send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen}) return nil end return { description = "Generate a meme image with up and bottom texts.", usage = { "!meme search (name): Return the name of the meme that match.", "!meme list: Return the link where you can see the memes.", "!meme listall: Return the list of all memes. Only admin can call it.", '!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.', '!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.', }, patterns = { "^!meme (search) (.+)$", '^!meme (list)$', '^!meme (listall)$', '^!meme (.+) "(.*)" "(.*)"$', '^!meme "(.+)" "(.*)" "(.*)"$', "^!meme (.+) %- (.*) %- (.*)$" }, run = run }
gpl-2.0
qianqians/Screw
3rdparty/ammo.js/bullet/Demos/premake4.lua
10
2983
function createDemos( demos, incdirs, linknames) for _, name in ipairs(demos) do project ( "App_" .. name ) kind "ConsoleApp" targetdir ".." includedirs {incdirs} configuration { "Windows" } defines { "GLEW_STATIC"} links { "opengl32" } includedirs{ "../Glut" } libdirs {"../Glut"} files { "../build/bullet.rc" } configuration {"Windows", "x32"} links {"glew32s","glut32"} configuration {"Windows", "x64"} links {"glew64s", "glut64"} configuration {"MacOSX"} --print "hello" linkoptions { "-framework Carbon -framework OpenGL -framework AGL -framework Glut" } configuration {"not Windows", "not MacOSX"} links {"GL","GLU","glut"} configuration{} links { linknames } files { "./" .. name .. "/*.cpp" , "./" .. name .. "/*.h" } end end -- "CharacterDemo", fixme: it includes BspDemo files local localdemos = { "BasicDemo", "Box2dDemo", "BspDemo", "CcdPhysicsDemo", "CollisionDemo", "CollisionInterfaceDemo", "ConcaveConvexcastDemo", "ConcaveDemo", "ConcaveRaycastDemo", "ConstraintDemo", "ContinuousConvexCollision", "ConvexHullDistance", "DynamicControlDemo", "EPAPenDepthDemo", "ForkLiftDemo", "FeatherstoneMultiBodyDemo", "FractureDemo", "GenericJointDemo", "GimpactTestDemo", "GjkConvexCastDemo", "GyroscopicDemo", "InternalEdgeDemo", "MovingConcaveDemo", "MultiMaterialDemo", "RagdollDemo", "Raytracer", "RaytestDemo", "RollingFrictionDemo", "SimplexDemo", "SliderConstraintDemo", "TerrainDemo", "UserCollisionAlgorithm", "VehicleDemo", "VoronoiFractureDemo" } -- the following demos require custom include or link settings createDemos({"HelloWorld"},{"../src"},{"BulletDynamics","BulletCollision","LinearMath"}) createDemos(localdemos,{"../src","OpenGL"},{"OpenGLSupport","BulletDynamics", "BulletCollision", "LinearMath"}) createDemos({"ConvexDecompositionDemo"},{"../Extras/HACD","../Extras/ConvexDecomposition","../src","OpenGL"},{"OpenGLSupport","BulletDynamics", "BulletCollision", "LinearMath","HACD","ConvexDecomposition"}) createDemos({"SoftDemo"},{"../src","OpenGL"}, {"OpenGLSupport","BulletSoftBody", "BulletDynamics", "BulletCollision", "LinearMath"}) createDemos({"SerializeDemo"},{"../Extras/Serialize/BulletFileLoader","../Extras/Serialize/BulletWorldImporter","../src","OpenGL"},{"OpenGLSupport","BulletWorldImporter", "BulletFileLoader", "BulletSoftBody", "BulletDynamics", "BulletCollision", "LinearMath"}) createDemos({"BulletXmlImportDemo"},{"../Extras/Serialize/BulletFileLoader","../Extras/Serialize/BulletXmlWorldImporter", "../Extras/Serialize/BulletWorldImporter","../src","OpenGL"},{"OpenGLSupport","BulletXmlWorldImporter","BulletWorldImporter", "BulletFileLoader", "BulletSoftBody", "BulletDynamics", "BulletCollision", "LinearMath"}) include "OpenGL"
lgpl-2.1
araeisy/araeisy
plugins/youtube.lua
674
1270
do local google_config = load_from_file('data/google.lua') local function httpsRequest(url) print(url) local res,code = https.request(url) if code ~= 200 then return nil end return json:decode(res) end local function searchYoutubeVideos(text) local url = 'https://www.googleapis.com/youtube/v3/search?' url = url..'part=snippet'..'&maxResults=4'..'&type=video' url = url..'&q='..URL.escape(text) if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local data = httpsRequest(url) if not data then print("HTTP Error") return nil elseif not data.items then return nil end return data.items end local function run(msg, matches) local text = '' local items = searchYoutubeVideos(matches[1]) if not items then return "Error!" end for k,item in pairs(items) do text = text..'http://youtu.be/'..item.id.videoId..' '.. item.snippet.title..'\n\n' end return text end return { description = "Search video on youtube and send it.", usage = "!youtube [term]: Search for a youtube video and send it.", patterns = { "^!youtube (.*)" }, run = run } end
mit
AMIRUJK/teleujk
text axs.lua
24
1059
local function tosticker(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/stickers/'..msg.from.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) send_photo(get_receiver(msg), file, ok_cb, false) redis:del("sticker:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function run(msg,matches) local receiver = get_receiver(msg) local group = msg.to.id if msg.media then if msg.media.type == 'document' and is_momod(msg) and redis:get("sticker:photo") then if redis:get("sticker:photo") == 'waiting' then load_document(msg.id, tosticker, msg) end end end if matches[1] == "tophoto" and is_momod(msg) then redis:set("sticker:photo", "waiting") return 'Please send your sticker now' end end return { patterns = { "^[!/](tophoto)$", "%[(document)%]", }, run = run, }
gpl-2.0
Tri125/MCServer
MCServer/Plugins/APIDump/Hooks/OnChunkGenerating.lua
44
1623
return { HOOK_CHUNK_GENERATING = { CalledWhen = "A chunk is about to be generated. Plugin can override the built-in generator.", DefaultFnName = "OnChunkGenerating", -- also used as pagename Desc = [[ This hook is called before the world generator starts generating a chunk. The plugin may provide some or all parts of the generation, by-passing the built-in generator. The function is given access to the {{cChunkDesc|ChunkDesc}} object representing the contents of the chunk. It may override parts of the built-in generator by using the object's <i>SetUseDefaultXXX(false)</i> functions. After all the callbacks for a chunk have been processed, the server will generate the chunk based on the {{cChunkDesc|ChunkDesc}} description - those parts that are set for generating (by default everything) are generated, the rest are read from the ChunkDesc object.</p> <p> See also the {{OnChunkGenerated|HOOK_CHUNK_GENERATED}} hook. ]], Params = { { Name = "World", Type = "{{cWorld}}", Notes = "The world to which the chunk will be added" }, { Name = "ChunkX", Type = "number", Notes = "X-coord of the chunk" }, { Name = "ChunkZ", Type = "number", Notes = "Z-coord of the chunk" }, { Name = "ChunkDesc", Type = "{{cChunkDesc}}", Notes = "Generated chunk data." }, }, Returns = [[ If this function returns true, the server will not call any other plugin with the same chunk. If this function returns false, the server will call the rest of the plugins with the same chunk, possibly overwriting the ChunkDesc's contents. ]], }, -- HOOK_CHUNK_GENERATING }
apache-2.0
Enignite/darkstar
scripts/zones/Southern_San_dOria/npcs/Coderiant.lua
36
1471
----------------------------------- -- Area: Southern San d'Oria -- NPC: Coderiant -- General Info NPC -- @zone 230 -- @pos -111 -2 33 ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x247); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Enignite/darkstar
scripts/zones/RuAun_Gardens/mobs/Groundskeeper.lua
25
1323
----------------------------------- -- Area: RuAun Gardens -- MOB: Groundskeeper -- Note: Place holder Despot ----------------------------------- require("scripts/zones/RuAun_Gardens/MobIDs"); require("scripts/globals/fieldsofvalor"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) checkRegime(killer,mob,143,2); checkRegime(killer,mob,144,1); -- Get Groundskeeper ID and check if it is a PH of Despot mob = mob:getID(); -- Check if Groundskeeper is within the Despot_PH table if (Despot_PH[mob] ~= nil) then -- printf("%u is a PH",mob); -- Get Despot previous ToD Despot_ToD = GetServerVariable("[POP]Despot"); -- Check if Despot window is open, and there is not an Despot popped already(ACTION_NONE = 0) if (Despot_ToD <= os.time(t) and GetMobAction(Despot) == 0) then -- printf("Despot window open"); -- Give Groundskeeper 5 percent chance to pop Despot if (math.random(1,20) == 5) then -- printf("Despot will pop"); GetMobByID(Despot):setRespawnTime(GetMobRespawnTime(mob)); SetServerVariable("[PH]Despot", mob); DeterMob(mob, true); end end end end;
gpl-3.0
Enignite/darkstar
scripts/zones/Hall_of_Transference/npcs/_0e4.lua
43
1699
----------------------------------- -- Area: Hall of Transference -- NPC: Large Apparatus (Right) - Holla -- @pos -242.301 -1.849 269.867 14 ----------------------------------- package.loaded["scripts/zones/Hall_of_Transference/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Hall_of_Transference/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getVar("HollaChipRegistration") == 0 and player:getVar("skyShortcut") == 1 and trade:hasItemQty(478,1) and trade:getItemCount() == 1) then player:tradeComplete(); player:startEvent(0x00A6); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("HollaChipRegistration") == 1) then player:messageSpecial(NO_RESPONSE_OFFSET+6); -- Device seems to be functioning correctly. else player:startEvent(0x00A5); -- Hexagonal Cones end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00A6) then player:messageSpecial(NO_RESPONSE_OFFSET+4,478); -- You fit.. player:messageSpecial(NO_RESPONSE_OFFSET+5); -- Device has been repaired player:setVar("HollaChipRegistration",1); end end;
gpl-3.0
QUSpilPrgm/cuberite
Server/Plugins/NetworkTest/NetworkTest.lua
22
17057
-- NetworkTest.lua -- Implements a few tests for the cNetwork API --- Map of all servers currently open -- g_Servers[PortNum] = cServerHandle local g_Servers = {} --- Map of all UDP endpoints currently open -- g_UDPEndpoints[PortNum] = cUDPEndpoint local g_UDPEndpoints = {} --- List of fortune messages for the fortune server -- A random message is chosen for each incoming connection -- The contents are loaded from the splashes.txt file on plugin startup local g_Fortunes = { "Empty splashes.txt", } -- HTTPS certificate to be used for the SSL server: local g_HTTPSCert = [[ -----BEGIN CERTIFICATE----- MIIDfzCCAmegAwIBAgIJAOBHN+qOWodcMA0GCSqGSIb3DQEBBQUAMFYxCzAJBgNV BAYTAmN6MQswCQYDVQQIDAJjejEMMAoGA1UEBwwDbG9jMQswCQYDVQQKDAJfWDEL MAkGA1UECwwCT1UxEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xNTAxMjQwODQ2MzFa Fw0yNTAxMjEwODQ2MzFaMFYxCzAJBgNVBAYTAmN6MQswCQYDVQQIDAJjejEMMAoG A1UEBwwDbG9jMQswCQYDVQQKDAJfWDELMAkGA1UECwwCT1UxEjAQBgNVBAMMCWxv Y2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJkFYSElu/jw nxqjimmj246DejKJK8uy/l9QQibb/Z4kO/3s0gVPOYo0mKv32xUFP7wYIE3XWT61 zyfvK+1jpnlQTCtM8T5xw/7CULKgLmuIzlQx5Dhy7d+tW46kOjFKwQajS9YzwqWu KBOPnFamQWz6vIzuM05+7aIMXbzamInvW/1x3klIrpGQgALwSB1N+oUzTInTBRKK 21pecUE9t3qrU40Cs5bN0fQBnBjLwbgmnTh6LEplfQZHG5wLvj0IeERVU9vH7luM e9/IxuEZluCiu5ViF3jqLPpjYOrkX7JDSKme64CCmNIf0KkrwtFjF104Qylike60 YD3+kw8Q+DECAwEAAaNQME4wHQYDVR0OBBYEFHHIDTc7mrLDXftjQ5ejU9Udfdyo MB8GA1UdIwQYMBaAFHHIDTc7mrLDXftjQ5ejU9UdfdyoMAwGA1UdEwQFMAMBAf8w DQYJKoZIhvcNAQEFBQADggEBAHxCJxZPmH9tvx8GKiDV3rgGY++sMItzrW5Uhf0/ bl3DPbVz51CYF8nXiWvSJJzxhH61hKpZiqvRlpyMuovV415dYQ+Xc2d2IrTX6e+d Z4Pmwfb4yaX+kYqIygjXMoyNxOJyhTnCbJzycV3v5tvncBWN9Wqez6ZonWDdFdAm J+Moty+atc4afT02sUg1xz+CDr1uMbt62tHwKYCdxXCwT//bOs6W21+mQJ5bEAyA YrHQPgX76uo8ed8rPf6y8Qj//lzq/+33EIWqf9pnbklQgIPXJU07h+5L+Y63RF4A ComLkzas+qnQLcEN28Dg8QElXop6hfiD0xq3K0ac2bDnjoU= -----END CERTIFICATE----- ]] local g_HTTPSPrivKey = [[ -----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCZBWEhJbv48J8a o4ppo9uOg3oyiSvLsv5fUEIm2/2eJDv97NIFTzmKNJir99sVBT+8GCBN11k+tc8n 7yvtY6Z5UEwrTPE+ccP+wlCyoC5riM5UMeQ4cu3frVuOpDoxSsEGo0vWM8KlrigT j5xWpkFs+ryM7jNOfu2iDF282piJ71v9cd5JSK6RkIAC8EgdTfqFM0yJ0wUSitta XnFBPbd6q1ONArOWzdH0AZwYy8G4Jp04eixKZX0GRxucC749CHhEVVPbx+5bjHvf yMbhGZbgoruVYhd46iz6Y2Dq5F+yQ0ipnuuAgpjSH9CpK8LRYxddOEMpYpHutGA9 /pMPEPgxAgMBAAECggEAWxQ4m+I54BJYoSJ2YCqHpGvdb/b1emkvvsumlDqc2mP2 0U0ENOTS+tATj0gXvotBRFOX5r0nAYx1oO9a1hFaJRsGOz+w19ofLqO6JJfzCU6E gNixXmgJ7fjhZiWZ/XzhJ3JK0VQ9px/h+sKf63NJvfQABmJBZ5dlGe8CXEZARNin 03TnE3RUIEK+jEgwShN2OrGjwK9fjcnXMHwEnKZtCBiYEfD2N+pQmS20gIm13L1t +ZmObIC24NqllXxl4I821qzBdhmcT7+rGmKR0OT5YKbt6wFA5FPKD9dqlzXzlKck r2VAh+JlCtFKxcScmWtQOnVDtf5+mcKFbP4ck724AQKBgQDLk+RDhvE5ykin5R+B dehUQZgHb2pPL7N1DAZShfzwSmyZSOPQDFr7c0CMijn6G0Pw9VX6Vrln0crfTQYz Hli+zxlmcMAD/WC6VImM1LCUzouNRy37rSCnuPtngZyHdsyzfheGnjORH7HlPjtY JCTLaekg0ckQvt//HpRV3DCdaQKBgQDAbLmIOTyGfne74HLswWnY/kCOfFt6eO+E lZ724MWmVPWkxq+9rltC2CDx2i8jjdkm90dsgR5OG2EaLnUWldUpkE0zH0ATrZSV ezJWD9SsxTm8ksbThD+pJKAVPxDAboejF7kPvpaO2wY+bf0AbO3M24rJ2tccpMv8 AcfXBICDiQKBgQCSxp81/I3hf7HgszaC7ZLDZMOK4M6CJz847aGFUCtsyAwCfGYb 8zyJvK/WZDam14+lpA0IQAzPCJg/ZVZJ9uA/OivzCum2NrHNxfOiQRrLPxuokaBa q5k2tA02tGE53fJ6mze1DEzbnkFxqeu5gd2xdzvpOLfBxgzT8KU8PlQiuQKBgGn5 NvCj/QZhDhYFVaW4G1ArLmiKamL3yYluUV7LiW7CaYp29gBzzsTwfKxVqhJdo5NH KinCrmr7vy2JGmj22a+LTkjyU/rCZQsyDxXAoDMKZ3LILwH8WocPqa4pzlL8TGzw urXGE+rXCwhE0Mp0Mz7YRgZHJKMcy06duG5dh11pAoGBALHbsBIDihgHPyp2eKMP K1f42MdKrTBiIXV80hv2OnvWVRCYvnhrqpeRMzCR1pmVbh+QhnwIMAdWq9PAVTTn ypusoEsG8Y5fx8xhgjs0D2yMcrmi0L0kCgHIFNoym+4pI+sv6GgxpemfrmaPNcMx DXi9JpaquFRJLGJ7jMCDgotL -----END PRIVATE KEY----- ]] --- Map of all services that can be run as servers -- g_Services[ServiceName] = function() -> accept-callbacks local g_Services = { -- Echo service: each connection echoes back what has been sent to it echo = function (a_Port) return { -- A new connection has come, give it new link-callbacks: OnIncomingConnection = function (a_RemoteIP, a_RemotePort) return { OnError = function (a_Link, a_ErrorCode, a_ErrorMsg) LOG("EchoServer(" .. a_Port .. ": Connection to " .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. " failed: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, OnReceivedData = function (a_Link, a_Data) -- Echo the received data back to the link: a_Link:Send(a_Data) end, OnRemoteClosed = function (a_Link) end } -- Link callbacks end, -- OnIncomingConnection() -- Send a welcome message to newly accepted connections: OnAccepted = function (a_Link) a_Link:Send("Hello, " .. a_Link:GetRemoteIP() .. ", welcome to the echo server @ Cuberite-Lua\r\n") end, -- OnAccepted() -- There was an error listening on the port: OnError = function (a_ErrorCode, a_ErrorMsg) LOGINFO("EchoServer(" .. a_Port .. ": Cannot listen: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, -- OnError() } -- Listen callbacks end, -- echo -- Fortune service: each incoming connection gets a welcome message plus a random fortune text; all communication is ignored afterwards fortune = function (a_Port) return { -- A new connection has come, give it new link-callbacks: OnIncomingConnection = function (a_RemoteIP, a_RemotePort) return { OnError = function (a_Link, a_ErrorCode, a_ErrorMsg) LOG("FortuneServer(" .. a_Port .. "): Connection to " .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. " failed: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, OnReceivedData = function (a_Link, a_Data) -- Ignore any received data end, OnRemoteClosed = function (a_Link) end } -- Link callbacks end, -- OnIncomingConnection() -- Send a welcome message and the fortune to newly accepted connections: OnAccepted = function (a_Link) a_Link:Send("Hello, " .. a_Link:GetRemoteIP() .. ", welcome to the fortune server @ Cuberite-Lua\r\n\r\nYour fortune:\r\n") a_Link:Send(g_Fortunes[math.random(#g_Fortunes)] .. "\r\n") end, -- OnAccepted() -- There was an error listening on the port: OnError = function (a_ErrorCode, a_ErrorMsg) LOGINFO("FortuneServer(" .. a_Port .. "): Cannot listen: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, -- OnError() } -- Listen callbacks end, -- fortune -- HTTPS time - serves current time for each https request received httpstime = function (a_Port) return { -- A new connection has come, give it new link-callbacks: OnIncomingConnection = function (a_RemoteIP, a_RemotePort) local IncomingData = "" -- accumulator for the incoming data, until processed by the http return { OnError = function (a_Link, a_ErrorCode, a_ErrorMsg) LOG("https-time server(" .. a_Port .. "): Connection to " .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. " failed: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, OnReceivedData = function (a_Link, a_Data) IncomingData = IncomingData .. a_Data if (IncomingData:find("\r\n\r\n")) then -- We have received the entire request headers, just send the response and shutdown the link: local Content = os.date() a_Link:Send("HTTP/1.0 200 OK\r\nContent-type: text/plain\r\nContent-length: " .. #Content .. "\r\n\r\n" .. Content) a_Link:Shutdown() end end, OnRemoteClosed = function (a_Link) LOG("httpstime: link closed by remote") end } -- Link callbacks end, -- OnIncomingConnection() -- Start TLS on the new link: OnAccepted = function (a_Link) local res, msg = a_Link:StartTLSServer(g_HTTPSCert, g_HTTPSPrivKey, "") if not(res) then LOG("https-time server(" .. a_Port .. "): Cannot start TLS server: " .. msg) a_Link:Close() end end, -- OnAccepted() -- There was an error listening on the port: OnError = function (a_ErrorCode, a_ErrorMsg) LOGINFO("https-time server(" .. a_Port .. "): Cannot listen: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, -- OnError() } -- Listen callbacks end, -- httpstime -- TODO: Other services (daytime, ...) } function Initialize(a_Plugin) -- Load the splashes.txt file into g_Fortunes, overwriting current content: local idx = 1 for line in io.lines(a_Plugin:GetLocalFolder() .. "/splashes.txt") do g_Fortunes[idx] = line idx = idx + 1 end -- Use the InfoReg shared library to process the Info.lua file: dofile(cPluginManager:GetPluginsPath() .. "/InfoReg.lua") RegisterPluginInfoCommands() RegisterPluginInfoConsoleCommands() -- Seed the random generator: math.randomseed(os.time()) return true end function HandleConsoleNetClient(a_Split) -- Get the address to connect to: local Host = a_Split[3] or "google.com" local Port = a_Split[4] or 80 -- Create the callbacks "personalised" for the address: local Callbacks = { OnConnected = function (a_Link) LOG("Connected to " .. Host .. ":" .. Port .. ".") LOG("Connection stats: Remote address: " .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. ", Local address: " .. a_Link:GetLocalIP() .. ":" .. a_Link:GetLocalPort()) LOG("Sending HTTP request for front page.") a_Link:Send("GET / HTTP/1.0\r\nHost: " .. Host .. "\r\n\r\n") end, OnError = function (a_Link, a_ErrorCode, a_ErrorMsg) LOG("Connection to " .. Host .. ":" .. Port .. " failed: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, OnReceivedData = function (a_Link, a_Data) LOG("Received data from " .. Host .. ":" .. Port .. ":\r\n" .. a_Data) end, OnRemoteClosed = function (a_Link) LOG("Connection to " .. Host .. ":" .. Port .. " was closed by the remote peer.") end } -- Queue a connect request: local res = cNetwork:Connect(Host, Port, Callbacks) if not(res) then LOGWARNING("cNetwork:Connect call failed immediately") return true end return true, "Client connection request queued." end function HandleConsoleNetClose(a_Split) -- Get the port to close: local Port = tonumber(a_Split[3] or 1024) if not(Port) then return true, "Bad port number: \"" .. a_Split[3] .. "\"." end -- Close the server, if there is one: if not(g_Servers[Port]) then return true, "There is no server currently listening on port " .. Port .. "." end g_Servers[Port]:Close() g_Servers[Port] = nil return true, "Port " .. Port .. " closed." end function HandleConsoleNetIps(a_Split) local Addresses = cNetwork:EnumLocalIPAddresses() LOG("IP addresses enumerated, " .. #Addresses .. " found") for idx, addr in ipairs(Addresses) do LOG(" IP #" .. idx .. ": " .. addr) end return true end function HandleConsoleNetLookup(a_Split) -- Get the name to look up: local Addr = a_Split[3] or "google.com" -- Create the callbacks "personalised" for the host: local Callbacks = { OnNameResolved = function (a_Hostname, a_IP) LOG(a_Hostname .. " resolves to " .. a_IP) end, OnError = function (a_Query, a_ErrorCode, a_ErrorMsg) LOG("Failed to retrieve information for " .. a_Query .. ": " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") assert(a_Query == Addr) end, OnFinished = function (a_Query) LOG("Resolving " .. a_Query .. " has finished.") assert(a_Query == Addr) end, } -- Queue both name and IP DNS queries; -- we don't distinguish between an IP and a hostname in this command so we don't know which one to use: local res = cNetwork:HostnameToIP(Addr, Callbacks) if not(res) then LOGWARNING("cNetwork:HostnameToIP call failed immediately") return true end res = cNetwork:IPToHostname(Addr, Callbacks) if not(res) then LOGWARNING("cNetwork:IPToHostname call failed immediately") return true end return true, "DNS query has been queued." end function HandleConsoleNetListen(a_Split) -- Get the params: local Port = tonumber(a_Split[3] or 1024) if not(Port) then return true, "Invalid port: \"" .. a_Split[3] .. "\"." end local Service = string.lower(a_Split[4] or "echo") -- Create the callbacks specific for the service: if (g_Services[Service] == nil) then return true, "No such service: " .. Service end local Callbacks = g_Services[Service](Port) -- Start the server: local srv = cNetwork:Listen(Port, Callbacks) if not(srv:IsListening()) then -- The error message has already been printed in the Callbacks.OnError() return true end g_Servers[Port] = srv return true, Service .. " server started on port " .. Port end function HandleConsoleNetSClient(a_Split) -- Get the address to connect to: local Host = a_Split[3] or "github.com" local Port = a_Split[4] or 443 -- Create the callbacks "personalised" for the address: local Callbacks = { OnConnected = function (a_Link) LOG("Connected to " .. Host .. ":" .. Port .. ".") LOG("Connection stats: Remote address: " .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. ", Local address: " .. a_Link:GetLocalIP() .. ":" .. a_Link:GetLocalPort()) LOG("Sending HTTP request for front page.") a_Link:StartTLSClient() a_Link:Send("GET / HTTP/1.0\r\nHost: " .. Host .. "\r\n\r\n") end, OnError = function (a_Link, a_ErrorCode, a_ErrorMsg) LOG("Connection to " .. Host .. ":" .. Port .. " failed: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, OnReceivedData = function (a_Link, a_Data) LOG("Received data from " .. Host .. ":" .. Port .. ":\r\n" .. a_Data) end, OnRemoteClosed = function (a_Link) LOG("Connection to " .. Host .. ":" .. Port .. " was closed by the remote peer.") end } -- Queue a connect request: local res = cNetwork:Connect(Host, Port, Callbacks) if not(res) then LOGWARNING("cNetwork:Connect call failed immediately") return true end return true, "SSL Client connection request queued." end function HandleConsoleNetUdpClose(a_Split) -- Get the port to close: local Port = tonumber(a_Split[4] or 1024) if not(Port) then return true, "Bad port number: \"" .. a_Split[4] .. "\"." end -- Close the server, if there is one: if not(g_UDPEndpoints[Port]) then return true, "There is no UDP endpoint currently listening on port " .. Port .. "." end g_UDPEndpoints[Port]:Close() g_UDPEndpoints[Port] = nil return true, "UDP Port " .. Port .. " closed." end function HandleConsoleNetUdpListen(a_Split) -- Get the params: local Port = tonumber(a_Split[4] or 1024) if not(Port) then return true, "Invalid port: \"" .. a_Split[4] .. "\"." end local Callbacks = { OnReceivedData = function (a_Endpoint, a_Data, a_RemotePeer, a_RemotePort) LOG("Incoming UDP datagram from " .. a_RemotePeer .. " port " .. a_RemotePort .. ":\r\n" .. a_Data) end, OnError = function (a_Endpoint, a_ErrorCode, a_ErrorMsg) LOG("Error in UDP endpoint: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, } g_UDPEndpoints[Port] = cNetwork:CreateUDPEndpoint(Port, Callbacks) return true, "UDP listener on port " .. Port .. " started." end function HandleConsoleNetUdpSend(a_Split) -- Get the params: local Host = a_Split[4] or "localhost" local Port = tonumber(a_Split[5] or 1024) if not(Port) then return true, "Invalid port: \"" .. a_Split[5] .. "\"." end local Message if (a_Split[6]) then Message = table.concat(a_Split, " ", 6) else Message = "hello" end -- Define minimum callbacks for the UDP endpoint: local Callbacks = { OnError = function (a_Endpoint, a_ErrorCode, a_ErrorMsg) LOG("Error in UDP datagram sending: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, OnReceivedData = function () -- ignore end, } -- Send the data: local Endpoint = cNetwork:CreateUDPEndpoint(0, Callbacks) Endpoint:EnableBroadcasts() if not(Endpoint:Send(Message, Host, Port)) then Endpoint:Close() return true, "Sending UDP datagram failed" end Endpoint:Close() return true, "UDP datagram sent" end function HandleConsoleNetWasc(a_Split) local Callbacks = { OnConnected = function (a_Link) LOG("Connected to webadmin, starting TLS...") local res, msg = a_Link:StartTLSClient("", "", "") if not(res) then LOG("Failed to start TLS client: " .. msg) return end -- We need to send a keep-alive due to #1737 a_Link:Send("GET / HTTP/1.0\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n") end, OnError = function (a_Link, a_ErrorCode, a_ErrorMsg) LOG("Connection to webadmin failed: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, OnReceivedData = function (a_Link, a_Data) LOG("Received data from webadmin:\r\n" .. a_Data) -- Close the link once all the data is received: if (a_Data == "0\r\n\r\n") then -- Poor man's end-of-data detection; works on localhost -- TODO: The Close() method is not yet exported to Lua -- a_Link:Close() end end, OnRemoteClosed = function (a_Link) LOG("Connection to webadmin was closed") end, } if not(cNetwork:Connect("localhost", "8080", Callbacks)) then LOG("Canot connect to webadmin") end return true end
apache-2.0
Enignite/darkstar
scripts/zones/Windurst_Woods/npcs/Ibwam.lua
18
4569
----------------------------------- -- Area: Windurst Woods -- NPC: Ibwam -- Type: Warp NPC -- @pos -25.655 1.749 -60.651 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/globals/teleports"); require("scripts/globals/keyitems"); require("scripts/zones/Windurst_Woods/TextIDs"); --[[ Bitmask Designations: Windurst Woods (Working in a circuit from Ibwam) 00001 (H-10) Soni-Muni (Bomingo Round, walking the rim of the fountain) 00002 (J-13) Etsa Rhuyuli (atop the Auction House) 00004 (I-10) Cayu Pensharhumi (at the arch in the corridor west of Leviathan's Gate) 00008 (I-5) Umumu (Mithra Groves, at the arch next to the dhalmels.) 00010 (J-3) Nanaa Mihgo (Mithra Groves. North-most cluster) Windurst Walls (Counter-clockwise) 00020 (J-11) Yoriri (on top of the Auction House) 00040 (K-7) Shantotto (in Shantotto's Manor) 00080 (J-6) Moan-Maon (just west of the Consulate of Jeuno, at the pathway that leads to it) 00100 (H-3) Chomomo (on the East side behind the House of the Hero, go on the path leading North from Gerun-Garun) 00200 (F-5) Naih Arihmepp (wanders along the path by Yoran-Oran's Manor) Windurst Waters (All NPCs are in North Waters) (North to South) 00400 (G-4) Npopo (right by the gate to Sarutabaruta) 00800 (F-8) Lago-Charago (on top of the Optistery) 01000 (G-9) Amagusa-Chigurusa (South-east part of Huntsman's Court area, top left corner of G-9) 02000 (F-9) Funpo-Shipo (walks along the path outside Timbre Timbers Tavern, on the north side) 04000 (F-10) Kyume-Romeh (bottom floor of Timbre Timber Tavern) Port Windurst (West to East) 08000 (E-7) Kunchichi (a magic-caster inside the Orastery) 10000 (E-7) Yaman-Hachuman (inside the Orastery, east wall) 20000 (F-6) Choyi Totlihpa (southeast of Consulate of Bastok, entrance of the pathway tunnel) 40000 (G-7) Three of Clubs (standing guard leading to the dock/pier with the Magic/Weapon-Armor shops) 80000 (M-6) Yujuju (outside the Air Travel Agency) ]]-- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:getGil() == 300 and trade:getItemCount() == 1 and player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_COMPLETED and player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then -- Needs a check for at least traded an invitation card to Naja Salaheem player:startEvent(0x031a); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local LureWindurst = player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST); local WildcatWindurst = player:getVar("WildcatWindurst"); if (LureWindurst ~= QUEST_COMPLETED and ENABLE_TOAU == 1) then if (LureWindurst == QUEST_AVAILABLE) then player:startEvent(0x02e0); else if (WildcatWindurst == 0) then player:startEvent(0x02e1); elseif (player:isMaskFull(WildcatWindurst,20) == true) then player:startEvent(0x02e3); else player:startEvent(0x02e2); end end elseif (player:getCurrentMission(TOAU) >= 2) then player:startEvent(0x0319); else player:startEvent(0x02e4); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x02e0) then player:addQuest(WINDURST,LURE_OF_THE_WILDCAT_WINDURST); player:setVar("WildcatWindurst",0); player:addKeyItem(GREEN_SENTINEL_BADGE); player:messageSpecial(KEYITEM_OBTAINED,GREEN_SENTINEL_BADGE); elseif (csid == 0x02e3) then player:completeQuest(WINDURST,LURE_OF_THE_WILDCAT_WINDURST); player:addFame(WINDURST,150); player:setVar("WildcatWindurst",0); player:delKeyItem(GREEN_SENTINEL_BADGE); player:addKeyItem(GREEN_INVITATION_CARD); player:messageSpecial(KEYITEM_LOST,GREEN_SENTINEL_BADGE); player:messageSpecial(KEYITEM_OBTAINED,GREEN_INVITATION_CARD); elseif (csid == 0x031a) then player:tradeComplete(); toAhtUrhganWhitegate(player); end end;
gpl-3.0
apung/prosody-modules
mod_post_msg/mod_post_msg.lua
32
2623
module:depends"http" local jid_split = require "util.jid".split; local jid_prep = require "util.jid".prep; local msg = require "util.stanza".message; local test_password = require "core.usermanager".test_password; local b64_decode = require "util.encodings".base64.decode; local formdecode = require "net.http".formdecode; local xml = require"util.xml"; local function require_valid_user(f) return function(event, path) local request = event.request; local response = event.response; local headers = request.headers; if not headers.authorization then response.headers.www_authenticate = ("Basic realm=%q"):format(module.host.."/"..module.name); return 401 end local from_jid, password = b64_decode(headers.authorization:match"[^ ]*$"):match"([^:]*):(.*)"; from_jid = jid_prep(from_jid); if from_jid and password then local user, host = jid_split(from_jid); local ok, err = test_password(user, host, password); if ok and user and host then module:log("debug", "Authed as %s", from_jid); return f(event, path, from_jid); elseif err then module:log("debug", "User failed authentication: %s", err); end end return 401 end end local function handle_post(event, path, authed_user) local request = event.request; local response = event.response; local headers = request.headers; local body_type = headers.content_type; local to = jid_prep(path); local message; if body_type == "text/plain" then if to and request.body then message = msg({ to = to, from = authed_user, type = "chat"},request.body); end elseif body_type == "application/x-www-form-urlencoded" then local post_body = formdecode(request.body); message = msg({ to = post_body.to or to, from = authed_user, type = post_body.type or "chat"}, post_body.body); if post_body.html then local html, err = xml.parse([[<body xmlns="http://www.w3.org/1999/xhtml">]]..post_body.html..[[</body>]]); if not html then module:log("warn", "mod_post_msg: invalid XML: %s", err); return 400; end message:tag("html", {xmlns="http://jabber.org/protocol/xhtml-im"}):add_child(html):up(); end else return 415; end if message and message.attr.to then module:log("debug", "Sending %s", tostring(message)); module:send(message); return 201; end return 422; end module:provides("http", { default_path = "/msg"; route = { ["POST /*"] = require_valid_user(handle_post); OPTIONS = function(e) local headers = e.response.headers; headers.allow = "POST"; headers.accept = "application/x-www-form-urlencoded, text/plain"; return 200; end; } });
mit
Enignite/darkstar
scripts/globals/weaponskills/spirits_within.lua
30
1518
----------------------------------- -- Spirits Within -- Sword weapon skill -- Spirits Within Sword Weapon Skill -- TrolandAdded by Troland -- Skill Level: 175 -- Delivers an unavoidable attack. Damage varies with HP and TP. -- Not aligned with any "elemental gorgets" or "elemental belts" due to it's absence of Skillchain properties. -- Element: None -- Modifiers: HP: -- 100%TP 200%TP 300%TP -- 12.5% 50% 100% ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); require("scripts/globals/utils"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local HP = player:getHP(); local TP = player:getTP(); local WSC = 0; if (TP == 300) then WSC = HP * 0.46875; elseif (TP >= 200) then WSC = HP * ((TP - 200) / (100 / (0.46875 - 0.1875))); elseif (TP >= 100) then WSC = HP * ((TP - 100) / (100 / (0.1875 - 0.125))); end if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then -- Damage calculations changed based on: http://www.bg-wiki.com/bg/Spirits_Within http://www.bluegartr.com/threads/121610-Rehauled-Weapon-Skills-tier-lists?p=6142188&viewfull=1#post6142188 if (TP == 300) then WSC = HP; elseif (TP >= 200) then WSC = HP * .5 elseif (TP >= 100) then WSC = HP * .125; end end local damage = target:breathDmgTaken(WSC); damage = damage * WEAPON_SKILL_POWER return 1, 0, false, damage; end
gpl-3.0
Enignite/darkstar
scripts/zones/Wajaom_Woodlands/npcs/leypoint.lua
17
2538
----------------------------------- -- Area: Wajaom Woodlands -- NPC: Leypoint -- Teleport point, Quest -- NAVIGATING THE UNFRIENDLY SEAS RELATED -- -- @pos -200.027 -8.500 80.058 51 ----------------------------------- require("scripts/zones/Wajaom_Woodlands/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(AHT_URHGAN,OLDUUM) == QUEST_COMPLETED and player:hasItem(15769) == false) then if (trade:hasItemQty(2217,1) and trade:getItemCount() == 1) then -- Trade Lightning Band player:tradeComplete(); -- Trade Complete player:addItem(15769); -- Receive Olduum Ring player:messageSpecial(ITEM_OBTAINED,15769); -- Message for Receiving Ring end end if (player:getQuestStatus(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS) == QUEST_ACCEPTED and player:getVar("NavigatingtheUnfriendlySeas") == 2) then if (trade:hasItemQty(2341,1) and trade:getItemCount() == 1) then -- Trade Hydrogauge player:messageSpecial(PLACE_HYDROGAUGE,2341); -- You set the <item> in the trench. player:tradeComplete(); --Trade Complete player:setVar("NavigatingtheUnfriendlySeas",3) player:setVar("Leypoint_waitJTime",getMidnight()); -- Time Set for 1 day real life time. printf("Midnight: %u",getMidnight()); printf("Os: %u",os.time()); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS) == QUEST_ACCEPTED and player:getVar("NavigatingtheUnfriendlySeas") == 3) then if (player:getVar("Leypoint_waitJTime") <= os.time()) then player:startEvent(0x01FC); player:setVar("NavigatingtheUnfriendlySeas",4); -- play cs for having waited enough time else player:messageSpecial(ENIGMATIC_LIGHT,2341); -- play cs for not waiting long enough end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
omidtarh/hasan
plugins/boobs.lua
731
1601
do -- Recursive function local function getRandomButts(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.obutts.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt <= 3 then print('Cannot get that butts, trying another one...') return getRandomButts(attempt) end return 'http://media.obutts.ru/' .. data.preview end local function getRandomBoobs(attempt) attempt = attempt or 0 attempt = attempt + 1 local res,status = http.request("http://api.oboobs.ru/noise/1") if status ~= 200 then return nil end local data = json:decode(res)[1] -- The OpenBoobs API sometimes returns an empty array if not data and attempt < 10 then print('Cannot get that boobs, trying another one...') return getRandomBoobs(attempt) end return 'http://media.oboobs.ru/' .. data.preview end local function run(msg, matches) local url = nil if matches[1] == "!boobs" then url = getRandomBoobs() end if matches[1] == "!butts" then url = getRandomButts() end if url ~= nil then local receiver = get_receiver(msg) send_photo_from_url(receiver, url) else return 'Error getting boobs/butts for you, please try again later.' end end return { description = "Gets a random boobs or butts pic", usage = { "!boobs: Get a boobs NSFW image. 🔞", "!butts: Get a butts NSFW image. 🔞" }, patterns = { "^!boobs$", "^!butts$" }, run = run } end
gpl-2.0
Enignite/darkstar
scripts/zones/Xarcabard/npcs/Trail_Markings.lua
17
2473
----------------------------------- -- Area: Xarcabard -- NPC: Trail Markings -- Dynamis-Xarcabard Enter -- @pos 570 0 -272 112 ----------------------------------- package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/dynamis"); require("scripts/zones/Xarcabard/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("DynaXarcabard_Win") == 1) then player:startEvent(0x0020,HYDRA_CORPS_BATTLE_STANDARD); -- Win CS elseif (player:hasKeyItem(HYDRA_CORPS_INSIGNIA)) then local firstDyna = 0; local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if (checkFirstDyna(player,6)) then -- First Dyna-Xarcabard => CS firstDyna = 1; end if (player:getMainLvl() < DYNA_LEVEL_MIN) then player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN); elseif ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaXarcabard]UniqueID")) then player:startEvent(0x0010,6,firstDyna,0,BETWEEN_2DYNA_WAIT_TIME,32,VIAL_OF_SHROUDED_SAND,4236,4237); else dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456); player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,6); end else player:messageSpecial(UNUSUAL_ARRANGEMENT_OF_PEBBLES); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("updateRESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("finishRESULT: %u",option); if (csid == 0x0020) then player:setVar("DynaXarcabard_Win",0); elseif (csid == 0x0010 and option == 0) then if (checkFirstDyna(player,6)) then player:setVar("Dynamis_Status",player:getVar("Dynamis_Status") + 64); end player:setPos(569.312,-0.098,-270.158,90,0x87); end end;
gpl-3.0
Enignite/darkstar
scripts/globals/items/pumpkin_cake.lua
36
1213
----------------------------------------- -- ID: 5631 -- Item: Pumpkin Cake -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP Recovered while healing +2 -- MP Recovered while healing +4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5631); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_MPHEAL, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_MPHEAL, 4); end;
gpl-3.0
mamadtnt/new
plugins/add_bot.lua
189
1492
--[[ Bot can join into a group by replying a message contain an invite link or by typing !add [invite link]. URL.parse cannot parsing complicated message. So, this plugin only works for single [invite link] in a post. [invite link] may be preceeded but must not followed by another characters. --]] do local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) i = 0 for k,segment in pairs(parsed_path) do i = i + 1 if segment == 'joinchat' then invite_link = string.gsub(parsed_path[i+1], '[ %c].+$', '') break end end return invite_link end local function action_by_reply(extra, success, result) local hash = parsed_url(result.text) join = import_chat_link(hash, ok_cb, false) end function run(msg, matches) if is_sudo(msg) then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) elseif matches[1] then local hash = parsed_url(matches[1]) join = import_chat_link(hash, ok_cb, false) end end end return { description = 'Invite the bot into a group chat via its invite link.', usage = { '!AddBot : Join a group by replying a message containing invite link.', '!AddBot [invite_link] : Join into a group by providing their [invite_link].' }, patterns = { '^[/!](addBot)$', '^[/!](ddBot) (.*)$' }, run = run } end
gpl-2.0
dwdm/snabbswitch
src/apps/csv.lua
15
1587
module(...,package.seeall) local app = require("core.app") local ffi = require("ffi") local C = ffi.C -- Frequency at which lines are added to the CSV file. -- (XXX should be an argument to the app.) interval = 1.0 CSV = {} function CSV:new (directory) local o = { appfile = io.open(directory.."/app.csv", "w"), linkfile = io.open(directory.."/link.csv", "w") } o.appfile:write("time,name,class,cpu,crashes,starttime\n") o.appfile:flush() o.linkfile:write("time,from_app,from_port,to_app,to_port,txbytes,txpackets,rxbytes,rxpackets,dropbytes,droppackets\n") o.linkfile:flush() timer.new('CSV', function () o:output() end, 1e9, 'repeating') return setmetatable(o, {__index = CSV}) end function CSV:pull () local now = engine.now() if self.next_report and self.next_report > now then return end self.next_report = (self.next_report or now) + interval for name, app in pairs(app.app_table) do self.appfile:write( string.format("%f,%s,%s,%d,%d,%d\n", tonumber(now), name, app.zone, 0, 0, 0)) self.appfile:flush() end for spec, link in pairs(app.link_table) do local fa, fl, ta, tl = config.parse_link(spec) local s = link.stats self.linkfile:write( string.format("%f,%s,%s,%s,%s,%d,%d,%d,%d,%d,%d\n", now,fa,fl,ta,tl, s.txbytes, s.txpackets, s.rxbytes, s.rxpackets, 0, s.txdrop)) self.linkfile:flush() end end
apache-2.0
aqasaeed/telebot
plugins/get.lua
613
1067
local function get_variables_hash(msg) if msg.to.type == 'chat' then return 'chat:'..msg.to.id..':variables' end if msg.to.type == 'user' then return 'user:'..msg.from.id..':variables' end end local function list_variables(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do text = text..names[i]..'\n' end return text end end local function get_value(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return'Not found, use "!get" to list variables' else return var_name..' => '..value end end end local function run(msg, matches) if matches[2] then return get_value(msg, matches[2]) else return list_variables(msg) end end return { description = "Retrieves variables saved with !set", usage = "!get (value_name): Returns the value_name value.", patterns = { "^(!get) (.+)$", "^!get$" }, run = run }
gpl-2.0
Enignite/darkstar
scripts/zones/Port_Bastok/npcs/Alib-Mufalib.lua
19
3841
----------------------------------- -- Area: Port Bastok -- NPC: Alib-Mufalib -- Type: Warp NPC -- @pos 116.080 7.372 -31.820 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/globals/teleports"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Bastok/TextIDs"); --[[ Bitmask Designations: Port Bastok (East to West) 00001 (J-5) Kaede (northernmost house) 00002 (F-5) Patient Wheel (north of Warehouse 2) 00004 (F-6) Paujean (bottom floor of Warehouse 2) 00008 (E-6) Hilda (Steaming Sheep Restaurant, walks on the top floor and occasionally down. However, she can still be talked to when on second floor. Unable to get if you have Cid's Secret flagged.) 00010 (F-8) Tilian (end of a pier west of Air Travel Agency) Metalworks (all found on top floor) 00020 (G-8) Raibaht (Cid's lab) 00040 (G-8) Invincible Shield (outside Cid's Lab) 00080 (G-7) Manilam (on top of Cermet Refinery) 00100 (I-8) Kaela (between Consulate of Windurst & Consulate of Bastok) 00200 (K-7) Ayame (Inside north Cannonry) Bastok Markets (East to West) 00400 (K-10) Harmodios (Harmodios's Music Shop) 00800 (J-10) Arawn (west of music store) 01000 (I-9) Horatius (Inside Trader's Home) 02000 (E-10) Ken (outside Mjoll's General Goods) 04000 (E-11) Pavel (West Gate to South Gustaberg) Bastok Mines (Clockwise, starting at Ore Street, upper floor to lower floor) 08000 (H-5) Griselda (upper floor, Bat's Lair Inn) 10000 (I-6) Goraow (upper floor, in stairwell of Ore Street) 20000 (I-7) Echo Hawk (lower floor, Ore Street) 40000 (H-6) Deidogg (lower floor, Ore Street) 80000 (H-9) Vaghron (southwest of South Auction House) ]]-- function onTrade(player,npc,trade) if (trade:getGil() == 300 and trade:getItemCount() == 1 and player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_COMPLETED and player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then -- Needs a check for at least traded an invitation card to Naja Salaheem player:startEvent(0x017b); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local LureBastok = player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK); local WildcatBastok = player:getVar("WildcatBastok"); if (LureBastok ~= 2 and ENABLE_TOAU == 1) then if (LureBastok == 0) then player:startEvent(0x0165); else if (WildcatBastok == 0) then player:startEvent(0x0166); elseif (player:isMaskFull(WildcatBastok,20) == true) then player:startEvent(0x0168); else player:startEvent(0x0167); end end elseif (player:getCurrentMission(TOAU) >= 2) then player:startEvent(0x017a); else player:startEvent(0x0169); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0165) then player:addQuest(BASTOK,LURE_OF_THE_WILDCAT_BASTOK); player:setVar("WildcatBastok",0); player:addKeyItem(BLUE_SENTINEL_BADGE); player:messageSpecial(KEYITEM_OBTAINED,BLUE_SENTINEL_BADGE); elseif (csid == 0x0168) then player:completeQuest(BASTOK,LURE_OF_THE_WILDCAT_BASTOK); player:addFame(BASTOK,150); player:setVar("WildcatBastok",0); player:delKeyItem(BLUE_SENTINEL_BADGE); player:addKeyItem(BLUE_INVITATION_CARD); player:messageSpecial(KEYITEM_LOST,BLUE_SENTINEL_BADGE); player:messageSpecial(KEYITEM_OBTAINED,BLUE_INVITATION_CARD); elseif (csid == 0x017b) then player:tradeComplete(); toAhtUrhganWhitegate(player); end end;
gpl-3.0
Enignite/darkstar
scripts/globals/items/pamama_tart.lua
35
1447
----------------------------------------- -- ID: 4563 -- Item: pamama_tart -- Food Effect: 1hour, All Races ----------------------------------------- -- HP 10 -- MP 10 -- Dexterity -1 -- Intelligence 3 -- MP Recovered While Healing 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4563); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_MP, 10); target:addMod(MOD_DEX, -1); target:addMod(MOD_INT, 3); target:addMod(MOD_MPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_MP, 10); target:delMod(MOD_DEX, -1); target:delMod(MOD_INT, 3); target:delMod(MOD_MPHEAL, 2); end;
gpl-3.0
Enignite/darkstar
scripts/zones/Bastok_Mines/npcs/Deidogg.lua
19
4762
----------------------------------- -- Area: Bastok Mines -- NPC: Deidogg -- Starts and Finishes Quest: The Talekeeper's Truth, The Talekeeper's Gift (start) -- @pos -13 7 29 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getVar("theTalekeeperTruthCS") == 3) then if (trade:hasItemQty(1101,1) and trade:getItemCount() == 1) then -- Trade Mottled Quadav Egg player:startEvent(0x00a2); end elseif (player:getVar("theTalekeeperTruthCS") == 4) then if (trade:hasItemQty(1099,1) and trade:getItemCount() == 1) then -- Trade Parasite Skin player:startEvent(0x00a4); end elseif (player:getVar("theTalekeeperGiftCS") == 2) then if (trade:hasItemQty(4394,1) and trade:getItemCount() == 1) then -- Trade Ginger Cookie player:startEvent(0x00ac); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local theDoorman = player:getQuestStatus(BASTOK,THE_DOORMAN); local theTalekeeperTruth = player:getQuestStatus(BASTOK,THE_TALEKEEPER_S_TRUTH); local theTalekeeperTruthCS = player:getVar("theTalekeeperTruthCS"); local Wait1DayForAF3 = player:getVar("DeidoggWait1DayForAF3"); local theTalekeeperGiftCS = player:getVar("theTalekeeperGiftCS"); local WildcatBastok = player:getVar("WildcatBastok"); if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,18) == false) then player:startEvent(0x01f8); elseif (theDoorman == QUEST_COMPLETED and theTalekeeperTruth == QUEST_AVAILABLE and player:getMainJob() == 1 and player:getMainLvl() >= 50) then if (theTalekeeperTruthCS == 1) then player:startEvent(0x00a0); player:setVar("theTalekeeperTruthCS",2); elseif (theTalekeeperTruthCS == 2) then player:startEvent(0x00a1); -- Start Quest "The Talekeeper's Truth" else player:startEvent(0x0020); -- Standard dialog end elseif (theTalekeeperTruthCS == 4) then player:startEvent(0x00a3); -- During Quest "The Talekeeper's Truth" elseif (theTalekeeperTruthCS == 5 and VanadielDayOfTheYear() ~= player:getVar("theTalekeeperTruth_timer")) then player:startEvent(0x00a5); -- Finish Quest "The Talekeeper's Truth" elseif (theTalekeeperTruthCS == 5 or (theTalekeeperTruth == QUEST_COMPLETED and (player:needToZone() or VanadielDayOfTheYear() == Wait1DayForAF3))) then player:startEvent(0x00a6); -- New standard dialog after "The Talekeeper's Truth" elseif (player:needToZone() == false and VanadielDayOfTheYear() ~= Wait1DayForAF3 and Wait1DayForAF3 ~= 0 and theTalekeeperGiftCS == 0 and player:getMainJob() == 1) then player:startEvent(0x00aa); player:setVar("theTalekeeperGiftCS",1); player:setVar("DeidoggWait1DayForAF3",0); else player:startEvent(0x0020); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00a1) then player:addQuest(BASTOK,THE_TALEKEEPER_S_TRUTH); player:setVar("theTalekeeperTruthCS",3); elseif (csid == 0x00a2) then player:tradeComplete(); player:setVar("theTalekeeperTruthCS",4); elseif (csid == 0x00a4) then player:tradeComplete(); player:setVar("theTalekeeperTruthCS",5); player:setVar("theTalekeeperTruth_timer",VanadielDayOfTheYear()); elseif (csid == 0x00a5) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14089); -- Fighter's Calligae else player:addItem(14089); player:messageSpecial(ITEM_OBTAINED, 14089); -- Fighter's Calligae player:setVar("theTalekeeperTruthCS",0); player:setVar("theTalekeeperTruth_timer",0); player:setVar("DeidoggWait1DayForAF3",VanadielDayOfTheYear()); player:needToZone(true); player:addFame(BASTOK,AF2_FAME); player:completeQuest(BASTOK,THE_TALEKEEPER_S_TRUTH); end elseif (csid == 0x00ac) then player:tradeComplete(); player:addQuest(BASTOK,THE_TALEKEEPER_S_GIFT); player:setVar("theTalekeeperGiftCS",3); elseif (csid == 0x01f8) then player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",18,true); end end;
gpl-3.0
Enignite/darkstar
scripts/zones/Boneyard_Gully/mobs/Race_Runner.lua
16
1498
----------------------------------- -- Area: Boneyard_Gully -- Name: Race Runner ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); local path = { -539, 0, -481, -556, 0, -478, -581, 0, -475, -579, -3, -460, -572, 2, -433, -545, 1, -440, -532, 0, -466 }; ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) onMobRoam(mob); end; ----------------------------------- -- onMobRoamAction Action ----------------------------------- function onMobRoamAction(mob) pathfind.patrol(mob, path, PATHFLAG_REVERSE); end; ----------------------------------- -- onMobRoam Action ----------------------------------- function onMobRoam(mob) -- move to start position if not moving if (mob:isFollowingPath() == false) then mob:pathThrough(pathfind.first(path)); end end; ----------------------------------- -- onMobEngaged Action ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) end;
gpl-3.0
fcpxhacks/fcpxhacks
src/extensions/cp/highland2/Sidebar.lua
2
1480
--- === cp.highland2.Sidebar === --- --- Represents the sidebar for a document opened in Highland. local Group = require "cp.ui.Group" local go = require "cp.rx.go" local If = go.If local Sidebar = Group:subclass("cp.highland2.Sidebar") function Sidebar.static.matches(e) return Group.matches(e) and e:attributeValue("AXIdentifier") == "Sidebar View Controller" end function Sidebar:initialized(document, uiFinder) Group.initialized(self, document, uiFinder) end --- cp.highland2.Sidebar.document <cp.highland2.Document> --- Field --- The [Document](cp.highland2.Document.md) this `Sidebar` belongs to. function Sidebar.lazy.value:document() return self:parent() end --- cp.highland2.Sidebar.doShow <cp.rx.go.Statement> --- Field --- A [Statement](cp.rx.go.Statement.md) that will attempt to show the Sidebar, if possible. function Sidebar.lazy.value:doShow() return If(self.isShowing):Is(false) :Then(self.document.doShow) :Then(self:app().menu:doSelectMenu({"View", "Toggle Sidebar"})) end --- cp.highland2.Sidebar.doHide <cp.rx.go.Statement> --- Field --- A [Statement](cp.rx.go.Statement.md) that will attempt to hide the Sidebar, if possible. function Sidebar.lazy.value:doHide() return If(self.isShowing) :Then(self.document.doShow) :Then(self:app().menu:doSelectMenu({"View", "Toggle Sidebar"})) end return Sidebar
mit
BooM-amour/MOHAMAD
plugins/admin.lua
60
6680
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function user_info_callback(cb_extra, success, result) result.access_hash = nil result.flags = nil result.phone = nil if result.username then result.username = '@'..result.username end result.print_name = result.print_name:gsub("_","") local text = serpent.block(result, {comment=false}) text = text:gsub("[{}]", "") text = text:gsub('"', "") text = text:gsub(",","") if cb_extra.msg.to.type == "chat" then send_large_msg("chat#id"..cb_extra.msg.to.id, text) else send_large_msg("user#id"..cb_extra.msg.to.id, text) end end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairs(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "Msg sent" end if matches[1] == "block" then if is_admin2(matches[2]) then return "You can't block admins" end block_user("user#id"..matches[2],ok_cb,false) return "User blocked" end if matches[1] == "unblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User unblocked" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "delcontact" then del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent dialog list with both json and text format to your private" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end return end return { usage = { "pm: Send Pm To Priavate Chat.", "block: Block User [id].", "unblock: Unblock User [id].", "markread on: Reads Messages agancy Bot.", "markread off: Don't Reads Messages agancy Bot.", "setbotphoto: Set New Photo For Bot Account.", "contactlist: Send A List Of Bot Contacts.", "dialoglist: Send A Dialog Of Chat.", "delcontact: Delete Contact.", "import: Added Bot In Group With Link.", }, patterns = { "^(pm) (%d+) (.*)$", "^(import) (.*)$", "^(unblock) (%d+)$", "^(block) (%d+)$", "^(markread) (on)$", "^(markread) (off)$", "^(setbotphoto)$", "%[(photo)%]", "^(contactlist)$", "^(dialoglist)$", "^(delcontact) (%d+)$", "^(whois) (%d+)$" }, run = run, }
gpl-2.0
Enignite/darkstar
scripts/globals/items/gold_lobster.lua
18
1405
----------------------------------------- -- ID: 5797 -- Item: gold_lobster -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -5 -- Vitality 3 -- Defense % 15 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5797); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, -5); target:addMod(MOD_VIT, 3); target:addMod(MOD_DEFP, 15); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, -5); target:delMod(MOD_VIT, 3); target:delMod(MOD_DEFP, 15); end;
gpl-3.0
zeus-ff/test
dd/plugins.lua
2
4751
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_plugins(only_enabled) local text = '' for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return 'Plugin '..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return 'Plugin '..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return 'Plugin '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return 'Plugin '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return 'Plugin '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return 'Plugin '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '/plugins' then return list_plugins() end -- Re-enable a plugin for this chat if matches[1] == 'enable' and matches[3] == 'chat' then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == 'enable' then local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == 'disable' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == 'disable' then print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'reload' then return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { "/plugins: list all plugins.", "/plugins enable [plugin]: enable plugin.", "/plugins disable [plugin]: disable plugin.", "/plugins disable [plugin] chat: disable plugin only this chat.", "/plugins reload: reloads all plugins." }, patterns = { "^[!/]plugins$", "^[!/]plugins? (enable) ([%w_%.%-]+)$", "^[!/]plugins? (disable) ([%w_%.%-]+)$", "^[!/]plugins? (enable) ([%w_%.%-]+) (chat)", "^[!/]plugins? (disable) ([%w_%.%-]+) (chat)", "^[!/]plugins? (reload)$" }, run = run, privileged = true } end
gpl-2.0
vladimir-g/fainty
widgets/battery.lua
1
7863
-------------------- -- Battery widget -- -------------------- -- Copyright (c) 2013-2015 Vladimir Gorbunov -- Release under MIT license, see LICENSE file for more details local wibox = require("wibox") local awful = require('awful') local naughty = require('naughty') local utils = require("fainty.utils") local base = require("fainty.widgets.base") local gears = require("gears") local math = math local unpack = unpack local setmetatable = setmetatable local io = io local os = os local pairs = pairs local table = table local Battery = { mt = {} } Battery.path = '/sys/class/power_supply/' function Battery:new(bat) local new_instance = { name = bat, path = Battery.path .. bat .. '/' } setmetatable(new_instance, { __index = Battery }) return new_instance end function Battery:read(val) local path = self.path .. val local fd = io.open(path, 'r') if not fd then return nil end data = fd:read('*all') fd:close() return utils.trim(data) end function Battery:is_present() local present = self:read('present') if present == '1' then return true else return false end end function Battery:status() local data = { status = self:read('status'), percent = nil, time = nil, capacity = nil, watt = nil } local current, full, rate data.percent = tonumber(self:read('capacity')) -- local rate_v = tonumber(self:read('voltage_now')) if self:read('energy_now') then current = tonumber(self:read('energy_now')) full = tonumber(self:read('energy_full')) rate = tonumber(self:read('power_now')) elseif self:read('charge_now') then current = tonumber(self:read('charge_now')) full = tonumber(self:read('charge_full')) rate = tonumber(self:read('current_now')) else return data end -- if rate ~= nil and rate_v ~= nil then -- data.watt = (rate * rate_v) / 1e12 -- end if not data.percent then data.percent = math.min(math.floor(current / full * 100), 100) end local left if rate ~= 0 and data.status == 'Discharging' then left = current / rate elseif rate ~= 0 and data.status == 'Charging' then left = (full - current) / rate else left = nil end if left then data.hours = math.floor(left) data.minutes = math.floor(60 * (left - data.hours)) data.in_seconds = math.floor(data.hours * 3600 + (data.minutes * 60)) else data.hours = nil data.minutes = nil data.in_seconds = nil end return data end local BatteryWidget = { mt = {} } function BatteryWidget:refresh() local bat = self.selected if bat == nil then self:set_markup(self.settings.fmt_not_present) return end if bat:is_present() then local data = bat:status() local fmt = self.settings.fmt_unknown if data.status == 'Discharging' then fmt = self.settings.fmt_discharging elseif data.status == 'Charging' then fmt = self.settings.fmt_charging end if (data.in_seconds and data.in_seconds < self.warning_seconds and data.status == 'Discharging') then fmt = self.settings.fmt_warning if self.settings.notify_warning then self.notif_id = naughty.notify({ preset = naughty.config.presets.critical, timeout = 10, replaces_id = self.notif_id or nil, title = self.settings.notify_warning_title, text = self.settings.notify_warning_text }).id end end local percent = 0 if data.percent then percent = data.percent end local values = { name = self.selected.name, status = data.status, percent = percent or 0, hours = data.hours or 0, minutes = data.minutes or 0, in_seconds = data.in_seconds or 0, watt = data.watt or 0 } self:set_markup(fmt % values) -- Update popup if needed if self.settings.show_popup then self.popup_wgt:set_markup(self.settings.popup_fmt % values) end else self:set_markup(self.settings.fmt_not_present) end return end -- Get batteries table for awful.menu function BatteryWidget:get_menu_items() local battery_list = {} for k, v in pairs(self.batteries) do battery_list[k] = { v.name, function () self.selected = self.batteries[k] self:refresh() end } end return battery_list end local function new(args) -- TODO: Additional battery params, voltage, etc args.selected = args.selected or 'BAT0' settings = utils.merge_settings( args.settings or {}, { fmt_discharging = ' <span color="#F80000">↯</span>%(percent)3d% ' .. '(%(hours)d:%(minutes)02d)', -- Red color fmt_charging = ' <span color="#00EE00">↯</span>%(percent)3d% ' .. '(%(hours)d:%(minutes)02d)', -- Green color fmt_unknown = ' <span color="#FFFFFF">↯</span>%(percent)3d%', -- White fmt_warning = ' <span color="#F80000">↯!%(percent)3d%</span>', -- Red fmt_not_present = ' <span color="#FFFFFF">↯</span> N/A', -- White popup_fmt = 'Name: %(name)s\n' .. 'Status: %(status)s\n' .. 'Remaining: %(percent)s%\n' .. 'Time: %(hours)d:%(minutes)02d', show_popup = true, menu_theme = { width = 120, height = 15 }, bind_buttons = true, warning_seconds = 600, refresh_timeout = 25, notify_warning = true, notify_warning_title = 'Low battery', notify_warning_text = 'Less than 10 minutes remaining' } ) local obj = base(wibox.widget.textbox()) -- local obj = wibox.widget.textbox() for k, v in pairs(BatteryWidget) do obj[k] = v end obj.settings = settings obj.warning_seconds = settings.warning_seconds -- Get battery list obj.batteries = {} obj.selected = nil local batlist = io.popen('ls ' .. Battery.path) for line in batlist:lines() do if line:match('^BAT%d+') then battery = Battery:new(line) if battery.name == args.selected then obj.selected = battery end table.insert(obj.batteries, battery) end end if not obj.selected and #obj.batteries ~= 0 then obj.selected = obj.batteries[1] end batlist:close() local btns = {} -- Popup if obj.settings.show_popup then obj:create_popup() if settings.bind_buttons then btns = gears.table.join( btns, awful.button({ }, 1, function () obj:toggle_popup() end) ) end end -- Add menu if there is more than one battery if #obj.batteries ~= 1 then local battery_menu = awful.menu({ items = obj:get_menu_items(), theme = settings.menu_theme }) if settings.bind_buttons then btns = gears.table.join( btns, awful.button({ }, 3, function () battery_menu:toggle() end) ) end end if settings.bind_buttons then obj:buttons(btns) obj.popup:buttons( awful.button({ }, 1, function () obj:toggle_popup() end) ) end obj:refresh() -- Set update timer if #obj.batteries ~= 0 then refresh_timer = gears.timer({ timeout = settings.refresh_timeout }) refresh_timer:connect_signal("timeout", function() obj:refresh() end) refresh_timer:start() end return obj end function BatteryWidget.mt:__call(...) return new(...) end return setmetatable(BatteryWidget, BatteryWidget.mt)
mit
Enignite/darkstar
scripts/zones/Yughott_Grotto/npcs/Treasure_Chest.lua
19
2570
----------------------------------- -- Area: Yughott Grotto -- NPC: Treasure Chest -- @zone 142 ----------------------------------- package.loaded["scripts/zones/Yughott_Grotto/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/treasure"); require("scripts/zones/Yughott_Grotto/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1024,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1024,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1024); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
zeus-ff/test
bot/utils.lua
473
24167
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 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 -- 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) 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 --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(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)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == 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 function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not 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 function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_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 == user_id then var = true end end return var end --Check if user is the mod of that group or not 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[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == 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 function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
Enignite/darkstar
scripts/zones/Metalworks/npcs/Malduc.lua
19
3425
----------------------------------- -- Area: Metalworks -- NPC: Malduc -- Type: Mission Giver -- @pos 66.200 -14.999 4.426 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local CurrentMission = player:getCurrentMission(BASTOK); local Count = trade:getItemCount(); if (CurrentMission ~= 255) then if (CurrentMission == FETICHISM and player:hasCompletedMission(BASTOK,FETICHISM) == false and trade:hasItemQty(606,1) and trade:hasItemQty(607,1) and trade:hasItemQty(608,1) and trade:hasItemQty(609,1) and Count == 4) then player:startEvent(0x03F0); -- Finish Mission "Fetichism" (First Time) elseif (CurrentMission == FETICHISM and trade:hasItemQty(606,1) and trade:hasItemQty(607,1) and trade:hasItemQty(608,1) and trade:hasItemQty(609,1) and Count == 4) then player:startEvent(0x03ED); -- Finish Mission "Fetichism" (Repeat) elseif (CurrentMission == TO_THE_FORSAKEN_MINES and player:hasCompletedMission(BASTOK,TO_THE_FORSAKEN_MINES) == false and trade:hasItemQty(563,1) and Count == 1) then player:startEvent(0x03F2); -- Finish Mission "To the forsaken mines" (First Time) elseif (CurrentMission == TO_THE_FORSAKEN_MINES and trade:hasItemQty(563,1) and Count == 1) then player:startEvent(0x03EE); -- Finish Mission "To the forsaken mines" (Repeat) end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() ~= BASTOK) then player:startEvent(0x03eb); -- For non-Bastokian else local CurrentMission = player:getCurrentMission(BASTOK); local cs, p, offset = getMissionOffset(player,1,CurrentMission,player:getVar("MissionStatus")); if (cs ~= 0 or offset ~= 0 or ((CurrentMission == 0 or CurrentMission == 16) and offset == 0)) then if (CurrentMission <= 15 and cs == 0) then player:showText(npc,ORIGINAL_MISSION_OFFSET + offset); -- dialog after accepting mission (Rank 1~5) elseif (CurrentMission > 15 and cs == 0) then player:showText(npc,EXTENDED_MISSION_OFFSET + offset); -- dialog after accepting mission (Rank 6~10) else player:startEvent(cs,p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8]); end elseif (player:getRank() == 1 and player:hasCompletedMission(BASTOK,THE_ZERUHN_REPORT) == false) then player:startEvent(0x03E8); -- Start First Mission "The Zeruhn Report" elseif (CurrentMission ~= 255) then player:startEvent(0x03EA); -- Have mission already activated else local flagMission, repeatMission = getMissionMask(player); player:startEvent(0x03E9,flagMission,0,0,0,0,repeatMission); -- Mission List end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); finishMissionTimeline(player,1,csid,option); end;
gpl-3.0
Enignite/darkstar
scripts/globals/weaponskills/knights_of_round.lua
18
2076
----------------------------------- -- Knights Of Round -- Sword Weapon Skill -- Skill Level: N/A -- Caliburn/Excalibur: Additional Effect: Regen. -- Regen 10HP/Tick, duration varies with TP. -- Available only when equipped with the Relic Weapons Caliburn (Dynamis use only) or Excalibur. -- Also available without aftermath as a latent effect on Corbenic Sword. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: None -- Modifiers: STR:40% ; MND:40% -- 100%TP 200%TP 300%TP -- 3.00 3.00 3.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3; params.str_wsc = 0.4; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.4; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 5; params.ftp200 = 5; params.ftp300 = 5; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if ((player:getEquipID(SLOT_MAIN) == 18276) and (player:getMainJob() == JOB_RDM or JOB_PLD)) then if (damage > 0) then if (player:getTP() >= 100 and player:getTP() < 200) then player:addStatusEffect(EFFECT_AFTERMATH, 10, 0, 20, 0, 3); elseif (player:getTP() >= 200 and player:getTP() < 300) then player:addStatusEffect(EFFECT_AFTERMATH, 10, 0, 40, 0, 3); elseif (player:getTP() == 300) then player:addStatusEffect(EFFECT_AFTERMATH, 10, 0, 60, 0, 3); end end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
apung/prosody-modules
mod_pubsub_hub/mod_pubsub_hub.lua
32
6808
-- Copyright (C) 2011 - 2012 Kim Alvefur -- -- This file is MIT/X11 licensed. local http = require "net.http"; local formdecode = http.formdecode; local formencode = http.formencode; local http_request = http.request; local uuid = require "util.uuid".generate; local hmac_sha1 = require "util.hmac".sha1; local json_encode = require "util.json".encode; local time = os.time; local m_min, m_max = math.min, math.max; local tostring = tostring; local xmlns_pubsub = "http://jabber.org/protocol/pubsub"; local xmlns_pubsub_event = xmlns_pubsub .. "#event"; local subs_by_topic = module:shared"subscriptions"; local max_lease, min_lease, default_lease = 86400, 600, 3600; module:depends"pubsub"; local valid_modes = { ["subscribe"] = true, ["unsubscribe"] = true, } local function do_subscribe(subscription) -- FIXME handle other states if subscription.state == "subscribed" then local ok, err = hosts[module.host].modules.pubsub.service:add_subscription(subscription.topic, true, module.host); module:log(ok and "debug" or "error", "add_subscription() => %s, %s", tostring(ok), tostring(err)); end end local function handle_request(event) local request, response = event.request, event.response; local method, body = request.method, request.body; local query = request.url.query or {}; if query and type(query) == "string" then query = formdecode(query); end if body and request.headers.content_type == "application/x-www-form-urlencoded" then body = formdecode(body); end if method == "POST" then -- Subscription request if body["hub.callback"] and body["hub.mode"] and valid_modes[body["hub.mode"]] and body["hub.topic"] and body["hub.verify"] then -- http://pubsubhubbub.googlecode.com/svn/trunk/pubsubhubbub-core-0.3.html#anchor5 local callback = body["hub.callback"]; local mode = body["hub.mode"]; local topic = body["hub.topic"]; local lease_seconds = m_max(min_lease, m_min(tonumber(body["hub.lease_seconds"]) or default_lease, max_lease)); local secret = body["hub.secret"]; local verify_token = body["hub.verify_token"]; module:log("debug", "topic is "..(type(topic)=="string" and "%q" or "%s"), tostring(topic)); if not subs_by_topic[topic] then subs_by_topic[topic] = {}; end local subscription = subs_by_topic[topic][callback]; local verify_modes = {}; for i=1,#body do if body[i].name == "hub.verify" then verify_modes[body[i].value] = true; end end subscription = subscription or { id = uuid(), callback = callback, topic = topic, state = "unsubscribed", secret = secret, want_state = mode, }; subscription.lease_seconds = lease_seconds; subscription.expires = time() + lease_seconds; subs_by_topic[topic][callback] = subscription; local challenge = uuid(); local callback_url = callback .. (callback:match("%?") and "&" or "?") .. formencode{ ["hub.mode"] = mode, ["hub.topic"] = topic, ["hub.challenge"] = challenge, ["hub.lease_seconds"] = tostring(lease_seconds), ["hub.verify_token"] = verify_token, -- COMPAT draft version 0.3 } module:log("debug", "Sending async verification request to %s for %s", tostring(callback_url), tostring(subscription)); http_request(callback_url, nil, function(body, code) if body == challenge and code > 199 and code < 300 then if not subscription.want_state then module:log("warn", "Verification of already verified request, probably"); return; end subscription.state = subscription.want_state .. "d"; subscription.want_state = nil; module:log("debug", "calling do_subscribe()"); do_subscribe(subscription); subs_by_topic[topic][callback] = subscription; else module:log("warn", "status %d and body was %q", tostring(code), tostring(body)); subs_by_topic[topic][callback] = subscription; end end) return 202; else response.status = 400; response.headers.content_type = "text/html"; return "<h1>Bad Request</h1>\n<a href='http://pubsubhubbub.googlecode.com/svn/trunk/pubsubhubbub-core-0.3.html#anchor5'>Missing required parameter(s)</a>\n" end end end local function periodic(now) local next_check = now + max_lease; local purge = false; for topic, callbacks in pairs(subs_by_topic) do for callback, subscription in pairs(callbacks) do if subscription.mode == "subscribed" then if subscription.expires < now then -- Subscription has expired, drop it. purge = true; else next_check = m_min(next_check, subscription.expires); end end end if purge then local new_callbacks = {}; for callback, subscription in pairs(callbacks) do if (subscription.state == "subscribed" and subscription.expires < now) and subscription.want_state ~= "remove" then new_callbacks[callback] = subscription; end end subs_by_topic[topic] = new_callbacks; purge = false; end end return m_max((now - next_check) - min_lease, min_lease); end local xmlns_atom = "http://www.w3.org/2005/Atom"; local st = require "util.stanza"; local function on_notify(subscription, content) if content.attr and content.attr.xmlns == xmlns_atom then -- COMPAT This is required by the PubSubHubbub spec. content = st.stanza("feed", {xmlns=xmlns_atom}):add_child(content); end local body = tostring(content); local headers = { ["Content-Type"] = "application/xml", }; if subscription.secret then headers["X-Hub-Signature"] = "sha1="..hmac_sha1(subscription.secret, body, true); end http_request(subscription.callback, { method = "POST", body = body, headers = headers }, function(body, code) if code >= 200 and code <= 299 then module:log("debug", "Delivered"); else module:log("warn", "Got status code %d on delivery to %s", tonumber(code) or -1, tostring(subscription.callback)); -- TODO Retry -- ... but the spec says that you should not retry, wtf? end end); end module:hook("message/host", function(event) local stanza = event.stanza; if stanza.attr.from ~= module.host then return end; for pubsub_event in stanza:childtags("event", xmlns_pubsub_event) do local items = pubsub_event:get_child("items"); local node = items.attr.node; if items and node and subs_by_topic[node] then for item in items:childtags("item") do local content = item.tags[1]; for callback, subscription in pairs(subs_by_topic[node]) do on_notify(subscription, content) end end end end return true; end, 10); module:depends"http"; module:provides("http", { default_path = "/hub"; route = { POST = handle_request; GET = function() return json_encode(subs_by_topic); end; ["GET /topic/*"] = function(event, path) return json_encode(subs_by_topic[path]) end; }; }); module:add_timer(1, periodic);
mit
Enignite/darkstar
scripts/globals/weaponskills/shattersoul.lua
30
2341
----------------------------------- -- Skill Level: 357 -- Description: Delivers a threefold attack. Decreases target's magic defense. Duration of effect varies with TP. -- To obtain Shattersoul, the quest Martial Mastery must be completed and it must be purchased from the Merit Points menu. -- Target's magic defense is lowered by 10. -- Aligned with the Shadow Gorget, Soil Gorget & Snow Gorget. -- Aligned with the Shadow Belt, Soil Belt & Snow Belt. -- Element: N/A -- Skillchain Properties: Gravitation/Induration -- Shattersoul is only available to Warriors, Monks, White Mages, Black Mages, Paladins, Bards, Dragoons, Summoners and Scholars. -- While some jobs may obtain skill level 357 earlier than level 96, Shattersoul must be unlocked once skill reaches level 357 and job level 96 is reached. -- Staff skill level 357 is obtainable by the following jobs at these corresponding levels: -- Modifiers: INT:73~85%, depending on merit points upgrades. -- Damage Multipliers by TP: -- 100%TP 200%TP 300%TP -- 1.375 1.375 1.375 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 3; params.ftp100 = 1.375; params.ftp200 = 1.375; params.ftp300 = 1.375; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.85 + (player:getMerit(MERIT_SHATTERSOUL) / 100); params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.int_wsc = 0.7 + (player:getMerit(MERIT_SHATTERSOUL) / 100); end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if damage > 0 and (target:hasStatusEffect(EFFECT_MAGIC_DEF_DOWN) == false) then target:addStatusEffect(EFFECT_MAGIC_DEF_DOWN, 10, 0, 120); end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
GraionDilach/OpenRA
mods/d2k/maps/atreides-01b/atreides01b.lua
5
5293
--[[ Copyright 2007-2017 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] HarkonnenReinforcements = { } HarkonnenReinforcements["easy"] = { { "light_inf", "light_inf" } } HarkonnenReinforcements["normal"] = { { "light_inf", "light_inf" }, { "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike" }, } HarkonnenReinforcements["hard"] = { { "light_inf", "light_inf" }, { "trike", "trike" }, { "light_inf", "light_inf", "light_inf" }, { "light_inf", "trike" }, { "trike", "trike" } } HarkonnenEntryWaypoints = { HarkonnenWaypoint1.Location, HarkonnenWaypoint2.Location, HarkonnenWaypoint3.Location, HarkonnenWaypoint4.Location } HarkonnenAttackDelay = DateTime.Seconds(30) HarkonnenAttackWaves = { } HarkonnenAttackWaves["easy"] = 1 HarkonnenAttackWaves["normal"] = 5 HarkonnenAttackWaves["hard"] = 12 ToHarvest = { } ToHarvest["easy"] = 2500 ToHarvest["normal"] = 3000 ToHarvest["hard"] = 3500 AtreidesReinforcements = { "light_inf", "light_inf", "light_inf", "light_inf" } AtreidesEntryPath = { AtreidesWaypoint.Location, AtreidesRally.Location } Messages = { "Build a concrete foundation before placing your buildings.", "Build a Wind Trap for power.", "Build a Refinery to collect Spice.", "Build a Silo to store additional Spice." } IdleHunt = function(actor) if not actor.IsDead then Trigger.OnIdle(actor, actor.Hunt) end end Tick = function() if HarkonnenArrived and harkonnen.HasNoRequiredUnits() then player.MarkCompletedObjective(KillHarkonnen) end if player.Resources > ToHarvest[Map.LobbyOption("difficulty")] - 1 then player.MarkCompletedObjective(GatherSpice) end -- player has no Wind Trap if (player.PowerProvided <= 20 or player.PowerState ~= "Normal") and DateTime.GameTime % DateTime.Seconds(32) == 0 then HasPower = false Media.DisplayMessage(Messages[2], "Mentat") else HasPower = true end -- player has no Refinery and no Silos if HasPower and player.ResourceCapacity == 0 and DateTime.GameTime % DateTime.Seconds(32) == 0 then Media.DisplayMessage(Messages[3], "Mentat") end if HasPower and player.Resources > player.ResourceCapacity * 0.8 and DateTime.GameTime % DateTime.Seconds(32) == 0 then Media.DisplayMessage(Messages[4], "Mentat") end UserInterface.SetMissionText("Harvested resources: " .. player.Resources .. "/" .. ToHarvest[Map.LobbyOption("difficulty")], player.Color) end WorldLoaded = function() player = Player.GetPlayer("Atreides") harkonnen = Player.GetPlayer("Harkonnen") InitObjectives() Trigger.OnRemovedFromWorld(AtreidesConyard, function() local refs = Utils.Where(Map.ActorsInWorld, function(actor) return actor.Type == "refinery" end) if #refs == 0 then harkonnen.MarkCompletedObjective(KillAtreides) else Trigger.OnAllRemovedFromWorld(refs, function() harkonnen.MarkCompletedObjective(KillAtreides) end) end end) Media.DisplayMessage(Messages[1], "Mentat") Trigger.AfterDelay(DateTime.Seconds(25), function() Media.PlaySpeechNotification(player, "Reinforce") Reinforcements.Reinforce(player, AtreidesReinforcements, AtreidesEntryPath) end) WavesLeft = HarkonnenAttackWaves[Map.LobbyOption("difficulty")] SendReinforcements() end SendReinforcements = function() local units = HarkonnenReinforcements[Map.LobbyOption("difficulty")] local delay = Utils.RandomInteger(HarkonnenAttackDelay - DateTime.Seconds(2), HarkonnenAttackDelay) HarkonnenAttackDelay = HarkonnenAttackDelay - (#units * 3 - 3 - WavesLeft) * DateTime.Seconds(1) if HarkonnenAttackDelay < 0 then HarkonnenAttackDelay = 0 end Trigger.AfterDelay(delay, function() Reinforcements.Reinforce(harkonnen, Utils.Random(units), { Utils.Random(HarkonnenEntryWaypoints) }, 10, IdleHunt) WavesLeft = WavesLeft - 1 if WavesLeft == 0 then Trigger.AfterDelay(DateTime.Seconds(1), function() HarkonnenArrived = true end) else SendReinforcements() end end) end InitObjectives = function() Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) KillAtreides = harkonnen.AddPrimaryObjective("Kill all Atreides units.") GatherSpice = player.AddPrimaryObjective("Harvest " .. tostring(ToHarvest[Map.LobbyOption("difficulty")]) .. " Solaris worth of Spice.") KillHarkonnen = player.AddSecondaryObjective("Eliminate all Harkonnen units and reinforcements\nin the area.") Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerLost(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "Lose") end) end) Trigger.OnPlayerWon(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "Win") end) end) end
gpl-3.0
Enignite/darkstar
scripts/zones/Southern_San_dOria/npcs/Pourette.lua
30
2210
----------------------------------- -- Area: Southern San d'Oria -- NPC: Pourette -- Only sells when San d'Oria controlls Derfland Region ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/events/harvest_festivals"); require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/globals/conquest"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == 1) then if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then player:messageSpecial(FLYER_REFUSED); end else onHalloweenTrade(player,trade,npc); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(DERFLAND); if (RegionOwner ~= SANDORIA) then player:showText(npc,POURETTE_CLOSED_DIALOG); else player:showText(npc,POURETTE_OPEN_DIALOG); stock = {0x1100,128, --Derfland Pear 0x0269,142, --Ginger 0x11c1,62, --Gysahl Greens 0x0584,1656, --Olive Flower 0x0279,14, --Olive Oil 0x03b7,110} --Wijnruit showShop(player,SANDORIA,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Enignite/darkstar
scripts/zones/Bastok_Markets/npcs/Cleades.lua
17
3519
----------------------------------- -- Area: Bastok Markets -- NPC: Cleades -- Type: Mission Giver -- @pos -358 -10 -168 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local CurrentMission = player:getCurrentMission(BASTOK); local Count = trade:getItemCount(); if (CurrentMission ~= 255) then if (CurrentMission == FETICHISM and player:hasCompletedMission(BASTOK,FETICHISM) == false and trade:hasItemQty(606,1) and trade:hasItemQty(607,1) and trade:hasItemQty(608,1) and trade:hasItemQty(609,1) and Count == 4) then player:startEvent(0x03F0); -- Finish Mission "Fetichism" (First Time) elseif (CurrentMission == FETICHISM and trade:hasItemQty(606,1) and trade:hasItemQty(607,1) and trade:hasItemQty(608,1) and trade:hasItemQty(609,1) and Count == 4) then player:startEvent(0x03ED); -- Finish Mission "Fetichism" (Repeat) elseif (CurrentMission == TO_THE_FORSAKEN_MINES and player:hasCompletedMission(BASTOK,TO_THE_FORSAKEN_MINES) == false and trade:hasItemQty(563,1) and Count == 1) then player:startEvent(0x03F2); -- Finish Mission "To the forsaken mines" (First Time) elseif (CurrentMission == TO_THE_FORSAKEN_MINES and trade:hasItemQty(563,1) and Count == 1) then player:startEvent(0x03EE); -- Finish Mission "To the forsaken mines" (Repeat) end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() ~= BASTOK) then player:startEvent(0x03eb); -- For non-Bastokian else local CurrentMission = player:getCurrentMission(BASTOK); local cs, p, offset = getMissionOffset(player,1,CurrentMission,player:getVar("MissionStatus")); if (cs ~= 0 or offset ~= 0 or ((CurrentMission == 0 or CurrentMission == 16) and offset == 0)) then if (CurrentMission <= 15 and cs == 0) then player:showText(npc,ORIGINAL_MISSION_OFFSET + offset); -- dialog after accepting mission (Rank 1~5) elseif (CurrentMission > 15 and cs == 0) then player:showText(npc,EXTENDED_MISSION_OFFSET + offset); -- dialog after accepting mission (Rank 6~10) else player:startEvent(cs,p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8]); end elseif (player:getRank() == 1 and player:hasCompletedMission(BASTOK,THE_ZERUHN_REPORT) == false) then player:startEvent(0x03E8); -- Start First Mission "The Zeruhn Report" elseif (CurrentMission ~= 255) then player:startEvent(0x03EA); -- Have mission already activated else local flagMission, repeatMission = getMissionMask(player); player:startEvent(0x03E9,flagMission,0,0,0,0,repeatMission); -- Mission List end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); finishMissionTimeline(player,1,csid,option); end;
gpl-3.0
Enignite/darkstar
scripts/zones/Phomiuna_Aqueducts/npcs/_0rw.lua
17
1304
----------------------------------- -- Area: Phomiuna_Aqueducts -- NPC: _0rw (Oil Lamp) -- Notes: Opens south door at J-9 from inside. -- @pos 103.703 -26.180 83.000 27 ----------------------------------- package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Phomiuna_Aqueducts/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorOffset = npc:getID() - 1; if (GetNPCByID(DoorOffset):getAnimation() == 9) then if (player:getZPos() < 85) then npc:openDoor(7); -- torch animation GetNPCByID(DoorOffset):openDoor(7); -- _0rh end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
araeisy/araeisy
plugins/azan.lua
2
3102
do function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') return result end local api_key = nil local base_api = "https://maps.googleapis.com/maps/api" function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end function get_staticmap(area) local api = base_api .. "/staticmap?" local lat,lng,acc,types = get_latlong(area) local scale = types[1] if scale=="locality" then zoom=8 elseif scale=="country" then zoom=4 else zoom = 13 end local parameters = "size=600x300" .. "&zoom=" .. zoom .. "&center=" .. URL.escape(area) .. "&markers=color:red"..URL.escape("|"..area) if api_key ~=nil and api_key ~= "" then parameters = parameters .. "&key="..api_key end return lat, lng, api..parameters end function run(msg, matches) local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) local receiver = get_receiver(msg) local city = matches[1] if matches[1] == 'azan' then city = 'Tehran' end local lat,lng,url = get_staticmap(city) local dumptime = run_bash('date +%s') local code = http.request('http://api.aladhan.com/timings/'..dumptime..'?latitude='..lat..'&longitude='..lng..'&timezonestring=Asia/Tehran&method=7') local jdat = json:decode(code) local data = jdat.data.timings local text = 'شهر: '..city text = text..'\nاذان صبح: '..data.Fajr text = text..'\nطلوع آفتاب: '..data.Sunrise text = text..'\nاذان ظهر: '..data.Dhuhr text = text..'\nغروب آفتاب: '..data.Sunset text = text..'\nاذان مغرب: '..data.Maghrib text = text..'\nعشاء : '..data.Isha text = text..'\n\n@WaderTGTeam' if string.match(text, '0') then text = string.gsub(text, '0', '۰') end if string.match(text, '1') then text = string.gsub(text, '1', '۱') end if string.match(text, '2') then text = string.gsub(text, '2', '۲') end if string.match(text, '3') then text = string.gsub(text, '3', '۳') end if string.match(text, '4') then text = string.gsub(text, '4', '۴') end if string.match(text, '5') then text = string.gsub(text, '5', '۵') end if string.match(text, '6') then text = string.gsub(text, '6', '۶') end if string.match(text, '7') then text = string.gsub(text, '7', '۷') end if string.match(text, '8') then text = string.gsub(text, '8', '۸') end if string.match(text, '9') then text = string.gsub(text, '9', '۹') end return text end return { patterns = {"^[#/!][Aa]zan (.*)$","^[#/!](azan)$"}, run = run } end
mit
Enignite/darkstar
scripts/zones/Spire_of_Dem/npcs/_0j1.lua
51
1321
----------------------------------- -- Area: Spire_of_Dem -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Dem/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Dem/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
Enignite/darkstar
scripts/zones/Sacrarium/npcs/qm4.lua
17
1738
----------------------------------- -- Area: Sacrarium -- NPC: qm4 (???) -- Notes: Used to spawn Old Prof. Mariselle -- @pos 22.669 -3.111 127.279 28 ----------------------------------- package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Sacrarium/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local OldProfessor = 16891970; if (GetServerVariable("Old_Prof_Spawn_Location") == 4) then if (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 3 and player:hasKeyItem(RELIQUIARIUM_KEY)==false and GetMobAction(OldProfessor) == 0) then player:messageSpecial(EVIL_PRESENCE); SpawnMob(OldProfessor,300):updateClaim(player); GetMobByID(OldProfessor):setPos(npc:getXPos()+1, npc:getYPos(), npc:getZPos()+1); -- Set Prof. spawn x and z pos. +1 from NPC else player:messageSpecial(DRAWER_SHUT); end elseif (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 4 and player:hasKeyItem(RELIQUIARIUM_KEY)==false) then player:addKeyItem(RELIQUIARIUM_KEY); player:messageSpecial(KEYITEM_OBTAINED,RELIQUIARIUM_KEY); else player:messageSpecial(DRAWER_OPEN); player:messageSpecial(DRAWER_EMPTY); end end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) end;
gpl-3.0
fcpxhacks/fcpxhacks
src/extensions/cp/result.lua
2
6270
--- === cp.result === --- --- Represents the result of an operation which may end in `success` or `failure`. --- If it is a `success`, a `value` is typically provided. --- If it is a `failure`, a `message` is typically provided. --- --- Using this type allows for more structured checking when performing an operation which may fail in a number --- of ways, rather than just calling `error` and crashing out. For example: --- --- ```lua --- function clamped(value, min, max) --- if value < min then --- return result.failure("expected at least %d but got %d", min, value) --- elseif value > max then --- return result.failure("expected at most %d but got %d", max, value") --- else --- return result.success(value) --- end --- end --- --- local outcome = clamped(-1, 0, 100) --- if outcome.failure then --- error(outcome.message) --- end --- local value = outcome.value --- ``` --- --- Of course, simply checking the result and throwing an `error` is a common case, so you can achieve the same result like so: --- --- ```lua --- local value = clamped(-1, 0, 100):get() --- ``` --- --- If you want to perform other tasks, check for `.failure` or `.success` and perform the appropriate response. local log = require "hs.logger" .new "result" local inspect = require "hs.inspect" local format = string.format local mod = {} mod.mt = {} mod.mt.__index = mod.mt --- cp.result.is(value) -> boolean --- Function --- Checks if the `value` is an instance of a `cp.result`. --- --- Parameters: --- * `value` - The value to check. --- --- Returns: --- * `true` if the value is an instance of `cp.result`. function mod.is(value) if value and type(value) == "table" then local mt = getmetatable(value) return mt == mod.mt end return false end --- cp.result.success(value) -> result --- Constructor --- Creates a new `success` result, with the specified `value`. --- --- Parameters: --- * value - The specified value --- --- Returns: --- * A new result function mod.success(value) return setmetatable({success = true, value = value}, mod.mt) end --- cp.result.failure(message) -> result --- Constructor --- Creates a new `failure` result, with the specified error `message`. --- --- Parameters: --- * message - Error message --- --- Returns: --- * A new result function mod.failure(message, ...) if message and select("#", ...) > 0 then message = format(message, ...) end return setmetatable({failure = true, message = message}, mod.mt) end --- cp.result.from(value, err) -> result --- Constructor --- Provides a simple wrapper for the common `value, err` pattern of function error handling in Lua. --- If the `err` value is not `nil`, it will result in a `failure`, otherwise the `value` is passed to a `success`. --- --- Parameters: --- * value - The value if successful. --- * err - The error message if there was a failure. --- --- Returns: --- * A `result.success` or `result.failure`. function mod.from(value, err) if err then return mod.failure(err) else return mod.success(value) end end --- cp.result.valueErr(value, err) -> result --- Constructor --- Provides a simple wrapper for the common `value, err` pattern of function error handling in Lua. --- If the `err` is not `nil` it will result in a `failure` with the message, otherwise the `value` is passed to a `success`. --- --- Parameters: --- * value - The value if successful. --- * err - The error message if there was a failure. --- --- Returns: --- * A `result.success` or `result.failure`. function mod.valueErr(value, err) if err ~= nil then return mod.failure(err) else return mod.success(value) end end --- cp.result.okValue(ok, value) -> result --- Constructor --- Provides a simple wrapper for the common `ok, value|err` pattern of function error handling in Lua. --- If `ok` is true, `value` is the successful result, otherwise `value` is the error message. --- --- Parameters: --- * ok - if `true`, the operation was successful. --- * value - `ok` is true, the successful value, otherwise the error message. --- --- Returns: --- * A `result.success` or `result.failure`. function mod.okValue(ok, value) if ok then return mod.success(value) else return mod.failure(value) end end --- cp.result:get() -> anything --- Method --- Gets the successful value, or throws an `error` with the provided `message`. --- --- Parameters: --- * None --- --- Returns: --- * The `value` if it was a `success`, otherwise throws an `error`. function mod.mt:get() if self.failure then error(self.message, 2) else return self.value end end local function _tostring(value) local valueType = type(value) if value == nil then value = "nil" elseif valueType == "table" or valueType=="userdata" then if value.__tostring then value = tostring(value) else value = inspect(value) end else value = tostring(value) end return value end --- cp.result:log([context]) -> cp.result --- Method --- Logs the result to either the default channel (if `success`) or error channel (if `failure`), --- with the `context` string (if provided). --- --- Parameters: --- * context - A `string` that provides context for the logged value. --- --- Returns: --- * The same `cp.result` instance. function mod.mt:log(context) local detail = context..":" or "" if self.success then detail = detail .. _tostring(self.value) log.f("SUCCESS: %s", detail) else log.ef("FAILURE: %s", _tostring(self.message)) end return self end -- converts the result to a human-readable string. function mod.mt:__tostring() if self.success then return format("success: %s", _tostring(self.value)) else return self.message == nil and "error" or format("error: %s", _tostring(self.message)) end end -- compares two result values. function mod.mt.__eq(a,b) if a.success then return b.success and a.value == b.value elseif a.failure then return b.failure and a.message == b.message else return false end end return mod
mit
joaofvieira/luci
applications/luci-app-privoxy/luasrc/controller/privoxy.lua
33
4608
-- Copyright 2014 Christian Schoenebeck <christian dot schoenebeck at gmail dot com> -- Licensed under the Apache License, Version 2.0 module("luci.controller.privoxy", package.seeall) local NX = require "nixio" local NXFS = require "nixio.fs" local HTTP = require "luci.http" local UCI = require "luci.model.uci" local UTIL = require "luci.util" local SYS = require "luci.sys" PRIVOXY_MIN = "3.0.22-0" -- minimum version of service required function index() entry( {"admin", "services", "privoxy"}, cbi("privoxy"), _("Privoxy WEB proxy"), 59) entry( {"admin", "services", "privoxy", "logview"}, call("logread") ).leaf = true entry( {"admin", "services", "privoxy", "startstop"}, call("startstop") ).leaf = true entry( {"admin", "services", "privoxy", "status"}, call("get_pid") ).leaf = true end -- called by XHR.get from detail_logview.htm function logread() -- read application settings local uci = UCI.cursor() local logdir = uci:get("privoxy", "privoxy", "logdir") or "/var/log" local logfile = uci:get("privoxy", "privoxy", "logfile") or "privoxy.log" uci:unload("privoxy") local lfile=logdir .. "/" .. logfile local ldata=NXFS.readfile(lfile) if not ldata or #ldata == 0 then ldata="_nodata_" end HTTP.write(ldata) end -- called by XHR.get from detail_startstop.htm function startstop() local pid = get_pid(true) if pid > 0 then SYS.call("/etc/init.d/privoxy stop") NX.nanosleep(1) -- sleep a second if NX.kill(pid, 0) then -- still running NX.kill(pid, 9) -- send SIGKILL end pid = 0 else SYS.call("/etc/init.d/privoxy start") NX.nanosleep(1) -- sleep a second pid = tonumber(NXFS.readfile("/var/run/privoxy.pid") or 0 ) if pid > 0 and not NX.kill(pid, 0) then pid = 0 -- process did not start end end HTTP.write(tostring(pid)) -- HTTP needs string not number end -- called by XHR.poll from detail_startstop.htm -- and from lua (with parameter "true") function get_pid(from_lua) local pid = tonumber(NXFS.readfile("/var/run/privoxy.pid") or 0 ) if pid > 0 and not NX.kill(pid, 0) then pid = 0 end if from_lua then return pid else HTTP.write(tostring(pid)) -- HTTP needs string not number end end -- compare versions using "<=" "<" ">" ">=" "=" "<<" ">>" function ipkg_ver_compare(ver1, comp, ver2) if not ver1 or not ver2 or not comp or not (#comp > 0) then return nil end -- correct compare string if comp == "<>" or comp == "><" or comp == "!=" or comp == "~=" then comp = "~=" elseif comp == "<=" or comp == "<" or comp == "=<" then comp = "<=" elseif comp == ">=" or comp == ">" or comp == "=>" then comp = ">=" elseif comp == "=" or comp == "==" then comp = "==" elseif comp == "<<" then comp = "<" elseif comp == ">>" then comp = ">" else return nil end local av1 = UTIL.split(ver1, "[%.%-]", nil, true) local av2 = UTIL.split(ver2, "[%.%-]", nil, true) for i = 1, math.max(table.getn(av1),table.getn(av2)), 1 do local s1 = av1[i] or "" local s2 = av2[i] or "" -- first "not equal" found return true if comp == "~=" and (s1 ~= s2) then return true end -- first "lower" found return true if (comp == "<" or comp == "<=") and (s1 < s2) then return true end -- first "greater" found return true if (comp == ">" or comp == ">=") and (s1 > s2) then return true end -- not equal then return false if (s1 ~= s2) then return false end end -- all equal and not compare greater or lower then true return not (comp == "<" or comp == ">") end -- read version information for given package if installed function ipkg_ver_installed(pkg) local version = nil local control = io.open("/usr/lib/opkg/info/%s.control" % pkg, "r") if control then local ln repeat ln = control:read("*l") if ln and ln:match("^Version: ") then version = ln:gsub("^Version: ", "") break end until not ln control:close() end return version end -- replacement of build-in Flag.parse of cbi.lua -- modified to mark section as changed if value changes -- current parse did not do this, but it is done AbstaractValue.parse() function flag_parse(self, section) local fexists = self.map:formvalue( luci.cbi.FEXIST_PREFIX .. self.config .. "." .. section .. "." .. self.option) if fexists then local fvalue = self:formvalue(section) and self.enabled or self.disabled local cvalue = self:cfgvalue(section) if fvalue ~= self.default or (not self.optional and not self.rmempty) then self:write(section, fvalue) else self:remove(section) end if (fvalue ~= cvalue) then self.section.changed = true end else self:remove(section) self.section.changed = true end end
apache-2.0
yetsky/luci
modules/admin-mini/luasrc/model/cbi/mini/network.lua
82
6273
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local wa = require "luci.tools.webadmin" local sys = require "luci.sys" local fs = require "nixio.fs" local has_pptp = fs.access("/usr/sbin/pptp") local has_pppoe = fs.glob("/usr/lib/pppd/*/rp-pppoe.so")() local network = luci.model.uci.cursor_state():get_all("network") local netstat = sys.net.deviceinfo() local ifaces = {} for k, v in pairs(network) do if v[".type"] == "interface" and k ~= "loopback" then table.insert(ifaces, v) end end m = Map("network", translate("Network")) s = m:section(Table, ifaces, translate("Status")) s.parse = function() end s:option(DummyValue, ".name", translate("Network")) hwaddr = s:option(DummyValue, "_hwaddr", translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"), translate("Hardware Address")) function hwaddr.cfgvalue(self, section) local ix = self.map:get(section, "ifname") or "" local mac = fs.readfile("/sys/class/net/" .. ix .. "/address") if not mac then mac = luci.util.exec("ifconfig " .. ix) mac = mac and mac:match(" ([A-F0-9:]+)%s*\n") end if mac and #mac > 0 then return mac:upper() end return "?" end s:option(DummyValue, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address")) s:option(DummyValue, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")) txrx = s:option(DummyValue, "_txrx", translate("Traffic"), translate("transmitted / received")) function txrx.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][1] rx = rx and wa.byte_format(tonumber(rx)) or "-" local tx = netstat and netstat[ix] and netstat[ix][9] tx = tx and wa.byte_format(tonumber(tx)) or "-" return string.format("%s / %s", tx, rx) end errors = s:option(DummyValue, "_err", translate("Errors"), translate("TX / RX")) function errors.cfgvalue(self, section) local ix = self.map:get(section, "ifname") local rx = netstat and netstat[ix] and netstat[ix][3] local tx = netstat and netstat[ix] and netstat[ix][11] rx = rx and tostring(rx) or "-" tx = tx and tostring(tx) or "-" return string.format("%s / %s", tx, rx) end s = m:section(NamedSection, "lan", "interface", translate("Local Network")) s.addremove = false s:option(Value, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address")) nm = s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")) nm:value("255.255.255.0") nm:value("255.255.0.0") nm:value("255.0.0.0") gw = s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway") .. translate(" (optional)")) gw.rmempty = true dns = s:option(Value, "dns", translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server") .. translate(" (optional)")) dns.rmempty = true s = m:section(NamedSection, "wan", "interface", translate("Internet Connection")) s.addremove = false p = s:option(ListValue, "proto", translate("Protocol")) p.override_values = true p:value("none", "disabled") p:value("static", translate("manual")) p:value("dhcp", translate("automatic")) if has_pppoe then p:value("pppoe", "PPPoE") end if has_pptp then p:value("pptp", "PPTP") end function p.write(self, section, value) -- Always set defaultroute to PPP and use remote dns -- Overwrite a bad variable behaviour in OpenWrt if value == "pptp" or value == "pppoe" then self.map:set(section, "peerdns", "1") self.map:set(section, "defaultroute", "1") end return ListValue.write(self, section, value) end if not ( has_pppoe and has_pptp ) then p.description = translate("You need to install \"ppp-mod-pppoe\" for PPPoE or \"pptp\" for PPtP support") end ip = s:option(Value, "ipaddr", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address")) ip:depends("proto", "static") nm = s:option(Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask")) nm:depends("proto", "static") gw = s:option(Value, "gateway", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Gateway")) gw:depends("proto", "static") gw.rmempty = true dns = s:option(Value, "dns", translate("<abbr title=\"Domain Name System\">DNS</abbr>-Server")) dns:depends("proto", "static") dns.rmempty = true usr = s:option(Value, "username", translate("Username")) usr:depends("proto", "pppoe") usr:depends("proto", "pptp") pwd = s:option(Value, "password", translate("Password")) pwd.password = true pwd:depends("proto", "pppoe") pwd:depends("proto", "pptp") -- Allow user to set MSS correction here if the UCI firewall is installed -- This cures some cancer for providers with pre-war routers if fs.access("/etc/config/firewall") then mssfix = s:option(Flag, "_mssfix", translate("Clamp Segment Size"), translate("Fixes problems with unreachable websites, submitting forms or other unexpected behaviour for some ISPs.")) mssfix.rmempty = false function mssfix.cfgvalue(self) local value m.uci:foreach("firewall", "forwarding", function(s) if s.src == "lan" and s.dest == "wan" then value = s.mtu_fix end end) return value end function mssfix.write(self, section, value) m.uci:foreach("firewall", "forwarding", function(s) if s.src == "lan" and s.dest == "wan" then m.uci:set("firewall", s[".name"], "mtu_fix", value) m:chain("firewall") end end) end end kea = s:option(Flag, "keepalive", translate("automatically reconnect")) kea:depends("proto", "pppoe") kea:depends("proto", "pptp") kea.rmempty = true kea.enabled = "10" cod = s:option(Value, "demand", translate("disconnect when idle for"), "s") cod:depends("proto", "pppoe") cod:depends("proto", "pptp") cod.rmempty = true srv = s:option(Value, "server", translate("<abbr title=\"Point-to-Point Tunneling Protocol\">PPTP</abbr>-Server")) srv:depends("proto", "pptp") srv.rmempty = true return m
apache-2.0
mjarco/sysdig
userspace/sysdig/chisels/topscalls_time.lua
12
1702
--[[ Copyright (C) 2013-2014 Draios inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] -- The number of items to show TOP_NUMBER = 30 -- Chisel description description = "Show the top " .. TOP_NUMBER .. " system calls in terms of time spent in each call. You can use filters to restrict this to a specific process, thread or file. This chisel is compatable with containers using the sysdig -pc or -pcontainer argument, otherwise no container information will be shown." short_description = "Top system calls by time" category = "Performance" -- Chisel argument list args = {} -- Argument notification callback function on_set_arg(name, val) return false end -- Initialization callback function on_init() -- The -pc or -pcontainer options was supplied on the cmd line print_container = sysdig.is_print_container_data() if print_container then chisel.exec("table_generator", "evt.type,container.name", "Syscall,container.name", "evt.latency", "Time", "", "" .. TOP_NUMBER, "time") else chisel.exec("table_generator", "evt.type", "Syscall", "evt.latency", "Time", "", "" .. TOP_NUMBER, "time") end return true end
gpl-2.0
ZerothAngel/FtDScripts
main/dediblademaintainer.lua
1
1120
--! dediblademaintainer --@ periodic drivemaintainer spinnercontrol ThrottleController = DriveMaintainer.new(ThrottleDriveMaintainerFacing) PropulsionSpinners = SpinnerControl.new(Vector3.forward) DesiredThrottle = 0 function DediBladeMaintainer_Control(I) local Throttle = ThrottleWhen[I:GetAIMovementMode()] if Throttle then DesiredThrottle = Throttle else DesiredThrottle = ThrottleController:GetThrottle(I) end end function DediBladeMaintainer_Update(I) -- Note: Standard propulsion can link up to the drive maintainer normally PropulsionSpinners:Classify(I) PropulsionSpinners:SetSpeed(I, DesiredThrottle * 30) end function DediBladeMaintainer_Disable(I) PropulsionSpinners:Classify(I) PropulsionSpinners:SetSpeed(I, 0) end DediBladeMaintainer = Periodic.new(UpdateRate, DediBladeMaintainer_Control) function Update(I) -- luacheck: ignore 131 if ActivateWhen[I:GetAIMovementMode()] then if not I:IsDocked() then DediBladeMaintainer:Tick(I) DediBladeMaintainer_Update(I) else DediBladeMaintainer_Disable(I) end end end
mit
philsiff/Red-Vs-Blue
Red Vs. Blue Files/gamemodes/base/gamemode/cl_init.lua
1
19408
include( 'shared.lua' ) include( 'cl_scoreboard.lua' ) include( 'cl_targetid.lua' ) include( 'cl_hudpickup.lua' ) include( 'cl_spawnmenu.lua' ) include( 'cl_deathnotice.lua' ) include( 'cl_pickteam.lua' ) include( 'cl_voice.lua' ) --[[--------------------------------------------------------- Name: gamemode:Initialize( ) Desc: Called immediately after starting the gamemode -----------------------------------------------------------]] function GM:Initialize( ) GAMEMODE.ShowScoreboard = false end --[[--------------------------------------------------------- Name: gamemode:InitPostEntity( ) Desc: Called as soon as all map entities have been spawned -----------------------------------------------------------]] function GM:InitPostEntity( ) end --[[--------------------------------------------------------- Name: gamemode:Think( ) Desc: Called every frame -----------------------------------------------------------]] function GM:Think( ) end --[[--------------------------------------------------------- Name: gamemode:PlayerDeath( ) Desc: Called when a player dies. If the attacker was a player then attacker will become a Player instead of an Entity. -----------------------------------------------------------]] function GM:PlayerDeath( ply, attacker ) end --[[--------------------------------------------------------- Name: gamemode:PlayerBindPress( ) Desc: A player pressed a bound key - return true to override action -----------------------------------------------------------]] function GM:PlayerBindPress( pl, bind, down ) return false end --[[--------------------------------------------------------- Name: gamemode:HUDShouldDraw( name ) Desc: return true if we should draw the named element -----------------------------------------------------------]] function GM:HUDShouldDraw( name ) -- Allow the weapon to override this local ply = LocalPlayer() if ( IsValid( ply ) ) then local wep = ply:GetActiveWeapon() if (wep && wep:IsValid() && wep.HUDShouldDraw != nil) then return wep.HUDShouldDraw( wep, name ) end end return true; end --[[--------------------------------------------------------- Name: gamemode:HUDPaint( ) Desc: Use this section to paint your HUD -----------------------------------------------------------]] function GM:HUDPaint() hook.Run( "HUDDrawTargetID" ) hook.Run( "HUDDrawPickupHistory" ) hook.Run( "DrawDeathNotice", 0.85, 0.04 ) end --[[--------------------------------------------------------- Name: gamemode:HUDPaintBackground( ) Desc: Same as HUDPaint except drawn before -----------------------------------------------------------]] function GM:HUDPaintBackground() end --[[--------------------------------------------------------- Name: gamemode:GUIMouseReleased( mousecode ) Desc: The mouse was double clicked -----------------------------------------------------------]] function GM:GUIMouseDoublePressed( mousecode, AimVector ) -- We don't capture double clicks by default, -- We just treat them as regular presses GAMEMODE:GUIMousePressed( mousecode, AimVector ) end --[[--------------------------------------------------------- Name: gamemode:ShutDown( ) Desc: Called when the Lua system is about to shut down -----------------------------------------------------------]] function GM:ShutDown( ) end --[[--------------------------------------------------------- Name: gamemode:RenderScreenspaceEffects( ) Desc: Bloom etc should be drawn here (or using this hook) -----------------------------------------------------------]] function GM:RenderScreenspaceEffects() end --[[--------------------------------------------------------- Name: gamemode:GetTeamColor( ent ) Desc: Return the color for this ent's team This is for chat and deathnotice text -----------------------------------------------------------]] function GM:GetTeamColor( ent ) local team = TEAM_UNASSIGNED if (ent.Team) then team = ent:Team() end return GAMEMODE:GetTeamNumColor( team ) end --[[--------------------------------------------------------- Name: gamemode:GetTeamNumColor( num ) Desc: returns the colour for this team num -----------------------------------------------------------]] function GM:GetTeamNumColor( num ) return team.GetColor( num ) end --[[--------------------------------------------------------- Name: gamemode:OnChatTab( str ) Desc: Tab is pressed when typing (Auto-complete names, IRC style) -----------------------------------------------------------]] function GM:OnChatTab( str ) local LastWord for word in string.gmatch( str, "%a+" ) do LastWord = word; end if (LastWord == nil) then return str end playerlist = player.GetAll() for k, v in pairs( playerlist ) do local nickname = v:Nick() if ( string.len(LastWord) < string.len(nickname) && string.find( string.lower(nickname), string.lower(LastWord) ) == 1 ) then str = string.sub( str, 1, (string.len(LastWord) * -1) - 1) str = str .. nickname return str end end return str; end --[[--------------------------------------------------------- Name: gamemode:StartChat( teamsay ) Desc: Start Chat. If you want to display your chat shit different here's what you'd do: In StartChat show your text box and return true to hide the default Update the text in your box with the text passed to ChatTextChanged Close and clear your text box when FinishChat is called. Return true in ChatText to not show the default chat text -----------------------------------------------------------]] function GM:StartChat( teamsay ) return false end --[[--------------------------------------------------------- Name: gamemode:FinishChat() -----------------------------------------------------------]] function GM:FinishChat() end --[[--------------------------------------------------------- Name: gamemode:ChatTextChanged( text) -----------------------------------------------------------]] function GM:ChatTextChanged( text ) end --[[--------------------------------------------------------- Name: ChatText Allows override of the chat text -----------------------------------------------------------]] function GM:ChatText( playerindex, playername, text, filter ) if ( filter == "chat" ) then Msg( playername, ": ", text, "\n" ) else Msg( text, "\n" ) end return false end --[[--------------------------------------------------------- Name: gamemode:PostProcessPermitted( str ) Desc: return true/false depending on whether this post process should be allowed -----------------------------------------------------------]] function GM:PostProcessPermitted( str ) return true end --[[--------------------------------------------------------- Name: gamemode:PostRenderVGUI( ) Desc: Called after VGUI has been rendered -----------------------------------------------------------]] function GM:PostRenderVGUI() end --[[--------------------------------------------------------- Name: gamemode:PreRender( ) Desc: Called before all rendering Return true to NOT render this frame for some reason (danger!) -----------------------------------------------------------]] function GM:PreRender() return false; end --[[--------------------------------------------------------- Name: gamemode:PostRender( ) Desc: Called after all rendering -----------------------------------------------------------]] function GM:PostRender() end --[[--------------------------------------------------------- Name: gamemode:GetVehicles( ) Desc: Gets the vehicles table.. -----------------------------------------------------------]] function GM:GetVehicles() return vehicles.GetTable() end --[[--------------------------------------------------------- Name: gamemode:RenderScene( ) Desc: Render the scene -----------------------------------------------------------]] function GM:RenderScene( origin, angle, fov ) end --[[--------------------------------------------------------- Name: CalcVehicleThirdPersonView -----------------------------------------------------------]] function GM:CalcVehicleView( Vehicle, ply, view ) if ( Vehicle.GetThirdPersonMode == nil ) then -- This hsouldn't ever happen. return end -- -- If we're not in third person mode - then get outa here stalker -- if ( !Vehicle:GetThirdPersonMode() ) then return view end -- Don't roll the camera -- view.angles.roll = 0 local mn, mx = Vehicle:GetRenderBounds() local radius = (mn - mx):Length() local radius = radius + radius * Vehicle:GetCameraDistance(); -- Trace back from the original eye position, so we don't clip through walls/objects local TargetOrigin = view.origin + ( view.angles:Forward() * -radius ) local WallOffset = 4; local tr = util.TraceHull( { start = view.origin, endpos = TargetOrigin, filter = Vehicle, mins = Vector( -WallOffset, -WallOffset, -WallOffset ), maxs = Vector( WallOffset, WallOffset, WallOffset ), }) view.origin = tr.HitPos view.drawviewer = true -- -- If the trace hit something, put the camera there. -- if ( tr.Hit && !tr.StartSolid) then view.origin = view.origin + tr.HitNormal * WallOffset end return view end --[[--------------------------------------------------------- Name: CalcView Allows override of the default view -----------------------------------------------------------]] function GM:CalcView( ply, origin, angles, fov, znear, zfar ) local Vehicle = ply:GetVehicle() local Weapon = ply:GetActiveWeapon() local view = {} view.origin = origin view.angles = angles view.fov = fov view.znear = znear view.zfar = zfar view.drawviewer = false -- -- Let the vehicle override the view -- if ( IsValid( Vehicle ) ) then return GAMEMODE:CalcVehicleView( Vehicle, ply, view ) end -- -- Let drive possibly alter the view -- if ( drive.CalcView( ply, view ) ) then return view end -- -- Give the player manager a turn at altering the view -- player_manager.RunClass( ply, "CalcView", view ) -- Give the active weapon a go at changing the viewmodel position if ( IsValid( Weapon ) ) then local func = Weapon.GetViewModelPosition if ( func ) then view.vm_origin, view.vm_angles = func( Weapon, origin*1, angles*1 ) -- Note: *1 to copy the object so the child function can't edit it. end local func = Weapon.CalcView if ( func ) then view.origin, view.angles, view.fov = func( Weapon, ply, origin*1, angles*1, fov ) -- Note: *1 to copy the object so the child function can't edit it. end end return view end -- -- If return true: Will draw the local player -- If return false: Won't draw the local player -- If return nil: Will carry out default action -- function GM:ShouldDrawLocalPlayer( ply ) return player_manager.RunClass( ply, "ShouldDrawLocal" ) end --[[--------------------------------------------------------- Name: gamemode:AdjustMouseSensitivity() Desc: Allows you to adjust the mouse sensitivity. The return is a fraction of the normal sensitivity (0.5 would be half as sensitive) Return -1 to not override. -----------------------------------------------------------]] function GM:AdjustMouseSensitivity( fDefault ) local ply = LocalPlayer() if (!ply || !ply:IsValid()) then return -1 end local wep = ply:GetActiveWeapon() if ( wep && wep.AdjustMouseSensitivity ) then return wep:AdjustMouseSensitivity() end return -1 end --[[--------------------------------------------------------- Name: gamemode:ForceDermaSkin() Desc: Return the name of skin this gamemode should use. If nil is returned the skin will use default -----------------------------------------------------------]] function GM:ForceDermaSkin() --return "example" return nil end --[[--------------------------------------------------------- Name: gamemode:PostPlayerDraw() Desc: The player has just been drawn. -----------------------------------------------------------]] function GM:PostPlayerDraw( ply ) end --[[--------------------------------------------------------- Name: gamemode:PrePlayerDraw() Desc: The player is just about to be drawn. -----------------------------------------------------------]] function GM:PrePlayerDraw( ply ) end --[[--------------------------------------------------------- Name: gamemode:GetMotionBlurSettings() Desc: Allows you to edit the motion blur values -----------------------------------------------------------]] function GM:GetMotionBlurValues( x, y, fwd, spin ) -- fwd = 0.5 + math.sin( CurTime() * 5 ) * 0.5 return x, y, fwd, spin end --[[--------------------------------------------------------- Name: gamemode:InputMouseApply() Desc: Allows you to control how moving the mouse affects the view angles -----------------------------------------------------------]] function GM:InputMouseApply( cmd, x, y, angle ) --angle.roll = angle.roll + 1 --cmd:SetViewAngles( Ang ) --return true end --[[--------------------------------------------------------- Name: gamemode:OnAchievementAchieved() -----------------------------------------------------------]] function GM:OnAchievementAchieved( ply, achid ) chat.AddText( ply, Color( 230, 230, 230 ), " earned the achievement ", Color( 255, 200, 0 ), achievements.GetName( achid ) ); end --[[--------------------------------------------------------- Name: gamemode:PreDrawSkyBox() Desc: Called before drawing the skybox. Return true to not draw the skybox. -----------------------------------------------------------]] function GM:PreDrawSkyBox() --return true; end --[[--------------------------------------------------------- Name: gamemode:PostDrawSkyBox() Desc: Called after drawing the skybox -----------------------------------------------------------]] function GM:PostDrawSkyBox() end -- -- Name: GM:PostDraw2DSkyBox -- Desc: Called right after the 2D skybox has been drawn - allowing you to draw over it. -- Arg1: -- Ret1: -- function GM:PostDraw2DSkyBox() end --[[--------------------------------------------------------- Name: gamemode:PreDrawOpaqueRenderables() Desc: Called before drawing opaque entities -----------------------------------------------------------]] function GM:PreDrawOpaqueRenderables( bDrawingDepth, bDrawingSkybox ) -- return true; end --[[--------------------------------------------------------- Name: gamemode:PreDrawOpaqueRenderables() Desc: Called before drawing opaque entities -----------------------------------------------------------]] function GM:PostDrawOpaqueRenderables( bDrawingDepth, bDrawingSkybox ) end --[[--------------------------------------------------------- Name: gamemode:PreDrawOpaqueRenderables() Desc: Called before drawing opaque entities -----------------------------------------------------------]] function GM:PreDrawTranslucentRenderables( bDrawingDepth, bDrawingSkybox ) -- return true end --[[--------------------------------------------------------- Name: gamemode:PreDrawOpaqueRenderables() Desc: Called before drawing opaque entities -----------------------------------------------------------]] function GM:PostDrawTranslucentRenderables( bDrawingDepth, bDrawingSkybox ) end --[[--------------------------------------------------------- Name: gamemode:CalcViewModelView() Desc: Called to set the view model's position -----------------------------------------------------------]] function GM:CalcViewModelView( Weapon, ViewModel, OldEyePos, OldEyeAng, EyePos, EyeAng ) --OldEyePos = OldEyePos + VectorRand() * 2 --ViewModel:SetPos( OldEyePos, OldEyeAng ) if ( !IsValid( Weapon ) ) then return end if ( Weapon.CalcViewModelView == nil ) then return end Weapon:CalcViewModelView( ViewModel, OldEyePos, OldEyeAng, EyePos, EyeAng ) end --[[--------------------------------------------------------- Name: gamemode:PreDrawViewModel() Desc: Called before drawing the view model -----------------------------------------------------------]] function GM:PreDrawViewModel( ViewModel, Player, Weapon ) if ( !IsValid( Weapon ) ) then return false end player_manager.RunClass( Player, "PreDrawViewModel", ViewModel, Weapon ) if ( Weapon.PreDrawViewModel == nil ) then return false end return Weapon:PreDrawViewModel( ViewModel, Weapon, Player ) end --[[--------------------------------------------------------- Name: gamemode:PostDrawViewModel() Desc: Called after drawing the view model -----------------------------------------------------------]] function GM:PostDrawViewModel( ViewModel, Player, Weapon ) if ( !IsValid( Weapon ) ) then return false end player_manager.RunClass( Player, "PostDrawViewModel", ViewModel, Weapon ) if ( Weapon.PostDrawViewModel == nil ) then return false end return Weapon:PostDrawViewModel( ViewModel, Weapon, Player ) end --[[--------------------------------------------------------- Name: gamemode:DrawPhysgunBeam() Desc: Return false to override completely -----------------------------------------------------------]] function GM:DrawPhysgunBeam( ply, weapon, bOn, target, boneid, pos ) -- Do nothing return true end --[[--------------------------------------------------------- Name: gamemode:NetworkEntityCreated() Desc: Entity is created over the network -----------------------------------------------------------]] function GM:NetworkEntityCreated( ent ) end --[[--------------------------------------------------------- Name: gamemode:CreateMove( command ) Desc: Allows the client to change the move commands before it's send to the server -----------------------------------------------------------]] function GM:CreateMove( cmd ) if ( drive.CreateMove( cmd ) ) then return true end if ( player_manager.RunClass( LocalPlayer(), "CreateMove", cmd ) ) then return true end end --[[--------------------------------------------------------- Name: gamemode:PreventScreenClicks() Desc: The player is hovering over a ScreenClickable world -----------------------------------------------------------]] function GM:PreventScreenClicks( cmd ) -- -- Returning true in this hook will prevent screen clicking sending IN_ATTACK -- commands to the weapons. We want to do this in the properties system, so -- that you don't fire guns when opening the properties menu. Holla! -- return false end --[[--------------------------------------------------------- Name: gamemode:GUIMousePressed( mousecode ) Desc: The mouse has been pressed on the game screen -----------------------------------------------------------]] function GM:GUIMousePressed( mousecode, AimVector ) end --[[--------------------------------------------------------- Name: gamemode:GUIMouseReleased( mousecode ) Desc: The mouse has been released on the game screen -----------------------------------------------------------]] function GM:GUIMouseReleased( mousecode, AimVector ) end function GM:PreDrawHUD() end function GM:PostDrawHUD() end function GM:DrawOverlay() end function GM:DrawMonitors() end function GM:PreDrawEffects() end function GM:PostDrawEffects() end function GM:PreDrawHalos() end function GM:CloseDermaMenus() end function GM:CreateClientsideRagdoll( entity, ragdoll ) end
mit
arkana-fts/cegui
cegui/src/ScriptModules/Lua/support/tolua++bin/lua/enumerate.lua
14
2744
-- tolua: enumerate 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. -- Enumerate class -- Represents enumeration -- The following fields are stored: -- {i} = list of constant names classEnumerate = { } classEnumerate.__index = classEnumerate setmetatable(classEnumerate,classFeature) -- register enumeration function classEnumerate:register (pre) pre = pre or '' local nspace = getnamespace(classContainer.curr) local i=1 while self[i] do output(pre..'tolua_constant(tolua_S,"'..self.lnames[i]..'",'..nspace..self[i]..');') i = i+1 end end -- Print method function classEnumerate:print (ident,close) print(ident.."Enumerate{") print(ident.." name = "..self.name) local i=1 while self[i] do print(ident.." '"..self[i].."'("..self.lnames[i].."),") i = i+1 end print(ident.."}"..close) end --- -- LuaDoc Patch -- outputs an empty(without documentation) LuaDoc interface -- by klapeto (http://cegui.org.uk/forum/viewtopic.php?f=7&t=6784) function classEnumerate:output_luadoc() if not self:check_public_access() then return end local i=1 while self[i] do if self.lnames[i] and self.lnames[i] ~= "" then output('---\n') output('-- '..self.lnames[i]..'\n') output('-- @field [parent=#'..cleanseType(self.parent.name)..'] #number '..self.lnames[i]..'\n') output('\n') end i = i+1 end end -- Internal constructor function _Enumerate (t,varname) setmetatable(t,classEnumerate) append(t) appendenum(t) if varname and varname ~= "" then if t.name ~= "" then Variable(t.name.." "..varname) else local ns = getcurrnamespace() warning("Variable "..ns..varname.." of type <anonymous enum> is declared as read-only") Variable("tolua_readonly int "..varname) end end return t end -- Constructor -- Expects a string representing the enumerate body function Enumerate (n,b,varname) b = string.gsub(b, ",[%s\n]*}", "\n}") -- eliminate last ',' local t = split(strsub(b,2,-2),',') -- eliminate braces local i = 1 local e = {n=0} while t[i] do local tt = split(t[i],'=') -- discard initial value e.n = e.n + 1 e[e.n] = tt[1] i = i+1 end -- set lua names i = 1 e.lnames = {} local ns = getcurrnamespace() while e[i] do local t = split(e[i],'@') e[i] = t[1] if not t[2] then t[2] = applyrenaming(t[1]) end e.lnames[i] = t[2] or t[1] _global_enums[ ns..e[i] ] = (ns..e[i]) i = i+1 end e.name = n if n ~= "" then Typedef("int "..n) end return _Enumerate(e, varname) end
mit
philsiff/Red-Vs-Blue
Red Vs. Blue Files/gamemodes/sandbox/entities/weapons/gmod_tool/stools/material.lua
1
4044
TOOL.Category = "Render" TOOL.Name = "#tool.material.name" TOOL.Command = nil TOOL.ConfigName = "" TOOL.ClientConVar[ "override" ] = "debug/env_cubemap_model" -- -- Duplicator function -- local function SetMaterial( Player, Entity, Data ) if ( SERVER ) then -- -- Make sure this is in the 'allowed' list in multiplayer - to stop people using exploits -- if ( !game.SinglePlayer() && !list.Contains( "OverrideMaterials", Data.MaterialOverride ) && Data.MaterialOverride != "" ) then return end Entity:SetMaterial( Data.MaterialOverride ) duplicator.StoreEntityModifier( Entity, "material", Data ) end return true end duplicator.RegisterEntityModifier( "material", SetMaterial ) -- -- Left click applies the current material -- function TOOL:LeftClick( trace ) if ( !IsValid( trace.Entity ) ) then return end local mat = self:GetClientInfo( "override" ) SetMaterial( self:GetOwner(), trace.Entity, { MaterialOverride = mat } ) return true end -- -- Right click reverts the material -- function TOOL:RightClick( trace ) if ( !IsValid( trace.Entity ) ) then return end SetMaterial( self:GetOwner(), trace.Entity, { MaterialOverride = "" } ) return true end list.Add( "OverrideMaterials", "models/wireframe" ) list.Add( "OverrideMaterials", "debug/env_cubemap_model" ) list.Add( "OverrideMaterials", "models/shadertest/shader3" ) list.Add( "OverrideMaterials", "models/shadertest/shader4" ) list.Add( "OverrideMaterials", "models/shadertest/shader5" ) list.Add( "OverrideMaterials", "models/shiny" ) list.Add( "OverrideMaterials", "models/debug/debugwhite" ) list.Add( "OverrideMaterials", "Models/effects/comball_sphere" ) list.Add( "OverrideMaterials", "Models/effects/comball_tape" ) list.Add( "OverrideMaterials", "Models/effects/splodearc_sheet" ) list.Add( "OverrideMaterials", "Models/effects/vol_light001" ) list.Add( "OverrideMaterials", "models/props_combine/stasisshield_sheet" ) list.Add( "OverrideMaterials", "models/props_combine/portalball001_sheet" ) list.Add( "OverrideMaterials", "models/props_combine/com_shield001a" ) list.Add( "OverrideMaterials", "models/props_c17/frostedglass_01a" ) list.Add( "OverrideMaterials", "models/props_lab/Tank_Glass001" ) list.Add( "OverrideMaterials", "models/props_combine/tprings_globe" ) list.Add( "OverrideMaterials", "models/rendertarget" ) list.Add( "OverrideMaterials", "models/screenspace" ) list.Add( "OverrideMaterials", "brick/brick_model" ) list.Add( "OverrideMaterials", "models/props_pipes/GutterMetal01a" ) list.Add( "OverrideMaterials", "models/props_pipes/Pipesystem01a_skin3" ) list.Add( "OverrideMaterials", "models/props_wasteland/wood_fence01a" ) list.Add( "OverrideMaterials", "models/props_foliage/tree_deciduous_01a_trunk" ) list.Add( "OverrideMaterials", "models/props_c17/FurnitureFabric003a" ) list.Add( "OverrideMaterials", "models/props_c17/FurnitureMetal001a" ) list.Add( "OverrideMaterials", "models/props_c17/paper01" ) list.Add( "OverrideMaterials", "models/flesh" ) -- phx list.Add( "OverrideMaterials", "phoenix_storms/metalset_1-2" ) list.Add( "OverrideMaterials", "phoenix_storms/metalfloor_2-3" ) list.Add( "OverrideMaterials", "phoenix_storms/plastic" ) list.Add( "OverrideMaterials", "phoenix_storms/wood" ) list.Add( "OverrideMaterials", "phoenix_storms/bluemetal" ) list.Add( "OverrideMaterials", "phoenix_storms/cube" ) list.Add( "OverrideMaterials", "phoenix_storms/dome" ) list.Add( "OverrideMaterials", "phoenix_storms/gear" ) list.Add( "OverrideMaterials", "phoenix_storms/stripes" ) list.Add( "OverrideMaterials", "phoenix_storms/wire/pcb_green" ) list.Add( "OverrideMaterials", "phoenix_storms/wire/pcb_red" ) list.Add( "OverrideMaterials", "phoenix_storms/wire/pcb_blue" ) list.Add( "OverrideMaterials", "hunter/myplastic" ) list.Add( "OverrideMaterials", "models/XQM/LightLinesRed_tool" ) function TOOL.BuildCPanel( CPanel ) -- HEADER CPanel:SetTooltip( "#tool.material.desc" ) CPanel:MatSelect( "material_override", list.Get( "OverrideMaterials" ), true, 0.33, 0.33 ) end
mit
joaofvieira/luci
modules/luci-base/luasrc/tools/webadmin.lua
59
2301
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008-2015 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.tools.webadmin", package.seeall) local util = require "luci.util" local uci = require "luci.model.uci" local ip = require "luci.ip" function byte_format(byte) local suff = {"B", "KB", "MB", "GB", "TB"} for i=1, 5 do if byte > 1024 and i < 5 then byte = byte / 1024 else return string.format("%.2f %s", byte, suff[i]) end end end function date_format(secs) local suff = {"min", "h", "d"} local mins = 0 local hour = 0 local days = 0 secs = math.floor(secs) if secs > 60 then mins = math.floor(secs / 60) secs = secs % 60 end if mins > 60 then hour = math.floor(mins / 60) mins = mins % 60 end if hour > 24 then days = math.floor(hour / 24) hour = hour % 24 end if days > 0 then return string.format("%.0fd %02.0fh %02.0fmin %02.0fs", days, hour, mins, secs) else return string.format("%02.0fh %02.0fmin %02.0fs", hour, mins, secs) end end function cbi_add_networks(field) uci.cursor():foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then field:value(section[".name"]) end end ) field.titleref = luci.dispatcher.build_url("admin", "network", "network") end function cbi_add_knownips(field) local _, n for _, n in ipairs(ip.neighbors({ family = 4 })) do if n.dest then field:value(n.dest:string()) end end end function firewall_find_zone(name) local find luci.model.uci.cursor():foreach("firewall", "zone", function (section) if section.name == name then find = section[".name"] end end ) return find end function iface_get_network(iface) local link = ip.link(tostring(iface)) if link.master then iface = link.master end local cur = uci.cursor() local dump = util.ubus("network.interface", "dump", { }) if dump then local _, net for _, net in ipairs(dump.interface) do if net.l3_device == iface or net.device == iface then -- cross check with uci to filter out @name style aliases local uciname = cur:get("network", net.interface, "ifname") if not uciname or uciname:sub(1, 1) ~= "@" then return net.interface end end end end end
apache-2.0
anonymous12212020/sbss
plugins/time.lua
38
2898
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "این شهر وجود ندارن" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "زمان در شهر "..timeZoneId.." اینگونه است: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "دریافت زمان منطقه", usage = "زمان [area]: زمان منطقه جغرافیایی", patterns = {"^زمان (.*)$"}, run = run }
gpl-2.0
philsiff/Red-Vs-Blue
Very Basic TDM [Gamemode]/gamemodes/vbtdm/gamemode/hitmarker/sv_hitdamagenumbers.lua
1
1537
//test util.AddNetworkString( "imHDN_createHitNumber" ) local on = true CreateConVar( "sv_hitnums_show", 1 ) cvars.AddChangeCallback( "sv_hitnums_show", function() on = (GetConVarNumber("sv_hitnums_show") ~= 0) end ) local showAll = false CreateConVar( "sv_hitnums_showalldamage", 0 ) cvars.AddChangeCallback( "sv_hitnums_showalldamage", function() showAll = (GetConVarNumber("sv_hitnums_showalldamage") ~= 0) end ) function EntDamage(target, dmginfo) if not on then return end local attacker = dmginfo:GetAttacker() if target:IsValid() and (attacker:IsValid() or showAll) then if (showAll or attacker:IsPlayer()) and target:Health()>0 and target:GetCollisionGroup() ~= COLLISION_GROUP_DEBRIS then net.Start("imHDN_createHitNumber") -- Damage amount net.WriteFloat(dmginfo:GetDamage()) -- Type of damage net.WriteUInt(dmginfo:GetDamageType(), 32) -- Is it a critical hit? (for players and npcs only) net.WriteBit( (dmginfo:GetDamage() >= target:GetMaxHealth()) and (target:IsPlayer() or target:IsNPC()) ) -- Get damage position local pos if dmginfo:IsBulletDamage() then pos = dmginfo:GetDamagePosition() else if target:IsPlayer() or target:IsNPC() then pos = target:GetPos() + Vector(0,0,48) else pos = target:GetPos() end end net.WriteVector(pos) if showAll then net.Broadcast() else net.Send(attacker) end end end end hook.Add("EntityTakeDamage", "ihHDN_EntDamage", EntDamage)
mit
8day/aegisub-auto4-scripts
calculate-org-to-reproduce-perspective-distortion.lua
1
6211
--[[ Description Auto4 script written in Lua for subtitle editor Aegisub. Purpose is stated in the "script_description" variable. Take a note that the approach described here does not always work (!). That's probably because the **whole** vanishing point should've been used as an origin \org, but since its calculation is very hard (I don't know math that well), I came up with this alternative (org.y = video.height/2) that does not work always, but simplifies handpicking of approximate angles for \fr[xyz]. HowTo 1) find rotated plane on top of which you want to place your graphics. Make sure that edges are visible, at least enough to draw a line on top of them; 2) create first subtitle, and use \move (start and end point should represent ends of an interval) to draw a line on top of one edge; 3) repeat second step, but make sure that second line is parallel to the one that was drawn in the first step; 4) select both subtitles and use this script; 5) through trial-and-error try to find the best possible \fr[xyz] to suit your plane. Video showing how to do this is here: youtu.be/oLNLzyvOGj0 ToDo Add function to determine plane rotation. ]]-- include("karaskel.lua") script_name = "Calculate \\org to reproduce perspective distortion" script_description = "Calculates values for \\org to aid in manual perspective distortion reproduction, i.e. to make your subs look like they were positioned in 3D space." script_author = "8day" script_version = "1.2.2" script_modified = "27.12.2013" function roundNum(val, decimal) if (decimal) then return math.floor(((val * 10^decimal) + 0.5) / (10^decimal)) else return math.floor(val + 0.5) end end -- This algorithm was taken from http://alienryderflex.com/intersect/ -- Apperently, its author is Darel Rex Finley. function point_of_intersection(Ax, Ay, Bx, By, Cx, Cy, Dx, Dy) local msg, distAB, theCos, theSin, newX, ABpos, X, Y -- Fail if either line is undefined. if (Ax == Bx and Ay == By) or (Cx == Dx and Cy == Dy) then msg = "One of the lines is undefined, i.e. both points specified in one of the \\move are in the same place.\n" aegisub.progress.title("Error") aegisub.debug.out(msg) return false end -- 1) Translate the system so that point A is on the origin. Bx = Bx - Ax; By = By - Ay Cx = Cx - Ax; Cy = Cy - Ay Dx = Dx - Ax; Dy = Dy - Ay -- Discover the length of segment A-B. distAB = math.sqrt(Bx * Bx + By * By) -- 2) Rotate the system so that point B is on the positive X axis. theCos = Bx / distAB theSin = By / distAB newX = Cx * theCos + Cy * theSin Cy = Cy * theCos - Cx * theSin Cx = newX newX = Dx * theCos + Dy * theSin Dy = Dy * theCos - Dx * theSin Dx = newX -- Somehow, I cannot simply compare two numbers... -- Had to use this "rounding"... -- WTF I'm doing wrong here...?! if roundNum(Cy, 12) == roundNum(Dy, 12) then msg = "Lines specified by \\move are parallel!\n" aegisub.progress.title("Error") aegisub.debug.out(msg) return false end -- 3) Discover the position of the intersection point along line A-B. ABpos = Dx + (Cx - Dx) * Dy / (Dy - Cy) -- 4) Apply the discovered position to line A-B in the original coordinate system. X = Ax + ABpos * theCos Y = Ay + ABpos * theSin -- Success. return {["x"] = X, ["y"] = Y} end -- Main abracadabra. function calculate_org(subs, sel) local msg -- Check whether user selected exactly two subs. if #sel ~= 2 then msg = string.format("You should choose exactly two subtitles, not %d!\n", #sel) aegisub.progress.title("Error") aegisub.debug.out(msg) return false end -- Check whether both subs are alike. local meta, styles, fst, snd meta, styles = karaskel.collect_head(subs, false) fst, snd = subs[sel[1]], subs[sel[2]] karaskel.preproc_line_text(meta, styles, fst) karaskel.preproc_line_text(meta, styles, snd) entries = {"class", "text_stripped", "layer", "start_time", "end_time", "style", "actor", "margin_l", "margin_r", "margin_t", "margin_b", "effect"} for i, entry in pairs(entries) do if fst[entry] ~= snd[entry] then msg = string.format("Selected subtitles are different in the field \"%s\".\n", entry) aegisub.progress.title("Error") aegisub.debug.out(msg) return false end end -- Find which \move flavour were used. local nmb, content1, content2, pattern1, pattern2, pattern_move nmb = "%s*(-?%d+%.?%d*)%s*" content1 = string.format("%s,%s,%s,%s,%s,%s", nmb, nmb, nmb, nmb, nmb, nmb) content2 = string.format("%s,%s,%s,%s", nmb, nmb, nmb, nmb) pattern1 = "\\move%(" .. content1 .. "%)" pattern2 = "\\move%(" .. content2 .. "%)" if string.find(fst.text, pattern1) and string.find(snd.text, pattern1) then pattern_move = pattern1 elseif string.find(fst.text, pattern2) and string.find(snd.text, pattern2) then pattern_move = pattern2 else msg = "Couldn't find all \\move tags. Most likely one of them is absent or malformed." aegisub.progress.title("Error") aegisub.debug.out(msg) return false end -- Find vanishing point. local m1_x1, m1_x2, m1_y1, m1_y2, m2_x1, m2_x2, m2_y1, m2_y2, vanishing_point m1_x1, m1_x2, m1_y1, m1_y2 = string.match(fst.text, pattern_move) m2_x1, m2_x2, m2_y1, m2_y2 = string.match(snd.text, pattern_move) vanishing_point = point_of_intersection(m1_x1, m1_x2, m1_y1, m1_y2, m2_x1, m2_x2, m2_y1, m2_y2) if vanishing_point == false then return false end -- Final processing: -- 1) calculate coordinates for \org; -- 2) replace first \move by \org; -- 3) remove second \move. local org_x, org_y, org, pattern_org org_x = math.floor(meta.res_x / 2) org_y = math.floor(vanishing_point.y) org = string.format("\\org(%d,%d)", org_x, org_y) pattern_org = "\\org%(" .. nmb .. "," .. nmb .. "%)" if string.find(fst.text, pattern_org) then fst.text = string.gsub(fst.text, pattern_org, org) fst.text = string.gsub(fst.text, pattern_move, "") else fst.text = string.gsub(fst.text, pattern_move, org) end subs[sel[1]] = fst subs.delete(sel[2]) return true end -- Macro. function macro(subs, sel) if calculate_org(subs, sel) then aegisub.set_undo_point("\"" .. script_name .. "\"") end end -- Register macro in Aegisub. aegisub.register_macro(script_name, script_description, macro)
bsd-3-clause
crinai/oolua
unit_tests/test.unit.lua
8
1199
--OOLua test.unit local root = "../" local name = "test.unit" create_package(name,root,"ConsoleApp") configuration {} files { root .. "unit_tests/main.cpp", root .. "unit_tests/bind_classes/*.h", root .. "unit_tests/bind_classes/*.cpp", root .. "unit_tests/cpp_classes/*.h", root .. "unit_tests/cpp_classes/*.cpp", root .. "unit_tests/test_classes/*h", root .. "unit_tests/test_classes/*.cpp" } includedirs { "include/cppunit", "include/gmock", "include/lua", "include/", root .. "include/", "/usr/local/include", "/usr/include", root .. "unit_tests/bind_classes", root .. "unit_tests/cpp_classes", root .. "unit_tests/test_classes", --"/usr/local/include/lua52" } --flags{ "NoExceptions"} defines { "OOLUA_USE_PRECOMPILED_HEADER" } links { "oolua" } configuration{"gmake"} pchheader("unit_tests/test_classes/oolua_tests_pch.h") configuration{"not gmake","not vs*"} pchheader(root .. "unit_tests/test_classes/oolua_tests_pch.h") configuration{"vs*"} pchheader(root .. "unit_tests/test_classes/oolua_tests_pch.h") pchsource(root .. "unit_tests/test_classes/oolua_tests_pch.cpp") buildoptions {"/FI oolua_tests_pch.h"} unit_test_config(root,name)
mit
FoxelBox/FoxBukkitLua
lua/src/main/lua/classes/Questioner.lua
1
5868
--[[ This file is part of FoxBukkitLua-lua. FoxBukkitLua-lua is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. FoxBukkitLua-lua 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with FoxBukkitLua-lua. If not, see <http://www.gnu.org/licenses/>. ]] local Chat = require("Chat") local Player = require("Player") local Command = require("Command") local Event = require("Event") local table_insert = table.insert local table_concat = table.concat local next = next if not Chat:isAvailable() then return { isAvailable = function(self) return false end } end Event:register{ class = "org.bukkit.event.player.PlayerQuitEvent", priority = Event.Priority.NORMAL, ignoreCancelled = true, run = function(self, event) Player:extend(event:getPlayer())._questions = nil end } local COMMAND_NAME = "/__qq__" .. __LUA_STATE:getModule() Command:register{ name = COMMAND_NAME:sub(2), permission = "foxbukkit.lua.questioner", arguments = { { name = "id", type = "string" }, { name = "answer", type = "string" } }, run = function(self, ply, args) local myQuestions = ply._questions if not myQuestions then ply:sendError("You answered an unknwon/expired question") return end local question = myQuestions[args.id] if not question then ply:sendError("You answered an unknwon/expired question") return end local callback = question[args.answer] myQuestions[args.id] = nil if callback then callback() end end } local function makeQuestionID(ply) local id local myQuestions = ply._questions while (not id) or (myQuestions and myQuestions[id]) do id = tostring(math.random(0, 99999999999)) end return id end local function rememberConfirmation(ply, rememberKey, state) if not ply.rememberConfirmations then ply.rememberConfirmations = {} end ply.rememberConfirmations[rememberKey] = state ply:__save() end local Questioner = { isAvailable = function(self) return true end, forgetPlayerConfirmation = function(self, ply, rememberKey) if ply.rememberConfirmations then ply.rememberConfirmations[rememberKey] = nil ply:__save() end end, askPlayerConfirmation = function(self, ply, rememberKey, yesCallback, noCallback) if rememberKey then local rememberedConfirmation if ply.rememberConfirmations then rememberedConfirmation = ply.rememberConfirmations[rememberKey] end if rememberedConfirmation ~= nil then if rememberedConfirmation then yesCallback() else noCallback() end return end return self:askPlayer(ply, { { name = "yes", callback = yesCallback }, { name = "no", callback = noCallback }, { name = "always", callback = function() rememberConfirmation(ply, rememberKey, true) if yesCallback then return yesCallback() end end }, { name = "never", callback = function() rememberConfirmation(ply, rememberKey, false) if noCallback then return noCallback() end end } }, rememberKey) else return self:askPlayer(ply, { { name = "yes", callback = yesCallback }, { name = "no", callback = noCallback } }) end end, askPlayer = function(self, ply, buttons, rememberKey) local msg = {} local buttonCallbacks = {} local questionId = rememberKey or makeQuestionID(ply) for _, v in next, buttons do buttonCallbacks[v.name] = v.callback table_insert(msg, Chat:makeButton(COMMAND_NAME .. " " .. questionId .. " " .. v.name, v.name, "blue", true, false)) end if not ply._questions then ply._questions = {} end ply._questions[questionId] = buttonCallbacks return { id = questionId, message = table_concat(msg, " ") } end } Player:addExtensions{ ask = function(self, buttons, rememberKey) return Questioner:askPlayer(self, buttons, rememberKey) end, forgetConfirmation = function(self, rememberKey) return Questioner:forgetPlayerConfirmation(self, rememberKey) end, askConfirmation = function(self, rememberKey, yesCallback, noCallback) return Questioner:askPlayerConfirmation(self, rememberKey, yesCallback, noCallback) end } return Questioner
lgpl-3.0
eggBOY91/Arctic-Core
src/scripts/lua/Lua/Stable Scripts/Azeroth/Karazhan/BOSS_Karazhan_Netherspite.lua
30
1703
function Netherspite_Portal_PhaseA(Unit, event, miscunit, misc) print "Netherspite Portal PhaseA" Unit:SendAreaTriggerMessage("PORTAL PHASE") Unit:FullCastSpell(30400) Unit:FullCastSpell(30401) Unit:FullCastSpell(30402) end function Netherspite_Nether_Burn(Unit, event, miscunit, misc) print "Netherspite Nether Burn" Unit:FullCastSpellOnTarget(30523,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "BURN...") end function Netherspite_Vode_Zone(Unit, event, miscunit, misc) print "Netherspite Vode Zone" Unit:FullCastSpellOnTarget(30533,Unit:GetRandomPlayer()) Unit:SendChatMessage(11, 0, "Bad Zone...") end function Netherspite_Banish_Phase(Unit, event, miscunit, misc) print "Netherspite Banish Phase" Unit:SendAreaTriggerMessage("BANISH PHASE") Unit:FullCastSpell(35182) Unit:FullCastSpellOnTarget(38524,Unit:GetClosestPlayer()) end function Netherspite_Portal_PhaseB(Unit, event, miscunit, misc) print "Netherspite Portal PhaseB" Unit:SendAreaTriggerMessage("PORTAL PHASE") Unit:FullCastSpell(30400) Unit:FullCastSpell(30401) Unit:FullCastSpell(30402) end function Netherspite_Enrage(Unit, event, miscunit, misc) print "Netherspite Enrage" Unit:FullCastSpell(35595) Unit:SendChatMessage(11, 0, "You will all die...") end function Netherspite(unit, event, miscunit, misc) print "Netherspite" unit:RegisterEvent("Netherspite_Portal_PhaseA",1000,1) unit:RegisterEvent("Netherspite_Nether_Burn",10000,0) unit:RegisterEvent("Netherspite_Vode_Zone",20000,0) unit:RegisterEvent("Netherspite_Banish_Phase",30000,0) unit:RegisterEvent("Netherspite_Portal_PhaseB",60000,0) unit:RegisterEvent("Netherspite_Enrage",540000,0) end RegisterUnitEvent(15689,1,"Netherspite")
agpl-3.0
notestudio/shall-I-kill-her
assets/scripts/messages.lua
1
5013
require 'assets/scripts/vendor/MessageInABottle' local messages = {} messages.active = true function messages.load() ocean = Ocean:new() end function messages.update(dt, game) ocean:update(dt) if game.status == 1 and messages.active then messages.new_message('welcome', 10) messages.active = false end end function messages.draw() ocean:draw() end function messages.new_message(cap, time) local texts = {} texts.welcome = "I must make decision. I won’t leave this room until I’ve decided to kill my girlfriend or not. How has it come to this? I’ve got little time. Her life is teetering through my fingers." texts.cap1preview="She’s gorgeous in this picture. My mother has given me more than I’ll ever be able to give her back. Not only did she give me the gift of life, but a reason to go on. Her lessons and strong character have made me become the man I am now. What I most want in this world is for her to be proud of me. Proud of my work and my partner. But a bitch had to screw it all up. She stepped on what I loved most. She attacked all my mother taught me and undermined my deepest beliefs. I don’t believe half-way, like my siblings, but truly. And this girl did nothing but ridicule me. Make fun of me in front of my friends; call me a nutter in private; tell me I was wrong; brand me as a brute - a moron. But she’s the moron! She’s just an immoral, sinful whore…I need to calm down, clear my mind. Listen to God’s Word. If I go out now, I’ll kill her! I must settle down and think straight. God, speak to me!" texts.cap2stage=" Corinthians 12:10 That is why, for Christ's sake, I delight in weaknesses, in insults, in hardships, in persecutions, in difficulties. For when I am weak, then I am strong uAs strong as she made me. She laughed at me in front of my friends, but to help me overcome my shyness. She said I was a nutter to help me overcome my issues, to make me realise the obsessions I’d inherited from my mother. Brute when I wasn’t tolerant with others. And I just got upset…like a moron. A part of my soul still belongs to her. But I mustn’t forget where I first met her, where I bought her first kisses. My parents must never know the truth. My mother shall never know about the smokes, the drinks I had. I must destroy that sheet of paper. Nobody must see it." texts.cap3stage="While the smoke went through my nostrils, I remembered the barbecue parties we threw every Saturday with my family. My cousins adored her and she got on really well with my uncle and aunt. She was completely integrated in my family, so we invited her to come to this barbecue party. And then, while we were saying grace, she started to eat. In the silence you could hear her chewing on a greasy sausage. In shock, they all looked at her, and then, at my grimace. I couldn’t believe what was happening. I took her outside to the log cabin. She won’t easily forget what I said to her. I’d never met such an insensitive person, such a…and as an apology she gave us a fucking compact disc as a gift. Does she really think it would make up for what she’d done? What a shitty gift!" texts.cap4stage="I love this song. I remember now why she bought this one. It was our song. A hidden apology for me. Maybe I got too carried away. After all, she’s not religious, she’d never said grace. She hadn’t even seen how it’s done. She did what anybody would have done: sit down and start to eat. Poor one. I shouldn’t have accepted the album, her tears were more than enough. She meant no harm. But I did…and now I must kill her. I must do it before she starts telling lies about me and harms my family's reputation. I can't allow this to happen. I'm not gay. I'm not sick. I'm not using this key. I'll go out that door and I'll do her in. No more memories, I've made up my mind." texts.endbad="Die, bitch." texts.endgood="My bra. It's so uncomfortable. I've always hated wearing it. It makes my breasts hurt. On our first secret anniversary he bought me an outfit. He's got me. He's always helped me grow as a person. To break ties. Like the one I'm in now. Telling my mother I'm a woman who's into other...women. And that the Lord justs wants me to be happy. I've got to be strong. 2 Corinthians 12:10 That is why, for Christ's sake, I delight in weaknesses, in insults, in hardships, in persecutions, in difficulties. For when I am weak, then I am strong uAs strong as she made me. She laughed at me in front of my friends, but to help me overcome my shyness. She said I was a nutter to help me overcome my issues, to make me realise the obsessions I’d inherited from my mother. Brute when I wasn’t tolerant with others. And I just got upset…like a moron. A part of my soul still belongs to her. Thanks my love." local bottle = TimeBottle:new(cap, texts['' .. cap], time) bottle:setX(30) bottle:setY(500) bottle:setWidth(1220) bottle:setHeight(140) bottle:setVolume(0) ocean:addBottle(bottle) end return messages
apache-2.0
sgraham/nope
third_party/skia/tools/lua/paths.lua
92
3129
-- -- Copyright 2014 Google Inc. -- -- Use of this source code is governed by a BSD-style license that can be -- found in the LICENSE file. -- -- Path scraping script. -- This script is designed to count the number of times we fall back to software -- rendering for a path in a given SKP. However, this script does not count an exact -- number of uploads, since there is some overlap with clipping: e.g. two clipped paths -- may cause three uploads to the GPU (set clip 1, set clip 2, unset clip 2/reset clip 1), -- but these cases are rare. draws = 0 drawPaths = 0 drawPathsAnti = 0 drawPathsConvexAnti = 0 clips = 0 clipPaths = 0 clipPathsAnti = 0 clipPathsConvexAnti = 0 usedPath = false usedSWPath = false skpsTotal = 0 skpsWithPath = 0 skpsWithSWPath = 0 function sk_scrape_startcanvas(c, fileName) usedPath = false usedSWPath = false end function sk_scrape_endcanvas(c, fileName) skpsTotal = skpsTotal + 1 if usedPath then skpsWithPath = skpsWithPath + 1 if usedSWPath then skpsWithSWPath = skpsWithSWPath + 1 end end end function string.starts(String,Start) return string.sub(String,1,string.len(Start))==Start end function isPathValid(path) if not path then return false end if path:isEmpty() then return false end if path:isRect() then return false end return true end function sk_scrape_accumulate(t) if (string.starts(t.verb, "draw")) then draws = draws + 1 end if (string.starts(t.verb, "clip")) then clips = clips + 1 end if t.verb == "clipPath" then local path = t.path if isPathValid(path) then clipPaths = clipPaths + 1 usedPath = true if t.aa then clipPathsAnti = clipPathsAnti + 1 if path:isConvex() then clipPathsConvexAnti = clipPathsConvexAnti + 1 else usedSWPath = true end end end end if t.verb == "drawPath" then local path = t.path local paint = t.paint if paint and isPathValid(path) then drawPaths = drawPaths + 1 usedPath = true if paint:isAntiAlias() then drawPathsAnti = drawPathsAnti + 1 if path:isConvex() then drawPathsConvexAnti = drawPathsConvexAnti + 1 else usedSWPath = true end end end end end function sk_scrape_summarize() local swDrawPaths = drawPathsAnti - drawPathsConvexAnti local swClipPaths = clipPathsAnti - clipPathsConvexAnti io.write("clips = clips + ", clips, "\n"); io.write("draws = draws + ", draws, "\n"); io.write("clipPaths = clipPaths + ", clipPaths, "\n"); io.write("drawPaths = drawPaths + ", drawPaths, "\n"); io.write("swClipPaths = swClipPaths + ", swClipPaths, "\n"); io.write("swDrawPaths = swDrawPaths + ", swDrawPaths, "\n"); io.write("skpsTotal = skpsTotal + ", skpsTotal, "\n"); io.write("skpsWithPath = skpsWithPath + ", skpsWithPath, "\n"); io.write("skpsWithSWPath = skpsWithSWPath + ", skpsWithSWPath, "\n"); end
bsd-3-clause
telebombang2018/energy
plugins/PL (5).lua
3
1634
-----my_name_is_ehsan*#@mafia_boy -----@ENERGY_TEAM FOR UPDATE -----لطفا پیام بالا رو پاک نکنید function run(msg,matches) if matches[1] == 'id' or 'ایدی' and msg.reply_to_message_id_ == 0 then if is_sudo(msg) then rank = 'صاحب ربات' elseif is_owner(msg) then rank = 'صاحب گروه' elseif is_mod(msg) then rank = 'ناظر گروه' else rank = 'کاربر عادی' end local function getpro(arg, data) if data.photos_[0] then tdcli.sendPhoto(msg.chat_id_, msg.id_, 0, 1, nil, data.photos_[0].sizes_[1].photo_.persistent_id_,'\n● 》 Your Name➢ '..msg.from.print_name..'\n● 》 Your ID➢ '..msg.sender_user_id_..'\n● 》 Your UserName➢ '..(msg.from.username or '----')..'\n● 》 Your Phone➢ '..(msg.from.phone or 'I Not Have Your Phone Number!')..'\n● 》 Your Rank➢ '..rank..'\n',msg.id_,msg.id_) else tdcli.sendMassage(msg.chat_id_, msg.id_, 1, "You Have'nt Profile Photo!!\n\n● 》 *Supergroup ID➢* `"..msg.chat_id_.."`\n*● 》 Your ID➢* `"..msg.sender_user_id_.."\n*● 》 Your UserName➢* `"..(msg.from.username or "----").."`\n*● 》 Your Phone➢* `"..(msg.from.phone or "I Not Have Your Phone Number!").."`\n*● 》 Your Rank➢* `"..rank.."`", 1, 'md') end end tdcli_function ({ ID = "GetUserProfilePhotos", user_id_ = msg.sender_user_id_, offset_ = 0, limit_ = 1 }, getpro, nil) end end return { patterns = { "^[/!#](id)$", "^(ایدی)$", }, run = run } -----my_name_is_ehsan*#@mafia_boy -----@ENERGY_TEAM FOR UPDATE -----لطفا پیام بالا رو پاک نکنید
gpl-3.0
joeherwig/RealAir-Turbine-Duke-V2-LUA
Modules/linda-cfg/aircrafts/RealAir Duke Turbine V2/config-user.lua
1
1321
-- USER CONFIGURATION FOR AUTOSAVE -- Updated for LINDA 2.5 -- Nov 2014 -- All the settings here could be overridden on per-plane basis -- by creating file config-user.lua in correspnding plane's configs folder -- (i.e. SIM/Modules/linda-cfg/aircrafts/Cessna 172/config-user.lua) -- Use the same variables there with new desired values. -- Autosave feature settings -- ========================= -- Global autosave feature enable/disable AUTOSAVE_ENABLE = 1 -- Make LINDA also save the default flight named "_linda_default", -- so you could set it as default flight in your sim and make next -- flight start from the same place AUTOSAVE_DEFAULT_FLIGHT = 1 -- Make LINDA also save the _plane_specific_ default flight named "_linda_lastpos_AircraftID", -- so you could load it manualy if you have several planes in use -- and want to fast resume their flights AUTOSAVE_PLANE_FLIGHT = 1 -- Make separate save file for each airport (logfile mode) AUTOSAVE_EACH_AIRFIELD = 0 -- What systems should be turned OFF to trigger the autosave action: -- Engine should be off AUTOSAVE_ENGINE_CHECK = 1 -- Magneto should be off AUTOSAVE_MAGNETO_CHECK = 1 -- Main battery should be off AUTOSAVE_BATTERY_CHECK = 1 -- All lights should be off AUTOSAVE_LIGHTS_CHECK = 1 -- Parking brake should be set AUTOSAVE_PARKING_CHECK = 1
mit
pazos/koreader
frontend/apps/reader/modules/readerhighlight.lua
1
61837
local BD = require("ui/bidi") local ButtonDialog = require("ui/widget/buttondialog") local Device = require("device") local Event = require("ui/event") local InfoMessage = require("ui/widget/infomessage") local InputContainer = require("ui/widget/container/inputcontainer") local MultiConfirmBox = require("ui/widget/multiconfirmbox") local Notification = require("ui/widget/notification") local TimeVal = require("ui/timeval") local Translator = require("ui/translator") local UIManager = require("ui/uimanager") local logger = require("logger") local util = require("util") local ffiUtil = require("ffi/util") local _ = require("gettext") local C_ = _.pgettext local T = require("ffi/util").template local Screen = Device.screen local ReaderHighlight = InputContainer:new{ } local function inside_box(pos, box) if pos then local x, y = pos.x, pos.y if box.x <= x and box.y <= y and box.x + box.w >= x and box.y + box.h >= y then return true end end end local function cleanupSelectedText(text) -- Trim spaces and new lines at start and end text = text:gsub("^[\n%s]*", "") text = text:gsub("[\n%s]*$", "") -- Trim spaces around newlines text = text:gsub("%s*\n%s*", "\n") -- Trim consecutive spaces (that would probably have collapsed -- in rendered CreDocuments) text = text:gsub("%s%s+", " ") return text end function ReaderHighlight:init() self._highlight_buttons = { -- highlight and add_note are for the document itself, -- so we put them first. ["01_highlight"] = function(_self) return { text = _("Highlight"), callback = function() _self:saveHighlight() _self:onClose() end, enabled = _self.hold_pos ~= nil, } end, ["02_add_note"] = function(_self) return { text = _("Add Note"), callback = function() _self:addNote() _self:onClose() end, enabled = _self.hold_pos ~= nil, } end, -- copy and search are internal functions that don't depend on anything, -- hence the second line. ["03_copy"] = function(_self) return { text = C_("Text", "Copy"), enabled = Device:hasClipboard(), callback = function() Device.input.setClipboardText(cleanupSelectedText(_self.selected_text.text)) end, } end, ["04_search"] = function(_self) return { text = _("Search"), callback = function() _self:onHighlightSearch() UIManager:close(self.highlight_dialog) -- We don't call _self:onClose(), crengine will highlight -- search matches on the current page, and self:clear() -- would redraw and remove crengine native highlights end, } end, -- then information lookup functions, putting on the left those that -- depend on an internet connection. ["05_wikipedia"] = function(_self) return { text = _("Wikipedia"), callback = function() UIManager:scheduleIn(0.1, function() _self:lookupWikipedia() -- We don't call _self:onClose(), we need the highlight -- to still be there, as we may Highlight it from the -- dict lookup widget end) end, } end, ["06_dictionary"] = function(_self) return { text = _("Dictionary"), callback = function() _self:onHighlightDictLookup() -- We don't call _self:onClose(), same reason as above end, } end, ["07_translate"] = function(_self) return { text = _("Translate"), callback = function() _self:translate(_self.selected_text) -- We don't call _self:onClose(), so one can still see -- the highlighted text when moving the translated -- text window, and also if NetworkMgr:promptWifiOn() -- is needed, so the user can just tap again on this -- button and does not need to select the text again. end, } end, } -- Text export functions if applicable. if not self.ui.document.info.has_pages then self:addToHighlightDialog("08_view_html", function(_self) return { text = _("View HTML"), callback = function() _self:viewSelectionHTML() end, } end) end if Device:canShareText() then self:addToHighlightDialog("09_share_text", function(_self) return { text = _("Share Text"), callback = function() local text = cleanupSelectedText(_self.selected_text.text) -- call self:onClose() before calling the android framework _self:onClose() Device.doShareText(text) end, } end) end -- Links if self.selected_link ~= nil then self:addToHighlightDialog("10_follow_link", function(_self) return { text = _("Follow Link"), callback = function() local link = _self.selected_link.link or _self.selected_link _self.ui.link:onGotoLink(link) _self:onClose() end, } end) end self.ui:registerPostInitCallback(function() self.ui.menu:registerToMainMenu(self) end) end function ReaderHighlight:setupTouchZones() -- deligate gesture listener to readerui self.ges_events = {} self.onGesture = nil if not Device:isTouchDevice() then return end local hold_pan_rate = G_reader_settings:readSetting("hold_pan_rate") if not hold_pan_rate then hold_pan_rate = Screen.low_pan_rate and 5.0 or 30.0 end self.ui:registerTouchZones({ { id = "readerhighlight_tap", ges = "tap", screen_zone = { ratio_x = 0, ratio_y = 0, ratio_w = 1, ratio_h = 1, }, overrides = { -- Tap on existing highlights have priority over -- everything but tap on links (as links can be -- part of some highlighted text) "tap_top_left_corner", "tap_top_right_corner", "tap_left_bottom_corner", "tap_right_bottom_corner", "readerfooter_tap", "readerconfigmenu_ext_tap", "readerconfigmenu_tap", "readermenu_ext_tap", "readermenu_tap", "tap_forward", "tap_backward", }, handler = function(ges) return self:onTap(nil, ges) end }, { id = "readerhighlight_hold", ges = "hold", screen_zone = { ratio_x = 0, ratio_y = 0, ratio_w = 1, ratio_h = 1, }, overrides = { "readerfooter_hold", }, handler = function(ges) return self:onHold(nil, ges) end }, { id = "readerhighlight_hold_release", ges = "hold_release", screen_zone = { ratio_x = 0, ratio_y = 0, ratio_w = 1, ratio_h = 1, }, handler = function() return self:onHoldRelease() end }, { id = "readerhighlight_hold_pan", ges = "hold_pan", rate = hold_pan_rate, screen_zone = { ratio_x = 0, ratio_y = 0, ratio_w = 1, ratio_h = 1, }, handler = function(ges) return self:onHoldPan(nil, ges) end }, }) end function ReaderHighlight:onReaderReady() self:setupTouchZones() end function ReaderHighlight:addToMainMenu(menu_items) -- insert table to main reader menu menu_items.highlight_options = { text = _("Highlighting"), sub_item_table = self:genHighlightDrawerMenu(), } if self.document.info.has_pages then menu_items.panel_zoom_options = { text = _("Panel zoom (manga/comic)"), sub_item_table = self:genPanelZoomMenu(), } end menu_items.translation_settings = Translator:genSettingsMenu() end local highlight_style = { lighten = _("Lighten"), underscore = _("Underline"), invert = _("Invert"), } function ReaderHighlight:genPanelZoomMenu() return { { text = _("Allow panel zoom"), checked_func = function() return self.panel_zoom_enabled end, callback = function() self:onTogglePanelZoomSetting() end, hold_callback = function() local ext = util.getFileNameSuffix(self.ui.document.file) local curr_val = G_reader_settings:getSettingForExt("panel_zoom_enabled", ext) G_reader_settings:saveSettingForExt("panel_zoom_enabled", not curr_val, ext) end, separator = true, }, { text = _("Fall back to text selection"), checked_func = function() return self.panel_zoom_fallback_to_text_selection end, callback = function() self:onToggleFallbackTextSelection() end, hold_callback = function() local ext = util.getFileNameSuffix(self.ui.document.file) G_reader_settings:saveSettingForExt("panel_zoom_fallback_to_text_selection", self.panel_zoom_fallback_to_text_selection, ext) end, separator = true, }, } end function ReaderHighlight:genHighlightDrawerMenu() local get_highlight_style = function(style) return { text = highlight_style[style], checked_func = function() return self.view.highlight.saved_drawer == style end, enabled_func = function() return not self.view.highlight.disabled end, callback = function() self.view.highlight.saved_drawer = style end } end return { { text = _("Allow highlighting"), checked_func = function() return not self.view.highlight.disabled end, callback = function() self.view.highlight.disabled = not self.view.highlight.disabled end, hold_callback = function(touchmenu_instance) self:toggleDefault() end, separator = true, }, get_highlight_style("lighten"), get_highlight_style("underscore"), get_highlight_style("invert"), } end -- Returns a unique id, that can be provided on delayed call to :clear(id) -- to ensure current highlight has not already been cleared, and that we -- are not going to clear a new highlight function ReaderHighlight:getClearId() self.clear_id = TimeVal.now() -- can act as a unique id return self.clear_id end function ReaderHighlight:clear(clear_id) if clear_id then -- should be provided by delayed call to clear() if clear_id ~= self.clear_id then -- if clear_id is no more valid, highlight has already been -- cleared since this clear_id was given return end end self.clear_id = nil -- invalidate id if self.ui.document.info.has_pages then self.view.highlight.temp = {} else self.ui.document:clearSelection() end if self.restore_page_mode_func then self.restore_page_mode_func() self.restore_page_mode_func = nil end self.selected_text_start_xpointer = nil if self.hold_pos then self.hold_pos = nil self.selected_text = nil UIManager:setDirty(self.dialog, "ui") return true end end function ReaderHighlight:onClearHighlight() self:clear() return true end function ReaderHighlight:onTap(_, ges) -- We only actually need to clear if we have something to clear in the first place. -- (We mainly want to avoid CRe's clearSelection, -- which may incur a redraw as it invalidates the cache, c.f., #6854) -- ReaderHighlight:clear can only return true if self.hold_pos was set anyway. local cleared = self.hold_pos and self:clear() -- We only care about potential taps on existing highlights, not on taps that closed a highlight menu. if not cleared and ges then if self.ui.document.info.has_pages then return self:onTapPageSavedHighlight(ges) else return self:onTapXPointerSavedHighlight(ges) end end end function ReaderHighlight:onTapPageSavedHighlight(ges) local pages = self.view:getCurrentPageList() local pos = self.view:screenToPageTransform(ges.pos) for key, page in pairs(pages) do local items = self.view.highlight.saved[page] if items then for i = 1, #items do local pos0, pos1 = items[i].pos0, items[i].pos1 local boxes = self.ui.document:getPageBoxesFromPositions(page, pos0, pos1) if boxes then for index, box in pairs(boxes) do if inside_box(pos, box) then logger.dbg("Tap on highlight") return self:onShowHighlightDialog(page, i) end end end end end end end function ReaderHighlight:onTapXPointerSavedHighlight(ges) -- Getting screen boxes is done for each tap on screen (changing pages, -- showing menu...). We might want to cache these boxes per page (and -- clear that cache when page layout change or highlights are added -- or removed). local cur_view_top, cur_view_bottom local pos = self.view:screenToPageTransform(ges.pos) -- NOTE: By now, pos.page is set, but if a highlight spans across multiple pages, -- it's stored under the hash of its *starting* point, -- so we can't just check the current page, hence the giant hashwalk of death... -- We can't even limit the walk to page <= pos.page, -- because pos.page isn't super accurate in continuous mode -- (it's the page number for what's it the topleft corner of the screen, -- i.e., often a bit earlier)... for page, items in pairs(self.view.highlight.saved) do if items then for i = 1, #items do local item = items[i] local pos0, pos1 = item.pos0, item.pos1 -- document:getScreenBoxesFromPositions() is expensive, so we -- first check this item is on current page if not cur_view_top then -- Even in page mode, it's safer to use pos and ui.dimen.h -- than pages' xpointers pos, even if ui.dimen.h is a bit -- larger than pages' heights cur_view_top = self.ui.document:getCurrentPos() if self.view.view_mode == "page" and self.ui.document:getVisiblePageCount() > 1 then cur_view_bottom = cur_view_top + 2 * self.ui.dimen.h else cur_view_bottom = cur_view_top + self.ui.dimen.h end end local spos0 = self.ui.document:getPosFromXPointer(pos0) local spos1 = self.ui.document:getPosFromXPointer(pos1) local start_pos = math.min(spos0, spos1) local end_pos = math.max(spos0, spos1) if start_pos <= cur_view_bottom and end_pos >= cur_view_top then local boxes = self.ui.document:getScreenBoxesFromPositions(pos0, pos1, true) -- get_segments=true if boxes then for index, box in pairs(boxes) do if inside_box(pos, box) then logger.dbg("Tap on highlight") return self:onShowHighlightDialog(page, i) end end end end end end end end function ReaderHighlight:updateHighlight(page, index, side, direction, move_by_char) if self.ui.document.info.has_pages then -- we do this only if it's epub file return end local highlight = self.view.highlight.saved[page][index] local highlight_time = highlight.datetime local highlight_beginning = highlight.pos0 local highlight_end = highlight.pos1 if side == 0 then -- we move pos0 local updated_highlight_beginning if direction == 1 then -- move highlight to the right if move_by_char then updated_highlight_beginning = self.ui.document:getNextVisibleChar(highlight_beginning) else updated_highlight_beginning = self.ui.document:getNextVisibleWordStart(highlight_beginning) end else -- move highlight to the left if move_by_char then updated_highlight_beginning = self.ui.document:getPrevVisibleChar(highlight_beginning) else updated_highlight_beginning = self.ui.document:getPrevVisibleWordStart(highlight_beginning) end end if updated_highlight_beginning then local order = self.ui.document:compareXPointers(updated_highlight_beginning, highlight_end) if order and order > 0 then -- only if beginning did not go past end self.view.highlight.saved[page][index].pos0 = updated_highlight_beginning end end else -- we move pos1 local updated_highlight_end if direction == 1 then -- move highlight to the right if move_by_char then updated_highlight_end = self.ui.document:getNextVisibleChar(highlight_end) else updated_highlight_end = self.ui.document:getNextVisibleWordEnd(highlight_end) end else -- move highlight to the left if move_by_char then updated_highlight_end = self.ui.document:getPrevVisibleChar(highlight_end) else updated_highlight_end = self.ui.document:getPrevVisibleWordEnd(highlight_end) end end if updated_highlight_end then local order = self.ui.document:compareXPointers(highlight_beginning, updated_highlight_end) if order and order > 0 then -- only if end did not go back past beginning self.view.highlight.saved[page][index].pos1 = updated_highlight_end end end end local new_beginning = self.view.highlight.saved[page][index].pos0 local new_end = self.view.highlight.saved[page][index].pos1 local new_text = self.ui.document:getTextFromXPointers(new_beginning, new_end) local new_chapter = self.ui.toc:getTocTitleByPage(new_beginning) self.view.highlight.saved[page][index].text = cleanupSelectedText(new_text) self.view.highlight.saved[page][index].chapter = new_chapter local new_highlight = self.view.highlight.saved[page][index] self.ui.bookmark:updateBookmark({ page = highlight_beginning, datetime = highlight_time, updated_highlight = new_highlight }, true) if side == 0 then -- Ensure we show the page with the new beginning of highlight if not self.ui.document:isXPointerInCurrentPage(new_beginning) then self.ui:handleEvent(Event:new("GotoXPointer", new_beginning)) end else -- Ensure we show the page with the new end of highlight if not self.ui.document:isXPointerInCurrentPage(new_end) then if self.view.view_mode == "page" then self.ui:handleEvent(Event:new("GotoXPointer", new_end)) else -- Not easy to get the y that would show the whole line -- containing new_end. So, we scroll so that new_end -- is at 2/3 of the screen. local end_y = self.ui.document:getPosFromXPointer(new_end) local top_y = end_y - math.floor(Screen:getHeight() * 2/3) self.ui.rolling:_gotoPos(top_y) end end end UIManager:setDirty(self.dialog, "ui") end function ReaderHighlight:onShowHighlightDialog(page, index) local buttons = { { { text = _("Delete"), callback = function() self:deleteHighlight(page, index) -- other part outside of the dialog may be dirty UIManager:close(self.edit_highlight_dialog, "ui") end, }, { text = _("Edit"), callback = function() self:editHighlight(page, index) UIManager:close(self.edit_highlight_dialog) end, }, { text = _("…"), callback = function() self.selected_text = self.view.highlight.saved[page][index] self:onShowHighlightMenu() UIManager:close(self.edit_highlight_dialog) end, }, } } if not self.ui.document.info.has_pages then local start_prev = "◁⇱" local start_next = "⇱▷" local end_prev = "◁⇲" local end_next = "⇲▷" if BD.mirroredUILayout() then -- Sadly, there's only north west & south east arrow to corner, -- north east and south west do not exist in Unicode. start_prev, start_next = BD.ltr(start_next), BD.ltr(start_prev) end_prev, end_next = BD.ltr(end_next), BD.ltr(end_prev) end table.insert(buttons, { { text = start_prev, callback = function() self:updateHighlight(page, index, 0, -1, false) end, hold_callback = function() self:updateHighlight(page, index, 0, -1, true) return true end }, { text = start_next, callback = function() self:updateHighlight(page, index, 0, 1, false) end, hold_callback = function() self:updateHighlight(page, index, 0, 1, true) return true end }, { text = end_prev, callback = function() self:updateHighlight(page, index, 1, -1, false) end, hold_callback = function() self:updateHighlight(page, index, 1, -1, true) end }, { text = end_next, callback = function() self:updateHighlight(page, index, 1, 1, false) end, hold_callback = function() self:updateHighlight(page, index, 1, 1, true) end } }) end self.edit_highlight_dialog = ButtonDialog:new{ buttons = buttons } UIManager:show(self.edit_highlight_dialog) return true end function ReaderHighlight:addToHighlightDialog(idx, fn_button) -- fn_button is a function that takes the ReaderHighlight instance -- as argument, and returns a table describing the button to be added. self._highlight_buttons[idx] = fn_button end function ReaderHighlight:removeFromHighlightDialog(idx) local button = self._highlight_buttons[idx] self._highlight_buttons[idx] = nil return button end function ReaderHighlight:onShowHighlightMenu() local highlight_buttons = {{}} local columns = 2 for idx, fn_button in ffiUtil.orderedPairs(self._highlight_buttons) do if #highlight_buttons[#highlight_buttons] >= columns then table.insert(highlight_buttons, {}) end table.insert(highlight_buttons[#highlight_buttons], fn_button(self)) logger.dbg("ReaderHighlight", idx..": line "..#highlight_buttons..", col "..#highlight_buttons[#highlight_buttons]) end self.highlight_dialog = ButtonDialog:new{ buttons = highlight_buttons, tap_close_callback = function() self:handleEvent(Event:new("Tap")) end, } UIManager:show(self.highlight_dialog) end function ReaderHighlight:_resetHoldTimer(clear) if clear then self.hold_last_tv = nil else self.hold_last_tv = TimeVal.now() end end function ReaderHighlight:onTogglePanelZoomSetting(arg, ges) if not self.document.info.has_pages then return end self.panel_zoom_enabled = not self.panel_zoom_enabled end function ReaderHighlight:onToggleFallbackTextSelection(arg, ges) if not self.document.info.has_pages then return end self.panel_zoom_fallback_to_text_selection = not self.panel_zoom_fallback_to_text_selection end function ReaderHighlight:onPanelZoom(arg, ges) self:clear() local hold_pos = self.view:screenToPageTransform(ges.pos) if not hold_pos then return false end -- outside page boundary local rect = self.ui.document:getPanelFromPage(hold_pos.page, hold_pos) if not rect then return false end -- panel not found, return local image = self.ui.document:getPagePart(hold_pos.page, rect, 0) if image then local ImageViewer = require("ui/widget/imageviewer") local imgviewer = ImageViewer:new{ image = image, with_title_bar = false, fullscreen = true, } UIManager:show(imgviewer) return true end return false end function ReaderHighlight:onHold(arg, ges) if self.document.info.has_pages and self.panel_zoom_enabled then local res = self:onPanelZoom(arg, ges) if res or not self.panel_zoom_fallback_to_text_selection then return res end end -- disable hold gesture if highlighting is disabled if self.view.highlight.disabled then return false end self:clear() -- clear previous highlight (delayed clear may not have done it yet) self.hold_ges_pos = ges.pos -- remember hold original gesture position self.hold_pos = self.view:screenToPageTransform(ges.pos) logger.dbg("hold position in page", self.hold_pos) if not self.hold_pos then logger.dbg("not inside page area") return false end -- check if we were holding on an image -- we provide want_frames=true, so we get a list of images for -- animated GIFs (supported by ImageViewer) local image = self.ui.document:getImageFromPosition(self.hold_pos, true) if image then logger.dbg("hold on image") local ImageViewer = require("ui/widget/imageviewer") local imgviewer = ImageViewer:new{ image = image, -- title_text = _("Document embedded image"), -- No title, more room for image with_title_bar = false, fullscreen = true, } UIManager:show(imgviewer) return true end -- otherwise, we must be holding on text local ok, word = pcall(self.ui.document.getWordFromPosition, self.ui.document, self.hold_pos) if ok and word then logger.dbg("selected word:", word) self.selected_word = word local link = self.ui.link:getLinkFromGes(ges) self.selected_link = nil if link then logger.dbg("link:", link) self.selected_link = link end if self.ui.document.info.has_pages then local boxes = {} table.insert(boxes, self.selected_word.sbox) self.view.highlight.temp[self.hold_pos.page] = boxes -- Unfortunately, getWordFromPosition() may not return good coordinates, -- so refresh the whole page UIManager:setDirty(self.dialog, "ui") else -- With crengine, getWordFromPosition() does return good coordinates UIManager:setDirty(self.dialog, "ui", self.selected_word.sbox) end self:_resetHoldTimer() if word.pos0 then -- Remember original highlight start position, so we can show -- a marker when back from across-pages text selection, which -- is handled in onHoldPan() self.selected_text_start_xpointer = word.pos0 end return true end return false end function ReaderHighlight:onHoldPan(_, ges) if self.hold_pos == nil then logger.dbg("no previous hold position") self:_resetHoldTimer(true) return true end local page_area = self.view:getScreenPageArea(self.hold_pos.page) if ges.pos:notIntersectWith(page_area) then logger.dbg("not inside page area", ges, page_area) self:_resetHoldTimer() return true end self.holdpan_pos = self.view:screenToPageTransform(ges.pos) logger.dbg("holdpan position in page", self.holdpan_pos) if not self.ui.document.info.has_pages and self.selected_text_start_xpointer then -- With CreDocuments, allow text selection across multiple pages -- by (temporarily) switching to scroll mode when panning to the -- top left or bottom right corners. local mirrored_reading = BD.mirroredUILayout() if self.ui.rolling and self.ui.rolling.inverse_reading_order then mirrored_reading = not mirrored_reading end local is_in_prev_page_corner, is_in_next_page_corner if mirrored_reading then -- Note: this might not be really usable, as crengine native selection -- is not adapted to RTL text -- top right corner is_in_prev_page_corner = self.holdpan_pos.y < 1/8*Screen:getHeight() and self.holdpan_pos.x > 7/8*Screen:getWidth() -- bottom left corner is_in_next_page_corner = self.holdpan_pos.y > 7/8*Screen:getHeight() and self.holdpan_pos.x < 1/8*Screen:getWidth() else -- default in LTR UI with no inverse_reading_order -- top left corner is_in_prev_page_corner = self.holdpan_pos.y < 1/8*Screen:getHeight() and self.holdpan_pos.x < 1/8*Screen:getWidth() -- bottom right corner is_in_next_page_corner = self.holdpan_pos.y > 7/8*Screen:getHeight() and self.holdpan_pos.x > 7/8*Screen:getWidth() end if is_in_prev_page_corner or is_in_next_page_corner then self:_resetHoldTimer() if self.was_in_some_corner then -- Do nothing, wait for the user to move his finger out of that corner return true end self.was_in_some_corner = true if self.ui.document:getVisiblePageCount() == 1 then -- single page mode -- We'll adjust hold_pos.y after the mode switch and the scroll -- so it's accurate in the new screen coordinates local orig_y = self.ui.document:getScreenPositionFromXPointer(self.selected_text_start_xpointer) if self.view.view_mode ~= "scroll" then -- Switch from page mode to scroll mode local restore_page_mode_xpointer = self.ui.document:getXPointer() -- top of current page self.restore_page_mode_func = function() self.ui:handleEvent(Event:new("SetViewMode", "page")) self.ui.rolling:onGotoXPointer(restore_page_mode_xpointer, self.selected_text_start_xpointer) end self.ui:handleEvent(Event:new("SetViewMode", "scroll")) end -- (using rolling:onGotoViewRel(1/3) has some strange side effects) local scroll_distance = math.floor(Screen:getHeight() * 1/3) local move_y = is_in_next_page_corner and scroll_distance or -scroll_distance self.ui.rolling:_gotoPos(self.ui.document:getCurrentPos() + move_y) local new_y = self.ui.document:getScreenPositionFromXPointer(self.selected_text_start_xpointer) self.hold_pos.y = self.hold_pos.y - orig_y + new_y UIManager:setDirty(self.dialog, "ui") return true else -- two pages mode -- We don't switch to scroll mode: we just turn 1 page to -- allow continuing the selection. -- Unlike in 1-page mode, we have a limitation here: we can't adjust -- the selection to further than current page and prev/next one. -- So don't handle another corner if we already handled one: -- Note that this feature won't work well with the RTL UI or -- if inverse_reading_order as crengine currently always displays -- the first page on the left and the second on the right in -- dual page mode. if self.restore_page_mode_func then return true end -- Also, we are not able to move hold_pos.x out of screen, -- so if we started on the right page, ignore top left corner, -- and if we started on the left page, ignore bottom right corner. local screen_half_width = math.floor(Screen:getWidth() * 0.5) if self.hold_pos.x >= screen_half_width and is_in_prev_page_corner then return true elseif self.hold_pos.x <= screen_half_width and is_in_next_page_corner then return true end -- To be able to browse half-page when 2 visible pages as 1 page number, -- we must work with internal page numbers local cur_page = self.ui.document:getCurrentPage(true) local restore_page_mode_xpointer = self.ui.document:getXPointer() -- top of current page self.ui.document.no_page_sync = true -- avoid CreDocument:drawCurrentViewByPage() to resync page self.restore_page_mode_func = function() self.ui.document.no_page_sync = nil self.ui.rolling:onGotoXPointer(restore_page_mode_xpointer, self.selected_text_start_xpointer) end if is_in_next_page_corner then -- bottom right corner in LTR UI self.ui.rolling:_gotoPage(cur_page + 1, true, true) -- no odd left page enforcement self.hold_pos.x = self.hold_pos.x - screen_half_width else -- top left corner in RTL UI self.ui.rolling:_gotoPage(cur_page - 1, true, true) -- no odd left page enforcement self.hold_pos.x = self.hold_pos.x + screen_half_width end UIManager:setDirty(self.dialog, "ui") return true end else self.was_in_some_corner = nil end end local old_text = self.selected_text and self.selected_text.text self.selected_text = self.ui.document:getTextFromPositions(self.hold_pos, self.holdpan_pos) if self.selected_text and self.selected_text.pos0 then if not self.selected_text_start_xpointer then -- This should have been set in onHold(), where we would get -- a precise pos0 on the first word selected. -- Do it here too in case onHold() missed it, but it could be -- less precise (getTextFromPositions() does order pos0 and pos1, -- so it's not certain pos0 is where we started from; we get -- the ones from the first pan, and if it is not small enough -- and spans quite some height, the marker could point away -- from the start position) self.selected_text_start_xpointer = self.selected_text.pos0 end end if self.selected_text and old_text and old_text == self.selected_text.text then -- no modification return end self:_resetHoldTimer() -- selection updated logger.dbg("selected text:", self.selected_text) if self.selected_text then self.view.highlight.temp[self.hold_pos.page] = self.selected_text.sboxes -- remove selected word if hold moves out of word box if not self.selected_text.sboxes or #self.selected_text.sboxes == 0 then self.selected_word = nil elseif self.selected_word and not self.selected_word.sbox:contains(self.selected_text.sboxes[1]) or #self.selected_text.sboxes > 1 then self.selected_word = nil end end UIManager:setDirty(self.dialog, "ui") end local info_message_ocr_text = _([[ No OCR results or no language data. KOReader has a build-in OCR engine for recognizing words in scanned PDF and DjVu documents. In order to use OCR in scanned pages, you need to install tesseract trained data for your document language. You can download language data files for version 3.04 from https://tesseract-ocr.github.io/tessdoc/Data-Files Copy the language data files for Tesseract 3.04 (e.g., eng.traineddata for English and spa.traineddata for Spanish) into koreader/data/tessdata]]) function ReaderHighlight:lookup(selected_word, selected_link) -- if we extracted text directly if selected_word.word then local word_box = self.view:pageToScreenTransform(self.hold_pos.page, selected_word.sbox) self.ui:handleEvent(Event:new("LookupWord", selected_word.word, false, word_box, self, selected_link)) -- or we will do OCR elseif selected_word.sbox and self.hold_pos then local word = self.ui.document:getOCRWord(self.hold_pos.page, selected_word) logger.dbg("OCRed word:", word) if word and word ~= "" then local word_box = self.view:pageToScreenTransform(self.hold_pos.page, selected_word.sbox) self.ui:handleEvent(Event:new("LookupWord", word, false, word_box, self, selected_link)) else UIManager:show(InfoMessage:new{ text = info_message_ocr_text, }) end end end function ReaderHighlight:viewSelectionHTML(debug_view) if self.ui.document.info.has_pages then return end if self.selected_text and self.selected_text.pos0 and self.selected_text.pos1 then -- For available flags, see the "#define WRITENODEEX_*" in crengine/src/lvtinydom.cpp -- Start with valid and classic displayed HTML (with only block nodes indented), -- including styles found in <HEAD>, linked CSS files content, and misc info. local html_flags = 0x6830 if not debug_view then debug_view = 0 end if debug_view == 1 then -- Each node on a line, with markers and numbers of skipped chars and siblings shown, -- with possibly invalid HTML (text nodes not escaped) html_flags = 0x6B5A elseif debug_view == 2 then -- Additionally see rendering methods of each node html_flags = 0x6F5A elseif debug_view == 3 then -- Or additionally see unicode codepoint of each char html_flags = 0x6B5E end local html, css_files = self.ui.document:getHTMLFromXPointers(self.selected_text.pos0, self.selected_text.pos1, html_flags, true) if html then -- Make some invisible chars visible if debug_view >= 1 then html = html:gsub("\xC2\xA0", "␣") -- no break space: open box html = html:gsub("\xC2\xAD", "⋅") -- soft hyphen: dot operator (smaller than middle dot ·) -- Prettify inlined CSS (from <HEAD>, put in an internal -- <body><stylesheet> element by crengine (the opening tag may -- include some href=, or end with " ~X>" with some html_flags) -- (We do that in debug_view mode only: as this may increase -- the height of this section, we don't want to have to scroll -- many pages to get to the HTML content on the initial view.) html = html:gsub("(<stylesheet[^>]*>)%s*(.-)%s*(</stylesheet>)", function(pre, css_text, post) return pre .. "\n" .. util.prettifyCSS(css_text) .. post end) end local TextViewer = require("ui/widget/textviewer") local Font = require("ui/font") local textviewer local buttons_table = {} if css_files then for i=1, #css_files do local button = { text = T(_("View %1"), BD.filepath(css_files[i])), callback = function() local css_text = self.ui.document:getDocumentFileContent(css_files[i]) local cssviewer cssviewer = TextViewer:new{ title = css_files[i], text = css_text or _("Failed getting CSS content"), text_face = Font:getFace("smallinfont"), justified = false, para_direction_rtl = false, auto_para_direction = false, buttons_table = { {{ text = _("Prettify"), enabled = css_text and true or false, callback = function() UIManager:close(cssviewer) UIManager:show(TextViewer:new{ title = css_files[i], text = util.prettifyCSS(css_text), text_face = Font:getFace("smallinfont"), justified = false, para_direction_rtl = false, auto_para_direction = false, }) end, }}, {{ text = _("Close"), callback = function() UIManager:close(cssviewer) end, }}, } } UIManager:show(cssviewer) end, } -- One button per row, too make room for the possibly long css filename table.insert(buttons_table, {button}) end end local next_debug_text local next_debug_view = debug_view + 1 if next_debug_view == 1 then next_debug_text = _("Switch to debug view") elseif next_debug_view == 2 then next_debug_text = _("Switch to rendering debug view") elseif next_debug_view == 3 then next_debug_text = _("Switch to unicode debug view") else next_debug_view = 0 next_debug_text = _("Switch to standard view") end table.insert(buttons_table, {{ text = next_debug_text, callback = function() UIManager:close(textviewer) self:viewSelectionHTML(next_debug_view) end, }}) table.insert(buttons_table, {{ text = _("Close"), callback = function() UIManager:close(textviewer) end, }}) textviewer = TextViewer:new{ title = _("Selection HTML"), text = html, text_face = Font:getFace("smallinfont"), justified = false, para_direction_rtl = false, auto_para_direction = false, buttons_table = buttons_table, } UIManager:show(textviewer) else UIManager:show(InfoMessage:new{ text = _("Failed getting HTML for selection"), }) end end end function ReaderHighlight:translate(selected_text) if selected_text.text ~= "" then self:onTranslateText(selected_text.text) -- or we will do OCR else local text = self.ui.document:getOCRText(self.hold_pos.page, selected_text) logger.dbg("OCRed text:", text) if text and text ~= "" then self:onTranslateText(text) else UIManager:show(InfoMessage:new{ text = info_message_ocr_text, }) end end end function ReaderHighlight:onTranslateText(text) Translator:showTranslation(text) end function ReaderHighlight:onHoldRelease() local long_final_hold = false if self.hold_last_tv then local hold_duration = TimeVal.now() - self.hold_last_tv hold_duration = hold_duration.sec + hold_duration.usec/1000000 if hold_duration > 3.0 then -- We stayed 3 seconds before release without updating selection long_final_hold = true end self.hold_last_tv = nil end if self.selected_word then -- single-word selection if long_final_hold or G_reader_settings:isTrue("highlight_action_on_single_word") then -- Force a 0-distance pan to have a self.selected_text with this word, -- which will enable the highlight menu or action instead of dict lookup self:onHoldPan(nil, {pos=self.hold_ges_pos}) end end if self.selected_text then local default_highlight_action = G_reader_settings:readSetting("default_highlight_action") if long_final_hold or not default_highlight_action then -- bypass default action and show popup if long final hold self:onShowHighlightMenu() elseif default_highlight_action == "highlight" then self:saveHighlight() self:onClose() elseif default_highlight_action == "translate" then self:translate(self.selected_text) self:onClose() elseif default_highlight_action == "wikipedia" then self:lookupWikipedia() self:onClose() elseif default_highlight_action == "dictionary" then self:onHighlightDictLookup() self:onClose() elseif default_highlight_action == "search" then self:onHighlightSearch() -- No self:onClose() to not remove the selected text -- which will have been the first search result end elseif self.selected_word then self:lookup(self.selected_word, self.selected_link) self.selected_word = nil end return true end function ReaderHighlight:onCycleHighlightAction() local next_actions = { highlight = "translate", translate = "wikipedia", wikipedia = "dictionary", dictionary = "search", search = nil, } local current_action = G_reader_settings:readSetting("default_highlight_action") if not current_action then G_reader_settings:saveSetting("default_highlight_action", "highlight") UIManager:show(Notification:new{ text = _("Default highlight action changed to 'highlight'."), }) else local next_action = next_actions[current_action] G_reader_settings:saveSetting("default_highlight_action", next_action) UIManager:show(Notification:new{ text = T(_("Default highlight action changed to '%1'."), (next_action or "default")), }) end return true end function ReaderHighlight:onCycleHighlightStyle() local next_actions = { lighten = "underscore", underscore = "invert", invert = "lighten" } self.view.highlight.saved_drawer = next_actions[self.view.highlight.saved_drawer] self.ui.doc_settings:saveSetting("highlight_drawer", self.view.highlight.saved_drawer) UIManager:show(Notification:new{ text = T(_("Default highlight style changed to '%1'."), self.view.highlight.saved_drawer), }) return true end function ReaderHighlight:highlightFromHoldPos() if self.hold_pos then if not self.selected_text then self.selected_text = self.ui.document:getTextFromPositions(self.hold_pos, self.hold_pos) logger.dbg("selected text:", self.selected_text) end end end function ReaderHighlight:onHighlight() self:saveHighlight() end function ReaderHighlight:onUnhighlight(bookmark_item) local page local sel_text local sel_pos0 local datetime local idx if bookmark_item then -- called from Bookmarks menu onHold page = bookmark_item.page sel_text = bookmark_item.notes sel_pos0 = bookmark_item.pos0 datetime = bookmark_item.datetime else -- called from DictQuickLookup Unhighlight button page = self.hold_pos.page sel_text = cleanupSelectedText(self.selected_text.text) sel_pos0 = self.selected_text.pos0 end if self.ui.document.info.has_pages then -- We can safely use page for index = 1, #self.view.highlight.saved[page] do local highlight = self.view.highlight.saved[page][index] -- pos0 are tables and can't be compared directly, except when from -- DictQuickLookup where these are the same object. -- If bookmark_item provided, just check datetime if highlight.text == sel_text and ( (datetime == nil and highlight.pos0 == sel_pos0) or (datetime ~= nil and highlight.datetime == datetime)) then idx = index break end end else -- page is a xpointer -- The original page could be found in bookmark_item.text, but -- no more if it has been renamed: we need to loop through all -- highlights on all page slots for p, highlights in pairs(self.view.highlight.saved) do for index = 1, #highlights do local highlight = highlights[index] -- pos0 are strings and can be compared directly if highlight.text == sel_text and ( (datetime == nil and highlight.pos0 == sel_pos0) or (datetime ~= nil and highlight.datetime == datetime)) then page = p -- this is the original page slot idx = index break end end if idx then break end end end if bookmark_item and not idx then logger.warn("unhighlight: bookmark_item not found among highlights", bookmark_item) -- Remove it from bookmarks anyway, so we're not stuck with an -- unremovable bookmark self.ui.bookmark:removeBookmark(bookmark_item) return end logger.dbg("found highlight to delete on page", page, idx) self:deleteHighlight(page, idx, bookmark_item) return true end function ReaderHighlight:getHighlightBookmarkItem() if self.hold_pos and not self.selected_text then self:highlightFromHoldPos() end if self.selected_text and self.selected_text.pos0 and self.selected_text.pos1 then local datetime = os.date("%Y-%m-%d %H:%M:%S") local page = self.ui.document.info.has_pages and self.hold_pos.page or self.selected_text.pos0 local chapter_name = self.ui.toc:getTocTitleByPage(page) return { page = page, pos0 = self.selected_text.pos0, pos1 = self.selected_text.pos1, datetime = datetime, notes = cleanupSelectedText(self.selected_text.text), highlighted = true, chapter = chapter_name, } end end function ReaderHighlight:saveHighlight() self.ui:handleEvent(Event:new("AddHighlight")) logger.dbg("save highlight") local page = self.hold_pos.page if self.hold_pos and self.selected_text and self.selected_text.pos0 and self.selected_text.pos1 then if not self.view.highlight.saved[page] then self.view.highlight.saved[page] = {} end local datetime = os.date("%Y-%m-%d %H:%M:%S") local pg_or_xp = self.ui.document.info.has_pages and self.hold_pos.page or self.selected_text.pos0 local chapter_name = self.ui.toc:getTocTitleByPage(pg_or_xp) local hl_item = { datetime = datetime, text = cleanupSelectedText(self.selected_text.text), pos0 = self.selected_text.pos0, pos1 = self.selected_text.pos1, pboxes = self.selected_text.pboxes, drawer = self.view.highlight.saved_drawer, chapter = chapter_name } table.insert(self.view.highlight.saved[page], hl_item) local bookmark_item = self:getHighlightBookmarkItem() if bookmark_item then self.ui.bookmark:addBookmark(bookmark_item) end --[[ -- disable exporting highlights to My Clippings -- since it's not portable and there is a better Evernote plugin -- to do the same thing if self.selected_text.text ~= "" then self:exportToClippings(page, hl_item) end --]] if self.selected_text.pboxes then self:exportToDocument(page, hl_item) end return page, #self.view.highlight.saved[page] end end --[[ function ReaderHighlight:exportToClippings(page, item) logger.dbg("export highlight to clippings", item) local clippings = io.open("/mnt/us/documents/My Clippings.txt", "a+") if clippings and item.text then local current_locale = os.setlocale() os.setlocale("C") clippings:write(self.document.file:gsub("(.*/)(.*)", "%2").."\n") clippings:write("- KOReader Highlight Page "..page.." ") clippings:write("| Added on "..os.date("%A, %b %d, %Y %I:%M:%S %p\n\n")) -- My Clippings only holds one line of highlight clippings:write(item["text"]:gsub("\n", " ").."\n") clippings:write("==========\n") clippings:close() os.setlocale(current_locale) end end --]] function ReaderHighlight:exportToDocument(page, item) local setting = G_reader_settings:readSetting("save_document") if setting == "disable" then return end logger.dbg("export highlight to document", item) local can_write = self.ui.document:saveHighlight(page, item) if can_write == false and not self.warned_once then self.warned_once = true UIManager:show(InfoMessage:new{ text = _([[ Highlights in this document will be saved in the settings file, but they won't be written in the document itself because the file is in a read-only location. If you wish your highlights to be saved in the document, just move it to a writable directory first.]]), timeout = 5, }) end end function ReaderHighlight:addNote() local page, index = self:saveHighlight() self:editHighlight(page, index) UIManager:close(self.edit_highlight_dialog) self.ui:handleEvent(Event:new("AddNote")) end function ReaderHighlight:lookupWikipedia() if self.selected_text then self.ui:handleEvent(Event:new("LookupWikipedia", cleanupSelectedText(self.selected_text.text))) end end function ReaderHighlight:onHighlightSearch() logger.dbg("search highlight") self:highlightFromHoldPos() if self.selected_text then local text = util.stripPunctuation(cleanupSelectedText(self.selected_text.text)) self.ui:handleEvent(Event:new("ShowSearchDialog", text)) end end function ReaderHighlight:onHighlightDictLookup() logger.dbg("dictionary lookup highlight") self:highlightFromHoldPos() if self.selected_text then self.ui:handleEvent(Event:new("LookupWord", cleanupSelectedText(self.selected_text.text))) end end function ReaderHighlight:shareHighlight() logger.info("share highlight") end function ReaderHighlight:moreAction() logger.info("more action") end function ReaderHighlight:deleteHighlight(page, i, bookmark_item) self.ui:handleEvent(Event:new("DelHighlight")) logger.dbg("delete highlight", page, i) -- The per-page table is a pure array local removed = table.remove(self.view.highlight.saved[page], i) -- But the main, outer table is a hash, so clear the table for this page if there are no longer any highlights on it if #self.view.highlight.saved[page] == 0 then self.view.highlight.saved[page] = nil end if bookmark_item then self.ui.bookmark:removeBookmark(bookmark_item) else self.ui.bookmark:removeBookmark({ page = self.ui.document.info.has_pages and page or removed.pos0, datetime = removed.datetime, }) end end function ReaderHighlight:editHighlight(page, i) local item = self.view.highlight.saved[page][i] self.ui.bookmark:renameBookmark({ page = self.ui.document.info.has_pages and page or item.pos0, datetime = item.datetime, }, true) end function ReaderHighlight:onReadSettings(config) self.view.highlight.saved_drawer = config:readSetting("highlight_drawer") or self.view.highlight.saved_drawer local disable_highlight = config:readSetting("highlight_disabled") if disable_highlight == nil then disable_highlight = G_reader_settings:readSetting("highlight_disabled") or false end self.view.highlight.disabled = disable_highlight -- panel zoom settings isn't supported in EPUB if self.document.info.has_pages then local ext = util.getFileNameSuffix(self.ui.document.file) G_reader_settings:initializeExtSettings("panel_zoom_enabled", {cbz = true, cbt = true}) G_reader_settings:initializeExtSettings("panel_zoom_fallback_to_text_selection", {pdf = true}) self.panel_zoom_enabled = config:readSetting("panel_zoom_enabled") if self.panel_zoom_enabled == nil then self.panel_zoom_enabled = G_reader_settings:getSettingForExt("panel_zoom_enabled", ext) or false end self.panel_zoom_fallback_to_text_selection = config:readSetting("panel_zoom_fallback_to_text_selection") if self.panel_zoom_fallback_to_text_selection == nil then self.panel_zoom_fallback_to_text_selection = G_reader_settings:getSettingForExt("panel_zoom_fallback_to_text_selection", ext) or false end end end function ReaderHighlight:onUpdateHoldPanRate() self:setupTouchZones() end function ReaderHighlight:onSaveSettings() self.ui.doc_settings:saveSetting("highlight_drawer", self.view.highlight.saved_drawer) self.ui.doc_settings:saveSetting("highlight_disabled", self.view.highlight.disabled) self.ui.doc_settings:saveSetting("panel_zoom_enabled", self.panel_zoom_enabled) end function ReaderHighlight:onClose() UIManager:close(self.highlight_dialog) -- clear highlighted text self:clear() end function ReaderHighlight:toggleDefault() local highlight_disabled = G_reader_settings:isTrue("highlight_disabled") UIManager:show(MultiConfirmBox:new{ text = highlight_disabled and _("Would you like to enable or disable highlighting by default?\n\nThe current default (★) is disabled.") or _("Would you like to enable or disable highlighting by default?\n\nThe current default (★) is enabled."), choice1_text_func = function() return highlight_disabled and _("Disable (★)") or _("Disable") end, choice1_callback = function() G_reader_settings:saveSetting("highlight_disabled", true) end, choice2_text_func = function() return highlight_disabled and _("Enable") or _("Enable (★)") end, choice2_callback = function() G_reader_settings:saveSetting("highlight_disabled", false) end, }) end return ReaderHighlight
agpl-3.0
breakds/corpus-accu
cnn-sentence/training.lua
1
6477
require 'torch' require 'nn' require 'os' ---------- Command Line Options ---------- local cmd = torch.CmdLine() cmd:option('-sentence_size', 20, 'Max allowed length of sentences.') -- Dictionary cmd:option('-dictionary', '/home/breakds/tmp/bilibili/input/word_vecs.bin', 'path to the word2vec binary dictionary.') cmd:option('-save_dictionary', '', 'Save the dictionary object to the specified path.') -- Training cmd:option('-positive', '', 'path to valid sentences dataset.') cmd:option('-negative', '', 'path to invalid sentences dataset.') cmd:option('-gen_negative', 0, 'when > 0, randomly generate specified number of invalid sentences.') cmd:option('-save_training_set', '', 'Save the training set to the specified path.') cmd:option('-load_training_set', '', 'Load the training set from the specified path.') -- Model cmd:option('-save_model', '', 'Specify path to store the trained model.') cmd:option('-load_model', '', 'When specified, load the model instead of construct it.') cmd:option('-learning_rate', 0.001, 'The learning rate.') cmd:option('-max_iteration', 20, 'The max per batch iteration.') cmd:option('-max_epoch', 200, 'The max number of epoches.') cmd:option('-batch_size', 5000, 'The number of sentences in a batch.') local arguments = cmd:parse(arg) -- Initialize the seed using /dev/urandom torch.seed() function LoadTraningSet(DataSet, dictionary) -- Assert that we have non empty positive data and negative data assert(('' ~= arguments.load_training_set) or ('' ~= arguments.positive and ((0 < arguments.gen_negative) or ('' ~= arguments.negative)))) local options = {} options.sentence_size = arguments.sentence_size options.dictionary = dictionary local buffer_table = {} buffer_table.input = {} buffer_table.target = {} -- Load base set if '' ~= arguments.load_training_set then print('[info] Loading base dataset ...') local input = torch.load( arguments.load_training_set .. '/input.torch') local target = torch.load( arguments.load_training_set .. '/target.torch') assert(input:size(1) == target:size(1)) for i = 1, input:size(1) do table.insert(buffer_table.input, input[i]) table.insert(buffer_table.target, target[i]) end print('[ ok ] Base dataset loaded.') end -- Extra positive dataset local positive = nil if '' ~= arguments.positive then print('[info] Loading positive dataset ...') positive = DataSet.Load(arguments.positive, options) for i = 1, positive:size(1) do table.insert(buffer_table.input, positive[i]) table.insert(buffer_table.target, 1) -- label 1 = valid sentence end print('[ ok ] Positive dataset loaded.') end -- Extra negative dataset local negative = nil if arguments.gen_negative > 0 then print('[info] Generating negative dataset ...') negative = DataSet.GenNegative(arguments.gen_negative, options) elseif '' ~= arguments.negative then print('[info] Loading negative dataset ...') negative = DataSet.Load(arguments.negative, options) end if negative then for i = 1, negative:size(1) do table.insert(buffer_table.input, negative[i]) table.insert(buffer_table.target, 2) -- label 2 = invalid sentence end print('[info] Negative dataset loaded.') end -- Form training data local training_set = {} training_set.size = #buffer_table.input training_set.dictionary = dictionary training_set.input = torch.Tensor(#buffer_table.input, arguments.sentence_size) training_set.target = torch.Tensor(#buffer_table.input) shuffle = torch.randperm(training_set.size) for i = 1, training_set.size do training_set.input[i] = buffer_table.input[shuffle[i]] training_set.target[i] = buffer_table.target[shuffle[i]] end -- Save training set if '' ~= arguments.save_training_set then os.execute('mkdir -p ' .. arguments.save_training_set) torch.save(arguments.save_training_set .. '/input.torch', training_set.input) torch.save(arguments.save_training_set .. '/target.torch', training_set.target) print(string.format('[ ok ] Training set saved to %s.', arguments.save_training_set)) end return training_set end function Training() ---------- Part 1: Initialization ---------- assert(arguments.save_model) -- Load Package local Dictionary = require 'DataHandler.Dictionary' local DataSet = require 'DataHandler.DataSet' -- Load Dictionary print('[info] Loading dictionary ...') local dictionary = {} if not pcall(function () dictionary = torch.load(arguments.dictionary) print('[ ok ] Dictionary loaded.') end) then dictionary = Dictionary(arguments.dictionary) if '' ~= arguments.save_dictionary then torch.save(arguments.save_dictionary, dictionary) print(string.format('[ ok ] Dictionary saved to %s', arguments.save_dictionary)) end end ---------- Part II: Load Traning Set ---------- local training_set = LoadTraningSet(DataSet, dictionary) ---------- Part III: Construct Neural Network ---------- local SimpleCNN = require 'Model.SimpleCNN' local model = {} if '' == arguments.load_model then model = SimpleCNN { input_frame_size = dictionary.dimension, sentence_size = training_set.input:size()[2], num_convolutions = 100, kernel_size = 5} print('[ ok ] Neural Network Constructed.') else model = SimpleCNN { load_path = arguments.load_model } print('[ ok ] Neural Network Loaded.') end print('[info] Neural Network Summary:') print(model.network) ---------- Part IV: Traning ---------- model:train(DataSet, training_set, { learningRate = arguments.learning_rate, maxIteration = arguments.max_iteration, maxEpoch = arguments.max_epoch, batchSize = arguments.batch_size }) ---------- Part V: Save Model ---------- model:save(arguments.save_model) end Training()
mit
eggBOY91/Arctic-Core
src/scripts/lua/LuaBridge/Stable Scripts/Azeroth/Karazhan/BOSS_Karazhan_Nightbane.lua
30
1906
function Nightbane_Cleave(Unit, event, miscunit, misc) print "Nightbane Cleave" Unit:FullCastSpellOnTarget(42587,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "Cleave on you...") end function Nightbane_Tail_Sweep(Unit, event, miscunit, misc) print "Nightbane Tail Sweep" Unit:FullCastSpellOnTarget(25653,Unit:GetRandomPlayer()) Unit:SendChatMessage(11, 0, "Take that...") end function Nightbane_Bone_Shards(Unit, event, miscunit, misc) print "Nightbane Bone Shards" Unit:FullCastSpell(17014) Unit:SendChatMessage(11, 0, "Bones protect me...") end function Nightbane_Distracting_Ash(Unit, event, miscunit, misc) print "Nightbane Distracting Ash" Unit:FullCastSpellOnTarget(30130,Unit:GetRandomPlayer()) Unit:SendChatMessage(11, 0, "Ho, your are distracting...") end function Nightbane_Bellowing_Roar(Unit, event, miscunit, misc) print "Nightbane Bellowing Roar" Unit:FullCastSpellOnTarget(37066,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "FEAR on you guys...") end function Nightbane_Charred_Earth(Unit, event, miscunit, misc) print "Nightbane Charred Earth" Unit:FullCastSpellOnTarget(30129,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "FIRE...") end function Nightbane_Smoldering_Breath(Unit, event, miscunit, misc) print "Nightbane Smoldering Breath" Unit:FullCastSpellOnTarget(39385,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "A Good breath...") end function Nightbane(unit, event, miscunit, misc) print "Nightbane" unit:RegisterEvent("Nightbane_Cleave",10000,0) unit:RegisterEvent("Nightbane_Tail_Sweep",13000,0) unit:RegisterEvent("Nightbane_Bone_Shards",17000,0) unit:RegisterEvent("Nightbane_Distracting_Ash",23000,0) unit:RegisterEvent("Nightbane_Bellowing_Roar",31000,0) unit:RegisterEvent("Nightbane_Charred_Earth",37000,0) unit:RegisterEvent("Nightbane_Smoldering_Breath",43000,0) end RegisterUnitEvent(17225,1,"Nightbane")
agpl-3.0
yetsky/luci
applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-format.lua
80
3636
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true format_au = module:option(ListValue, "format_au", "Sun Microsystems AU format (signed linear)", "") format_au:value("yes", "Load") format_au:value("no", "Do Not Load") format_au:value("auto", "Load as Required") format_au.rmempty = true format_g723 = module:option(ListValue, "format_g723", "G.723.1 Simple Timestamp File Format", "") format_g723:value("yes", "Load") format_g723:value("no", "Do Not Load") format_g723:value("auto", "Load as Required") format_g723.rmempty = true format_g726 = module:option(ListValue, "format_g726", "Raw G.726 (16/24/32/40kbps) data", "") format_g726:value("yes", "Load") format_g726:value("no", "Do Not Load") format_g726:value("auto", "Load as Required") format_g726.rmempty = true format_g729 = module:option(ListValue, "format_g729", "Raw G729 data", "") format_g729:value("yes", "Load") format_g729:value("no", "Do Not Load") format_g729:value("auto", "Load as Required") format_g729.rmempty = true format_gsm = module:option(ListValue, "format_gsm", "Raw GSM data", "") format_gsm:value("yes", "Load") format_gsm:value("no", "Do Not Load") format_gsm:value("auto", "Load as Required") format_gsm.rmempty = true format_h263 = module:option(ListValue, "format_h263", "Raw h263 data", "") format_h263:value("yes", "Load") format_h263:value("no", "Do Not Load") format_h263:value("auto", "Load as Required") format_h263.rmempty = true format_jpeg = module:option(ListValue, "format_jpeg", "JPEG (Joint Picture Experts Group) Image", "") format_jpeg:value("yes", "Load") format_jpeg:value("no", "Do Not Load") format_jpeg:value("auto", "Load as Required") format_jpeg.rmempty = true format_pcm = module:option(ListValue, "format_pcm", "Raw uLaw 8khz Audio support (PCM)", "") format_pcm:value("yes", "Load") format_pcm:value("no", "Do Not Load") format_pcm:value("auto", "Load as Required") format_pcm.rmempty = true format_pcm_alaw = module:option(ListValue, "format_pcm_alaw", "load => .so ; Raw aLaw 8khz PCM Audio support", "") format_pcm_alaw:value("yes", "Load") format_pcm_alaw:value("no", "Do Not Load") format_pcm_alaw:value("auto", "Load as Required") format_pcm_alaw.rmempty = true format_sln = module:option(ListValue, "format_sln", "Raw Signed Linear Audio support (SLN)", "") format_sln:value("yes", "Load") format_sln:value("no", "Do Not Load") format_sln:value("auto", "Load as Required") format_sln.rmempty = true format_vox = module:option(ListValue, "format_vox", "Dialogic VOX (ADPCM) File Format", "") format_vox:value("yes", "Load") format_vox:value("no", "Do Not Load") format_vox:value("auto", "Load as Required") format_vox.rmempty = true format_wav = module:option(ListValue, "format_wav", "Microsoft WAV format (8000hz Signed Line", "") format_wav:value("yes", "Load") format_wav:value("no", "Do Not Load") format_wav:value("auto", "Load as Required") format_wav.rmempty = true format_wav_gsm = module:option(ListValue, "format_wav_gsm", "Microsoft WAV format (Proprietary GSM)", "") format_wav_gsm:value("yes", "Load") format_wav_gsm:value("no", "Do Not Load") format_wav_gsm:value("auto", "Load as Required") format_wav_gsm.rmempty = true return cbimap
apache-2.0
pazos/koreader
frontend/apps/reader/modules/readerlink.lua
1
59490
--[[-- ReaderLink is an abstraction for document-specific link interfaces. ]] local BD = require("ui/bidi") local ButtonDialogTitle = require("ui/widget/buttondialogtitle") local ConfirmBox = require("ui/widget/confirmbox") local Device = require("device") local Event = require("ui/event") local InfoMessage = require("ui/widget/infomessage") local InputContainer = require("ui/widget/container/inputcontainer") local LinkBox = require("ui/widget/linkbox") local Notification = require("ui/widget/notification") local UIManager = require("ui/uimanager") local ffiutil = require("ffi/util") local logger = require("logger") local util = require("util") local _ = require("gettext") local Screen = Device.screen local T = ffiutil.template local ReaderLink = InputContainer:new{ location_stack = {} } function ReaderLink:init() if Device:hasKeys() then self.key_events.SelectNextPageLink = { {"Tab" }, doc = "select next page link", event = "SelectNextPageLink", } self.key_events.SelectPrevPageLink = { {"Shift", "Tab" }, {"Sym", "Tab" }, -- Right Shift + Tab doc = "select previous page link", event = "SelectPrevPageLink", } self.key_events.GotoSelectedPageLink = { { "Press" }, doc = "go to selected page link", event = "GotoSelectedPageLink", } -- "Back" is handled by ReaderBack, which will call our onGoBackLink() -- when G_reader_settings:readSetting("back_in_reader") == "previous_location" end if Device:isTouchDevice() then self.ui:registerTouchZones({ { id = "tap_link", ges = "tap", screen_zone = { ratio_x = 0, ratio_y = 0, ratio_w = 1, ratio_h = 1, }, overrides = { -- Tap on links have priority over everything (it can -- be disabled with "Tap to follow links" menu item) "readerhighlight_tap", "tap_top_left_corner", "tap_top_right_corner", "tap_left_bottom_corner", "tap_right_bottom_corner", "readerfooter_tap", "readerconfigmenu_ext_tap", "readerconfigmenu_tap", "readermenu_ext_tap", "readermenu_tap", "tap_forward", "tap_backward", }, handler = function(ges) return self:onTap(_, ges) end, }, { id = "swipe_link", ges = "swipe", screen_zone = { ratio_x = 0, ratio_y = 0, ratio_w = 1, ratio_h = 1, }, overrides = { "paging_swipe", "rolling_swipe" }, handler = function(ges) return self:onSwipe(_, ges) end, }, }) end self.ui:registerPostInitCallback(function() self.ui.menu:registerToMainMenu(self) end) -- For relative local file links local directory, filename = util.splitFilePathName(self.ui.document.file) -- luacheck: no unused self.document_dir = directory -- Migrate these old settings to the new common one if G_reader_settings:isTrue("tap_link_footnote_popup") or G_reader_settings:isTrue("swipe_link_footnote_popup") then G_reader_settings:saveSetting("tap_link_footnote_popup", nil) G_reader_settings:saveSetting("swipe_link_footnote_popup", nil) G_reader_settings:saveSetting("footnote_link_in_popup", true) end end function ReaderLink:onReadSettings(config) -- called when loading new document self.location_stack = {} end local function isTapToFollowLinksOn() return G_reader_settings:nilOrTrue("tap_to_follow_links") end local function isLargerTapAreaToFollowLinksEnabled() return G_reader_settings:isTrue("larger_tap_area_to_follow_links") end local function isTapIgnoreExternalLinksEnabled() return G_reader_settings:isTrue("tap_ignore_external_links") end local function isFootnoteLinkInPopupEnabled() return G_reader_settings:isTrue("footnote_link_in_popup") end local function isPreferFootnoteEnabled() return G_reader_settings:isTrue("link_prefer_footnote") end local function isSwipeToGoBackEnabled() return G_reader_settings:isTrue("swipe_to_go_back") end local function isSwipeToFollowNearestLinkEnabled() return G_reader_settings:isTrue("swipe_to_follow_nearest_link") end local function isSwipeIgnoreExternalLinksEnabled() return G_reader_settings:nilOrTrue("swipe_ignore_external_links") end local function isSwipeToJumpToLatestBookmarkEnabled() return G_reader_settings:isTrue("swipe_to_jump_to_latest_bookmark") end function ReaderLink:addToMainMenu(menu_items) -- insert table to main reader menu menu_items.follow_links = { text = _("Links"), sub_item_table = { { text = _("Tap to follow links"), checked_func = isTapToFollowLinksOn, callback = function() G_reader_settings:saveSetting("tap_to_follow_links", not isTapToFollowLinksOn()) end, help_text = _([[Tap on links to follow them.]]), }, { text = _("Ignore external links on tap"), enabled_func = isTapToFollowLinksOn, checked_func = isTapIgnoreExternalLinksEnabled, callback = function() G_reader_settings:saveSetting("tap_ignore_external_links", not isTapIgnoreExternalLinksEnabled()) end, help_text = _([[ Ignore taps on external links. Useful with Wikipedia EPUBs to make page turning easier. You can still follow them from the dictionary window or the selection menu after holding on them.]]), separator = true, }, { text = _("Swipe to go back"), checked_func = isSwipeToGoBackEnabled, callback = function() G_reader_settings:saveSetting("swipe_to_go_back", not isSwipeToGoBackEnabled()) end, help_text = _([[Swipe to the right to go back to the previous location after you have followed a link. When the location stack is empty, swiping to the right takes you to the previous page.]]), }, { text = _("Swipe to follow nearest link"), checked_func = isSwipeToFollowNearestLinkEnabled, callback = function() G_reader_settings:saveSetting("swipe_to_follow_nearest_link", not isSwipeToFollowNearestLinkEnabled()) end, help_text = _([[Swipe to the left to follow the link nearest to where you started the swipe. This is useful when a small font is used and tapping on small links is tedious.]]), }, { text = _("Ignore external links on swipe"), enabled_func = isSwipeToFollowNearestLinkEnabled, checked_func = isSwipeIgnoreExternalLinksEnabled, callback = function() G_reader_settings:saveSetting("swipe_ignore_external_links", not isSwipeIgnoreExternalLinksEnabled()) end, help_text = _([[ Ignore external links near swipe. Useful with Wikipedia EPUBs to follow only footnotes with swipe. You can still follow external links from the dictionary window or the selection menu after holding on them.]]), separator = true, }, { text = _("Swipe to jump to latest bookmark"), checked_func = isSwipeToJumpToLatestBookmarkEnabled, callback = function() G_reader_settings:saveSetting("swipe_to_jump_to_latest_bookmark", not isSwipeToJumpToLatestBookmarkEnabled()) end, help_text = _([[ Swipe to the left to go the most recently bookmarked page. This can be useful to quickly swipe back and forth between what you are reading and some reference page (for example notes, a map or a characters list). If any of the other Swipe to follow link options is enabled, this will work only when the current page contains no link.]]), }, } } -- Insert other items that are (for now) only supported with CreDocuments -- (They could be supported nearly as-is, but given that there is a lot -- less visual feedback on PDF document of what is a link, or that we just -- followed a link, than on EPUB, it's safer to not use them on PDF documents -- even if the user enabled these features for EPUB documents). if not self.ui.document.info.has_pages then -- Tap section table.insert(menu_items.follow_links.sub_item_table, 2, { text = _("Allow larger tap area around links"), enabled_func = isTapToFollowLinksOn, checked_func = isLargerTapAreaToFollowLinksEnabled, callback = function() G_reader_settings:saveSetting("larger_tap_area_to_follow_links", not isLargerTapAreaToFollowLinksEnabled()) end, help_text = _([[Extends the tap area around internal links. Useful with a small font where tapping on small footnote links may be tedious.]]), }) table.insert(menu_items.follow_links.sub_item_table, 4, { text = _("Show footnotes in popup"), enabled_func = function() return isTapToFollowLinksOn() or isSwipeToFollowNearestLinkEnabled() end, checked_func = isFootnoteLinkInPopupEnabled, callback = function() G_reader_settings:saveSetting("footnote_link_in_popup", not isFootnoteLinkInPopupEnabled()) end, help_text = _([[ Show internal link target content in a footnote popup when it looks like it might be a footnote, instead of following the link. Note that depending on the book quality, footnote detection may not always work correctly. The footnote content may be empty, truncated, or include other footnotes. From the footnote popup, you can jump to the footnote location in the book by swiping to the left.]]), }) table.insert(menu_items.follow_links.sub_item_table, 5, { text = _("Show more links as footnotes"), enabled_func = function() return isFootnoteLinkInPopupEnabled() and (isTapToFollowLinksOn() or isSwipeToFollowNearestLinkEnabled()) end, checked_func = isPreferFootnoteEnabled, callback = function() G_reader_settings:saveSetting("link_prefer_footnote", not isPreferFootnoteEnabled()) end, help_text = _([[Loosen footnote detection rules to show more links as footnotes.]]), }) table.insert(menu_items.follow_links.sub_item_table, 6, { text = _("Set footnote popup font size"), enabled_func = function() return isFootnoteLinkInPopupEnabled() and (isTapToFollowLinksOn() or isSwipeToFollowNearestLinkEnabled()) end, keep_menu_open = true, callback = function() local spin_widget local get_font_size_widget get_font_size_widget = function(show_absolute_font_size_widget) local SpinWidget = require("ui/widget/spinwidget") if show_absolute_font_size_widget then spin_widget = SpinWidget:new{ width = math.floor(Screen:getWidth() * 0.75), value = G_reader_settings:readSetting("footnote_popup_absolute_font_size") or Screen:scaleBySize(self.ui.font.font_size), value_min = 12, value_max = 255, precision = "%d", ok_text = _("Set font size"), title_text = _("Set footnote popup font size"), info_text = _([[ The footnote popup font can adjust to the font size you've set for the document, but you can specify here a fixed absolute font size to be used instead.]]), callback = function(spin) G_reader_settings:delSetting("footnote_popup_relative_font_size") G_reader_settings:saveSetting("footnote_popup_absolute_font_size", spin.value) end, extra_text = _("Set a relative font size instead"), extra_callback = function() UIManager:close(spin_widget) spin_widget = get_font_size_widget(false) UIManager:show(spin_widget) end, } else spin_widget = SpinWidget:new{ width = math.floor(Screen:getWidth() * 0.75), value = G_reader_settings:readSetting("footnote_popup_relative_font_size") or -2, value_min = -10, value_max = 5, precision = "%+d", ok_text = _("Set font size"), title_text = _("Set footnote popup font size"), info_text = _([[ The footnote popup font adjusts to the font size you've set for the document. You can specify here how much smaller or larger it should be relative to the document font size. A negative value will make it smaller, while a positive one will make it larger. The recommended value is -2.]]), callback = function(spin) G_reader_settings:delSetting("footnote_popup_absolute_font_size") G_reader_settings:saveSetting("footnote_popup_relative_font_size", spin.value) end, extra_text = _("Set an absolute font size instead"), extra_callback = function() UIManager:close(spin_widget) spin_widget = get_font_size_widget(true) UIManager:show(spin_widget) end, } end return spin_widget end local show_absolute_font_size_widget = G_reader_settings:readSetting("footnote_popup_absolute_font_size") ~= nil spin_widget = get_font_size_widget(show_absolute_font_size_widget) UIManager:show(spin_widget) end, help_text = _([[ The footnote popup font adjusts to the font size you've set for the document. This allows you to specify how much smaller or larger it should be relative to the document font size.]]), separator = true, }) end menu_items.go_to_previous_location = { text = _("Go back to previous location"), enabled_func = function() return #self.location_stack > 0 end, callback = function() self:onGoBackLink() end, hold_callback = function(touchmenu_instance) UIManager:show(ConfirmBox:new{ text = _("Clear location history?"), ok_text = _("Clear"), ok_callback = function() self:onClearLocationStack() touchmenu_instance:closeMenu() end, }) end, } end --- Check if a xpointer to <a> node really points to itself function ReaderLink:isXpointerCoherent(a_xpointer) -- Get screen coordinates of xpointer local screen_y, screen_x = self.ui.document:getScreenPositionFromXPointer(a_xpointer) -- Get again link and a_xpointer from this position local re_link_xpointer, re_a_xpointer = self.ui.document:getLinkFromPosition({x = screen_x, y = screen_y}) -- luacheck: no unused -- We should get the same a_xpointer. If not, crengine has messed up -- and we should not trust this xpointer to get back to this link. if re_a_xpointer ~= a_xpointer then -- Try it again with screen_x+1 (in the rare cases where screen_x -- fails, screen_x+1 usually works - probably something in crengine, -- but easier to workaround here that way) re_link_xpointer, re_a_xpointer = self.ui.document:getLinkFromPosition({x = screen_x+1, y = screen_y}) -- luacheck: no unused if re_a_xpointer ~= a_xpointer then logger.info("not coherent a_xpointer:", a_xpointer) return false end end return true end --- Gets link from gesture. -- `Document:getLinkFromPosition()` behaves differently depending on -- document type, so this function provides a wrapper. function ReaderLink:getLinkFromGes(ges) if self.ui.document.info.has_pages then local pos = self.view:screenToPageTransform(ges.pos) if pos then -- link box in native page local link, lbox = self.ui.document:getLinkFromPosition(pos.page, pos) if link and lbox then return { link = link, lbox = lbox, pos = pos, } end end else local link_xpointer, a_xpointer = self.ui.document:getLinkFromPosition(ges.pos) logger.dbg("getLinkFromPosition link_xpointer:", link_xpointer) logger.dbg("getLinkFromPosition a_xpointer:", a_xpointer) -- On some documents, crengine may sometimes give a wrong a_xpointer -- (in some Wikipedia saved as EPUB, it would point to some other <A> -- element in the same paragraph). If followed then back, we could get -- to a different page. So, we check here how valid it is, and if not, -- we just discard it so that addCurrentLocationToStack() is used. local from_xpointer = nil if a_xpointer and self:isXpointerCoherent(a_xpointer) then from_xpointer = a_xpointer end if link_xpointer ~= "" then -- This link's source xpointer is more precise than a classic -- xpointer to top of a page: we can show a marker at its -- y-position in target page -- (keep a_xpointer even if incoherent, might be needed for -- footnote detection (better than nothing if incoherent) return { xpointer = link_xpointer, marker_xpointer = link_xpointer, from_xpointer = from_xpointer, a_xpointer = a_xpointer, -- tap y-position should be a good approximation of link y -- (needed to keep its highlight a bit more time if it was -- hidden by the footnote popup) link_y = ges.pos.y } end end end --- Highlights a linkbox if available and goes to it. function ReaderLink:showLinkBox(link, allow_footnote_popup) if link and link.lbox then -- pdfdocument -- screen box that holds the link local sbox = self.view:pageToScreenTransform(link.pos.page, self.ui.document:nativeToPageRectTransform(link.pos.page, link.lbox)) if sbox then UIManager:show(LinkBox:new{ box = sbox, timeout = FOLLOW_LINK_TIMEOUT, callback = function() self:onGotoLink(link.link, false, allow_footnote_popup) end }) return true end elseif link and link.xpointer ~= "" then -- credocument return self:onGotoLink(link, false, allow_footnote_popup) end end function ReaderLink:onTap(_, ges) if not isTapToFollowLinksOn() then return end if self.ui.document.info.has_pages then -- (footnote popup and larger tap area are for not -- not supported with non-CreDocuments) local link = self:getLinkFromGes(ges) if link then if link.link and link.link.uri and isTapIgnoreExternalLinksEnabled() then return end return self:showLinkBox(link) end return end -- For CreDocuments only from now on local allow_footnote_popup = isFootnoteLinkInPopupEnabled() -- If tap_ignore_external_links, skip precise tap detection to really -- ignore a tap on an external link, and allow using onGoToPageLink() -- to find the nearest internal link if not isTapIgnoreExternalLinksEnabled() then local link = self:getLinkFromGes(ges) if link then return self:showLinkBox(link, allow_footnote_popup) end end if isLargerTapAreaToFollowLinksEnabled() or isTapIgnoreExternalLinksEnabled() then local max_distance = 0 -- used when only isTapIgnoreExternalLinksEnabled() if isLargerTapAreaToFollowLinksEnabled() then -- If no link found exactly at the tap position, -- try to find any link in page around that tap position. -- With "Ignore external links", onGoToPageLink() will grab -- only internal links, which is nice as url links are usually -- longer - so this give more chance to catch a small link to -- footnote stuck to a longer Wikipedia article name link. -- -- 30px on a reference 167 dpi screen makes 0.45cm, which -- seems fine (on a 300dpi device, this will be scaled -- to 54px (which makes 1/20th of screen witdh on a GloHD) -- Trust Screen.dpi (which may not be the real device -- screen DPI if the user has set another one). max_distance = Screen:scaleByDPI(30) end return self:onGoToPageLink(ges, isTapIgnoreExternalLinksEnabled(), max_distance) end end --- Remember current location so we can go back to it function ReaderLink:addCurrentLocationToStack() if self.ui.document.info.has_pages then table.insert(self.location_stack, self.ui.paging:getBookLocation()) else table.insert(self.location_stack, { xpointer = self.ui.rolling:getBookLocation(), }) end end function ReaderLink:onClearLocationStack(show_notification) self.location_stack = {} if show_notification then UIManager:show(Notification:new{ text = _("Location history cleared."), }) end return true end --- Goes to link. -- (This is called by other modules (highlight, search) to jump to a xpointer, -- they should not provide allow_footnote_popup=true) function ReaderLink:onGotoLink(link, neglect_current_location, allow_footnote_popup) logger.dbg("onGotoLink:", link) local link_url if self.ui.document.info.has_pages then -- internal pdf links have a "page" attribute, while external ones have an "uri" attribute if link.page then -- Internal link logger.dbg("Internal link:", link) if not neglect_current_location then self:addCurrentLocationToStack() end self.ui:handleEvent(Event:new("GotoPage", link.page + 1)) return true end link_url = link.uri -- external link else -- For crengine, internal links may look like : -- #_doc_fragment_0_Organisation (link from anchor) -- /body/DocFragment/body/ul[2]/li[5]/text()[3].16 (xpointer from full-text search) -- If the XPointer does not exist (or is a full url), we will jump to page 1 -- Best to check that this link exists in document with the following, -- which accepts both of the above legitimate xpointer as input. if self.ui.document:isXPointerInDocument(link.xpointer) then logger.dbg("Internal link:", link) if allow_footnote_popup then if self:showAsFootnotePopup(link, neglect_current_location) then return true end -- if it fails for any reason, fallback to following link end if not neglect_current_location then if link.from_xpointer then -- We have a more precise xpointer than the xpointer to top of -- current page that addCurrentLocationToStack() would give, and -- we may be able to show a marker when back local saved_location if self.view.view_mode == "scroll" then -- In scroll mode, we still use the top of page as the -- xpointer to go back to, so we get back to the same view. -- We can still show the marker at the link position saved_location = { xpointer = self.ui.rolling:getBookLocation(), marker_xpointer = link.from_xpointer, } else -- In page mode, we use the same for go to and for marker, -- as 'page mode' ensures we get back to the same view. saved_location = { xpointer = link.from_xpointer, marker_xpointer = link.from_xpointer, } end table.insert(self.location_stack, saved_location) else self:addCurrentLocationToStack() end end self.ui:handleEvent(Event:new("GotoXPointer", link.xpointer, link.marker_xpointer)) return true end link_url = link.xpointer -- external link end logger.dbg("External link:", link_url) local is_http_link = link_url:find("^https?://") ~= nil if is_http_link and self:onGoToExternalLink(link_url) then return true end -- Check if it is a link to a local file local linked_filename = link_url:gsub("^file:(//)?", "") -- remove local file protocol if any local anchor if linked_filename:find("?") then -- remove any query string (including any following anchor) linked_filename, anchor = linked_filename:match("^(.-)(%?.*)$") elseif linked_filename:find("#") then -- remove any anchor linked_filename, anchor = linked_filename:match("^(.-)(#.*)$") end linked_filename = ffiutil.joinPath(self.document_dir, linked_filename) -- get full path linked_filename = ffiutil.realpath(linked_filename) -- clean full path from ./ or ../ if linked_filename and lfs.attributes(linked_filename, "mode") == "file" then local DocumentRegistry = require("document/documentregistry") local provider = DocumentRegistry:getProvider(linked_filename) if provider then -- Display filename with anchor or query string, so the user gets -- this information and can manually go to the appropriate place local display_filename = linked_filename if anchor then display_filename = display_filename .. anchor end UIManager:show(ConfirmBox:new{ text = T(_("Would you like to read this local document?\n\n%1\n"), BD.filepath(display_filename)), ok_callback = function() UIManager:scheduleIn(0.1, function() self.ui:switchDocument(linked_filename) end) end }) else UIManager:show(InfoMessage:new{ text = T(_("Link to unsupported local file:\n%1"), BD.url(link_url)), }) end return true end -- Not supported UIManager:show(InfoMessage:new{ text = T(_("Invalid or external link:\n%1"), BD.url(link_url)), -- no timeout to allow user to type that link in his web browser }) -- don't propagate, user will notice and tap elsewhere if he wants to change page return true end function ReaderLink:onGoToExternalLink(link_url) local text local dialog local buttons = { { { text = _("Cancel"), callback = function() UIManager:close(dialog) end, }, }, } local add_button = function(button) if #buttons[#buttons] >= 2 then -- add new row if last contains already 2 table.insert(buttons, {}) end -- append button to last row table.insert(buttons[#buttons], button) end -- Set up buttons for alternative external link handling methods local alt_handlers_buttons = {} if self.ui.wallabag then table.insert(alt_handlers_buttons, { text = _("Add to Wallabag"), callback = function() UIManager:close(dialog) self.ui:handleEvent(Event:new("AddWallabagArticle", link_url)) end, }) end if Device:canOpenLink() then table.insert(alt_handlers_buttons, { text = _("Open in browser"), callback = function() UIManager:close(dialog) Device:openLink(link_url) end, }) end -- Check if it is a wikipedia link local wiki_lang, wiki_page = link_url:match([[https?://([^%.]+).wikipedia.org/wiki/([^/]+)]]) if wiki_lang and wiki_page then logger.dbg("Wikipedia link:", wiki_lang, wiki_page) -- Ask for user confirmation before launching lookup (on a -- wikipedia page saved as epub, full of wikipedia links, it's -- too easy to click on links when wanting to change page...) -- But first check if this wikipedia article has been saved as EPUB local epub_filename = wiki_page .. "."..string.upper(wiki_lang)..".epub" local epub_fullpath -- either in current book directory local last_file = G_reader_settings:readSetting("lastfile") if last_file then local current_book_dir = last_file:match("(.*)/") local safe_filename = util.getSafeFilename(epub_filename, current_book_dir):gsub("_", " ") local epub_path = current_book_dir .. "/" .. safe_filename if util.pathExists(epub_path) then epub_fullpath = epub_path end end -- or in wikipedia save directory if not epub_fullpath then local dir = G_reader_settings:readSetting("wikipedia_save_dir") if not dir then dir = G_reader_settings:readSetting("home_dir") end if not dir then dir = require("apps/filemanager/filemanagerutil").getDefaultDir() end if dir then local safe_filename = util.getSafeFilename(epub_filename, dir):gsub("_", " ") local epub_path = dir .. "/" .. safe_filename if util.pathExists(epub_path) then epub_fullpath = epub_path end end end text = T(_("Would you like to read this Wikipedia %1 article?\n\n%2\n"), wiki_lang:upper(), wiki_page:gsub("_", " ")) add_button({ text = _("Read online"), callback = function() UIManager:nextTick(function() UIManager:close(dialog) self.ui:handleEvent(Event:new("LookupWikipedia", wiki_page, true, false, true, wiki_lang)) end) end, }) if epub_fullpath then text = T("%1\n%2", text, _("This article has previously been saved as EPUB. You may wish to read the saved EPUB instead.")) add_button({ text = _("Read EPUB"), callback = function() UIManager:scheduleIn(0.1, function() UIManager:close(dialog) self.ui:switchDocument(epub_fullpath) end) end, }) end else if #alt_handlers_buttons == 0 then -- No external link handler return false end text = T(_("External link:\n\n%1"), BD.url(link_url)) end -- Add all alternative handlers buttons for __, button in ipairs(alt_handlers_buttons) do add_button(button) end dialog = ButtonDialogTitle:new{ title = text, use_info_style = true, buttons = buttons, } UIManager:show(dialog) return true end --- Goes back to previous location. function ReaderLink:onGoBackLink(show_notification_if_empty) local saved_location = table.remove(self.location_stack) if saved_location then logger.dbg("GoBack: restoring:", saved_location) self.ui:handleEvent(Event:new('RestoreBookLocation', saved_location)) return true elseif show_notification_if_empty then UIManager:show(Notification:new{ text = _("Location history is empty."), }) end end function ReaderLink:onSwipe(arg, ges) local direction = BD.flipDirectionIfMirroredUILayout(ges.direction) if direction == "east" then if isSwipeToGoBackEnabled() then if #self.location_stack > 0 then -- Remember if location stack is going to be empty, so we -- can stop the propagation of next swipe back: so the user -- knows it is empty and that next swipe back will get him -- to previous page (and not to previous location) self.swipe_back_resist = #self.location_stack == 1 return self:onGoBackLink() elseif self.swipe_back_resist then self.swipe_back_resist = false -- Make that gesture don't do anything, and show a Notification -- so the user knows why UIManager:show(Notification:new{ text = _("Location history is empty."), }) return true end end elseif direction == "west" then local ret = false if isSwipeToFollowNearestLinkEnabled() then ret = self:onGoToPageLink(ges, isSwipeIgnoreExternalLinksEnabled()) end -- If no link found, or no follow link option enabled, -- jump to latest bookmark (if enabled) if not ret and isSwipeToJumpToLatestBookmarkEnabled() then ret = self:onGoToLatestBookmark(ges) end return ret end end --- Goes to link nearest to the gesture (or first link in page) function ReaderLink:onGoToPageLink(ges, internal_links_only, max_distance) local selected_link = nil local selected_distance2 = nil -- We use squares of distances all along the calculations, no need -- to math.sqrt() them when comparing if self.ui.document.info.has_pages then local pos = self.view:screenToPageTransform(ges.pos) if not pos then return end local links = self.ui.document:getPageLinks(pos.page) if not links or #links == 0 then return end -- DEBUG("PDF Page links : ", links) -- We may get multiple links: internal ones (with "page" key) -- that we're interested in, but also external links (no "page", but -- a "uri" key) that we don't care about. -- [2] = { -- ["y1"] = 107.88977050781, -- ["x1"] = 176.60360717773, -- ["y0"] = 97.944396972656, -- ["x0"] = 97, -- ["page"] = 347 -- }, local pos_x, pos_y = pos.x, pos.y local shortest_dist = nil for _, link in ipairs(links) do if not internal_links_only or link.page then local start_dist = math.pow(link.x0 - pos_x, 2) + math.pow(link.y0 - pos_y, 2) local end_dist = math.pow(link.x1 - pos_x, 2) + math.pow(link.y1 - pos_y, 2) local min_dist = math.min(start_dist, end_dist) if shortest_dist == nil or min_dist < shortest_dist then -- onGotoLink()'s GotoPage event needs the link -- itself, and will use its "page" value selected_link = link shortest_dist = min_dist end end end if shortest_dist then selected_distance2 = shortest_dist end else -- Getting segments on a page with many internal links is -- a bit expensive. With larger_tap_area_to_follow_links=true, -- this is done for each tap on screen (changing pages, showing -- menu...). We might want to cache these links per page (and -- clear that cache when page layout change). -- If we care only about internal links, request them only -- (and avoid that expensive segments work on external links) local links = self.ui.document:getPageLinks(internal_links_only) if not links or #links == 0 then return end -- DEBUG("CRE Page links : ", links) -- We may get multiple links: internal ones (they have a "section" key) -- that we're interested in, but also external links (no "section", but -- a "uri" key) that we don't care about. -- [1] = { -- ["end_x"] = 825, -- ["uri"] = "", -- ["end_y"] = 333511, -- ["start_x"] = 90, -- ["start_y"] = 333511 -- }, -- [2] = { -- ["end_x"] = 366, -- ["section"] = "#_doc_fragment_19_ftn_fn6", -- ["end_y"] = 1201, -- ["start_x"] = 352, -- ["start_y"] = 1201 -- ["a_xpointer"] = "/body/DocFragment/body/div/p[12]/sup[3]/a[3].0", -- }, -- and when segments requested (example for a multi-lines link): -- [3] = { -- ["section"] = "#_doc_fragment_0_ Man_of_letters", -- ["a_xpointer"] = "/body/DocFragment/body/div/div[4]/ul/li[3]/ul/li[2]/ul/li[1]/ul/li[3]/a.0", -- ["start_x"] = 101, -- ["start_y"] = 457, -- ["end_x"] = 176, -- ["end_y"] = 482,, -- ["segments"] = { -- [1] = { -- ["x0"] = 101, -- ["y0"] = 457, -- ["x1"] = 590, -- ["y1"] = 482, -- }, -- [2] = { -- ["x0"] = 101, -- ["y0"] = 482, -- ["x1"] = 177, -- ["y1"] = 507, -- } -- }, -- }, -- Note: with some documents and some links, crengine may give wrong -- coordinates, and our code below may miss or give the wrong first -- or nearest link... local pos_x, pos_y = ges.pos.x, ges.pos.y local shortest_dist = nil for _, link in ipairs(links) do -- link.uri may be an empty string with some invalid links: ignore them if link.section or (link.uri and link.uri ~= "") then if link.segments then -- With segments, each is a horizontal segment, with start_x < end_x, -- and we should compute the distance from gesture position to -- each segment. local segments_max_y = -1 local link_is_shortest = false local segments = link.segments for i=1, #segments do local segment = segments[i] local segment_dist -- Distance here is kept squared (d^2 = diff_x^2 + diff_y^2), -- and we compute each part individually -- First, vertical distance (squared) if pos_y < segment.y0 then -- above the segment height segment_dist = math.pow(segment.y0 - pos_y, 2) elseif pos_y > segment.y1 then -- below the segment height segment_dist = math.pow(pos_y - segment.y1, 2) else -- gesture pos is on the segment height, no vertical distance segment_dist = 0 end -- Next, horizontal distance (squared) if pos_x < segment.x0 then -- on the left of segment: calc dist to x0 segment_dist = segment_dist + math.pow(segment.x0 - pos_x, 2) elseif pos_x > segment.x1 then -- on the right of segment : calc dist to x1 segment_dist = segment_dist + math.pow(pos_x - segment.x1, 2) -- else -- gesture pos is in the segment width, no horizontal distance end if shortest_dist == nil or segment_dist < shortest_dist then selected_link = link shortest_dist = segment_dist link_is_shortest = true end if segment.y1 > segments_max_y then segments_max_y = segment.y1 end end if link_is_shortest then -- update the selected_link we just set with its lower segment y selected_link.link_y = segments_max_y end else -- Before "segments" were available, we did this: -- We'd only get a horizontal segment if the link is on a single line. -- When it is multi-lines, we can't do much calculation... -- We used to just check distance from start_x and end_x, and -- we could miss a tap in the middle of a long link. -- (also start_y = end_y = the top of the rect for a link on a single line) local start_dist = math.pow(link.start_x - pos_x, 2) + math.pow(link.start_y - pos_y, 2) local end_dist = math.pow(link.end_x - pos_x, 2) + math.pow(link.end_y - pos_y, 2) local min_dist = math.min(start_dist, end_dist) if shortest_dist == nil or min_dist < shortest_dist then selected_link = link selected_link.link_y = link.end_y shortest_dist = min_dist end end end end if shortest_dist then selected_distance2 = shortest_dist end if selected_link then logger.dbg("nearest selected_link", selected_link) -- Check a_xpointer is coherent, use it as from_xpointer only if it is local from_xpointer = nil if selected_link.a_xpointer and self:isXpointerCoherent(selected_link.a_xpointer) then from_xpointer = selected_link.a_xpointer end -- Make it a link as expected by onGotoLink selected_link = { xpointer = selected_link.section or selected_link.uri, marker_xpointer = selected_link.section, from_xpointer = from_xpointer, -- (keep a_xpointer even if incoherent, might be needed for -- footnote detection (better than nothing if incoherent) a_xpointer = selected_link.a_xpointer, -- keep the link y position, so we can keep its highlight shown -- a bit more time if it was hidden by the footnote popup link_y = selected_link.link_y, } end end if selected_link then if max_distance and selected_distance2 and selected_distance2 > math.pow(max_distance, 2) then logger.dbg("nearest link is further than max distance, ignoring it") else return self:onGotoLink(selected_link, false, isFootnoteLinkInPopupEnabled()) end end end function ReaderLink:onGoToInternalPageLink(ges) self:onGoToPageLink(ges, true) end function ReaderLink:onSelectNextPageLink() return self:selectRelPageLink(1) end function ReaderLink:onSelectPrevPageLink() return self:selectRelPageLink(-1) end function ReaderLink:selectRelPageLink(rel) if self.ui.document.info.has_pages then -- not implemented for now (see at doing like in showLinkBox() -- to highlight the link before jumping to it) return end -- Follow swipe_ignore_external_links setting to allow -- skipping external links when using keys local links = self.ui.document:getPageLinks(isSwipeIgnoreExternalLinksEnabled()) if not links or #links == 0 then return end if self.cur_selected_page_link_num then self.cur_selected_page_link_num = self.cur_selected_page_link_num + rel -- When reaching end of list, don't immediately jump to -- the other side: allow one step with no link selected if self.cur_selected_page_link_num > #links then self.cur_selected_page_link_num = nil elseif self.cur_selected_page_link_num <= 0 then self.cur_selected_page_link_num = nil end else if rel > 0 then self.cur_selected_page_link_num = 1 elseif rel < 0 then self.cur_selected_page_link_num = #links end end if not self.cur_selected_page_link_num then self.cur_selected_link = nil self.ui.document:highlightXPointer() UIManager:setDirty(self.dialog, "ui") return end local selected_link = links[self.cur_selected_page_link_num] logger.dbg("selected_link", selected_link) -- Check a_xpointer is coherent, use it as from_xpointer only if it is local from_xpointer = nil if selected_link.a_xpointer and self:isXpointerCoherent(selected_link.a_xpointer) then from_xpointer = selected_link.a_xpointer end local link_y if selected_link.segments and #selected_link.segments > 0 then link_y = selected_link.segments[#selected_link.segments].y1 else link_y = selected_link.end_y end -- Make it a link as expected by onGotoLink self.cur_selected_link = { xpointer = selected_link.section or selected_link.uri, marker_xpointer = selected_link.section, from_xpointer = from_xpointer, -- (keep a_xpointer even if incoherent, might be needed for -- footnote detection (better than nothing if incoherent) a_xpointer = selected_link.a_xpointer, -- keep the link y position, so we can keep its highlight shown -- a bit more time if it was hidden by the footnote popup link_y = link_y, } self.ui.document:highlightXPointer() -- clear any previous one self.ui.document:highlightXPointer(self.cur_selected_link.from_xpointer) UIManager:setDirty(self.dialog, "ui") return true end function ReaderLink:onGotoSelectedPageLink() if self.cur_selected_link then return self:onGotoLink(self.cur_selected_link, false, isFootnoteLinkInPopupEnabled()) end end function ReaderLink:onPageUpdate() if self.cur_selected_link then self.ui.document:highlightXPointer() self.cur_selected_page_link_num = nil self.cur_selected_link = nil end end function ReaderLink:onPosUpdate() if self.cur_selected_link then self.ui.document:highlightXPointer() self.cur_selected_page_link_num = nil self.cur_selected_link = nil end end function ReaderLink:onGoToLatestBookmark(ges) local latest_bookmark = self.ui.bookmark:getLatestBookmark() if latest_bookmark then if self.ui.document.info.has_pages then -- self:onGotoLink() needs something with a page attribute. -- we need to substract 1 to bookmark page, as links start from 0 -- and onGotoLink will add 1 - we need a fake_link (with a single -- page attribute) so we don't touch the bookmark itself local fake_link = {} fake_link.page = latest_bookmark.page - 1 return self:onGotoLink(fake_link) else -- Make it a link as expected by onGotoLink local link if latest_bookmark.pos0 then -- text highlighted, precise xpointer link = { xpointer = latest_bookmark.pos0, marker_xpointer = latest_bookmark.pos0, } else -- page bookmarked, 'page' is a xpointer to top of page link = { xpointer = latest_bookmark.page, } end return self:onGotoLink(link) end end end function ReaderLink:showAsFootnotePopup(link, neglect_current_location) if self.ui.document.info.has_pages then return false -- not supported end local source_xpointer = link.from_xpointer or link.a_xpointer local target_xpointer = link.xpointer if not source_xpointer or not target_xpointer then return false end local trust_source_xpointer = link.from_xpointer ~= nil -- For reference, Kobo information and conditions for showing a link as popup: -- https://github.com/kobolabs/epub-spec#footnotesendnotes-are-fully-supported-across-kobo-platforms -- Calibre has its own heuristics to decide if a link is to a footnote or not, -- and what to gather around the footnote target as the footnote content to display: -- Nearly same logic, implemented in python and in coffeescript: -- https://github.com/kovidgoyal/calibre/blob/master/src/pyj/read_book/footnotes.pyj -- https://github.com/kovidgoyal/calibre/blob/master/src/calibre/ebooks/oeb/display/extract.coffee -- We do many tests, including most of those done by Kobo and Calibre, to -- detect if a link is to a footnote. -- The detection is done in cre.cpp, because it makes use of DOM navigation and -- inspection that can't be done from Lua (unless we add many proxy functions) -- Detection flags, to allow tweaking a bit cre.cpp code if needed local flags = 0 -- If no detection decided, fallback to false (not a footnote, so, follow link) if isPreferFootnoteEnabled() then flags = flags + 0x0001 -- if set, fallback to true end if trust_source_xpointer then -- trust source_xpointer: allow checking attribute and styles -- if not trusted, checks marked (*) don't apply flags = flags + 0x0002 end -- Checks for private CSS properties "-cr-hint: footnote/noteref/..." are -- always done (they can be applied to specific elements or classe names -- with Styles tweaks.) -- Trust role= and epub:type= attribute values if defined, for source(*) and target flags = flags + 0x0004 -- Accept classic FB2 footnotes: body[name="notes" or "comments"] > section flags = flags + 0x0008 -- TARGET STATUS AND SOURCE RELATION -- Target must have an anchor #id (ie: must not be a simple link to a html file) flags = flags + 0x0010 -- Target must come after source in the book -- (Glossary definitions may point to others before, so avoid this check -- if user wants more footnotes) if not isPreferFootnoteEnabled() then flags = flags + 0x0020 end -- Target must not be a target of a TOC entry flags = flags + 0x0040 -- flags = flags + 0x0080 -- Unused yet -- SOURCE NODE CONTEXT -- (*) Source link must not be empty content, and must not be the only content of -- its parent block tag (this could mean it's a chapter title in an inline ToC) flags = flags + 0x0100 -- (*) Source node vertical alignment: -- check that all non-empty-nor-space-only children have their computed -- vertical-align: any of: sub super top bottom (which will be the case -- whether a parent or the childre themselves are in a <sub> or <sup>) -- (Also checks if parent or children are <sub> or <sup>, which may -- have been tweaked with CSS to not have one of these vertical-align.) flags = flags + 0x0200 -- (*) Source node text (punctuation and parens stripped) is a number -- (3 digits max, to avoid catching years ... but only years>1000) flags = flags + 0x0400 -- (*) Source node text (punctuation and parens stripped) is 1 or 2 letters, -- with 0 to 2 numbers (a, z, ab, 1a, B2) flags = flags + 0x0800 -- TARGET NODE CONTEXT -- Target must not contain, or be contained, in H1..H6 flags = flags + 0x1000 -- flags = flags + 0x2000 -- Unused yet -- Try to extend footnote, to gather more text after target flags = flags + 0x4000 -- Extended target readable text (not accounting HTML tags) must not be -- larger than max_text_size flags = flags + 0x8000 local max_text_size = 10000 -- nb of chars logger.dbg("Checking if link is to a footnote:", flags, source_xpointer, target_xpointer) local is_footnote, reason, extStopReason, extStartXP, extEndXP = self.ui.document:isLinkToFootnote(source_xpointer, target_xpointer, flags, max_text_size) if not is_footnote then logger.info("not a footnote:", reason) return false end logger.info("is a footnote:", reason) if extStartXP then logger.info(" extended until:", extStopReason) logger.info(extStartXP) logger.info(extEndXP) else logger.info(" not extended because:", extStopReason) end -- OK, done with the dirty footnote detection work, we can now -- get back to the fancy UI stuff -- We don't request CSS files, to have a more consistent footnote style. -- (we still get and give to MuPDF styles set with style="" ) -- (We also don't because MuPDF is quite sensitive to bad css, and may -- then just ignore the whole stylesheet, including our own declarations -- we add at start) -- -- flags = 0x1001 to get the simplest/purest HTML without CSS, with added -- soft-hyphens where hyphenation is allowed (done by crengine according -- to user's hyphenation settings), and dir= and lang= attributes grabbed -- from parent nodes local html if extStartXP and extEndXP then html = self.ui.document:getHTMLFromXPointers(extStartXP, extEndXP, 0x1001) else html = self.ui.document:getHTMLFromXPointer(target_xpointer, 0x1001, true) -- from_final_parent = true to get a possibly more complete footnote end if not html then logger.info("failed getting HTML for xpointer:", target_xpointer) return false end -- if false then -- for debug, to display html -- UIManager:show( require("ui/widget/textviewer"):new{text = html}) -- return true -- end -- As we stay on the current page, we can highlight the selected link -- (which might not be seen when covered by FootnoteWidget) local close_callback = nil if link.from_xpointer then -- coherent xpointer self.ui.document:highlightXPointer() -- clear any previous one self.ui.document:highlightXPointer(link.from_xpointer) -- Don't let a previous footnote popup clear our highlight self._footnote_popup_discard_previous_close_callback = true UIManager:setDirty(self.dialog, "ui") close_callback = function(footnote_height) -- remove this highlight (actually all) on close local highlight_page = self.ui.document:getCurrentPage() local clear_highlight = function() self.ui.document:highlightXPointer() -- Only refresh if we stayed on the same page, otherwise -- this could remove too early a marker on the target page -- after this footnote is followed if self.ui.document:getCurrentPage() == highlight_page then UIManager:setDirty(self.dialog, "ui") end end if footnote_height then -- If the link was hidden by the footnote popup, -- delay a bit its clearing, so the user can see -- it and know where to start reading again local footnote_top_y = Screen:getHeight() - footnote_height if link.link_y > footnote_top_y then UIManager:scheduleIn(0.5, clear_highlight) else clear_highlight() end else clear_highlight() end end end -- We give FootnoteWidget the document margins and font size, so -- it can base its own values on them (note that this can look -- misaligned when floating punctuation is enabled, as margins then -- don't have a fixed size) local FootnoteWidget = require("ui/widget/footnotewidget") local popup popup = FootnoteWidget:new{ html = html, doc_font_size = Screen:scaleBySize(self.ui.font.font_size), doc_margins = self.ui.document:getPageMargins(), close_callback = close_callback, follow_callback = function() -- follow the link on swipe west UIManager:close(popup) self:onGotoLink(link, neglect_current_location) end, on_tap_close_callback = function(arg, ges, footnote_height) self._footnote_popup_discard_previous_close_callback = nil -- On tap outside, see if we are tapping on another footnote, -- and display it if we do (avoid the need for 2 taps) self:onTap(arg, ges) -- If onTap() did show another FootnoteWidget, and it -- has already cleared our highlight, avoid calling our -- close_callback so we do not clear the new highlight if not self._footnote_popup_discard_previous_close_callback then if close_callback then -- not set if xpointer not coherent close_callback(footnote_height) end end self._footnote_popup_discard_previous_close_callback = nil end, dialog = self.dialog, } UIManager:show(popup) return true end return ReaderLink
agpl-3.0
NatWeiss/RGP
src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/auto/api/Bone.lua
8
8058
-------------------------------- -- @module Bone -- @extend Node -- @parent_module ccs -------------------------------- -- -- @function [parent=#Bone] isTransformDirty -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Bone] setBlendFunc -- @param self -- @param #cc.BlendFunc blendFunc -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] isIgnoreMovementBoneData -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Update zorder -- @function [parent=#Bone] updateZOrder -- @param self -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] getDisplayRenderNode -- @param self -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- -- @function [parent=#Bone] isBlendDirty -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- Add a child to this bone, and it will let this child call setParent(Bone *parent) function to set self to it's parent<br> -- param child the child you want to add -- @function [parent=#Bone] addChildBone -- @param self -- @param #ccs.Bone child -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] getWorldInfo -- @param self -- @return BaseData#BaseData ret (return value: ccs.BaseData) -------------------------------- -- -- @function [parent=#Bone] getTween -- @param self -- @return Tween#Tween ret (return value: ccs.Tween) -------------------------------- -- Get parent bone<br> -- return parent bone -- @function [parent=#Bone] getParentBone -- @param self -- @return Bone#Bone ret (return value: ccs.Bone) -------------------------------- -- Update color to render display -- @function [parent=#Bone] updateColor -- @param self -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] setTransformDirty -- @param self -- @param #bool dirty -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] getDisplayRenderNodeType -- @param self -- @return int#int ret (return value: int) -------------------------------- -- -- @function [parent=#Bone] removeDisplay -- @param self -- @param #int index -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] setBoneData -- @param self -- @param #ccs.BoneData boneData -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- @overload self, string -- @overload self -- @function [parent=#Bone] init -- @param self -- @param #string name -- @return bool#bool ret (return value: bool) -------------------------------- -- Set parent bone.<br> -- If parent is NUll, then also remove this bone from armature.<br> -- It will not set the Armature, if you want to add the bone to a Armature, you should use Armature::addBone(Bone *bone, const char* parentName).<br> -- param parent the parent bone.<br> -- nullptr : remove this bone from armature -- @function [parent=#Bone] setParentBone -- @param self -- @param #ccs.Bone parent -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- @overload self, cc.Node, int -- @overload self, ccs.DisplayData, int -- @function [parent=#Bone] addDisplay -- @param self -- @param #ccs.DisplayData displayData -- @param #int index -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] getBlendFunc -- @param self -- @return BlendFunc#BlendFunc ret (return value: cc.BlendFunc) -------------------------------- -- Remove itself from its parent.<br> -- param recursion whether or not to remove childBone's display -- @function [parent=#Bone] removeFromParent -- @param self -- @param #bool recursion -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] getColliderDetector -- @param self -- @return ColliderDetector#ColliderDetector ret (return value: ccs.ColliderDetector) -------------------------------- -- -- @function [parent=#Bone] getChildArmature -- @param self -- @return Armature#Armature ret (return value: ccs.Armature) -------------------------------- -- -- @function [parent=#Bone] getTweenData -- @param self -- @return FrameData#FrameData ret (return value: ccs.FrameData) -------------------------------- -- -- @function [parent=#Bone] changeDisplayWithIndex -- @param self -- @param #int index -- @param #bool force -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] changeDisplayWithName -- @param self -- @param #string name -- @param #bool force -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] setArmature -- @param self -- @param #ccs.Armature armature -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] setBlendDirty -- @param self -- @param #bool dirty -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- Removes a child Bone<br> -- param bone the bone you want to remove -- @function [parent=#Bone] removeChildBone -- @param self -- @param #ccs.Bone bone -- @param #bool recursion -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] setChildArmature -- @param self -- @param #ccs.Armature childArmature -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] getNodeToArmatureTransform -- @param self -- @return mat4_table#mat4_table ret (return value: mat4_table) -------------------------------- -- -- @function [parent=#Bone] getDisplayManager -- @param self -- @return DisplayManager#DisplayManager ret (return value: ccs.DisplayManager) -------------------------------- -- -- @function [parent=#Bone] getArmature -- @param self -- @return Armature#Armature ret (return value: ccs.Armature) -------------------------------- -- -- @function [parent=#Bone] getBoneData -- @param self -- @return BoneData#BoneData ret (return value: ccs.BoneData) -------------------------------- -- @overload self, string -- @overload self -- @function [parent=#Bone] create -- @param self -- @param #string name -- @return Bone#Bone ret (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] updateDisplayedColor -- @param self -- @param #color3b_table parentColor -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] setLocalZOrder -- @param self -- @param #int zOrder -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] getNodeToWorldTransform -- @param self -- @return mat4_table#mat4_table ret (return value: mat4_table) -------------------------------- -- -- @function [parent=#Bone] update -- @param self -- @param #float delta -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Bone] updateDisplayedOpacity -- @param self -- @param #unsigned char parentOpacity -- @return Bone#Bone self (return value: ccs.Bone) -------------------------------- -- js ctor -- @function [parent=#Bone] Bone -- @param self -- @return Bone#Bone self (return value: ccs.Bone) return nil
mit
ZipFile/vlc
share/lua/meta/art/01_googleimage.lua
74
1764
--[[ Gets an artwork from images.google.com $Id$ Copyright © 2007 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] function descriptor() return { scope="network" } end -- Return the artwork function fetch_art() if vlc.item == nil then return nil end local meta = vlc.item:metas() -- Radio Entries if meta["Listing Type"] == "radio" then title = meta["title"] .. " radio logo" -- TV Entries elseif meta["Listing Type"] == "tv" then title = meta["title"] .. " tv logo" -- Album entries elseif meta["artist"] and meta["album"] then title = meta["artist"].." "..meta["album"].." cover" elseif meta["artist"] and meta["title"] then title = meta["artist"].." "..meta["title"].." cover" else return nil end fd = vlc.stream( "http://images.google.com/images?q="..vlc.strings.encode_uri_component( title ) ) if not fd then return nil end page = fd:read( 65653 ) fd = nil _, _, _, arturl = string.find( page, "<img height=\"([0-9]+)\" src=\"([^\"]+gstatic.com[^\"]+)\"" ) return arturl end
gpl-2.0
ld-test/lua-curl
test/test_easy.lua
1
19551
local lunit, RUN = lunit do RUN = lunit and function()end or function () local res = lunit.run() if res.errors + res.failed > 0 then os.exit(-1) end return os.exit(0) end lunit = require "lunit" end local TEST_CASE = assert(lunit.TEST_CASE) local skip = lunit.skip or function() end local curl = require "lcurl" local scurl = require "lcurl.safe" local json = require "dkjson" local path = require "path" local upath = require "path".new('/') local url = "http://example.com" local fname = "./test.download" print("------------------------------------") print("Lua version: " .. (_G.jit and _G.jit.version or _G._VERSION)) print("cURL version: " .. curl.version()) print("------------------------------------") print("") local function weak_ptr(val) return setmetatable({value = val},{__mode = 'v'}) end local function gc_collect() collectgarbage("collect") collectgarbage("collect") end local function cver(min, maj, pat) return min * 2^16 + maj * 2^8 + pat end local function is_curl_ge(min, maj, pat) assert(0x070908 == cver(7,9,8)) return curl.version_info('version_num') >= cver(min, maj, pat) end local function read_file(n) local f, e = io.open(n, "r") if not f then return nil, e end local d, e = f:read("*all") f:close() return d, e end local function get_bin_by(str,n) local pos = 1 - n return function() pos = pos + n return (str:sub(pos,pos+n-1)) end end local function strem(ch, n, m) return n, get_bin_by( (ch):rep(n), m) end local ENABLE = true local _ENV = TEST_CASE'write_callback' if ENABLE then local c, f function teardown() if f then f:close() end os.remove(fname) if c then c:close() end f, c = nil end function test_write_to_file() f = assert(io.open(fname, "w+b")) c = assert(curl.easy{ url = url; writefunction = f; }) assert_equal(c, c:perform()) end function test_write_abort_01() c = assert(scurl.easy{ url = url; writefunction = function(str) return #str - 1 end; }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_WRITE_ERROR), e) end function test_write_abort_02() c = assert(scurl.easy{ url = url; writefunction = function(str) return false end; }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_WRITE_ERROR), e) end function test_write_abort_03() c = assert(scurl.easy{ url = url; writefunction = function(str) return nil, "WRITEERROR" end; }) local _, e = assert_nil(c:perform()) assert_equal("WRITEERROR", e) end function test_write_abort_04() c = assert(scurl.easy{ url = url; writefunction = function(str) return nil end; }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_WRITE_ERROR), e) end function test_reset_write_callback() f = assert(io.open(fname, "w+b")) c = assert(curl.easy{url = url}) assert_equal(c, c:setopt_writefunction(f)) assert_equal(c, c:setopt_writefunction(f.write, f)) assert_equal(c, c:setopt_writefunction(print)) assert_error(function()c:setopt_writefunction()end) assert_error(function()c:setopt_writefunction(nil)end) assert_error(function()c:setopt_writefunction(nil, f)end) end function test_write_pass_01() c = assert(curl.easy{ url = url; writefunction = function(s) return #s end }) assert_equal(c, c:perform()) end function test_write_pass_02() c = assert(curl.easy{ url = url; writefunction = function() return end }) assert_equal(c, c:perform()) end function test_write_pass_03() c = assert(curl.easy{ url = url; writefunction = function() return true end }) assert_equal(c, c:perform()) end end local _ENV = TEST_CASE'progress_callback' if ENABLE then local c local function pass() end function teardown() if f then f:close() end os.remove(fname) if c then c:close() end f, c = nil end function test_abort_01() c = assert(scurl.easy{ url = url, writefunction = pass, noprogress = false, progressfunction = function() return false end }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_02() c = assert(scurl.easy{ url = url, writefunction = pass, noprogress = false, progressfunction = function() return 0 end }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_03() c = assert(scurl.easy{ url = url, writefunction = pass, noprogress = false, progressfunction = function() return nil end }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_04() c = assert(scurl.easy{ url = url, writefunction = pass, noprogress = false, progressfunction = function() return nil, "PROGRESSERROR" end }) local _, e = assert_nil(c:perform()) assert_equal("PROGRESSERROR", e) end function test_abort_05() c = assert(scurl.easy{ url = url, writefunction = pass, noprogress = false, progressfunction = function() error( "PROGRESSERROR" )end }) assert_error_match("PROGRESSERROR", function() c:perform() end) end function test_pass_01() c = assert(scurl.easy{ url = url, writefunction = pass, noprogress = false, progressfunction = function() end }) assert_equal(c, c:perform()) end function test_pass_02() c = assert(scurl.easy{ url = url, writefunction = pass, noprogress = false, progressfunction = function() return true end }) assert_equal(c, c:perform()) end function test_pass_03() c = assert(scurl.easy{ url = url, writefunction = pass, noprogress = false, progressfunction = function() return 1 end }) assert_equal(c, c:perform()) end end local _ENV = TEST_CASE'header_callback' if ENABLE then local c, f local function dummy() end function teardown() if c then c:close() end f, c = nil end function test_header_abort_01() c = assert(scurl.easy{ url = url; writefunction = dummy, headerfunction = function(str) return #str - 1 end; }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_WRITE_ERROR), e) end function test_header_abort_02() c = assert(scurl.easy{ url = url; writefunction = dummy, headerfunction = function(str) return false end; }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_WRITE_ERROR), e) end function test_header_abort_03() c = assert(scurl.easy{ url = url; writefunction = dummy, headerfunction = function(str) return nil, "WRITEERROR" end; }) local _, e = assert_nil(c:perform()) assert_equal("WRITEERROR", e) end function test_header_abort_04() c = assert(scurl.easy{ url = url; writefunction = dummy, headerfunction = function(str) return nil end; }) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_WRITE_ERROR), e) end function test_reset_header_callback() f = {header = function() end} c = assert(curl.easy{url = url}) assert_equal(c, c:setopt_headerfunction(f)) assert_equal(c, c:setopt_headerfunction(f.header, f)) assert_equal(c, c:setopt_headerfunction(print)) assert_error(function()c:setopt_headerfunction()end) assert_error(function()c:setopt_headerfunction(nil)end) assert_error(function()c:setopt_headerfunction(nil, f)end) end function test_header_pass_01() c = assert(curl.easy{ url = url; writefunction = dummy, headerfunction = function(s) return #s end }) assert_equal(c, c:perform()) end function test_header_pass_02() c = assert(curl.easy{ url = url; writefunction = dummy, headerfunction = function() return end }) assert_equal(c, c:perform()) end function test_header_pass_03() c = assert(curl.easy{ url = url; writefunction = dummy, headerfunction = function() return true end }) assert_equal(c, c:perform()) end end local _ENV = TEST_CASE'read_stream_callback' if ENABLE and is_curl_ge(7,30,0) then -- tested on WinXP(x32)/Win8(x64) libcurl/7.37.1 / libcurl/7.30.0 local url = "http://httpbin.org/post" local c, f, t local function json_data() return json.decode(table.concat(t)) end function setup() t = {} f = assert(scurl.form()) c = assert(scurl.easy{ url = url, timeout = 60, }) assert_equal(c, c:setopt_writefunction(table.insert, t)) end function teardown() if f then f:free() end if c then c:close() end t, f, c = nil end function test() assert_equal(f, f:add_stream('SSSSS', strem('X', 128, 13))) assert_equal(c, c:setopt_httppost(f)) assert_equal(c, c:perform()) assert_equal(200, c:getinfo_response_code()) local data = assert_table(json_data()) assert_table(data.form) assert_equal(('X'):rep(128), data.form.SSSSS) end function test_abort_01() assert_equal(f, f:add_stream('SSSSS', 128 * 1024, function() end)) assert_equal(c, c:setopt_timeout(5)) assert_equal(c, c:setopt_httppost(f)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_OPERATION_TIMEDOUT), e) end function test_abort_02() assert_equal(f, f:add_stream('SSSSS', 128, function() return nil, "READERROR" end)) assert_equal(c, c:setopt_httppost(f)) local _, e = assert_nil(c:perform()) assert_equal("READERROR", e) end function test_abort_03() assert_equal(f, f:add_stream('SSSSS', 128, function() return 1 end)) assert_equal(c, c:setopt_httppost(f)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_04() assert_equal(f, f:add_stream('SSSSS', 128, function() return true end)) assert_equal(c, c:setopt_httppost(f)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_05() assert_equal(f, f:add_stream('SSSSS', 128, function() error("READERROR") end)) assert_equal(c, c:setopt_httppost(f)) assert_error_match("READERROR", function() c:perform() end) end function test_abort_06() assert_equal(f, f:add_stream('SSSSS', 128, function() return false end)) assert_equal(c, c:setopt_httppost(f)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_pass_01() assert_equal(c, c:setopt_timeout(10)) assert_equal(f, f:add_stream('SSSSS', 128, function() return nil end)) assert_equal(c, c:setopt_httppost(f)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_OPERATION_TIMEDOUT), e) end function test_pause() local counter = 0 assert_equal(f, f:add_stream('SSSSS', 128, function() if counter == 0 then counter = counter + 1 return curl.READFUNC_PAUSE end if counter == 1 then counter = counter + 1 return ('X'):rep(128) end return '' end)) assert_equal(c, c:setopt_progressfunction(function() if counter == 1 then c:pause(curl.PAUSE_CONT) end end)) assert_equal(c, c:setopt_noprogress(false)) assert_equal(c, c:setopt_httppost(f)) assert_equal(c, c:perform()) assert_equal(200, c:getinfo_response_code()) local data = assert_table(json_data()) assert_table(data.form) assert_equal(('X'):rep(128), data.form.SSSSS) end end local _ENV = TEST_CASE'read_callback' if ENABLE then local uname = upath:normolize(path.fullpath(fname)) local url = "FILE://" .. uname local c function setup() c = assert(scurl.easy{ url = url, upload = true, }) end function teardown() os.remove(fname) if c then c:close() end c = nil end function test_abort_01() -- assert_equal(c, c:setopt_readfunction(function() end)) -- -- local _, e = assert_nil(c:perform()) -- assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_02() assert_equal(c, c:setopt_readfunction(function() return nil, "READERROR" end)) local _, e = assert_nil(c:perform()) assert_equal("READERROR", e) end function test_abort_03() assert_equal(c, c:setopt_readfunction(function() return 1 end)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_04() assert_equal(c, c:setopt_readfunction(function() return true end)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_abort_05() assert_equal(c, c:setopt_readfunction(function() error("READERROR") end)) assert_error_match("READERROR", function() c:perform() end) end function test_abort_06() assert_equal(c, c:setopt_readfunction(function() return false end)) local _, e = assert_nil(c:perform()) assert_equal(curl.error(curl.ERROR_EASY, curl.E_ABORTED_BY_CALLBACK), e) end function test_pause() -- BUG? -- c:perform() returns curl.E_READ_ERROR after readfunction return curl.READFUNC_PAUSE -- -- OS version : Linux Mint 17 (x86_64) -- cURL version : libcurl/7.35.0 OpenSSL/1.0.1f zlib/1.2.8 libidn/1.28 librtmp/2.3 -- version_info("host"): x86_64-pc-linux-gnu -- -- OS version : Windows XP (x86_64) -- cURL version : libcurl/7.38.0 OpenSSL/1.0.1c zlib/1.2.7 WinIDN -- cURL version : libcurl/7.37.1 OpenSSL/1.0.1c zlib/1.2.7 WinIDN -- version_info("host"): i386-pc-win32 -- -- Works correctly on -- (same binary as with libcurl 7.38.0/7.37.1) -- -- OS version : Windows XP (x86_64) -- cURL version : libcurl/7.30.0 OpenSSL/0.9.8y zlib/1.2.7 -- version_info("host"): i386-pc-win32 -- local counter = 0 assert_equal(c, c:setopt_readfunction(function() if counter == 0 then counter = counter + 1 return curl.READFUNC_PAUSE end if counter == 1 then counter = counter + 1 return ('X'):rep(128) end return '' end)) assert_equal(c, c:setopt_progressfunction(function() if counter == 1 then c:pause(curl.PAUSE_CONT) end end)) assert_equal(c, c:setopt_noprogress(false)) local ok, err = c:perform() if (not ok) and err:name() == "READ_ERROR" then skip("TODO check pause on readfunction") end assert_equal(c, ok, err) assert_equal(0, c:getinfo_response_code()) end function test_readbuffer() local flag = false local N assert_equal(c, c:setopt_readfunction(function(n) if not flag then flag = true N = math.floor(n*2 + n/3) assert(N > n) return ("s"):rep(N) end return '' end)) assert_equal(c, c:perform()) c:close() local data = read_file(fname) assert_equal(N, #data) assert_equal(("s"):rep(N), data) end function test_pass_01() -- We need this to support file:read() method which returns nil as EOF assert_equal(c, c:setopt_readfunction(function() return nil end)) assert_equal(c, c:perform()) c:close() local data = read_file(fname) assert_equal(0, #data) end function test_pass_02() local counter = 10 assert_equal(c, c:setopt_readfunction(function() if counter > 0 then counter = counter - 1 return 'a' end end)) assert_equal(c, c:perform()) c:close() local data = read_file(fname) assert_equal(('a'):rep(10), data) end end local _ENV = TEST_CASE'escape' if ENABLE then local c function teardown() if c then c:close() end f, c = nil end function test() local e = "This%2Bis%2Ba%2Bsimple%2B%2526%2Bshort%2Btest." local d = "This+is+a+simple+%26+short+test." c = assert(curl.easy()) assert_equal(e, c:escape(d)) assert_equal(d, c:unescape(e)) end end local _ENV = TEST_CASE'setopt_form' if ENABLE then local c function teardown() if c then c:close() end c = nil end function test() local pfrom, e do local form = curl.form() e = curl.easy{httppost = form} pfrom = weak_ptr(form) end gc_collect() assert(pfrom.value) e:setopt_httppost(curl.form()) gc_collect() assert(not pfrom.value) end function test_unset() local pfrom, e do local form = curl.form() e = curl.easy{httppost = form} pfrom = weak_ptr(form) end gc_collect() assert(pfrom.value) e:unsetopt_httppost() gc_collect() assert(not pfrom.value) end function test_reset() local pfrom, e do local form = curl.form() e = curl.easy{httppost = form} pfrom = weak_ptr(form) end gc_collect() assert(pfrom.value) e:reset() gc_collect() assert(not pfrom.value) end end local _ENV = TEST_CASE'setopt_postfields' if ENABLE then local c function teardown() if c then c:close() end c = nil end function test() do local fields = {} for i = 1, 100 do fields[#fields + 1] = "key" .. i .. "=value"..i end fields = table.concat(fields, '&') c = assert(curl.easy{ url = "http://httpbin.org/post", postfields = fields, writefunction = function()end, }) end -- call gc to try clear `fields` string for i = 1, 4 do collectgarbage"collect" end c:perform() end function test_unset() local pfields do local fields = {} for i = 1, 100 do fields[#fields + 1] = "key" .. i .. "=value"..i end fields = table.concat(fields, '&') c = assert(curl.easy{ url = "http://httpbin.org/post", postfields = fields, writefunction = function()end, }) pfields = weak_ptr(fields) end -- call gc to try clear `fields` string for i = 1, 4 do collectgarbage"collect" end assert_string(pfields.value) assert_equal(c, c:unsetopt_postfields()) -- @todo check internal storage because gc really do not clear `weak` string -- for i = 1, 4 do collectgarbage"collect" end -- assert_nil(pfields.value) -- c:perform() end end local _ENV = TEST_CASE'setopt_user_data' if ENABLE then local c function setup() if c then c:close() end c = nil end function test_data() c = assert(curl.easy()) assert_nil(c:getdata()) c:setdata("hello") assert_equal("hello", c:getdata()) end function test_cleanup() local ptr do local t = {} local e = curl.easy():setdata(t) ptr = weak_ptr(t) gc_collect() assert_equal(t, ptr.value) end gc_collect() assert_nil(ptr.value) end end RUN()
mit
bottelebot/Umbrella
plugins/gnuplot.lua
622
1813
--[[ * Gnuplot plugin by psykomantis * dependencies: * - gnuplot 5.00 * - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html * ]] -- Gnuplot needs absolute path for the plot, so i run some commands to find where we are local outputFile = io.popen("pwd","r") io.input(outputFile) local _pwd = io.read("*line") io.close(outputFile) local _absolutePlotPath = _pwd .. "/data/plot.png" local _scriptPath = "./data/gnuplotScript.gpl" do local function gnuplot(msg, fun) local receiver = get_receiver(msg) -- We generate the plot commands local formattedString = [[ set grid set terminal png set output "]] .. _absolutePlotPath .. [[" plot ]] .. fun local file = io.open(_scriptPath,"w"); file:write(formattedString) file:close() os.execute("gnuplot " .. _scriptPath) os.remove (_scriptPath) return _send_photo(receiver, _absolutePlotPath) end -- Check all dependencies before executing local function checkDependencies() local status = os.execute("gnuplot -h") if(status==true) then status = os.execute("gnuplot -e 'set terminal png'") if(status == true) then return 0 -- OK ready to go! else return 1 -- missing libgd2-xpm-dev end else return 2 -- missing gnuplot end end local function run(msg, matches) local status = checkDependencies() if(status == 0) then return gnuplot(msg,matches[1]) elseif(status == 1) then return "It seems that this bot miss a dependency :/" else return "It seems that this bot doesn't have gnuplot :/" end end return { description = "use gnuplot through telegram, only plot single variable function", usage = "!gnuplot [single variable function]", patterns = {"^!gnuplot (.+)$"}, run = run } end
gpl-2.0
xiaowa183/Atlas
lib/admin-bak.lua
37
3379
--[[ $%BEGINLICENSE%$ Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. 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 $%ENDLICENSE%$ --]] -- redefine next, used for iterate userdata rawnext = next function next(t,k) local m = getmetatable(t) local n = m and m.__next or rawnext return n(t,k) end function set_error(errmsg) proxy.response = { type = proxy.MYSQLD_PACKET_ERR, errmsg = errmsg or "error" } end function read_query(packet) if packet:byte() ~= proxy.COM_QUERY then set_error("[admin] we only handle text-based queries (COM_QUERY)") return proxy.PROXY_SEND_RESULT end local query = packet:sub(2) local rows = { } local fields = { } if query:lower() == "select * from backends" then fields = { { name = "backend_ndx", type = proxy.MYSQL_TYPE_LONG }, { name = "username", type = proxy.MYSQL_TYPE_STRING }, { name = "address", type = proxy.MYSQL_TYPE_STRING }, { name = "state", type = proxy.MYSQL_TYPE_STRING }, { name = "type", type = proxy.MYSQL_TYPE_STRING }, { name = "uuid", type = proxy.MYSQL_TYPE_STRING }, { name = "connected_clients", type = proxy.MYSQL_TYPE_LONG }, { name = "cur_idle_connections", type = proxy.MYSQL_TYPE_LONG }, } for i = 1, #proxy.global.backends do local states = { "unknown", "up", "down" } local types = { "unknown", "rw", "ro" } local b = proxy.global.backends[i] for j, username in next, b.pool.users, 0 do rows[#rows + 1] = { i, username, b.dst.name, -- configured backend address states[b.state + 1], -- the C-id is pushed down starting at 0 types[b.type + 1], -- the C-id is pushed down starting at 0 b.uuid, -- the MySQL Server's UUID if it is managed b.connected_clients, -- currently connected clients b.pool.users[username].cur_idle_connections } end end elseif query:lower() == "select * from help" then fields = { { name = "command", type = proxy.MYSQL_TYPE_STRING }, { name = "description", type = proxy.MYSQL_TYPE_STRING }, } rows[#rows + 1] = { "SELECT * FROM help", "shows this help" } rows[#rows + 1] = { "SELECT * FROM backends", "lists the backends and their state" } else set_error("use 'SELECT * FROM help' to see the supported commands") return proxy.PROXY_SEND_RESULT end proxy.response = { type = proxy.MYSQLD_PACKET_OK, resultset = { fields = fields, rows = rows } } return proxy.PROXY_SEND_RESULT end
gpl-2.0
nimaghorbani/ghbotfool
plugins/chat.lua
28
1195
local function run(msg) if msg.text == "hi" then return "Hello bb" end if msg.text == "Hi" then return "Hello honey" end if msg.text == "Hello" then return "Hi bb" end if msg.text == "hello" then return "Hi honey" end if msg.text == "Salam" then return "Salam aleykom" end if msg.text == "salam" then return "و علیکم السلام" end if msg.text == "InfernalTG" then return "BEst Bot In The World!" end if msg.text == "INFERNALtg" then return "Best Bot In The World!" end if msg.text == "INFERNALTG" then return "Best Bot In The World" end if msg.text == "Infernal" then return "Yes?" end if msg.text == "infernal" then return "What?" end if msg.text == "bot" then return "hum?" end if msg.text == "Bot" then return "Huuuum?" end if msg.text == "?" then return "Hum??" end if msg.text == "Bye" then return "Babay" end if msg.text == "bye" then return "Bye Bye" end end return { description = "Chat With Robot Server", usage = "chat with robot", patterns = { "^[Hh]i$", "^[Hh]ello$", "^[Zz]ac$", "^InfernalTG$", "^[Bb]ot$", "^[Ii]nfernal$", "^[Bb]ye$", "^?$", "^[Ss]alam$", }, run = run, --privileged = true, pre_process = pre_process }
gpl-2.0
jxwr/redis
deps/lua/test/sort.lua
889
1494
-- two implementations of a sort function -- this is an example only. Lua has now a built-in function "sort" -- extracted from Programming Pearls, page 110 function qsort(x,l,u,f) if l<u then local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u x[l],x[m]=x[m],x[l] -- swap pivot to first position local t=x[l] -- pivot value m=l local i=l+1 while i<=u do -- invariant: x[l+1..m] < t <= x[m+1..i-1] if f(x[i],t) then m=m+1 x[m],x[i]=x[i],x[m] -- swap x[i] and x[m] end i=i+1 end x[l],x[m]=x[m],x[l] -- swap pivot to a valid place -- x[l+1..m-1] < x[m] <= x[m+1..u] qsort(x,l,m-1,f) qsort(x,m+1,u,f) end end function selectionsort(x,n,f) local i=1 while i<=n do local m,j=i,i+1 while j<=n do if f(x[j],x[m]) then m=j end j=j+1 end x[i],x[m]=x[m],x[i] -- swap x[i] and x[m] i=i+1 end end function show(m,x) io.write(m,"\n\t") local i=1 while x[i] do io.write(x[i]) i=i+1 if x[i] then io.write(",") end end io.write("\n") end function testsorts(x) local n=1 while x[n] do n=n+1 end; n=n-1 -- count elements show("original",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort",x) selectionsort(x,n,function (x,y) return x>y end) show("after reverse selection sort",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort again",x) end -- array to be sorted x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"} testsorts(x)
bsd-3-clause
mjarco/sysdig
userspace/sysdig/chisels/fdbytes_by.lua
18
1508
--[[ Copyright (C) 2013-2014 Draios inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] -- Chisel description description = "Groups FD activity based on the given filter field, and returns the key that generated the most input+output bytes. For example, this script can be used to list the processes or TCP ports that generated most traffic." short_description = "I/O bytes, aggregated by an arbitrary filter field" category = "I/O" -- Chisel argument list args = { { name = "key", description = "The filter field used for grouping", argtype = "string" }, } -- The number of items to show TOP_NUMBER = 30 key_fld = "" -- Argument notification callback function on_set_arg(name, val) if name == "key" then key_fld = val return true end return false end -- Initialization callback function on_init() chisel.exec("table_generator", key_fld, key_fld, "evt.rawarg.res", "Bytes", "evt.is_io=true and evt.failed=false", "" .. TOP_NUMBER, "bytes") return true end
gpl-2.0
pazos/koreader
frontend/device/key.lua
18
2147
--[[ an interface for key presses ]] local Key = {} function Key:new(key, modifiers) local o = { key = key, modifiers = modifiers } -- we're a hash map, too o[key] = true for mod, pressed in pairs(modifiers) do if pressed then o[mod] = true end end setmetatable(o, self) self.__index = self return o end function Key:__tostring() return table.concat(self:getSequence(), "-") end --[[ get a sequence that can be matched against later use this to let the user press a sequence and then store this as configuration data (configurable shortcuts) ]] function Key:getSequence() local seq = {} for mod, pressed in pairs(self.modifiers) do if pressed then table.insert(seq, mod) end end table.insert(seq, self.key) end --[[ this will match a key against a sequence the sequence should be a table of key names that must be pressed together to match. if an entry in this table is itself a table, at least one key in this table must match. E.g.: Key:match({ "Alt", "K" }) -- match Alt-K Key:match({ "Alt", { "K", "L" }}) -- match Alt-K _or_ Alt-L ]] function Key:match(sequence) local mod_keys = {} -- a hash table for checked modifiers for _, key in ipairs(sequence) do if type(key) == "table" then local found = false for _, variant in ipairs(key) do if self[variant] then found = true break end end if not found then -- one of the needed keys is not pressed return false end elseif not self[key] then -- needed key not pressed return false elseif self.modifiers[key] ~= nil then -- checked key is a modifier key mod_keys[key] = true end end for mod, pressed in pairs(self.modifiers) do if pressed and not mod_keys[mod] then -- additional modifier keys are pressed, don't match return false end end return true end return Key
agpl-3.0
philsiff/Red-Vs-Blue
Red Vs. Blue Files/lua/vgui/dpanel.lua
2
2466
--[[ _ ( ) _| | __ _ __ ___ ___ _ _ /'_` | /'__`\( '__)/' _ ` _ `\ /'_` ) ( (_| |( ___/| | | ( ) ( ) |( (_| | `\__,_)`\____)(_) (_) (_) (_)`\__,_) DPanel --]] local PANEL = {} AccessorFunc( PANEL, "m_bBackground", "PaintBackground", FORCE_BOOL ) AccessorFunc( PANEL, "m_bBackground", "DrawBackground", FORCE_BOOL ) AccessorFunc( PANEL, "m_bIsMenuComponent", "IsMenu", FORCE_BOOL ) AccessorFunc( PANEL, "m_bDisableTabbing", "TabbingDisabled", FORCE_BOOL ) AccessorFunc( PANEL, "m_bDisabled", "Disabled" ) AccessorFunc( PANEL, "m_bgColor", "BackgroundColor" ) Derma_Hook( PANEL, "Paint", "Paint", "Panel" ) Derma_Hook( PANEL, "ApplySchemeSettings", "Scheme", "Panel" ) Derma_Hook( PANEL, "PerformLayout", "Layout", "Panel" ) --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:Init() self:SetPaintBackground( true ) -- This turns off the engine drawing self:SetPaintBackgroundEnabled( false ) self:SetPaintBorderEnabled( false ) end --[[--------------------------------------------------------- -----------------------------------------------------------]] function PANEL:SetDisabled( bDisabled ) self.m_bDisabled = bDisabled if ( bDisabled ) then self:SetAlpha( 75 ) self:SetMouseInputEnabled( false ) else self:SetAlpha( 255 ) self:SetMouseInputEnabled( true ) end end --[[--------------------------------------------------------- OnMousePressed -----------------------------------------------------------]] function PANEL:OnMousePressed( mousecode ) if ( self.m_bSelectionCanvas && !dragndrop.IsDragging() ) then self:StartBoxSelection(); return end if ( self:IsDraggable() ) then self:MouseCapture( true ) self:DragMousePress( mousecode ); end end --[[--------------------------------------------------------- OnMouseReleased -----------------------------------------------------------]] function PANEL:OnMouseReleased( mousecode ) if ( self:EndBoxSelection() ) then return end self:MouseCapture( false ) if ( self:DragMouseRelease( mousecode ) ) then return end end --[[--------------------------------------------------------- UpdateColours -----------------------------------------------------------]] function PANEL:UpdateColours() end derma.DefineControl( "DPanel", "", PANEL, "Panel" )
mit
LuaDist2/lua-path
lua/path/findfile.lua
2
2396
------------------------------------------------------------------ -- -- Author: Alexey Melnichuk <alexeymelnichuck@gmail.com> -- -- Copyright (C) 2013-2016 Alexey Melnichuk <alexeymelnichuck@gmail.com> -- -- Licensed according to the included 'LICENCE' document -- -- This file is part of lua-path library. -- ------------------------------------------------------------------ --- -- Implementation of afx.findfile local string = require "string" local table = require "table" local coroutine = require "coroutine" local PATH = require "path.module" local function load(findfile_t) local function clone(t) local o = {} for k,v in pairs(t) do o[k] = v end return o end local function findfile_ssf(str_file, str_params, func_callback, tbl_option) tbl_option = tbl_option and clone(tbl_option) or {} tbl_option.file = assert(str_file) tbl_option.param = assert(str_params) tbl_option.callback = assert(func_callback) return findfile_t(tbl_option) end local function findfile_ss(str_file, str_params, tbl_option) tbl_option = tbl_option and clone(tbl_option) or {} tbl_option.file = assert(str_file) tbl_option.param = assert(str_params) return findfile_t(tbl_option) end local function findfile_sf(str_file, func_callback, tbl_option) tbl_option = tbl_option and clone(tbl_option) or {} tbl_option.file = assert(str_file) tbl_option.callback = assert(func_callback) return findfile_t(tbl_option) end local function findfile_s(str_file, tbl_option) tbl_option = tbl_option and clone(tbl_option) or {} tbl_option.file = assert(str_file) return findfile_t(tbl_option) end local function findfile_f(func_callback, tbl_option) tbl_option = clone(assert(tbl_option)) -- need file tbl_option.callback = assert(func_callback) return findfile_t(tbl_option) end local function findfile(p1,p2,p3,p4) if type(p1) == 'string' then if type(p2) == 'string' then if type(p3) == 'function' then return findfile_ssf(p1,p2,p3,p4) end return findfile_ss(p1,p2,p3) end if type(p2) == 'function' then return findfile_sf(p1,p2,p3) end return findfile_s(p1,p2) end if type(p1) == 'function' then return findfile_f(p1,p2) end return findfile_t(p1) end return findfile end return {load = load}
mit
LuaDist2/luarocks
src/luarocks/refresh_cache.lua
9
1061
--- Module implementing the luarocks-admin "refresh_cache" command. local refresh_cache = {} package.loaded["luarocks.refresh_cache"] = refresh_cache local util = require("luarocks.util") local cfg = require("luarocks.cfg") local cache = require("luarocks.cache") util.add_run_function(refresh_cache) refresh_cache.help_summary = "Refresh local cache of a remote rocks server." refresh_cache.help_arguments = "[--from=<server>]" refresh_cache.help = [[ The flag --from indicates which server to use. If not given, the default server set in the upload_server variable from the configuration file is used instead. ]] function refresh_cache.command(flags) local server, upload_server = cache.get_upload_server(flags["server"]) if not server then return nil, upload_server end local download_url = cache.get_server_urls(server, upload_server) local ok, err = cache.refresh_local_cache(server, download_url, cfg.upload_user, cfg.upload_password) if not ok then return nil, err else return true end end return refresh_cache
mit
the1glorfindel/minetest-sickle
sickle.lua
1
1095
farming.register_sickle(":farming:sickle_wood", { description = "Wooden Sickle", inventory_image = "farming_tool_woodhoe.png", max_uses = 60, material = "group:wood" }) farming.register_sickle(":farming:sickle_stone", { description = "Stone Sickle", inventory_image = "farming_tool_stonehoe.png", max_uses = 120, material = "group:stone" }) farming.register_sickle(":farming:sickle_steel", { description = "Steel Sickle", inventory_image = "farming_tool_steelhoe.png", max_uses = 300, material = "default:steel_ingot" }) farming.register_sickle(":farming:sickle_bronze", { description = "Bronze Sickle", inventory_image = "farming_tool_bronzehoe.png", max_uses = 220, material = "default:bronze_ingot" }) farming.register_sickle(":farming:sickle_mese", { description = "Mese Sickle", inventory_image = "farming_tool_mesehoe.png", max_uses = 450, material = "default:mese_crystal" }) farming.register_sickle(":farming:sickle_diamond", { description = "Diamond Sickle", inventory_image = "farming_tool_diamondhoe.png", max_uses = 1000, material = "default:diamond" })
gpl-2.0
MRMV2000/amira-o
system/libs/serpent.lua
656
7877
local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
gpl-2.0
redxdev/Wake
dist/game/init.lua
1
1988
local Camera = require('camera') local config = require('config.cfg') local obj = assets.loadModel("assets/models/sponza.wmdl") if obj == nil then print("Unable to load model.") return end assets.loadMaterials(obj) engine.setClearColor(1, 1, 1, 1) local cam = Camera.new(Vector3.new(-2.5, 0, 0)) local speed = 1 local fastSpeed = 2 engine.tick:bind(function(dt) local moveSpeed = speed if input.getKey(input.key.LeftShift) == input.action.Press then moveSpeed = fastSpeed end if input.getKey(input.key.W) == input.action.Press then cam:moveForward(moveSpeed * dt) end if input.getKey(input.key.S) == input.action.Press then cam:moveForward(-moveSpeed * dt) end if input.getKey(input.key.A) == input.action.Press then cam:moveRight(-moveSpeed * dt) end if input.getKey(input.key.D) == input.action.Press then cam:moveRight(moveSpeed * dt) end if input.getKey(input.key.Q) == input.action.Press then cam:moveUp(-moveSpeed * dt) end if input.getKey(input.key.E) == input.action.Press then cam:moveUp(moveSpeed * dt) end local params = Material.new() params:setMatrix4("transform", math.scale{0.002, 0.002, 0.002}) cam:use(params) obj:draw(params) end) engine.quit:bind(function() print("Shutdown at " .. engine.getTime()) end) input.event.key:bind(function(key, action) if key == input.key.Escape and action == input.action.Release then engine.stop() end end) local lastX = 0 local lastY = 0 local firstMouse = true input.setCursorMode(input.cursorMode.Disabled) input.event.cursorPos:bind(function(x, y) if firstMouse then firstMouse = false lastX = x lastY = y end local xOffset = (x - lastX) * config.input.mouseSensitivity local yOffset = (y - lastY) * config.input.mouseSensitivity cam:addRotation(Vector3.new{0, xOffset, yOffset}) lastX = x lastY = y end)
mit
githabbot/server22
plugins/lock_sticker.lua
17
19859
-- data saved to data/moderation.json do local administrators_only = 'For administrator only!' local moderators_only = 'For moderators only!' local function create_group(msg) if not is_admin(msg) then return administrators_only end local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.' end local function addgroup(msg) if not is_admin(msg) then return administrators_only end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_bots = 'no', lock_name = 'no', lock_photo = 'no', lock_member = 'no', anti_flood = 'no', welcome = 'no', sticker = 'ok' } } save_data(_config.moderation.data, data) return 'Group has been added.' end local function remgroup(msg) if not is_admin(msg) then return administrators_only end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if not data[tostring(msg.to.id)] then return 'Group is not added.' end data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return 'Group has been removed' end local function export_chat_link_callback(extra, success, result) local msg = extra.msg local group_name = msg.to.title local data = extra.data local receiver = get_receiver(msg) if success == 0 then return send_large_msg(receiver, 'Cannot generate invite link for this group.\nMake sure you are an admin or a sudoer.') end data[tostring(msg.to.id)]['link'] = result save_data(_config.moderation.data, data) return send_large_msg(receiver,'Newest generated invite link for '..group_name..' is:\n'..result) end local function set_description(msg, data) if not is_mod(msg) then return moderators_only end local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = deskripsi save_data(_config.moderation.data, data) return 'Set group description to:\n'..deskripsi end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] return string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about end local function set_rules(msg, data) if not is_mod(msg) then return moderators_only end local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules return rules end -- dis/allow APIs bots to enter group. Spam prevention. local function allow_api_bots(msg, data) if not is_mod(msg) then return moderators_only end local group_bot_lock = data[tostring(msg.to.id)]['settings']['lock_bots'] if group_bot_lock == 'no' then return 'Bots are allowed to enter group.' else data[tostring(msg.to.id)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Group is open for bots.' end end local function disallow_api_bots(msg, data) if not is_mod(msg) then return moderators_only end local group_bot_lock = data[tostring(msg.to.id)]['settings']['lock_bots'] if group_bot_lock == 'yes' then return 'Group is already locked from bots.' else data[tostring(msg.to.id)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Group is locked from bots.' end end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data) if not is_mod(msg) then return moderators_only end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ') save_data(_config.moderation.data, data) return 'Group name has been locked' end end local function unlock_group_name(msg, data) if not is_mod(msg) then return moderators_only end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data) if not is_mod(msg) then return moderators_only end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data) if not is_mod(msg) then return moderators_only end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data) if not is_mod(msg) then return moderators_only end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data) if not is_mod(msg) then return moderators_only end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end -- show group settings local function show_group_settings(msg, data) if not is_mod(msg) then return moderators_only end local settings = data[tostring(msg.to.id)]['settings'] if settings.lock_bots == 'yes' then lock_bots_state = 'ًں”’' elseif settings.lock_bots == 'no' then lock_bots_state = 'ًں”“' end if settings.lock_name == 'yes' then lock_name_state = 'ًں”’' elseif settings.lock_name == 'no' then lock_name_state = 'ًں”“' end if settings.lock_photo == 'yes' then lock_photo_state = 'ًں”’' elseif settings.lock_photo == 'no' then lock_photo_state = 'ًں”“' end if settings.lock_member == 'yes' then lock_member_state = 'ًں”’' elseif settings.lock_member == 'no' then lock_member_state = 'ًں”“' end if settings.anti_flood ~= 'no' then antiflood_state = 'ًں”’' elseif settings.anti_flood == 'no' then antiflood_state = 'ًں”“' end if settings.welcome ~= 'no' then greeting_state = 'ًں”’' elseif settings.welcome == 'no' then greeting_state = 'ًں”“' end if settings.sticker ~= 'ok' then sticker_state = 'ًں”’' elseif settings.sticker == 'ok' then sticker_state = 'ًں”“' end local text = 'Group settings:\n' ..'\n'..lock_bots_state..' Lock group from bot : '..settings.lock_bots ..'\n'..lock_name_state..' Lock group name : '..settings.lock_name ..'\n'..lock_photo_state..' Lock group photo : '..settings.lock_photo ..'\n'..lock_member_state..' Lock group member : '..settings.lock_member ..'\n'..antiflood_state..' Flood protection : '..settings.anti_flood ..'\n'..greeting_state..' Welcome message : '..settings.welcome ..'\n'..sticker_state..' Sticker policy : '..settings.sticker return text end -- media handler. needed by group_photo_lock local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end function run(msg, matches) if not is_chat_msg(msg) then return "This is not a group chat." end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) -- create a group if matches[1] == 'mkgroup' and matches[2] then group_name = matches[2] return create_group(msg) end -- add a group to be moderated if matches[1] == 'addgroup' then return addgroup(msg) end -- remove group from moderation if matches[1] == 'remgroup' then return remgroup(msg) end if msg.media and is_chat_msg(msg) and is_momod(msg) then if msg.media.type == 'photo' and data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then load_photo(msg.id, set_group_photo, msg) end end end if data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'setabout' and matches[2] then deskripsi = matches[2] return set_description(msg, data) end if matches[1] == 'about' then return get_description(msg, data) end if matches[1] == 'setrules' then rules = matches[2] return set_rules(msg, data) end if matches[1] == 'rules' then return get_rules(msg, data) end -- group link {get|set} if matches[1] == 'link' then if matches[2] == 'get' then if data[tostring(msg.to.id)]['link'] then local about = get_description(msg, data) local link = data[tostring(msg.to.id)]['link'] return about.."\n\n"..link else return 'Invite link does not exist.\nTry !link set to generate it.' end end if matches[2] == 'set' and is_mod(msg) then msgr = export_chat_link(receiver, export_chat_link_callback, {data=data, msg=msg}) end end if matches[1] == 'group' then -- lock {bot|name|member|photo|sticker} if matches[2] == 'lock' then if matches[3] == 'bot' then return disallow_api_bots(msg, data) end if matches[3] == 'name' then return lock_group_name(msg, data) end if matches[3] == 'member' then return lock_group_member(msg, data) end if matches[3] == 'photo' then return lock_group_photo(msg, data) end -- unlock {bot|name|member|photo|sticker} elseif matches[2] == 'unlock' then if matches[3] == 'bot' then return allow_api_bots(msg, data) end if matches[3] == 'name' then return unlock_group_name(msg, data) end if matches[3] == 'member' then return unlock_group_member(msg, data) end if matches[3] == 'photo' then return unlock_group_photo(msg, data) end -- view group settings elseif matches[2] == 'settings' then return show_group_settings(msg, data) end end if matches[1] == 'sticker' then if matches[2] == 'warn' then if is_momod(msg) then if welcome_stat ~= 'warn' then data[tostring(msg.to.id)]['settings']['sticker'] = 'warn' save_data(_config.moderation.data, data) end return 'فعال شد\nدر صورت ارسال استیکر،ابتدا اخطار داده شده\nدر صورت ارسال مجدد از گروه حذف خواهد شد' end end if matches[2] == 'kick' then if is_momod(msg) then if welcome_stat ~= 'kick' then data[tostring(msg.to.id)]['settings']['sticker'] = 'kick' save_data(_config.moderation.data, data) end return 'فعال شد!\nدر صورت ارسال استیکر،فرد ارسال کننده حذف خواهد شد' end end if matches[2] == 'ok' then if is_momod(msg) then if welcome_stat == 'ok' then return 'قفل استیکر غیرفعال شد' else data[tostring(msg.to.id)]['settings']['sticker'] = 'ok' save_data(_config.moderation.data, data) return 'قفل استیکر غیر فعال میباشد ' end end end end -- if group name is renamed if matches[1] == 'chat_rename' then if not msg.service then return 'Are you trying to troll me?' end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end -- set group name if matches[1] == 'setname' and is_mod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) end -- set group photo if matches[1] == 'setphoto' and is_mod(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 a user is added to group 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 group_bot_lock = settings.lock_bots local user = 'user#id'..msg.action.user.id if group_member_lock == 'yes' then chat_del_user(receiver, user, ok_cb, true) -- no APIs bot are allowed to enter chat group. elseif group_bot_lock == 'yes' and msg.action.user.flags == 4352 then chat_del_user(receiver, user, ok_cb, true) elseif group_bot_lock == 'no' or group_member_lock == 'no' then return nil end end -- if sticker is sent if msg.media and msg.media.caption == 'sticker.webp' and not is_momod(msg) then local user_id = msg.from.id local chat_id = msg.to.id local sticker_hash = 'mer_sticker:'..chat_id..':'..user_id local is_sticker_offender = redis:get(sticker_hash) if settings.sticker == 'warn' then if is_sticker_offender then chat_del_user(receiver, 'user#id'..user_id, ok_cb, true) redis:del(sticker_hash) return 'به دلیل ارسال استیکر از ادامه چت محروم میشوید' elseif not is_sticker_offender then redis:set(sticker_hash, true) return ' استیکر ارسال نکنید!\nاین یک اخطار میباشد\n\nدر صورت رعایت نکردن از گروه حذف خواهید شد' end elseif settings.sticker == 'kick' then chat_del_user(receiver, 'user#id'..user_id, ok_cb, true) return 'به دلیل استفاده از استیکر از گروه حذف میشوید' elseif settings.sticker == 'ok' then return nil end end -- if group photo is deleted if matches[1] == 'chat_delete_photo' then if not msg.service then return 'Are you trying to troll me?' end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end -- if group photo is changed if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return 'Are you trying to troll me?' end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end end end return { description = 'Plugin to manage group chat.', usage = { admin = { '!mkgroup <group_name> : Make/create a new group.', '!addgroup : Add group to moderation list.', '!remgroup : Remove group from moderation list.' }, moderator = { '!group <lock|unlock> bot : {Dis}allow APIs bots.', '!group <lock|unlock> member : Lock/unlock group member.', '!group <lock|unlock> name : Lock/unlock group name.', '!group <lock|unlock> photo : Lock/unlock group photo.', '!group settings : Show group settings.', '!link <set> : Generate/revoke invite link.', '!setabout <description> : Set group description.', '!setname <new_name> : Set group name.', '!setphoto : Set group photo.', '!setrules <rules> : Set group rules.', '!sticker warn : Sticker restriction, sender will be warned for the first violation.', '!sticker kick : Sticker restriction, sender will be kick.', '!sticker ok : Disable sticker restriction.' }, user = { '!about : Read group description', '!rules : Read group rules', '!link <get> : Print invite link' }, }, patterns = { --"^!(about)$", --"^!(addgroup)$", "%[(audio)%]", "%[(document)%]", --"^!(group) (lock) (.*)$", --"^!(group) (settings)$", --"^!(group) (unlock) (.*)$", --"^!(link) (.*)$", --"^!(mkgroup) (.*)$", --"%[(photo)%]", --"^!(remgroup)$", --"^!(rules)$", -- "^!(setabout) (.*)$", -- "^!(setname) (.*)$", --"^!(setphoto)$", --"^!(setrules) (.*)$", "^[!/](sticker) (.*)$", "^!!tgservice (.+)$", "%[(video)%]" }, run = run, pre_process = pre_process } end -- arman ino neveshte dg entezare bishtar azin nadashte bashid :| --namosan hal nadaram baqiasho hazf konam :| --hamino estefade konid okeye moshkeli nadare :| --negarane speed plug ham nabashid chon pattern ha bastas,okeye ;)
gpl-2.0
InfiniteRain/CS2D-AmplifiedScripting
classes/map.lua
1
3652
-- Initializing map class. cas.map = cas.class() -------------------- -- Static methods -- -------------------- --== Getters ==-- -- Gets the name of the map. function cas.map.getName() return cas._cs2dCommands.map("name") end -- Gets the X size of the map. function cas.map.getXSize() return cas._cs2dCommands.map("xsize") end -- Gets the Y size of the map. function cas.map.getYSize() return cas._cs2dCommands.map("ysize") end -- Gets the size of the map. function cas.map.getSize() return cas._cs2dCommands.map("xsize"), cas._cs2dCommands.map("ysize") end -- Gets the tileset used for the map. function cas.map.getTileset() return cas._cs2dCommands.map("tileset") end -- Gets the number of tiles in the tileset. function cas.map.getTileCount() return cas._cs2dCommands.map("tilecount") end -- Gets background image. function cas.map.getBackgroundImage() return cas._cs2dCommands.map("back_img") end -- Gets background scroll X speed. function cas.map.getBackgroundScrollXSpeed() return cas._cs2dCommands.map("back_scrollx") end -- Gets background scroll Y speed. function cas.map.getBackgroundScrollYSpeed() return cas._cs2dCommands.map("back_scrolly") end -- Gets background scroll speed. function cas.map.getBackgroundScrollSpeed() return cas._cs2dCommands.map("back_scrollx"), cas._cs2dCommands.map("back_scrolly") end -- Gets whether or not the background scrolls like tiles. function cas.map.isBackgroundScrollLikeTiles() return cas._cs2dCommands.map("back_scrolltile") end -- Gets background color. function cas.map.getBackgroundColor() return cas.color.new( cas._cs2dCommands.map("back_r"), cas._cs2dCommands.map("back_g"), cas._cs2dCommands.map("back_b")) end -- Gets storm X speed. function cas.map.getStormXSpeed() return cas._cs2dCommands.map("storm_x") end -- Gets storm Y speed. function cas.map.getStormYSpeed() return cas._cs2dCommands.map("storm_y") end -- Gets storm speed. function cas.map.getStormSpeed() return cas._cs2dCommands.map("storm_x"), cas._cs2dCommands.map("storm_y") end -- Gets the number of VIP spawns. function cas.map.getVIPSpawns() return cas._cs2dCommands.map("mission_vips") end -- Gets the number of hostages. function cas.map.getHostages() return cas._cs2dCommands.map("mission_hostages") end -- Gets the number of bomb spots. function cas.map.getBombSpots() return cas._cs2dCommands.map("mission_bombspots") end -- Gets the number of CTF flags. function cas.map.getCTFFlags() return cas._cs2dCommands.map("mission_ctfflags") end -- Gets the number of domination points. function cas.map.getDomPoints() return cas._cs2dCommands.map("mission_dompoints") end -- Checks if buying is allowed. function cas.map.isBuyingAllowed() return cas._cs2dCommands.map("nobuying") == 0 and true or false end -- Checks if weapons are allowed. function cas.map.isWeaponsAllowed() return cas._cs2dCommands.map("noweapons") == 0 and true or false end -- Checks if there are any teleporters on the map. function cas.map.isTelporters() return cas._cs2dCommands.map("teleporters") == 0 and false or true end -- Gets the number of the bot nodes. function cas.map.getBotNodes() return cas._cs2dCommands.map("botnodes") end --== Setters/control ==-- -- Changes server map. function cas.map.changeMap(name) if type(name) ~= "string" then error("Passed \"name\" parameter is not valid. String expected, ".. type(name) .." passed.", 2) end cas.console.parse("changemap", name) end ---------------------- -- Instance methods -- ---------------------- -- Constructor. function cas.map:constructor() error("Instantiation of this class is not allowed.", 2) end
mit
sdgdsffdsfff/nginx-openresty-windows
LuaJIT-2.1-20150622/src/jit/dis_ppc.lua
78
20318
---------------------------------------------------------------------------- -- LuaJIT PPC disassembler module. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT/X license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- It disassembles all common, non-privileged 32/64 bit PowerPC instructions -- plus the e500 SPE instructions and some Cell/Xenon extensions. -- -- NYI: VMX, VMX128 ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local concat = table.concat local bit = require("bit") local band, bor, tohex = bit.band, bit.bor, bit.tohex local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift ------------------------------------------------------------------------------ -- Primary and extended opcode maps ------------------------------------------------------------------------------ local map_crops = { shift = 1, mask = 1023, [0] = "mcrfXX", [33] = "crnor|crnotCCC=", [129] = "crandcCCC", [193] = "crxor|crclrCCC%", [225] = "crnandCCC", [257] = "crandCCC", [289] = "creqv|crsetCCC%", [417] = "crorcCCC", [449] = "cror|crmoveCCC=", [16] = "b_lrKB", [528] = "b_ctrKB", [150] = "isync", } local map_rlwinm = setmetatable({ shift = 0, mask = -1, }, { __index = function(t, x) local rot = band(rshift(x, 11), 31) local mb = band(rshift(x, 6), 31) local me = band(rshift(x, 1), 31) if mb == 0 and me == 31-rot then return "slwiRR~A." elseif me == 31 and mb == 32-rot then return "srwiRR~-A." else return "rlwinmRR~AAA." end end }) local map_rld = { shift = 2, mask = 7, [0] = "rldiclRR~HM.", "rldicrRR~HM.", "rldicRR~HM.", "rldimiRR~HM.", { shift = 1, mask = 1, [0] = "rldclRR~RM.", "rldcrRR~RM.", }, } local map_ext = setmetatable({ shift = 1, mask = 1023, [0] = "cmp_YLRR", [32] = "cmpl_YLRR", [4] = "twARR", [68] = "tdARR", [8] = "subfcRRR.", [40] = "subfRRR.", [104] = "negRR.", [136] = "subfeRRR.", [200] = "subfzeRR.", [232] = "subfmeRR.", [520] = "subfcoRRR.", [552] = "subfoRRR.", [616] = "negoRR.", [648] = "subfeoRRR.", [712] = "subfzeoRR.", [744] = "subfmeoRR.", [9] = "mulhduRRR.", [73] = "mulhdRRR.", [233] = "mulldRRR.", [457] = "divduRRR.", [489] = "divdRRR.", [745] = "mulldoRRR.", [969] = "divduoRRR.", [1001] = "divdoRRR.", [10] = "addcRRR.", [138] = "addeRRR.", [202] = "addzeRR.", [234] = "addmeRR.", [266] = "addRRR.", [522] = "addcoRRR.", [650] = "addeoRRR.", [714] = "addzeoRR.", [746] = "addmeoRR.", [778] = "addoRRR.", [11] = "mulhwuRRR.", [75] = "mulhwRRR.", [235] = "mullwRRR.", [459] = "divwuRRR.", [491] = "divwRRR.", [747] = "mullwoRRR.", [971] = "divwouRRR.", [1003] = "divwoRRR.", [15] = "iselltRRR", [47] = "iselgtRRR", [79] = "iseleqRRR", [144] = { shift = 20, mask = 1, [0] = "mtcrfRZ~", "mtocrfRZ~", }, [19] = { shift = 20, mask = 1, [0] = "mfcrR", "mfocrfRZ", }, [371] = { shift = 11, mask = 1023, [392] = "mftbR", [424] = "mftbuR", }, [339] = { shift = 11, mask = 1023, [32] = "mferR", [256] = "mflrR", [288] = "mfctrR", [16] = "mfspefscrR", }, [467] = { shift = 11, mask = 1023, [32] = "mtxerR", [256] = "mtlrR", [288] = "mtctrR", [16] = "mtspefscrR", }, [20] = "lwarxRR0R", [84] = "ldarxRR0R", [21] = "ldxRR0R", [53] = "lduxRRR", [149] = "stdxRR0R", [181] = "stduxRRR", [341] = "lwaxRR0R", [373] = "lwauxRRR", [23] = "lwzxRR0R", [55] = "lwzuxRRR", [87] = "lbzxRR0R", [119] = "lbzuxRRR", [151] = "stwxRR0R", [183] = "stwuxRRR", [215] = "stbxRR0R", [247] = "stbuxRRR", [279] = "lhzxRR0R", [311] = "lhzuxRRR", [343] = "lhaxRR0R", [375] = "lhauxRRR", [407] = "sthxRR0R", [439] = "sthuxRRR", [54] = "dcbst-R0R", [86] = "dcbf-R0R", [150] = "stwcxRR0R.", [214] = "stdcxRR0R.", [246] = "dcbtst-R0R", [278] = "dcbt-R0R", [310] = "eciwxRR0R", [438] = "ecowxRR0R", [470] = "dcbi-RR", [598] = { shift = 21, mask = 3, [0] = "sync", "lwsync", "ptesync", }, [758] = "dcba-RR", [854] = "eieio", [982] = "icbi-R0R", [1014] = "dcbz-R0R", [26] = "cntlzwRR~", [58] = "cntlzdRR~", [122] = "popcntbRR~", [154] = "prtywRR~", [186] = "prtydRR~", [28] = "andRR~R.", [60] = "andcRR~R.", [124] = "nor|notRR~R=.", [284] = "eqvRR~R.", [316] = "xorRR~R.", [412] = "orcRR~R.", [444] = "or|mrRR~R=.", [476] = "nandRR~R.", [508] = "cmpbRR~R", [512] = "mcrxrX", [532] = "ldbrxRR0R", [660] = "stdbrxRR0R", [533] = "lswxRR0R", [597] = "lswiRR0A", [661] = "stswxRR0R", [725] = "stswiRR0A", [534] = "lwbrxRR0R", [662] = "stwbrxRR0R", [790] = "lhbrxRR0R", [918] = "sthbrxRR0R", [535] = "lfsxFR0R", [567] = "lfsuxFRR", [599] = "lfdxFR0R", [631] = "lfduxFRR", [663] = "stfsxFR0R", [695] = "stfsuxFRR", [727] = "stfdxFR0R", [759] = "stfduxFR0R", [855] = "lfiwaxFR0R", [983] = "stfiwxFR0R", [24] = "slwRR~R.", [27] = "sldRR~R.", [536] = "srwRR~R.", [792] = "srawRR~R.", [824] = "srawiRR~A.", [794] = "sradRR~R.", [826] = "sradiRR~H.", [827] = "sradiRR~H.", [922] = "extshRR~.", [954] = "extsbRR~.", [986] = "extswRR~.", [539] = "srdRR~R.", }, { __index = function(t, x) if band(x, 31) == 15 then return "iselRRRC" end end }) local map_ld = { shift = 0, mask = 3, [0] = "ldRRE", "lduRRE", "lwaRRE", } local map_std = { shift = 0, mask = 3, [0] = "stdRRE", "stduRRE", } local map_fps = { shift = 5, mask = 1, { shift = 1, mask = 15, [0] = false, false, "fdivsFFF.", false, "fsubsFFF.", "faddsFFF.", "fsqrtsF-F.", false, "fresF-F.", "fmulsFF-F.", "frsqrtesF-F.", false, "fmsubsFFFF~.", "fmaddsFFFF~.", "fnmsubsFFFF~.", "fnmaddsFFFF~.", } } local map_fpd = { shift = 5, mask = 1, [0] = { shift = 1, mask = 1023, [0] = "fcmpuXFF", [32] = "fcmpoXFF", [64] = "mcrfsXX", [38] = "mtfsb1A.", [70] = "mtfsb0A.", [134] = "mtfsfiA>>-A>", [8] = "fcpsgnFFF.", [40] = "fnegF-F.", [72] = "fmrF-F.", [136] = "fnabsF-F.", [264] = "fabsF-F.", [12] = "frspF-F.", [14] = "fctiwF-F.", [15] = "fctiwzF-F.", [583] = "mffsF.", [711] = "mtfsfZF.", [392] = "frinF-F.", [424] = "frizF-F.", [456] = "fripF-F.", [488] = "frimF-F.", [814] = "fctidF-F.", [815] = "fctidzF-F.", [846] = "fcfidF-F.", }, { shift = 1, mask = 15, [0] = false, false, "fdivFFF.", false, "fsubFFF.", "faddFFF.", "fsqrtF-F.", "fselFFFF~.", "freF-F.", "fmulFF-F.", "frsqrteF-F.", false, "fmsubFFFF~.", "fmaddFFFF~.", "fnmsubFFFF~.", "fnmaddFFFF~.", } } local map_spe = { shift = 0, mask = 2047, [512] = "evaddwRRR", [514] = "evaddiwRAR~", [516] = "evsubwRRR~", [518] = "evsubiwRAR~", [520] = "evabsRR", [521] = "evnegRR", [522] = "evextsbRR", [523] = "evextshRR", [524] = "evrndwRR", [525] = "evcntlzwRR", [526] = "evcntlswRR", [527] = "brincRRR", [529] = "evandRRR", [530] = "evandcRRR", [534] = "evxorRRR", [535] = "evor|evmrRRR=", [536] = "evnor|evnotRRR=", [537] = "eveqvRRR", [539] = "evorcRRR", [542] = "evnandRRR", [544] = "evsrwuRRR", [545] = "evsrwsRRR", [546] = "evsrwiuRRA", [547] = "evsrwisRRA", [548] = "evslwRRR", [550] = "evslwiRRA", [552] = "evrlwRRR", [553] = "evsplatiRS", [554] = "evrlwiRRA", [555] = "evsplatfiRS", [556] = "evmergehiRRR", [557] = "evmergeloRRR", [558] = "evmergehiloRRR", [559] = "evmergelohiRRR", [560] = "evcmpgtuYRR", [561] = "evcmpgtsYRR", [562] = "evcmpltuYRR", [563] = "evcmpltsYRR", [564] = "evcmpeqYRR", [632] = "evselRRR", [633] = "evselRRRW", [634] = "evselRRRW", [635] = "evselRRRW", [636] = "evselRRRW", [637] = "evselRRRW", [638] = "evselRRRW", [639] = "evselRRRW", [640] = "evfsaddRRR", [641] = "evfssubRRR", [644] = "evfsabsRR", [645] = "evfsnabsRR", [646] = "evfsnegRR", [648] = "evfsmulRRR", [649] = "evfsdivRRR", [652] = "evfscmpgtYRR", [653] = "evfscmpltYRR", [654] = "evfscmpeqYRR", [656] = "evfscfuiR-R", [657] = "evfscfsiR-R", [658] = "evfscfufR-R", [659] = "evfscfsfR-R", [660] = "evfsctuiR-R", [661] = "evfsctsiR-R", [662] = "evfsctufR-R", [663] = "evfsctsfR-R", [664] = "evfsctuizR-R", [666] = "evfsctsizR-R", [668] = "evfststgtYRR", [669] = "evfststltYRR", [670] = "evfststeqYRR", [704] = "efsaddRRR", [705] = "efssubRRR", [708] = "efsabsRR", [709] = "efsnabsRR", [710] = "efsnegRR", [712] = "efsmulRRR", [713] = "efsdivRRR", [716] = "efscmpgtYRR", [717] = "efscmpltYRR", [718] = "efscmpeqYRR", [719] = "efscfdR-R", [720] = "efscfuiR-R", [721] = "efscfsiR-R", [722] = "efscfufR-R", [723] = "efscfsfR-R", [724] = "efsctuiR-R", [725] = "efsctsiR-R", [726] = "efsctufR-R", [727] = "efsctsfR-R", [728] = "efsctuizR-R", [730] = "efsctsizR-R", [732] = "efststgtYRR", [733] = "efststltYRR", [734] = "efststeqYRR", [736] = "efdaddRRR", [737] = "efdsubRRR", [738] = "efdcfuidR-R", [739] = "efdcfsidR-R", [740] = "efdabsRR", [741] = "efdnabsRR", [742] = "efdnegRR", [744] = "efdmulRRR", [745] = "efddivRRR", [746] = "efdctuidzR-R", [747] = "efdctsidzR-R", [748] = "efdcmpgtYRR", [749] = "efdcmpltYRR", [750] = "efdcmpeqYRR", [751] = "efdcfsR-R", [752] = "efdcfuiR-R", [753] = "efdcfsiR-R", [754] = "efdcfufR-R", [755] = "efdcfsfR-R", [756] = "efdctuiR-R", [757] = "efdctsiR-R", [758] = "efdctufR-R", [759] = "efdctsfR-R", [760] = "efdctuizR-R", [762] = "efdctsizR-R", [764] = "efdtstgtYRR", [765] = "efdtstltYRR", [766] = "efdtsteqYRR", [768] = "evlddxRR0R", [769] = "evlddRR8", [770] = "evldwxRR0R", [771] = "evldwRR8", [772] = "evldhxRR0R", [773] = "evldhRR8", [776] = "evlhhesplatxRR0R", [777] = "evlhhesplatRR2", [780] = "evlhhousplatxRR0R", [781] = "evlhhousplatRR2", [782] = "evlhhossplatxRR0R", [783] = "evlhhossplatRR2", [784] = "evlwhexRR0R", [785] = "evlwheRR4", [788] = "evlwhouxRR0R", [789] = "evlwhouRR4", [790] = "evlwhosxRR0R", [791] = "evlwhosRR4", [792] = "evlwwsplatxRR0R", [793] = "evlwwsplatRR4", [796] = "evlwhsplatxRR0R", [797] = "evlwhsplatRR4", [800] = "evstddxRR0R", [801] = "evstddRR8", [802] = "evstdwxRR0R", [803] = "evstdwRR8", [804] = "evstdhxRR0R", [805] = "evstdhRR8", [816] = "evstwhexRR0R", [817] = "evstwheRR4", [820] = "evstwhoxRR0R", [821] = "evstwhoRR4", [824] = "evstwwexRR0R", [825] = "evstwweRR4", [828] = "evstwwoxRR0R", [829] = "evstwwoRR4", [1027] = "evmhessfRRR", [1031] = "evmhossfRRR", [1032] = "evmheumiRRR", [1033] = "evmhesmiRRR", [1035] = "evmhesmfRRR", [1036] = "evmhoumiRRR", [1037] = "evmhosmiRRR", [1039] = "evmhosmfRRR", [1059] = "evmhessfaRRR", [1063] = "evmhossfaRRR", [1064] = "evmheumiaRRR", [1065] = "evmhesmiaRRR", [1067] = "evmhesmfaRRR", [1068] = "evmhoumiaRRR", [1069] = "evmhosmiaRRR", [1071] = "evmhosmfaRRR", [1095] = "evmwhssfRRR", [1096] = "evmwlumiRRR", [1100] = "evmwhumiRRR", [1101] = "evmwhsmiRRR", [1103] = "evmwhsmfRRR", [1107] = "evmwssfRRR", [1112] = "evmwumiRRR", [1113] = "evmwsmiRRR", [1115] = "evmwsmfRRR", [1127] = "evmwhssfaRRR", [1128] = "evmwlumiaRRR", [1132] = "evmwhumiaRRR", [1133] = "evmwhsmiaRRR", [1135] = "evmwhsmfaRRR", [1139] = "evmwssfaRRR", [1144] = "evmwumiaRRR", [1145] = "evmwsmiaRRR", [1147] = "evmwsmfaRRR", [1216] = "evaddusiaawRR", [1217] = "evaddssiaawRR", [1218] = "evsubfusiaawRR", [1219] = "evsubfssiaawRR", [1220] = "evmraRR", [1222] = "evdivwsRRR", [1223] = "evdivwuRRR", [1224] = "evaddumiaawRR", [1225] = "evaddsmiaawRR", [1226] = "evsubfumiaawRR", [1227] = "evsubfsmiaawRR", [1280] = "evmheusiaawRRR", [1281] = "evmhessiaawRRR", [1283] = "evmhessfaawRRR", [1284] = "evmhousiaawRRR", [1285] = "evmhossiaawRRR", [1287] = "evmhossfaawRRR", [1288] = "evmheumiaawRRR", [1289] = "evmhesmiaawRRR", [1291] = "evmhesmfaawRRR", [1292] = "evmhoumiaawRRR", [1293] = "evmhosmiaawRRR", [1295] = "evmhosmfaawRRR", [1320] = "evmhegumiaaRRR", [1321] = "evmhegsmiaaRRR", [1323] = "evmhegsmfaaRRR", [1324] = "evmhogumiaaRRR", [1325] = "evmhogsmiaaRRR", [1327] = "evmhogsmfaaRRR", [1344] = "evmwlusiaawRRR", [1345] = "evmwlssiaawRRR", [1352] = "evmwlumiaawRRR", [1353] = "evmwlsmiaawRRR", [1363] = "evmwssfaaRRR", [1368] = "evmwumiaaRRR", [1369] = "evmwsmiaaRRR", [1371] = "evmwsmfaaRRR", [1408] = "evmheusianwRRR", [1409] = "evmhessianwRRR", [1411] = "evmhessfanwRRR", [1412] = "evmhousianwRRR", [1413] = "evmhossianwRRR", [1415] = "evmhossfanwRRR", [1416] = "evmheumianwRRR", [1417] = "evmhesmianwRRR", [1419] = "evmhesmfanwRRR", [1420] = "evmhoumianwRRR", [1421] = "evmhosmianwRRR", [1423] = "evmhosmfanwRRR", [1448] = "evmhegumianRRR", [1449] = "evmhegsmianRRR", [1451] = "evmhegsmfanRRR", [1452] = "evmhogumianRRR", [1453] = "evmhogsmianRRR", [1455] = "evmhogsmfanRRR", [1472] = "evmwlusianwRRR", [1473] = "evmwlssianwRRR", [1480] = "evmwlumianwRRR", [1481] = "evmwlsmianwRRR", [1491] = "evmwssfanRRR", [1496] = "evmwumianRRR", [1497] = "evmwsmianRRR", [1499] = "evmwsmfanRRR", } local map_pri = { [0] = false, false, "tdiARI", "twiARI", map_spe, false, false, "mulliRRI", "subficRRI", false, "cmpl_iYLRU", "cmp_iYLRI", "addicRRI", "addic.RRI", "addi|liRR0I", "addis|lisRR0I", "b_KBJ", "sc", "bKJ", map_crops, "rlwimiRR~AAA.", map_rlwinm, false, "rlwnmRR~RAA.", "oriNRR~U", "orisRR~U", "xoriRR~U", "xorisRR~U", "andi.RR~U", "andis.RR~U", map_rld, map_ext, "lwzRRD", "lwzuRRD", "lbzRRD", "lbzuRRD", "stwRRD", "stwuRRD", "stbRRD", "stbuRRD", "lhzRRD", "lhzuRRD", "lhaRRD", "lhauRRD", "sthRRD", "sthuRRD", "lmwRRD", "stmwRRD", "lfsFRD", "lfsuFRD", "lfdFRD", "lfduFRD", "stfsFRD", "stfsuFRD", "stfdFRD", "stfduFRD", false, false, map_ld, map_fps, false, false, map_std, map_fpd, } ------------------------------------------------------------------------------ local map_gpr = { [0] = "r0", "sp", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31", } local map_cond = { [0] = "lt", "gt", "eq", "so", "ge", "le", "ne", "ns", } -- Format a condition bit. local function condfmt(cond) if cond <= 3 then return map_cond[band(cond, 3)] else return format("4*cr%d+%s", rshift(cond, 2), map_cond[band(cond, 3)]) end end ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local pos = ctx.pos local extra = "" if ctx.rel then local sym = ctx.symtab[ctx.rel] if sym then extra = "\t->"..sym end end if ctx.hexdump > 0 then ctx.out(format("%08x %s %-7s %s%s\n", ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra)) else ctx.out(format("%08x %-7s %s%s\n", ctx.addr+pos, text, concat(operands, ", "), extra)) end ctx.pos = pos + 4 end -- Fallback for unknown opcodes. local function unknown(ctx) return putop(ctx, ".long", { "0x"..tohex(ctx.op) }) end -- Disassemble a single instruction. local function disass_ins(ctx) local pos = ctx.pos local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4) local op = bor(lshift(b0, 24), lshift(b1, 16), lshift(b2, 8), b3) local operands = {} local last = nil local rs = 21 ctx.op = op ctx.rel = nil local opat = map_pri[rshift(b0, 2)] while type(opat) ~= "string" do if not opat then return unknown(ctx) end opat = opat[band(rshift(op, opat.shift), opat.mask)] end local name, pat = match(opat, "^([a-z0-9_.]*)(.*)") local altname, pat2 = match(pat, "|([a-z0-9_.]*)(.*)") if altname then pat = pat2 end for p in gmatch(pat, ".") do local x = nil if p == "R" then x = map_gpr[band(rshift(op, rs), 31)] rs = rs - 5 elseif p == "F" then x = "f"..band(rshift(op, rs), 31) rs = rs - 5 elseif p == "A" then x = band(rshift(op, rs), 31) rs = rs - 5 elseif p == "S" then x = arshift(lshift(op, 27-rs), 27) rs = rs - 5 elseif p == "I" then x = arshift(lshift(op, 16), 16) elseif p == "U" then x = band(op, 0xffff) elseif p == "D" or p == "E" then local disp = arshift(lshift(op, 16), 16) if p == "E" then disp = band(disp, -4) end if last == "r0" then last = "0" end operands[#operands] = format("%d(%s)", disp, last) elseif p >= "2" and p <= "8" then local disp = band(rshift(op, rs), 31) * p if last == "r0" then last = "0" end operands[#operands] = format("%d(%s)", disp, last) elseif p == "H" then x = band(rshift(op, rs), 31) + lshift(band(op, 2), 4) rs = rs - 5 elseif p == "M" then x = band(rshift(op, rs), 31) + band(op, 0x20) elseif p == "C" then x = condfmt(band(rshift(op, rs), 31)) rs = rs - 5 elseif p == "B" then local bo = rshift(op, 21) local cond = band(rshift(op, 16), 31) local cn = "" rs = rs - 10 if band(bo, 4) == 0 then cn = band(bo, 2) == 0 and "dnz" or "dz" if band(bo, 0x10) == 0 then cn = cn..(band(bo, 8) == 0 and "f" or "t") end if band(bo, 0x10) == 0 then x = condfmt(cond) end name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+") elseif band(bo, 0x10) == 0 then cn = map_cond[band(cond, 3) + (band(bo, 8) == 0 and 4 or 0)] if cond > 3 then x = "cr"..rshift(cond, 2) end name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+") end name = gsub(name, "_", cn) elseif p == "J" then x = arshift(lshift(op, 27-rs), 29-rs)*4 if band(op, 2) == 0 then x = ctx.addr + pos + x end ctx.rel = x x = "0x"..tohex(x) elseif p == "K" then if band(op, 1) ~= 0 then name = name.."l" end if band(op, 2) ~= 0 then name = name.."a" end elseif p == "X" or p == "Y" then x = band(rshift(op, rs+2), 7) if x == 0 and p == "Y" then x = nil else x = "cr"..x end rs = rs - 5 elseif p == "W" then x = "cr"..band(op, 7) elseif p == "Z" then x = band(rshift(op, rs-4), 255) rs = rs - 10 elseif p == ">" then operands[#operands] = rshift(operands[#operands], 1) elseif p == "0" then if last == "r0" then operands[#operands] = nil if altname then name = altname end end elseif p == "L" then name = gsub(name, "_", band(op, 0x00200000) ~= 0 and "d" or "w") elseif p == "." then if band(op, 1) == 1 then name = name.."." end elseif p == "N" then if op == 0x60000000 then name = "nop"; break end elseif p == "~" then local n = #operands operands[n-1], operands[n] = operands[n], operands[n-1] elseif p == "=" then local n = #operands if last == operands[n-1] then operands[n] = nil name = altname end elseif p == "%" then local n = #operands if last == operands[n-1] and last == operands[n-2] then operands[n] = nil operands[n-1] = nil name = altname end elseif p == "-" then rs = rs - 5 else assert(false) end if x then operands[#operands+1] = x; last = x end end return putop(ctx, name, operands) end ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code stop = stop - stop % 4 ctx.pos = ofs - ofs % 4 ctx.rel = nil while ctx.pos < stop do disass_ins(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create(code, addr, out) local ctx = {} ctx.code = code ctx.addr = addr or 0 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 8 return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass(code, addr, out) create(code, addr, out):disass() end -- Return register name for RID. local function regname(r) if r < 32 then return map_gpr[r] end return "f"..(r-32) end -- Public module functions. return { create = create, disass = disass, regname = regname }
bsd-2-clause
Aminkavari/-xXD4RKXx-
plugins/rss.lua
700
5434
local function get_base_redis(id, option, extra) local ex = '' if option ~= nil then ex = ex .. ':' .. option if extra ~= nil then ex = ex .. ':' .. extra end end return 'rss:' .. id .. ex end local function prot_url(url) local url, h = string.gsub(url, "http://", "") local url, hs = string.gsub(url, "https://", "") local protocol = "http" if hs == 1 then protocol = "https" end return url, protocol end local function get_rss(url, prot) local res, code = nil, 0 if prot == "http" then res, code = http.request(url) elseif prot == "https" then res, code = https.request(url) end if code ~= 200 then return nil, "Error while doing the petition to " .. url end local parsed = feedparser.parse(res) if parsed == nil then return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?" end return parsed, nil end local function get_new_entries(last, nentries) local entries = {} for k,v in pairs(nentries) do if v.id == last then return entries else table.insert(entries, v) end end return entries end local function print_subs(id) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) local text = id .. ' are subscribed to:\n---------\n' for k,v in pairs(subs) do text = text .. k .. ") " .. v .. '\n' end return text end local function subscribe(id, url) local baseurl, protocol = prot_url(url) local prothash = get_base_redis(baseurl, "protocol") local lasthash = get_base_redis(baseurl, "last_entry") local lhash = get_base_redis(baseurl, "subs") local uhash = get_base_redis(id) if redis:sismember(uhash, baseurl) then return "You are already subscribed to " .. url end local parsed, err = get_rss(url, protocol) if err ~= nil then return err end local last_entry = "" if #parsed.entries > 0 then last_entry = parsed.entries[1].id end local name = parsed.feed.title redis:set(prothash, protocol) redis:set(lasthash, last_entry) redis:sadd(lhash, id) redis:sadd(uhash, baseurl) return "You had been subscribed to " .. name end local function unsubscribe(id, n) if #n > 3 then return "I don't think that you have that many subscriptions." end n = tonumber(n) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) if n < 1 or n > #subs then return "Subscription id out of range!" end local sub = subs[n] local lhash = get_base_redis(sub, "subs") redis:srem(uhash, sub) redis:srem(lhash, id) local left = redis:smembers(lhash) if #left < 1 then -- no one subscribed, remove it local prothash = get_base_redis(sub, "protocol") local lasthash = get_base_redis(sub, "last_entry") redis:del(prothash) redis:del(lasthash) end return "You had been unsubscribed from " .. sub end local function cron() -- sync every 15 mins? local keys = redis:keys(get_base_redis("*", "subs")) for k,v in pairs(keys) do local base = string.match(v, "rss:(.+):subs") -- Get the URL base local prot = redis:get(get_base_redis(base, "protocol")) local last = redis:get(get_base_redis(base, "last_entry")) local url = prot .. "://" .. base local parsed, err = get_rss(url, prot) if err ~= nil then return end local newentr = get_new_entries(last, parsed.entries) local subscribers = {} local text = '' -- Send only one message with all updates for k2, v2 in pairs(newentr) do local title = v2.title or 'No title' local link = v2.link or v2.id or 'No Link' text = text .. "[rss](" .. link .. ") - " .. title .. '\n' end if text ~= '' then local newlast = newentr[1].id redis:set(get_base_redis(base, "last_entry"), newlast) for k2, receiver in pairs(redis:smembers(v)) do send_msg(receiver, text, ok_cb, false) end end end end local function run(msg, matches) local id = "user#id" .. msg.from.id if is_chat_msg(msg) then id = "chat#id" .. msg.to.id end if matches[1] == "!rss"then return print_subs(id) end if matches[1] == "sync" then if not is_sudo(msg) then return "Only sudo users can sync the RSS." end cron() end if matches[1] == "subscribe" or matches[1] == "sub" then return subscribe(id, matches[2]) end if matches[1] == "unsubscribe" or matches[1] == "uns" then return unsubscribe(id, matches[2]) end end return { description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.", usage = { "!rss: Get your rss (or chat rss) subscriptions", "!rss subscribe (url): Subscribe to that url", "!rss unsubscribe (id): Unsubscribe of that id", "!rss sync: Download now the updates and send it. Only sudo users can use this option." }, patterns = { "^!rss$", "^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (unsubscribe) (%d+)$", "^!rss (uns) (%d+)$", "^!rss (sync)$" }, run = run, cron = cron }
gpl-2.0
miraage/gladdy
Options.lua
1
6613
local tonumber = tonumber local type = type local pairs = pairs local tinsert = table.insert local tsort = table.sort local InterfaceOptionsFrame_OpenToFrame = InterfaceOptionsFrame_OpenToFrame local Gladdy = LibStub("Gladdy") local L = Gladdy.L Gladdy.defaults = { profile = { locked = false, x = 0, y = 0, growUp = false, frameScale = 1, padding = 5, frameColor = {r = 0, g = 0, b = 0, a = .4}, barWidth = 180, bottomMargin = 10, }, } SLASH_GLADDY1 = "/gladdy" SlashCmdList["GLADDY"] = function(msg) if (msg == "test2") then Gladdy:ToggleFrame(2) elseif (msg == "test5") then Gladdy:ToggleFrame(5) elseif (msg:find("test")) then Gladdy:ToggleFrame(3) elseif (msg == "ui" or msg == "options" or msg == "config") then Gladdy:ShowOptions() elseif (msg:find("trinket")) then local unitId = tonumber(msg:match("^trinket(.+)")) Gladdy:Call("Trinket", "Used", "arena" .. unitId) elseif (msg == "reset") then Gladdy.dbi:ResetProfile() elseif (msg == "hide") then Gladdy:Reset() Gladdy:HideFrame() else Gladdy:Print(L["Valid slash commands are:"]) Gladdy:Print("/gladdy ui") Gladdy:Print("/gladdy test2-5") Gladdy:Print("/gladdy hide") Gladdy:Print("/gladdy reset") end end local function getOpt(info) local key = info.arg or info[#info] return Gladdy.dbi.profile[key] end local function setOpt(info, value) local key = info.arg or info[#info] Gladdy.dbi.profile[key] = value Gladdy:UpdateFrame() end local function getColorOpt(info) local key = info.arg or info[#info] return Gladdy.dbi.profile[key].r, Gladdy.dbi.profile[key].g, Gladdy.dbi.profile[key].b, Gladdy.dbi.profile[key].a end local function setColorOpt(info, r, g, b ,a) local key = info.arg or info[#info] Gladdy.dbi.profile[key].r, Gladdy.dbi.profile[key].g, Gladdy.dbi.profile[key].b, Gladdy.dbi.profile[key].a = r, g, b ,a Gladdy:UpdateFrame() end function Gladdy:SetupModule(name, module, order) self.options.args[name] = { type = "group", name = L[name], desc = L[name .. " settings"], order = order, args = {}, } local options = module:GetOptions() if (type(options) == "table") then self.options.args[name].args = options self.options.args[name].args.reset = { type = "execute", name = L["Reset module"], desc = L["Reset module to defaults"], order = 1, func = function() for k, v in pairs(module.defaults) do self.dbi.profile[k] = v end Gladdy:UpdateFrame() Gladdy:SetupModule(name, module, order) -- For example click names are not reset by default end } else self.options.args[name].args.nothing = { type = "description", name = L["No settings"], desc = L["Module has no settings"], order = 1, } end end local function pairsByKeys(t) local a = {} for k in pairs(t) do tinsert(a, k) end tsort(a) local i = 0 return function() i = i + 1 if (a[i] ~= nil) then return a[i], t[a[i]] else return nil end end end function Gladdy:SetupOptions() self.options = { type = "group", name = "Gladdy", plugins = {}, get = getOpt, set = setOpt, args = { general = { type = "group", name = L["General"], desc = L["General settings"], order = 1, args = { locked = { type = "toggle", name = L["Lock frame"], desc = L["Toggle if frame can be moved"], order = 1, }, growUp = { type = "toggle", name = L["Grow frame upwards"], desc = L["If enabled the frame will grow upwards instead of downwards"], order = 2, }, frameScale = { type = "range", name = L["Frame scale"], desc = L["Scale of the frame"], order = 3, min = .1, max = 2, step = .1, }, padding = { type = "range", name = L["Frame padding"], desc = L["Padding of the frame"], order = 4, min = 0, max = 20, step = 1, }, frameColor = { type = "color", name = L["Frame color"], desc = L["Color of the frame"], order = 5, hasAlpha = true, get = getColorOpt, set = setColorOpt, }, barWidth = { type = "range", name = L["Bar width"], desc = L["Width of the bars"], order = 6, min = 10, max = 500, step = 5, }, bottomMargin = { type = "range", name = L["Bottom margin"], desc = L["Margin between each button"], order = 7, min = 0, max = 50, step = 1, }, }, }, }, } local order = 2 for k, v in pairsByKeys(self.modules) do self:SetupModule(k, v, order) order = order + 1 end self.options.plugins.profiles = {profiles = LibStub("AceDBOptions-3.0"):GetOptionsTable(self.dbi) } LibStub("AceConfig-3.0"):RegisterOptionsTable("Gladdy", self.options) LibStub("AceConfigDialog-3.0"):AddToBlizOptions("Gladdy", "Gladdy") end function Gladdy:ShowOptions() InterfaceOptionsFrame_OpenToFrame("Gladdy") end
mit
daniel-slaney/demirogue
src/mode/ForceDrawMode.lua
3
6595
-- -- mode/ForceDrawMode.lua -- -- Test bed and debugging tool for the force drawing algorithm. -- require 'Graph' local AABB = require 'lib/AABB' require 'Vector' require 'geometry' require 'graph2D' local graphDraw = require 'lib/graphDraw' local schema, ForceDrawMode = require 'lib/mode' { 'ForceDrawMode' } local config = { tolerance = 20, } local function _shadowf(font, x, y, ... ) love.graphics.setFont(font) love.graphics.setColor(0, 0, 0, 255) local text = string.format(...) love.graphics.print(text, x-1, y-1) love.graphics.print(text, x-1, y+1) love.graphics.print(text, x+1, y-1) love.graphics.print(text, x+1, y+1) love.graphics.setColor(192, 192, 192, 255) love.graphics.print(text, x, y) end local graph = Graph.new() local undo = {} local log = nil local logmode = nil local logmodes = { repulse = { 255, 0, 0, 255 }, attract = { 0, 255, 0, 255 }, edge = { 0, 0, 255, 255 }, accum = { 255, 255, 255, 255 }, proj = { 255, 255, 0, 255 }, clip = { 255, 0, 255, 255 }, arc = { 0, 128, 0, 128 }, plane = { 255, 255, 255, 255 }, } local selected = nil local connect = false local time = 0 function ForceDrawMode:update( dt ) time = time + dt local mx, my = love.mouse.getX(), love.mouse.getY() local coord = Vector.new { x = mx, y = my } local distance = math.huge local selection = nil for vertex, _ in pairs(graph.vertices) do local d = coord:toLength(vertex) if d < distance then distance = d selection = { type = 'vertex', vertex = vertex } end end if distance > config.tolerance then selection = nil end -- What about an edge? if not selection then distance = math.huge for edge, endverts in pairs(graph.edges) do local d = geometry.closestPointOnLine(endverts[1], endverts[2], coord):toLength(coord) if d < distance then distance = d selection = { type = 'edge', edge = edge } end end if distance > config.tolerance then selection = nil end end if connect then assert(selected) assert(selected.type == 'vertex') local current = selected.vertex if selection and selection.type == 'vertex' then if current ~= selection.vertex then if not graph:isPeer(current, selection.vertex) then graph:addEdge({}, current, selection.vertex) end end end else if selection and distance < config.tolerance then selected = selection else selected = nil end end end local function _render( graph, colour ) -- Mid-grey. love.graphics.setColor(colour[1], colour[2], colour[3], colour[4]) love.graphics.setLineWidth(3) love.graphics.setLineStyle('rough') for edge, endverts in pairs(graph.edges) do local v1, v2 = endverts[1], endverts[2] love.graphics.line(v1.x, v1.y, v2.x, v2.y) end local radius = 5 for vertex, _ in pairs(graph.vertices) do love.graphics.circle('fill', vertex.x, vertex.y, radius) end end function ForceDrawMode:draw() -- Highlight any selection. if selected then -- yellow love.graphics.setColor(255, 255, 0, 255) if selected.type == 'vertex' then local radius = 10 local vertex = selected.vertex love.graphics.setLineWidth(3) love.graphics.setLineStyle('rough') if connect then -- Magenta! love.graphics.setColor(255, 0, 255, 255) local mx, my = love.mouse.getX(), love.mouse.getY() love.graphics.line(vertex.x, vertex.y, mx, my) end love.graphics.circle('line', vertex.x, vertex.y, radius) end if selected.type == 'edge' then local endverts = graph.edges[selected.edge] love.graphics.setLineWidth(10) love.graphics.setLineStyle('rough') love.graphics.line(endverts[1].x, endverts[1].y, endverts[2].x, endverts[2].y) end end if #undo > 0 then local colour = { 128, 128, 128, 255 } _render(undo[#undo].graph, colour) end local colour = { 64, 64, 64, 255 } _render(graph, colour) if log then love.graphics.setLineWidth(1) love.graphics.setLineStyle('rough') for _, line in ipairs(log) do if logmode ~= nil and line[1] == logmode then love.graphics.setColor(unpack(logmodes[line[1]])) if line[1] ~= 'arc' then local x1, y1, x2, y2 = line[2], line[3], line[4], line[5] love.graphics.line(x1, y1, x2, y2) -- draw arrow head local dir = Vector.new { x=x1-x2, y=y1-y2 } dir:normalise() dir:scale(5) local arr1 = dir:perp() local arr2 = dir:antiPerp() love.graphics.line(x2, y2, x2+dir.x+arr1.x, y2+dir.y+arr1.y) love.graphics.line(x2, y2, x2+dir.x+arr2.x, y2+dir.y+arr2.y) love.graphics.line(x1, y1, x1+arr1.x, y1+arr1.y) love.graphics.line(x1, y1, x1+arr2.x, y1+arr2.y) else local x, y = line[2], line[3] local dir = line[4] local radius = line[5] local segments = 10 local angle = math.atan2(dir.y, dir.x) local cw = angle + (math.pi / 8) local ccw = angle - (math.pi / 8) if radius ~= math.huge then love.graphics.arc('fill', x, y, radius, cw, ccw, segments) love.graphics.setColor(0, 255, 0, 255) love.graphics.arc('line', x, y, radius, cw, ccw, segments) end end end end end _shadowf(gFont15, 0, 0, 'logmode: %s M.E.L.:%.2f', logmode, graph2D.meanEdgeLength(graph)) end function ForceDrawMode:mousepressed( x, y, button ) if button ~= 'l' then return end -- This stops vertices being placed too close to other vertices. if selected and selected.type == 'vertex' then return end local coord = Vector.new { x = x, y = y } local vertex = { x = x, y = y } graph:addVertex(vertex) end function ForceDrawMode:keypressed( key ) key = key:lower() if key == 'delete' or key == 'backspace' then if selected then if selected.type == 'vertex' then graph:removeVertex(selected.vertex) else graph:removeEdge(selected.edge) end end selected = nil elseif key == 'lshift' or key == 'rshift' then if selected and selected.type == 'vertex' then connect = true end elseif key == ' ' then local stash = { graph = graph:clone(table.copy, table.copy), log = log } undo[#undo+1] = stash local delta = 100 local gamma = 50 local epsilon = 0.1 local logging = true -- log = graphDraw.pred(graph, delta, gamma, epsilon, logging) log = graphDraw.demipred(graph, delta, gamma, epsilon, logging) elseif key == 'l' then logmode = next(logmodes, logmode) elseif key == 'u' then if #undo > 0 then graph = undo[#undo].graph log = undo[#undo].log undo[#undo] = nil end end end function ForceDrawMode:keyreleased( key ) if key == 'lshift' or key == 'rshift' then connect = false end end
bsd-3-clause
philsiff/Red-Vs-Blue
Red Vs. Blue Files/lua/includes/modules/cleanup.lua
1
4444
module( "cleanup", package.seeall ) local cleanup_types = {} local function IsType( type ) for key, val in pairs( cleanup_types ) do if ( val == type ) then return true end end return false end function Register( type ) if ( type == "all" ) then return end for key, val in pairs( cleanup_types ) do if val == type then return end end table.insert( cleanup_types, type ) end function GetTable( ) return cleanup_types end if ( SERVER ) then local cleanup_list = {} function GetList( ) return cleanup_list end local function Save( save ) saverestore.WriteTable( cleanup_list, save ) end local function Restore( restore ) cleanup_list = saverestore.ReadTable( restore ) end saverestore.AddSaveHook( "CleanupTable", Save ) saverestore.AddRestoreHook( "CleanupTable", Restore ) function Add( pl, type, ent ) if ( !ent ) then return end if ( !IsType( type ) ) then return end local id = pl:UniqueID() cleanup_list[ id ] = cleanup_list[ id ] or {} cleanup_list[ id ][ type ] = cleanup_list[ id ][ type ] or {} if ( !ent:IsValid() ) then return end table.insert( cleanup_list[ id ][ type ], ent ) end function ReplaceEntity( from, to ) local ActionTaken = false for _, PlayerTable in pairs(cleanup_list) do for _, TypeTable in pairs(PlayerTable) do for key, ent in pairs(TypeTable) do if ( ent == from ) then TypeTable[ key ] = to ActionTaken = true end end end end return ActionTaken end function CC_Cleanup( pl, command, args ) local id = pl:UniqueID() if ( !cleanup_list[id] ) then return end if ( !args[1] ) then local count = 0 for key, val in pairs( cleanup_list[id] ) do for key, ent in pairs( val ) do if ( ent:IsValid() ) then ent:Remove() end count = count + 1 end table.Empty( val ) end -- Send tooltip command to client if ( count > 0 ) then pl:SendLua( "GAMEMODE:OnCleanup( 'all' )" ) end return end if ( !IsType( args[1] ) ) then return end if ( !cleanup_list[id][args[1]] ) then return end for key, ent in pairs( cleanup_list[id][args[1]] ) do if ( ent:IsValid() ) then ent:Remove() end end table.Empty( cleanup_list[id][args[1]] ) -- Send tooltip command to client pl:SendLua( "GAMEMODE:OnCleanup( '"..args[1].."' )" ) end function CC_AdminCleanup( pl, command, args ) if ( pl && pl:IsValid() && !pl:IsAdmin() ) then return end if ( !args[1] ) then for key, player in pairs( cleanup_list ) do for key, type in pairs( player ) do for key, ent in pairs( type ) do if ( ent:IsValid() ) then ent:Remove() end end table.Empty( type ) end end game.CleanUpMap() -- Send tooltip command to client pl:SendLua( "GAMEMODE:OnCleanup( 'all' )" ) return end if ( !IsType( args[1] ) ) then return end for key, player in pairs( cleanup_list ) do if ( player[args[1]] != nil ) then for key, ent in pairs( player[args[1]] ) do if ( ent:IsValid() ) then ent:Remove() end end table.Empty( player[args[1]] ) end end -- Send tooltip command to client pl:SendLua( "GAMEMODE:OnCleanup( '"..args[1].."' )" ) end concommand.Add( "gmod_cleanup", CC_Cleanup, nil, "", { FCVAR_DONTRECORD } ) concommand.Add( "gmod_admin_cleanup", CC_AdminCleanup, nil, "", { FCVAR_DONTRECORD } ) else function UpdateUI() local Panel = controlpanel.Get( "User_Cleanup" ) if (!Panel) then return end Panel:ClearControls() Panel:AddControl( "Header", { Text = "#CleanUp" } ) Panel:Button( "#CleanupAll", "gmod_cleanup" ) table.sort( cleanup_types ) for key, val in pairs( cleanup_types ) do Panel:Button( "#Cleanup_"..val, "gmod_cleanup", val ) end local Panel = controlpanel.Get( "Admin_Cleanup" ) if (!Panel) then return end Panel:ClearControls() Panel:AddControl( "Header", { Text = "#CleanUp" } ) Panel:Button( "#CleanupAll", "gmod_admin_cleanup" ) table.sort( cleanup_types ) for key, val in pairs( cleanup_types ) do Panel:Button( "#Cleanup_"..val, "gmod_admin_cleanup", val ) end end hook.Add( "PostReloadToolsMenu", "BuildCleanupUI", UpdateUI ) end
mit
eggBOY91/Arctic-Core
src/scripts/lua/Lua/Stable Scripts/Azeroth/Karazhan/BOSS_Karazhan_Shadikith.lua
30
1115
function Shadikith_Charge(Unit, event, miscunit, misc) print "Shadikith Charge" Unit:FullCastSpellOnTarget(38461,Unit:GetRandomPlayer()) Unit:SendChatMessage(11, 0, "Charge...") end function Shadikith_Sonic_Burst(Unit, event, miscunit, misc) print "Shadikith Sonic Burst" Unit:FullCastSpellOnTarget(39052,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "Ho, A nice burst...") end function Shadikith_Wing_Buffet(Unit, event, miscunit, misc) print "Romulo Daring" Unit:FullCastSpellOnTarget(38110,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "Let's Rock...") end function Shadikith_Knockback(Unit, event, miscunit, misc) print "Romulo Poisoned Thrust" Unit:FullCastSpellOnTarget(37966,Unit:GetRandomPlayer()) Unit:SendChatMessage(11, 0, "Now, let's do more damage...") end function Shadikith(unit, event, miscunit, misc) print "Shadikith" unit:RegisterEvent("Shadikith_Charge",10000,0) unit:RegisterEvent("Shadikith_Sonic_Burst",17000,0) unit:RegisterEvent("Shadikith_Wing_Buffet",27000,0) unit:RegisterEvent("Shadikith_Knockback",33000,0) end RegisterUnitEvent(16180,1,"Shadikith")
agpl-3.0
parsaalemi/xybot
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
amirmrbad/flashbot
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
joaofvieira/luci
modules/luci-mod-admin-mini/luasrc/model/cbi/mini/wifi.lua
48
11450
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. -- Data init -- local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() if not uci:get("network", "wan") then uci:section("network", "interface", "wan", {proto="none", ifname=" "}) uci:save("network") uci:commit("network") end local wlcursor = luci.model.uci.cursor_state() local wireless = wlcursor:get_all("wireless") local wifidevs = {} local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" then table.insert(ifaces, v) end end wlcursor:foreach("wireless", "wifi-device", function(section) table.insert(wifidevs, section[".name"]) end) -- Main Map -- m = Map("wireless", translate("Wifi"), translate("Here you can configure installed wifi devices.")) m:chain("network") -- Status Table -- s = m:section(Table, ifaces, translate("Networks")) link = s:option(DummyValue, "_link", translate("Link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d/%d" %{ iwinfo.quality, iwinfo.quality_max } or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and iwinfo.bssid or "-" end channel = s:option(DummyValue, "channel", translate("Channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("Protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("Mode")) encryption = s:option(DummyValue, "encryption", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) power = s:option(DummyValue, "_power", translate("Power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d dBm" % iwinfo.txpower or "-" end scan = s:option(Button, "_scan", translate("Scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end -- WLAN-Scan-Table -- t2 = m:section(Table, {}, translate("<abbr title=\"Wireless Local Area Network\">WLAN</abbr>-Scan"), translate("Wifi networks in your local environment")) function scan.write(self, section) m.autoapply = false t2.render = t2._render local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) if iwinfo then local _, cell for _, cell in ipairs(iwinfo.scanlist) do t2.data[#t2.data+1] = { Quality = "%d/%d" %{ cell.quality, cell.quality_max }, ESSID = cell.ssid, Address = cell.bssid, Mode = cell.mode, ["Encryption key"] = cell.encryption.enabled and "On" or "Off", ["Signal level"] = "%d dBm" % cell.signal, ["Noise level"] = "%d dBm" % iwinfo.noise } end end end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("Link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return self.map:get(section, "ESSID") end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("Mode")) chan = t2:option(DummyValue, "channel", translate("Channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) t2:option(DummyValue, "Signal level", translate("Signal")) t2:option(DummyValue, "Noise level", translate("Noise")) if #wifidevs < 1 then return m end -- Config Section -- s = m:section(NamedSection, wifidevs[1], "wifi-device", translate("Devices")) s.addremove = false en = s:option(Flag, "disabled", translate("enable")) en.rmempty = false en.enabled = "0" en.disabled = "1" function en.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end local hwtype = m:get(wifidevs[1], "type") if hwtype == "atheros" then mode = s:option(ListValue, "hwmode", translate("Mode")) mode.override_values = true mode:value("", "auto") mode:value("11b", "802.11b") mode:value("11g", "802.11g") mode:value("11a", "802.11a") mode:value("11bg", "802.11b+g") mode.rmempty = true end ch = s:option(Value, "channel", translate("Channel")) for i=1, 14 do ch:value(i, i .. " (2.4 GHz)") end s = m:section(TypedSection, "wifi-iface", translate("Local Network")) s.anonymous = true s.addremove = false s:option(Value, "ssid", translate("Network Name (<abbr title=\"Extended Service Set Identifier\">ESSID</abbr>)")) bssid = s:option(Value, "bssid", translate("<abbr title=\"Basic Service Set Identifier\">BSSID</abbr>")) local devs = {} luci.model.uci.cursor():foreach("wireless", "wifi-device", function (section) table.insert(devs, section[".name"]) end) if #devs > 1 then device = s:option(DummyValue, "device", translate("Device")) else s.defaults.device = devs[1] end mode = s:option(ListValue, "mode", translate("Mode")) mode.override_values = true mode:value("ap", translate("Provide (Access Point)")) mode:value("adhoc", translate("Independent (Ad-Hoc)")) mode:value("sta", translate("Join (Client)")) function mode.write(self, section, value) if value == "sta" then local oldif = m.uci:get("network", "wan", "ifname") if oldif and oldif ~= " " then m.uci:set("network", "wan", "_ifname", oldif) end m.uci:set("network", "wan", "ifname", " ") self.map:set(section, "network", "wan") else if m.uci:get("network", "wan", "_ifname") then m.uci:set("network", "wan", "ifname", m.uci:get("network", "wan", "_ifname")) end self.map:set(section, "network", "lan") end return ListValue.write(self, section, value) end encr = s:option(ListValue, "encryption", translate("Encryption")) encr.override_values = true encr:value("none", "No Encryption") encr:value("wep", "WEP") if hwtype == "atheros" or hwtype == "mac80211" then local supplicant = fs.access("/usr/sbin/wpa_supplicant") local hostapd = fs.access("/usr/sbin/hostapd") if hostapd and supplicant then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode") encr:value("wpa", "WPA-Radius", {mode="ap"}, {mode="sta"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}, {mode="sta"}) elseif hostapd and not supplicant then encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="adhoc"}) encr:value("wpa", "WPA-Radius", {mode="ap"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) elseif not hostapd and supplicant then encr:value("psk", "WPA-PSK", {mode="sta"}) encr:value("psk2", "WPA2-PSK", {mode="sta"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="sta"}) encr:value("wpa", "WPA-EAP", {mode="sta"}) encr:value("wpa2", "WPA2-EAP", {mode="sta"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) else encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) end elseif hwtype == "broadcom" then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk+psk2", "WPA-PSK/WPA2-PSK Mixed Mode") end key = s:option(Value, "key", translate("Key")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "psk2") key:depends("encryption", "psk+psk2") key:depends("encryption", "psk-mixed") key:depends({mode="ap", encryption="wpa"}) key:depends({mode="ap", encryption="wpa2"}) key.rmempty = true key.password = true server = s:option(Value, "server", translate("Radius-Server")) server:depends({mode="ap", encryption="wpa"}) server:depends({mode="ap", encryption="wpa2"}) server.rmempty = true port = s:option(Value, "port", translate("Radius-Port")) port:depends({mode="ap", encryption="wpa"}) port:depends({mode="ap", encryption="wpa2"}) port.rmempty = true if hwtype == "atheros" or hwtype == "mac80211" then nasid = s:option(Value, "nasid", translate("NAS ID")) nasid:depends({mode="ap", encryption="wpa"}) nasid:depends({mode="ap", encryption="wpa2"}) nasid.rmempty = true eaptype = s:option(ListValue, "eap_type", translate("EAP-Method")) eaptype:value("TLS") eaptype:value("TTLS") eaptype:value("PEAP") eaptype:depends({mode="sta", encryption="wpa"}) eaptype:depends({mode="sta", encryption="wpa2"}) cacert = s:option(FileUpload, "ca_cert", translate("Path to CA-Certificate")) cacert:depends({mode="sta", encryption="wpa"}) cacert:depends({mode="sta", encryption="wpa2"}) privkey = s:option(FileUpload, "priv_key", translate("Path to Private Key")) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa"}) privkeypwd = s:option(Value, "priv_key_pwd", translate("Password of Private Key")) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa"}) auth = s:option(Value, "auth", translate("Authentication")) auth:value("PAP") auth:value("CHAP") auth:value("MSCHAP") auth:value("MSCHAPV2") auth:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) auth:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) identity = s:option(Value, "identity", translate("Identity")) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) password = s:option(Value, "password", translate("Password")) password:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) password:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) end if hwtype == "atheros" or hwtype == "broadcom" then iso = s:option(Flag, "isolate", translate("AP-Isolation"), translate("Prevents Client to Client communication")) iso.rmempty = true iso:depends("mode", "ap") hide = s:option(Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) hide.rmempty = true hide:depends("mode", "ap") end if hwtype == "mac80211" or hwtype == "atheros" then bssid:depends({mode="adhoc"}) end if hwtype == "broadcom" then bssid:depends({mode="wds"}) bssid:depends({mode="adhoc"}) end return m
apache-2.0
johnymarek/tsdemuxer
xupnpd/src/plugins/xupnpd_dreambox.lua
6
6744
-- Plugin for converting channels lists from DVB receivers based on Enigma2 -- Copyright (C) 2012 Igor Drach -- leaigor@gmail.com function dreambox_url_encode(str) if (str) then str = string.gsub (str, " ", "%%20") str = string.gsub (str, "\"", "%%22") end return str end function xml_to_tables(file,label,started) -- print("label=",label) local xmltable={} repeat local string=file:read() if string then -- print("string="..string) local n,m,i,field,j=string.find(string,"<(%w+)>(.*)<%/(%w+)>") -- print(i,field,j) if i==j and field and started then -- print("add to table",i,field) -- table.insert(xmltable,{i,field}) xmltable[i]=field -- table.insert(xmltable,{"value",{i,field}}) else local i,j,field=string.find(string,"<(%w+)>") -- print(field) if field then if started or not label then -- print("start "..field) -- local insertedtable=xml_to_tables(file,field,true) -- print("insertedtable=",insertedtable) local insertedvalue={} insertedvalue[field]=xml_to_tables(file,field,true) table.insert(xmltable,insertedvalue) elseif label==field then label=field started=true end else local i,j,field=string.find(string,"<%/(%w+)>") if field==label and field then -- print("close "..field) -- print("table=",xmltable) -- dreambox_table_print(xmltable) return xmltable end end end end until not string -- return xmltable end function dreambox_table_print (tt, indent, done) done = done or {} indent = indent or 0 if type(tt) == "table" then for key, value in pairs (tt) do io.write(string.rep (" ", indent)) -- indent it if type (value) == "table" and not done [value] then done [value] = true io.write(string.format("[%s] => table\n", tostring (key))); io.write(string.rep (" ", indent+4)) -- indent it io.write("(\n"); dreambox_table_print (value, indent + 7, done) io.write(string.rep (" ", indent+4)) -- indent it io.write(")\n"); else io.write(string.format("[%s] => %s\n", tostring (key), tostring(value))) end end else io.write(tt .. "\n") end end function dreambox_updatefeed(feed,friendly_name) local rc=false local feedspath=cfg.feeds_path if not friendly_name then friendly_name=feed end local wget="wget -q -O- " local dreambox_url='http://'..feed..'/web/' --local dreambox_m3u_url='http://'..feed..'/web/stream.m3u?ref=' local bouquets={} print(wget..dreambox_url.."getservices") local xmlbouquetsfile=io.popen(wget..dreambox_url.."getservices") bouquets=xml_to_tables(xmlbouquetsfile,"e2servicelist") xmlbouquetsfile:close() if bouquets then local bindex local bouquett={} local bouquet={} for bindex,bouquett in pairs(bouquets) do bouquet=bouquett["e2service"] if bouquet then local bouquetname=bouquet["e2servicename"] local bouquetreference=bouquet["e2servicereference"] local cindex local channelt={} local channel={} local line print(wget..dreambox_url_encode(dreambox_url.."services.m3u?bRef="..bouquetreference)) local bouquetfile=io.popen(wget..dreambox_url_encode(dreambox_url.."services.m3u?bRef="..bouquetreference)) if bouquetfile then local m3ufilename=cfg.tmp_path.."dreambox_"..friendly_name.."_bouquet"..bindex..".m3u" print(m3ufilename) local m3ufile=io.open(m3ufilename,"w") for line in bouquetfile:lines() do if string.match(line,'#EXTM3U') then m3ufile:write("#EXTM3U name=\""..bouquetname.."\"\n") else m3ufile:write(line.."\n") end end m3ufile:close() os.execute(string.format('mv %s %s',m3ufilename,feedspath)) rc=true end bouquetfile:close() end end local m3ufilename=cfg.tmp_path.."dreambox_"..friendly_name.."_controls"..".m3u" local m3ufile=io.open(m3ufilename,"w") m3ufile:write("#EXTM3U name=\"Управление\" plugin=dreambox type=ts\n") m3ufile:write("#EXTINF:0,1-Текущий канал\n") m3ufile:write(dreambox_url.."command=current\n") m3ufile:write("#EXTINF:0,2-Проснуться + Текущий канал\n") m3ufile:write(dreambox_url.."command=on\n") m3ufile:write("#EXTINF:0,3-Заснуть\n") m3ufile:write(dreambox_url.."command=off\n") m3ufile:close() os.execute(string.format('mv %s %s',m3ufilename,feedspath)) end return rc end function dreambox_sendurl(dreambox_url,range) print("range=",range) local url local file local wget="wget -q -O- " local wgetn="wget -q -O /dev/null " local i,j,urlbase=string.find(dreambox_url,"(.+/web/).+") if urlbase then print("BaseURL=",urlbase) end local i,j,command=string.find(dreambox_url,".+command=(%w+)") local standby={} local currentservice={} local service={} local servicereference if command then file=io.popen(wget..urlbase..'powerstate') standby=xml_to_tables(file,"e2powerstate") file:close() print("standby=",standby["e2instandby"]," command=",command) -- dreambox_table_print(standby) if command=="on" and standby["e2instandby"]=='true' then print(wget..urlbase..'remotecontrol?command=116') file=io.popen(wget..urlbase..'remotecontrol?command=116') file:read() file:close() end if standby["e2instandby"]=='false' and command=='off' then print(wget..urlbase..'powerstate?newstate=0') file=io.popen(wget..urlbase..'powerstate?newstate=0') file:read() file:close() end file=io.popen(wget..urlbase.."subservices") currentservice=xml_to_tables(file,"e2service") file:close() if currentservice then servicereference=currentservice["e2servicereference"] if servicereference~="N/A" then url=wget..urlbase.."stream.m3u?ref="..servicereference end end else url=wget..dreambox_url end local newurl if url then print("url="..url) file=io.popen(url) local string repeat string=file:read() print('string='..string) if not string.match(string,'^%s*#') then newurl=string end until not string or newurl file:close() end print("newurl=",newurl) if newurl then plugin_sendurl(dreambox_url,newurl,range) else plugin_sendfile('www/corrupted.mp4') end end --dreambox_updatefeed("10.36.40.5","dreambox1") --dreambox_sendurl("http://10.36.40.5/web/stream.m3u?ref=1:0:1:BBB:CB:FFFF:1682DF6:0:0:0:",0) plugins['dreambox']={} plugins.dreambox.name="DreamBox" plugins.dreambox.desc="IP address (example: <i>192.168.0.1</i>)" plugins.dreambox.updatefeed=dreambox_updatefeed plugins.dreambox.sendurl=dreambox_sendurl
mit
githabbot/server22
plugins/stats.lua
12
6289
-- Saves the number of messages from a user -- Can check the number of messages with !stats do local NUM_MSG_MAX = 5 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ('..user_id..')' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text ..user.name..'\n تعداد پیام های فرد=> '..user.msgs..'\n\n' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'کاربران: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nگروه ها: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'این پلاگین تنها در گروه کار میکند' end end if matches[2] == "bot" or "telemanager" then if not is_sudo(msg) then return "تنها برای سودو مجاز است" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "تنها برای سودو مجاز است" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tats) (chat) (%d+)", "^[!/]([Ss]tats) (bot)", "^[!/]([Ss]tats) (telemanager)" }, run = run, pre_process = pre_process } end -- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- -- -- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- ||\\ //|| //\\ || //|| //\\ // || || // -- || \\ // || // \\ || // || // \\ // || || // -- || \\ // || // \\ || // || // \\ || || || // -- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || // -- || \\ // || // \\ || // || // \\ || || || || \\ -- || \\ // || // \\ || // || // \\ \\ || || || \\ -- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\ -- -- -- ||-_-_-_- || || || //-_-_-_-_-_- -- || || || || || // -- ||_-_-_|| || || || // -- || || || || \\ -- || || \\ // \\ -- || || \\ // // -- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-// -- --By @ali_ghoghnoos --@telemanager_ch
gpl-2.0