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
yswifi/APlan
build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/modules/admin-full/luasrc/model/cbi/admin_system/fstab/swap.lua
84
1922
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local util = require "nixio.util" local devices = {} util.consume((fs.glob("/dev/sd*")), devices) util.consume((fs.glob("/dev/hd*")), devices) util.consume((fs.glob("/dev/scd*")), devices) util.consume((fs.glob("/dev/mmc*")), devices) local size = {} for i, dev in ipairs(devices) do local s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev:sub(6)))) size[dev] = s and math.floor(s / 2048) end m = Map("fstab", translate("Mount Points - Swap Entry")) m.redirect = luci.dispatcher.build_url("admin/system/fstab") if not arg[1] or m.uci:get("fstab", arg[1]) ~= "swap" then luci.http.redirect(m.redirect) return end mount = m:section(NamedSection, arg[1], "swap", translate("Swap Entry")) mount.anonymous = true mount.addremove = false mount:tab("general", translate("General Settings")) mount:tab("advanced", translate("Advanced Settings")) mount:taboption("general", Flag, "enabled", translate("Enable this swap")).rmempty = false o = mount:taboption("general", Value, "device", translate("Device"), translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)")) for i, d in ipairs(devices) do o:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end o = mount:taboption("advanced", Value, "uuid", translate("UUID"), translate("If specified, mount the device by its UUID instead of a fixed device node")) o = mount:taboption("advanced", Value, "label", translate("Label"), translate("If specified, mount the device by the partition label instead of a fixed device node")) return m
gpl-2.0
bnetcc/darkstar
scripts/zones/Northern_San_dOria/npcs/Secodiand.lua
5
1737
----------------------------------- -- Area: Northern San d'Oria -- NPC: Secodiand -- Starts and Finishes Quest: Fear of the dark -- @zone 231 -- !pos -160 -0 137 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) -- if (player:getQuestStatus(SANDORIA,FEAR_OF_THE_DARK) ~= QUEST_AVAILABLE) then if (trade:hasItemQty(922,2) and trade:getItemCount() == 2) then player:startEvent(18); end end --]] end; function onTrigger(player,npc) FearOfTheDark = player:getQuestStatus(SANDORIA,FEAR_OF_THE_DARK); if (FearOfTheDark == QUEST_AVAILABLE) then player:startEvent(19); else player:startEvent(17); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); -- if (csid == 19 and option == 1) then player:addQuest(SANDORIA,FEAR_OF_THE_DARK); elseif (csid == 18) then player:tradeComplete(); player:addGil(GIL_RATE*200); player:messageSpecial(GIL_OBTAINED,GIL_RATE*200); if (player:getQuestStatus(SANDORIA,FEAR_OF_THE_DARK) == QUEST_ACCEPTED) then player:addFame(SANDORIA,30); player:completeQuest(SANDORIA,FEAR_OF_THE_DARK); else player:addFame(SANDORIA,5); end end --]] end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Upper_Jeuno/npcs/Mailloquetat.lua
5
1074
----------------------------------- -- Area: Upper Jeuno -- NPC: Mailloquetat -- Involved in Quests: Save my Sister -- @zone 244 -- !pos -31 -1 8 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getFameLevel(JEUNO) >= 4 and player:getVar("saveMySisterVar") == 1) then player:startEvent(159); -- For "Save my Sister" quest else player:startEvent(25); -- Standard dialog end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 159) then player:setVar("saveMySisterVar", 2); end end;
gpl-3.0
bnetcc/darkstar
scripts/globals/effects/allied_tags.lua
1
1039
----------------------------------- -- -- -- ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) if (target:getPet()) then target:getPet():addStatusEffect(effect); end -- local allegiance = target:getAllegiance(); -- local ALLEGIANCE_CAMPAIGN_PLAYER = 9; -- target:setStatus(STATUS_UPDATE,ALLEGIANCE_CAMPAIGN_PLAYER); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) if (target:getPet()) then target:getPet():delStatusEffect(EFFECT_ALLIED_TAGS); end -- local allegiance = target:getAllegiance(); -- local ALLEGIANCE_PLAYER = 1; -- target:setFlag(ALLEGIANCE_PLAYER); end;
gpl-3.0
mwoz123/koreader
frontend/apps/reader/modules/readerback.lua
3
7566
local ConfirmBox = require("ui/widget/confirmbox") local Device = require("device") local Event = require("ui/event") local EventListener = require("ui/widget/eventlistener") local Notification = require("ui/widget/notification") local UIManager = require("ui/uimanager") local logger = require("logger") local util = require("util") local _ = require("gettext") -- This module handles the "Back" key (and the "Back" gesture action). -- When global setting "back_in_reader" == "previous_read_page", it -- additionally handles a location stack for each visited page or -- page view change (when scrolling in a same page) local ReaderBack = EventListener:new{ location_stack = {}, -- a limit not intended to be a practical limit but just a failsafe max_stack = 5000, } function ReaderBack:init() if Device:hasKeys() then self.ui.key_events.Back = { {"Back"}, doc = "Reader back" } end -- Regular function wrapping our method, to avoid re-creating -- an anonymous function at each page turn self._addPreviousLocationToStackCallback = function() self:_addPreviousLocationToStack() end end function ReaderBack:_getCurrentLocation() if self.ui.document.info.has_pages then local current_location = self.ui.paging:getBookLocation() if current_location then -- We need a copy, as we're getting references to -- objects ReaderPaging/ReaderView may still modify local res = {} for i=1, #current_location do res[i] = util.tableDeepCopy(current_location[i]) end return res end else return { xpointer = self.ui.rolling:getBookLocation(), } end end function ReaderBack:_areLocationsSimilar(location1, location2) if self.ui.document.info.has_pages then -- locations are arrays of k/v tables if #location1 ~= #location2 then return false end for i=1, #location1 do if not util.tableEquals(location1[i], location2[i]) then return false end end return true else return location1.xpointer == location2.xpointer end end function ReaderBack:_addPreviousLocationToStack() local new_location = self:_getCurrentLocation() if self.cur_location and new_location then if self:_areLocationsSimilar(self.cur_location, new_location) then -- Unchanged, don't add it yet return end table.insert(self.location_stack, self.cur_location) if #self.location_stack > self.max_stack then table.remove(self.location_stack, 1) end end if new_location then self.cur_location = new_location end end -- Called when loading new document function ReaderBack:onReadSettings(config) self.location_stack = {} self.cur_location = nil end function ReaderBack:_onViewPossiblyUpdated() if G_reader_settings:readSetting("back_in_reader") == "previous_read_page" then -- As multiple modules will have their :onPageUpdate()/... called, -- and some of them will set up the new page with it, we need to -- delay our handling after all of them are called (otherwise, -- depending on the order of the calls, we may be have the location -- of either the previous page or the current one). UIManager:nextTick(self._addPreviousLocationToStackCallback) end self.back_resist = nil end -- Hook to events that do/may change page/view (more than one of these events -- may be sent on a single page turn/scroll, _addPreviousLocationToStack() -- will ignore those for the same book location): -- Called after initial page is set up ReaderBack.onReaderReady = ReaderBack._onViewPossiblyUpdated -- New page on paged media or crengine in page mode ReaderBack.onPageUpdate = ReaderBack._onViewPossiblyUpdated -- New page on crengine in scroll mode ReaderBack.onPosUpdate = ReaderBack._onViewPossiblyUpdated -- View updated (possibly on the same page) on paged media ReaderBack.onViewRecalculate = ReaderBack._onViewPossiblyUpdated -- View updated (possibly on the same page) on paged media (needed in Reflow mode) ReaderBack.onPagePositionUpdated = ReaderBack._onViewPossiblyUpdated function ReaderBack:onBack() local back_in_reader = G_reader_settings:readSetting("back_in_reader") or "previous_location" local back_to_exit = G_reader_settings:readSetting("back_to_exit") or "prompt" if back_in_reader == "previous_read_page" then if #self.location_stack > 0 then local saved_location = table.remove(self.location_stack) if saved_location then -- Reset self.cur_location, which will be updated with the restored -- saved_location, which will then not be added to the stack self.cur_location = nil logger.dbg("[ReaderBack] restoring:", saved_location) self.ui:handleEvent(Event:new('RestoreBookLocation', saved_location)) -- Ensure we always have self.cur_location updated, as in some -- cases (same page), no event that we handle might be sent. UIManager:nextTick(self._addPreviousLocationToStackCallback) return true end elseif not self.back_resist or back_to_exit == "disable" then -- Show a one time notification when location stack is empty. -- On next "Back" only, proceed with the default behaviour (unless -- it's disabled, in which case we always show this notification) self.back_resist = true UIManager:show(Notification:new{ text = _("Location history is empty."), }) return true else self.back_resist = nil end elseif back_in_reader == "previous_location" then -- ReaderLink maintains its own location_stack of less frequent jumps -- (links or TOC entries followed, skim document...) if back_to_exit == "disable" then -- Let ReaderLink always show its notification if empty self.ui.link:onGoBackLink(true) -- show_notification_if_empty=true return true end if self.back_resist then -- Notification "Location history is empty" previously shown by ReaderLink self.back_resist = nil elseif self.ui.link:onGoBackLink(true) then -- show_notification_if_empty=true return true -- some location restored else -- ReaderLink has shown its notification that location stack is empty. -- On next "Back" only, proceed with the default behaviour self.back_resist = true return true end elseif back_in_reader == "filebrowser" then self.ui:handleEvent(Event:new("Home")) -- Filebrowser will handle next "Back" and ensure back_to_exit return true end -- location stack empty, or back_in_reader == "default" if back_to_exit == "always" then self.ui:handleEvent(Event:new("Close")) elseif back_to_exit == "disable" then return true elseif back_to_exit == "prompt" then UIManager:show(ConfirmBox:new{ text = _("Exit KOReader?"), ok_text = _("Exit"), ok_callback = function() self.ui:handleEvent(Event:new("Close")) end }) end return true end return ReaderBack
agpl-3.0
sartura/openwrt-packages
net/dynapoint/src/dynapoint.lua
94
6369
#!/usr/bin/lua --[[ Copyright (C) 2016 Tobias Ilte <tobias.ilte@campus.tu-berlin.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] require "uci" require "ubus" require "uloop" log = require "nixio" --open sys-logging log.openlog("DynaPoint", "ndelay", "cons", "nowait"); local uci_cursor = uci.cursor() -- get all config sections with the given type function getConfType(conf_file,type) local ifce={} uci_cursor:foreach(conf_file,type,function(s) ifce[s[".index"]]=s end) return ifce end ubus = ubus.connect() if not ubus then error("Failed to connect to ubusd") end ubus:call("network", "reload", {}) local interval = uci_cursor:get("dynapoint", "internet", "interval") local timeout = uci_cursor:get("dynapoint", "internet", "timeout") local offline_threshold = tonumber(uci_cursor:get("dynapoint", "internet", "offline_threshold")) local hosts = uci_cursor:get("dynapoint", "internet", "hosts") local numhosts = #hosts local curl = tonumber(uci_cursor:get("dynapoint", "internet", "use_curl")) if (curl == 1) then curl_interface = uci_cursor:get("dynapoint", "internet", "curl_interface") end function get_system_sections(t) for pos,val in pairs(t) do if (type(val)=="table") then get_system_sections(val); elseif (type(val)=="string") then if (pos == "hostname") then localhostname = val end end end end if (tonumber(uci_cursor:get("dynapoint", "internet", "add_hostname_to_ssid")) == 1 ) then get_system_sections(getConfType("system","system")) if (not localhostname) then error("Failed to obtain system hostname") end end local table_names_rule = {} local table_names_not_rule = {} local ssids_with_hostname = {} local ssids_not_rule = {} function get_dynapoint_sections(t) for pos,val in pairs(t) do if (type(val)=="table") then get_dynapoint_sections(val); elseif (type(val)=="string") then if (pos == "dynapoint_rule") then if (val == "internet") then table_names_rule[#table_names_rule+1] = t[".name"] elseif (val == "!internet") then table_names_not_rule[#table_names_not_rule+1] = t[".name"] if (localhostname) then ssids_not_rule[#ssids_not_rule+1] = uci_cursor:get("wireless", t[".name"], "ssid") ssids_with_hostname[#ssids_with_hostname+1] = uci_cursor:get("wireless", t[".name"], "ssid").."_"..localhostname end end end end end end --print(table.getn(hosts)) get_dynapoint_sections(getConfType("wireless","wifi-iface")) -- revert all non-persistent ssid uci-changes regarding sections affecting dynapoint for i = 1, #table_names_not_rule do uci_cursor:revert("wireless", table_names_not_rule[i], "ssid") end local online = true if (#table_names_rule > 0) then if (tonumber(uci_cursor:get("wireless", table_names_rule[1], "disabled")) == 1) then online = false end else log.syslog("info","Not properly configured. Please add <option dynapoint_rule 'internet'> to /etc/config/wireless") end local timer local offline_counter = 0 uloop.init() function do_internet_check(host) if (curl == 1 ) then if (curl_interface) then result = os.execute("curl -s -m "..timeout.." --max-redirs 0 --interface "..curl_interface.." --head "..host.." > /dev/null") else result = os.execute("curl -s -m "..timeout.." --max-redirs 0 --head "..host.." > /dev/null") end else result = os.execute("wget -q --timeout="..timeout.." --spider "..host) end if (result == 0) then return true else return false end end function change_wireless_config(switch_to_offline) if (switch_to_offline == 1) then log.syslog("info","Switched to OFFLINE") for i = 1, #table_names_not_rule do uci_cursor:set("wireless",table_names_not_rule[i], "disabled", "0") if (localhostname) then uci_cursor:set("wireless", table_names_not_rule[i], "ssid", ssids_with_hostname[i]) end log.syslog("info","Bring up new AP "..uci_cursor:get("wireless", table_names_not_rule[i], "ssid")) end for i = 1, #table_names_rule do uci_cursor:set("wireless",table_names_rule[i], "disabled", "1") end else log.syslog("info","Switched to ONLINE") for i = 1, #table_names_not_rule do uci_cursor:set("wireless",table_names_not_rule[i], "disabled", "1") if (localhostname) then uci_cursor:set("wireless", table_names_not_rule[i], "ssid", ssids_not_rule[i]) end end for i = 1, #table_names_rule do uci_cursor:set("wireless",table_names_rule[i], "disabled", "0") log.syslog("info","Bring up new AP "..uci_cursor:get("wireless", table_names_rule[i], "ssid")) end end uci_cursor:save("wireless") ubus:call("network", "reload", {}) end local hostindex = 1 function check_internet_connection() print("checking "..hosts[hostindex].."...") if (do_internet_check(hosts[hostindex]) == true) then -- online print("...seems to be online") offline_counter = 0 hostindex = 1 if (online == false) then print("changed state to online") online = true change_wireless_config(0) end else --offline print("...seems to be offline") hostindex = hostindex + 1 if (hostindex <= numhosts) then check_internet_connection() else hostindex = 1 -- and activate offline-mode print("all hosts offline") if (online == true) then offline_counter = offline_counter + 1 if (offline_counter == offline_threshold) then print("changed state to offline") online = false change_wireless_config(1) end end end end timer:set(interval * 1000) end timer = uloop.timer(check_internet_connection) timer:set(interval * 1000) uloop.run()
gpl-2.0
bnetcc/darkstar
scripts/zones/Lebros_Cavern/IDs.lua
7
3220
Lebros = { text = { -- General Texts ITEM_CANNOT_BE_OBTAINED = 6381, -- You cannot obtain the <item>. Come back after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6385, -- You cannot obtain the <item>. Try trading again after sorting your inventory. ITEM_OBTAINED = 6387, -- Obtained: <item>. GIL_OBTAINED = 6388, -- Obtained <number> gil. KEYITEM_OBTAINED = 6390, -- Obtained key item: <keyitem>. KEYITEM_LOST = 6391, -- Lost key item: <keyitem>. NOT_HAVE_ENOUGH_GIL = 6392, -- You do not have enough gil. ITEMS_OBTAINED = 6396, -- You obtain <number> <item>! -- Assault Texts ASSAULT_21_START = 7366, -- Commencing <assault>! Objective: Remove the obstructions ASSAULT_22_START = 7367, -- Commencing <assault>! Objective: Deliver the provisions ASSAULT_23_START = 7368, -- Commencing <assault>! Objective: Destroy the Troll fugitives ASSAULT_24_START = 7369, -- Commencing <assault>! Objective: Discover alternate route ASSAULT_25_START = 7370, -- Commencing <assault>! Objective: Assassinate Borgerlur ASSAULT_26_START = 7371, -- Commencing <assault>! Objective: Match the Apkallu ASSAULT_27_START = 7372, -- Commencing <assault>! Objective: Remove the threat ASSAULT_28_START = 7373, -- Commencing <assault>! Objective: Drive out the hunters ASSAULT_29_START = 7374, -- Commencing <assault>! Objective: Rescue Princess Kadjaya ASSAULT_30_START = 7375, -- Commencing <assault>! Objective: Defeat Black Shuck TIME_TO_COMPLETE = 7406, -- You have <number> [minute/minutes] (Earth time) to complete this mission. MISSION_FAILED = 7407, -- The mission has failed. Leaving area. RUNE_UNLOCKED = 7408, -- Mission objective completed. Unlocking Rune of Release. ASSAULT_POINTS_OBTAINED = 7409, -- You gain <number> [Assault point/Assault points]! TIME_REMAINING_MINUTES = 7410, -- Time remaining: <number> [minute/minutes] (Earth time). TIME_REMAINING_SECONDS = 7411, -- Time remaining: <number> [second/seconds] (Earth time). PARTY_FALLEN = 7414 -- All party members have fallen in battle. Mission failure in <number> [minute/minutes]. }, mobs = { -- Wamoura Farm Raid Assault [27] = { RANCH_WAMOURA1 = 17035359, RANCH_WAMOURA2 = 17035360, RANCH_WAMOURA3 = 17035361, RANCH_WAMOURA4 = 17035362, RANCH_WAMOURA5 = 17035363, RANCH_WAMOURA6 = 17035365, RANCH_WAMOURA7 = 17035367, RANCH_WAMOURA8 = 17035368, RANCH_WAMOURA9 = 17035369, RANCH_WAMOURA10 = 17035370, RANCH_WAMOURA11 = 17035371, RANCH_WAMOURA12 = 17035372, RANCH_WAMOURA13 = 17035376, RANCH_WAMOURA14 = 17035377, RANCH_WAMOURA15 = 17035378 } }, npcs = { ANCIENT_LOCKBOX = 17035478, RUNE_OF_RELEASE = 17035479 } }
gpl-3.0
bnetcc/darkstar
scripts/zones/Gusgen_Mines/npcs/Clay.lua
5
1181
----------------------------------- -- Area: Gusgen Mines -- NPC: Clay -- Involved in Quest: A Potter's Preference -- !pos 117 -21 432 196 ----------------------------------- 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"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local GUSGENCLAY = 569; if (player:hasItem(GUSGENCLAY) == false) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,GUSGENCLAY); else player:addItem(GUSGENCLAY); player:messageSpecial(ITEM_OBTAINED, GUSGENCLAY); end else player:messageSpecial(NOTHING_OUT_OF_THE_ORDINARY); end end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bnetcc/darkstar
scripts/globals/mobskills/hyper_pulse_pantokrator_custom.lua
8
1327
--------------------------------------------------- -- Hyper_Pulse -- -- Description: 300 magic damage, Gravity and short Bind, wipes Utsusemi -- Type: Magical -- --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobID = mob:getID(); --(16908294 ,16908301 ,16908308 =omega ,16933124=proto-omega) local mobhp = mob:getHPP(); if ((mobID == 16908294 or mobID ==16908301 or mobID ==16908308)and mobhp > 25 ) then --omega return 0; elseif (mobID == 16933124 and mobhp > 30 and mobhp < 70)then -- omega bipedform return 0; end return 1; end; function onMobWeaponSkill(target, mob, skill) local typeEffect1 = EFFECT_BIND; MobStatusEffectMove(mob, target, typeEffect1, 1, 0, 4); local typeEffect2 = EFFECT_WEIGHT; MobStatusEffectMove(mob, target, typeEffect2, 50, 0, 30); local dmgmod = 1.5; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_DARK,dmgmod,TP_MAB_BONUS,1); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end
gpl-3.0
bnetcc/darkstar
scripts/globals/spells/cure_iii.lua
3
4931
----------------------------------------- -- Spell: Cure III -- Restores target's HP. -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local divisor = 0; local constant = 0; local basepower = 0; local power = 0; local basecure = 0; local final = 0; local minCure = 130; if (USE_OLD_CURE_FORMULA == true) then power = getCurePowerOld(caster); rate = 1; constant = 70; if (power > 300) then rate = 15.6666; constant = 180.43; elseif (power > 180) then rate = 2; constant = 115; end else power = getCurePower(caster); if (power < 125) then divisor = 2.2 constant = 130; basepower = 70; elseif (power < 200) then divisor = 75/65; constant = 155; basepower = 125; elseif (power < 300) then divisor = 2.5; constant = 220; basepower = 200; elseif (power < 700) then divisor = 5; constant = 260; basepower = 300; else divisor = 999999; constant = 340; basepower = 0; end end if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCure(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end final = getCureFinal(caster,spell,basecure,minCure,false); if (caster:hasStatusEffect(EFFECT_AFFLATUS_SOLACE) and target:hasStatusEffect(EFFECT_STONESKIN) == false) then local solaceStoneskin = 0; local equippedBody = caster:getEquipID(SLOT_BODY); if (equippedBody == 11186) then solaceStoneskin = math.floor(final * 0.30); elseif (equippedBody == 11086) then solaceStoneskin = math.floor(final * 0.35); else solaceStoneskin = math.floor(final * 0.25); end target:addStatusEffect(EFFECT_STONESKIN,solaceStoneskin,0,25); end; final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); --Applying server mods.... final = final * CURE_POWER; local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); else if (target:isUndead()) then spell:setMsg(msgBasic.MAGIC_DMG); local params = {}; params.dmg = minCure; params.multiplier = 1; params.skillType = HEALING_MAGIC_SKILL; params.attribute = MOD_MND; params.hasMultipleTargetReduction = false; local dmg = calculateMagicDamage(caster, target, spell, params)*0.5; local params = {}; params.diff = caster:getStat(MOD_MND)-target:getStat(MOD_MND); params.attribute = MOD_MND; params.skillType = HEALING_MAGIC_SKILL; params.bonus = 1.0; local resist = applyResistance(caster, target, spell, params); dmg = dmg*resist; dmg = addBonuses(caster,spell,target,dmg); dmg = adjustForTarget(target,dmg,spell:getElement()); dmg = finalMagicAdjustments(caster,target,spell,dmg); final = dmg; target:delHP(final); target:updateEnmityFromDamage(caster,final); elseif (caster:getObjType() == TYPE_PC) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); else -- e.g. monsters healing themselves. if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCureOld(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end final = getCureFinal(caster,spell,basecure,minCure,false); local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); end end local mpBonusPercent = (final*caster:getMod(MOD_CURE2MP_PERCENT))/100; if (mpBonusPercent > 0) then caster:addMP(mpBonusPercent); end return final; end;
gpl-3.0
bnetcc/darkstar
scripts/globals/items/pearlscale.lua
3
1074
----------------------------------------- -- ID: 5714 -- Item: Pearlscale -- Food Effect: 5 Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5714); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); end; function onEffectLose(target, effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
consulo/consulo-lua
src/test/resources/non-test-system-files/lua5.1-tests/BadLua001.lua
1
2600
function admin_do( pl, handler, id, encoded, decoded ) local players = player.GetAll() local ply = players[ decoded[ 2 ] ] local act = decoded[ 1 ] if act == "slap" then ply:SetHealth( ply:Health() - 1 ) if ply:Health() == 0 then ply:Kill() end AddNotify( ply, "You've been slapped by an admin!", 1, 5 ) elseif act == "slay" then ply:Kill() AddNotify( ply, "You've been slayed by an admin!", 1, 5 ) elseif act == "jail" then JailPlayer( ply ) AddNotify( ply, "You've been arrested by an admin!", 1, 5 ) elseif act == "free" then FreePlayer( ply ) AddNotify( ply, "You've been freed by an admin!", 1, 5 ) elseif act == "freeze" then ply:Freeze( true ) AddNotify( ply, "You've been frozen by an admin!", 1, 5 ) elseif act == "unfreeze" then ply:Freeze( false ) AddNotify( ply, "You've been unfrozen by an admin!", 1, 5 ) elseif act == "strip" then ply:StripWeapons() ply:StripAmmo() ply:Give( "krp_hands" ) AddNotify( ply, "You've been stripped of weapons by an admin!", 1, 5 ) elseif act == "kick" then ply:Kick( "Bye." ) elseif act == "temp" then ply:Ban( 2880, "Please fuck off for a couple days." ) ply:Kick( "Bye." ) elseif act == "ban" then ply:Ban( 0, "Fuck off." ) ply:Kick( "Bye." ) end end datastream.Hook( "admin_do", admin_do ) function zombeh_mode( pl, handler, id, encoded, decoded ) if !zombieMode then zombieMode = true for k, v in pairs( player.GetAll() ) do v:PrintMessage( HUD_PRINTCENTER, "ZOMBIE MODE ENABLED!" ) end else zombieMode = false for k, v in pairs( player.GetAll() ) do v:PrintMessage( HUD_PRINTCENTER, "ZOMBIE MODE DISABLED! Kill all the remaining rebels!" ) end end end datastream.Hook( "zombeh_mode", zombeh_mode ) function rebel_mode( pl, handler, id, encoded, decoded ) if !rebelMode then rebelMode = true for k, v in pairs( player.GetAll() ) do v:PrintMessage( HUD_PRINTCENTER, "REBEL MODE ENABLED!" ) end else rebelMode = false for k, v in pairs( player.GetAll() ) do v:PrintMessage( HUD_PRINTCENTER, "REBEL MODE DISABLED! Kill all the remaining rebels!" ) end end end datastream.Hook( "rebel_mode", rebel_mode ) function combine_mode( pl, handler, id, encoded, decoded ) if !combineMode then combineMode = true for k, v in pairs( player.GetAll() ) do v:PrintMessage( HUD_PRINTCENTER, "COMBINE MODE ENABLED!" ) end else combineMode = false for k, v in pairs( player.GetAll() ) do v:PrintMessage( HUD_PRINTCENTER, "COMBINE MODE DISABLED! Kill all the remaining combine!" ) end end end datastream.Hook( "combine_mode", combine_mode )
apache-2.0
awesomeWM/awesome
tests/examples/wibox/widget/textbox/wrap1.lua
1
1091
--DOC_GEN_IMAGE --DOC_HIDE_START local l = ... local wibox = require("wibox") local beautiful = require("beautiful") local ret = wibox.layout.fixed.vertical() --DOC_HIDE_END for _, wrap in ipairs {"word", "char", "word_char"} do local w = wibox.widget { wrap = wrap, text = "Notable dinausors: Tyrannosaurus-Rex, Triceratops, Velociraptor, Sauropods, Archaeopteryx.", widget = wibox.widget.textbox, } --DOC_HIDE_START ret:add( wibox.widget { markup = "Wrap: <b>" .. wrap .."</b>", widget = wibox.widget.textbox }, wibox.widget{ w, margins = 1, color = beautiful.bg_normal, forced_width = 85, forced_height = 70, widget = wibox.container.margin, }, { forced_height = 10, widget = wibox.widget.base.make_widget() } ) --DOC_HIDE_END end --DOC_HIDE_START l:add(ret) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
bnetcc/darkstar
scripts/globals/items/piece_of_akamochi.lua
3
2461
----------------------------------------- -- ID: 6260 -- Item: akamochi -- Food Effect: 30 Min, All Races ----------------------------------------- -- HP + 20 (Pet & Master) -- Vitality + 3 (Pet & Master) -- Acc + 10% Cap: 50 (Pet & Master) Pet Cap: 75 -- R. Acc + 10% Cap: 50 (Pet & Master) Pet Cap: 75 -- Attack + 16% Cap: 50 (Pet & Master) Pet Cap: 75 -- R. Attack + 16% Cap: 50 (Pet & Master) Pet Cap: 75 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD)) then result = 246; end return result; end; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,6260); end; function onEffectGain(target, effect) target:addMod(MOD_HP, 20) target:addMod(MOD_VIT, 3) target:addMod(MOD_FOOD_ACCP, 10) target:addMod(MOD_FOOD_ACC_CAP, 50) target:addMod(MOD_FOOD_RACCP, 10) target:addMod(MOD_FOOD_RACC_CAP, 50) target:addMod(MOD_FOOD_ATTP, 16) target:addMod(MOD_FOOD_ATT_CAP, 50) target:addMod(MOD_FOOD_RATTP, 16) target:addMod(MOD_FOOD_RATT_CAP, 50) target:addPetMod(MOD_HP, 20) target:addPetMod(MOD_VIT, 3) target:addPetMod(MOD_FOOD_ACCP, 10) target:addPetMod(MOD_FOOD_ACC_CAP, 75) target:addPetMod(MOD_FOOD_RACCP, 10) target:addPetMod(MOD_FOOD_RACC_CAP, 75) target:addPetMod(MOD_FOOD_ATTP, 16) target:addPetMod(MOD_FOOD_ATT_CAP, 75) target:addPetMod(MOD_FOOD_RATTP, 16) target:addPetMod(MOD_FOOD_RATT_CAP, 75) end; function onEffectLose(target, effect) target:delMod(MOD_HP, 20) target:delMod(MOD_VIT, 3) target:delMod(MOD_FOOD_ACCP, 10) target:delMod(MOD_FOOD_ACC_CAP, 50) target:delMod(MOD_FOOD_RACCP, 10) target:delMod(MOD_FOOD_RACC_CAP, 50) target:delMod(MOD_FOOD_ATTP, 16) target:delMod(MOD_FOOD_ATT_CAP, 50) target:delMod(MOD_FOOD_RATTP, 16) target:delMod(MOD_FOOD_RATT_CAP, 50) target:delPetMod(MOD_HP, 20) target:delPetMod(MOD_VIT, 3) target:delPetMod(MOD_FOOD_ACCP, 10) target:delPetMod(MOD_FOOD_ACC_CAP, 75) target:delPetMod(MOD_FOOD_RACCP, 10) target:delPetMod(MOD_FOOD_RACC_CAP, 75) target:delPetMod(MOD_FOOD_ATTP, 16) target:delPetMod(MOD_FOOD_ATT_CAP, 75) target:delPetMod(MOD_FOOD_RATTP, 16) target:delPetMod(MOD_FOOD_RATT_CAP, 75) end;
gpl-3.0
bnetcc/darkstar
scripts/globals/mobskills/sparkstorm_custom.lua
1
1092
--------------------------------------------------- -- Sparkstorm -- Hurkan --------------------------------------------------- require("scripts/globals/monstertpmoves"); require("scripts/globals/settings"); require("scripts/globals/status"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg() * 4,ELE_THUNDER,dmgmod,TP_MAB_BONUS,1); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_THUNDER,MOBPARAM_IGNORE_SHADOWS); MobStatusEffectMove(mob, target, EFFECT_MAX_MP_DOWN, 50, 0, 60); MobStatusEffectMove(mob, target, EFFECT_ATTACK_DOWN, 50, 0, 60); MobStatusEffectMove(mob, target, EFFECT_DEFENSE_DOWN, 50, 0, 60); MobStatusEffectMove(mob, target, EFFECT_MAGIC_DEF_DOWN, 50, 0, 60); target:delHP(dmg); -- Effect AFTER dmg to avoid instant KO MobStatusEffectMove(mob, target, EFFECT_MAX_HP_DOWN, 50, 0, 60); return dmg; end;
gpl-3.0
s4jj4d021/TgGuard
plugins/saveplug.lua
20
1784
local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end return false end local function disable_plugin( name, chat ) local k = plugin_enabled(name) if not k then return end table.remove(_config.enabled_plugins, k) save_config( ) end local function enable_plugin( plugin_name ) if plugin_enabled(plugin_name) then return disable_plugin( name, chat ) end table.insert(_config.enabled_plugins, plugin_name) save_config() end 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 reload_plugins( ) plugins = {} load_plugins() end local function saveplug(extra, success, result) local msg = extra.msg local name = extra.name local receiver = get_receiver(msg) if success then local file = 'plugins/'..name..'.lua' print('File saving to:', result) os.rename(result, file) print('File moved to:', file) enable_plugin(name) reload_plugins( ) 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.reply_id then local name = matches[2] if matches[1] == "save" and matches[2] and is_sudo(msg) then load_document(msg.reply_id, saveplug, {msg=msg,name=name}) return 'Plugin '..name..' has been saved.' end end end return { advan = { "Created by: @janlou & @Alirezamee", "Powered by: @SUDO_TM & @AdvanTM", "CopyRight all right reserved", }, patterns = { "^[!/#](save) (.*)$", }, run = run, }
agpl-3.0
bnetcc/darkstar
scripts/zones/Gusgen_Mines/npcs/Treasure_Chest.lua
5
3415
----------------------------------- -- Area: Gusgen Mines -- NPC: Treasure Chest -- Involved In Quest: The Goblin Tailor -- @zone 196 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/treasure"); require("scripts/zones/Gusgen_Mines/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 43; local TreasureMinLvL = 33; function onTrade(player,npc,trade) --trade:hasItemQty(1031,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(1031,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(); -- IMPORTANT ITEM: The Goblin Tailor Quest ----------- if (player:getQuestStatus(JEUNO,THE_GOBLIN_TAILOR) >= QUEST_ACCEPTED and VanadielRSELocation() == 1 and VanadielRSERace() == player:getRace() and player:hasKeyItem(MAGICAL_PATTERN) == false) then questItemNeeded = 1; end -------------------------------------- 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 local respawn = false; -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then respawn = true; player:addKeyItem(MAGICAL_PATTERN); player:messageSpecial(KEYITEM_OBTAINED,MAGICAL_PATTERN); else 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 end UpdateTreasureSpawnPoint(npc:getID(),respawn); end end end end; function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1031); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
ameihm0912/MozDef
examples/heka-lua-bro/bro_ftp.lua
10
3588
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. -- Copyright (c) 2014 Mozilla Corporation -- -- Contributors: -- Anthony Verez averez@mozilla.com -- Jeff Bryner jbryner@mozilla.com -- Michal Purzynski mpurzynski@mozilla.com local l=require "lpeg" local string=require "string" l.locale(l) --add locale entries in the lpeg table local space = l.space^0 --define a space constant local sep = l.P"\t" local elem = l.C((1-sep)^0) grammar = l.Ct(elem * (sep * elem)^0) -- split on tabs, return as table function toString(value) if value == "-" then return nil end return value end function nilToString(value) if value == nil then return "" end return value end function toNumber(value) if value == "-" then return nil end return tonumber(value) end function truncate(value) -- truncate the URI if too long (heka limited to 63KiB messages) if toString(value) then if string.len(value) > 10000 then return toString(string.sub(value, 1, 10000)) .. "[truncated]" else return value end end end function lastField(value) -- remove last "\n" if there's one if value ~= nil and string.len(value) > 1 and string.sub(value, -2) == "\n" then return string.sub(value, 1, -2) end return value end function process_message() local log = read_message("Payload") --set a default msg that heka's --message matcher can ignore via a message matcher: -- message_matcher = "( Type!='heka.all-report' && Type != 'IGNORE' )" local msg = { Type = "IGNORE", Fields={} } local matches = grammar:match(log) if not matches then --return 0 to not propogate errors to heka's log. --return a message with IGNORE type to not match heka's message matcher inject_message(msg) return 0 end if string.sub(log,1,1)=='#' then --it's a comment line inject_message(msg) return 0 end msg['Type'] = 'broftp' msg['Logger'] = 'nsm' msg.Fields['ts'] = toString(matches[1]) msg.Fields['uid'] = toString(matches[2]) msg.Fields['sourceipaddress'] = toString(matches[3]) msg.Fields['sourceport'] = toNumber(matches[4]) msg.Fields['destinationipaddress'] = toString(matches[5]) msg.Fields['destinationport'] = toNumber(matches[6]) msg.Fields['user'] = toString(matches[7]) msg.Fields['password'] = toString(matches[8]) msg.Fields['command'] = toString(matches[9]) msg.Fields['arg'] = toString(matches[10]) msg.Fields['mime_type'] = toString(matches[11]) msg.Fields['file_size_int'] = toNumber(matches[12]) msg.Fields['reply_code_int'] = toNumber(matches[13]) msg.Fields['reply_msg'] = toString(matches[14]) msg.Fields['data_channel.passive'] = toString(matches[15]) msg.Fields['data_channel.orig_h'] = toString(matches[16]) msg.Fields['data_channel.resp_h'] = toString(matches[17]) msg.Fields['data_channel.resp_p_int'] = toNumber(matches[18]) msg.Fields['fuid'] = lastField(matches[19]) -- remove last "\n" msg.Fields['summary'] = "FTP: " .. nilToString(msg.Fields['sourceipaddress']) .. " -> " .. nilToString(msg.Fields['destinationipaddress']) .. ":" .. nilToString(msg.Fields['destinationport']) .. " " .. nilToString(msg.Fields['command']) .. " as " .. nilToString(msg.Fields['user']) inject_message(msg) return 0 end
mpl-2.0
bnetcc/darkstar
scripts/globals/weaponskills/shield_break.lua
3
1927
----------------------------------- -- Shield Break -- Great Axe weapon skill -- Skill level: 5 -- Lowers enemy's Evasion. Duration of effect varies with TP. -- Lowers Evasion by as much as 40 if unresisted. -- Strong against: Bees, Beetles, Birds, Crabs, Crawlers, Flies, Lizards, Mandragora, Opo-opo, Pugils, Sabotenders, Scorpions, Sea Monks, Spiders, Tonberry, Yagudo. -- Immune: Bombs, Gigas, Ghosts, Sheep, Skeletons, Tigers. -- Will stack with Sneak Attack. -- Aligned with the Thunder Gorget. -- Aligned with the Thunder Belt. -- Element: Ice -- Modifiers: STR:60% ; VIT:60% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.2; params.agi_wsc = 0.0; params.int_wsc = 0.0; 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.str_wsc = 0.6; params.vit_wsc = 0.6; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); if (damage > 0 and target:hasStatusEffect(EFFECT_EVASION_DOWN) == false) then local duration = (120 + (tp/1000 * 60)) * applyResistanceAddEffect(player,target,ELE_ICE,0); target:addStatusEffect(EFFECT_EVASION_DOWN, 40, 0, duration); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
seeker24/happy
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
MoonTeamBot/TeleMoon
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
farshadfaza/newpermag
libs/url.lua
31
8003
-- کد های پایین در ربات نشان داده نمیشوند -- http://permag.ir -- @permag_ir -- @permag_bots -- @permag local string = require("string") local base = _G local table = require("table") local Url={} Url._VERSION = "URL 1.0.2" function Url.escape(s) return string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end) end local function make_set(t) local s = {} for i,v in base.ipairs(t) do s[t[i]] = 1 end return s end local segment_set = make_set { "-", "_", ".", "!", "~", "*", "'", "(", ")", ":", "@", "&", "=", "+", "$", ",", } local function protect_segment(s) return string.gsub(s, "([^A-Za-z0-9_])", function (c) if segment_set[c] then return c else return string.format("%%%02x", string.byte(c)) end end) end function Url.unescape(s) return string.gsub(s, "%%(%x%x)", function(hex) return string.char(base.tonumber(hex, 16)) end) end local function absolute_path(base_path, relative_path) if string.sub(relative_path, 1, 1) == "/" then return relative_path end local path = string.gsub(base_path, "[^/]*$", "") path = path .. relative_path path = string.gsub(path, "([^/]*%./)", function (s) if s ~= "./" then return s else return "" end end) path = string.gsub(path, "/%.$", "/") local reduced while reduced ~= path do reduced = path path = string.gsub(reduced, "([^/]*/%.%./)", function (s) if s ~= "../../" then return "" else return s end end) end path = string.gsub(reduced, "([^/]*/%.%.)$", function (s) if s ~= "../.." then return "" else return s end end) return path end ----------------------------------------------------------------------------- -- Parses a url and returns a table with all its parts according to RFC 2396 -- The following grammar describes the names given to the URL parts -- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment> -- <authority> ::= <userinfo>@<host>:<port> -- <userinfo> ::= <user>[:<password>] -- <path> :: = {<segment>/}<segment> -- Input -- url: uniform resource locator of request -- default: table with default values for each field -- Returns -- table with the following fields, where RFC naming conventions have -- been preserved: -- scheme, authority, userinfo, user, password, host, port, -- path, params, query, fragment -- Obs: -- the leading '/' in {/<path>} is considered part of <path> ----------------------------------------------------------------------------- function Url.parse(url, default) -- initialize default parameters local parsed = {} for i,v in base.pairs(default or parsed) do parsed[i] = v end -- empty url is parsed to nil if not url or url == "" then return nil, "invalid url" end -- remove whitespace -- url = string.gsub(url, "%s", "") -- get fragment url = string.gsub(url, "#(.*)$", function(f) parsed.fragment = f return "" end) -- get scheme url = string.gsub(url, "^([%w][%w%+%-%.]*)%:", function(s) parsed.scheme = s; return "" end) -- get authority url = string.gsub(url, "^//([^/]*)", function(n) parsed.authority = n return "" end) -- get query stringing url = string.gsub(url, "%?(.*)", function(q) parsed.query = q return "" end) -- get params url = string.gsub(url, "%;(.*)", function(p) parsed.params = p return "" end) -- path is whatever was left if url ~= "" then parsed.path = url end local authority = parsed.authority if not authority then return parsed end authority = string.gsub(authority,"^([^@]*)@", function(u) parsed.userinfo = u; return "" end) authority = string.gsub(authority, ":([^:]*)$", function(p) parsed.port = p; return "" end) if authority ~= "" then parsed.host = authority end local userinfo = parsed.userinfo if not userinfo then return parsed end userinfo = string.gsub(userinfo, ":([^:]*)$", function(p) parsed.password = p; return "" end) parsed.user = userinfo return parsed end ----------------------------------------------------------------------------- -- Rebuilds a parsed URL from its components. -- Components are protected if any reserved or unallowed characters are found -- Input -- parsed: parsed URL, as returned by parse -- Returns -- a stringing with the corresponding URL ----------------------------------------------------------------------------- function Url.build(parsed) local ppath = Url.parse_path(parsed.path or "") local url = Url.build_path(ppath) if parsed.params then url = url .. ";" .. parsed.params end if parsed.query then url = url .. "?" .. parsed.query end local authority = parsed.authority if parsed.host then authority = parsed.host if parsed.port then authority = authority .. ":" .. parsed.port end local userinfo = parsed.userinfo if parsed.user then userinfo = parsed.user if parsed.password then userinfo = userinfo .. ":" .. parsed.password end end if userinfo then authority = userinfo .. "@" .. authority end end if authority then url = "//" .. authority .. url end if parsed.scheme then url = parsed.scheme .. ":" .. url end if parsed.fragment then url = url .. "#" .. parsed.fragment end -- url = string.gsub(url, "%s", "") return url end -- Builds a absolute URL from a base and a relative URL according to RFC 2396 function Url.absolute(base_url, relative_url) if base.type(base_url) == "table" then base_parsed = base_url base_url = Url.build(base_parsed) else base_parsed = Url.parse(base_url) end local relative_parsed = Url.parse(relative_url) if not base_parsed then return relative_url elseif not relative_parsed then return base_url elseif relative_parsed.scheme then return relative_url else relative_parsed.scheme = base_parsed.scheme if not relative_parsed.authority then relative_parsed.authority = base_parsed.authority if not relative_parsed.path then relative_parsed.path = base_parsed.path if not relative_parsed.params then relative_parsed.params = base_parsed.params if not relative_parsed.query then relative_parsed.query = base_parsed.query end end else relative_parsed.path = absolute_path(base_parsed.path or "", relative_parsed.path) end end return Url.build(relative_parsed) end end -- Breaks a path into its segments, unescaping the segments function Url.parse_path(path) local parsed = {} path = path or "" --path = string.gsub(path, "%s", "") string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end) for i = 1, #parsed do parsed[i] = Url.unescape(parsed[i]) end if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end return parsed end -- Builds a path component from its segments, escaping protected characters. function Url.build_path(parsed, unsafe) local path = "" local n = #parsed if unsafe then for i = 1, n-1 do path = path .. parsed[i] path = path .. "/" end if n > 0 then path = path .. parsed[n] if parsed.is_directory then path = path .. "/" end end else for i = 1, n-1 do path = path .. protect_segment(parsed[i]) path = path .. "/" end if n > 0 then path = path .. protect_segment(parsed[n]) if parsed.is_directory then path = path .. "/" end end end if parsed.is_absolute then path = "/" .. path end return path end return Url -- کد های پایین در ربات نشان داده نمیشوند -- http://permag.ir -- @permag_ir -- @permag_bots -- @permag
gpl-3.0
ameihm0912/MozDef
examples/heka-lua-bro/bro_socks.lua
2
3146
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. -- Copyright (c) 2014 Mozilla Corporation -- -- Contributors: -- Anthony Verez averez@mozilla.com -- Jeff Bryner jbryner@mozilla.com -- Michal Purzynski mpurzynski@mozilla.com require "lpeg" require "string" -- Some magic for parsing tab-separated logs local sep = lpeg.P"\t" local elem = lpeg.C((1-sep)^0) local grammar = -lpeg.P"#" * lpeg.Ct(elem * (sep * elem)^0) -- ignore comment, split on tabs, return as table local msg = { Type = "brosocks", Logger = "nsm", Fields = { -- Initializing our fields ['ts'] = nil, ['uid'] = nil, ['sourceipaddress'] = nil, ['sourceport'] = nil, ['destinationipaddress'] = nil, ['destinationport'] = nil, ['version_int'] = nil, ['user'] = nil, ['status'] = nil, ['request.host'] = nil, ['request.name'] = nil, ['request_p_int'] = nil, ['bound.host'] = nil, ['bound.name'] = nil, ['bound_p_int'] = nil, ['summary'] = nil, summary = nil, severity = "INFO", category = "brosocks", tags = "nsm,bro,socks" } } function toString(value) if value == "-" then return nil end return value end function toNumber(value) if value == "-" then return nil end return tonumber(value) end function nilToString(value) if value == nil then return "" end return value end function process_message() local log = read_message("Payload") local matches = grammar:match(log) if not matches then return -1 end msg.Fields['ts'] = toString(matches[1]) msg.Fields['uid'] = toString(matches[2]) msg.Fields['sourceipaddress'] = toString(matches[3]) msg.Fields['sourceport'] = toNumber(matches[4]) msg.Fields['destinationipaddress'] = toString(matches[5]) msg.Fields['destinationport'] = toNumber(matches[6]) msg.Fields['version_int'] = toNumber(matches[7]) msg.Fields['user'] = toString(matches[8]) msg.Fields['status'] = toString(matches[9]) msg.Fields['request.host'] = toString(matches[10]) msg.Fields['request.name'] = toString(matches[11]) msg.Fields['request_p_int'] = toNumber(matches[12]) msg.Fields['bound.host'] = toString(matches[13]) msg.Fields['bound.name'] = toString(matches[14]) msg.Fields['bound_p_int'] = toNumber(string.sub(matches[15], 1, -2)) -- remove last "\n" msg.Fields['summary'] = nilToString(msg.Fields['sourceipaddress']) .. ":" .. nilToString(msg.Fields['sourceport']) .. " -> " .. nilToString(msg.Fields['destinationipaddress']) .. ":" .. nilToString(msg.Fields['destinationport']) .. " SOCKS v" .. nilToString(msg.Fields['version_int']) .. " " .. nilToString(msg.Fields['request.host']) .. ":" .. nilToString(msg.Fields['request_p_int']) .. " -> " .. nilToString(msg.Fields['bound.host']) .. ":" .. nilToString(msg.Fields['bound_p_int']) inject_message(msg) return 0 end
mpl-2.0
bnetcc/darkstar
scripts/globals/items/bowl_of_zesty_zoni.lua
3
1722
----------------------------------------- -- ID: 5619 -- Item: Bowl of Zesti Zoni -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- HP 12 -- MP 12 -- Strength 2 -- Dexterity 2 -- Vitality 2 -- Agility 2 -- Accuracy +2 -- Ranged Accuracy +2 -- Attack +2 -- Ranged Attack +2 -- Evasion +2 -- MP Recovered while healing 1 -- HP Recovered while healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5619); end; function onEffectGain(target, effect) target:addMod(MOD_HP, 12); target:addMod(MOD_MP, 12); target:addMod(MOD_STR, 2); target:addMod(MOD_DEX, 2); target:addMod(MOD_VIT, 2); target:addMod(MOD_AGI, 2); target:addMod(MOD_ACC, 2); target:addMod(MOD_RACC, 2); target:addMod(MOD_ATT, 2); target:addMod(MOD_RATT, 2); target:addMod(MOD_EVA, 2); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_MPHEAL, 1); end; function onEffectLose(target, effect) target:delMod(MOD_HP, 12); target:delMod(MOD_MP, 12); target:delMod(MOD_STR, 2); target:delMod(MOD_DEX, 2); target:delMod(MOD_VIT, 2); target:delMod(MOD_AGI, 2); target:delMod(MOD_ACC, 2); target:delMod(MOD_RACC, 2); target:delMod(MOD_ATT, 2); target:delMod(MOD_RATT, 2); target:delMod(MOD_EVA, 2); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
yswifi/APlan
build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/ipkg-ramips_24kec/luci-lib-ipkg/usr/lib/lua/luci/model/ipkg.lua
82
5778
--[[ LuCI - Lua Configuration Interface (c) 2008-2011 Jo-Philipp Wich <xm@subsignal.org> (c) 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local os = require "os" local io = require "io" local fs = require "nixio.fs" local util = require "luci.util" local type = type local pairs = pairs local error = error local table = table local ipkg = "opkg --force-removal-of-dependent-packages --force-overwrite --nocase" local icfg = "/etc/opkg.conf" --- LuCI OPKG call abstraction library module "luci.model.ipkg" -- Internal action function local function _action(cmd, ...) local pkg = "" for k, v in pairs({...}) do pkg = pkg .. " '" .. v:gsub("'", "") .. "'" end local c = "%s %s %s >/tmp/opkg.stdout 2>/tmp/opkg.stderr" %{ ipkg, cmd, pkg } local r = os.execute(c) local e = fs.readfile("/tmp/opkg.stderr") local o = fs.readfile("/tmp/opkg.stdout") fs.unlink("/tmp/opkg.stderr") fs.unlink("/tmp/opkg.stdout") return r, o or "", e or "" end -- Internal parser function local function _parselist(rawdata) if type(rawdata) ~= "function" then error("OPKG: Invalid rawdata given") end local data = {} local c = {} local l = nil for line in rawdata do if line:sub(1, 1) ~= " " then local key, val = line:match("(.-): ?(.*)%s*") if key and val then if key == "Package" then c = {Package = val} data[val] = c elseif key == "Status" then c.Status = {} for j in val:gmatch("([^ ]+)") do c.Status[j] = true end else c[key] = val end l = key end else -- Multi-line field c[l] = c[l] .. "\n" .. line end end return data end -- Internal lookup function local function _lookup(act, pkg) local cmd = ipkg .. " " .. act if pkg then cmd = cmd .. " '" .. pkg:gsub("'", "") .. "'" end -- OPKG sometimes kills the whole machine because it sucks -- Therefore we have to use a sucky approach too and use -- tmpfiles instead of directly reading the output local tmpfile = os.tmpname() os.execute(cmd .. (" >%s 2>/dev/null" % tmpfile)) local data = _parselist(io.lines(tmpfile)) os.remove(tmpfile) return data end --- Return information about installed and available packages. -- @param pkg Limit output to a (set of) packages -- @return Table containing package information function info(pkg) return _lookup("info", pkg) end --- Return the package status of one or more packages. -- @param pkg Limit output to a (set of) packages -- @return Table containing package status information function status(pkg) return _lookup("status", pkg) end --- Install one or more packages. -- @param ... List of packages to install -- @return Boolean indicating the status of the action -- @return OPKG return code, STDOUT and STDERR function install(...) return _action("install", ...) end --- Determine whether a given package is installed. -- @param pkg Package -- @return Boolean function installed(pkg) local p = status(pkg)[pkg] return (p and p.Status and p.Status.installed) end --- Remove one or more packages. -- @param ... List of packages to install -- @return Boolean indicating the status of the action -- @return OPKG return code, STDOUT and STDERR function remove(...) return _action("remove", ...) end --- Update package lists. -- @return Boolean indicating the status of the action -- @return OPKG return code, STDOUT and STDERR function update() return _action("update") end --- Upgrades all installed packages. -- @return Boolean indicating the status of the action -- @return OPKG return code, STDOUT and STDERR function upgrade() return _action("upgrade") end -- List helper function _list(action, pat, cb) local fd = io.popen(ipkg .. " " .. action .. (pat and (" '%s'" % pat:gsub("'", "")) or "")) if fd then local name, version, desc while true do local line = fd:read("*l") if not line then break end name, version, desc = line:match("^(.-) %- (.-) %- (.+)") if not name then name, version = line:match("^(.-) %- (.+)") desc = "" end cb(name, version, desc) name = nil version = nil desc = nil end fd:close() end end --- List all packages known to opkg. -- @param pat Only find packages matching this pattern, nil lists all packages -- @param cb Callback function invoked for each package, receives name, version and description as arguments -- @return nothing function list_all(pat, cb) _list("list", pat, cb) end --- List installed packages. -- @param pat Only find packages matching this pattern, nil lists all packages -- @param cb Callback function invoked for each package, receives name, version and description as arguments -- @return nothing function list_installed(pat, cb) _list("list_installed", pat, cb) end --- Find packages that match the given pattern. -- @param pat Find packages whose names or descriptions match this pattern, nil results in zero results -- @param cb Callback function invoked for each patckage, receives name, version and description as arguments -- @return nothing function find(pat, cb) _list("find", pat, cb) end --- Determines the overlay root used by opkg. -- @return String containing the directory path of the overlay root. function overlay_root() local od = "/" local fd = io.open(icfg, "r") if fd then local ln repeat ln = fd:read("*l") if ln and ln:match("^%s*option%s+overlay_root%s+") then od = ln:match("^%s*option%s+overlay_root%s+(%S+)") local s = fs.stat(od) if not s or s.type ~= "dir" then od = "/" end break end until not ln fd:close() end return od end
gpl-2.0
bnetcc/darkstar
scripts/zones/Abyssea-Grauberg/npcs/Atma_Infusionist.lua
1
3166
----------------------------------- -- Zone: Abyssea - Grauberg -- NPC: Atma Infusionist -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Grauberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/abyssea"); require("scripts/zones/Abyssea-Grauberg/TextIDs"); require("scripts/globals/atma"); require("scripts/globals/msg"); ----------------------------------- function onTrade(player,npc,trade) removeATMA(player); end; function onTrigger(player,npc) local param1 = player:getCurrency("Cruor"); -- This param seems to contain both the players current cruor total and the reinfuse option. local param2 = 0x01000000; -- This param seems to contain values relating to both the infuse(byte4), reinfuse, and examine options. local param3 = 0xFFFFFFFF; -- Available ATMA masks, dummied for now. local param4 = 0xFFFFFFFF; -- Available ATMA masks, dummied for now. local param5 = 0xFFFFFFFF; -- Available ATMA masks, dummied for now. local param6 = 0xFFFFFFFF; -- Available ATMA masks, dummied for now. local param7 = 0xFFFFFFFF; -- Available ATMA masks, dummied for now. local param8 = 0xFFFFFFFF; -- Available ATMA masks, dummied for now. if (countLunars(player) == 0) then player:startEvent(2003); elseif ((player:getVar("ACTIVE_ATMA_COUNT") >= countLunars(player))) then local msgText = string.format("You have the maximum ATMA effects your %i Lunar Abyssite will allow.", countLunars(player)); player:PrintToPlayer(msgText, chatType.SAY, npc:getName()); player:PrintToPlayer("To have all ATMA effects removed, trade me 1 gil. ", chatType.SAY, npc:getName()); else player:PrintToPlayer("Parts of this menu are not yet functional!") player:PrintToPlayer("ATMA will be shown even if you do not have it yet!") player:startEvent(2003, param1, param2, param3, param4, param5, param6, param7, param8); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); -- player:PrintToPlayer(string.format("Update: %u", option)); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); -- player:PrintToPlayer(string.format("Option: %u",option)); if (option == 3 or option == 268435461 or option == 134217733 or option == 67108869 or option == 33554437 or option == 16777221 or option == 8388613 or option == 4194309 or option == 2097157 or option == 1048581) then player:PrintToPlayer("Previous set and recent history options do not work yet."); elseif (option >= 65537 and option ~= 1073741824) then if (player:getVar("ACTIVE_ATMA_COUNT") < countLunars(player)) then -- player:PrintToPlayer(string.format("Lunars: %i ", countLunars(player))); local pwr = (option -1)/65536; -- player:PrintToPlayer(string.format("ATMA ID: %d",pwr)); applyATMA(player, pwr) else player:PrintToPlayer("ERROR! How did you get here?"); end end end;
gpl-3.0
ammeurer/osrm-backend
profiles/foot.lua
8
6969
-- Foot profile local find_access_tag = require("lib/access").find_access_tag -- Begin of globals barrier_whitelist = { [""] = true, ["cycle_barrier"] = true, ["bollard"] = true, ["entrance"] = true, ["cattle_grid"] = true, ["border_control"] = true, ["toll_booth"] = true, ["sally_port"] = true, ["gate"] = true, ["no"] = true} access_tag_whitelist = { ["yes"] = true, ["foot"] = true, ["permissive"] = true, ["designated"] = true } access_tag_blacklist = { ["no"] = true, ["private"] = true, ["agricultural"] = true, ["forestry"] = true } access_tag_restricted = { ["destination"] = true, ["delivery"] = true } access_tags_hierachy = { "foot", "access" } service_tag_restricted = { ["parking_aisle"] = true } ignore_in_grid = { ["ferry"] = true } restriction_exception_tags = { "foot" } walking_speed = 5 speeds = { ["primary"] = walking_speed, ["primary_link"] = walking_speed, ["secondary"] = walking_speed, ["secondary_link"] = walking_speed, ["tertiary"] = walking_speed, ["tertiary_link"] = walking_speed, ["unclassified"] = walking_speed, ["residential"] = walking_speed, ["road"] = walking_speed, ["living_street"] = walking_speed, ["service"] = walking_speed, ["track"] = walking_speed, ["path"] = walking_speed, ["steps"] = walking_speed, ["pedestrian"] = walking_speed, ["footway"] = walking_speed, ["pier"] = walking_speed, ["default"] = walking_speed } route_speeds = { ["ferry"] = 5 } platform_speeds = { ["platform"] = walking_speed } amenity_speeds = { ["parking"] = walking_speed, ["parking_entrance"] = walking_speed } man_made_speeds = { ["pier"] = walking_speed } surface_speeds = { ["fine_gravel"] = walking_speed*0.75, ["gravel"] = walking_speed*0.75, ["pebblestone"] = walking_speed*0.75, ["mud"] = walking_speed*0.5, ["sand"] = walking_speed*0.5 } leisure_speeds = { ["track"] = walking_speed } traffic_signal_penalty = 2 u_turn_penalty = 2 use_turn_restrictions = false --modes local mode_normal = 1 local mode_ferry = 2 function get_exceptions(vector) for i,v in ipairs(restriction_exception_tags) do vector:Add(v) end end function node_function (node, result) local barrier = node:get_value_by_key("barrier") local access = find_access_tag(node, access_tags_hierachy) local traffic_signal = node:get_value_by_key("highway") -- flag node if it carries a traffic light if traffic_signal and traffic_signal == "traffic_signals" then result.traffic_light = true end -- parse access and barrier tags if access and access ~= "" then if access_tag_blacklist[access] then result.barrier = true else result.barrier = false end elseif barrier and barrier ~= "" then if barrier_whitelist[barrier] then result.barrier = false else result.barrier = true end end return 1 end function way_function (way, result) -- initial routability check, filters out buildings, boundaries, etc local highway = way:get_value_by_key("highway") local leisure = way:get_value_by_key("leisure") local route = way:get_value_by_key("route") local man_made = way:get_value_by_key("man_made") local railway = way:get_value_by_key("railway") local amenity = way:get_value_by_key("amenity") local public_transport = way:get_value_by_key("public_transport") if (not highway or highway == '') and (not leisure or leisure == '') and (not route or route == '') and (not railway or railway=='') and (not amenity or amenity=='') and (not man_made or man_made=='') and (not public_transport or public_transport=='') then return end -- don't route on ways that are still under construction if highway=='construction' then return end -- access local access = find_access_tag(way, access_tags_hierachy) if access_tag_blacklist[access] then return end local name = way:get_value_by_key("name") local ref = way:get_value_by_key("ref") local junction = way:get_value_by_key("junction") local onewayClass = way:get_value_by_key("oneway:foot") local duration = way:get_value_by_key("duration") local service = way:get_value_by_key("service") local area = way:get_value_by_key("area") local foot = way:get_value_by_key("foot") local surface = way:get_value_by_key("surface") -- name if ref and "" ~= ref and name and "" ~= name then result.name = name .. ' / ' .. ref elseif ref and "" ~= ref then result.name = ref elseif name and "" ~= name then result.name = name elseif highway then result.name = "{highway:"..highway.."}" -- if no name exists, use way type -- this encoding scheme is excepted to be a temporary solution end -- roundabouts if "roundabout" == junction then result.roundabout = true; end -- speed if route_speeds[route] then -- ferries (doesn't cover routes tagged using relations) result.ignore_in_grid = true if duration and durationIsValid(duration) then result.duration = math.max( 1, parseDuration(duration) ) else result.forward_speed = route_speeds[route] result.backward_speed = route_speeds[route] end result.forward_mode = mode_ferry result.backward_mode = mode_ferry elseif railway and platform_speeds[railway] then -- railway platforms (old tagging scheme) result.forward_speed = platform_speeds[railway] result.backward_speed = platform_speeds[railway] elseif platform_speeds[public_transport] then -- public_transport platforms (new tagging platform) result.forward_speed = platform_speeds[public_transport] result.backward_speed = platform_speeds[public_transport] elseif amenity and amenity_speeds[amenity] then -- parking areas result.forward_speed = amenity_speeds[amenity] result.backward_speed = amenity_speeds[amenity] elseif leisure and leisure_speeds[leisure] then -- running tracks result.forward_speed = leisure_speeds[leisure] result.backward_speed = leisure_speeds[leisure] elseif speeds[highway] then -- regular ways result.forward_speed = speeds[highway] result.backward_speed = speeds[highway] elseif access and access_tag_whitelist[access] then -- unknown way, but valid access tag result.forward_speed = walking_speed result.backward_speed = walking_speed end -- oneway if onewayClass == "yes" or onewayClass == "1" or onewayClass == "true" then result.backward_mode = 0 elseif onewayClass == "no" or onewayClass == "0" or onewayClass == "false" then -- nothing to do elseif onewayClass == "-1" then result.forward_mode = 0 end -- surfaces if surface then surface_speed = surface_speeds[surface] if surface_speed then result.forward_speed = math.min(result.forward_speed, surface_speed) result.backward_speed = math.min(result.backward_speed, surface_speed) end end end
bsd-2-clause
vowstar/nodemcu-firmware
lua_examples/mcp23008/mcp23008_buttons.lua
82
1801
--- -- @description Shows how to read 8 GPIO pins/buttons via I2C with the MCP23008 I/O expander. -- Tested on NodeMCU 0.9.5 build 20150213. -- @circuit -- Connect GPIO0 of the ESP8266-01 module to the SCL pin of the MCP23008. -- Connect GPIO2 of the ESP8266-01 module to the SDA pin of the MCP23008. -- Use 3.3V for VCC. -- Connect switches or buttons to the GPIOs of the MCP23008 and GND. -- Connect two 4.7k pull-up resistors on SDA and SCL -- We will enable the internal pull up resistors for the GPIOS of the MCP23008. -- @author Miguel (AllAboutEE) -- GitHub: https://github.com/AllAboutEE -- YouTube: https://www.youtube.com/user/AllAboutEE -- Website: http://AllAboutEE.com --------------------------------------------------------------------------------------------- require ("mcp23008") -- ESP-01 GPIO Mapping as per GPIO Table in https://github.com/nodemcu/nodemcu-firmware gpio0, gpio2 = 3, 4 -- Setup the MCP23008 mcp23008.begin(0x0,gpio2,gpio0,i2c.SLOW) mcp23008.writeIODIR(0xff) mcp23008.writeGPPU(0xff) --- -- @name showButtons -- @description Shows the state of each GPIO pin -- @return void --------------------------------------------------------- function showButtons() local gpio = mcp23008.readGPIO() -- read the GPIO/buttons states -- get/extract the state of one pin at a time for pin=0,7 do local pinState = bit.band(bit.rshift(gpio,pin),0x1) -- extract one pin state -- change to string state (HIGH, LOW) instead of 1 or 0 respectively if(pinState == mcp23008.HIGH) then pinState = "HIGH" else pinState = "LOW" end print("Pin ".. pin .. ": ".. pinState) end print("\r\n") end tmr.alarm(0,2000,1,showButtons) -- run showButtons() every 2 seconds
mit
bnetcc/darkstar
scripts/globals/items/red_curry_bun_+1.lua
3
1798
----------------------------------------- -- ID: 5765 -- Item: red_curry_bun_+1 -- Food Effect: 60 Min, All Races ----------------------------------------- -- TODO: Group effects -- Health 35 -- Strength 7 -- Agility 3 -- Attack % 25 (cap 150) -- Ranged Atk % 25 (cap 150) -- Demon Killer 6 -- Resist Sleep +5 -- HP recovered when healing +6 -- MP recovered when healing +3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5765); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 35); target:addMod(MOD_STR, 7); target:addMod(MOD_AGI, 3); target:addMod(MOD_FOOD_ATTP, 25); target:addMod(MOD_FOOD_ATT_CAP, 150); target:addMod(MOD_FOOD_RATTP, 25); target:addMod(MOD_FOOD_RATT_CAP, 150); target:addMod(MOD_DEMON_KILLER, 6); target:addMod(MOD_SLEEPRES, 5); target:addMod(MOD_HPHEAL, 6); target:addMod(MOD_MPHEAL, 3); end; function onEffectLose(target, effect) target:delMod(MOD_HP, 35); target:delMod(MOD_STR, 7); target:delMod(MOD_AGI, 3); target:delMod(MOD_FOOD_ATTP, 25); target:delMod(MOD_FOOD_ATT_CAP, 150); target:delMod(MOD_FOOD_RATTP, 25); target:delMod(MOD_FOOD_RATT_CAP, 150); target:delMod(MOD_DEMON_KILLER, 6); target:delMod(MOD_SLEEPRES, 5); target:delMod(MOD_HPHEAL, 6); target:delMod(MOD_MPHEAL, 3); end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Dynamis-Tavnazia/Zone.lua
5
2047
----------------------------------- -- -- Zone: Dynamis-Tavnazia -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Dynamis-Tavnazia/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Dynamis-Tavnazia/TextIDs"); ----------------------------------- function onInitialize(zone) end; function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; function onZoneIn(player,prevZone) local cs = 0; local inst = 0; if player:isBcnmsFull() == 1 then -- run currently in progress -- add player to the run if they entered via markings, or if they reconnected to a run they were previously in -- gms will be automatically registered if player:getVar("enteringDynamis") == 1 or player:getVar("DynamisID") == GetServerVariable("[DynaTavnazia]UniqueID") or player:getGMLevel() > 0 then inst = player:addPlayerToDynamis(1289); end else -- no run yet in progress -- register run by player if they entered via markings -- gms will be automatically registered if player:getVar("enteringDynamis") == 1 or player:getGMLevel() > 0 then inst = player:bcnmRegister(1289); end end if inst == 1 then player:bcnmEnter(1289); cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(0.1,-7,-21,190); end end player:setVar("enteringDynamis",0); return cs; end; function onRegionEnter(player,region) end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0) then player:setPos(0.0,-7,-23,195,26); end end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Uleguerand_Range/npcs/Fissure.lua
5
1461
----------------------------------- -- Area: Uleguerand Range -- NPC: Fissure -- Teleports players from underground to surface -- !pos 380.267 34.859 -179.655 5 -- !pos 460.339 -29.137 220.311 5 -- !pos 180.207 -77.147 500.276 5 ----------------------------------- package.loaded["scripts/zones/Uleguerand_Range/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Uleguerand_Range/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local z = player:getZPos(); if (player:hasKeyItem(MYSTIC_ICE) == true) then if (z > -200 and z < -150) then -- southern Fissure (J-9) player:startEvent(2,MYSTIC_ICE); elseif (z > 200 and z < 250) then -- middle Fissure (K-7) player:startEvent(3,MYSTIC_ICE); elseif (z > 450) then -- northern Fissure (I-6) player:startEvent(4,MYSTIC_ICE); end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if ((csid == 2 or csid == 3 or csid == 4) and option == 2) then player:delKeyItem(MYSTIC_ICE); end end;
gpl-3.0
Atebite/NutScript
plugins/vendor/entities/entities/nut_vendor.lua
1
7094
ENT.Type = "anim" ENT.PrintName = "Vendor" ENT.Category = "NutScript" ENT.Spawnable = true ENT.AdminOnly = true function ENT:Initialize() if (SERVER) then self:SetModel("models/mossman.mdl") self:SetUseType(SIMPLE_USE) self:SetMoveType(MOVETYPE_NONE) self:DrawShadow(true) self:SetSolid(SOLID_BBOX) self:PhysicsInit(SOLID_BBOX) self.items = {} self.messages = {} self.factions = {} self.classes = {} self:setNetVar("name", "John Doe") self:setNetVar("desc", "") self.receivers = {} local physObj = self:GetPhysicsObject() if (IsValid(physObj)) then physObj:EnableMotion(false) physObj:Sleep() end end timer.Simple(1, function() if (IsValid(self)) then self:setAnim() end end) end function ENT:canAccess(client) if (client:IsAdmin()) then return true end local allowed = false local uniqueID = nut.faction.indices[client:Team()].uniqueID if (self.factions and table.Count(self.factions) > 0) then if (self.factions[uniqueID]) then allowed = true else return false end end if (allowed and self.classes and table.Count(self.classes) > 0) then local class = nut.class.list[client:getChar():getClass()] local uniqueID = class and class.uniqueID if (!self.classes[uniqueID]) then return false end end return true end function ENT:getStock(uniqueID) if (self.items[uniqueID] and self.items[uniqueID][VENDOR_MAXSTOCK]) then return self.items[uniqueID][VENDOR_STOCK] or 0, self.items[uniqueID][VENDOR_MAXSTOCK] end end function ENT:getPrice(uniqueID, selling) local price = nut.item.list[uniqueID] and self.items[uniqueID] and self.items[uniqueID][VENDOR_PRICE] or nut.item.list[uniqueID].price or 0 if (selling) then price = math.floor(price * (self.scale or 0.5)) end return price end function ENT:canSellToPlayer(client, uniqueID) local data = self.items[uniqueID] if (!data or !client:getChar() or !nut.item.list[uniqueID]) then return false end if (data[VENDOR_MODE] == VENDOR_BUYONLY) then return false end if (!client:getChar():hasMoney(self:getPrice(uniqueID))) then return false end if (data[VENDOR_STOCK] and data[VENDOR_STOCK] < 1) then return false end return true end function ENT:canBuyFromPlayer(client, uniqueID) local data = self.items[uniqueID] if (!data or !client:getChar() or !nut.item.list[uniqueID]) then return false end if (data[VENDOR_MODE] != VENDOR_SELLONLY) then return false end if (!self:hasMoney(data[VENDOR_PRICE] or nut.item.list[uniqueID].price or 0)) then return false end return true end function ENT:hasMoney(amount) -- Vendor not using money system so they can always afford it. if (!self.money) then return true end return self.money >= amount end function ENT:setAnim() for k, v in ipairs(self:GetSequenceList()) do if (v:lower():find("idle") and v != "idlenoise") then return self:ResetSequence(k) end end self:ResetSequence(4) end if (SERVER) then local PLUGIN = PLUGIN function ENT:SpawnFunction(client, trace) local angles = (trace.HitPos - client:GetPos()):Angle() angles.r = 0 angles.p = 0 angles.y = angles.y + 180 local entity = ents.Create("nut_vendor") entity:SetPos(trace.HitPos) entity:SetAngles(angles) entity:Spawn() PLUGIN:saveVendors() return entity end function ENT:Use(activator) if (!self:canAccess(activator) or hook.Run("CanPlayerUseVendor", activator) == false) then if (self.messages[VENDOR_NOTRADE]) then activator:ChatPrint(self:getNetVar("name")..": "..self.messages[VENDOR_NOTRADE]) end return end self.receivers[#self.receivers + 1] = activator if (self.messages[VENDOR_WELCOME]) then activator:ChatPrint(self:getNetVar("name")..": "..self.messages[VENDOR_WELCOME]) end local items = {} -- Only send what is needed. for k, v in pairs(self.items) do if (table.Count(v) > 0 and (activator:IsAdmin() or v[VENDOR_MODE])) then items[k] = v end end local data = {} data[1] = items data[2] = self.money data[3] = self.scale if (activator:IsAdmin()) then data[4] = self.messages data[5] = self.factions data[6] = self.classes end activator.nutVendor = self netstream.Start(activator, "vendorOpen", self:EntIndex(), unpack(data)) end function ENT:setMoney(value) self.money = value netstream.Start(self.receivers, "vendorMoney", value) end function ENT:giveMoney(value) if (self.money) then self:setMoney(self:getMoney() + value) end end function ENT:takeMoney(value) if (self.money) then self:giveMoney(-value) end end function ENT:setStock(uniqueID, value) if (!self.items[uniqueID][VENDOR_MAXSTOCK]) then return end self.items[uniqueID] = self.items[uniqueID] or {} self.items[uniqueID][VENDOR_STOCK] = math.min(value, self.items[uniqueID][VENDOR_MAXSTOCK]) netstream.Start(self.receivers, "vendorStock", uniqueID, value) end function ENT:addStock(uniqueID, value) if (!self.items[uniqueID][VENDOR_MAXSTOCK]) then return end self:setStock(uniqueID, self:getStock(uniqueID) + (value or 1)) end function ENT:takeStock(uniqueID, value) if (!self.items[uniqueID][VENDOR_MAXSTOCK]) then return end self:addStock(uniqueID, -(value or 1)) end function ENT:OnRemove() if (!nut.shuttingDown and !self.nutIsSafe) then PLUGIN:saveVendors() end end else function ENT:createBubble() self.bubble = ClientsideModel("models/extras/info_speech.mdl", RENDERGROUP_OPAQUE) self.bubble:SetPos(self:GetPos() + Vector(0, 0, 84)) self.bubble:SetModelScale(0.6, 0) end function ENT:Draw() local bubble = self.bubble if (IsValid(bubble)) then local realTime = RealTime() bubble:SetRenderOrigin(self:GetPos() + Vector(0, 0, 84 + math.sin(realTime * 3) * 0.05)) bubble:SetRenderAngles(Angle(0, realTime * 100, 0)) end self:DrawModel() end function ENT:Think() local noBubble = self:getNetVar("noBubble") if (IsValid(self.bubble) and noBubble) then self.bubble:Remove() elseif (!IsValid(self.bubble) and !noBubble) then self:createBubble() end if ((self.nextAnimCheck or 0) < CurTime()) then self:setAnim() self.nextAnimCheck = CurTime() + 60 end self:SetNextClientThink(CurTime() + 0.25) return true end function ENT:OnRemove() if (IsValid(self.bubble)) then self.bubble:Remove() end end local TEXT_OFFSET = Vector(0, 0, 20) local toScreen = FindMetaTable("Vector").ToScreen local colorAlpha = ColorAlpha local drawText = nut.util.drawText local configGet = nut.config.get ENT.DrawEntityInfo = true function ENT:onDrawEntityInfo(alpha) local position = toScreen(self.LocalToWorld(self, self.OBBCenter(self)) + TEXT_OFFSET) local x, y = position.x, position.y local desc = self.getNetVar(self, "desc") drawText(self.getNetVar(self, "name", "John Doe"), x, y, colorAlpha(configGet("color"), alpha), 1, 1, nil, alpha * 0.65) if (desc) then drawText(desc, x, y + 16, colorAlpha(color_white, alpha), 1, 1, "nutSmallFont", alpha * 0.65) end end end function ENT:getMoney() return self.money end
mit
bnetcc/darkstar
scripts/globals/mobskills/fanatic_dance.lua
5
1066
--------------------------------------------- -- Fanatic Dance -- Family: Orc -- Description: Charms all targets in an area of effect. -- Type: Enfeebling -- Utsusemi/Blink absorb: N/A -- Range: AoE around user -- Notes: Dynamis NM Orcs only --------------------------------------------- require("scripts/globals/monstertpmoves"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/msg"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:isInDynamis() and mob:isMobType(MOBTYPE_NOTORIOUS)) then return 0; end return 1; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_CHARM_I; local power = 0; if (not target:isPC()) then skill:setMsg(msgBasic.SKILL_MISS); return typeEffect; end; local msg = MobStatusEffectMove(mob, target, typeEffect, power, 3, 60) if (msg == msgBasic.SKILL_ENFEEB_IS) then mob:charm(target); end skill:setMsg(msg); return typeEffect; end
gpl-3.0
bnetcc/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Sulbahn.lua
3
1661
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Sulbahn -- Type: Alchemy Adv. Image Support -- !pos -10.470 -6.25 -141.700 241 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) local guildMember = isGuildMember(player,1); if (guildMember == 1) then if (trade:hasItemQty(2184,1) and trade:getItemCount() == 1) then if (player:hasStatusEffect(EFFECT_ALCHEMY_IMAGERY) == false) then player:tradeComplete(); player:startEvent(637,17160,1,19405,21215,30030,0,7,0); else npc:showText(npc, IMAGE_SUPPORT_ACTIVE); end end end end; function onTrigger(player,npc) local guildMember = isGuildMember(player,1); local SkillLevel = player:getSkillLevel(SKILL_ALCHEMY); if (guildMember == 1) then player:startEvent(636,2,SkillLevel,0,511,0,0,7,2184); else player:startEvent(636,0,0,0,0,0,0,7,0); -- Standard Dialogue end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 637) then player:messageSpecial(IMAGE_SUPPORT,0,7,0); player:addStatusEffect(EFFECT_ALCHEMY_IMAGERY,3,0,480); end end;
gpl-3.0
casperkaae/nn
TemporalSubSampling.lua
44
1378
local TemporalSubSampling, parent = torch.class('nn.TemporalSubSampling', 'nn.Module') function TemporalSubSampling:__init(inputFrameSize, kW, dW) parent.__init(self) dW = dW or 1 self.inputFrameSize = inputFrameSize self.kW = kW self.dW = dW self.weight = torch.Tensor(inputFrameSize) self.bias = torch.Tensor(inputFrameSize) self.gradWeight = torch.Tensor(inputFrameSize) self.gradBias = torch.Tensor(inputFrameSize) self:reset() end function TemporalSubSampling:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end function TemporalSubSampling:updateOutput(input) return input.nn.TemporalSubSampling_updateOutput(self, input) end function TemporalSubSampling:updateGradInput(input, gradOutput) if self.gradInput then return input.nn.TemporalSubSampling_updateGradInput(self, input, gradOutput) end end function TemporalSubSampling:accGradParameters(input, gradOutput, scale) return input.nn.TemporalSubSampling_accGradParameters(self, input, gradOutput, scale) end
bsd-3-clause
yswifi/APlan
build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/libs/core/luasrc/model/network.lua
47
33988
--[[ LuCI - Network model Copyright 2009-2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local type, next, pairs, ipairs, loadfile, table = type, next, pairs, ipairs, loadfile, table local tonumber, tostring, math = tonumber, tostring, math local require = require local bus = require "ubus" local nxo = require "nixio" local nfs = require "nixio.fs" local ipc = require "luci.ip" local sys = require "luci.sys" local utl = require "luci.util" local dsp = require "luci.dispatcher" local uci = require "luci.model.uci" local lng = require "luci.i18n" module "luci.model.network" IFACE_PATTERNS_VIRTUAL = { } IFACE_PATTERNS_IGNORE = { "^wmaster%d", "^wifi%d", "^hwsim%d", "^imq%d", "^ifb%d", "^mon%.wlan%d", "^sit%d", "^gre%d", "^lo$" } IFACE_PATTERNS_WIRELESS = { "^wlan%d", "^wl%d", "^ath%d", "^%w+%.network%d" } protocol = utl.class() local _protocols = { } local _interfaces, _bridge, _switch, _tunnel local _ubus, _ubusnetcache, _ubusdevcache, _ubuswificache local _uci_real, _uci_state function _filter(c, s, o, r) local val = _uci_real:get(c, s, o) if val then local l = { } if type(val) == "string" then for val in val:gmatch("%S+") do if val ~= r then l[#l+1] = val end end if #l > 0 then _uci_real:set(c, s, o, table.concat(l, " ")) else _uci_real:delete(c, s, o) end elseif type(val) == "table" then for _, val in ipairs(val) do if val ~= r then l[#l+1] = val end end if #l > 0 then _uci_real:set(c, s, o, l) else _uci_real:delete(c, s, o) end end end end function _append(c, s, o, a) local val = _uci_real:get(c, s, o) or "" if type(val) == "string" then local l = { } for val in val:gmatch("%S+") do if val ~= a then l[#l+1] = val end end l[#l+1] = a _uci_real:set(c, s, o, table.concat(l, " ")) elseif type(val) == "table" then local l = { } for _, val in ipairs(val) do if val ~= a then l[#l+1] = val end end l[#l+1] = a _uci_real:set(c, s, o, l) end end function _stror(s1, s2) if not s1 or #s1 == 0 then return s2 and #s2 > 0 and s2 else return s1 end end function _get(c, s, o) return _uci_real:get(c, s, o) end function _set(c, s, o, v) if v ~= nil then if type(v) == "boolean" then v = v and "1" or "0" end return _uci_real:set(c, s, o, v) else return _uci_real:delete(c, s, o) end end function _wifi_iface(x) local _, p for _, p in ipairs(IFACE_PATTERNS_WIRELESS) do if x:match(p) then return true end end return false end function _wifi_state(key, val, field) if not next(_ubuswificache) then _ubuswificache = _ubus:call("network.wireless", "status", {}) or {} end local radio, radiostate for radio, radiostate in pairs(_ubuswificache) do local ifc, ifcstate for ifc, ifcstate in pairs(radiostate.interfaces) do if ifcstate[key] == val then return ifcstate[field] end end end end function _wifi_lookup(ifn) -- got a radio#.network# pseudo iface, locate the corresponding section local radio, ifnidx = ifn:match("^(%w+)%.network(%d+)$") if radio and ifnidx then local sid = nil local num = 0 ifnidx = tonumber(ifnidx) _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device == radio then num = num + 1 if num == ifnidx then sid = s['.name'] return false end end end) return sid -- looks like wifi, try to locate the section via state vars elseif _wifi_iface(ifn) then local sid = _wifi_state("ifname", ifn, "section") if not sid then _uci_state:foreach("wireless", "wifi-iface", function(s) if s.ifname == ifn then sid = s['.name'] return false end end) end return sid end end function _iface_virtual(x) local _, p for _, p in ipairs(IFACE_PATTERNS_VIRTUAL) do if x:match(p) then return true end end return false end function _iface_ignore(x) local _, p for _, p in ipairs(IFACE_PATTERNS_IGNORE) do if x:match(p) then return true end end return _iface_virtual(x) end function init(cursor) _uci_real = cursor or _uci_real or uci.cursor() _uci_state = _uci_real:substate() _interfaces = { } _bridge = { } _switch = { } _tunnel = { } _ubus = bus.connect() _ubusnetcache = { } _ubusdevcache = { } _ubuswificache = { } -- read interface information local n, i for n, i in ipairs(nxo.getifaddrs()) do local name = i.name:match("[^:]+") local prnt = name:match("^([^%.]+)%.") if _iface_virtual(name) then _tunnel[name] = true end if _tunnel[name] or not _iface_ignore(name) then _interfaces[name] = _interfaces[name] or { idx = i.ifindex or n, name = name, rawname = i.name, flags = { }, ipaddrs = { }, ip6addrs = { } } if prnt then _switch[name] = true _switch[prnt] = true end if i.family == "packet" then _interfaces[name].flags = i.flags _interfaces[name].stats = i.data _interfaces[name].macaddr = i.addr elseif i.family == "inet" then _interfaces[name].ipaddrs[#_interfaces[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask) elseif i.family == "inet6" then _interfaces[name].ip6addrs[#_interfaces[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask) end end end -- read bridge informaton local b, l for l in utl.execi("brctl show") do if not l:match("STP") then local r = utl.split(l, "%s+", nil, true) if #r == 4 then b = { name = r[1], id = r[2], stp = r[3] == "yes", ifnames = { _interfaces[r[4]] } } if b.ifnames[1] then b.ifnames[1].bridge = b end _bridge[r[1]] = b elseif b then b.ifnames[#b.ifnames+1] = _interfaces[r[2]] b.ifnames[#b.ifnames].bridge = b end end end return _M end function save(self, ...) _uci_real:save(...) _uci_real:load(...) end function commit(self, ...) _uci_real:commit(...) _uci_real:load(...) end function ifnameof(self, x) if utl.instanceof(x, interface) then return x:name() elseif utl.instanceof(x, protocol) then return x:ifname() elseif type(x) == "string" then return x:match("^[^:]+") end end function get_protocol(self, protoname, netname) local v = _protocols[protoname] if v then return v(netname or "__dummy__") end end function get_protocols(self) local p = { } local _, v for _, v in ipairs(_protocols) do p[#p+1] = v("__dummy__") end return p end function register_protocol(self, protoname) local proto = utl.class(protocol) function proto.__init__(self, name) self.sid = name end function proto.proto(self) return protoname end _protocols[#_protocols+1] = proto _protocols[protoname] = proto return proto end function register_pattern_virtual(self, pat) IFACE_PATTERNS_VIRTUAL[#IFACE_PATTERNS_VIRTUAL+1] = pat end function has_ipv6(self) return nfs.access("/proc/net/ipv6_route") end function add_network(self, n, options) local oldnet = self:get_network(n) if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not oldnet then if _uci_real:section("network", "interface", n, options) then return network(n) end elseif oldnet and oldnet:is_empty() then if options then local k, v for k, v in pairs(options) do oldnet:set(k, v) end end return oldnet end end function get_network(self, n) if n and _uci_real:get("network", n) == "interface" then return network(n) end end function get_networks(self) local nets = { } local nls = { } _uci_real:foreach("network", "interface", function(s) nls[s['.name']] = network(s['.name']) end) local n for n in utl.kspairs(nls) do nets[#nets+1] = nls[n] end return nets end function del_network(self, n) local r = _uci_real:delete("network", n) if r then _uci_real:delete_all("network", "alias", function(s) return (s.interface == n) end) _uci_real:delete_all("network", "route", function(s) return (s.interface == n) end) _uci_real:delete_all("network", "route6", function(s) return (s.interface == n) end) _uci_real:foreach("wireless", "wifi-iface", function(s) local net local rest = { } for net in utl.imatch(s.network) do if net ~= n then rest[#rest+1] = net end end if #rest > 0 then _uci_real:set("wireless", s['.name'], "network", table.concat(rest, " ")) else _uci_real:delete("wireless", s['.name'], "network") end end) end return r end function rename_network(self, old, new) local r if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then r = _uci_real:section("network", "interface", new, _uci_real:get_all("network", old)) if r then _uci_real:foreach("network", "alias", function(s) if s.interface == old then _uci_real:set("network", s['.name'], "interface", new) end end) _uci_real:foreach("network", "route", function(s) if s.interface == old then _uci_real:set("network", s['.name'], "interface", new) end end) _uci_real:foreach("network", "route6", function(s) if s.interface == old then _uci_real:set("network", s['.name'], "interface", new) end end) _uci_real:foreach("wireless", "wifi-iface", function(s) local net local list = { } for net in utl.imatch(s.network) do if net == old then list[#list+1] = new else list[#list+1] = net end end if #list > 0 then _uci_real:set("wireless", s['.name'], "network", table.concat(list, " ")) end end) _uci_real:delete("network", old) end end return r or false end function get_interface(self, i) if _interfaces[i] or _wifi_iface(i) then return interface(i) else local ifc local num = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 if s['.name'] == i then ifc = interface( "%s.network%d" %{s.device, num[s.device] }) return false end end end) return ifc end end function get_interfaces(self) local iface local ifaces = { } local seen = { } local nfs = { } local baseof = { } -- find normal interfaces _uci_real:foreach("network", "interface", function(s) for iface in utl.imatch(s.ifname) do if not _iface_ignore(iface) and not _wifi_iface(iface) then seen[iface] = true nfs[iface] = interface(iface) end end end) for iface in utl.kspairs(_interfaces) do if not (seen[iface] or _iface_ignore(iface) or _wifi_iface(iface)) then nfs[iface] = interface(iface) end end -- find vlan interfaces _uci_real:foreach("network", "switch_vlan", function(s) if not s.device then return end local base = baseof[s.device] if not base then if not s.device:match("^eth%d") then local l for l in utl.execi("swconfig dev %q help 2>/dev/null" % s.device) do if not base then base = l:match("^%w+: (%w+)") end end if not base or not base:match("^eth%d") then base = "eth0" end else base = s.device end baseof[s.device] = base end local vid = tonumber(s.vid or s.vlan) if vid ~= nil and vid >= 0 and vid <= 4095 then local iface = "%s.%d" %{ base, vid } if not seen[iface] then seen[iface] = true nfs[iface] = interface(iface) end end end) for iface in utl.kspairs(nfs) do ifaces[#ifaces+1] = nfs[iface] end -- find wifi interfaces local num = { } local wfs = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local i = "%s.network%d" %{ s.device, num[s.device] } wfs[i] = interface(i) end end) for iface in utl.kspairs(wfs) do ifaces[#ifaces+1] = wfs[iface] end return ifaces end function ignore_interface(self, x) return _iface_ignore(x) end function get_wifidev(self, dev) if _uci_real:get("wireless", dev) == "wifi-device" then return wifidev(dev) end end function get_wifidevs(self) local devs = { } local wfd = { } _uci_real:foreach("wireless", "wifi-device", function(s) wfd[#wfd+1] = s['.name'] end) local dev for _, dev in utl.vspairs(wfd) do devs[#devs+1] = wifidev(dev) end return devs end function get_wifinet(self, net) local wnet = _wifi_lookup(net) if wnet then return wifinet(wnet) end end function add_wifinet(self, net, options) if type(options) == "table" and options.device and _uci_real:get("wireless", options.device) == "wifi-device" then local wnet = _uci_real:section("wireless", "wifi-iface", nil, options) return wifinet(wnet) end end function del_wifinet(self, net) local wnet = _wifi_lookup(net) if wnet then _uci_real:delete("wireless", wnet) return true end return false end function get_status_by_route(self, addr, mask) local _, object for _, object in ipairs(_ubus:objects()) do local net = object:match("^network%.interface%.(.+)") if net then local s = _ubus:call(object, "status", {}) if s and s.route then local rt for _, rt in ipairs(s.route) do if not rt.table and rt.target == addr and rt.mask == mask then return net, s end end end end end end function get_status_by_address(self, addr) local _, object for _, object in ipairs(_ubus:objects()) do local net = object:match("^network%.interface%.(.+)") if net then local s = _ubus:call(object, "status", {}) if s and s['ipv4-address'] then local a for _, a in ipairs(s['ipv4-address']) do if a.address == addr then return net, s end end end if s and s['ipv6-address'] then local a for _, a in ipairs(s['ipv6-address']) do if a.address == addr then return net, s end end end end end end function get_wannet(self) local net = self:get_status_by_route("0.0.0.0", 0) return net and network(net) end function get_wandev(self) local _, stat = self:get_status_by_route("0.0.0.0", 0) return stat and interface(stat.l3_device or stat.device) end function get_wan6net(self) local net = self:get_status_by_route("::", 0) return net and network(net) end function get_wan6dev(self) local _, stat = self:get_status_by_route("::", 0) return stat and interface(stat.l3_device or stat.device) end function network(name, proto) if name then local p = proto or _uci_real:get("network", name, "proto") local c = p and _protocols[p] or protocol return c(name) end end function protocol.__init__(self, name) self.sid = name end function protocol._get(self, opt) local v = _uci_real:get("network", self.sid, opt) if type(v) == "table" then return table.concat(v, " ") end return v or "" end function protocol._ubus(self, field) if not _ubusnetcache[self.sid] then _ubusnetcache[self.sid] = _ubus:call("network.interface.%s" % self.sid, "status", { }) end if _ubusnetcache[self.sid] and field then return _ubusnetcache[self.sid][field] end return _ubusnetcache[self.sid] end function protocol.get(self, opt) return _get("network", self.sid, opt) end function protocol.set(self, opt, val) return _set("network", self.sid, opt, val) end function protocol.ifname(self) local ifname if self:is_floating() then ifname = self:_ubus("l3_device") else ifname = self:_ubus("device") end if not ifname then local num = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local net for net in utl.imatch(s.network) do if net == self.sid then ifname = "%s.network%d" %{ s.device, num[s.device] } return false end end end end) end return ifname end function protocol.proto(self) return "none" end function protocol.get_i18n(self) local p = self:proto() if p == "none" then return lng.translate("Unmanaged") elseif p == "static" then return lng.translate("Static address") elseif p == "dhcp" then return lng.translate("DHCP client") else return lng.translate("Unknown") end end function protocol.type(self) return self:_get("type") end function protocol.name(self) return self.sid end function protocol.uptime(self) return self:_ubus("uptime") or 0 end function protocol.expires(self) local a = tonumber(_uci_state:get("network", self.sid, "lease_acquired")) local l = tonumber(_uci_state:get("network", self.sid, "lease_lifetime")) if a and l then l = l - (nxo.sysinfo().uptime - a) return l > 0 and l or 0 end return -1 end function protocol.metric(self) return tonumber(_uci_state:get("network", self.sid, "metric")) or 0 end function protocol.ipaddr(self) local addrs = self:_ubus("ipv4-address") return addrs and #addrs > 0 and addrs[1].address end function protocol.netmask(self) local addrs = self:_ubus("ipv4-address") return addrs and #addrs > 0 and ipc.IPv4("0.0.0.0/%d" % addrs[1].mask):mask():string() end function protocol.gwaddr(self) local _, route for _, route in ipairs(self:_ubus("route") or { }) do if route.target == "0.0.0.0" and route.mask == 0 then return route.nexthop end end end function protocol.dnsaddrs(self) local dns = { } local _, addr for _, addr in ipairs(self:_ubus("dns-server") or { }) do if not addr:match(":") then dns[#dns+1] = addr end end return dns end function protocol.ip6addr(self) local addrs = self:_ubus("ipv6-address") if addrs and #addrs > 0 then return "%s/%d" %{ addrs[1].address, addrs[1].mask } else addrs = self:_ubus("ipv6-prefix-assignment") if addrs and #addrs > 0 then return "%s/%d" %{ addrs[1].address, addrs[1].mask } end end end function protocol.gw6addr(self) local _, route for _, route in ipairs(self:_ubus("route") or { }) do if route.target == "::" and route.mask == 0 then return ipc.IPv6(route.nexthop):string() end end end function protocol.dns6addrs(self) local dns = { } local _, addr for _, addr in ipairs(self:_ubus("dns-server") or { }) do if addr:match(":") then dns[#dns+1] = addr end end return dns end function protocol.is_bridge(self) return (not self:is_virtual() and self:type() == "bridge") end function protocol.opkg_package(self) return nil end function protocol.is_installed(self) return true end function protocol.is_virtual(self) return false end function protocol.is_floating(self) return false end function protocol.is_empty(self) if self:is_floating() then return false else local rv = true if (self:_get("ifname") or ""):match("%S+") then rv = false end _uci_real:foreach("wireless", "wifi-iface", function(s) local n for n in utl.imatch(s.network) do if n == self.sid then rv = false return false end end end) return rv end end function protocol.add_interface(self, ifname) ifname = _M:ifnameof(ifname) if ifname and not self:is_floating() then -- if its a wifi interface, change its network option local wif = _wifi_lookup(ifname) if wif then _append("wireless", wif, "network", self.sid) -- add iface to our iface list else _append("network", self.sid, "ifname", ifname) end end end function protocol.del_interface(self, ifname) ifname = _M:ifnameof(ifname) if ifname and not self:is_floating() then -- if its a wireless interface, clear its network option local wif = _wifi_lookup(ifname) if wif then _filter("wireless", wif, "network", self.sid) end -- remove the interface _filter("network", self.sid, "ifname", ifname) end end function protocol.get_interface(self) if self:is_virtual() then _tunnel[self:proto() .. "-" .. self.sid] = true return interface(self:proto() .. "-" .. self.sid, self) elseif self:is_bridge() then _bridge["br-" .. self.sid] = true return interface("br-" .. self.sid, self) else local ifn = nil local num = { } for ifn in utl.imatch(_uci_real:get("network", self.sid, "ifname")) do ifn = ifn:match("^[^:/]+") return ifn and interface(ifn, self) end ifn = nil _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local net for net in utl.imatch(s.network) do if net == self.sid then ifn = "%s.network%d" %{ s.device, num[s.device] } return false end end end end) return ifn and interface(ifn, self) end end function protocol.get_interfaces(self) if self:is_bridge() or (self:is_virtual() and not self:is_floating()) then local ifaces = { } local ifn local nfs = { } for ifn in utl.imatch(self:get("ifname")) do ifn = ifn:match("^[^:/]+") nfs[ifn] = interface(ifn, self) end for ifn in utl.kspairs(nfs) do ifaces[#ifaces+1] = nfs[ifn] end local num = { } local wfs = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local net for net in utl.imatch(s.network) do if net == self.sid then ifn = "%s.network%d" %{ s.device, num[s.device] } wfs[ifn] = interface(ifn, self) end end end end) for ifn in utl.kspairs(wfs) do ifaces[#ifaces+1] = wfs[ifn] end return ifaces end end function protocol.contains_interface(self, ifname) ifname = _M:ifnameof(ifname) if not ifname then return false elseif self:is_virtual() and self:proto() .. "-" .. self.sid == ifname then return true elseif self:is_bridge() and "br-" .. self.sid == ifname then return true else local ifn for ifn in utl.imatch(self:get("ifname")) do ifn = ifn:match("[^:]+") if ifn == ifname then return true end end local wif = _wifi_lookup(ifname) if wif then local n for n in utl.imatch(_uci_real:get("wireless", wif, "network")) do if n == self.sid then return true end end end end return false end function protocol.adminlink(self) return dsp.build_url("admin", "network", "network", self.sid) end interface = utl.class() function interface.__init__(self, ifname, network) local wif = _wifi_lookup(ifname) if wif then self.wif = wifinet(wif) self.ifname = _wifi_state("section", wif, "ifname") end self.ifname = self.ifname or ifname self.dev = _interfaces[self.ifname] self.network = network end function interface._ubus(self, field) if not _ubusdevcache[self.ifname] then _ubusdevcache[self.ifname] = _ubus:call("network.device", "status", { name = self.ifname }) end if _ubusdevcache[self.ifname] and field then return _ubusdevcache[self.ifname][field] end return _ubusdevcache[self.ifname] end function interface.name(self) return self.wif and self.wif:ifname() or self.ifname end function interface.mac(self) return (self:_ubus("macaddr") or "00:00:00:00:00:00"):upper() end function interface.ipaddrs(self) return self.dev and self.dev.ipaddrs or { } end function interface.ip6addrs(self) return self.dev and self.dev.ip6addrs or { } end function interface.type(self) if self.wif or _wifi_iface(self.ifname) then return "wifi" elseif _bridge[self.ifname] then return "bridge" elseif _tunnel[self.ifname] then return "tunnel" elseif self.ifname:match("%.") then return "vlan" elseif _switch[self.ifname] then return "switch" else return "ethernet" end end function interface.shortname(self) if self.wif then return "%s %q" %{ self.wif:active_mode(), self.wif:active_ssid() or self.wif:active_bssid() } else return self.ifname end end function interface.get_i18n(self) if self.wif then return "%s: %s %q" %{ lng.translate("Wireless Network"), self.wif:active_mode(), self.wif:active_ssid() or self.wif:active_bssid() } else return "%s: %q" %{ self:get_type_i18n(), self:name() } end end function interface.get_type_i18n(self) local x = self:type() if x == "wifi" then return lng.translate("Wireless Adapter") elseif x == "bridge" then return lng.translate("Bridge") elseif x == "switch" then return lng.translate("Ethernet Switch") elseif x == "vlan" then return lng.translate("VLAN Interface") elseif x == "tunnel" then return lng.translate("Tunnel Interface") else return lng.translate("Ethernet Adapter") end end function interface.adminlink(self) if self.wif then return self.wif:adminlink() end end function interface.ports(self) local members = self:_ubus("bridge-members") if members then local _, iface local ifaces = { } for _, iface in ipairs(members) do ifaces[#ifaces+1] = interface(iface) end end end function interface.bridge_id(self) if self.br then return self.br.id else return nil end end function interface.bridge_stp(self) if self.br then return self.br.stp else return false end end function interface.is_up(self) return self:_ubus("up") or false end function interface.is_bridge(self) return (self:type() == "bridge") end function interface.is_bridgeport(self) return self.dev and self.dev.bridge and true or false end function interface.tx_bytes(self) local stat = self:_ubus("statistics") return stat and stat.tx_bytes or 0 end function interface.rx_bytes(self) local stat = self:_ubus("statistics") return stat and stat.rx_bytes or 0 end function interface.tx_packets(self) local stat = self:_ubus("statistics") return stat and stat.tx_packets or 0 end function interface.rx_packets(self) local stat = self:_ubus("statistics") return stat and stat.rx_packets or 0 end function interface.get_network(self) return self:get_networks()[1] end function interface.get_networks(self) if not self.networks then local nets = { } local _, net for _, net in ipairs(_M:get_networks()) do if net:contains_interface(self.ifname) or net:ifname() == self.ifname then nets[#nets+1] = net end end table.sort(nets, function(a, b) return a.sid < b.sid end) self.networks = nets return nets else return self.networks end end function interface.get_wifinet(self) return self.wif end wifidev = utl.class() function wifidev.__init__(self, dev) self.sid = dev self.iwinfo = dev and sys.wifi.getiwinfo(dev) or { } end function wifidev.get(self, opt) return _get("wireless", self.sid, opt) end function wifidev.set(self, opt, val) return _set("wireless", self.sid, opt, val) end function wifidev.name(self) return self.sid end function wifidev.hwmodes(self) local l = self.iwinfo.hwmodelist if l and next(l) then return l else return { b = true, g = true } end end function wifidev.get_i18n(self) local t = "Generic" if self.iwinfo.type == "wl" then t = "Broadcom" elseif self.iwinfo.type == "madwifi" then t = "Atheros" end local m = "" local l = self:hwmodes() if l.a then m = m .. "a" end if l.b then m = m .. "b" end if l.g then m = m .. "g" end if l.n then m = m .. "n" end return "%s 802.11%s Wireless Controller (%s)" %{ t, m, self:name() } end function wifidev.is_up(self) if _ubuswificache[self.sid] then return (_ubuswificache[self.sid].up == true) end local up = false _uci_state:foreach("wireless", "wifi-iface", function(s) if s.device == self.sid then if s.up == "1" then up = true return false end end end) return up end function wifidev.get_wifinet(self, net) if _uci_real:get("wireless", net) == "wifi-iface" then return wifinet(net) else local wnet = _wifi_lookup(net) if wnet then return wifinet(wnet) end end end function wifidev.get_wifinets(self) local nets = { } _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device == self.sid then nets[#nets+1] = wifinet(s['.name']) end end) return nets end function wifidev.add_wifinet(self, options) options = options or { } options.device = self.sid local wnet = _uci_real:section("wireless", "wifi-iface", nil, options) if wnet then return wifinet(wnet, options) end end function wifidev.del_wifinet(self, net) if utl.instanceof(net, wifinet) then net = net.sid elseif _uci_real:get("wireless", net) ~= "wifi-iface" then net = _wifi_lookup(net) end if net and _uci_real:get("wireless", net, "device") == self.sid then _uci_real:delete("wireless", net) return true end return false end wifinet = utl.class() function wifinet.__init__(self, net, data) self.sid = net local num = { } local netid _uci_real:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 if s['.name'] == self.sid then netid = "%s.network%d" %{ s.device, num[s.device] } return false end end end) local dev = _wifi_state("section", self.sid, "ifname") or netid self.netid = netid self.wdev = dev self.iwinfo = dev and sys.wifi.getiwinfo(dev) or { } self.iwdata = data or _uci_state:get_all("wireless", self.sid) or _uci_real:get_all("wireless", self.sid) or { } end function wifinet.get(self, opt) return _get("wireless", self.sid, opt) end function wifinet.set(self, opt, val) return _set("wireless", self.sid, opt, val) end function wifinet.mode(self) return _uci_state:get("wireless", self.sid, "mode") or "ap" end function wifinet.ssid(self) return _uci_state:get("wireless", self.sid, "ssid") end function wifinet.bssid(self) return _uci_state:get("wireless", self.sid, "bssid") end function wifinet.network(self) return _uci_state:get("wifinet", self.sid, "network") end function wifinet.id(self) return self.netid end function wifinet.name(self) return self.sid end function wifinet.ifname(self) local ifname = self.iwinfo.ifname if not ifname or ifname:match("^wifi%d") or ifname:match("^radio%d") then ifname = self.wdev end return ifname end function wifinet.get_device(self) if self.iwdata.device then return wifidev(self.iwdata.device) end end function wifinet.is_up(self) local ifc = self:get_interface() return (ifc and ifc:is_up() or false) end function wifinet.active_mode(self) local m = _stror(self.iwinfo.mode, self.iwdata.mode) or "ap" if m == "ap" then m = "Master" elseif m == "sta" then m = "Client" elseif m == "adhoc" then m = "Ad-Hoc" elseif m == "mesh" then m = "Mesh" elseif m == "monitor" then m = "Monitor" end return m end function wifinet.active_mode_i18n(self) return lng.translate(self:active_mode()) end function wifinet.active_ssid(self) return _stror(self.iwinfo.ssid, self.iwdata.ssid) end function wifinet.active_bssid(self) return _stror(self.iwinfo.bssid, self.iwdata.bssid) or "00:00:00:00:00:00" end function wifinet.active_encryption(self) local enc = self.iwinfo and self.iwinfo.encryption return enc and enc.description or "-" end function wifinet.assoclist(self) return self.iwinfo.assoclist or { } end function wifinet.frequency(self) local freq = self.iwinfo.frequency if freq and freq > 0 then return "%.03f" % (freq / 1000) end end function wifinet.bitrate(self) local rate = self.iwinfo.bitrate if rate and rate > 0 then return (rate / 1000) end end function wifinet.channel(self) return self.iwinfo.channel or tonumber(_uci_state:get("wireless", self.iwdata.device, "channel")) end function wifinet.signal(self) return self.iwinfo.signal or 0 end function wifinet.noise(self) return self.iwinfo.noise or 0 end function wifinet.country(self) return self.iwinfo.country or "00" end function wifinet.txpower(self) local pwr = (self.iwinfo.txpower or 0) return pwr + self:txpower_offset() end function wifinet.txpower_offset(self) return self.iwinfo.txpower_offset or 0 end function wifinet.signal_level(self, s, n) if self:active_bssid() ~= "00:00:00:00:00:00" then local signal = s or self:signal() local noise = n or self:noise() if signal < 0 and noise < 0 then local snr = -1 * (noise - signal) return math.floor(snr / 5) else return 0 end else return -1 end end function wifinet.signal_percent(self) local qc = self.iwinfo.quality or 0 local qm = self.iwinfo.quality_max or 0 if qc > 0 and qm > 0 then return math.floor((100 / qm) * qc) else return 0 end end function wifinet.shortname(self) return "%s %q" %{ lng.translate(self:active_mode()), self:active_ssid() or self:active_bssid() } end function wifinet.get_i18n(self) return "%s: %s %q (%s)" %{ lng.translate("Wireless Network"), lng.translate(self:active_mode()), self:active_ssid() or self:active_bssid(), self:ifname() } end function wifinet.adminlink(self) return dsp.build_url("admin", "network", "wireless", self.netid) end function wifinet.get_network(self) return self:get_networks()[1] end function wifinet.get_networks(self) local nets = { } local net for net in utl.imatch(tostring(self.iwdata.network)) do if _uci_real:get("network", net) == "interface" then nets[#nets+1] = network(net) end end table.sort(nets, function(a, b) return a.sid < b.sid end) return nets end function wifinet.get_interface(self) return interface(self:ifname()) end -- setup base protocols _M:register_protocol("static") _M:register_protocol("dhcp") _M:register_protocol("none") -- load protocol extensions local exts = nfs.dir(utl.libpath() .. "/model/network") if exts then local ext for ext in exts do if ext:match("%.lua$") then require("luci.model.network." .. ext:gsub("%.lua$", "")) end end end
gpl-2.0
Wiladams/LLUI
src/fun.lua
12
28437
--- --- Lua Fun - a high-performance functional programming library for LuaJIT --- --- Copyright (c) 2013-2014 Roman Tsisyk <roman@tsisyk.com> --- --- Distributed under the MIT/X11 License. See COPYING.md for more details. --- --- https://github.com/rtsisyk/luafun --- local exports = {} local methods = {} -------------------------------------------------------------------------------- -- Tools -------------------------------------------------------------------------------- local return_if_not_empty = function(state_x, ...) if state_x == nil then return nil end return ... end local call_if_not_empty = function(fun, state_x, ...) if state_x == nil then return nil end return state_x, fun(...) end local function deepcopy(orig) -- used by cycle() local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end else copy = orig end return copy end local iterator_mt = { -- usually called by for-in loop __call = function(self, param, state) return self.gen(param, state) end; __tostring = function(self) return '<generator>' end; -- add all exported methods __index = methods; } local wrap = function(gen, param, state) return setmetatable({ gen = gen, param = param, state = state }, iterator_mt), param, state end exports.wrap = wrap local unwrap = function(self) return self.gen, self.param, self.state end methods.unwrap = unwrap -------------------------------------------------------------------------------- -- Basic Functions -------------------------------------------------------------------------------- local nil_gen = function(_param, _state) return nil end local string_gen = function(param, state) local state = state + 1 if state > #param then return nil end local r = string.sub(param, state, state) return state, r end local pairs_gen = pairs({ a = 0 }) -- get the generating function from pairs local map_gen = function(tab, key) local value local key, value = pairs_gen(tab, key) return key, key, value end local rawiter = function(obj, param, state) assert(obj ~= nil, "invalid iterator") if type(obj) == "table" then local mt = getmetatable(obj); if mt ~= nil then if mt == iterator_mt then return obj.gen, obj.param, obj.state elseif mt.__ipairs ~= nil then return mt.__ipairs(obj) elseif mt.__pairs ~= nil then return mt.__pairs(obj) end end if #obj > 0 then -- array return ipairs(obj) else -- hash return map_gen, obj, nil end elseif (type(obj) == "function") then return obj, param, state elseif (type(obj) == "string") then if #obj == 0 then return nil_gen, nil, nil end return string_gen, obj, 0 end error(string.format('object %s of type "%s" is not iterable', obj, type(obj))) end local iter = function(obj, param, state) return wrap(rawiter(obj, param, state)) end exports.iter = iter local method0 = function(fun) return function(self) return fun(self.gen, self.param, self.state) end end local method1 = function(fun) return function(self, arg1) return fun(arg1, self.gen, self.param, self.state) end end local method2 = function(fun) return function(self, arg1, arg2) return fun(arg1, arg2, self.gen, self.param, self.state) end end local export0 = function(fun) return function(gen, param, state) return fun(rawiter(gen, param, state)) end end local export1 = function(fun) return function(arg1, gen, param, state) return fun(arg1, rawiter(gen, param, state)) end end local export2 = function(fun) return function(arg1, arg2, gen, param, state) return fun(arg1, arg2, rawiter(gen, param, state)) end end local each = function(fun, gen, param, state) repeat state = call_if_not_empty(fun, gen(param, state)) until state == nil end methods.each = method1(each) exports.each = export1(each) methods.for_each = methods.each exports.for_each = exports.each methods.foreach = methods.each exports.foreach = exports.each -------------------------------------------------------------------------------- -- Generators -------------------------------------------------------------------------------- local range_gen = function(param, state) local stop, step = param[1], param[2] local state = state + step if state > stop then return nil end return state, state end local range_rev_gen = function(param, state) local stop, step = param[1], param[2] local state = state + step if state < stop then return nil end return state, state end local range = function(start, stop, step) if step == nil then if stop == nil then if start == 0 then return nil_gen, nil, nil end stop = start start = stop > 0 and 1 or -1 end step = start <= stop and 1 or -1 end assert(type(start) == "number", "start must be a number") assert(type(stop) == "number", "stop must be a number") assert(type(step) == "number", "step must be a number") assert(step ~= 0, "step must not be zero") if (step > 0) then return wrap(range_gen, {stop, step}, start - step) elseif (step < 0) then return wrap(range_rev_gen, {stop, step}, start - step) end end exports.range = range local duplicate_table_gen = function(param_x, state_x) return state_x + 1, unpack(param_x) end local duplicate_fun_gen = function(param_x, state_x) return state_x + 1, param_x(state_x) end local duplicate_gen = function(param_x, state_x) return state_x + 1, param_x end local duplicate = function(...) if select('#', ...) <= 1 then return wrap(duplicate_gen, select(1, ...), 0) else return wrap(duplicate_table_gen, {...}, 0) end end exports.duplicate = duplicate exports.replicate = duplicate exports.xrepeat = duplicate local tabulate = function(fun) assert(type(fun) == "function") return wrap(duplicate_fun_gen, fun, 0) end exports.tabulate = tabulate local zeros = function() return wrap(duplicate_gen, 0, 0) end exports.zeros = zeros local ones = function() return wrap(duplicate_gen, 1, 0) end exports.ones = ones local rands_gen = function(param_x, _state_x) return 0, math.random(param_x[1], param_x[2]) end local rands_nil_gen = function(_param_x, _state_x) return 0, math.random() end local rands = function(n, m) if n == nil and m == nil then return wrap(rands_nil_gen, 0, 0) end assert(type(n) == "number", "invalid first arg to rands") if m == nil then m = n n = 0 else assert(type(m) == "number", "invalid second arg to rands") end assert(n < m, "empty interval") return wrap(rands_gen, {n, m - 1}, 0) end exports.rands = rands -------------------------------------------------------------------------------- -- Slicing -------------------------------------------------------------------------------- local nth = function(n, gen_x, param_x, state_x) assert(n > 0, "invalid first argument to nth") -- An optimization for arrays and strings if gen_x == ipairs then return param_x[n] elseif gen_x == string_gen then if n < #param_x then return string.sub(param_x, n, n) else return nil end end for i=1,n-1,1 do state_x = gen_x(param_x, state_x) if state_x == nil then return nil end end return return_if_not_empty(gen_x(param_x, state_x)) end methods.nth = method1(nth) exports.nth = export1(nth) local head_call = function(state, ...) if state == nil then error("head: iterator is empty") end return ... end local head = function(gen, param, state) return head_call(gen(param, state)) end methods.head = method0(head) exports.head = export0(head) exports.car = exports.head methods.car = methods.head local tail = function(gen, param, state) state = gen(param, state) if state == nil then return wrap(nil_gen, nil, nil) end return wrap(gen, param, state) end methods.tail = method0(tail) exports.tail = export0(tail) exports.cdr = exports.tail methods.cdr = methods.tail local take_n_gen_x = function(i, state_x, ...) if state_x == nil then return nil end return {i, state_x}, ... end local take_n_gen = function(param, state) local n, gen_x, param_x = param[1], param[2], param[3] local i, state_x = state[1], state[2] if i >= n then return nil end return take_n_gen_x(i + 1, gen_x(param_x, state_x)) end local take_n = function(n, gen, param, state) assert(n >= 0, "invalid first argument to take_n") return wrap(take_n_gen, {n, gen, param}, {0, state}) end methods.take_n = method1(take_n) exports.take_n = export1(take_n) local take_while_gen_x = function(fun, state_x, ...) if state_x == nil or not fun(...) then return nil end return state_x, ... end local take_while_gen = function(param, state_x) local fun, gen_x, param_x = param[1], param[2], param[3] return take_while_gen_x(fun, gen_x(param_x, state_x)) end local take_while = function(fun, gen, param, state) assert(type(fun) == "function", "invalid first argument to take_while") return wrap(take_while_gen, {fun, gen, param}, state) end methods.take_while = method1(take_while) exports.take_while = export1(take_while) local take = function(n_or_fun, gen, param, state) if type(n_or_fun) == "number" then return take_n(n_or_fun, gen, param, state) else return take_while(n_or_fun, gen, param, state) end end methods.take = method1(take) exports.take = export1(take) local drop_n = function(n, gen, param, state) assert(n >= 0, "invalid first argument to drop_n") local i for i=1,n,1 do state = gen(param, state) if state == nil then return wrap(nil_gen, nil, nil) end end return wrap(gen, param, state) end methods.drop_n = method1(drop_n) exports.drop_n = export1(drop_n) local drop_while_x = function(fun, state_x, ...) if state_x == nil or not fun(...) then return state_x, false end return state_x, true, ... end local drop_while = function(fun, gen_x, param_x, state_x) assert(type(fun) == "function", "invalid first argument to drop_while") local cont, state_x_prev repeat state_x_prev = deepcopy(state_x) state_x, cont = drop_while_x(fun, gen_x(param_x, state_x)) until not cont if state_x == nil then return wrap(nil_gen, nil, nil) end return wrap(gen_x, param_x, state_x_prev) end methods.drop_while = method1(drop_while) exports.drop_while = export1(drop_while) local drop = function(n_or_fun, gen_x, param_x, state_x) if type(n_or_fun) == "number" then return drop_n(n_or_fun, gen_x, param_x, state_x) else return drop_while(n_or_fun, gen_x, param_x, state_x) end end methods.drop = method1(drop) exports.drop = export1(drop) local split = function(n_or_fun, gen_x, param_x, state_x) return take(n_or_fun, gen_x, param_x, state_x), drop(n_or_fun, gen_x, param_x, state_x) end methods.split = method1(split) exports.split = export1(split) methods.split_at = methods.split exports.split_at = exports.split methods.span = methods.split exports.span = exports.split -------------------------------------------------------------------------------- -- Indexing -------------------------------------------------------------------------------- local index = function(x, gen, param, state) local i = 1 for _k, r in gen, param, state do if r == x then return i end i = i + 1 end return nil end methods.index = method1(index) exports.index = export1(index) methods.index_of = methods.index exports.index_of = exports.index methods.elem_index = methods.index exports.elem_index = exports.index local indexes_gen = function(param, state) local x, gen_x, param_x = param[1], param[2], param[3] local i, state_x = state[1], state[2] local r while true do state_x, r = gen_x(param_x, state_x) if state_x == nil then return nil end i = i + 1 if r == x then return {i, state_x}, i end end end local indexes = function(x, gen, param, state) return wrap(indexes_gen, {x, gen, param}, {0, state}) end methods.indexes = method1(indexes) exports.indexes = export1(indexes) methods.elem_indexes = methods.indexes exports.elem_indexes = exports.indexes methods.indices = methods.indexes exports.indices = exports.indexes methods.elem_indices = methods.indexes exports.elem_indices = exports.indexes -------------------------------------------------------------------------------- -- Filtering -------------------------------------------------------------------------------- local filter1_gen = function(fun, gen_x, param_x, state_x, a) while true do if state_x == nil or fun(a) then break; end state_x, a = gen_x(param_x, state_x) end return state_x, a end -- call each other local filterm_gen local filterm_gen_shrink = function(fun, gen_x, param_x, state_x) return filterm_gen(fun, gen_x, param_x, gen_x(param_x, state_x)) end filterm_gen = function(fun, gen_x, param_x, state_x, ...) if state_x == nil then return nil end if fun(...) then return state_x, ... end return filterm_gen_shrink(fun, gen_x, param_x, state_x) end local filter_detect = function(fun, gen_x, param_x, state_x, ...) if select('#', ...) < 2 then return filter1_gen(fun, gen_x, param_x, state_x, ...) else return filterm_gen(fun, gen_x, param_x, state_x, ...) end end local filter_gen = function(param, state_x) local fun, gen_x, param_x = param[1], param[2], param[3] return filter_detect(fun, gen_x, param_x, gen_x(param_x, state_x)) end local filter = function(fun, gen, param, state) return wrap(filter_gen, {fun, gen, param}, state) end methods.filter = method1(filter) exports.filter = export1(filter) methods.remove_if = methods.filter exports.remove_if = exports.filter local grep = function(fun_or_regexp, gen, param, state) local fun = fun_or_regexp if type(fun_or_regexp) == "string" then fun = function(x) return string.find(x, fun_or_regexp) ~= nil end end return filter(fun, gen, param, state) end methods.grep = method1(grep) exports.grep = export1(grep) local partition = function(fun, gen, param, state) local neg_fun = function(...) return not fun(...) end return filter(fun, gen, param, state), filter(neg_fun, gen, param, state) end methods.partition = method1(partition) exports.partition = export1(partition) -------------------------------------------------------------------------------- -- Reducing -------------------------------------------------------------------------------- local foldl_call = function(fun, start, state, ...) if state == nil then return nil, start end return state, fun(start, ...) end local foldl = function(fun, start, gen_x, param_x, state_x) while true do state_x, start = foldl_call(fun, start, gen_x(param_x, state_x)) if state_x == nil then break; end end return start end methods.foldl = method2(foldl) exports.foldl = export2(foldl) methods.reduce = methods.foldl exports.reduce = exports.foldl local length = function(gen, param, state) if gen == ipairs or gen == string_gen then return #param end local len = 0 repeat state = gen(param, state) len = len + 1 until state == nil return len - 1 end methods.length = method0(length) exports.length = export0(length) local is_null = function(gen, param, state) return gen(param, deepcopy(state)) == nil end methods.is_null = method0(is_null) exports.is_null = export0(is_null) local is_prefix_of = function(iter_x, iter_y) local gen_x, param_x, state_x = iter(iter_x) local gen_y, param_y, state_y = iter(iter_y) local r_x, r_y for i=1,10,1 do state_x, r_x = gen_x(param_x, state_x) state_y, r_y = gen_y(param_y, state_y) if state_x == nil then return true end if state_y == nil or r_x ~= r_y then return false end end end methods.is_prefix_of = is_prefix_of exports.is_prefix_of = is_prefix_of local all = function(fun, gen_x, param_x, state_x) local r repeat state_x, r = call_if_not_empty(fun, gen_x(param_x, state_x)) until state_x == nil or not r return state_x == nil end methods.all = method1(all) exports.all = export1(all) methods.every = methods.all exports.every = exports.all local any = function(fun, gen_x, param_x, state_x) local r repeat state_x, r = call_if_not_empty(fun, gen_x(param_x, state_x)) until state_x == nil or r return not not r end methods.any = method1(any) exports.any = export1(any) methods.some = methods.any exports.some = exports.any local sum = function(gen, param, state) local s = 0 local r = 0 repeat s = s + r state, r = gen(param, state) until state == nil return s end methods.sum = method0(sum) exports.sum = export0(sum) local product = function(gen, param, state) local p = 1 local r = 1 repeat p = p * r state, r = gen(param, state) until state == nil return p end methods.product = method0(product) exports.product = export0(product) local min_cmp = function(m, n) if n < m then return n else return m end end local max_cmp = function(m, n) if n > m then return n else return m end end local min = function(gen, param, state) local state, m = gen(param, state) if state == nil then error("min: iterator is empty") end local cmp if type(m) == "number" then -- An optimization: use math.min for numbers cmp = math.min else cmp = min_cmp end for _, r in gen, param, state do m = cmp(m, r) end return m end methods.min = method0(min) exports.min = export0(min) methods.minimum = methods.min exports.minimum = exports.min local min_by = function(cmp, gen_x, param_x, state_x) local state_x, m = gen_x(param_x, state_x) if state_x == nil then error("min: iterator is empty") end for _, r in gen_x, param_x, state_x do m = cmp(m, r) end return m end methods.min_by = method1(min_by) exports.min_by = export1(min_by) methods.minimum_by = methods.min_by exports.minimum_by = exports.min_by local max = function(gen_x, param_x, state_x) local state_x, m = gen_x(param_x, state_x) if state_x == nil then error("max: iterator is empty") end local cmp if type(m) == "number" then -- An optimization: use math.max for numbers cmp = math.max else cmp = max_cmp end for _, r in gen_x, param_x, state_x do m = cmp(m, r) end return m end methods.max = method0(max) exports.max = export0(max) methods.maximum = methods.max exports.maximum = exports.max local max_by = function(cmp, gen_x, param_x, state_x) local state_x, m = gen_x(param_x, state_x) if state_x == nil then error("max: iterator is empty") end for _, r in gen_x, param_x, state_x do m = cmp(m, r) end return m end methods.max_by = method1(max_by) exports.max_by = export1(max_by) methods.maximum_by = methods.maximum_by exports.maximum_by = exports.maximum_by local totable = function(gen_x, param_x, state_x) local tab, key, val = {} while true do state_x, val = gen_x(param_x, state_x) if state_x == nil then break end table.insert(tab, val) end return tab end methods.totable = method0(totable) exports.totable = export0(totable) local tomap = function(gen_x, param_x, state_x) local tab, key, val = {} while true do state_x, key, val = gen_x(param_x, state_x) if state_x == nil then break end tab[key] = val end return tab end methods.tomap = method0(tomap) exports.tomap = export0(tomap) -------------------------------------------------------------------------------- -- Transformations -------------------------------------------------------------------------------- local map_gen = function(param, state) local gen_x, param_x, fun = param[1], param[2], param[3] return call_if_not_empty(fun, gen_x(param_x, state)) end local map = function(fun, gen, param, state) return wrap(map_gen, {gen, param, fun}, state) end methods.map = method1(map) exports.map = export1(map) local enumerate_gen_call = function(state, i, state_x, ...) if state_x == nil then return nil end return {i + 1, state_x}, i, ... end local enumerate_gen = function(param, state) local gen_x, param_x = param[1], param[2] local i, state_x = state[1], state[2] return enumerate_gen_call(state, i, gen_x(param_x, state_x)) end local enumerate = function(gen, param, state) return wrap(enumerate_gen, {gen, param}, {1, state}) end methods.enumerate = method0(enumerate) exports.enumerate = export0(enumerate) local intersperse_call = function(i, state_x, ...) if state_x == nil then return nil end return {i + 1, state_x}, ... end local intersperse_gen = function(param, state) local x, gen_x, param_x = param[1], param[2], param[3] local i, state_x = state[1], state[2] if i % 2 == 1 then return {i + 1, state_x}, x else return intersperse_call(i, gen_x(param_x, state_x)) end end -- TODO: interperse must not add x to the tail local intersperse = function(x, gen, param, state) return wrap(intersperse_gen, {x, gen, param}, {0, state}) end methods.intersperse = method1(intersperse) exports.intersperse = export1(intersperse) -------------------------------------------------------------------------------- -- Compositions -------------------------------------------------------------------------------- local function zip_gen_r(param, state, state_new, ...) if #state_new == #param / 2 then return state_new, ... end local i = #state_new + 1 local gen_x, param_x = param[2 * i - 1], param[2 * i] local state_x, r = gen_x(param_x, state[i]) if state_x == nil then return nil end table.insert(state_new, state_x) return zip_gen_r(param, state, state_new, r, ...) end local zip_gen = function(param, state) return zip_gen_r(param, state, {}) end -- A special hack for zip/chain to skip last two state, if a wrapped iterator -- has been passed local numargs = function(...) local n = select('#', ...) if n >= 3 then -- Fix last argument local it = select(n - 2, ...) if type(it) == 'table' and getmetatable(it) == iterator_mt and it.param == select(n - 1, ...) and it.state == select(n, ...) then return n - 2 end end return n end local zip = function(...) local n = numargs(...) if n == 0 then return wrap(nil_gen, nil, nil) end local param = { [2 * n] = 0 } local state = { [n] = 0 } local i, gen_x, param_x, state_x for i=1,n,1 do local it = select(n - i + 1, ...) gen_x, param_x, state_x = rawiter(it) param[2 * i - 1] = gen_x param[2 * i] = param_x state[i] = state_x end return wrap(zip_gen, param, state) end methods.zip = zip exports.zip = zip local cycle_gen_call = function(param, state_x, ...) if state_x == nil then local gen_x, param_x, state_x0 = param[1], param[2], param[3] return gen_x(param_x, deepcopy(state_x0)) end return state_x, ... end local cycle_gen = function(param, state_x) local gen_x, param_x, state_x0 = param[1], param[2], param[3] return cycle_gen_call(param, gen_x(param_x, state_x)) end local cycle = function(gen, param, state) return wrap(cycle_gen, {gen, param, state}, deepcopy(state)) end methods.cycle = method0(cycle) exports.cycle = export0(cycle) -- call each other local chain_gen_r1 local chain_gen_r2 = function(param, state, state_x, ...) if state_x == nil then local i = state[1] i = i + 1 if i > #param / 3 then return nil end local state_x = param[3 * i] return chain_gen_r1(param, {i, state_x}) end return {state[1], state_x}, ... end chain_gen_r1 = function(param, state) local i, state_x = state[1], state[2] local gen_x, param_x = param[3 * i - 2], param[3 * i - 1] return chain_gen_r2(param, state, gen_x(param_x, state[2])) end local chain = function(...) local n = numargs(...) if n == 0 then return wrap(nil_gen, nil, nil) end local param = { [3 * n] = 0 } local i, gen_x, param_x, state_x for i=1,n,1 do local elem = select(i, ...) gen_x, param_x, state_x = iter(elem) param[3 * i - 2] = gen_x param[3 * i - 1] = param_x param[3 * i] = state_x end return wrap(chain_gen_r1, param, {1, param[3]}) end methods.chain = chain exports.chain = chain -------------------------------------------------------------------------------- -- Operators -------------------------------------------------------------------------------- operator = { ---------------------------------------------------------------------------- -- Comparison operators ---------------------------------------------------------------------------- lt = function(a, b) return a < b end, le = function(a, b) return a <= b end, eq = function(a, b) return a == b end, ne = function(a, b) return a ~= b end, ge = function(a, b) return a >= b end, gt = function(a, b) return a > b end, ---------------------------------------------------------------------------- -- Arithmetic operators ---------------------------------------------------------------------------- add = function(a, b) return a + b end, div = function(a, b) return a / b end, floordiv = function(a, b) return math.floor(a/b) end, intdiv = function(a, b) local q = a / b if a >= 0 then return math.floor(q) else return math.ceil(q) end end, mod = function(a, b) return a % b end, mul = function(a, b) return a * b end, neq = function(a) return -a end, unm = function(a) return -a end, -- an alias pow = function(a, b) return a ^ b end, sub = function(a, b) return a - b end, truediv = function(a, b) return a / b end, ---------------------------------------------------------------------------- -- String operators ---------------------------------------------------------------------------- concat = function(a, b) return a..b end, len = function(a) return #a end, length = function(a) return #a end, -- an alias ---------------------------------------------------------------------------- -- Logical operators ---------------------------------------------------------------------------- land = function(a, b) return a and b end, lor = function(a, b) return a or b end, lnot = function(a) return not a end, truth = function(a) return not not a end, } exports.operator = operator methods.operator = operator exports.op = operator methods.op = operator -------------------------------------------------------------------------------- -- module definitions -------------------------------------------------------------------------------- -- a special syntax sugar to export all functions to the global table setmetatable(exports, { __call = function(t) for k, v in pairs(t) do _G[k] = v end end, }) return exports
mit
bnetcc/darkstar
scripts/globals/mobskills/tebbad_wing.lua
33
1231
--------------------------------------------- -- Tebbad Wing -- -- Description: A hot wind deals Fire damage to enemies within a very wide area of effect. Additional effect: Plague -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: 30' radial. -- Notes: Used only by Tiamat, Smok and Ildebrann --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:hasStatusEffect(EFFECT_MIGHTY_STRIKES)) then return 1; elseif (mob:AnimationSub() == 1) then return 1; elseif (target:isBehind(mob, 48) == true) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_PLAGUE; MobStatusEffectMove(mob, target, typeEffect, 10, 0, 120); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_FIRE,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_FIRE,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
fengshao0907/Atlas
lib/active-queries.lua
40
3780
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2008, 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%$ --]] -- proxy.auto-config will pick them up local commands = require("proxy.commands") local auto_config = require("proxy.auto-config") --- init the global scope if not proxy.global.active_queries then proxy.global.active_queries = {} end if not proxy.global.max_active_trx then proxy.global.max_active_trx = 0 end -- default config for this script if not proxy.global.config.active_queries then proxy.global.config.active_queries = { show_idle_connections = false } end --- -- track the active queries and dump all queries at each state-change -- function collect_stats() local num_conns = 0 local active_conns = 0 for k, v in pairs(proxy.global.active_queries) do num_conns = num_conns + 1 if v.state ~= "idle" then active_conns = active_conns + 1 end end if active_conns > proxy.global.max_active_trx then proxy.global.max_active_trx = active_conns end return { active_conns = active_conns, num_conns = num_conns, max_active_trx = proxy.global.max_active_trx } end --- -- dump the state of the current queries -- function print_stats(stats) local o = "" for k, v in pairs(proxy.global.active_queries) do if v.state ~= "idle" or proxy.global.config.active_queries.show_idle_connections then local cmd_query = "" if v.cmd then cmd_query = string.format("(%s) %q", v.cmd.type_name, v.cmd.query or "") end o = o .." ["..k.."] (".. v.username .."@".. v.db ..") " .. cmd_query .." (state=" .. v.state .. ")\n" end end -- prepend the data and the stats about the number of connections and trx o = os.date("%Y-%m-%d %H:%M:%S") .. "\n" .. " #connections: " .. stats.num_conns .. ", #active trx: " .. stats.active_conns .. ", max(active trx): ".. stats.max_active_trx .. "\n" .. o print(o) end --- -- enable tracking the packets function read_query(packet) local cmd = commands.parse(packet) local r = auto_config.handle(cmd) if r then return r end proxy.queries:append(1, packet) -- add the query to the global scope local connection_id = proxy.connection.server.thread_id proxy.global.active_queries[connection_id] = { state = "started", cmd = cmd, db = proxy.connection.client.default_db or "", username = proxy.connection.client.username or "" } print_stats(collect_stats()) return proxy.PROXY_SEND_QUERY end --- -- statement is done, track the change function read_query_result(inj) local connection_id = proxy.connection.server.thread_id proxy.global.active_queries[connection_id].state = "idle" proxy.global.active_queries[connection_id].cmd = nil if inj.resultset then local res = inj.resultset if res.flags.in_trans then proxy.global.active_queries[connection_id].state = "in_trans" end end print_stats(collect_stats()) end --- -- remove the information about the connection -- function disconnect_client() local connection_id = proxy.connection.server.thread_id if connection_id then proxy.global.active_queries[connection_id] = nil print_stats(collect_stats()) end end
gpl-2.0
swe-TeamRed/wesnoth
data/campaigns/Eastern_Invasion/lua/bandits.lua
3
3625
-- Used for the bandit villages in S5. Much more specific than the village spawn implementations elsewhere, -- since there are a lot more specific things needed (mostly the boss mechanics and village spreading) local helper = wesnoth.require "lua/helper.lua" local wml_actions = wesnoth.wml_actions local _ = wesnoth.textdomain "wesnoth-ei" local T = helper.set_wml_tag_metatable {} function wml_actions.spread_bandit_villages(cfg) local x = cfg.x or helper.wml_error("[spread_bandit_villages] missing required x= attribute.") local y = cfg.y or helper.wml_error("[spread_bandit_villages] missing required y= attribute.") local count = cfg.count or helper.wml_error("[spread_bandit_villages] missing required count= attribute.") local types = cfg.types or helper.wml_error("[spread_bandit_villages] missing required types= attribute.") wesnoth.set_variable("villages_visited", 0) wesnoth.set_variable("boss_found", false) wesnoth.set_variable("bandit_types", types) local villages = wesnoth.get_villages(cfg) -- Shouldn't happen in the scenario, but a failsafe is always nice. if count > #villages then count = #villages end local village_i for i = 0, (count - 1) do village_i = helper.rand("1.."..#villages) wesnoth.set_variable(string.format("bandit_villages[%d].x", i), villages[village_i][1]) wesnoth.set_variable(string.format("bandit_villages[%d].y", i), villages[village_i][2]) table.remove(villages, village_i) end end local function bandits_found(x,y) local bandit_types = wesnoth.get_variable("bandit_types") local bandit_villages = helper.get_variable_array("bandit_villages") local boss_found = wesnoth.get_variable("boss_found") local visited = wesnoth.get_variable("villages_visited") local rand1 = helper.rand("3,4") local rand2 = helper.rand("2.."..rand1) for i=1,rand2 do local radius = 1 local locs repeat locs = wesnoth.get_locations({T["not"] { T.filter {} } , T["and"] { x = x, y = y, radius = radius } }) radius = radius + 1 until locs[1] local bandit = helper.rand(bandit_types) local loc_i = helper.rand("1.."..#locs) wml_actions.move_unit_fake({x = string.format("%d,%d", x, locs[loc_i][1]), y = string.format("%d,%d", y, locs[loc_i][2]), type = bandit, side = "4"}) wesnoth.put_unit(locs[loc_i][1], locs[loc_i][2], { type = bandit, side = "4", random_traits = "yes", generate_name = "yes", upkeep = "loyal" }) end if not boss_found and visited > 2 then local boss_chance = (100 / #bandit_villages) local rand3 = helper.rand("1..100") if rand3 <= boss_chance or #bandit_villages < 3 then wesnoth.set_variable("boss_found", true) local loc = wesnoth.get_locations({T["not"] { T.filter {} } , T["and"] { x = x, y = y, radius = 2 } })[1] wesnoth.fire_event("boss_found", x, y, loc[1], loc[2]) end end end function wml_actions.bandit_village_capture(cfg) local bandit_villages = helper.get_variable_proxy_array("bandit_villages") local x = cfg.x or helper.wml_error("[bandit_village_capture] missing required x= attribute.") local y = cfg.y or helper.wml_error("[bandit_village_capture] missing required y= attribute.") for i=1,#bandit_villages do if bandit_villages[i].x == x and bandit_villages[i].y == y then wesnoth.set_variable(string.format("bandit_villages[%d]", i - 1)) local visited = wesnoth.get_variable("villages_visited") wesnoth.set_variable("villages_visited", visited + 1) wesnoth.fire("message" , { x = x , y = y , message = _"They're here!"}) bandits_found(x,y) return end end wesnoth.fire("message" , { x = x , y = y , message = _"No outlaws in this village."}) end
gpl-2.0
Zaratusa/gmod_addons
lua/autorun/client/gauss_rifle_textures.lua
2
2197
CreateConVar("gauss_rifle_body", 1, {FCVAR_CLIENTCMD_CAN_EXECUTE, FCVAR_ARCHIVE}, "Which color should the gauss rifle body have?") CreateConVar("gauss_rifle_scope", 1, {FCVAR_CLIENTCMD_CAN_EXECUTE, FCVAR_ARCHIVE}, "Which color should the gauss rifle scope have?") local BodyColors = {"blue", "green", "orange", "purple"} local ScopeColors = {"blue", "green", "orange", "purple", "grey", "white"} local function changeBodyTextures(color) Material("models/weapons/v_models/zaratusa.gauss.rifle/gauss_a_d"):SetTexture("$basetexture", "models/weapons/v_models/zaratusa.gauss.rifle/gauss_a_d_" .. color) Material("models/weapons/v_models/zaratusa.gauss.rifle/gauss_b_d"):SetTexture("$basetexture", "models/weapons/v_models/zaratusa.gauss.rifle/gauss_b_d_" .. color) Material("models/weapons/w_models/zaratusa.gauss.rifle/gauss_a"):SetTexture("$basetexture", "models/weapons/v_models/zaratusa.gauss.rifle/gauss_a_d_" .. color) Material("models/weapons/w_models/zaratusa.gauss.rifle/gauss_b"):SetTexture("$basetexture", "models/weapons/v_models/zaratusa.gauss.rifle/gauss_b_d_" .. color) end local function changeScopeTextures(color) Material("models/weapons/v_models/zaratusa.gauss.rifle/scope_d"):SetTexture("$basetexture", "models/weapons/v_models/zaratusa.gauss.rifle/scope_d_" .. color) Material("models/weapons/w_models/zaratusa.gauss.rifle/scope"):SetTexture("$basetexture", "models/weapons/v_models/zaratusa.gauss.rifle/scope_d_" .. color) end local function getIncreasedValue(conVar, maxValue) local value = conVar:GetInt() + 1 if (value > maxValue) then value = 1 end conVar:SetInt(value) return value end -- console commands concommand.Add("gr_changebody", function() changeBodyTextures(BodyColors[getIncreasedValue(GetConVar("gauss_rifle_body"), 4)]) end) concommand.Add("gr_changescope", function() changeScopeTextures(ScopeColors[getIncreasedValue(GetConVar("gauss_rifle_scope"), 6)]) end) -- somehow just loads like this on startup concommand.Add("gr_loadsettings", function() changeBodyTextures(BodyColors[GetConVar("gauss_rifle_body"):GetInt()]) changeScopeTextures(ScopeColors[GetConVar("gauss_rifle_scope"):GetInt()]) end) RunConsoleCommand("gr_loadsettings")
gpl-3.0
githubmereza/bOOOt
plugins/google.lua
1
1057
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="Search in Google:\n______________________________\n" for key,val in ipairs(results) do stringresults=stringresults..val[1].." - "..val[2].."\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searche in Google", usage = "جستجو (item) : google search", patterns = { "^جستجو (.*)$", "^%.[s|S]rc (.*)$" }, run = run }
gpl-2.0
TeleDALAD/test
plugins/google.lua
722
1037
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="" for key,val in ipairs(results) do stringresults=stringresults..val[1].." - "..val[2].."\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searches Google and send results", usage = "!google [terms]: Searches Google and send results", patterns = { "^!google (.*)$", "^%.[g|G]oogle (.*)$" }, run = run }
gpl-2.0
bnetcc/darkstar
scripts/commands/troll1.lua
1
1730
--------------------------------------------------------------------------------------------------- -- !troll1 -- Spawns 1st wave of Besieged Trolls --------------------------------------------------------------------------------------------------- cmdprops = { permission = 3, parameters = "" }; function onTrigger(player) SpawnMob(16973930); -- Troll_Paviser SpawnMob(16974002); -- Gurlufur_The_Menacing SpawnMob(16973931); -- Troll_Stormer SpawnMob(16973932); -- Troll_Hoplite SpawnMob(16973933); -- Troll_Pezhetairoi SpawnMob(16973934); -- Troll_Cannoneer SpawnMob(16973935); -- Troll_Velites SpawnMob(16973936); -- Troll_Speculator SpawnMob(16973937); -- Troll_Automaton SpawnMob(16973938); -- Troll_Paviser SpawnMob(16973939); -- Troll_Stormer SpawnMob(16973940); -- Troll_Hoplite SpawnMob(16973941); -- Troll_Pezhetairoi SpawnMob(16973942); -- Troll_Cannoneer SpawnMob(16973943); -- Troll_Velites SpawnMob(16973944); -- Troll_Speculator SpawnMob(16973945); -- Troll_Automaton SpawnMob(16973946); -- Troll_Paviser SpawnMob(16973947); -- Troll_Stormer SpawnMob(16973948); -- Troll_Hoplite SpawnMob(16973949); -- Troll_Pezhetairoi SpawnMob(16973950); -- Troll_Cannoneer SpawnMob(16973951); -- Troll_Velites SpawnMob(16973952); -- Troll_Speculator SpawnMob(16973953); -- Troll_Automaton SpawnMob(16973954); -- Flame_Eruca SpawnMob(16973955); -- Flame_Eruca SpawnMob(16973956); -- Flame_Eruca SpawnMob(16973957); -- Flame_Eruca SpawnMob(16973958); -- Flame_Eruca SpawnMob(16973959); -- War_Wamouracampa SpawnMob(16973960); -- War_Wamouracampa SpawnMob(16973961); -- War_Wamouracampa end
gpl-3.0
erosennin/koreader
frontend/optmath.lua
6
1337
--[[ Simple math helper function ]]-- local Math = {} function Math.roundAwayFromZero(num) if num > 0 then return math.ceil(num) else return math.floor(num) end end function Math.round(num) return math.floor(num + 0.5) end function Math.oddEven(number) if number % 2 == 1 then return "odd" else return "even" end end local function tmin_max(tab, func, op) if #tab == 0 then return nil, nil end local index, value = 1, tab[1] for i = 2, #tab do if func then if func(value, tab[i]) then index, value = i, tab[i] end elseif op == "min" then if value > tab[i] then index, value = i, tab[i] end elseif op == "max" then if value < tab[i] then index, value = i, tab[i] end end end return index, value end --[[ Return the minimum element of a table. The optional argument func specifies a one-argument ordering function. ]]-- function Math.tmin(tab, func) return tmin_max(tab, func, "min") end --[[ Return the maximum element of a table. The optional argument func specifies a one-argument ordering function. ]]-- function Math.tmax(tab, func) return tmin_max(tab, func, "max") end return Math
agpl-3.0
bnetcc/darkstar
scripts/zones/Abyssea-La_Theine/npcs/Cruor_Prospector.lua
1
10714
----------------------------------- -- Area: Abyssea - La_Theine -- NPC: Cruor Prospector -- Type: Cruor NPC -- @pos ? ? ? ? (needs filled in) ----------------------------------- package.loaded["scripts/zones/Abyssea-La_Theine/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Abyssea-La_Theine/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/keyitems"); require("scripts/globals/abyssea"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Cruor = player:getCurrency("cruor"); local Demilune = getDemiluneAbyssite(player); player:startEvent(2002, Cruor, Demilune); 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); local Price = 0; local ItemID = 0; local Quantity = 1; -- Items Page 1 if (option == 65537) then -- Perle Salade Price = 4000; ItemID = 11503; elseif (option == 131073) then -- Perle Hauberk Price = 5000; ItemID = 13759; elseif (option == 196609) then -- Perle Moufles Price = 3000; ItemID = 12745; elseif (option == 262145) then -- Perle Brayettes Price = 3000; ItemID = 14210; elseif (option == 327681) then -- Perle Solerets Price = 3000; ItemID = 11413; elseif (option == 393217) then -- Aurore Beret Price = 4000; ItemID = 11504; elseif (option == 458753) then -- Aurore Doublet Price = 5000; ItemID = 13760; elseif (option == 524289) then -- Aurore Gloves Price = 3000; ItemID = 12746; elseif (option == 589825) then -- Aurore Brais Price = 3000; ItemID = 14257; elseif (option == 655361) then -- Aurore Gaiters Price = 3000; ItemID = 11414; -- Items Page 2 elseif (option == 720897) then -- Teal Chapeau Price = 4000; ItemID = 11505; elseif (option == 786433) then -- Teal Saio Price = 5000; ItemID = 13778; elseif (option == 851969) then -- Teal Cuffs Price = 3000; ItemID = 12747; elseif (option == 917505) then -- Teal Slops Price = 3000; ItemID = 14258; elseif (option == 983041) then -- Teal Pigaches Price = 3000; ItemID = 11415; elseif (option == 17825793) then -- 1x Forbidden Key Price = 500; ItemID = 2490; elseif (option == 84934657) then -- 5x Forbidden Key Price = 2500; ItemID = 2490; Quantity = 5; elseif (option == 168820737) then -- 10x Forbidden Key Price = 5000; ItemID = 2490; Quantity = 10; elseif (option == 504365057) then -- 30x Forbidden Key Price = 15000; ItemID = 2490; Quantity = 30; elseif (option == 839909377) then -- 50x Forbidden Key Price = 25000; ItemID = 2490; Quantity = 50; -- Temp items elseif (option == 65538) then -- Lucid Potion I if (player:addTempItem(5824,1)) then player:messageSpecial(ITEM_OBTAINED,5824); player:delCurrency("cruor", 80); end elseif (option == 131074) then -- Lucid Ether I if (player:addTempItem(5827,1)) then player:messageSpecial(ITEM_OBTAINED,5827); player:delCurrency("cruor", 80); end elseif (option == 196610) then -- Catholicon if (player:addTempItem(4206,1)) then player:messageSpecial(ITEM_OBTAINED,4206); player:delCurrency("cruor", 80); end elseif (option == 262146) then -- Dusty Elixer if (player:addTempItem(5433,1)) then player:messageSpecial(ITEM_OBTAINED,5433); player:delCurrency("cruor", 120); end elseif (option == 327682) then -- Clear Salve I if (player:addTempItem(5837,1)) then player:messageSpecial(ITEM_OBTAINED,5837); player:delCurrency("cruor", 120); end elseif (option == 393218) then -- Stalworts Tonic if (player:addTempItem(5839,1)) then player:messageSpecial(ITEM_OBTAINED,5839); player:delCurrency("cruor", 150); end elseif (option == 458754) then -- Ascetics Tonic if (player:addTempItem(5841,1)) then player:messageSpecial(ITEM_OBTAINED,5841); player:delCurrency("cruor", 150); end elseif (option == 524290) then -- Champion's Tonic if (player:addTempItem(5843,1)) then player:messageSpecial(ITEM_OBTAINED,5843); player:delCurrency("cruor", 150); end elseif (option == 589826) then -- Lucid Potion II if (player:addTempItem(5825,1)) then player:messageSpecial(ITEM_OBTAINED,5825); player:delCurrency("cruor", 200); end elseif (option == 655362) then -- Lucid Potion II if (player:addTempItem(5828,1)) then player:messageSpecial(ITEM_OBTAINED,5828); player:delCurrency("cruor", 200); end -- Keyitems elseif (option == 65539) then -- Map of Abyssea - La_Theine if (player:hasKeyItem(MAP_OF_ABYSSEA_LA_THEINE) == false) then player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_ABYSSEA_LA_THEINE); player:addKeyItem(MAP_OF_ABYSSEA_LA_THEINE); player:delCurrency("cruor", 3500); end elseif (option == 131075) then -- Ivory Abyssite of Sojourn if (player:hasKeyItem(IVORY_ABYSSITE_OF_SOJOURN) == false) then player:messageSpecial(KEYITEM_OBTAINED,IVORY_ABYSSITE_OF_SOJOURN); player:addKeyItem(IVORY_ABYSSITE_OF_SOJOURN); player:delCurrency("cruor", 6000); end elseif (option == 196611) then -- Ivory Abyssite of Confluence if (player:hasKeyItem(IVORY_ABYSSITE_OF_CONFLUENCE) == false) then player:messageSpecial(KEYITEM_OBTAINED,IVORY_ABYSSITE_OF_CONFLUENCE); player:addKeyItem(IVORY_ABYSSITE_OF_CONFLUENCE); player:delCurrency("cruor", 4800); end elseif (option == 262147) then -- Ivory Abyssite of Expertise if (player:hasKeyItem(IVORY_ABYSSITE_OF_EXPERTISE) == false) then player:messageSpecial(KEYITEM_OBTAINED,IVORY_ABYSSITE_OF_EXPERTISE); player:addKeyItem(IVORY_ABYSSITE_OF_EXPERTISE); player:delCurrency("cruor", 4800); end elseif (option == 458755) then -- Clear Demilune Abyssite if (player:hasKeyItem(CLEAR_DEMILUNE_ABYSSITE) == false) then player:messageSpecial(KEYITEM_OBTAINED,CLEAR_DEMILUNE_ABYSSITE); player:addKeyItem(CLEAR_DEMILUNE_ABYSSITE); player:delCurrency("cruor", 300); end -- Enhancement Effects (only removed by zoning, infinite duration) elseif (option == 393220) then -- HP Boost player:addStatusEffectEx(EFFECT_ABYSSEA_HP,EFFECT_MAX_HP_BOOST,20+(getAbyssiteTotal(player,"MERIT") *10),0,0); player:addHP(20+(getAbyssiteTotal(player,"MERIT") *10) *10); player:delCurrency("cruor", 50); elseif (option == 458756) then -- MP Boost player:addStatusEffectEx(EFFECT_ABYSSEA_MP,EFFECT_MAX_MP_BOOST,10+(getAbyssiteTotal(player,"MERIT") *5),0,0); player:addMP(10+(getAbyssiteTotal(player,"MERIT") *5) *10); player:delCurrency("cruor", 120); elseif (option == 524292) then -- STR-DEX Boost player:addStatusEffectEx(EFFECT_ABYSSEA_STR,EFFECT_STR_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:addStatusEffectEx(EFFECT_ABYSSEA_DEX,EFFECT_DEX_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:delCurrency("cruor", 120); elseif (option == 589828) then -- VIT-AGI Boost player:addStatusEffectEx(EFFECT_ABYSSEA_VIT,EFFECT_VIT_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:addStatusEffectEx(EFFECT_ABYSSEA_AGI,EFFECT_AGI_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:delCurrency("cruor", 100); elseif (option == 655364) then -- INT-MND-CHR Boost player:addStatusEffectEx(EFFECT_ABYSSEA_INT,EFFECT_INT_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:addStatusEffectEx(EFFECT_ABYSSEA_MND,EFFECT_MND_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:addStatusEffectEx(EFFECT_ABYSSEA_CHR,EFFECT_CHR_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:delCurrency("cruor", 100); elseif (option == 720900) then -- All Enhancements player:addStatusEffectEx(EFFECT_ABYSSEA_HP,EFFECT_MAX_HP_BOOST,20+(getAbyssiteTotal(player,"MERIT") *10),0,0); player:addHP(20+(getAbyssiteTotal(player,"MERIT") *10) *10); player:addStatusEffectEx(EFFECT_ABYSSEA_MP,EFFECT_MAX_MP_BOOST,10+(getAbyssiteTotal(player,"MERIT") *5),0,0); player:addMP(10+(getAbyssiteTotal(player,"MERIT") *5) *10); player:addStatusEffectEx(EFFECT_ABYSSEA_STR,EFFECT_STR_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:addStatusEffectEx(EFFECT_ABYSSEA_DEX,EFFECT_DEX_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:addStatusEffectEx(EFFECT_ABYSSEA_VIT,EFFECT_VIT_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:addStatusEffectEx(EFFECT_ABYSSEA_AGI,EFFECT_AGI_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:addStatusEffectEx(EFFECT_ABYSSEA_INT,EFFECT_INT_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:addStatusEffectEx(EFFECT_ABYSSEA_MND,EFFECT_MND_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:addStatusEffectEx(EFFECT_ABYSSEA_CHR,EFFECT_CHR_BOOST,10+(getAbyssiteTotal(player,"FURTHERANCE") *10),0,0); player:delCurrency("cruor", 470); end if (ItemID ~= 0) then if (player:getFreeSlotsCount() >= 1) then player:messageSpecial(ITEM_OBTAINED,ItemID); player:addItem(ItemID,Quantity); player:delCurrency("cruor", Price); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,ItemID); end end end;
gpl-3.0
Solybum/PSOBBMod-Addons
Monster Reader/monsters.lua
1
7908
-- Set this to a number above 0 to hide monsters farther -- away than this distance. Recommended value 750-1000, -- but play with it and see what you like! local maxDistance = 0 -- Standard enemy colors are white, rare enemies are yellow, bosses are red. -- Minibosses are a less threatening red. 8) -- Changing the second value to "false" makes the enemy not appear on the monster -- reader. local m = {} m[0] = { color = 0xFFFFFFFF, display = false } -- Unknown -- Forest m[1] = { color = 0xFFFFFFFF, display = true } -- Hildebear / Hildelt m[2] = { color = 0xFFFFFF00, display = true } -- Hildeblue / Hildetorr m[3] = { color = 0xFFFFFFFF, display = true } -- Mothmant / Mothvert m[4] = { color = 0xFFFFFFFF, display = true } -- Monest / Mothvist m[5] = { color = 0xFFFFFFFF, display = true } -- Rag Rappy / El Rappy m[6] = { color = 0xFFFFFF00, display = true } -- Al Rappy / Pal Rappy m[7] = { color = 0xFFFFFFFF, display = true } -- Savage Wolf / Gulgus m[8] = { color = 0xFFFFFFFF, display = true } -- Barbarous Wolf / Gulgus-gue m[9] = { color = 0xFFFFFFFF, display = true } -- Booma / Bartle m[10] = { color = 0xFFFFFFFF, display = true } -- Gobooma / Barble m[11] = { color = 0xFFFFFFFF, display = true } -- Gigobooma / Tollaw -- Cave m[12] = { color = 0xFFFFFFFF, display = true } -- Grass Assassin / Crimson Assassin m[13] = { color = 0xFFFFFFFF, display = true } -- Poison Lily / Ob Lily m[14] = { color = 0xFFFFFF00, display = true } -- Nar Lily / Mil Lily m[15] = { color = 0xFFFFFFFF, display = true } -- Nano Dragon m[16] = { color = 0xFFFFFFFF, display = true } -- Evil Shark / Vulmer m[17] = { color = 0xFFFFFFFF, display = true } -- Pal Shark / Govulmer m[18] = { color = 0xFFFFFFFF, display = true } -- Guil Shark / Melqueek m[19] = { color = 0xFFFFFFFF, display = true } -- Pofuilly Slime m[20] = { color = 0xFFFFFF00, display = true } -- Pouilly Slime m[21] = { color = 0xFFFFFFFF, display = true } -- Pan Arms m[22] = { color = 0xFFFFFFFF, display = true } -- Migium m[23] = { color = 0xFFFFFFFF, display = true } -- Hidoom -- Mine m[24] = { color = 0xFFFFFFFF, display = true } -- Dubchic / Dubchich m[25] = { color = 0xFFFFFFFF, display = true } -- Garanz / Baranz m[26] = { color = 0xFFFFFFFF, display = true } -- Sinow Beat / Sinow Blue m[27] = { color = 0xFFFFFFFF, display = true } -- Sinow Gold / Sinow Red m[28] = { color = 0xFFFFFFFF, display = true } -- Canadine / Canabin m[29] = { color = 0xFFFFFFFF, display = true } -- Canane / Canune m[49] = { color = 0xFFFFFFFF, display = true } -- Dubwitch m[50] = { color = 0xFFFFFFFF, display = true } -- Gillchic / Gillchich -- Ruins m[30] = { color = 0xFFFFFFFF, display = true } -- Delsaber m[31] = { color = 0xFFFFFFFF, display = true } -- Chaos Sorcerer / Gran Sorcerer m[32] = { color = 0xFFFFFFFF, display = true } -- Bee R / Gee R m[33] = { color = 0xFFFFFFFF, display = true } -- Bee L / Gee L m[34] = { color = 0xFFFFFFFF, display = true } -- Dark Gunner m[35] = { color = 0xFFFFFFFF, display = true } -- Death Gunner m[36] = { color = 0xFFFFFFFF, display = true } -- Dark Bringer m[37] = { color = 0xFFFFFFFF, display = true } -- Indi Belra m[38] = { color = 0xFFFFFFFF, display = true } -- Claw m[39] = { color = 0xFFFFFFFF, display = true } -- Bulk m[40] = { color = 0xFFFFFFFF, display = true } -- Bulclaw m[41] = { color = 0xFFFFFFFF, display = true } -- Dimenian / Arlan m[42] = { color = 0xFFFFFFFF, display = true } -- La Dimenian / Merlan m[43] = { color = 0xFFFFFFFF, display = true } -- So Dimenian / Del-D -- Episode 1 Bosses m[44] = { color = 0xFFFF0000, display = true } -- Dragon / Sil Dragon m[45] = { color = 0xFFFF0000, display = true } -- De Rol Le / Dal Ral Lie m[46] = { color = 0xFFFF0000, display = true } -- Vol Opt / Vol Opt ver.2 m[47] = { color = 0xFFFF0000, display = true } -- Dark Falz -- VR Temple m[51] = { color = 0xFFFFFF00, display = true } -- Love Rappy m[73] = { color = 0xFFFF0000, display = true } -- Barba Ray m[74] = { color = 0xFFFFFFFF, display = true } -- Pig Ray m[75] = { color = 0xFFFFFFFF, display = true } -- Ul Ray m[79] = { color = 0xFFFFFFFF, display = true } -- St. Rappy m[80] = { color = 0xFFFFFF00, display = true } -- Hallo Rappy m[81] = { color = 0xFFFFFF00, display = true } -- Egg Rappy -- VR Spaceship m[76] = { color = 0xFFFF0000, display = true } -- Gol Dragon -- Central Control Area m[52] = { color = 0xFFFFFFFF, display = true } -- Merillia m[53] = { color = 0xFFFFFFFF, display = true } -- Meriltas m[54] = { color = 0xFFFFFFFF, display = true } -- Gee m[55] = { color = 0xFFFF8080, display = true } -- Gi Gue m[56] = { color = 0xFFFF8080, display = true } -- Mericarol m[57] = { color = 0xFFFF8080, display = true } -- Merikle m[58] = { color = 0xFFFF8080, display = true } -- Mericus m[59] = { color = 0xFFFFFFFF, display = true } -- Ul Gibbon m[60] = { color = 0xFFFFFFFF, display = true } -- Zol Gibbon m[61] = { color = 0xFFFF8080, display = true } -- Gibbles m[62] = { color = 0xFFFFFFFF, display = true } -- Sinow Berill m[63] = { color = 0xFFFFFFFF, display = true } -- Sinow Spigell m[77] = { color = 0xFFFF0000, display = true } -- Gal Gryphon m[82] = { color = 0xFFFFFFFF, display = true } -- Ill Gill m[83] = { color = 0xFFFFFFFF, display = true } -- Del Lily m[84] = { color = 0xFFFF8080, display = true } -- Epsilon m[87] = { color = 0xFFFFFFFF, display = true } -- Epsigard -- Seabed m[64] = { color = 0xFFFFFFFF, display = true } -- Dolmolm m[65] = { color = 0xFFFFFFFF, display = true } -- Dolmdarl m[66] = { color = 0xFFFFFFFF, display = true } -- Morfos m[67] = { color = 0xFFFFFFFF, display = true } -- Recobox m[68] = { color = 0xFFFFFFFF, display = true } -- Recon m[69] = { color = 0xFFFFFFFF, display = true } -- Sinow Zoa m[70] = { color = 0xFFFFFFFF, display = true } -- Sinow Zele m[71] = { color = 0xFFFFFFFF, display = true } -- Deldepth m[72] = { color = 0xFFFFFFFF, display = true } -- Delbiter m[78] = { color = 0xFFFF0000, display = true } -- Olga Flow m[85] = { color = 0xFFFFFFFF, display = true } -- Gael m[86] = { color = 0xFFFFFFFF, display = true } -- Giel -- Crater m[88] = { color = 0xFFFFFFFF, display = true } -- Astark m[89] = { color = 0xFFFFFFFF, display = true } -- Yowie m[90] = { color = 0xFFFFFFFF, display = true } -- Satellite Lizard m[94] = { color = 0xFFFFFFFF, display = true } -- Zu m[95] = { color = 0xFFFFFF00, display = true } -- Pazuzu m[96] = { color = 0xFFFFFFFF, display = true } -- Boota m[97] = { color = 0xFFFFFFFF, display = true } -- Za Boota m[98] = { color = 0xFFFFFFFF, display = true } -- Ba Boota m[99] = { color = 0xFFFFFFFF, display = true } -- Dorphon m[100] = { color = 0xFFFFFF00, display = true } -- Dorphon Eclair m[104] = { color = 0xFFFFFFFF, display = true } -- Sand Rappy m[105] = { color = 0xFFFFFF00, display = true } -- Del Rappy -- Desert m[91] = { color = 0xFFFFFFFF, display = true } -- Merissa A m[92] = { color = 0xFFFFFF00, display = true } -- Merissa AA m[93] = { color = 0xFFFFFFFF, display = true } -- Girtablulu m[101] = { color = 0xFFFFFFFF, display = true } -- Goran m[102] = { color = 0xFFFFFFFF, display = true } -- Goran Detonator m[103] = { color = 0xFFFFFFFF, display = true } -- Pyro Goran m[106] = { color = 0xFFFF0000, display = true } -- Saint-Milion m[107] = { color = 0xFFFF0000, display = true } -- Shambertin m[108] = { color = 0xFFFF8000, display = true } -- Kondrieu -- Other m[48] = { color = 0xFFFFFFFF, display = true } -- Container return { maxDistance = maxDistance, m = m, }
gpl-3.0
notcake/vfs
lua/vfs/adaptors/expression2_files.lua
1
5592
if not CLIENT then return end local commandQueue = {} local nextRunItem = 1 local function QueueConsoleCommand (...) commandQueue [#commandQueue + 1] = {...} if #commandQueue == 1 then timer.Create ("VFS.Adaptors.E2FileList", 0.1, 0, function () for i = 1, 10 do RunConsoleCommand (unpack (commandQueue [nextRunItem])) nextRunItem = nextRunItem + 1 if nextRunItem > #commandQueue then commandQueue = {} nextRunItem = 1 timer.Destroy ("VFS.Adaptors.E2FileList") break end end end) end end local upload_buffer = {} local upload_chunk_size = 200 local function upload_callback () if not upload_buffer or not upload_buffer.data then return end local chunk_size = math.Clamp (string.len (upload_buffer.data), 0, upload_chunk_size) local transmittedString = string.sub (upload_buffer.data, 1, chunk_size) local i = 0 while transmittedString:sub (-1, -1) == "%" or transmittedString:sub (-1, -1) == "." do i = i + 1 transmittedString = string.sub (upload_buffer.data, 1, chunk_size + i) end QueueConsoleCommand ("wire_expression2_file_chunk", transmittedString) upload_buffer.data = string.sub (upload_buffer.data, transmittedString:len () + 1, string.len (upload_buffer.data)) if upload_buffer.chunk >= upload_buffer.chunks then QueueConsoleCommand ("wire_expression2_file_finish") timer.Remove ("wire_expression2_file_upload") return end upload_buffer.chunk = upload_buffer.chunk + 1 end local function wire_expression2_request_file (filePath) if filePath:sub (-5, -1) == "\\.txt" then filePath = filePath:sub (1, -6) end VFS.Debug ("[VFS] expression2_files: request_file: " .. filePath) VFS.Root:GetChild (GAuth.GetLocalId (), filePath, function (returnCode, node) if returnCode == VFS.ReturnCode.Success then if node:IsFile () then node:Open (GAuth.GetLocalId (), VFS.OpenFlags.Read, function (returnCode, filestream) if returnCode == VFS.ReturnCode.Success then filestream:Read (filestream:GetLength (), function (returnCode, data) if returnCode == VFS.ReturnCode.Success then local encoded = E2Lib.encode (data) upload_buffer = { chunk = 1, chunks = math.ceil (string.len (encoded) / upload_chunk_size), data = encoded } QueueConsoleCommand ("wire_expression2_file_begin", "1", string.len (data)) timer.Create ("wire_expression2_file_upload", 1 / 60, upload_buffer.chunks, upload_callback) else filestream:Close () VFS.Debug ("[VFS] expression2_files: Cannot read " .. filePath .. " (" .. VFS.ReturnCode [returnCode] .. ")") QueueConsoleCommand ("wire_expression2_file_begin", "0") end end ) else VFS.Debug ("[VFS] expression2_files: Cannot open " .. filePath .. " (" .. VFS.ReturnCode [returnCode] .. ")") QueueConsoleCommand ("wire_expression2_file_begin", "0") end end ) else VFS.Debug ("[VFS] expression2_files: " .. filePath .. " is not a file!") QueueConsoleCommand ("wire_expression2_file_begin", "0") end else VFS.Debug ("[VFS] expression2_files: Error when resolving " .. filePath .. " (" .. VFS.ReturnCode [returnCode] .. ")") QueueConsoleCommand ("wire_expression2_file_begin", "0") end end ) end local function InstallFileSystemOverride () if not usermessage.GetTable () ["wire_expression2_request_file"] then GLib.CallDelayed (InstallFileSystemOverride) return end usermessage.GetTable () ["wire_expression2_request_file"] = { Function = function (umsg) local filePath = umsg:ReadString () GLib.CallDelayed ( function () wire_expression2_request_file (filePath) end ) end, PreArgs = {} } usermessage.GetTable () ["wire_expression2_request_file_sp"] = usermessage.GetTable () ["wire_expression2_request_file"] usermessage.GetTable () ["wire_expression2_request_list"] = { Function = function (umsg) local folderPath = umsg:ReadString () or "" VFS.Debug ("[VFS] expression2_files: request_list: " .. folderPath) VFS.Root:GetChild (GAuth.GetLocalId (), folderPath, function (returnCode, node) if returnCode == VFS.ReturnCode.Success then node:EnumerateChildren (GAuth.GetLocalId (), function (returnCode, node) if returnCode == VFS.ReturnCode.Success then if node:IsFolder () then QueueConsoleCommand ("wire_expression2_file_list", "1", E2Lib.encode (node:GetDisplayName () .. "/")) else QueueConsoleCommand ("wire_expression2_file_list", "1", E2Lib.encode (node:GetDisplayName ())) end elseif returnCode == VFS.ReturnCode.Finished then QueueConsoleCommand ("wire_expression2_file_list", "0") else VFS.Debug ("[VFS] expression2_files: Error when enumerating contents of " .. folderPath .. " (" .. VFS.ReturnCode [returnCode] .. ")") QueueConsoleCommand ("wire_expression2_file_list", "0") end end ) else VFS.Debug ("[VFS] expression2_files: Error when resolving folder " .. folderPath .. " (" .. VFS.ReturnCode [returnCode] .. ")") QueueConsoleCommand ("wire_expression2_file_list", "0") end end ) end, PreArgs = {} } end timer.Simple (1, InstallFileSystemOverride)
gpl-3.0
Benjji/wesnoth
data/ai/micro_ais/cas/ca_swarm_move.lua
26
2504
local H = wesnoth.require "lua/helper.lua" local AH = wesnoth.require "ai/lua/ai_helper.lua" local ca_swarm_move = {} function ca_swarm_move:evaluation(ai, cfg) local units = wesnoth.get_units { side = wesnoth.current.side } for _,unit in ipairs(units) do if (unit.moves > 0) then return cfg.ca_score end end return 0 end function ca_swarm_move:execution(ai, cfg) local enemy_distance = cfg.enemy_distance or 5 local vision_distance = cfg.vision_distance or 12 -- If no close enemies, swarm will move semi-randomly, staying close together, but away from enemies local all_units = wesnoth.get_units { side = wesnoth.current.side } local units, units_no_moves = {}, {} for _,unit in ipairs(all_units) do if (unit.moves > 0) then table.insert(units, unit) else table.insert(units_no_moves, unit) end end local enemies = wesnoth.get_units { { "filter_side", { { "enemy_of", {side = wesnoth.current.side } } } } } -- Pick one unit at random, swarm does not move systematically local unit = units[math.random(#units)] -- Find best place for that unit to move to local best_hex = AH.find_best_move(unit, function(x, y) local rating = 0 -- Only units within 'vision_distance' count for rejoining local close_units_no_moves = {} for _,unit_noMP in ipairs(units_no_moves) do if (H.distance_between(unit.x, unit.y, unit_noMP.x, unit_noMP.y) <= vision_distance) then table.insert(close_units_no_moves, unit_noMP) end end -- If all units on the side have moves left, simply go to a hex far away if (not close_units_no_moves[1]) then rating = rating + H.distance_between(x, y, unit.x, unit.y) else -- Otherwise, minimize distance from units that have already moved for _,close_unit in ipairs(close_units_no_moves) do rating = rating - H.distance_between(x, y, close_unit.x, close_unit.y) end end -- We also try to stay out of attack range of any enemy for _,enemy in ipairs(enemies) do local dist = H.distance_between(x, y, enemy.x, enemy.y) if (dist < enemy_distance) then rating = rating - (enemy_distance - dist) * 10. end end return rating end) AH.movefull_stopunit(ai, unit, best_hex) end return ca_swarm_move
gpl-2.0
bnetcc/darkstar
scripts/globals/spells/bluemagic/diamondhide.lua
5
1028
----------------------------------------- -- Spell: Diamondhide -- Gives party members within area of effect the effect of "Stoneskin" -- Spell cost: 99 MP -- Monster Type: Beastmen -- Spell Type: Magical (Earth) -- Blue Magic Points: 3 -- Stat Bonus: VIT+1 -- Level: 67 -- Casting Time: 7 seconds -- Recast Time: 1 minute 30 seconds -- 5 minutes -- -- Combos: None ----------------------------------------- require("scripts/globals/bluemagic"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local typeEffect = EFFECT_STONESKIN; local blueskill = caster:getSkillLevel(BLUE_SKILL); local power = ((blueskill)/3) *2; local duration = 300; if (target:addStatusEffect(typeEffect,power,0,duration) == false) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end; return typeEffect; end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Lower_Jeuno/npcs/Kurou-Morou.lua
5
5111
----------------------------------- -- Area: Lower Jeuno -- Starts and Finishes Quest: Your Crystal Ball & Never to return -- !pos -4 -6 -28 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,YOUR_CRYSTAL_BALL) == QUEST_ACCEPTED and trade:getItemCount() == 1) then if (trade:hasItemQty(557,1) == true) then player:startEvent(192); -- CS for ahriman lens trade; Trading the lens to Kurou-Morou is optional elseif (trade:hasItemQty(556,1) == true) then player:startEvent(196); -- Trade divination sphere, finish quest end elseif (player:getQuestStatus(JEUNO,NEVER_TO_RETURN) == QUEST_ACCEPTED and trade:hasItemQty(12507,1) == true and trade:getItemCount() == 1) then player:startEvent(203); -- Finish "Never to return" quest end end; function onTrigger(player,npc) -- printf("Ontrigger completed"); local YourCrystalBall = player:getQuestStatus(JEUNO,YOUR_CRYSTAL_BALL); local SearchingForTheRightWords = player:getQuestStatus(JEUNO,SEARCHING_FOR_THE_RIGHT_WORDS); local ACandlelightVigil = player:getQuestStatus(JEUNO,A_CANDLELIGHT_VIGIL); local RubbishDay = player:getQuestStatus(JEUNO,RUBBISH_DAY); local NeverToReturn = player:getQuestStatus(JEUNO,NEVER_TO_RETURN); local JFame = player:getFameLevel(JEUNO); local SearchingForWords_prereq = player:getVar("QuestSearchRightWords_prereq"); if (JFame >= 2 and YourCrystalBall == QUEST_AVAILABLE) then player:startEvent(194); -- Start "Your Crystal Ball" quest elseif (JFame >= 5 and YourCrystalBall == QUEST_COMPLETED and player:getQuestStatus(JEUNO,NEVER_TO_RETURN) == QUEST_AVAILABLE and player:getVar("QuestNeverToReturn_day") ~= VanadielDayOfTheYear()) then prog = player:getVar("QuestNeverToReturn_prog"); if (prog <= 2) then fortune = math.random(1,99); player:startEvent(204,fortune); -- Required to get fortune read 3x on 3 diff game days before quest is kicked off elseif (prog == 3) then player:startEvent(202); -- Start "Never to return" quest end --if searching for right words *prereq* CS has been activated elseif (SearchingForWords_prereq == 1) then player:startEvent(38); elseif (player:getVar("QuestSearchRightWords_denied") == 1) then player:startEvent(36); elseif (SearchingForTheRightWords == QUEST_ACCEPTED) then player:startEvent(39); elseif (player:getVar("SearchingForRightWords_postcs") == -2) then player:startEvent(154); elseif (SearchingForTheRightWords == QUEST_COMPLETED) then --final state, after all quests complete player:startEvent(37); --conditions for searching for the right words elseif (ACandlelightVigil == QUEST_COMPLETED and RubbishDay == QUEST_COMPLETED and NeverToReturn == QUEST_COMPLETED and SearchingForTheRightWords == QUEST_AVAILABLE) then player:startEvent(17); else player:startEvent(193); -- Standard dialog end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 194 and option == 0) then player:addQuest(JEUNO,YOUR_CRYSTAL_BALL); elseif (csid == 196) then player:addTitle(FORTUNETELLER_IN_TRAINING); player:addFame(JEUNO, 30); player:tradeComplete(trade); player:completeQuest(JEUNO,YOUR_CRYSTAL_BALL); elseif (csid == 204 and option == 0) then player:setVar("QuestNeverToReturn_prog", player:getVar("QuestNeverToReturn_prog") + 1); -- Keep track of how many times the players fortune has been read player:setVar("QuestNeverToReturn_day", VanadielDayOfTheYear()); -- new vanadiel day elseif (csid == 202 and option == 0) then player:addQuest(JEUNO,NEVER_TO_RETURN); player:setVar("QuestNeverToReturn_prog", 0); player:setVar("QuestNeverToReturn_day", 0); elseif (csid == 203) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13477); else player:addGil(GIL_RATE*1200); player:messageSpecial(GIL_OBTAINED,GIL_RATE*1200); player:addItem(13477); player:messageSpecial(ITEM_OBTAINED,13477); player:addFame(JEUNO, 30); player:tradeComplete(trade); player:completeQuest(JEUNO,NEVER_TO_RETURN); end elseif (csid == 17) then player:setVar("QuestSearchRightWords_prereq", 1); elseif (csid == 154) then player:setVar("SearchingForRightWords_postcs", -1); end end;
gpl-3.0
mrvigeo/uzzbot
plugins/plugins.lua
325
6164
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' 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' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == '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' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == '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' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!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, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
tehran980/Tele_MAXBOT
plugins/plugins.lua
325
6164
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' 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' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == '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' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == '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' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!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, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
TurkeyMan/premake-core
modules/vstudio/tests/sln2005/test_dependencies.lua
15
2331
-- -- tests/actions/vstudio/sln2005/test_dependencies.lua -- Validate generation of Visual Studio 2005+ solution project dependencies. -- Copyright (c) 2009-2012 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vstudio_sln2005_dependencies") local sln2005 = p.vstudio.sln2005 -- -- Setup -- local wks, prj1, prj2 function suite.setup() p.action.set("vs2005") wks, prj1 = test.createWorkspace() uuid "AE61726D-187C-E440-BD07-2556188A6565" prj2 = test.createproject(wks) uuid "2151E83B-997F-4A9D-955D-380157E88C31" prj3 = test.createproject(wks) uuid "CAA68162-8B96-11E1-8D5E-5885BBE59B18" links "MyProject" dependson "MyProject2" end local function prepare(language) prj1.language = language prj2.language = language prj2 = test.getproject(wks, 2) sln2005.projectdependencies(prj2) prj3.language = language prj3 = test.getproject(wks, 3) sln2005.projectdependencies(prj3) end -- -- Verify dependencies between C++ projects are listed. -- function suite.dependency_onCppProjects() prepare("C++") test.capture [[ ProjectSection(ProjectDependencies) = postProject {2151E83B-997F-4A9D-955D-380157E88C31} = {2151E83B-997F-4A9D-955D-380157E88C31} EndProjectSection ]] end -- -- Verify dependencies between C# projects are listed. -- function suite.dependency_onCSharpProjects() prepare("C#") test.capture [[ ProjectSection(ProjectDependencies) = postProject {2151E83B-997F-4A9D-955D-380157E88C31} = {2151E83B-997F-4A9D-955D-380157E88C31} EndProjectSection ]] end -- -- Most C# references should go into the project rather than the solution, -- but until I know the conditions, put everything here to be safe. -- function suite.dependency_onCSharpProjectsVs2010() p.action.set("vs2010") prepare("C#") test.capture [[ ProjectSection(ProjectDependencies) = postProject {2151E83B-997F-4A9D-955D-380157E88C31} = {2151E83B-997F-4A9D-955D-380157E88C31} EndProjectSection ]] end -- -- Verify dependencies between projects C# are listed for VS2012. -- function suite.dependency_onCSharpProjectsVs2012() p.action.set("vs2012") prepare("C#") test.capture [[ ProjectSection(ProjectDependencies) = postProject {2151E83B-997F-4A9D-955D-380157E88C31} = {2151E83B-997F-4A9D-955D-380157E88C31} EndProjectSection ]] end
bsd-3-clause
mwoz123/koreader
frontend/ui/widget/inputdialog.lua
1
33376
--[[-- Widget for taking user input. Example: local InputDialog = require("ui/widget/inputdialog") local @{ui.uimanager|UIManager} = require("ui/uimanager") local @{logger} = require("logger") local @{gettext|_} = require("gettext") local sample_input sample_input = InputDialog:new{ title = _("Dialog title"), input = "default value", -- A placeholder text shown in the text box. input_hint = _("Hint text"), input_type = "string", -- A description shown above the input. description = _("Some more description."), -- text_type = "password", buttons = { { { text = _("Cancel"), callback = function() UIManager:close(sample_input) end, }, { text = _("Save"), -- button with is_enter_default set to true will be -- triggered after user press the enter key from keyboard is_enter_default = true, callback = function() logger.dbg("Got user input as raw text:", sample_input:getInputText()) logger.dbg("Got user input as value:", sample_input:getInputValue()) end, }, } }, } UIManager:show(sample_input) sample_input:onShowKeyboard() To get a full screen text editor, use: fullscreen = true, -- No need to provide any height and width. condensed = true, allow_newline = true, cursor_at_end = false, -- and one of these: add_scroll_buttons = true, add_nav_bar = true, To add |Save|Close| buttons, use: save_callback = function(content, closing) -- ...Deal with the edited content... if closing then UIManager:nextTick( -- Stuff to do when InputDialog is closed, if anything. ) end return nil -- sucess, default notification shown return true, success_notif_text return false, error_infomsg_text end To additionally add a Reset button and have |Reset|Save|Close|, use: reset_callback = function() return original_content -- success return original_content, success_notif_text return nil, error_infomsg_text end If you don't need more buttons than these, use these options for consistency between dialogs, and don't provide any buttons. Text used on these buttons and their messages and notifications can be changed by providing alternative text with these additional options: reset_button_text save_button_text close_button_text close_unsaved_confirm_text close_cancel_button_text close_discard_button_text close_save_button_text close_discarded_notif_text If it would take the user more than half a minute to recover from a mistake, a "Cancel" button <em>must</em> be added to the dialog. The cancellation button should be kept on the left and the button executing the action on the right. It is strongly recommended to use a text describing the action to be executed, as demonstrated in the example above. If the resulting phrase would be longer than three words it should just read "OK". ]] local Blitbuffer = require("ffi/blitbuffer") local ButtonTable = require("ui/widget/buttontable") local CenterContainer = require("ui/widget/container/centercontainer") local Device = require("device") local Font = require("ui/font") local FrameContainer = require("ui/widget/container/framecontainer") local Geom = require("ui/geometry") local InfoMessage = require("ui/widget/infomessage") local InputContainer = require("ui/widget/container/inputcontainer") local InputText = require("ui/widget/inputtext") local LineWidget = require("ui/widget/linewidget") local MovableContainer = require("ui/widget/container/movablecontainer") local MultiConfirmBox = require("ui/widget/multiconfirmbox") local Notification = require("ui/widget/notification") local Size = require("ui/size") local TextBoxWidget = require("ui/widget/textboxwidget") local TextWidget = require("ui/widget/textwidget") local UIManager = require("ui/uimanager") local VerticalGroup = require("ui/widget/verticalgroup") local VerticalSpan = require("ui/widget/verticalspan") local Screen = Device.screen local T = require("ffi/util").template local _ = require("gettext") local InputDialog = InputContainer:new{ is_always_active = true, title = "", input = "", input_hint = "", description = nil, buttons = nil, input_type = nil, enter_callback = nil, readonly = false, -- don't allow editing, will not show keyboard allow_newline = false, -- allow entering new lines (this disables any enter_callback) cursor_at_end = true, -- starts with cursor at end of text, ready for appending fullscreen = false, -- adjust to full screen minus keyboard condensed = false, -- true will prevent adding air and balance between elements add_scroll_buttons = false, -- add scroll Up/Down buttons to first row of buttons add_nav_bar = false, -- append a row of page navigation buttons -- note that the text widget can be scrolled with Swipe North/South even when no button keyboard_hidden = false, -- start with keyboard hidden in full fullscreen mode -- needs add_nav_bar to have a Show keyboard button to get it back scroll_by_pan = false, -- allow scrolling by lines with Pan (= Swipe, but wait a bit at end -- of gesture before releasing) (may conflict with movable) -- If save_callback provided, a Save and a Close buttons will be added to the first row -- if reset_callback provided, a Reset button will be added (before Save) to the first row save_callback = nil, -- Called with the input text content when Save (and true as 2nd arg -- if closing, false if non-closing Save). -- Should return nil or true on success, false on failure. -- (This save_callback can do some syntax check before saving) reset_callback = nil, -- Called with no arg, should return the original content on success, -- nil on failure. -- Both these callbacks can return a string as a 2nd return value. -- This string is then shown: -- - on success: as the notification text instead of the default one -- - on failure: in an InfoMessage close_callback = nil, -- Called when closing (if discarded or saved, after save_callback if saved) edited_callback = nil, -- Called on each text modification -- For use by TextEditor plugin: view_pos_callback = nil, -- Called with no arg to get initial top_line_num/charpos, -- called with (top_line_num, charpos) to give back position on close. -- movable = true, -- set to false if movable gestures conflicts with subwidgets gestures -- for now, too much conflicts between InputText and MovableContainer, and -- there's the keyboard to exclude from move area (the InputDialog could -- be moved under the keyboard, and the user would be locked) movable = false, width = nil, text_width = nil, text_height = nil, title_face = Font:getFace("x_smalltfont"), description_face = Font:getFace("x_smallinfofont"), input_face = Font:getFace("x_smallinfofont"), title_padding = Size.padding.default, title_margin = Size.margin.title, desc_padding = Size.padding.default, -- Use the same as title for their desc_margin = Size.margin.title, -- texts to be visually aligned input_padding = Size.padding.default, input_margin = Size.margin.default, button_padding = Size.padding.default, border_size = Size.border.window, -- See TextBoxWidget for details about these options alignment = "left", justified = false, lang = nil, para_direction_rtl = nil, auto_para_direction = false, alignment_strict = false, -- for internal use _text_modified = false, -- previous known modified status _top_line_num = nil, _charpos = nil, _buttons_edit_callback = nil, _buttons_scroll_callback = nil, _buttons_backup_done = false, _buttons_backup = nil, } function InputDialog:init() if self.fullscreen then self.movable = false self.border_size = 0 self.width = Screen:getWidth() - 2*self.border_size self.covers_fullscreen = true -- hint for UIManager:_repaint() else self.width = self.width or math.floor(Screen:getWidth() * 0.8) end if self.condensed then self.text_width = self.width - 2*(self.border_size + self.input_padding + self.input_margin) else self.text_width = self.text_width or math.floor(self.width * 0.9) end if self.readonly then -- hide keyboard if we can't edit self.keyboard_hidden = true end -- Title & description self.title_widget = FrameContainer:new{ padding = self.title_padding, margin = self.title_margin, bordersize = 0, TextWidget:new{ text = self.title, face = self.title_face, max_width = self.width, } } self.title_bar = LineWidget:new{ dimen = Geom:new{ w = self.width, h = Size.line.thick, } } if self.description then self.description_widget = FrameContainer:new{ padding = self.desc_padding, margin = self.desc_margin, bordersize = 0, TextBoxWidget:new{ text = self.description, face = self.description_face, width = self.width - 2*self.desc_padding - 2*self.desc_margin, } } else self.description_widget = VerticalSpan:new{ width = 0 } end -- Vertical spaces added before and after InputText -- (these will be adjusted later to center the input text if needed) local vspan_before_input_text = VerticalSpan:new{ width = 0 } local vspan_after_input_text = VerticalSpan:new{ width = 0 } -- We add the same vertical space used under description after the input widget -- (can be disabled by setting condensed=true) if not self.condensed then local desc_pad_height = self.desc_margin + self.desc_padding if self.description then vspan_before_input_text.width = 0 -- already provided by description_widget vspan_after_input_text.width = desc_pad_height else vspan_before_input_text.width = desc_pad_height vspan_after_input_text.width = desc_pad_height end end -- Buttons -- In case of re-init(), keep backup of original buttons and restore them self:_backupRestoreButtons() -- If requested, add predefined buttons alongside provided ones if self.save_callback then -- If save_callback provided, adds (Reset) / Save / Close buttons self:_addSaveCloseButtons() end if self.add_nav_bar then -- Home / End / Up / Down buttons self:_addScrollButtons(true) elseif self.add_scroll_buttons then -- Up / Down buttons self:_addScrollButtons(false) end -- Buttons Table self.button_table = ButtonTable:new{ width = self.width - 2*self.button_padding, button_font_face = "cfont", button_font_size = 20, buttons = self.buttons, zero_sep = true, show_parent = self, } local buttons_container = CenterContainer:new{ dimen = Geom:new{ w = self.width, h = self.button_table:getSize().h, }, self.button_table, } -- Remember provided text_height if any (to restore it on keyboard height change) if self.orig_text_height == nil then if self.text_height then self.orig_text_height = self.text_height else self.orig_text_height = false end end -- InputText if not self.text_height or self.fullscreen then -- We need to find the best height to avoid screen overflow -- Create a dummy input widget to get some metrics local input_widget = InputText:new{ text = self.fullscreen and "-" or self.input, face = self.input_face, width = self.text_width, padding = self.input_padding, margin = self.input_margin, lang = self.lang, -- these might influence height para_direction_rtl = self.para_direction_rtl, auto_para_direction = self.auto_para_direction, for_measurement_only = true, -- flag it as a dummy, so it won't trigger any bogus repaint/refresh... } local text_height = input_widget:getTextHeight() local line_height = input_widget:getLineHeight() local input_pad_height = input_widget:getSize().h - text_height local keyboard_height = 0 if not self.keyboard_hidden then keyboard_height = input_widget:getKeyboardDimen().h end input_widget:onCloseWidget() -- free() textboxwidget and keyboard -- Find out available height local available_height = Screen:getHeight() - 2*self.border_size - self.title_widget:getSize().h - self.title_bar:getSize().h - self.description_widget:getSize().h - vspan_before_input_text:getSize().h - input_pad_height - vspan_after_input_text:getSize().h - buttons_container:getSize().h - keyboard_height if self.fullscreen or text_height > available_height then -- Don't leave unusable space in the text widget, as the user could think -- it's an empty line: move that space in pads after and below (for centering) self.text_height = math.floor(available_height / line_height) * line_height local pad_height = available_height - self.text_height local pad_before = math.ceil(pad_height / 2) local pad_after = pad_height - pad_before vspan_before_input_text.width = vspan_before_input_text.width + pad_before vspan_after_input_text.width = vspan_after_input_text.width + pad_after self.cursor_at_end = false -- stay at start if overflowed else -- Don't leave unusable space in the text widget self.text_height = text_height end end if self.view_pos_callback then -- Get initial cursor and top line num from callback -- (will work in case of re-init as these are saved by onClose() self._top_line_num, self._charpos = self.view_pos_callback() end self._input_widget = InputText:new{ text = self.input, hint = self.input_hint, face = self.input_face, alignment = self.alignment, justified = self.justified, lang = self.lang, para_direction_rtl = self.para_direction_rtl, auto_para_direction = self.auto_para_direction, alignment_strict = self.alignment_strict, width = self.text_width, height = self.text_height or nil, padding = self.input_padding, margin = self.input_margin, input_type = self.input_type, text_type = self.text_type, enter_callback = self.enter_callback or function() for _,btn_row in ipairs(self.buttons) do for _,btn in ipairs(btn_row) do if btn.is_enter_default then btn.callback() return end end end end, edit_callback = self._buttons_edit_callback, -- nil if no Save/Close buttons scroll_callback = self._buttons_scroll_callback, -- nil if no Nav or Scroll buttons scroll = true, scroll_by_pan = self.scroll_by_pan, cursor_at_end = self.cursor_at_end, readonly = self.readonly, parent = self, is_text_edited = self._text_modified, top_line_num = self._top_line_num, charpos = self._charpos, } if self.allow_newline then -- remove any enter_callback self._input_widget.enter_callback = nil end if Device:hasDPad() then --little hack to piggyback on the layout of the button_table to handle the new InputText table.insert(self.button_table.layout, 1, {self._input_widget}) end -- Complementary setup for some of our added buttons if self.save_callback then local save_button = self.button_table:getButtonById("save") if self.readonly then save_button:setText(_("Read only"), save_button.width) elseif not self._input_widget:isTextEditable() then save_button:setText(_("Not editable"), save_button.width) end end -- Final widget self.dialog_frame = FrameContainer:new{ radius = self.fullscreen and 0 or Size.radius.window, padding = 0, margin = 0, bordersize = self.border_size, background = Blitbuffer.COLOR_WHITE, VerticalGroup:new{ align = "left", self.title_widget, self.title_bar, self.description_widget, vspan_before_input_text, CenterContainer:new{ dimen = Geom:new{ w = self.width, h = self._input_widget:getSize().h, }, self._input_widget, }, vspan_after_input_text, buttons_container, } } local frame = self.dialog_frame if self.movable then frame = MovableContainer:new{ self.dialog_frame, } end local keyboard_height = self.keyboard_hidden and 0 or self._input_widget:getKeyboardDimen().h self[1] = CenterContainer:new{ dimen = Geom:new{ w = Screen:getWidth(), h = Screen:getHeight() - keyboard_height, }, frame } end function InputDialog:getInputText() return self._input_widget:getText() end function InputDialog:getInputValue() local text = self:getInputText() if self.input_type == "number" then return tonumber(text) else return text end end function InputDialog:setInputText(text, edited_state) self._input_widget:setText(text) if edited_state ~= nil and self._buttons_edit_callback then self._buttons_edit_callback(edited_state) end end function InputDialog:isTextEditable() return self._input_widget:isTextEditable() end function InputDialog:isTextEdited() return self._input_widget:isTextEdited() end function InputDialog:onShow() UIManager:setDirty(self, function() return "ui", self.dialog_frame.dimen end) end function InputDialog:onCloseWidget() self:onClose() UIManager:setDirty(nil, self.fullscreen and "full" or function() return "ui", self.dialog_frame.dimen end) end function InputDialog:onShowKeyboard(ignore_first_hold_release) if not self.readonly and not self.keyboard_hidden then self._input_widget:onShowKeyboard(ignore_first_hold_release) end end function InputDialog:onKeyboardHeightChanged() self.input = self:getInputText() -- re-init with up-to-date text self:onClose() -- will close keyboard and save view position self._input_widget:onCloseWidget() -- proper cleanup of InputText and its keyboard self:free() -- Restore original text_height (or reset it if none to force recomputing it) self.text_height = self.orig_text_height or nil self:init() if not self.keyboard_hidden then self:onShowKeyboard() end -- Our position on screen has probably changed, so have the full screen refreshed UIManager:setDirty("all", "flashui") end function InputDialog:onClose() -- Remember current view & position in case of re-init self._top_line_num = self._input_widget.top_line_num self._charpos = self._input_widget.charpos if self.view_pos_callback then -- Give back top line num and cursor position self.view_pos_callback(self._top_line_num, self._charpos) end self._input_widget:onCloseKeyboard() end function InputDialog:refreshButtons() -- Using what ought to be enough: -- return "ui", self.button_table.dimen -- causes 2 non-intersecting refreshes (because if our buttons -- change, the text widget did) that may sometimes cause -- the button_table to become white. -- Safer to refresh the whole widget so the refreshes can -- be merged into one. UIManager:setDirty(self, function() return "ui", self.dialog_frame.dimen end) end function InputDialog:_backupRestoreButtons() -- In case of re-init(), keep backup of original buttons and restore them if self._buttons_backup_done then -- Move backup and override current, and re-create backup from original, -- to avoid duplicating the copy code) self.buttons = self._buttons_backup -- restore (we may restore 'nil') end if self.buttons then -- (re-)create backup self._buttons_backup = {} -- deep copy, except for the buttons themselves for i, row in ipairs(self.buttons) do if row then local row_copy = {} self._buttons_backup[i] = row_copy for j, b in ipairs(row) do row_copy[j] = b end end end end self._buttons_backup_done = true end function InputDialog:_addSaveCloseButtons() if not self.buttons then self.buttons = {{}} end -- Add them to the end of first row local row = self.buttons[1] local button = function(id) -- shortcut for more readable code return self.button_table:getButtonById(id) end -- Callback to enable/disable Reset/Save buttons, for feedback when text modified self._buttons_edit_callback = function(edited) if self._text_modified and not edited then self._text_modified = false button("save"):disable() if button("reset") then button("reset"):disable() end self:refreshButtons() elseif edited and not self._text_modified then self._text_modified = true button("save"):enable() if button("reset") then button("reset"):enable() end self:refreshButtons() end if self.edited_callback then self.edited_callback() end end if self.reset_callback then -- if reset_callback provided, add button to restore -- test to some previous state table.insert(row, { text = self.reset_button_text or _("Reset"), id = "reset", enabled = self._text_modified, callback = function() -- Wrapped via Trapper, to allow reset_callback to use Trapper -- to show progress or ask questions while getting original content require("ui/trapper"):wrap(function() local content, msg = self.reset_callback() if content then self:setInputText(content) self._buttons_edit_callback(false) UIManager:show(Notification:new{ text = msg or _("Text reset"), }) else -- nil content, assume failure and show msg if msg ~= false then -- false allows for no InfoMessage UIManager:show(InfoMessage:new{ text = msg or _("Resetting failed."), }) end end end) end, }) end table.insert(row, { text = self.save_button_text or _("Save"), id = "save", enabled = self._text_modified, callback = function() -- Wrapped via Trapper, to allow save_callback to use Trapper -- to show progress or ask questions while saving require("ui/trapper"):wrap(function() if self._text_modified then local success, msg = self.save_callback(self:getInputText()) if success == false then if msg ~= false then -- false allows for no InfoMessage UIManager:show(InfoMessage:new{ text = msg or _("Saving failed."), }) end else -- nil or true self._buttons_edit_callback(false) UIManager:show(Notification:new{ text = msg or _("Saved"), }) end end end) end, }) table.insert(row, { text = self.close_button_text or _("Close"), id = "close", callback = function() if self._text_modified then UIManager:show(MultiConfirmBox:new{ text = self.close_unsaved_confirm_text or _("You have unsaved changes."), cancel_text = self.close_cancel_button_text or _("Cancel"), choice1_text = self.close_discard_button_text or _("Discard"), choice1_callback = function() if self.close_callback then self.close_callback() end UIManager:close(self) UIManager:show(Notification:new{ text = self.close_discarded_notif_text or _("Changes discarded"), }) end, choice2_text = self.close_save_button_text or _("Save"), choice2_callback = function() -- Wrapped via Trapper, to allow save_callback to use Trapper -- to show progress or ask questions while saving require("ui/trapper"):wrap(function() local success, msg = self.save_callback(self:getInputText(), true) if success == false then if msg ~= false then -- false allows for no InfoMessage UIManager:show(InfoMessage:new{ text = msg or _("Saving failed."), }) end else -- nil or true if self.close_callback then self.close_callback() end UIManager:close(self) UIManager:show(Notification:new{ text = msg or _("Saved"), }) end end) end, }) else -- Not modified, exit without any message if self.close_callback then self.close_callback() end UIManager:close(self) end end, }) end function InputDialog:_addScrollButtons(nav_bar) local row if nav_bar then -- Add Home / End / Up / Down buttons as a last row if not self.buttons then self.buttons = {} end row = {} -- Empty additional buttons row table.insert(self.buttons, row) else -- Add the Up / Down buttons to the first row if not self.buttons then self.buttons = {{}} end row = self.buttons[1] end if nav_bar then -- Add the Home & End buttons -- Also add Keyboard hide/show button if we can if self.fullscreen and not self.readonly then table.insert(row, { text = self.keyboard_hidden and "↑⌨" or "↓⌨", id = "keyboard", callback = function() self.keyboard_hidden = not self.keyboard_hidden self.input = self:getInputText() -- re-init with up-to-date text self:onClose() -- will close keyboard and save view position self:free() self:init() if not self.keyboard_hidden then self:onShowKeyboard() end end, }) end -- Add a button to go to the line by its number in the file if self.fullscreen then table.insert(row, { text = _("Go"), callback = function() local cur_line_num, last_line_num = self._input_widget:getLineNums() local input_dialog input_dialog = InputDialog:new{ title = _("Enter line number"), -- @translators %1 is the current line number, %2 is the last line number input_hint = T(_("%1 (1 - %2)"), cur_line_num, last_line_num), input_type = "number", stop_events_propagation = true, -- avoid interactions with upper InputDialog buttons = { { { text = _("Cancel"), callback = function() UIManager:close(input_dialog) end, }, { text = _("Go to line"), is_enter_default = true, callback = function() local new_line_num = tonumber(input_dialog:getInputText()) if new_line_num and new_line_num >= 1 and new_line_num <= last_line_num then UIManager:close(input_dialog) self._input_widget:moveCursorToCharPos(self._input_widget:getLineCharPos(new_line_num)) end end, }, }, }, } UIManager:show(input_dialog) input_dialog:onShowKeyboard() end, }) end table.insert(row, { text = "⇱", id = "top", vsync = true, callback = function() self._input_widget:scrollToTop() end, }) table.insert(row, { text = "⇲", id = "bottom", vsync = true, callback = function() self._input_widget:scrollToBottom() end, }) end -- Add the Up & Down buttons table.insert(row, { text = "△", id = "up", callback = function() self._input_widget:scrollUp() end, }) table.insert(row, { text = "▽", id = "down", callback = function() self._input_widget:scrollDown() end, }) -- Callback to enable/disable buttons, for at-top/at-bottom feedback local prev_at_top = false -- Buttons were created enabled local prev_at_bottom = false local button = function(id) -- shortcut for more readable code return self.button_table:getButtonById(id) end self._buttons_scroll_callback = function(low, high) local changed = false if prev_at_top and low > 0 then button("up"):enable() if button("top") then button("top"):enable() end prev_at_top = false changed = true elseif not prev_at_top and low <= 0 then button("up"):disable() if button("top") then button("top"):disable() end prev_at_top = true changed = true end if prev_at_bottom and high < 1 then button("down"):enable() if button("bottom") then button("bottom"):enable() end prev_at_bottom = false changed = true elseif not prev_at_bottom and high >= 1 then button("down"):disable() if button("bottom") then button("bottom"):disable() end prev_at_bottom = true changed = true end if changed then self:refreshButtons() end end end return InputDialog
agpl-3.0
bnetcc/darkstar
scripts/zones/Waughroon_Shrine/npcs/Burning_Circle.lua
8
2249
----------------------------------- -- Area: Waughroon Shrine -- NPC: Burning Circle -- Waughroon Shrine Burning Circle -- !pos -345 104 -260 144 ------------------------------------- package.loaded["scripts/zones/Waughroon_Shrine/TextIDs"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Waughroon_Shrine/TextIDs"); ---- 0: Rank 2 Final Mission for Bastok "The Emissary" and Sandy "Journey Abroad" ---- 1: Worms Turn ---- 2: Grimshell Shocktroopers ---- 3: On my Way ---- 4: Thief in Norg ---- 5: 3, 2, 1 ---- 6: Shattering Stars (RDM) ---- 7: Shattering Stars (THF) ---- 8: Shattering Stars (BST) ---- 9: Birds of the feather ---- 10: Crustacean Conundrum ---- 11: Grove Gardians ---- 12: The Hills are alive ---- 13: Royal Jelly ---- 14: The Final Bout ---- 15: Up in arms ---- 16: Copy Cat ---- 17: Operation Desert Swarm ---- 18: Prehistoric Pigeons ---- 19: The Palborough Project ---- 20: Shell Shocked ---- 21: Beyond infinity ----------------------------------- -- 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; 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
farshadfaza/newpermag
plugins/lock-fosh.lua
1
2300
local function pre_process(msg) local chkfosh = redis:hget('settings:fosh',msg.chat_id_) if not chkfosh then redis:hset('settings:fosh',msg.chat_id_,'off') end end local function run(msg, matches) --Commands --دستورات فعال و غیرفعال کردن فحش if matches[1]:lower() == 'unlock' then if matches[2]:lower() == 'fosh' then if not is_mod(msg) then return end local fosh = redis:hget('settings:fosh',msg.chat_id_) if fosh == 'on' then redis:hset('settings:fosh',msg.chat_id_,'off') return '' elseif fosh == 'off' then return '' end end end if matches[1]:lower() == 'lock' then if matches[2]:lower() == 'fosh' then if not is_mod(msg) then return end local fosh = redis:hget('settings:fosh',msg.chat_id_) if fosh == 'off' then redis:hset('settings:fosh',msg.chat_id_,'on') return '' elseif fosh == 'on' then return '' end end end --Delete words contains --حذف پیامهای فحش if not is_mod(msg) then local fosh = redis:hget('settings:fosh',msg.chat_id_) if fosh == 'on' then tdcli.deleteMessages(msg.chat_id_, {[0] = msg.id_}, dl_cb, nil) end end end return { patterns = { "(ک*س)$", "کیر", "کص", "کــــــــــیر", "کــــــــــــــــــــــــــــــیر", "کـیـــــــــــــــــــــــــــــــــــــــــــــــــــر", "ک×یر", "ک÷یر", "ک*ص", "کــــــــــیرر", "kir", "kos", "گوساله", "gosale", "gusale", "جاکش", "قرمساق", "دیوس", "دیوص", "dayus", "dayos", "dayu3", "10yus", "10yu3", "daus", "dau3", "تخمی", "حرومزاده", "حروم زاده", "harumzade", "haromzade", "haroomzade", "lashi", "لاشی", "لاشي", "جنده", "jende", "tokhmi", "madarjende", "kharkosde", "خارکسده", "خوارکسده", "خارکصده", "خوارکصده", "kharko3de", "مادرجنده", --Commands ##Don't change this## "^[!/#]([Ll][Oo][Cc][Kk]) (.*)$", "^[!/#]([Uu][Nn][Ll][Oo][Cc][Kk]) (.*)$", ------------End---------------- }, run = run, pre_process = pre_process } -- ادیت توسط : -- @ninjatem -- @farshadfarokh -- @akambagroxxx -- @ninjahacker
gpl-3.0
lzubiaur/ini.lua
ini.lua
2
3991
-- Copyright (c) 2015 Laurent Zubiaur -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to deal -- in the Software without restriction, including without limitation the rights -- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -- copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -- THE SOFTWARE. -- See README.md for the documentation and examples local lpeg = require 'lpeg' lpeg.locale(lpeg) -- adds locale entries into 'lpeg' table -- The module local ini = {} ini.config = function(t) -- Config parameters local sc = t.separator or '=' -- Separator character local cc = t.comment or ';#' -- Comment characters local trim = t.trim == nil and true or t.trim -- Should capture or trim white spaces local lc = t.lowercase == nil and false or t.lowercase -- Should keys be lowercase? local escape = t.escape == nil and true or t.escape -- Should string literals used escape sequences? -- LPeg shortcut local P = lpeg.P -- Pattern local R = lpeg.R -- Range local S = lpeg.S -- String local V = lpeg.V -- Variable local C = lpeg.C -- Capture local Cf = lpeg.Cf -- Capture floding local Cc = lpeg.Cc -- Constant capture local Ct = lpeg.Ct -- Table capture local Cg = lpeg.Cg -- Group capture local Cs = lpeg.Cs -- Capture String (replace) local space = lpeg.space -- include tab and new line (\n) local alpha = lpeg.alpha local digit = lpeg.digit local any = P(1) local _alpha = P('_') + alpha -- underscore or alpha character local keyid = _alpha^1 * (_alpha + digit)^0 -- Lua escape sequences (http://www.lua.org/pil/2.4.html) if escape then any = any - P'\\a' + P'\\a'/'\a' -- bell - P'\\n' + P'\\n'/'\n' -- newline - P'\\r' + P'\\r'/'\r' -- carriage return - P'\\t' + P'\\t'/'\t' -- horizontal tab - P'\\f' + P'\\f'/'\f' -- form feed - P'\\b' + P'\\b'/'\b' -- back space - P'\\v' + P'\\v'/'\v' -- vertical tab - P'\\\\' + P'\\\\'/'\\' -- backslash end ini.grammar = P{ 'all'; key = not lc and C(keyid) * space^0 or Cs(keyid / function(s) return s:lower() end) * space^0, sep = P(sc), cr = P'\n' + P'\r\n', comment = S(cc)^1 * lpeg.print^0, string = space^0 * P'"' * Cs((any - P'"' + P'""'/'"')^0) * P'"' * space^0, value = trim and space^0 * C(((space - '\n')^0 * (any - space)^1)^1) * space^0 or C((any - P'\n') ^1), set = Cg(V'key' * V'sep' * (V'string' + V'value')), line = space^0 * (V'comment' + V'set'), body = Cf(Ct'' * (V'cr' + V'line')^0, rawset), label = P'[' * space^0 * V'key' * space^0 * P']' * space^0, -- the section label section = space^0 * Cg(V'label' * V'body'), sections = V'section' * (V'cr' + V'section')^0, all = Cf(Ct'' * ((V'cr' + V'line')^0 * V'sections'^0), rawset) * (V'cr' + -1), -- lines followed by a line return or end of string } end ini.parse = function(data) if type(data) == 'string' then return lpeg.match(ini.grammar, data) end return {} end ini.parse_file = function(filename) local f = assert(io.open(filename, "r")) local t = ini.parse(f:read('*all')) f:close() return t end -- Use default settings ini.config{} return ini
mit
bnetcc/darkstar
scripts/zones/Promyvion-Vahzl/npcs/_0md.lua
7
1058
----------------------------------- -- Area: Promyvion vahzl -- NPC: Memory flux (2) ----------------------------------- package.loaded["scripts/zones/Promyvion-Vahzl/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Promyvion-Vahzl/TextIDs"); require("scripts/zones/Promyvion-Vahzl/MobIDs"); require("scripts/globals/missions"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==3 and not GetMobByID(SOLICITOR):isSpawned()) then SpawnMob(SOLICITOR):updateClaim(player); elseif (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==4) then player:startEvent(52); else player:messageSpecial(OVERFLOWING_MEMORIES); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 52) then player:setVar("PromathiaStatus",5); end end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Port_Windurst/npcs/Kohlo-Lakolo.lua
5
10978
----------------------------------- -- Area: Port Windurst -- NPC: Kohlo-Lakolo -- Invloved In Quests: Truth, Justice, and the Onion Way!, -- Know One's Onions, -- Inspector's Gadget, -- Onion Rings, -- Crying Over Onions, -- Wild Card, -- The Promise ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS); if (KnowOnesOnions == QUEST_ACCEPTED) then count = trade:getItemCount(); WildOnion = trade:hasItemQty(4387,4); if (WildOnion == true and count == 4) then player:startEvent(398,0,4387); end elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then count = trade:getItemCount(); RarabTail = trade:hasItemQty(4444,1); if (RarabTail == true and count == 1) then player:startEvent(378,0,4444); end end end; function onTrigger(player,npc) TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS); InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET); OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS); CryingOverOnions = player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS); WildCard = player:getQuestStatus(WINDURST,WILD_CARD); ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE); NeedToZone = player:needToZone(); Level = player:getMainLvl(); Fame = player:getFameLevel(WINDURST); if (ThePromise == QUEST_COMPLETED) then player:startEvent(544); elseif (ThePromise == QUEST_ACCEPTED) then InvisibleManSticker = player:hasKeyItem(INVISIBLE_MAN_STICKER); if (InvisibleManSticker == true) then ThePromiseCS_Seen = player:getVar("ThePromiseCS_Seen"); if (ThePromiseCS_Seen == 1) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:completeQuest(WINDURST,THE_PROMISE); player:addFame(WINDURST,150); player:delKeyItem(INVISIBLE_MAN_STICKER); player:addItem(13135); player:messageSpecial(ITEM_OBTAINED,13135); player:setVar("ThePromise",0); player:setVar("ThePromiseCS_Seen",0); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13135); end else player:startEvent(522,0,INVISIBLE_MAN_STICKER); end else player:startEvent(514); end elseif (WildCard == QUEST_COMPLETED) then player:startEvent(513,0,INVISIBLE_MAN_STICKER); elseif (WildCard == QUEST_ACCEPTED) then WildCardVar = player:getVar("WildCard"); if (WildCardVar == 0) then player:setVar("WildCard",1); end player:showText(npc,KOHLO_LAKOLO_DIALOG_A); elseif (CryingOverOnions == QUEST_COMPLETED) then player:startEvent(505); elseif (CryingOverOnions == QUEST_ACCEPTED) then CryingOverOnionsVar = player:getVar("CryingOverOnions"); if (CryingOverOnionsVar == 3) then player:startEvent(512); elseif (CryingOverOnionsVar == 2) then player:startEvent(497); else player:startEvent(498); end elseif (OnionRings == QUEST_COMPLETED) then if (NeedToZone == false and Fame >= 5) then player:startEvent(496); else player:startEvent(440); end elseif (OnionRings == QUEST_ACCEPTED) then OldRing = player:hasKeyItem(OLD_RING); if (OldRing == true) then OnionRingsTime = player:getVar("OnionRingsTime"); CurrentTime = os.time(); if (CurrentTime >= OnionRingsTime) then player:startEvent(433); else player:startEvent(431); end end elseif (InspectorsGadget == QUEST_COMPLETED) then if (NeedToZone == false and Fame >= 3) then OldRing = player:hasKeyItem(OLD_RING); if (OldRing == true) then OnionRingsVar = player:getVar("OnionRings"); if (OnionRingsVar == 1) then player:startEvent(430,0,OLD_RING); else player:startEvent(432,0,OLD_RING); end else player:startEvent(429); end else player:startEvent(422); end elseif (InspectorsGadget == QUEST_ACCEPTED) then FakeMoustache = player:hasKeyItem(FAKE_MOUSTACHE); if (FakeMoustache == true) then player:startEvent(421); else player:startEvent(414); end elseif (KnowOnesOnions == QUEST_COMPLETED) then if (NeedToZone == false and Fame >= 2) then player:startEvent(413); else player:startEvent(401); end elseif (KnowOnesOnions == QUEST_ACCEPTED) then KnowOnesOnionsVar = player:getVar("KnowOnesOnions"); KnowOnesOnionsTime = player:getVar("KnowOnesOnionsTime"); CurrentTime = os.time(); if (KnowOnesOnionsVar == 2) then player:startEvent(400); elseif (KnowOnesOnionsVar == 1 and CurrentTime >= KnowOnesOnionsTime) then player:startEvent(386); elseif (KnowOnesOnionsVar == 1) then player:startEvent(399,0,4387); else player:startEvent(392,0,4387); end elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then if (NeedToZone == false and Level >= 5) then player:startEvent(391,0,4387); else player:startEvent(379); end elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then player:startEvent(371); elseif (TruthJusticeOnionWay == QUEST_AVAILABLE) then player:startEvent(368); else player:startEvent(361); end end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 368 and option == 0) then player:addQuest(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); elseif (csid == 378) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:completeQuest(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); player:addFame(WINDURST,75); player:addTitle(STAR_ONION_BRIGADE_MEMBER); player:tradeComplete(); player:addItem(13093); player:messageSpecial(ITEM_OBTAINED,13093); player:needToZone(true); else player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,13093); end elseif (csid == 391) then player:addQuest(WINDURST,KNOW_ONE_S_ONIONS); elseif (csid == 398) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then TradeTime = os.time(); player:tradeComplete(); player:addItem(4857); player:messageSpecial(ITEM_OBTAINED,4857); player:setVar("KnowOnesOnions",1); player:setVar("KnowOnesOnionsTime", TradeTime + 86400); else player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,4857); end elseif (csid == 386 or csid == 400) then player:completeQuest(WINDURST,KNOW_ONE_S_ONIONS); player:addFame(WINDURST,80); player:addTitle(SOB_SUPER_HERO); player:setVar("KnowOnesOnions",0); player:setVar("KnowOnesOnionsTime",0); player:needToZone(true); elseif (csid == 413 and option == 0) then player:addQuest(WINDURST,INSPECTOR_S_GADGET); elseif (csid == 421) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:completeQuest(WINDURST,INSPECTOR_S_GADGET); player:addFame(WINDURST,90); player:addTitle(FAKEMOUSTACHED_INVESTIGATOR); player:addItem(13204); player:messageSpecial(ITEM_OBTAINED,13204); player:needToZone(true); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13204); end elseif (csid == 429) then player:setVar("OnionRings",1); elseif (csid == 430) then OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS); if (OnionRings == QUEST_AVAILABLE) then CurrentTime = os.time(); player:addQuest(WINDURST,ONION_RINGS); player:setVar("OnionRingsTime", CurrentTime + 86400); end elseif (csid == 432 or csid == 433) then player:completeQuest(WINDURST,ONION_RINGS); player:addFame(WINDURST,100); player:addTitle(STAR_ONION_BRIGADIER); player:delKeyItem(OLD_RING); player:setVar("OnionRingsTime",0); player:needToZone(true); elseif (csid == 440) then OnionRingsVar = player:getVar("OnionRings"); NeedToZone = player:getVar("NeedToZone"); if (OnionRingsVar == 2 and NeedToZone == 0) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:setVar("OnionRings",0); player:addItem(17029); player:messageSpecial(ITEM_OBTAINED,17029); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17029); end end elseif (csid == 496) then player:addQuest(WINDURST,CRYING_OVER_ONIONS); elseif (csid == 497) then player:setVar("CryingOverOnions",3); elseif (csid == 513) then player:addQuest(WINDURST,THE_PROMISE); elseif (csid == 522) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:completeQuest(WINDURST,THE_PROMISE); player:addFame(WINDURST,150); player:delKeyItem(INVISIBLE_MAN_STICKER); player:addItem(13135); player:messageSpecial(ITEM_OBTAINED,13135); player:setVar("ThePromise",0); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13135); player:setVar("ThePromiseCS_Seen",1); end end end;
gpl-3.0
bnetcc/darkstar
scripts/globals/spells/raptor_mazurka.lua
5
1131
----------------------------------------- -- Spell: Raptor Mazurka -- Gives party members enhanced movement ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local power = 12; local iBoost = caster:getMod(MOD_MAZURKA_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then duration = duration * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then duration = duration * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MAZURKA,power,0,duration,caster:getID(), 0, 1)) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end return EFFECT_MAZURKA; end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Windurst_Waters/npcs/Kirarara.lua
5
1036
----------------------------------- -- Area: Windurst Waters -- NPC: Kirarara -- Involved in Quest: Making the Grade -- !pos 132 -7 172 238 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/titles"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then player:startEvent(447); -- During Making the GRADE else player:startEvent(425); -- Standard conversation end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
younishd/chick
lib/coxpcall/coxpcall.lua
1
3534
------------------------------------------------------------------------------- -- Coroutine safe xpcall and pcall versions -- -- Encapsulates the protected calls with a coroutine based loop, so errors can -- be dealed without the usual Lua 5.x pcall/xpcall issues with coroutines -- yielding inside the call to pcall or xpcall. -- -- Authors: Roberto Ierusalimschy and Andre Carregal -- Contributors: Thomas Harning Jr., Ignacio Burgueño, Fabio Mascarenhas -- -- Copyright 2005 - Kepler Project -- -- $Id: coxpcall.lua,v 1.13 2008/05/19 19:20:02 mascarenhas Exp $ ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- Checks if (x)pcall function is coroutine safe ------------------------------------------------------------------------------- local function isCoroutineSafe(func) local co = coroutine.create(function() return func(coroutine.yield, function() end) end) coroutine.resume(co) return coroutine.resume(co) end -- No need to do anything if pcall and xpcall are already safe. if isCoroutineSafe(pcall) and isCoroutineSafe(xpcall) then copcall = pcall coxpcall = xpcall return { pcall = pcall, xpcall = xpcall, running = coroutine.running } end ------------------------------------------------------------------------------- -- Implements xpcall with coroutines ------------------------------------------------------------------------------- local performResume, handleReturnValue local oldpcall, oldxpcall = pcall, xpcall local pack = table.pack or function(...) return {n = select("#", ...), ...} end local unpack = table.unpack or unpack local running = coroutine.running local coromap = setmetatable({}, { __mode = "k" }) function handleReturnValue(err, co, status, ...) if not status then return false, err(debug.traceback(co, (...)), ...) end if coroutine.status(co) == 'suspended' then return performResume(err, co, coroutine.yield(...)) else return true, ... end end function performResume(err, co, ...) return handleReturnValue(err, co, coroutine.resume(co, ...)) end local function id(trace, ...) return trace end function coxpcall(f, err, ...) local current = running() if not current then if err == id then return oldpcall(f, ...) else if select("#", ...) > 0 then local oldf, params = f, pack(...) f = function() return oldf(unpack(params, 1, params.n)) end end return oldxpcall(f, err) end else local res, co = oldpcall(coroutine.create, f) if not res then local newf = function(...) return f(...) end co = coroutine.create(newf) end coromap[co] = current return performResume(err, co, ...) end end local function corunning(coro) if coro ~= nil then assert(type(coro)=="thread", "Bad argument; expected thread, got: "..type(coro)) else coro = running() end while coromap[coro] do coro = coromap[coro] end if coro == "mainthread" then return nil end return coro end ------------------------------------------------------------------------------- -- Implements pcall with coroutines ------------------------------------------------------------------------------- function copcall(f, ...) return coxpcall(f, id, ...) end return { pcall = copcall, xpcall = coxpcall, running = corunning }
mit
mwoz123/koreader
frontend/ui/data/dictionaries.lua
6
52775
local _ = require("gettext") -- largely thanks to https://tuxor1337.github.io/firedict/dictionaries.html local dictionaries = { { name = "CIA World Factbook 2014", lang_in = "English", lang_out = "English", entries = 2577, license = _("Public Domain"), url = "http://build.koreader.rocks/download/dict/factbook.tar.gz", }, { name = "GNU Collaborative International Dictionary of English", lang_in = "English", lang_out = "English", entries = 108121, license = "GPLv3+", url = "http://build.koreader.rocks/download/dict/gcide.tar.gz", }, { name = "Douglas Harper's Online Etymology Dictionary", lang_in = "English", lang_out = "English", entries = 46133, license = "Unknown/©Douglas Harper", url = "https://gitlab.com/koreader/stardict-dictionaries/uploads/ce281fd8b5e83751d5c7b82d1e07a663/etymonline.tar.gz", }, { name = "Folkets lexikon", lang_in = "English", lang_out = "Swedish", entries = 53618, license = "CC-BY-SA 2.5", url = "https://gitlab.com/koreader/stardict-dictionaries/uploads/619cbab2537b4d115d5503cdd023ce05/folkets_en-sv.tar.gz", }, { name = "Folkets lexikon", lang_in = "Swedish", lang_out = "English", entries = 36513, license = "CC-BY-SA 2.5", url = "https://gitlab.com/koreader/stardict-dictionaries/uploads/53a0a9fea8cab8661cf930ddd2353a4c/folkets_sv-en.tar.gz", }, { name = "Dictionnaire Littré (xmlittre)", lang_in = "French", lang_out = "French", entries = 78428, license = "CC-BY-SA 3.0", url = "http://http.debian.net/debian/pool/main/s/stardict-xmlittre/stardict-xmlittre_1.0.orig.tar.gz", }, { name = "Dictionnaire de l'Académie Française: 8ème edition", lang_in = "French", lang_out = "French", entries = 31934, license = _("Public Domain (copyright expired, published 1935)"), url = "https://gitlab.com/koreader/stardict-dictionaries/uploads/b8e8ba6b8941a78762675ff2ef95d1d1/acadfran.tar.gz", }, { name = "Pape: Handwörterbuch der griechischen Sprache", lang_in = "Ancient Greek", lang_out = "German", entries = 98893, license = _("Public Domain (copyright expired, published 1880)"), url = "http://build.koreader.rocks/download/dict/pape_gr-de.tar.gz", }, { name = "Georges: Ausführliches lateinisch-deutsches Handwörterbuch", lang_in = "Latin", lang_out = "German", entries = 54831, license = _("Public Domain (copyright expired, published 1913)"), url = "https://gitlab.com/koreader/stardict-dictionaries/uploads/6339585b68ac485bedb8ee67892cb974/georges_lat-de.tar.gz", }, { name = "Georges: Kleines deutsch-lateinisches Handwörterbuch", lang_in = "German", lang_out = "Latin", entries = 26608, license = _("Public Domain (copyright expired, published 1910)"), url = "https://gitlab.com/koreader/stardict-dictionaries/uploads/a04de66c7376e436913ca288a3ca608b/georges_de-lat.tar.gz", }, { name = "Dicionário Aberto", lang_in = "Portuguese", lang_out = "Portuguese", entries = 128521, license = _("CC-BY-SA 2.5"), url = "http://www.dicionario-aberto.net/stardict-DicAberto.tar.bz2", }, { name = "GNU/FDL Anglicko/Český slovník", lang_in = "English", lang_out = "Czech", entries = 178904, -- ~90000 each way license = _("GNU/FDL"), url = "http://http.debian.net/debian/pool/non-free/s/stardict-english-czech/stardict-english-czech_20161201.orig.tar.gz", }, { name = "GNU/FDL Anglicko/Český slovník", lang_in = "Czech", lang_out = "English", entries = 178904, -- ~90000 each way license = _("GNU/FDL"), url = "http://http.debian.net/debian/pool/non-free/s/stardict-english-czech/stardict-english-czech_20161201.orig.tar.gz", }, { name = "GNU/FDL Německo/Český slovník", lang_in = "German", lang_out = "Czech", entries = 2341, -- ~1200 each way license = _("GNU/FDL"), url = "http://http.debian.net/debian/pool/non-free/s/stardict-german-czech/stardict-german-czech_20161201.orig.tar.gz", }, { name = "GNU/FDL Německo/Český slovník", lang_in = "Czech", lang_out = "German", entries = 2341, -- ~1200 each way license = _("GNU/FDL"), url = "http://http.debian.net/debian/pool/non-free/s/stardict-german-czech/stardict-german-czech_20161201.orig.tar.gz", }, -- Dictionaries mirrored from Sourceforge, see https://github.com/koreader/koreader/pull/3176#issuecomment-447085441 { name = "Afrikaans-English dictionary", lang_in = "Afrikaans", lang_out = "English", entries = 4198, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_afrikaans-english-2.4.2.tar.gz" }, { name = "Chinese-English dictionary", lang_in = "Chinese", lang_out = "English", entries = 26017, license = "from CEDICT http://www.mandarintools.com/cedict", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_chinese-eng-2.4.2.tar.gz" }, { name = "Chinese-English dictionary", lang_in = "Chinese", lang_out = "English", entries = 26017, license = "from CEDICT http://www.mandarintools.com/cedict", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_sdict02_chinese-eng-2.4.2.tar.gz" }, { name = "Computer Security (En-Ru)", lang_in = "English", lang_out = "Russian", entries = 12300, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002b/stardict-comn_dls03_xn_secvoc_formatted_en-ru-2.4.2.tar.gz" }, { name = "Construction Dictionary (En-Ru)", lang_in = "English", lang_out = "Russian", entries = 36936, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002b/stardict-comn_dls03_xn_stroika_en-ru-2.4.2.tar.gz" }, { name = "CyberLexicon(En-Es)", lang_in = "English", lang_out = "Spanish", entries = 861, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002b/stardict-comn_dls03_cyber_lexicon_en-es-2.4.2.tar.gz" }, { name = "Czech-Russian dictionary", lang_in = "Czech", lang_out = "Russian", entries = 9656, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_sdict02_czech-rus-2.4.2.tar.gz" }, { name = "Danish-English dictionary", lang_in = "Danish", lang_out = "English", entries = 3323, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_danish-english-2.4.2.tar.gz" }, { name = "Deutsch-Russian dictionary", lang_in = "Deutsch", lang_out = "Russian", entries = 12950, license = "ftp://ftp.ifmo.ru/unix/unix-soft/utils/dictionaries/slowo/dicts/deutsch.tgz", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_deutsch_de-ru-2.4.2.tar.gz" }, { name = "Dictionnaire des idées reçues, de Gustave Flaubert (1912).", lang_in = "French", lang_out = "French", entries = 960, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002e/stardict-user_hctr01_ideesrecues8-2.4.2.tar.gz" }, { name = "Dutch monolingual dictionary", lang_in = "Dutch", lang_out = "Dutch", entries = 3194, license = "http://www.muiswerk.nl/WRDNBOEK/INHOUD.HTM", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_muiswerk-2.4.2.tar.gz" }, { name = "Dutch-English dictionary", lang_in = "Dutch", lang_out = "English", entries = 18244, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_dutch-english-2.4.2.tar.gz" }, { name = "Engligh Idioms (eng-eng)", lang_in = "English", lang_out = "English", entries = 8560, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_idioms_eng_eng-2.4.2.tar.gz" }, { name = "Engligh Idioms (eng-rus)", lang_in = "English", lang_out = "Russian", entries = 9739, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_idioms_eng_rus-2.4.2.tar.gz" }, { name = "English explanatory dictionary (main)", lang_in = "English", lang_out = "English", entries = 45897, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng_eng_main-2.4.2.tar.gz" }, { name = "English explanatory dictionary (new words)", lang_in = "English", lang_out = "English", entries = 1159, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng_eng_nw-2.4.2.tar.gz" }, { name = "English-Arabic dictionary", lang_in = "English", lang_out = "Arabic", entries = 87423, license = "from www.arabeyes.org", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng_arabic-2.4.2.tar.gz" }, { name = "English-Belarusian Computer Dictionary", lang_in = "English", lang_out = "Belarusian", entries = 88, license = "http://mova.org", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_compbe-2.4.2.tar.gz" }, { name = "English-Bulgarian computer dictionary", lang_in = "English", lang_out = "Bulgarian", entries = 523, license = "SA Dictionary, http://sa.dir.bg/sa.htm", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_bulg_comp-2.4.2.tar.gz" }, { name = "English-Finnish dictionary", lang_in = "English", lang_out = "Finnish", entries = 17851, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng_fin-2.4.2.tar.gz" }, { name = "English-German dictionary", lang_in = "English", lang_out = "German", entries = 128707, license = "http://www.dict.cc/", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002d/stardict-comn_sdict_axm05_English_German-2.4.2.tar.gz" }, { name = "English-Hungarian dictionary", lang_in = "English", lang_out = "Hungarian", entries = 67262, license = "jDictionary project, http://jdictionary.info", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng-hung-2.4.2.tar.gz" }, { name = "English-Russian business dictionary", lang_in = "English", lang_out = "Russian", entries = 12673, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng_rus_bus-2.4.2.tar.gz" }, { name = "English-Russian computer dictionary", lang_in = "English", lang_out = "Russian", entries = 13163, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng_rus_comp-2.4.2.tar.gz" }, { name = "English-Russian economic dictionary", lang_in = "English", lang_out = "Russian", entries = 14436, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng_rus_eco-2.4.2.tar.gz" }, { name = "English-Russian full dictionary", lang_in = "English", lang_out = "Russian", entries = 526873, license = "GNU Public License.", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng_rus_full-2.4.2.tar.gz" }, { name = "English-Russian short dictionary", lang_in = "English", lang_out = "Russian", entries = 46650, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng_rus_short-2.4.2.tar.gz" }, { name = "English-Russian slang dictionary", lang_in = "English", lang_out = "Russian", entries = 850, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng_rus_slang-2.4.2.tar.gz" }, { name = "English-Serbian dictionary", lang_in = "English", lang_out = "Serbian", entries = 27546, license = "jDictionary project, http://jdictionary.info", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng_serb-2.4.2.tar.gz" }, { name = "English-Spanish dictionary", lang_in = "English", lang_out = "Spanish", entries = 22527, license = "jDictionary project, http://jdictionary.info", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_eng-spa-2.4.2.tar.gz" }, { name = "Esperanto-Russian dictionary", lang_in = "Esperanto", lang_out = "Russian", entries = 1378, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002d/stardict-comn_sdict_axm05_Esperanto-Russian-2.4.2.tar.gz" }, { name = "Estonian-Russian dictionary", lang_in = "Estonian", lang_out = "Russian", entries = 63825, license = "from ER-DICT: http://sourceforge.net/projects/er-dict", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_est-rus-2.4.2.tar.gz" }, { name = "Finnish-English dictionary", lang_in = "Finnish", lang_out = "English", entries = 2063, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_finnish-english-2.4.2.tar.gz" }, { name = "Finnish-English dictionary", lang_in = "Finnish", lang_out = "English", entries = 29180, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_fin_eng-2.4.2.tar.gz" }, { name = "French-English dictionary", lang_in = "French", lang_out = "English", entries = 41398, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_french-english-2.4.2.tar.gz" }, { name = "French-Hungarian dictionary", lang_in = "French", lang_out = "Hungarian", entries = 5473, license = "jDictionary project, http://jdictionary.info", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_fr_hung-2.4.2.tar.gz" }, { name = "Geological English-Russian dictionary", lang_in = "English", lang_out = "Russian", entries = 2275, license = "ftp://Somewhere/geologe.zip", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_geology_en-ru-2.4.2.tar.gz" }, { name = "Geological Russian-English dictionary", lang_in = "Russian", lang_out = "English", entries = 1951, license = "ftp://Somewhere/geologe.zip", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_geology_ru-en-2.4.2.tar.gz" }, { name = "German-English dictionary", lang_in = "German", lang_out = "English", entries = 79276, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_german_english-2.4.2.tar.gz" }, { name = "German-English dictionary", lang_in = "German", lang_out = "English", entries = 96743, license = "jDictionary project, http://jdictionary.info", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_ger_eng-2.4.2.tar.gz" }, { name = "German-English dictionary", lang_in = "German", lang_out = "English", entries = 96803, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_german-english-2.4.2.tar.gz" }, { name = "German-Hungarian dictionary", lang_in = "German", lang_out = "Hungarian", entries = 22092, license = "jDictionary project, http://jdictionary.info", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_ger_hung-2.4.2.tar.gz" }, { name = "German-Russian dictionary", lang_in = "German", lang_out = "Russian", entries = 12802, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_german_rus-2.4.2.tar.gz" }, { name = "German-Russian dictionary (2)", lang_in = "German", lang_out = "Russian", entries = 94047, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_german_rus2-2.4.2.tar.gz" }, { name = "Glazunov(En-Ru)", lang_in = "English", lang_out = "Russian", entries = 15168, license = nil, url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dsl02_glazunov-2.4.2.tar.gz" }, { name = "Grand dictionnaire de cuisine (1873)", lang_in = "French", lang_out = "French", entries = 2463, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002e/stardict-user_hctr01_dictionnaireCuisine38-2.4.2.tar.gz" }, { name = "Hungarian-English Expressions dictionary", lang_in = "Hungarian", lang_out = "English", entries = 28215, license = "jDictionary project, http://jdictionary.info", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_hung_eng_expr-2.4.2.tar.gz" }, { name = "Hungarian-English dictionary", lang_in = "Hungarian", lang_out = "English", entries = 131568, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_hungarian-english-2.4.2.tar.gz" }, { name = "Islandsko-český slovník 1.3", lang_in = "Icelandic", lang_out = "Czech", entries = 4902, license = "http://www.hvalur.org", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002e/stardict-user_ales01_is_cz_dict-2.4.2.tar.gz" }, { name = "Italian-English dictionary", lang_in = "Italian", lang_out = "English", entries = 12156, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_italian-english-2.4.2.tar.gz" }, { name = "Japanese(Kanji)-English dictionary", lang_in = "Japanese", lang_out = "English", entries = 108472, license = "from http://ftp.cc.monash.edu.au/pub/nihongo/", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_jap-eng-2.4.2.tar.gz" }, { name = "Latin-English dictionary", lang_in = "Latin", lang_out = "English", entries = 4453, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_latin-english-2.4.2.tar.gz" }, { name = "Lingvo GSM E (En-Ru)", lang_in = "English", lang_out = "Russian", entries = 3996, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002b/stardict-comn_dls03_lingvo_gsm_formatted_en-ru-2.4.2.tar.gz" }, { name = "Mueller English-Russian Dictionary", lang_in = "English", lang_out = "Russian", entries = 45962, license = "http://www.chat.ru/~mueller_dic", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_mueller7-2.4.2.tar.gz" }, { name = "Mueller English-Russian Dictionary (24th Edition)", lang_in = "English", lang_out = "Russian", entries = 67066, license = "GPL (from http://mueller-dic.chat.ru/)", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002d/stardict-comn_sdict_axm05_mueller24-2.4.2.tar.gz" }, { name = "New Dictionary of Contemporary Informal English (Глазунов)", lang_in = "English", lang_out = "Russian", entries = 15116, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_sdict02_eng_rus_glazunov-2.4.2.tar.gz" }, { name = "Norwegian-English dictionary", lang_in = "Norwegian", lang_out = "English", entries = 8440, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_norwegian-english-2.4.2.tar.gz" }, { name = "Portuguese-English dictionary", lang_in = "Portuguese", lang_out = "English", entries = 6106, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_portuguese-english-2.4.2.tar.gz" }, { name = "Russian-Deutsch dictionary", lang_in = "Russian", lang_out = "Deutsch", entries = 12101, license = "ftp://ftp.ifmo.ru/unix/unix-soft/utils/dictionaries/slowo/dicts/deutsch.tgz", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_deutsch_ru-de-2.4.2.tar.gz" }, { name = "Russian-English full dictionary", lang_in = "Russian", lang_out = "English", entries = 372553, license = "GNU Public License.", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_rus_eng_full-2.4.2.tar.gz" }, { name = "Russian-English short dictionary", lang_in = "Russian", lang_out = "English", entries = 69117, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_rus_eng_short-2.4.2.tar.gz" }, { name = "Russian-German dictionary", lang_in = "Russian", lang_out = "German", entries = 32001, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_rus_ger-2.4.2.tar.gz" }, { name = "Russian-Russian Big Encyclopaedic Dictionary", lang_in = "Russian", lang_out = "Russian", entries = 70769, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_rus_bigencdic-2.4.2.tar.gz" }, { name = "Russian-Swedish dictionary", lang_in = "Russian", lang_out = "Swedish", entries = 9917, license = "ftp://ftp.ifmo.ru/unix/unix-soft/utils/dictionaries/slowo/dicts/deutsch.tgz", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_swedish_ru-sv-2.4.2.tar.gz" }, { name = "Security (En-Ru)", lang_in = "English", lang_out = "Russian", entries = 2216, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002b/stardict-comn_dls03_Security_v8-2.4.2.tar.gz" }, { name = "Sociology (En-Ru)", lang_in = "English", lang_out = "Russian", entries = 14688, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002b/stardict-comn_dls03_xn_sociology_en-ru-2.4.2.tar.gz" }, { name = "Spain-Russian Dictionary (Sadikov) dictionary", lang_in = "Spain", lang_out = "Russian", entries = 18534, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_sdict02_spa_rus_sadikov-2.4.2.tar.gz" }, { name = "Spanish-English dictionary", lang_in = "Spanish", lang_out = "English", entries = 23670, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_spanish-english-2.4.2.tar.gz" }, { name = "Suomen kielen perussanakirja (pieni versio)", lang_in = "Finnish", lang_out = "Finnish", entries = 93488, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_fifi_norm-2.4.2.tar.gz" }, { name = "Suomen kielen perussanakirja (suuri versio)", lang_in = "Finnish", lang_out = "Finnish", entries = 695069, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_fifi_plus-2.4.2.tar.gz" }, { name = "Swahili-English dictionary", lang_in = "Swahili", lang_out = "English", entries = 759, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_swahili-english-2.4.2.tar.gz" }, { name = "Swedish-English dictionary", lang_in = "Swedish", lang_out = "English", entries = 30260, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_swedish-english-2.4.2.tar.gz" }, { name = "Swedish-Russian dictionary", lang_in = "Swedish", lang_out = "Russian", entries = 10386, license = "ftp://ftp.dvo.ru/pub/dicts/src/schweden.tgz", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_swedish_sv-ru-2.4.2.tar.gz" }, { name = "The Open English-Russian Computer Dictionary", lang_in = "English", lang_out = "Russian", entries = 1259, license = "http://www.chat.ru/~mueller_dic", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_engcom-2.4.2.tar.gz" }, { name = "Tradeport Business Glossary (En)", lang_in = "English", lang_out = "English", entries = 2993, license = "Tradeport Business Glossary http://www.englspace.com/dl/details/dic_tradebusglossary.shtml", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002b/stardict-comn_dls03_tradeport_gloss_en-en-2.4.2.tar.gz" }, { name = "U.S. Gazetteer (1990)", lang_in = "English", lang_out = "English", entries = 52991, license = "Public Domain", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_gazetteer-2.4.2.tar.gz" }, { name = "Universal(Sp-Ru)", lang_in = "Spanish", lang_out = "Russian", entries = 19191, license = nil, url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dsl02_sadikov-2.4.2.tar.gz" }, { name = "Universale(It-Ru)", lang_in = "Italian", lang_out = "Russian", entries = 64231, license = nil, url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dsl02_zorko-2.4.2.tar.gz" }, { name = "WordNet (r) 1.7", lang_in = "English", lang_out = "English", entries = 136970, license = "http://www.cogsci.princeton.edu/~wn/", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_wn-2.4.2.tar.gz" }, { name = "eng-rus_computer", lang_in = "English", lang_out = "Russian", entries = 5152, license = "GPL? See http://gambit.com.ru/~wolf/dic/ ", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-atla02_eng-rus_computer-2.4.2.tar.gz" }, { name = "eng-rus_math-alexandrov", lang_in = "English", lang_out = "Russian", entries = 2084, license = "GPL", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-atla02_eng-rus_math-alexandrov-2.4.2.tar.gz" }, { name = "eng-rus_math_alexandrov", lang_in = "English", lang_out = "Russian", entries = 6912, license = "GPL", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-atla02_eng-rus_math_alexandrov-2.4.2.tar.gz" }, { name = "eng-transcr_0107", lang_in = "English", lang_out = "Russian", entries = 45888, license = "Electronic Version by E.S.Cymbalyuk 1999 under GNU GPL, ver. 0.8", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-atla02_eng-transcr_0107-2.4.2.tar.gz" }, { name = "korolew_enru", lang_in = "English", lang_out = "Russian", entries = 32791, license = "ftp://ftp.ifmo.ru/unix/unix-soft/utils/dictionaries/slowo/dicts/korolew_enru.tgz", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_korolew_en-ru-2.4.2.tar.gz" }, { name = "korolew_ru-en", lang_in = "Russian", lang_out = "English", entries = 31671, license = "ftp://ftp.ifmo.ru/unix/unix-soft/utils/dictionaries/slowo/dicts/korolew_ruen.tgz", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_korolew_ru-en-2.4.2.tar.gz" }, { name = "rus-eng_korolew", lang_in = "Russian", lang_out = "English", entries = 32366, license = "GPL? See http://gambit.com.ru/~wolf/dic/ ", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-atla02_rus-eng_korolew-2.4.2.tar.gz" }, { name = "rus-rus_beslov", lang_in = "Russian", lang_out = "Russian", entries = 65372, license = "See translation for &lt;&lt;00-database-...&gt;&gt; ", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-atla02_rus-rus_beslov-2.4.2.tar.gz" }, { name = "rus-rus_brok_efr", lang_in = "Russian", lang_out = "Russian", entries = 4893, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-atla02_rus-rus_brok_efr-2.4.2.tar.gz" }, { name = "rus-rus_ozhshv", lang_in = "Russian", lang_out = "Russian", entries = 38845, license = "See translation for &lt;&lt;00-database-...&gt;&gt; ", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-atla02_rus-rus_ozhshv-2.4.2.tar.gz" }, { name = "rus-rus_ushakov", lang_in = "Russian", lang_out = "Russian", entries = 81573, license = "See translation for &lt;&lt;00-database-...&gt;&gt; ", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-atla02_rus-rus_ushakov-2.4.2.tar.gz" }, { name = "rus-ukr_slovnyk", lang_in = "Russian", lang_out = "Ukrainian", entries = 458787, license = "See translation for &lt;&lt;00-database-...&gt;&gt; ", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-atla02_rus-ukr_slovnyk-2.4.2.tar.gz" }, { name = "sinyagin_general_er", lang_in = "English", lang_out = "Russian", entries = 17303, license = "http://sinyagin.pp.ru/engrus-mirrors.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_sinyagin_general_er-2.4.2.tar.gz" }, { name = "sinyagin_general_re", lang_in = "Russian", lang_out = "English", entries = 20357, license = "http://sinyagin.pp.ru/engrus-mirrors.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_sinyagin_general_re-2.4.2.tar.gz" }, { name = "slovnyk_be-en", lang_in = "Belarusian", lang_out = "English", entries = 4967, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_be-en-2.4.2.tar.gz" }, { name = "slovnyk_be-pl", lang_in = "Belarusian", lang_out = "Polish", entries = 1344, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_be-pl-2.4.2.tar.gz" }, { name = "slovnyk_be-ru", lang_in = "Belarusian", lang_out = "Russian", entries = 7738, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_be-ru-2.4.2.tar.gz" }, { name = "slovnyk_be-uk", lang_in = "Belarusian", lang_out = "Ukrainian", entries = 6826, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_be-uk-2.4.2.tar.gz" }, { name = "slovnyk_en-be", lang_in = "English", lang_out = "Belarusian", entries = 10866, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_en-be-2.4.2.tar.gz" }, { name = "slovnyk_en-pl", lang_in = "English", lang_out = "Polish", entries = 15420, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_en-pl-2.4.2.tar.gz" }, { name = "slovnyk_en-ru", lang_in = "English", lang_out = "Russian", entries = 57508, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_en-ru-2.4.2.tar.gz" }, { name = "slovnyk_en-uk", lang_in = "English", lang_out = "Ukrainian", entries = 62785, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_en-uk-2.4.2.tar.gz" }, { name = "slovnyk_pl-be", lang_in = "Polish", lang_out = "Belarusian", entries = 3532, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_pl-be-2.4.2.tar.gz" }, { name = "slovnyk_pl-en", lang_in = "Polish", lang_out = "English", entries = 20084, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_pl-en-2.4.2.tar.gz" }, { name = "slovnyk_pl-ru", lang_in = "Polish", lang_out = "Russian", entries = 12789, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_pl-ru-2.4.2.tar.gz" }, { name = "slovnyk_pl-uk", lang_in = "Polish", lang_out = "Ukrainian", entries = 17430, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_pl-uk-2.4.2.tar.gz" }, { name = "slovnyk_ru-be", lang_in = "Russian", lang_out = "Belarusian", entries = 12524, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_ru-be-2.4.2.tar.gz" }, { name = "slovnyk_ru-en", lang_in = "Russian", lang_out = "English", entries = 55815, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_ru-en-2.4.2.tar.gz" }, { name = "slovnyk_ru-pl", lang_in = "Russian", lang_out = "Polish", entries = 15488, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_ru-pl-2.4.2.tar.gz" }, { name = "slovnyk_ru-uk", lang_in = "Russian", lang_out = "Ukrainian", entries = 458782, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_ru-uk-2.4.2.tar.gz" }, { name = "slovnyk_uk-be", lang_in = "Ukrainian", lang_out = "Belarusian", entries = 11864, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_uk-be-2.4.2.tar.gz" }, { name = "slovnyk_uk-en", lang_in = "Ukrainian", lang_out = "English", entries = 53938, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_uk-en-2.4.2.tar.gz" }, { name = "slovnyk_uk-pl", lang_in = "Ukrainian", lang_out = "Polish", entries = 16734, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_uk-pl-2.4.2.tar.gz" }, { name = "slovnyk_uk-ru", lang_in = "Ukrainian", lang_out = "Russian", entries = 440072, license = "http://www.slovnyk.org/prg/gszotar/index.html", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_slovnyk_uk-ru-2.4.2.tar.gz" }, { name = "sokrat_enru", lang_in = "English", lang_out = "Russian", entries = 55823, license = "ftp://ftp.ifmo.ru/unix/unix-soft/utils/dictionaries/slowo/dicts/sokrat_enru.tgz", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_sokrat_en-ru-2.4.2.tar.gz" }, { name = "sokrat_ruen", lang_in = "Russian", lang_out = "English", entries = 49856, license = "ftp://ftp.ifmo.ru/unix/unix-soft/utils/dictionaries/slowo/dicts/sokrat_ruen.tgz", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_sokrat_ru-en-2.4.2.tar.gz" }, { name = "ukr-rus_slovnyk", lang_in = "Ukrainian", lang_out = "Russian", entries = 440077, license = "See translation for &lt;&lt;00-database-...&gt;&gt; ", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-atla02_ukr-rus_slovnyk-2.4.2.tar.gz" }, { name = "Белорусско-русский словарь", lang_in = "Belarusian", lang_out = "Russian", entries = 52010, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002d/stardict-comn_sdict_axm05_BelRusVorvul-2.4.2.tar.gz" }, { name = "Большая Советская Энциклопедия", lang_in = "Russian", lang_out = "Russian", entries = 95058, license = "GNU Public License", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_rus_bse-2.4.2.tar.gz" }, { name = "Большой Энциклопедический Словарь", lang_in = "Russian", lang_out = "Russian", entries = 65390, license = "ftp://ftp.spez.kharkov.ua/pub/fileecho/book/beslov01.ha ftp://ftp.spez.kharkov.ua/pub/fileecho/book/beslov02.ha", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_beslov-2.4.2.tar.gz" }, { name = "Большой Юридический словарь", lang_in = "Russian", lang_out = "Russian", entries = 6800, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002d/stardict-comn_sdict_axm05_rus_big_jurid-2.4.2.tar.gz" }, { name = "Латинско-русский словарь", lang_in = "Latin", lang_out = "Russian", entries = 7812, license = "http://ornemus.da.ru/", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_latrus-2.4.2.tar.gz" }, { name = "Медицинский словарь", lang_in = "Russian", lang_out = "Russian", entries = 1191, license = "http://users.i.com.ua/~viorell/meddic.rar", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_meddict-2.4.2.tar.gz" }, { name = "Новый Большой англо-русский словарь", lang_in = "English", lang_out = "Russian", entries = 109600, license = "http://transmagus-dic.chat.ru/magus.tgz", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_magus-2.4.2.tar.gz" }, { name = "Русско-Белорусский математический словарь", lang_in = "Russian", lang_out = "Belarusian", entries = 2366, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002d/stardict-comn_sdict_axm05_RusBelMath-2.4.2.tar.gz" }, { name = "Русско-Белорусский универсальный словарь", lang_in = "Russian", lang_out = "Belarusian", entries = 106449, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002d/stardict-comn_sdict_axm05_RusBelUniversal-2.4.2.tar.gz" }, { name = "Русско-Белорусский физико-математический словарь", lang_in = "Russian", lang_out = "Belarusian", entries = 18496, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002d/stardict-comn_sdict_axm05_RusBelFizmat-2.4.2.tar.gz" }, { name = "Русско-английский словарь идиом", lang_in = "Russian", lang_out = "English", entries = 682, license = "http://www.lingvo.ru/upload//contents/336/idioms.zip", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_idioms-2.4.2.tar.gz" }, { name = "Словарь Ефремовой", lang_in = "Russian", lang_out = "Russian", entries = 135598, license = "Converted from ftp://files.zipsites.ru/slovari/ by swaj", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_sdict02_ru_efremova-2.4.2.tar.gz" }, { name = "Толковый словарь Ожегова", lang_in = "Russian", lang_out = "Russian", entries = 38832, license = "http://speakrus.narod.ru/zaliznyak/ozhegovw.zip", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_ozhegov-2.4.2.tar.gz" }, { name = "Толковый словарь Ушакова", lang_in = "Russian", lang_out = "Russian", entries = 81261, license = "http://ushdict.narod.ru/archive/ushak1.zip http://ushdict.narod.ru/archive/ushak2.zip", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_ushakov-2.4.2.tar.gz" }, { name = "Толковый словарь живого великорусского языка", lang_in = "Russian", lang_out = "Russian", entries = 43992, license = "http://www.booksite.ru/fulltext/RUSSIAN/DICTION/DALF.RAR", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/001/stardict-comn_dictd03_dalf-2.4.2.tar.gz" }, { name = "Энциклопедический словарь / Брокгауз Ф.А. Ефрон И.А.", lang_in = "Russian", lang_out = "Russian", entries = 120237, license = "", url = "https://gitlab.com/avsej/dicts-stardict-form-xdxf/raw/d636cc5e8d4a47e22ac7466f4af6d435a8a3f650/002c/stardict-comn_sdict05_brokg-2.4.2.tar.gz" }, } return dictionaries
agpl-3.0
bnetcc/darkstar
scripts/zones/Bastok_Markets/npcs/Aquillina.lua
5
1544
----------------------------------- -- Area: Bastok Markets -- NPC: Aquillina -- Starts & Finishes Repeatable Quest: A Flash In The Pan -- Note: Reapeatable every 15 minutes. -- !pos -97 -5 -81 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bastok_Markets/TextIDs"); require("scripts/globals/npc_util"); require("scripts/globals/quests"); function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,A_FLASH_IN_THE_PAN) >= QUEST_ACCEPTED) then if (os.time() >= player:getVar("FlashInThePan")) then if (npcUtil.tradeHas( trade, {{768,4}} )) then player:startEvent(219); end else player:startEvent(218); end end end; function onTrigger(player,npc) if (player:getQuestStatus(BASTOK,A_FLASH_IN_THE_PAN) == QUEST_AVAILABLE) then player:startEvent(217); else player:startEvent(116); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 217) then player:addQuest(BASTOK, A_FLASH_IN_THE_PAN); elseif (csid == 219) then local fame = player:hasCompleteQuest(BASTOK, A_FLASH_IN_THE_PAN) and 8 or 75; if (npcUtil.completeQuest(player, BASTOK, A_FLASH_IN_THE_PAN, {gil=100, fame=fame})) then player:confirmTrade(); player:setVar("FlashInThePan",os.time() + 900); end end end;
gpl-3.0
curiousguy13/shogun
examples/undocumented/lua_modular/serialization_complex_example.lua
21
2932
require 'os' require 'modshogun' require 'load' parameter_list={{5,1,10, 2.0, 10}, {10,0.3,2, 1.0, 0.1}} function check_status(status) assert(status == true) -- if status: -- print "OK reading/writing .h5\n" --else: -- print "ERROR reading/writing .h5\n" end function concatenate(...) local result = ... for _,t in ipairs{select(2, ...)} do for row,rowdata in ipairs(t) do for col,coldata in ipairs(rowdata) do table.insert(result[row], coldata) end end end return result end function rand_matrix(rows, cols, dist) local matrix = {} for i = 1, rows do matrix[i] = {} for j = 1, cols do matrix[i][j] = math.random() + dist end end return matrix end function generate_lab(num) lab={} for i=1,num do lab[i]=0 end for i=num+1,2*num do lab[i]=1 end for i=2*num+1,3*num do lab[i]=2 end for i=3*num+1,4*num do lab[i]=3 end return lab end function serialization_complex_example(num, dist, dim, C, width) math.randomseed(17) data=concatenate(rand_matrix(dim, num, 0), rand_matrix(dim, num, dist), rand_matrix(dim, num, 2 * dist), rand_matrix(dim, num, 3 * dist)) lab=generate_lab(num) feats=modshogun.RealFeatures(data) kernel=modshogun.GaussianKernel(feats, feats, width) labels=modshogun.MulticlassLabels(lab) svm = modshogun.GMNPSVM(C, kernel, labels) feats:add_preprocessor(modshogun.NormOne()) feats:add_preprocessor(modshogun.LogPlusOne()) feats:set_preprocessed(1) svm:train(feats) fstream = modshogun.SerializableHdf5File("blaah.h5", "w") status = svm:save_serializable(fstream) check_status(status) fstream = modshogun.SerializableAsciiFile("blaah.asc", "w") status = svm:save_serializable(fstream) check_status(status) -- fstream = modshogun.SerializableJsonFile("blaah.json", "w") -- status = svm:save_serializable(fstream) -- check_status(status) fstream = modshogun.SerializableXmlFile("blaah.xml", "w") status = svm:save_serializable(fstream) check_status(status) fstream = modshogun.SerializableHdf5File("blaah.h5", "r") new_svm=modshogun.GMNPSVM() status = new_svm:load_serializable(fstream) check_status(status) new_svm:train() fstream = modshogun.SerializableAsciiFile("blaah.asc", "r") new_svm=modshogun.GMNPSVM() status = new_svm:load_serializable(fstream) check_status(status) new_svm:train() -- fstream = modshogun.SerializableJsonFile("blaah.json", "r") -- new_svm=modshogun.GMNPSVM() -- status = new_svm:load_serializable(fstream) -- check_status(status) -- new_svm:train() fstream = modshogun.SerializableXmlFile("blaah.xml", "r") new_svm=modshogun.GMNPSVM() status = new_svm:load_serializable(fstream) check_status(status) new_svm:train() os.remove("blaah.h5") os.remove("blaah.asc") -- os.remove("blaah.json") os.remove("blaah.xml") return svm,new_svm end if debug.getinfo(3) == nill then print 'Serialization SVMLight' serialization_complex_example(unpack(parameter_list[1])) end
gpl-3.0
mwoz123/koreader
frontend/apps/reader/modules/readerstatus.lua
4
8939
local BD = require("ui/bidi") local BookStatusWidget = require("ui/widget/bookstatuswidget") local ButtonDialogTitle = require("ui/widget/buttondialogtitle") local Device = require("device") local Event = require("ui/event") local InfoMessage = require("ui/widget/infomessage") local InputContainer = require("ui/widget/container/inputcontainer") local UIManager = require("ui/uimanager") local _ = require("gettext") local T = require("ffi/util").template local ReaderStatus = InputContainer:new { document = nil, summary = { rating = 0, note = nil, status = "", modified = "", }, enabled = true, total_pages = 0 } function ReaderStatus:init() if self.ui.document.is_pic then self.enabled = false return else self.total_pages = self.document:getPageCount() self.ui.menu:registerToMainMenu(self) end end function ReaderStatus:addToMainMenu(menu_items) menu_items.book_status = { text = _("Book status"), callback = function() self:onShowBookStatus() end, } end function ReaderStatus:onEndOfBook() Device:performHapticFeedback("CONTEXT_CLICK") local settings = G_reader_settings:readSetting("end_document_action") local choose_action local collate = true local QuickStart = require("ui/quickstart") local last_file = G_reader_settings:readSetting("lastfile") if last_file and last_file == QuickStart.quickstart_filename then self:openFileBrowser() return end if G_reader_settings:readSetting("collate") == "access" then collate = false end -- Should we start by marking the book as read? if G_reader_settings:isTrue("end_document_auto_mark") then self:onMarkBook(true) end if (settings == "pop-up" or settings == nil) and UIManager:getTopWidget() ~= "end_document" then local buttons = { { { text_func = function() if self.settings.data.summary and self.settings.data.summary.status == "complete" then return _("Mark as reading") else return _("Mark as read") end end, callback = function() self:onMarkBook() UIManager:close(choose_action) end, }, { text = _("Book status"), callback = function() self:onShowBookStatus() UIManager:close(choose_action) end, }, }, { { text = _("Go to beginning"), callback = function() self.ui:handleEvent(Event:new("GoToBeginning")) UIManager:close(choose_action) end, }, { text = _("Open next file"), enabled = collate, callback = function() self:openNextFile(self.document.file) UIManager:close(choose_action) end, }, }, { { text = _("Delete file"), callback = function() self:deleteFile(self.document.file, false) UIManager:close(choose_action) end, }, { text = _("File browser"), callback = function() self:openFileBrowser() UIManager:close(choose_action) end, }, }, { { text = _("Cancel"), callback = function() UIManager:close(choose_action) end, }, }, } choose_action = ButtonDialogTitle:new{ name = "end_document", title = _("You've reached the end of the document.\nWhat would you like to do?"), title_align = "center", buttons = buttons, } UIManager:show(choose_action) elseif settings == "book_status" then self:onShowBookStatus() elseif settings == "next_file" then if G_reader_settings:readSetting("collate") ~= "access" then local info = InfoMessage:new{ text = _("Searching next file…"), } UIManager:show(info) UIManager:forceRePaint() self:openNextFile(self.document.file) UIManager:close(info) else UIManager:show(InfoMessage:new{ text = _("Could not open next file. Sort by last read date does not support this feature."), }) end elseif settings == "goto_beginning" then self.ui:handleEvent(Event:new("GoToBeginning")) elseif settings == "file_browser" then self:openFileBrowser() elseif settings == "mark_read" then self:onMarkBook(true) UIManager:show(InfoMessage:new{ text = _("You've reached the end of the document.\nThe current book is marked as read."), timeout = 3 }) elseif settings == "book_status_file_browser" then local before_show_callback = function() self:openFileBrowser() end self:onShowBookStatus(before_show_callback) elseif settings == "delete_file" then self:deleteFile(self.document.file, true) end end function ReaderStatus:openFileBrowser() local FileManager = require("apps/filemanager/filemanager") self.ui:onClose() if not FileManager.instance then self.ui:showFileManager() end self.document = nil end function ReaderStatus:openNextFile(next_file) local FileManager = require("apps/filemanager/filemanager") if not FileManager.instance then self.ui:showFileManager() end next_file = FileManager.instance.file_chooser:getNextFile(next_file) FileManager.instance:onClose() if next_file then self.ui:switchDocument(next_file) else UIManager:show(InfoMessage:new{ text = _("This is the last file in the current folder. No next file to open."), }) end end function ReaderStatus:deleteFile(file, text_end_book) local ConfirmBox = require("ui/widget/confirmbox") local message_end_book = "" if text_end_book then message_end_book = "You've reached the end of the document.\n" end UIManager:show(ConfirmBox:new{ text = T(_("%1Are you sure that you want to delete this file?\n%2\nIf you delete a file, it is permanently lost."), message_end_book, BD.filepath(file)), ok_text = _("Delete"), ok_callback = function() local FileManager = require("apps/filemanager/filemanager") self.ui:onClose() FileManager:deleteFile(file) require("readhistory"):fileDeleted(file) -- (will update "lastfile") if FileManager.instance then FileManager.instance.file_chooser:refreshPath() else FileManager:showFiles() end end, }) end function ReaderStatus:onShowBookStatus(before_show_callback) local status_page = BookStatusWidget:new { thumbnail = self.document:getCoverPageImage(), props = self.document:getProps(), document = self.document, settings = self.settings, view = self.view, } if before_show_callback then before_show_callback() end status_page.dithered = true UIManager:show(status_page, "full") return true end -- If mark_read is true then we change status only from reading/abandoned to read (complete). -- Otherwise we change status from reading/abandoned to read or from read to reading. function ReaderStatus:onMarkBook(mark_read) if self.settings.data.summary and self.settings.data.summary.status then local current_status = self.settings.data.summary.status if current_status == "complete" then if mark_read then -- Keep mark as read. self.settings.data.summary.status = "complete" else -- Change current status from read (complete) to reading self.settings.data.summary.status = "reading" end else self.settings.data.summary.status = "complete" end else self.settings.data.summary = {status = "complete"} end end function ReaderStatus:onReadSettings(config) self.settings = config end return ReaderStatus
agpl-3.0
bnetcc/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Gavrie.lua
5
1230
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Gavrie -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/shop"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:showText(npc,GAVRIE_SHOP_DIALOG); local stock = { 0x1036,2595, -- Eye Drops 0x1034,316, -- Antidote 0x1037,800, -- Echo Drops 0x1010,910, -- Potion 0x1020,4832, -- Ether 0x103B,3360, -- Remedy 0x119D,12, -- Distilled Water 0x492B,50, -- Automaton Oil 0x492C,250, -- Automaton Oil +1 0x492D,500, -- Automaton Oil +2 0x4AF1,1000} -- Automaton Oil +3 showShop(player, STATIC, stock); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bnetcc/darkstar
scripts/globals/items/bottle_of_berserkers_tonic.lua
1
1135
----------------------------------------- -- ID: 5851 -- Item: Bottle of Berserker's Tonic -- Item Effect: Increases Dbl Attk 80% -- Duration: 60 secs ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_MEDICINE)) then result = 111; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) if (target:addStatusEffect(EFFECT_MEDICINE,0,0,60,5851)) then target:messageBasic(205); else target:messageBasic(423); -- no effect end end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DOUBLE_ATTACK, 80); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DOUBLE_ATTACK, 80); end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Abyssea-Misareaux/npcs/Dilapidated_gate3.lua
1
1092
----------------------------------- ----------------------------------- package.loaded["scripts/zones/Abyssea-Misareaux/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/missions"); require("scripts/globals/campaign"); require("scripts/zones/Abyssea-Misareaux/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0102); 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
best98ir/SASAN
libs/fakeredis.lua
650
40405
local unpack = table.unpack or unpack --- Bit operations local ok,bit if _VERSION == "Lua 5.3" then bit = (load [[ return { band = function(x, y) return x & y end, bor = function(x, y) return x | y end, bxor = function(x, y) return x ~ y end, bnot = function(x) return ~x end, rshift = function(x, n) return x >> n end, lshift = function(x, n) return x << n end, } ]])() else ok,bit = pcall(require,"bit") if not ok then bit = bit32 end end assert(type(bit) == "table", "module for bitops not found") --- default sleep local default_sleep do local ok, mod = pcall(require, "socket") if ok and type(mod) == "table" then default_sleep = mod.sleep else default_sleep = function(n) local t0 = os.clock() while true do local delta = os.clock() - t0 if (delta < 0) or (delta > n) then break end end end end end --- Helpers local xdefv = function(ktype) if ktype == "list" then return {head = 0, tail = 0} elseif ktype == "zset" then return { list = {}, set = {}, } else return {} end end local xgetr = function(self, k, ktype) if self.data[k] then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) assert(self.data[k].value) return self.data[k].value else return xdefv(ktype) end end local xgetw = function(self, k, ktype) if self.data[k] and self.data[k].value then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) else self.data[k] = {ktype = ktype, value = xdefv(ktype)} end return self.data[k].value end local empty = function(self, k) local v, t = self.data[k].value, self.data[k].ktype if t == nil then return true elseif t == "string" then return not v[1] elseif (t == "hash") or (t == "set") then for _,_ in pairs(v) do return false end return true elseif t == "list" then return v.head == v.tail elseif t == "zset" then if #v.list == 0 then for _,_ in pairs(v.set) do error("incoherent") end return true else for _,_ in pairs(v.set) do return(false) end error("incoherent") end else error("unsupported") end end local cleanup = function(self, k) if empty(self, k) then self.data[k] = nil end end local is_integer = function(x) return (type(x) == "number") and (math.floor(x) == x) end local overflows = function(n) return (n > 2^53-1) or (n < -2^53+1) end local is_bounded_integer = function(x) return (is_integer(x) and (not overflows(x))) end local is_finite_number = function(x) return (type(x) == "number") and (x > -math.huge) and (x < math.huge) end local toint = function(x) if type(x) == "string" then x = tonumber(x) end return is_bounded_integer(x) and x or nil end local tofloat = function(x) if type(x) == "number" then return x end if type(x) ~= "string" then return nil end local r = tonumber(x) if r then return r end if x == "inf" or x == "+inf" then return math.huge elseif x == "-inf" then return -math.huge else return nil end end local tostr = function(x) if is_bounded_integer(x) then return string.format("%d", x) else return tostring(x) end end local char_bitcount = function(x) assert( (type(x) == "number") and (math.floor(x) == x) and (x >= 0) and (x < 256) ) local n = 0 while x ~= 0 do x = bit.band(x, x-1) n = n+1 end return n end local chkarg = function(x) if type(x) == "number" then x = tostr(x) end assert(type(x) == "string") return x end local chkargs = function(n, ...) local arg = {...} assert(#arg == n) for i=1,n do arg[i] = chkarg(arg[i]) end return unpack(arg) end local getargs = function(...) local arg = {...} local n = #arg; assert(n > 0) for i=1,n do arg[i] = chkarg(arg[i]) end return arg end local getargs_as_map = function(...) local arg, r = getargs(...), {} assert(#arg%2 == 0) for i=1,#arg,2 do r[arg[i]] = arg[i+1] end return r end local chkargs_wrap = function(f, n) assert( (type(f) == "function") and (type(n) == "number") ) return function(self, ...) return f(self, chkargs(n, ...)) end end local lset_to_list = function(s) local r = {} for v,_ in pairs(s) do r[#r+1] = v end return r end local nkeys = function(x) local r = 0 for _,_ in pairs(x) do r = r + 1 end return r end --- Commands -- keys local del = function(self, ...) local arg = getargs(...) local r = 0 for i=1,#arg do if self.data[arg[i]] then r = r + 1 end self.data[arg[i]] = nil end return r end local exists = function(self, k) return not not self.data[k] end local keys = function(self, pattern) assert(type(pattern) == "string") -- We want to convert the Redis pattern to a Lua pattern. -- Start by escaping dashes *outside* character classes. -- We also need to escape percents here. local t, p, n = {}, 1, #pattern local p1, p2 while true do p1, p2 = pattern:find("%[.+%]", p) if p1 then if p1 > p then t[#t+1] = {true, pattern:sub(p, p1-1)} end t[#t+1] = {false, pattern:sub(p1, p2)} p = p2+1 if p > n then break end else t[#t+1] = {true, pattern:sub(p, n)} break end end for i=1,#t do if t[i][1] then t[i] = t[i][2]:gsub("[%%%-]", "%%%0") else t[i] = t[i][2]:gsub("%%", "%%%%") end end -- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]' -- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is. -- Wrap in '^$' to enforce bounds. local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0") :gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$" local r = {} for k,_ in pairs(self.data) do if k:match(lp) then r[#r+1] = k end end return r end local _type = function(self, k) return self.data[k] and self.data[k].ktype or "none" end local randomkey = function(self) local ks = lset_to_list(self.data) local n = #ks if n > 0 then return ks[math.random(1, n)] else return nil end end local rename = function(self, k, k2) assert((k ~= k2) and self.data[k]) self.data[k2] = self.data[k] self.data[k] = nil return true end local renamenx = function(self, k, k2) if self.data[k2] then return false else return rename(self, k, k2) end end -- strings local getrange, incrby, set local append = function(self, k, v) local x = xgetw(self, k, "string") x[1] = (x[1] or "") .. v return #x[1] end local bitcount = function(self, k, i1, i2) k = chkarg(k) local s if i1 or i2 then assert(i1 and i2, "ERR syntax error") s = getrange(self, k, i1, i2) else s = xgetr(self, k, "string")[1] or "" end local r, bytes = 0,{s:byte(1, -1)} for i=1,#bytes do r = r + char_bitcount(bytes[i]) end return r end local bitop = function(self, op, k, ...) assert(type(op) == "string") op = op:lower() assert( (op == "and") or (op == "or") or (op == "xor") or (op == "not"), "ERR syntax error" ) k = chkarg(k) local arg = {...} local good_arity = (op == "not") and (#arg == 1) or (#arg > 0) assert(good_arity, "ERR wrong number of arguments for 'bitop' command") local l, vals = 0, {} local s for i=1,#arg do s = xgetr(self, arg[i], "string")[1] or "" if #s > l then l = #s end vals[i] = s end if l == 0 then del(self, k) return 0 end local vector_mt = {__index=function() return 0 end} for i=1,#vals do vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt) end local r = {} if op == "not" then assert(#vals[1] == l) for i=1,l do r[i] = bit.band(bit.bnot(vals[1][i]), 0xff) end else local _op = bit["b" .. op] for i=1,l do local t = {} for j=1,#vals do t[j] = vals[j][i] end r[i] = _op(unpack(t)) end end set(self, k, string.char(unpack(r))) return l end local decr = function(self, k) return incrby(self, k, -1) end local decrby = function(self, k, n) n = toint(n) assert(n, "ERR value is not an integer or out of range") return incrby(self, k, -n) end local get = function(self, k) local x = xgetr(self, k, "string") return x[1] end local getbit = function(self, k, offset) k = chkarg(k) offset = toint(offset) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" if bytepos >= #s then return 0 end local char = s:sub(bytepos+1, bytepos+1):byte() return bit.band(bit.rshift(char, 7-bitpos), 1) end getrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetr(self, k, "string") x = x[1] or "" if i1 >= 0 then i1 = i1 + 1 end if i2 >= 0 then i2 = i2 + 1 end return x:sub(i1, i2) end local getset = function(self, k, v) local r = get(self, k) set(self, k, v) return r end local incr = function(self, k) return incrby(self, k, 1) end incrby = function(self, k, n) k, n = chkarg(k), toint(n) assert(n, "ERR value is not an integer or out of range") local x = xgetw(self, k, "string") local i = toint(x[1] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[1] = tostr(i) return i end local incrbyfloat = function(self, k, n) k, n = chkarg(k), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "string") local i = tofloat(x[1] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[1] = tostr(i) return i end local mget = function(self, ...) local arg, r = getargs(...), {} for i=1,#arg do r[i] = get(self, arg[i]) end return r end local mset = function(self, ...) local argmap = getargs_as_map(...) for k,v in pairs(argmap) do set(self, k, v) end return true end local msetnx = function(self, ...) local argmap = getargs_as_map(...) for k,_ in pairs(argmap) do if self.data[k] then return false end end for k,v in pairs(argmap) do set(self, k, v) end return true end set = function(self, k, v) self.data[k] = {ktype = "string", value = {v}} return true end local setbit = function(self, k, offset, b) k = chkarg(k) offset, b = toint(offset), toint(b) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) assert( (b == 0) or (b == 1), "ERR bit is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" local pad = {s} for i=2,bytepos+2-#s do pad[i] = "\0" end s = table.concat(pad) assert(#s >= bytepos+1) local before = s:sub(1, bytepos) local char = s:sub(bytepos+1, bytepos+1):byte() local after = s:sub(bytepos+2, -1) local old = bit.band(bit.rshift(char, 7-bitpos), 1) if b == 1 then char = bit.bor(bit.lshift(1, 7-bitpos), char) else char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char) end local r = before .. string.char(char) .. after set(self, k, r) return old end local setnx = function(self, k, v) if self.data[k] then return false else return set(self, k, v) end end local setrange = function(self, k, i, s) local k, s = chkargs(2, k, s) i = toint(i) assert(i and (i >= 0)) local x = xgetw(self, k, "string") local y = x[1] or "" local ly, ls = #y, #s if i > ly then -- zero padding local t = {} for i=1, i-ly do t[i] = "\0" end y = y .. table.concat(t) .. s else y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly) end x[1] = y return #y end local strlen = function(self, k) local x = xgetr(self, k, "string") return x[1] and #x[1] or 0 end -- hashes local hdel = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local r = 0 local x = xgetw(self, k, "hash") for i=1,#arg do if x[arg[i]] then r = r + 1 end x[arg[i]] = nil end cleanup(self, k) return r end local hget local hexists = function(self, k, k2) return not not hget(self, k, k2) end hget = function(self, k, k2) local x = xgetr(self, k, "hash") return x[k2] end local hgetall = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,v in pairs(x) do r[_k] = v end return r end local hincrby = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), toint(n) assert(n, "ERR value is not an integer or out of range") assert(type(n) == "number") local x = xgetw(self, k, "hash") local i = toint(x[k2] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[k2] = tostr(i) return i end local hincrbyfloat = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "hash") local i = tofloat(x[k2] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[k2] = tostr(i) return i end local hkeys = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,_ in pairs(x) do r[#r+1] = _k end return r end local hlen = function(self, k) local x = xgetr(self, k, "hash") return nkeys(x) end local hmget = function(self, k, k2s) k = chkarg(k) assert((type(k2s) == "table")) local r = {} local x = xgetr(self, k, "hash") for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end return r end local hmset = function(self, k, ...) k = chkarg(k) local arg = {...} if type(arg[1]) == "table" then assert(#arg == 1) local x = xgetw(self, k, "hash") for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end else assert(#arg % 2 == 0) local x = xgetw(self, k, "hash") local t = getargs(...) for i=1,#t,2 do x[t[i]] = t[i+1] end end return true end local hset = function(self, k, k2, v) local x = xgetw(self, k, "hash") local r = not x[k2] x[k2] = v return r end local hsetnx = function(self, k, k2, v) local x = xgetw(self, k, "hash") if x[k2] == nil then x[k2] = v return true else return false end end local hvals = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _,v in pairs(x) do r[#r+1] = v end return r end -- lists (head = left, tail = right) local _l_real_i = function(x, i) if i < 0 then return x.tail+i+1 else return x.head+i+1 end end local _l_len = function(x) return x.tail - x.head end local _block_for = function(self, timeout) if timeout > 0 then local sleep = self.sleep or default_sleep if type(sleep) == "function" then sleep(timeout) else error("sleep function unavailable", 0) end else error("operation would block", 0) end end local rpoplpush local blpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpoplpush = function(self, k1, k2, timeout) k1, k2 = chkargs(2, k1, k2) timeout = toint(timeout) if not self.data[k1] then _block_for(self, timeout) end return rpoplpush(self, k1, k2) end local lindex = function(self, k, i) k = chkarg(k) i = assert(toint(i)) local x = xgetr(self, k, "list") return x[_l_real_i(x, i)] end local linsert = function(self, k, mode, pivot, v) mode = mode:lower() assert((mode == "before") or (mode == "after")) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local p = nil for i=x.head+1, x.tail do if x[i] == pivot then p = i break end end if not p then return -1 end if mode == "after" then for i=x.head+1, p do x[i-1] = x[i] end x.head = x.head - 1 else for i=x.tail, p, -1 do x[i+1] = x[i] end x.tail = x.tail + 1 end x[p] = v return _l_len(x) end local llen = function(self, k) local x = xgetr(self, k, "list") return _l_len(x) end local lpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return r end local lpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x[x.head] = vs[i] x.head = x.head - 1 end return _l_len(x) end local lpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x[x.head] = v x.head = x.head - 1 return _l_len(x) end local lrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x, r = xgetr(self, k, "list"), {} i1 = math.max(_l_real_i(x, i1), x.head+1) i2 = math.min(_l_real_i(x, i2), x.tail) for i=i1,i2 do r[#r+1] = x[i] end return r end local _lrem_i = function(x, p) for i=p,x.tail do x[i] = x[i+1] end x.tail = x.tail - 1 end local _lrem_l = function(x, v, s) assert(v) if not s then s = x.head+1 end for i=s,x.tail do if x[i] == v then _lrem_i(x, i) return i end end return false end local _lrem_r = function(x, v, s) assert(v) if not s then s = x.tail end for i=s,x.head+1,-1 do if x[i] == v then _lrem_i(x, i) return i end end return false end local lrem = function(self, k, count, v) k, v = chkarg(k), chkarg(v) count = assert(toint(count)) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local n, last = 0, nil local op = (count < 0) and _lrem_r or _lrem_l local limited = (count ~= 0) count = math.abs(count) while true do last = op(x, v, last) if last then n = n+1 if limited then count = count - 1 if count == 0 then break end end else break end end return n end local lset = function(self, k, i, v) k, v = chkarg(k), chkarg(v) i = assert(toint(i)) if not self.data[k] then error("ERR no such key") end local x = xgetw(self, k, "list") local l = _l_len(x) if i >= l or i < -l then error("ERR index out of range") end x[_l_real_i(x, i)] = v return true end local ltrim = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetw(self, k, "list") i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2) for i=x.head+1,i1-1 do x[i] = nil end for i=i2+1,x.tail do x[i] = nil end x.head = math.max(i1-1, x.head) x.tail = math.min(i2, x.tail) assert( (x[x.head] == nil) and (x[x.tail+1] == nil) ) cleanup(self, k) return true end local rpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return r end rpoplpush = function(self, k1, k2) local v = rpop(self, k1) if not v then return nil end lpush(self, k2, v) return v end local rpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x.tail = x.tail + 1 x[x.tail] = vs[i] end return _l_len(x) end local rpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x.tail = x.tail + 1 x[x.tail] = v return _l_len(x) end -- sets local sadd = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if not x[arg[i]] then x[arg[i]] = true r = r + 1 end end return r end local scard = function(self, k) local x = xgetr(self, k, "set") return nkeys(x) end local _sdiff = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} for v,_ in pairs(x) do r[v] = true end for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = nil end end return r end local sdiff = function(self, k, ...) return lset_to_list(_sdiff(self, k, ...)) end local sdiffstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sdiff(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local _sinter = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} local y for v,_ in pairs(x) do r[v] = true for i=1,#arg do y = xgetr(self, arg[i], "set") if not y[v] then r[v] = nil; break end end end return r end local sinter = function(self, k, ...) return lset_to_list(_sinter(self, k, ...)) end local sinterstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sinter(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local sismember = function(self, k, v) local x = xgetr(self, k, "set") return not not x[v] end local smembers = function(self, k) local x = xgetr(self, k, "set") return lset_to_list(x) end local smove = function(self, k, k2, v) local x = xgetr(self, k, "set") if x[v] then local y = xgetw(self, k2, "set") x[v] = nil y[v] = true return true else return false end end local spop = function(self, k) local x, r = xgetw(self, k, "set"), nil local l = lset_to_list(x) local n = #l if n > 0 then r = l[math.random(1, n)] x[r] = nil end cleanup(self, k) return r end local srandmember = function(self, k, count) k = chkarg(k) local x = xgetr(self, k, "set") local l = lset_to_list(x) local n = #l if not count then if n > 0 then return l[math.random(1, n)] else return nil end end count = toint(count) if (count == 0) or (n == 0) then return {} end if count >= n then return l end local r = {} if count > 0 then -- distinct elements for i=0,count-1 do r[#r+1] = table.remove(l, math.random(1, n-i)) end else -- allow repetition for i=1,-count do r[#r+1] = l[math.random(1, n)] end end return r end local srem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if x[arg[i]] then x[arg[i]] = nil r = r + 1 end end cleanup(self, k) return r end local _sunion = function(self, ...) local arg = getargs(...) local r = {} local x for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = true end end return r end local sunion = function(self, k, ...) return lset_to_list(_sunion(self, k, ...)) end local sunionstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sunion(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end -- zsets local _z_p_mt = { __eq = function(a, b) if a.v == b.v then assert(a.s == b.s) return true else return false end end, __lt = function(a, b) if a.s == b.s then return (a.v < b.v) else return (a.s < b.s) end end, } local _z_pair = function(s, v) assert( (type(s) == "number") and (type(v) == "string") ) local r = {s = s, v = v} return setmetatable(r, _z_p_mt) end local _z_pairs = function(...) local arg = {...} assert((#arg > 0) and (#arg % 2 == 0)) local ps = {} for i=1,#arg,2 do ps[#ps+1] = _z_pair( assert(tofloat(arg[i])), chkarg(arg[i+1]) ) end return ps end local _z_insert = function(x, ix, p) assert( (type(x) == "table") and (type(ix) == "number") and (type(p) == "table") ) local l = x.list table.insert(l, ix, p) for i=ix+1,#l do x.set[l[i].v] = x.set[l[i].v] + 1 end x.set[p.v] = ix end local _z_remove = function(x, v) if not x.set[v] then return false end local l, ix = x.list, x.set[v] assert(l[ix].v == v) table.remove(l, ix) for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - 1 end x.set[v] = nil return true end local _z_remove_range = function(x, i1, i2) local l = x.list i2 = i2 or i1 assert( (i1 > 0) and (i2 >= i1) and (i2 <= #l) ) local ix, n = i1, i2-i1+1 for i=1,n do x.set[l[ix].v] = nil table.remove(l, ix) end for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - n end return n end local _z_update = function(x, p) local l = x.list local found = _z_remove(x, p.v) local ix = nil for i=1,#l do if l[i] > p then ix = i; break end end if not ix then ix = #l+1 end _z_insert(x, ix, p) return found end local _z_coherence = function(x) local l, s = x.list, x.set local found, n = {}, 0 for val,pos in pairs(s) do if found[pos] then return false end found[pos] = true n = n + 1 if not (l[pos] and (l[pos].v == val)) then return false end end if #l ~= n then return false end for i=1, n-1 do if l[i].s > l[i+1].s then return false end end return true end local _z_normrange = function(l, i1, i2) i1, i2 = assert(toint(i1)), assert(toint(i2)) if i1 < 0 then i1 = #l+i1 end if i2 < 0 then i2 = #l+i2 end i1, i2 = math.max(i1+1, 1), i2+1 if (i2 < i1) or (i1 > #l) then return nil end i2 = math.min(i2, #l) return i1, i2 end local _zrbs_opts = function(...) local arg = {...} if #arg == 0 then return {} end local ix, opts = 1, {} while type(arg[ix]) == "string" do if arg[ix] == "withscores" then opts.withscores = true ix = ix + 1 elseif arg[ix] == "limit" then opts.limit = { offset = assert(toint(arg[ix+1])), count = assert(toint(arg[ix+2])), } ix = ix + 3 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.withscores = opts.withscores or _o.withscores if _o.limit then opts.limit = { offset = assert(toint(_o.limit.offset or _o.limit[1])), count = assert(toint(_o.limit.count or _o.limit[2])), } end ix = ix + 1 end assert(arg[ix] == nil) if opts.limit then assert( (opts.limit.count >= 0) and (opts.limit.offset >= 0) ) end return opts end local _z_store_params = function(dest, numkeys, ...) dest = chkarg(dest) numkeys = assert(toint(numkeys)) assert(numkeys > 0) local arg = {...} assert(#arg >= numkeys) local ks = {} for i=1, numkeys do ks[i] = chkarg(arg[i]) end local ix, opts = numkeys+1,{} while type(arg[ix]) == "string" do if arg[ix] == "weights" then opts.weights = {} ix = ix + 1 for i=1, numkeys do opts.weights[i] = assert(toint(arg[ix])) ix = ix + 1 end elseif arg[ix] == "aggregate" then opts.aggregate = assert(chkarg(arg[ix+1])) ix = ix + 2 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.weights = opts.weights or _o.weights opts.aggregate = opts.aggregate or _o.aggregate ix = ix + 1 end assert(arg[ix] == nil) if opts.aggregate then assert( (opts.aggregate == "sum") or (opts.aggregate == "min") or (opts.aggregate == "max") ) else opts.aggregate = "sum" end if opts.weights then assert(#opts.weights == numkeys) for i=1,#opts.weights do assert(type(opts.weights[i]) == "number") end else opts.weights = {} for i=1, numkeys do opts.weights[i] = 1 end end opts.keys = ks opts.dest = dest return opts end local _zrbs_limits = function(x, s1, s2, descending) local s1_incl, s2_incl = true, true if s1:sub(1, 1) == "(" then s1, s1_incl = s1:sub(2, -1), false end s1 = assert(tofloat(s1)) if s2:sub(1, 1) == "(" then s2, s2_incl = s2:sub(2, -1), false end s2 = assert(tofloat(s2)) if descending then s1, s2 = s2, s1 s1_incl, s2_incl = s2_incl, s1_incl end if s2 < s1 then return nil end local l = x.list local i1, i2 local fst, lst = l[1].s, l[#l].s if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end for i=1,#l do if (i1 and i2) then break end if (not i1) then if l[i].s > s1 then i1 = i end if s1_incl and l[i].s == s1 then i1 = i end end if (not i2) then if l[i].s > s2 then i2 = i-1 end if (not s2_incl) and l[i].s == s2 then i2 = i-1 end end end assert(i1 and i2) if descending then return #l-i2, #l-i1 else return i1-1, i2-1 end end local dbg_zcoherence = function(self, k) local x = xgetr(self, k, "zset") return _z_coherence(x) end local zadd = function(self, k, ...) k = chkarg(k) local ps = _z_pairs(...) local x = xgetw(self, k, "zset") local n = 0 for i=1,#ps do if not _z_update(x, ps[i]) then n = n+1 end end return n end local zcard = function(self, k) local x = xgetr(self, k, "zset") return #x.list end local zcount = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return i2 - i1 + 1 end local zincrby = function(self, k, n, v) k,v = chkargs(2, k, v) n = assert(tofloat(n)) local x = xgetw(self, k, "zset") local p = x.list[x.set[v]] local s = p and (p.s + n) or n _z_update(x, _z_pair(s, v)) return s end local zinterstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local aggregate if params.aggregate == "sum" then aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then aggregate = math.min elseif params.aggregate == "max" then aggregate = math.max else error() end local y = xgetr(self, params.keys[1], "zset") local p1, p2 for j=1,#y.list do p1 = _z_pair(y.list[j].s, y.list[j].v) _z_update(x, p1) end for i=2,#params.keys do y = xgetr(self, params.keys[i], "zset") local to_remove, to_update = {}, {} for j=1,#x.list do p1 = x.list[j] if y.set[p1.v] then p2 = _z_pair( aggregate( p1.s, params.weights[i] * y.list[y.set[p1.v]].s ), p1.v ) to_update[#to_update+1] = p2 else to_remove[#to_remove+1] = p1.v end end for j=1,#to_remove do _z_remove(x, to_remove[j]) end for j=1,#to_update do _z_update(x, to_update[j]) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end local _zranger = function(descending) return function(self, k, i1, i2, opts) k = chkarg(k) local withscores = false if type(opts) == "table" then withscores = opts.withscores elseif type(opts) == "string" then assert(opts:lower() == "withscores") withscores = true else assert(opts == nil) end local x = xgetr(self, k, "zset") local l = x.list i1, i2 = _z_normrange(l, i1, i2) if not i1 then return {} end local inc = 1 if descending then i1 = #l - i1 + 1 i2 = #l - i2 + 1 inc = -1 end local r = {} if withscores then for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end else for i=i1, i2, inc do r[#r+1] = l[i].v end end return r end end local zrange = _zranger(false) local zrevrange = _zranger(true) local _zrangerbyscore = function(descending) return function(self, k, s1, s2, ...) k, s1, s2 = chkargs(3, k, s1, s2) local opts = _zrbs_opts(...) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, descending) if not (i1 and i2) then return {} end if opts.limit then if opts.limit.count == 0 then return {} end i1 = i1 + opts.limit.offset if i1 > i2 then return {} end i2 = math.min(i2, i1+opts.limit.count-1) end if descending then return zrevrange(self, k, i1, i2, opts) else return zrange(self, k, i1, i2, opts) end end end local zrangebyscore = _zrangerbyscore(false) local zrevrangebyscore = _zrangerbyscore(true) local zrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return r-1 else return nil end end local zrem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "zset"), 0 for i=1,#arg do if _z_remove(x, arg[i]) then r = r + 1 end end cleanup(self, k) return r end local zremrangebyrank = function(self, k, i1, i2) k = chkarg(k) local x = xgetw(self, k, "zset") i1, i2 = _z_normrange(x.list, i1, i2) if not i1 then cleanup(self, k) return 0 end local n = _z_remove_range(x, i1, i2) cleanup(self, k) return n end local zremrangebyscore = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return zremrangebyrank(self, k, i1, i2) end local zrevrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return #x.list-r else return nil end end local zscore = function(self, k, v) local x = xgetr(self, k, "zset") local p = x.list[x.set[v]] if p then return p.s else return nil end end local zunionstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local default_score, aggregate if params.aggregate == "sum" then default_score = 0 aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then default_score = math.huge aggregate = math.min elseif params.aggregate == "max" then default_score = -math.huge aggregate = math.max else error() end local y, p1, p2 for i=1,#params.keys do y = xgetr(self, params.keys[i], "zset") for j=1,#y.list do p1 = y.list[j] p2 = _z_pair( aggregate( params.weights[i] * p1.s, x.set[p1.v] and x.list[x.set[p1.v]].s or default_score ), p1.v ) _z_update(x, p2) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end -- connection local echo = function(self, v) return v end local ping = function(self) return true end -- server local flushdb = function(self) self.data = {} return true end --- Class local methods = { -- keys del = del, -- (...) -> #removed exists = chkargs_wrap(exists, 1), -- (k) -> exists? keys = keys, -- (pattern) -> list of keys ["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none] randomkey = randomkey, -- () -> [k|nil] rename = chkargs_wrap(rename, 2), -- (k,k2) -> true renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2 -- strings append = chkargs_wrap(append, 2), -- (k,v) -> #new bitcount = bitcount, -- (k,[start,end]) -> n bitop = bitop, -- ([and|or|xor|not],k,...) decr = chkargs_wrap(decr, 1), -- (k) -> new decrby = decrby, -- (k,n) -> new get = chkargs_wrap(get, 1), -- (k) -> [v|nil] getbit = getbit, -- (k,offset) -> b getrange = getrange, -- (k,start,end) -> string getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil] incr = chkargs_wrap(incr, 1), -- (k) -> new incrby = incrby, -- (k,n) -> new incrbyfloat = incrbyfloat, -- (k,n) -> new mget = mget, -- (k1,...) -> {v1,...} mset = mset, -- (k1,v1,...) -> true msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k) set = chkargs_wrap(set, 2), -- (k,v) -> true setbit = setbit, -- (k,offset,b) -> old setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?) setrange = setrange, -- (k,offset,val) -> #new strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0] -- hashes hdel = hdel, -- (k,sk1,...) -> #removed hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists? hget = chkargs_wrap(hget,2), -- (k,sk) -> v hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map hincrby = hincrby, -- (k,sk,n) -> new hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0] hmget = hmget, -- (k,{sk1,...}) -> {v1,...} hmset = hmset, -- (k,{sk1=v1,...}) -> true hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed? hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?) hvals = chkargs_wrap(hvals, 1), -- (k) -> values -- lists blpop = blpop, -- (k1,...) -> k,v brpop = brpop, -- (k1,...) -> k,v brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v lindex = lindex, -- (k,i) -> v linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after) llen = chkargs_wrap(llen, 1), -- (k) -> #list lpop = chkargs_wrap(lpop, 1), -- (k) -> v lpush = lpush, -- (k,v1,...) -> #list (after) lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after) lrange = lrange, -- (k,start,stop) -> list lrem = lrem, -- (k,count,v) -> #removed lset = lset, -- (k,i,v) -> true ltrim = ltrim, -- (k,start,stop) -> true rpop = chkargs_wrap(rpop, 1), -- (k) -> v rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v rpush = rpush, -- (k,v1,...) -> #list (after) rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after) -- sets sadd = sadd, -- (k,v1,...) -> #added scard = chkargs_wrap(scard, 1), -- (k) -> [n|0] sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...) sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0 sinter = sinter, -- (k1,...) -> set sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0 sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member? smembers = chkargs_wrap(smembers, 1), -- (k) -> set smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1) spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil] srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...] srem = srem, -- (k,v1,...) -> #removed sunion = sunion, -- (k1,...) -> set sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0 -- zsets zadd = zadd, -- (k,score,member,[score,member,...]) zcard = chkargs_wrap(zcard, 1), -- (k) -> n zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count zincrby = zincrby, -- (k,score,v) -> score zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank zrem = zrem, -- (k,v1,...) -> #removed zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card -- connection echo = chkargs_wrap(echo, 1), -- (v) -> v ping = ping, -- () -> true -- server flushall = flushdb, -- () -> true flushdb = flushdb, -- () -> true -- debug dbg_zcoherence = dbg_zcoherence, } local new = function() local r = {data = {}} return setmetatable(r,{__index = methods}) end return { new = new, }
gpl-3.0
Atebite/NutScript
gamemode/core/libs/sh_class.lua
4
3264
nut.class = nut.class or {} nut.class.list = {} local charMeta = nut.meta.character -- Register classes from a directory. function nut.class.loadFromDir(directory) -- Search the directory for .lua files. for k, v in ipairs(file.Find(directory.."/*.lua", "LUA")) do -- Get the name without the "sh_" prefix and ".lua" suffix. local niceName = v:sub(4, -5) -- Determine a numeric identifier for this class. local index = #nut.class.list + 1 local halt for k, v in ipairs(nut.class.list) do if (v.uniqueID == niceName) then halt = true end end if (halt == true) then continue end -- Set up a global table so the file has access to the class table. CLASS = {index = index, uniqueID = niceName} -- Define some default variables. CLASS.name = "Unknown" CLASS.desc = "No description available." CLASS.limit = 0 -- For future use with plugins. if (PLUGIN) then CLASS.plugin = PLUGIN.uniqueID end -- Include the file so data can be modified. nut.util.include(directory.."/"..v, "shared") -- Why have a class without a faction? if (!CLASS.faction or !team.Valid(CLASS.faction)) then ErrorNoHalt("Class '"..niceName.."' does not have a valid faction!\n") CLASS = nil continue end -- Allow classes to be joinable by default. if (!CLASS.onCanBe) then CLASS.onCanBe = function(client) return true end end -- Add the class to the list of classes. nut.class.list[index] = CLASS -- Remove the global variable to prevent conflict. CLASS = nil end end -- Determines if a player is allowed to join a specific class. function nut.class.canBe(client, class) -- Get the class table by its numeric identifier. local info = nut.class.list[class] -- See if the class exists. if (!info) then return false, "no info" end -- If the player's faction matches the class's faction. if (client:Team() != info.faction) then return false, "not correct team" end if (client:getChar():getClass() == class) then return false, "same class request" end if (info.limit > 0) then if (#nut.class.getPlayers(info.index) >= info.limit) then return false, "class is full" end end -- See if the class allows the player to join it. return info:onCanBe(client) end function nut.class.getPlayers(class) local players = {} for k, v in ipairs(player.GetAll()) do local char = v:getChar() if (char and char:getClass() == class) then table.insert(players, v) end end return players end function charMeta:joinClass(class) if (!class) then self:kickClass() return end local oldClass = self:getClass() local client = self:getPlayer() if (nut.class.canBe(client, class)) then self:setClass(class) hook.Run("OnPlayerJoinClass", client, class, oldClass) return true else return false end end function charMeta:kickClass() self:setClass() local client = self:getPlayer() hook.Run("OnPlayerJoinClass", client, class) end function GM:OnPlayerJoinClass(client, class, oldClass) local info = nut.class.list[class] local info2 = nut.class.list[oldClass] if (info.onSet) then info:onSet(client) end if (info2 and info2.onLeave) then info2:onLeave(client) end netstream.Start(nil, "classUpdate", client) end
mit
bnetcc/darkstar
scripts/zones/Silver_Sea_route_to_Al_Zahbi/npcs/Yahliq.lua
1
1510
----------------------------------- -- Area: Silver Sea route to Al Zahbi -- NPC: Yahliq -- Type: Guild Merchant: Fishing Guild -- !pos 4.986 -2.101 -12.026 59 ----------------------------------- package.loaded["scripts/zones/Silver_Sea_route_to_Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Silver_Sea_route_to_Al_Zahbi/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) --[[ if (player:sendGuild(525,1,23,5)) then player:showText(npc,YAHLIQ_SHOP_DIALOG); end ]] player:showText(npc,YAHLIQ_SHOP_DIALOG); local stock = { 2177, 36, -- Ice Card 2180, 36, -- Thunder Card 2182, 36, -- Light Card 2183, 36, -- Dark Card 5449, 92, -- Hamsi 5450, 1957, -- Lakerda 17387, 4077, -- Tarutaru Fishing Rod 17395, 9, -- Lugworm 17399, 2394, -- Sabiki Rig 17400, 691, -- Sinking Minnow 17404, 270 -- Minnow }; showShop(player, STATIC, stock); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bnetcc/darkstar
scripts/globals/spells/bluemagic/cannonball.lua
33
1721
----------------------------------------- -- Spell: Cannonball -- Damage varies with TP -- Spell cost: 66 MP -- Monster Type: Vermin -- Spell Type: Physical (Blunt) -- Blue Magic Points: 3 -- Stat Bonus: STR+1, DEX+1 -- Level: 70 -- Casting Time: 0.5 seconds -- Recast Time: 28.5 seconds -- Skillchain Element(s): Fusion (can open/close Light with Fragmentation WSs and spells) -- Combos: None ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_DAMAGE; params.dmgtype = DMGTYPE_H2H; params.scattr = SC_FUSION; params.numhits = 1; params.multiplier = 1.75; params.tp150 = 2.125; params.tp300 = 2.75; params.azuretp = 2.875; params.duppercap = 75; params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.offcratiomod = caster:getStat(MOD_DEF); damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Selbina/npcs/Thunder_Hawk.lua
5
2160
----------------------------------- -- Area: Selbina -- NPC: Thunder Hawk -- Starts and Finishes Quest: The Rescue -- !pos -58 -10 6 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local TheRescue = player:getQuestStatus(OTHER_AREAS,THE_RESCUE); local SelbiFame = math.floor((player:getFameLevel(SANDORIA) + player:getFameLevel(BASTOK)) / 2); -- Selbina Fame if (TheRescue == QUEST_AVAILABLE and SelbiFame >= 1) then player:startEvent(80); -- Start quest "The rescue" elseif (TheRescue == QUEST_ACCEPTED and player:hasKeyItem(TRADERS_SACK) == false) then player:startEvent(83); -- During quest "The rescue" elseif (TheRescue == QUEST_ACCEPTED and player:hasKeyItem(TRADERS_SACK) == true) then player:startEvent(81); -- Finish quest "The rescue" elseif (TheRescue == QUEST_COMPLETED) then player:startEvent(82); -- New standard dialog else player:startEvent(84); -- Standard dialog end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 80 and option == 70) then player:addQuest(OTHER_AREAS,THE_RESCUE); elseif (csid == 81) then player:completeQuest(OTHER_AREAS,THE_RESCUE); player:addTitle(HONORARY_CITIZEN_OF_SELBINA); player:delKeyItem(TRADERS_SACK); if (player:hasKeyItem(MAP_OF_THE_RANGUEMONT_PASS) == false) then player:addKeyItem(MAP_OF_THE_RANGUEMONT_PASS); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_RANGUEMONT_PASS); end player:addGil(3000); player:messageSpecial(GIL_OBTAINED,3000); player:addFame(OTHER_AREAS,30); end end;
gpl-3.0
Etiene/Algorithm-Implementations
Bresenham_Based_Supercover_Line/Lua/Yonaba/bresenham_based_supercover_test.lua
27
1151
-- Tests for bresenham.lua local supercover_line = require 'bresenham_based_supercover' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end -- Checks if t1 and t2 arrays are the same local function same(t1, t2) for k,v in ipairs(t1) do if t2[k].x ~= v.x or t2[k].y ~= v.y then return false end end return true end run('Testing Bresenham-based supercover line marching', function() local expected = { {x = 1, y = 1}, {x = 2, y = 1}, {x = 1, y = 2}, {x = 2, y = 2}, {x = 3, y = 2}, {x = 2, y = 3}, {x = 3, y = 3}, {x = 4, y = 3}, {x = 3, y = 4}, {x = 4, y = 4}, {x = 5, y = 4}, {x = 4, y = 5}, {x = 5, y = 5} } assert(same(supercover_line(1, 1, 5, 5), expected)) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
MmxBoy/metalik
plugins/wiki.lua
735
4364
-- http://git.io/vUA4M local socket = require "socket" local JSON = require "cjson" local wikiusage = { "!wiki [text]: Read extract from default Wikipedia (EN)", "!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola", "!wiki search [text]: Search articles on default Wikipedia (EN)", "!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola", } local Wikipedia = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 300, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(self.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else self.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) print(request['url']) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(JSON.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then return text..": "..page.extract else local text = "Extract not found for "..text text = text..'\n'..table.concat(wikiusage, '\n') return text end else return "Sorry an error happened" end end -- search for term in wiki function Wikipedia:wikisearch(text, lang) local result = self:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "No results found" return titles else return "Sorry, an error occurred" end end local function run(msg, matches) -- TODO: Remember language (i18 on future version) -- TODO: Support for non Wikipedias but Mediawikis local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then local text = "Usage:\n" text = text..table.concat(wikiusage, '\n') return text end local result if search then result = Wikipedia:wikisearch(term, lang) else -- TODO: Show the link result = Wikipedia:wikintro(term, lang) end return result end return { description = "Searches Wikipedia and send results", usage = wikiusage, patterns = { "^![Ww]iki(%w+) (search) (.+)$", "^![Ww]iki (search) ?(.*)$", "^![Ww]iki(%w+) (.+)$", "^![Ww]iki ?(.*)$" }, run = run }
gpl-2.0
miralireza2/star_bottelegram
plugins/wiki.lua
735
4364
-- http://git.io/vUA4M local socket = require "socket" local JSON = require "cjson" local wikiusage = { "!wiki [text]: Read extract from default Wikipedia (EN)", "!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola", "!wiki search [text]: Search articles on default Wikipedia (EN)", "!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola", } local Wikipedia = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 300, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(self.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else self.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) print(request['url']) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(JSON.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then return text..": "..page.extract else local text = "Extract not found for "..text text = text..'\n'..table.concat(wikiusage, '\n') return text end else return "Sorry an error happened" end end -- search for term in wiki function Wikipedia:wikisearch(text, lang) local result = self:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "No results found" return titles else return "Sorry, an error occurred" end end local function run(msg, matches) -- TODO: Remember language (i18 on future version) -- TODO: Support for non Wikipedias but Mediawikis local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then local text = "Usage:\n" text = text..table.concat(wikiusage, '\n') return text end local result if search then result = Wikipedia:wikisearch(term, lang) else -- TODO: Show the link result = Wikipedia:wikintro(term, lang) end return result end return { description = "Searches Wikipedia and send results", usage = wikiusage, patterns = { "^![Ww]iki(%w+) (search) (.+)$", "^![Ww]iki (search) ?(.*)$", "^![Ww]iki(%w+) (.+)$", "^![Ww]iki ?(.*)$" }, run = run }
gpl-2.0
awesomeWM/awesome
tests/examples/shims/awesome.lua
1
3114
local lgi = require("lgi") local gears_obj = require("gears.object") -- Emulate the C API classes. They differ from C API objects as connect_signal -- doesn't take an object as first argument and they support fallback properties -- handlers. local function _shim_fake_class() local obj = gears_obj() obj._private = {} -- Deprecated. obj.data = obj._private local meta = { __index = function()end, __newindex = function()end, } obj._connect_signal = obj.connect_signal obj._disconnect_signal = obj.disconnect_signal function obj.connect_signal(name, func) return obj._connect_signal(obj, name, func) end function obj.disconnect_signal(name, func) return obj._disconnect_signal(obj, name, func) end function obj.set_index_miss_handler(handler) meta.__index = handler end function obj.set_newindex_miss_handler(handler) meta.__newindex = handler end function obj.emit_signal(name, c, ...) local conns = obj._signals[name] or {strong={}} for func in pairs(conns.strong) do func(c, ...) end end return obj, meta end local function forward_class(obj, class) assert(obj.emit_signal) local es = obj.emit_signal function obj:emit_signal(name, ...) es(obj, name, ...) class.emit_signal(name, obj, ...) end end local awesome = _shim_fake_class() awesome._shim_fake_class = _shim_fake_class awesome._forward_class = forward_class -- Avoid c.screen = acreen.focused() to be called, all tests will fail awesome.startup = true function awesome.register_xproperty() end function awesome.xkb_get_group_names() return "pc+us+inet(evdev)" end function awesome.xkb_get_layout_group() return 0 end awesome.load_image = lgi.cairo.ImageSurface.create_from_png function awesome.pixbuf_to_surface(_, path) return awesome.load_image(path) end function awesome.xrdb_get_value() return nil end function awesome.spawn() end -- Always show deprecated messages awesome.version = "v9999" awesome.api_level = 9999 -- SVG are composited. Without it we need a root surface awesome.composite_manager_running = true awesome._modifiers = { Shift = { {keycode = 50 , keysym = 'Shift_L' }, {keycode = 62 , keysym = 'Shift_R' }, }, Lock = {}, Control = { {keycode = 37 , keysym = 'Control_L' }, {keycode = 105, keysym = 'Control_R' }, }, Mod1 = { {keycode = 64 , keysym = 'Alt_L' }, {keycode = 108, keysym = 'Alt_R' }, }, Mod2 = { {keycode = 77 , keysym = 'Num_Lock' }, }, Mod3 = {}, Mod4 = { {keycode = 133, keysym = 'Super_L' }, {keycode = 134, keysym = 'Super_R' }, }, Mod5 = { {keycode = 203, keysym = 'Mode_switch'}, }, } function awesome._get_key_name(key) return key end awesome._active_modifiers = {} return awesome -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
vanloswang/conky_all
conky_colors/conkycolors/scripts/conkyCairo.lua
6
35239
--[[ -- This code is mostly by londonali1010, mrpeachy, VinDSL, Wlourf and SLK -- Conky-Colors by helmuthdu -- license : Distributed under the terms of GNU GPL version 2 or later ]] require 'cairo' ------------------------------------------------------------------------------- -- rgb_to_r_g_b -- converts color in hexa to decimal -- function rgb_to_r_g_b(colour, alpha) return ((colour / 0x10000) % 0x100) / 255., ((colour / 0x100) % 0x100) / 255., (colour % 0x100) / 255., alpha end ------------------------------------------------------------------------------- -- get_user_dir -- return user dir -- function get_user_dir() local f = assert(io.popen("conky-colors --localdir")) local s = assert(f:read('*l')) f:close() return s end ------------------------------------------------------------------------------- -- get_weather_info -- return yahoo weather info -- function get_yahoo_weather_info(dataType, dataLocation, dataUnit) local f = assert(io.popen("conky-colors --systemdir")) local s = assert(f:read('*l')) f:close() f = assert(io.popen("sh " .. s .. "/bin/conkyYahooWeather " .. dataType .. " " .. dataLocation .. " " .. dataUnit)) -- runs command s = assert(f:read('*l')) f:close() return s end ------------------------------------------------------------------------------- -- get_day_name -- return day name -- function get_day_name(format, day) local f = assert(io.popen("date " .. format .. " --date=" .. day)) -- runs command local s = assert(f:read('*l')) f:close() return s end ------------------------------------------------------------------------------- -- get_music_percent -- return music percent -- function get_music_percent (player) local f = assert(io.popen("conky-colors --systemdir")) local s = assert(f:read('*l')) f:close() f = assert(io.popen("sh " .. s .. "/bin/conky" .. player .. " --datatype=PP")) -- runs command s = assert(f:read('*a')) f:close() return s end ------------------------------------------------------------------------------- -- weather -- dispay text -- function display_text(data) local txt = data.txt local x, y = data.x, data.y local txt_weight, txt_size = data.txt_weight, data.txt_size local txt_fg_colour, txt_fg_alpha = data.txt_fg_colour, data.txt_fg_alpha if data.font==nil then data.font = "ubuntu" end cairo_select_font_face (cr, data.font, CAIRO_FONT_SLANT_NORMAL, txt_weight) cairo_set_font_size (cr, txt_size) cairo_set_source_rgba (cr, rgb_to_r_g_b(txt_fg_colour, txt_fg_alpha)) cairo_move_to (cr, x - (txt_size / 2), y) cairo_show_text (cr, txt) cairo_stroke (cr) end ------------------------------------------------------------------------------- -- clock_hands -- display clock hands -- function clock_hands(data) local xc = data.xc local yc = data.yc local colour = data.colour local alpha = data.alpha local show_secs = data.show_secs local size = data.size local secs,mins,hours,secs_arc,mins_arc,hours_arc local xh,yh,xm,ym,xs,ys secs=os.date("%S") mins=os.date("%M") hours=os.date("%I") secs_arc=(2*math.pi/60)*secs mins_arc=(2*math.pi/60)*mins+secs_arc/60 hours_arc=(2*math.pi/12)*hours+mins_arc/12 xh=xc+0.4*size*math.sin(hours_arc) yh=yc-0.4*size*math.cos(hours_arc) cairo_move_to(cr,xc,yc) cairo_line_to(cr,xh,yh) cairo_set_line_cap(cr,CAIRO_LINE_CAP_ROUND) cairo_set_line_width(cr,5) cairo_set_source_rgba(cr,rgb_to_r_g_b(colour,alpha)) cairo_stroke(cr) xm=xc+0.5*size*math.sin(mins_arc) ym=yc-0.5*size*math.cos(mins_arc) cairo_move_to(cr,xc,yc) cairo_line_to(cr,xm,ym) cairo_set_line_width(cr,3) cairo_stroke(cr) if show_secs then xs=xc+0.5*size*math.sin(secs_arc) ys=yc-0.5*size*math.cos(secs_arc) cairo_move_to(cr,xc,yc) cairo_line_to(cr,xs,ys) cairo_set_line_width(cr,1) cairo_stroke(cr) end cairo_set_line_cap(cr,CAIRO_LINE_CAP_BUTT) end ------------------------------------------------------------------------------- -- draw_clock_ring -- displays clock -- function draw_clock_ring(data) local value = data.value local value_max = data.value_max local x, y = data.x, data.y local graph_radius = data.graph_radius local graph_thickness, graph_unit_thickness = data.graph_thickness, data.graph_unit_thickness local graph_unit_angle = data.graph_unit_angle local graph_bg_colour, graph_bg_alpha = data.graph_bg_colour, data.graph_bg_alpha local graph_fg_colour, graph_fg_alpha = data.graph_fg_colour, data.graph_fg_alpha -- background ring cairo_arc(cr, x, y, graph_radius, 0, 2 * math.pi) cairo_set_source_rgba(cr, rgb_to_r_g_b(graph_bg_colour, graph_bg_alpha)) cairo_set_line_width(cr, graph_thickness) cairo_stroke(cr) -- arc of value local val = (value % value_max) local i = 1 while i <= val do cairo_arc(cr, x, y, graph_radius,( ((graph_unit_angle * i) - graph_unit_thickness)*(2*math.pi/360) )-(math.pi/2),((graph_unit_angle * i) * (2*math.pi/360))-(math.pi/2)) cairo_set_source_rgba(cr,rgb_to_r_g_b(graph_fg_colour,graph_fg_alpha)) cairo_stroke(cr) i = i + 1 end local angle = (graph_unit_angle * i) - graph_unit_thickness -- graduations marks local graduation_radius = data.graduation_radius local graduation_thickness, graduation_mark_thickness = data.graduation_thickness, data.graduation_mark_thickness local graduation_unit_angle = data.graduation_unit_angle local graduation_fg_colour, graduation_fg_alpha = data.graduation_fg_colour, data.graduation_fg_alpha if graduation_radius > 0 and graduation_thickness > 0 and graduation_unit_angle > 0 then local nb_graduation = 360 / graduation_unit_angle local i = 1 while i <= nb_graduation do cairo_set_line_width(cr, graduation_thickness) cairo_arc(cr, x, y, graduation_radius, (((graduation_unit_angle * i)-(graduation_mark_thickness/2))*(2*math.pi/360))-(math.pi/2),(((graduation_unit_angle * i)+(graduation_mark_thickness/2))*(2*math.pi/360))-(math.pi/2)) cairo_set_source_rgba(cr,rgb_to_r_g_b(graduation_fg_colour,graduation_fg_alpha)) cairo_stroke(cr) cairo_set_line_width(cr, graph_thickness) i = i + 1 end end -- text local txt_radius = data.txt_radius local txt_weight, txt_size = data.txt_weight, data.txt_size local txt_fg_colour, txt_fg_alpha = data.txt_fg_colour, data.txt_fg_alpha local movex = txt_radius * (math.cos((angle * 2 * math.pi / 360)-(math.pi/2))) local movey = txt_radius * (math.sin((angle * 2 * math.pi / 360)-(math.pi/2))) cairo_select_font_face (cr, "ubuntu", CAIRO_FONT_SLANT_NORMAL, txt_weight); cairo_set_font_size (cr, txt_size); cairo_set_source_rgba (cr, rgb_to_r_g_b(txt_fg_colour, txt_fg_alpha)); cairo_move_to (cr, x + movex - (txt_size / 2), y + movey + 3); cairo_show_text (cr, value); cairo_stroke (cr); end ------------------------------------------------------------------------------- -- angle_to_position -- convert degree to rad and rotate (0 degree is top/north) -- function angle_to_position(start_angle, current_angle) local pos = current_angle + start_angle return ( ( pos * (2 * math.pi / 360) ) - (math.pi / 2) ) end ------------------------------------------------------------------------------- -- draw_gauge_ring -- display gauges -- function draw_gauge_ring(data) local value = data.value local value_max = data.value_max local x, y = data.x, data.y local graph_radius = data.graph_radius local graph_thickness, graph_unit_thickness = data.graph_thickness, data.graph_unit_thickness local graph_start_angle = data.graph_start_angle local graph_unit_angle = data.graph_unit_angle local graph_bg_colour, graph_bg_alpha = data.graph_bg_colour, data.graph_bg_alpha local graph_fg_colour, graph_fg_alpha = data.graph_fg_colour, data.graph_fg_alpha local hand_fg_colour, hand_fg_alpha = data.hand_fg_colour, data.hand_fg_alpha local graph_end_angle = (value_max * graph_unit_angle) % 360 if value == nil then value=0 end -- background ring cairo_arc(cr, x, y, graph_radius, angle_to_position(graph_start_angle, 0), angle_to_position(graph_start_angle, graph_end_angle)) cairo_set_source_rgba(cr, rgb_to_r_g_b(graph_bg_colour, graph_bg_alpha)) cairo_set_line_width(cr, graph_thickness) cairo_stroke(cr) -- arc of value local val = value % (value_max + 1) local start_arc = 0 local stop_arc = 0 local i = 1 while i <= val do start_arc = (graph_unit_angle * i) - graph_unit_thickness stop_arc = (graph_unit_angle * i) cairo_arc(cr, x, y, graph_radius, angle_to_position(graph_start_angle, start_arc), angle_to_position(graph_start_angle, stop_arc)) cairo_set_source_rgba(cr, rgb_to_r_g_b(graph_fg_colour, graph_fg_alpha)) cairo_stroke(cr) i = i + 1 end local angle = start_arc -- hand start_arc = (graph_unit_angle * val) - (graph_unit_thickness * 2) stop_arc = (graph_unit_angle * val) cairo_arc(cr, x, y, graph_radius, angle_to_position(graph_start_angle, start_arc), angle_to_position(graph_start_angle, stop_arc)) cairo_set_source_rgba(cr, rgb_to_r_g_b(hand_fg_colour, hand_fg_alpha)) cairo_stroke(cr) -- graduations marks local graduation_radius = data.graduation_radius local graduation_thickness, graduation_mark_thickness = data.graduation_thickness, data.graduation_mark_thickness local graduation_unit_angle = data.graduation_unit_angle local graduation_fg_colour, graduation_fg_alpha = data.graduation_fg_colour, data.graduation_fg_alpha if graduation_radius > 0 and graduation_thickness > 0 and graduation_unit_angle > 0 then local nb_graduation = graph_end_angle / graduation_unit_angle local i = 0 while i < nb_graduation do cairo_set_line_width(cr, graduation_thickness) start_arc = (graduation_unit_angle * i) - (graduation_mark_thickness / 2) stop_arc = (graduation_unit_angle * i) + (graduation_mark_thickness / 2) cairo_arc(cr, x, y, graduation_radius, angle_to_position(graph_start_angle, start_arc), angle_to_position(graph_start_angle, stop_arc)) cairo_set_source_rgba(cr,rgb_to_r_g_b(graduation_fg_colour,graduation_fg_alpha)) cairo_stroke(cr) cairo_set_line_width(cr, graph_thickness) i = i + 1 end end -- text local txt_radius = data.txt_radius local txt_weight, txt_size = data.txt_weight, data.txt_size local txt_fg_colour, txt_fg_alpha = data.txt_fg_colour, data.txt_fg_alpha local movex = txt_radius * math.cos(angle_to_position(graph_start_angle, angle)) local movey = txt_radius * math.sin(angle_to_position(graph_start_angle, angle)) cairo_select_font_face (cr, "ubuntu", CAIRO_FONT_SLANT_NORMAL, txt_weight) cairo_set_font_size (cr, txt_size) cairo_set_source_rgba (cr, rgb_to_r_g_b(txt_fg_colour, txt_fg_alpha)) cairo_move_to (cr, x + movex - (txt_size / 2), y + movey + 3) cairo_show_text (cr, value) cairo_stroke (cr) -- caption local caption = data.caption local caption_weight, caption_size = data.caption_weight, data.caption_size local caption_fg_colour, caption_fg_alpha = data.caption_fg_colour, data.caption_fg_alpha local tox = graph_radius * (math.cos((graph_start_angle * 2 * math.pi / 360)-(math.pi/2))) local toy = graph_radius * (math.sin((graph_start_angle * 2 * math.pi / 360)-(math.pi/2))) cairo_select_font_face (cr, "ubuntu", CAIRO_FONT_SLANT_NORMAL, caption_weight); cairo_set_font_size (cr, caption_size) cairo_set_source_rgba (cr, rgb_to_r_g_b(caption_fg_colour, caption_fg_alpha)) cairo_move_to (cr, x + tox + 5, y + toy + 3) -- bad hack but not enough time ! if graph_start_angle < 105 then cairo_move_to (cr, x + tox - 30, y + toy + 1) end cairo_show_text (cr, caption) cairo_stroke (cr) end ------------------------------------------------------------------------------- -- draw_ring -- simple rings -- function draw_ring(data) local value = data.value local value_max = data.value_max local bgc = data.bg_colour local bga = data.bg_alpha local fgc = data.fg_colour local fga = data.fg_alpha local xc, yc = data.x, data.y local radius = data.radius local thickness = data.thickness local sa = data.start_angle local ea = data.end_angle local lr = data.lr if value == nil then value=0 end local pct = value/value_max local angle_0 = sa * math.pi/180 - math.pi/2 local angle_f = ea * math.pi/180 - math.pi/2 local pct_arc = pct * (angle_f - angle_0) -- Draw background ring cairo_arc(cr, xc, yc, radius, angle_0, angle_f) cairo_set_source_rgba(cr, rgb_to_r_g_b(bgc, bga)) cairo_set_line_width(cr, thickness) cairo_stroke(cr) -- Draw indicator ring cairo_arc(cr, xc, yc, radius, angle_0, angle_0 + pct_arc) cairo_set_source_rgba(cr, rgb_to_r_g_b(fgc, fga)) cairo_stroke(cr) end ------------------------------------------------------------------------------- -- draw_gauge_bars -- display gauge -- function draw_gauge_bars(data) local x=data.x local y=data.y local divisions=data.divisions local div_width=data.div_width local div_height=data.div_height local div_gap=data.div_gap local br,bg,bb,ba=rgb_to_r_g_b(data.bg_color, data.bg_alpha) local sr,sg,sb,sa=rgb_to_r_g_b(data.st_color, data.fg_alpha) local mr,mg,mb,ma=rgb_to_r_g_b(data.mid_color, data.fg_alpha) local er,eg,eb,ea=rgb_to_r_g_b(data.end_color, data.fg_alpha) if data.value==nil then value=0 else value=data.value end local value_max=data.value_max local value_divs=(value/value_max)*divisions cairo_set_line_width (cr,div_width) for i=1,divisions do if i<(divisions/2) and i<=value_divs then colr=((mr-sr)*(i/(divisions/2)))+sr colg=((mg-sg)*(i/(divisions/2)))+sg colb=((mb-sb)*(i/(divisions/2)))+sb cola=((ma-sa)*(i/(divisions/2)))+sa elseif i>=(divisions/2) and i<=value_divs then colr=((er-mr)*((i-(divisions/2))/(divisions/2)))+mr colg=((eg-mg)*((i-(divisions/2))/(divisions/2)))+mg colb=((eb-mb)*((i-(divisions/2))/(divisions/2)))+mb cola=((ea-ma)*((i-(divisions/2))/(divisions/2)))+ma else colr=br colg=bg colb=bb cola=ba end cairo_set_source_rgba (cr,colr,colg,colb,cola) if data.orientation == "horizontal" then cairo_move_to (cr,x+((div_width+div_gap)*i-1),y) else cairo_move_to (cr,x,y-((div_width+div_gap)*i-1)) end cairo_rel_line_to (cr,0,div_height) cairo_stroke (cr) end end--function bars ------------------------------------------------------------------------------- -- draw_box -- display background -- --[[BOX WIDGET v1.1 by Wlourf 27/01/2011 This widget can drawn some boxes, even circles in your conky window http://u-scripts.blogspot.com/2011/01/box-widget.html) Inspired by Background by londonali1010 (2009), thanks ;-) The parameters (all optionals) are : x - x coordinate of top-left corner of the box, default = 0 = (top-left corner of conky window) y - y coordinate of top-left corner of the box, default = 0 = (top-left corner of conky window) w - width of the box, default = width of the conky window h - height of the box, default = height of the conky window corners - corners is a table for the four corners in this order : top-left, top-right,bottom-right, bottom-left each corner is defined in a table with a shape and a radius, available shapes are : "curve","circle","line" example for the same shapes for all corners: { {"circle",10} } example for first corner different from the three others { {"circle",10}, {"circle",5} } example for top corners differents from bottom corners { {"circle",10}, {"circle",10}, {"line",0} } default = { {"line",0} } i.e=no corner operator - set the compositing operator (needs in the conkyrc : own_window_argb_visual yes) see http://cairographics.org/operators/ available operators are : "clear","source","over","in","out","atop","dest","dest_over","dest_in","dest_out","dest_atop","xor","add","saturate" default = "over" border - if border>0, the script draws only the border, like a frame, default=0 dash - if border>0 and dash>0, the border is draw with dashes, default=0 skew_x - skew box around x axis, default = 0 skew_y - skew box around y axis, default = 0 scale_x - rescale the x axis, default=1, useful for drawing elipses ... scale_y - rescale the x axis, default=1 angle - angle of rotation of the box in degrees, default = 0 i.e. a horizontal graph rot_x - x point of rotation's axis, default = 0, relative to top-left corner of the box, (not the conky window) rot_y - y point of rotation's axis, default = 0 relative to top-left corner of the box, (not the conky window) draw_me - if set to false, box is not drawn (default = true or 1) it can be used with a conky string, if the string returns 1, the box is drawn : example : "${if_empty ${wireless_essid wlan0}}${else}1$endif", linear_gradient - table with the coordinates of two points to define a linear gradient, points are relative to top-left corner of the box, (not the conky window) {x1,y1,x2,y2} radial_gradient - table with the coordinates of two circle to define a radial gradient, points are relative to top-left corner of the box, (not the conky window) {x1,y1,r1,x2,y2,r2} (r=radius) colour - table of colours, default = plain white {{1,0xFFFFFF,0.5}} this table contains one or more tables with format {P,C,A} P=position of gradient (0 = start of the gradient, 1= end of the gradient) C=hexadecimal colour A=alpha (opacity) of color (0=invisible,1=opacity 100%) Examples : for a plain color {{1,0x00FF00,0.5}} for a gradient with two colours {{0,0x00FF00,0.5},{1,0x000033,1}} {x=80,y=150,w=20,h=20, radial_gradient={20,20,0,20,20,20}, colour={{0.5,0xFFFFFF,1},{1,0x000000,0}}, or {{0.5,0x00FF00,1},{1,0x000033,1}} -with this one, gradient will start in the middle for a gradient with three colours {{0,0x00FF00,0.5},{0.5,0x000033,1},{1,0x440033,1}} and so on ... To call this script in Conky, use (assuming you have saved this script to ~/scripts/): lua_load ~/scripts/box.lua lua_draw_hook_pre main_box And leave one line blank or not after TEXT ]] function draw_box(data) if data.draw_me == true then data.draw_me = nil end if data.draw_me ~= nil and conky_parse(tostring(data.draw_me)) ~= "1" then return end local table_corners={"circle","curve","line"} local t_operators={ clear = CAIRO_OPERATOR_CLEAR, source = CAIRO_OPERATOR_SOURCE, over = CAIRO_OPERATOR_OVER, ["in"] = CAIRO_OPERATOR_IN, out = CAIRO_OPERATOR_OUT, atop = CAIRO_OPERATOR_ATOP, dest = CAIRO_OPERATOR_DEST, dest_over = CAIRO_OPERATOR_DEST_OVER, dest_in = CAIRO_OPERATOR_DEST_IN, dest_out = CAIRO_OPERATOR_DEST_OUT, dest_atop = CAIRO_OPERATOR_DEST_ATOP, xor = CAIRO_OPERATOR_XOR, add = CAIRO_OPERATOR_ADD, saturate = CAIRO_OPERATOR_SATURATE, } function rgba_to_r_g_b_a(tc) --tc={position,colour,alpha} local colour = tc[2] local alpha = tc[3] return ((colour / 0x10000) % 0x100) / 255., ((colour / 0x100) % 0x100) / 255., (colour % 0x100) / 255., alpha end function table.copy(data) local t2 = {} for k,v in pairs(data) do t2[k] = {v[1],v[2]} end return t2 end function draw_corner(num,t) local shape=t[1] local radius=t[2] local x,y = t[3],t[4] if shape=="line" then if num == 1 then cairo_line_to(cr,radius,0) elseif num == 2 then cairo_line_to(cr,x,radius) elseif num == 3 then cairo_line_to(cr,x-radius,y) elseif num == 4 then cairo_line_to(cr,0,y-radius) end end if shape=="circle" then local PI = math.pi if num == 1 then cairo_arc(cr,radius,radius,radius,-PI,-PI/2) elseif num == 2 then cairo_arc(cr,x-radius,y+radius,radius,-PI/2,0) elseif num == 3 then cairo_arc(cr,x-radius,y-radius,radius,0,PI/2) elseif num == 4 then cairo_arc(cr,radius,y-radius,radius,PI/2,-PI) end end if shape=="curve" then if num == 1 then cairo_curve_to(cr,0,radius ,0,0 ,radius,0) elseif num == 2 then cairo_curve_to(cr,x-radius,0, x,y, x,radius) elseif num == 3 then cairo_curve_to(cr,x,y-radius, x,y, x-radius,y) elseif num == 4 then cairo_curve_to(cr,radius,y, x,y, 0,y-radius) end end end --check values and set default values if data.x == nil then data.x = 0 end if data.y == nil then data.y = 0 end if data.w == nil then data.w = conky_window.width end if data.h == nil then data.h = conky_window.height end if data.radius == nil then data.radius = 0 end if data.border == nil then data.border = 0 end if data.colour==nil then data.colour={{1,0x000000,0.5}} end if data.linear_gradient ~= nil then if #data.linear_gradient ~= 4 then data.linear_gradient = {data.x,data.y,data.width,data.height} end end if data.angle==nil then data.angle = 0 end if data.skew_x == nil then data.skew_x=0 end if data.skew_y == nil then data.skew_y=0 end if data.scale_x==nil then data.scale_x=1 end if data.scale_y==nil then data.scale_y=1 end if data.rot_x == nil then data.rot_x=0 end if data.rot_y == nil then data.rot_y=0 end if data.operator == nil then data.operator = "over" end if (t_operators[data.operator]) == nil then print ("wrong operator :",data.operator) data.operator = "over" end if data.radial_gradient ~= nil then if #data.radial_gradient ~= 6 then data.radial_gradient = {data.x,data.y,0, data.x,data.y, data.width} end end for i=1, #data.colour do if #data.colour[i]~=3 then print ("error in color table") data.colour[i]={1,0xFFFFFF,1} end end if data.corners == nil then data.corners={ {"line",0} } end local data_corners = {} local data_corners = table.copy(data.corners) --don't use data_corners=data.corners otherwise data.corners is altered --complete the data_corners table if needed for i=#data_corners+1,4 do data_corners[i]=data_corners[#data_corners] local flag=false for j,v in pairs(table_corners) do flag=flag or (data_corners[i][1]==v) end if not flag then print ("error in corners table :",data_corners[i][1]);data_corners[i][1]="curve" end end --this way : -- data_corners[1][4]=x -- data_corners[2][3]=y --doesn't work data_corners[1]={data_corners[1][1],data_corners[1][2],0,0} data_corners[2]={data_corners[2][1],data_corners[2][2],data.w,0} data_corners[3]={data_corners[3][1],data_corners[3][2],data.w,data.h} data_corners[4]={data_corners[4][1],data_corners[4][2],0,data.h} data.no_gradient = (data.linear_gradient == nil ) and (data.radial_gradient == nil ) cairo_save(cr) cairo_translate(cr, data.x, data.y) if data.rot_x~=0 or data.rot_y~=0 or data.angle~=0 then cairo_translate(cr,data.rot_x,data.rot_y) cairo_rotate(cr,data.angle*math.pi/180) cairo_translate(cr,-data.rot_x,-data.rot_y) end if data.scale_x~=1 or data.scale_y~=1 or data.skew_x~=0 or data.skew_y~=0 then local matrix0 = cairo_matrix_t:create() tolua.takeownership(matrix0) cairo_matrix_init (matrix0, data.scale_x,math.pi*data.skew_y/180 , math.pi*data.skew_x/180 ,data.scale_y,0,0) cairo_transform(cr,matrix0) end local tc=data_corners cairo_move_to(cr,tc[1][2],0) cairo_line_to(cr,data.w-tc[2][2],0) draw_corner(2,tc[2]) cairo_line_to(cr,data.w,data.h-tc[3][2]) draw_corner(3,tc[3]) cairo_line_to(cr,tc[4][2],data.h) draw_corner(4,tc[4]) cairo_line_to(cr,0,tc[1][2]) draw_corner(1,tc[1]) if data.no_gradient then cairo_set_source_rgba(cr,rgba_to_r_g_b_a(data.colour[1])) else if data.linear_gradient ~= nil then pat = cairo_pattern_create_linear (data.linear_gradient[1],data.linear_gradient[2],data.linear_gradient[3],data.linear_gradient[4]) elseif data.radial_gradient ~= nil then pat = cairo_pattern_create_radial (data.radial_gradient[1],data.radial_gradient[2],data.radial_gradient[3], data.radial_gradient[4],data.radial_gradient[5],data.radial_gradient[6]) end for i=1, #data.colour do cairo_pattern_add_color_stop_rgba (pat, data.colour[i][1], rgba_to_r_g_b_a(data.colour[i])) end cairo_set_source (cr, pat) cairo_pattern_destroy(pat) end cairo_set_operator(cr,t_operators[data.operator]) if data.border>0 then cairo_close_path(cr) if data.dash ~= nil then cairo_set_dash(cr, data.dash, 1, 0.0) end cairo_set_line_width(cr,data.border) cairo_stroke(cr) else cairo_fill(cr) end cairo_restore(cr) end ------------------------------------------------------------------------------- -- MAIN function conky_main(color, theme, n_cpu, swap, clock_theme, player, player_theme) if conky_window == nil then return end local cs = cairo_xlib_surface_create(conky_window.display, conky_window.drawable, conky_window.visual, conky_window.width, conky_window.height) cr = cairo_create(cs) local updates=tonumber(conky_parse('${updates}')) if updates>5 then if color == "white" then bgc = 0xffffff -- the colour of the base ring. fgc = 0xffffff -- the colour of the indicator part of the ring. bga = 0.2 --the alpha value of the base ring. fga = 0.8 -- the alpha value of the indicator part of the ring. else bgc = 0x1e1c1a -- the colour of the base ring. fgc = 0x1e1c1a -- the colour of the indicator part of the ring. bga = 0.6 -- the alpha value of the base ring. fga = 0.8 -- the alpha value of the indicator part of the ring. end local theme = ("0x" .. theme) local w = conky_window.width local h = conky_window.height local hori_space = 190 local vert_space = 46 local xp = hori_space local yp = vert_space -- CPU for i=1,n_cpu do cpu_number = ("cpu" .. i) settings = {--CPU GRAPH CPU1 value=tonumber(conky_parse("${cpu " .. cpu_number .. "}")), value_max=100 , x=xp , y=yp , graph_radius=20 , graph_thickness=10 , graph_start_angle=180 , graph_unit_angle=1.85 , graph_unit_thickness=2.7 , graph_bg_colour=bgc , graph_bg_alpha=bga , graph_fg_colour=fgc , graph_fg_alpha=fga , hand_fg_colour=fgc , hand_fg_alpha=0.0 , txt_radius=35 , txt_weight=1 , txt_size=8.0 , txt_fg_colour=fgc , txt_fg_alpha=0 , graduation_radius=28 , graduation_thickness=0 , graduation_mark_thickness=1 , graduation_unit_angle=27 , graduation_fg_colour=theme , graduation_fg_alpha=0.3 , caption='' , caption_weight=1 , caption_size=10.0 , caption_fg_colour=fgc , caption_fg_alpha=fga , };draw_gauge_ring(settings) yp = yp + 64 end -- MEMORY settings = {--MEMPERC GRAPH value=tonumber(conky_parse("${memperc}")), value_max=100 , x=xp , y=yp , graph_radius=20 , graph_thickness=10 , graph_start_angle=180 , graph_unit_angle=1.85 , graph_unit_thickness=2.7 , graph_bg_colour=bgc , graph_bg_alpha=bga , graph_fg_colour=fgc , graph_fg_alpha=fga , hand_fg_colour=fgc , hand_fg_alpha=0.0 , txt_radius=35 , txt_weight=1 , txt_size=8.0 , txt_fg_colour=fgc , txt_fg_alpha=0.0 , graduation_radius=22 , graduation_thickness=0 , graduation_mark_thickness=2 , graduation_unit_angle=27 , graduation_fg_colour=fgc , graduation_fg_alpha=0.5 , caption='' , caption_weight=1 , caption_size=10.0 , caption_fg_colour=fgc , caption_fg_alpha=fga , };draw_gauge_ring(settings) -- SWAP if swap == "on" then yp = yp + 64 settings = {--SWAP FILESYSTEM USED GRAPH value=tonumber(conky_parse("${swapperc}")), value_max=100 , x=xp , y=yp , graph_radius=20 , graph_thickness=10 , graph_start_angle=180 , graph_unit_angle=1.85 , graph_unit_thickness=2.7 , graph_bg_colour=bgc , graph_bg_alpha=bga , graph_fg_colour=fgc , graph_fg_alpha=fga , hand_fg_colour=fgc , hand_fg_alpha=0.0 , txt_radius=35 , txt_weight=1 , txt_size=8.0 , txt_fg_colour=fgc , txt_fg_alpha=0 , graduation_radius=22 , graduation_thickness=0 , graduation_mark_thickness=2 , graduation_unit_angle=27 , graduation_fg_colour=fgc , graduation_fg_alpha=0.5 , caption='' , caption_weight=1 , caption_size=10.0 , caption_fg_colour=fgc , caption_fg_alpha=fga , };draw_gauge_ring(settings) end -- CLOCK if clock_theme == "cairo" then yp = yp + 64 settings = {--CLOCK HANDS xc = 154 , yc = yp , colour = bgc , alpha = 1 , show_secs = false , size = 30 , };clock_hands(settings) settings = {--SECONDS value=tonumber(conky_parse("${time %S}")), value_max = 60 , x = 154 , y = yp , bg_colour = bgc , bg_alpha = bga , fg_colour = fgc , fg_alpha = fga , radius =20 , thickness = 5 , start_angle = 0 , end_angle = 360 , lr = 0 , };draw_ring(settings) elseif clock_theme == "bigcairo" then yp = yp + 64 + 20 settings = {--CLOCK HANDS xc = 124 , yc = yp , colour = bgc , alpha = 1 , show_secs = true , size = 60 , };clock_hands(settings) settings = {--DAYS value=tonumber(conky_parse("${time %d}")), value_max = 31 , x = 124 , y = yp , bg_colour = bgc , bg_alpha = bga , fg_colour = fgc , fg_alpha = fga , radius =50 , thickness = 5 , start_angle = 215 , end_angle = 325 , lr = 0 , };draw_ring(settings) settings = {--MONTHS value=tonumber(conky_parse("${time %m}")), value_max = 12 , x = 124 , y = yp , bg_colour = bgc , bg_alpha = bga , fg_colour = fgc , fg_alpha = fga , radius = 50 , thickness = 5 , start_angle = 35 , end_angle = 145 , lr = 0 , };draw_ring(settings) settings = {--SECONDS value=tonumber(conky_parse("${time %S}")), value_max = 60 , x = 124 , y = yp , bg_colour = bgc , bg_alpha = bga , fg_colour = fgc , fg_alpha = fga , radius =40 , thickness = 10 , start_angle = 0 , end_angle = 360 , lr = 0 , };draw_ring(settings) yp = yp + 22 end yp = yp + 64 -- DISKS disks = {'/', '/home'} for i, partitions in ipairs(disks) do settings = {--FILESYSTEM USED GRAPH value=tonumber(conky_parse("${fs_used_perc " .. partitions .. "}")), value_max=100 , x=xp , y=yp , graph_radius=20 , graph_thickness=10 , graph_start_angle=180 , graph_unit_angle=1.85 , graph_unit_thickness=2.7 , graph_bg_colour=bgc , graph_bg_alpha=bga , graph_fg_colour=fgc , graph_fg_alpha=fga , hand_fg_colour=fgc , hand_fg_alpha=0.0 , txt_radius=35 , txt_weight=1 , txt_size=8.0 , txt_fg_colour=fgc , txt_fg_alpha=0 , graduation_radius=23 , graduation_thickness=0 , graduation_mark_thickness=2 , graduation_unit_angle=27 , graduation_fg_colour=fgc , graduation_fg_alpha=0.5 , caption='' , caption_weight=1 , caption_size=10.0 , caption_fg_colour=fgc , caption_fg_alpha=fga , };draw_gauge_ring(settings) yp = yp + 64 end -- PLAYERS if player == "Banshee" or player == "Clementine" or player == "Rhythmbox" then if player_theme == "cairo" then settings = { value=get_music_percent(player) , value_max = 100 , x = 154 , y = yp , bg_colour = bgc , bg_alpha = bga , fg_colour = theme , fg_alpha = fga , radius =10 , thickness = 20 , start_angle = 0 , end_angle = 360 , lr = 0 , };draw_ring(settings) settings = { value=get_music_percent(player), value_max = 100 , x = 154 , y = yp , bg_colour = bgc , bg_alpha = 0.4 , fg_colour = fgc , fg_alpha = 0.2 , radius =20 , thickness = 1 , start_angle = 0 , end_angle = 360 , lr = 0 , };draw_ring(settings) elseif player_theme == "cairocover" then settings = { value=get_music_percent(player), value_max = 100 , x = 174 , y = yp-18 , bg_colour = bgc , bg_alpha = 0.4 , fg_colour = theme , fg_alpha = 1 , radius =5 , thickness = 11 , start_angle = 0 , end_angle = 360 , lr = 0 , };draw_ring(settings) settings = { value=get_music_percent(player), value_max = 100 , x = 174 , y = yp-18 , bg_colour = bgc , bg_alpha = 0.6 , fg_colour = fgc , fg_alpha = 0.2 , radius =11 , thickness = 2 , start_angle = 0 , end_angle = 360 , lr = 0 , };draw_ring(settings) else settings = {--PLAYERS value=get_music_percent(player), value_max=100 , x=xp , y=yp , graph_radius=20 , graph_thickness=10 , graph_start_angle=180 , graph_unit_angle=1.85 , graph_unit_thickness=2.7 , graph_bg_colour=bgc , graph_bg_alpha=bga , graph_fg_colour=fgc , graph_fg_alpha=fga , hand_fg_colour=fgc , hand_fg_alpha=0.0 , txt_radius=35 , txt_weight=1 , txt_size=8.0 , txt_fg_colour=fgc , txt_fg_alpha=0 , graduation_radius=23 , graduation_thickness=0 , graduation_mark_thickness=2 , graduation_unit_angle=27 , graduation_fg_colour=fgc , graduation_fg_alpha=0.5 , caption='' , caption_weight=1 , caption_size=10.0 , caption_fg_colour=fgc , caption_fg_alpha=fga , };draw_gauge_ring(settings) end end end-- if updates>5 cairo_destroy(cr) cairo_surface_destroy(cs) cr=nil end-- end main function
gpl-3.0
leonardoaxe/OpenRA
mods/ra/maps/allies-04/allies04-AI.lua
3
7313
IdlingUnits = { } Yaks = { } AttackGroupSizes = { easy = 6, normal = 8, hard = 10 } AttackDelays = { easy = { DateTime.Seconds(4), DateTime.Seconds(9) }, normal = { DateTime.Seconds(2), DateTime.Seconds(7) }, hard = { DateTime.Seconds(1), DateTime.Seconds(5) } } AttackRallyPoints = { { SovietRally1.Location, SovietRally3.Location, SovietRally5.Location, SovietRally4.Location, SovietRally13.Location, PlayerBase.Location }, { SovietRally7.Location, SovietRally10.Location, PlayerBase.Location }, { SovietRally1.Location, SovietRally3.Location, SovietRally5.Location, SovietRally4.Location, SovietRally12.Location, PlayerBase.Location }, { SovietRally7.Location, ParadropPoint1.Location, PlayerBase.Location }, { SovietRally8.Location, SovietRally9.Location, ParadropPoint1.Location, PlayerBase.Location, } } SovietInfantryTypes = { "e1", "e1", "e2" } SovietVehicleTypes = { "3tnk", "3tnk", "3tnk", "ftrk", "ftrk", "apc" } SovietAircraftType = { "yak" } AttackOnGoing = false HoldProduction = false HarvesterKilled = false Powr1 = { name = "powr", pos = CPos.New(47, 21), prize = 500, exists = true } Barr = { name = "barr", pos = CPos.New(53, 26), prize = 400, exists = true } Proc = { name = "proc", pos = CPos.New(54, 21), prize = 1400, exists = true } Weap = { name = "weap", pos = CPos.New(48, 28), prize = 2000, exists = true } Powr2 = { name = "powr", pos = CPos.New(51, 21), prize = 500, exists = true } Powr3 = { name = "powr", pos = CPos.New(46, 25), prize = 500, exists = true } Powr4 = { name = "powr", pos = CPos.New(49, 21), prize = 500, exists = true } Ftur1 = { name = "powr", pos = CPos.New(56, 27), prize = 600, exists = true } Ftur2 = { name = "powr", pos = CPos.New(51, 32), prize = 600, exists = true } Ftur3 = { name = "powr", pos = CPos.New(54, 30), prize = 600, exists = true } Afld1 = { name = "afld", pos = CPos.New(43, 23), prize = 500, exists = true } Afld2 = { name = "afld", pos = CPos.New(43, 21), prize = 500, exists = true } BaseBuildings = { Powr1, Barr, Proc, Weap, Powr2, Powr3, Powr4, Ftur1, Ftur2, Ftur3, Afld1, Afld2 } InitialBase = { Barracks, Refinery, PowerPlant1, PowerPlant2, PowerPlant3, PowerPlant4, Warfactory, Flametur1, Flametur2, Flametur3, Airfield1, Airfield2 } BuildBase = function() if Conyard.IsDead or Conyard.Owner ~= ussr then return elseif Harvester.IsDead and ussr.Resources <= 299 then return end for i,v in ipairs(BaseBuildings) do if not v.exists then BuildBuilding(v) return end end Trigger.AfterDelay(DateTime.Seconds(10), BuildBase) end BuildBuilding = function(building) Trigger.AfterDelay(Actor.BuildTime(building.name), function() local actor = Actor.Create(building.name, true, { Owner = ussr, Location = building.pos }) ussr.Cash = ussr.Cash - building.prize building.exists = true Trigger.OnKilled(actor, function() building.exists = false end) Trigger.OnDamaged(actor, function(building) if building.Owner == ussr and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() DefendActor(actor) end end) Trigger.AfterDelay(DateTime.Seconds(10), BuildBase) end) end IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end SetupAttackGroup = function() local units = { } for i = 0, AttackGroupSize, 1 do if #IdlingUnits == 0 then return units end local number = Utils.RandomInteger(1, #IdlingUnits) if IdlingUnits[number] and not IdlingUnits[number].IsDead then units[i] = IdlingUnits[number] table.remove(IdlingUnits, number) end end return units end SendAttack = function() if Attacking then return end Attacking = true HoldProduction = true local units = SetupAttackGroup() local path = Utils.Random(AttackRallyPoints) Utils.Do(units, function(unit) unit.Patrol(path) IdleHunt(unit) end) Trigger.OnAllRemovedFromWorld(units, function() Attacking = false HoldProduction = false end) end ProtectHarvester = function(unit) DefendActor(unit) Trigger.OnKilled(unit, function() HarvesterKilled = true end) end DefendActor = function(unit) Trigger.OnDamaged(unit, function(self, attacker) if AttackOnGoing then return end AttackOnGoing = true local Guards = SetupAttackGroup() if #Guards <= 0 then AttackOnGoing = false return end Utils.Do(Guards, function(unit) if not self.IsDead then unit.AttackMove(self.Location) end IdleHunt(unit) end) Trigger.OnAllRemovedFromWorld(Guards, function() AttackOnGoing = false end) end) end InitAIUnits = function() IdlingUnits = ussr.GetGroundAttackers() DefendActor(Conyard) for i,v in ipairs(InitialBase) do DefendActor(v) Trigger.OnDamaged(v, function(building) if building.Owner == ussr and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) Trigger.OnKilled(v, function() BaseBuildings[i].exists = false end) end end ProduceInfantry = function() if HoldProduction then Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry) return end -- See AttackDelay in WorldLoaded local delay = Utils.RandomInteger(AttackDelay[1], AttackDelay[2]) local toBuild = { Utils.Random(SovietInfantryTypes) } ussr.Build(toBuild, function(unit) IdlingUnits[#IdlingUnits + 1] = unit[1] Trigger.AfterDelay(delay, ProduceInfantry) -- See AttackGroupSize in WorldLoaded if #IdlingUnits >= (AttackGroupSize * 2.5) then SendAttack() end end) end ProduceVehicles = function() if HoldProduction then Trigger.AfterDelay(DateTime.Minutes(1), ProduceVehicles) return end -- See AttackDelay in WorldLoaded local delay = Utils.RandomInteger(AttackDelay[1], AttackDelay[2]) if HarvesterKilled then ussr.Build({ "harv" }, function(harv) ProtectHarvester(harv[1]) HarvesterKilled = false Trigger.AfterDelay(delay, ProduceVehicles) end) else local toBuild = { Utils.Random(SovietVehicleTypes) } ussr.Build(toBuild, function(unit) IdlingUnits[#IdlingUnits + 1] = unit[1] Trigger.AfterDelay(delay, ProduceVehicles) -- See AttackGroupSize in WorldLoaded if #IdlingUnits >= (AttackGroupSize * 2.5) then SendAttack() end end) end end ProduceAircraft = function() ussr.Build(SovietAircraftType, function(units) local yak = units[1] Yaks[#Yaks + 1] = yak Trigger.OnKilled(yak, ProduceAircraft) if #Yaks == 1 then Trigger.AfterDelay(DateTime.Minutes(1), ProduceAircraft) end TargetAndAttack(yak) end) end TargetAndAttack = function(yak, target) if not target or target.IsDead or (not target.IsInWorld) then local enemies = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == player and self.HasProperty("Health") and yak.CanTarget(self) end) if #enemies > 0 then target = Utils.Random(enemies) end end if target and yak.AmmoCount() > 0 and yak.CanTarget(target) then yak.Attack(target) else yak.ReturnToBase() end yak.CallFunc(function() TargetAndAttack(yak, target) end) end ActivateAI = function() InitAIUnits() ProtectHarvester(Harvester) local difficulty = Map.LobbyOption("difficulty") AttackDelay = AttackDelays[difficulty] AttackGroupSize = AttackGroupSizes[difficulty] Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry() ProduceVehicles() ProduceAircraft() end) end
gpl-3.0
etienne-gauvin/projet-tut
core/libs/hump/timer.lua
7
6207
--[[ Copyright (c) 2010-2013 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local Timer = {} Timer.__index = Timer local function _nothing_() end local function new() return setmetatable({functions = {}, tween = Timer.tween}, Timer) end function Timer:update(dt) local to_remove = {} for handle, delay in pairs(self.functions) do delay = delay - dt if delay <= 0 then to_remove[#to_remove+1] = handle end self.functions[handle] = delay handle.func(dt, delay) end for _,handle in ipairs(to_remove) do self.functions[handle] = nil handle.after(handle.after) end end function Timer:do_for(delay, func, after) local handle = {func = func, after = after or _nothing_} self.functions[handle] = delay return handle end function Timer:add(delay, func) return self:do_for(delay, _nothing_, func) end function Timer:addPeriodic(delay, func, count) local count = count or math.huge -- exploit below: math.huge - 1 = math.huge return self:add(delay, function(f) if func(func) == false then return end count = count - 1 if count > 0 then self:add(delay, f) end end) end function Timer:cancel(handle) self.functions[handle] = nil end function Timer:clear() self.functions = {} end Timer.tween = setmetatable({ -- helper functions out = function(f) -- 'rotates' a function return function(s, ...) return 1 - f(1-s, ...) end end, chain = function(f1, f2) -- concatenates two functions return function(s, ...) return (s < .5 and f1(2*s, ...) or 1 + f2(2*s-1, ...)) * .5 end end, -- useful tweening functions linear = function(s) return s end, quad = function(s) return s*s end, cubic = function(s) return s*s*s end, quart = function(s) return s*s*s*s end, quint = function(s) return s*s*s*s*s end, sine = function(s) return 1-math.cos(s*math.pi/2) end, expo = function(s) return 2^(10*(s-1)) end, circ = function(s) return 1 - math.sqrt(1-s*s) end, back = function(s,bounciness) bounciness = bounciness or 1.70158 return s*s*((bounciness+1)*s - bounciness) end, bounce = function(s) -- magic numbers ahead local a,b = 7.5625, 1/2.75 return math.min(a*s^2, a*(s-1.5*b)^2 + .75, a*(s-2.25*b)^2 + .9375, a*(s-2.625*b)^2 + .984375) end, elastic = function(s, amp, period) amp, period = amp and math.max(1, amp) or 1, period or .3 return (-amp * math.sin(2*math.pi/period * (s-1) - math.asin(1/amp))) * 2^(10*(s-1)) end, }, { -- register new tween __call = function(tween, self, len, subject, target, method, after, ...) -- recursively collects fields that are defined in both subject and target into a flat list local function tween_collect_payload(subject, target, out) for k,v in pairs(target) do local ref = subject[k] assert(type(v) == type(ref), 'Type mismatch in field "'..k..'".') if type(v) == 'table' then tween_collect_payload(ref, v, out) else local ok, delta = pcall(function() return (v-ref)*1 end) assert(ok, 'Field "'..k..'" does not support arithmetic operations') out[#out+1] = {subject, k, delta} end end return out end method = tween[method or 'linear'] -- see __index local payload, t, args = tween_collect_payload(subject, target, {}), 0, {...} local last_s = 0 return self:do_for(len, function(dt) t = t + dt local s = method(math.min(1, t/len), unpack(args)) local ds = s - last_s last_s = s for _, info in ipairs(payload) do local ref, key, delta = unpack(info) ref[key] = ref[key] + delta * ds end end, after) end, -- fetches function and generated compositions for method `key` __index = function(tweens, key) if type(key) == 'function' then return key end assert(type(key) == 'string', 'Method must be function or string.') if rawget(tweens, key) then return rawget(tweens, key) end local function construct(pattern, f) local method = rawget(tweens, key:match(pattern)) if method then return f(method) end return nil end local out, chain = rawget(tweens,'out'), rawget(tweens,'chain') return construct('^in%-([^-]+)$', function(...) return ... end) or construct('^out%-([^-]+)$', out) or construct('^in%-out%-([^-]+)$', function(f) return chain(f, out(f)) end) or construct('^out%-in%-([^-]+)$', function(f) return chain(out(f), f) end) or error('Unknown interpolation method: ' .. key) end}) -- default timer local default = new() -- the module return setmetatable({ new = new, update = function(...) return default:update(...) end, do_for = function(...) return default:do_for(...) end, add = function(...) return default:add(...) end, addPeriodic = function(...) return default:addPeriodic(...) end, cancel = function(...) return default:cancel(...) end, clear = function(...) return default:clear(...) end, tween = setmetatable({}, { __index = Timer.tween, __newindex = function(_,k,v) Timer.tween[k] = v end, __call = function(t,...) return default:tween(...) end, }) }, {__call = new})
mit
yswifi/APlan
build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/modules/admin-core/luasrc/controller/admin/servicectl.lua
76
1376
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.admin.servicectl", package.seeall) function index() entry({"servicectl"}, alias("servicectl", "status")).sysauth = "root" entry({"servicectl", "status"}, call("action_status")).leaf = true entry({"servicectl", "restart"}, call("action_restart")).leaf = true end function action_status() local data = nixio.fs.readfile("/var/run/luci-reload-status") if data then luci.http.write("/etc/config/") luci.http.write(data) else luci.http.write("finish") end end function action_restart(args) local uci = require "luci.model.uci".cursor() if args then local service local services = { } for service in args:gmatch("[%w_-]+") do services[#services+1] = service end local command = uci:apply(services, true) if nixio.fork() == 0 then local i = nixio.open("/dev/null", "r") local o = nixio.open("/dev/null", "w") nixio.dup(i, nixio.stdin) nixio.dup(o, nixio.stdout) i:close() o:close() nixio.exec("/bin/sh", unpack(command)) else luci.http.write("OK") os.exit(0) end end end
gpl-2.0
abasshacker/abbas002
plugins/stats.lua
168
4001
do -- 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 = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(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 = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'creedbot' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /creedbot ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "creedbot" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (creedbot)",-- Put everything you like :) "^[!/]([Cc]reedbot)"-- Put everything you like :) }, run = run } end
gpl-2.0
bnetcc/darkstar
scripts/globals/weaponskills/calamity.lua
25
1516
----------------------------------- -- Calamity -- Axe weapon skill -- Skill level: 200 (Beastmasters and Warriors only.) -- Delivers a single-hit attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Soil Gorget & Thunder Gorget. -- Aligned with the Soil Belt & Thunder Belt. -- Element: None -- Modifiers: STR:32% ; VIT:32% -- 100%TP 200%TP 300%TP -- 1.00 1.50 4.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 4; params.str_wsc = 0.32; params.dex_wsc = 0.0; params.vit_wsc = 0.32; params.agi_wsc = 0.0; params.int_wsc = 0.0; 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 = 2.5; params.ftp200 = 6.5; params.ftp300 = 10.375; params.str_wsc = 0.5; params.vit_wsc = 0.5; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
bnetcc/darkstar
scripts/zones/Lufaise_Meadows/npcs/Jersey.lua
5
1533
----------------------------------- -- Area: Lufaise Meadows -- NPC: Jersey -- Type: Outpost Vendor -- !pos -548.706 -7.197 -53.897 24 ----------------------------------- package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); require("scripts/zones/Lufaise_Meadows/TextIDs"); local region = TAVNAZIANARCH; local csid = 0x7ff4; function onTrade(player,npc,trade) end; function onTrigger(player,npc) local owner = GetRegionOwner(region); local arg1 = getArg1(owner,player); if (owner == player:getNation()) then nation = 1; elseif (arg1 < 1792) then nation = 2; else nation = 0; end player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP()); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then ShowOPVendorShop(player); elseif (option == 2) then if (player:delGil(OP_TeleFee(player,region))) then toHomeNation(player); end elseif (option == 6) then player:delCP(OP_TeleFee(player,region)); toHomeNation(player); end end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Upper_Jeuno/npcs/Shiroro.lua
5
1043
----------------------------------- -- Area: Upper Jeuno -- NPC: Shiroro -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Upper_Jeuno/TextIDs"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,6) == false) then player:startEvent(10084); else player:startEvent(85); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 10084) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",6,true); end end;
gpl-3.0
sartura/openwrt-packages
utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/bmx6.lua
78
1115
#!/usr/bin/lua local json = require "cjson" local function interpret_suffix(rate) local value = string.sub(rate, 1, -2) local suffix = string.sub(rate, -1) if suffix == "K" then return tonumber(value) * 10^3 end if suffix == "M" then return tonumber(value) * 10^6 end if suffix == "G" then return tonumber(value) * 10^9 end return rate end local function scrape() local status = json.decode(get_contents("/var/run/bmx6/json/status")).status local labels = { version = status.version, id = status.name, address = status.primaryIp } metric("bmx6_status", "gauge", labels, 1) local links = json.decode(get_contents("/var/run/bmx6/json/links")).links local metric_bmx6_rxRate = metric("bmx6_link_rxRate","gauge") local metric_bmx6_txRate = metric("bmx6_link_txRate","gauge") for _, link in pairs(links) do local labels = { source = status.name, target = link.name, dev = link.viaDev } metric_bmx6_rxRate(labels, interpret_suffix(link.rxRate)) metric_bmx6_txRate(labels, interpret_suffix(link.txRate)) end end return { scrape = scrape }
gpl-2.0
bnetcc/darkstar
scripts/zones/Kazham/npcs/Majjih_Bakrhamab.lua
1
1746
----------------------------------- -- Area: Kazham -- NPC: Majjih Bakrhamab -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Kazham/TextIDs"); require("scripts/globals/teleports"); require("scripts/globals/settings"); require("scripts/globals/msg"); ----------------------------------- function onTrade(player,npc,trade) if (TRAVEL_SKIP >= 1) then if (trade:getGil() >= TRAVEL_SKIP and trade:getItemCount() == 1) then player:PrintToPlayer(string.format("eye's the %d gil.. ", TRAVEL_SKIP), chatType.EMOTION, npc:getName()); player:PrintToPlayer("Well..I guess I can let you aboard the express freight Vessel.. ", chatType.SAY, npc:getName()); player:delGil(TRAVEL_SKIP); -- player:setPos(-26,12,120,64,246); player:addStatusEffectEx(EFFECT_COMMUTE,0,COMMUTE.AISHIP_TO_JEUNO_K,0,2); end end end; function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 1 do vHour = vHour - 6; end if ( vHour == -5) then vHour = 1; elseif ( vHour == -4) then vHour = 2; elseif ( vHour == -3) then vHour = 3; elseif ( vHour == -2) then vHour = 4; elseif ( vHour == -1) then vHour = 5; end local seconds = math.floor(2.4 * ((vHour * 60) + vMin)); player:startEvent( 261, seconds, 0, 0, 0, 0, 0, 0, 0); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
awesomeWM/awesome
lib/menubar/init.lua
1
20313
--------------------------------------------------------------------------- --- Menubar module, which aims to provide a freedesktop menu alternative. -- -- List of menubar keybindings: -- --- -- -- <table class='widget_list' border=1> -- <tr style='font-weight: bold;'> -- <th align='center'>Keybinding</th> -- <th align='center'>Description</th> -- </tr> </td></tr> -- <tr><td><kbd>Left</kbd><kbd>C-j</kbd></td><td> select an item on the left </td></tr> -- <tr><td><kbd>Right</kbd><kbd>C-k</kbd></td><td> select an item on the right </td></tr> -- <tr><td><kbd>Backspace </kbd></td><td> exit the current category if we are in any </td></tr> -- <tr><td><kbd>Escape </kbd></td><td> exit the current directory or exit menubar </td></tr> -- <tr><td><kbd>Home </kbd></td><td> select the first item </td></tr> -- <tr><td><kbd>End </kbd></td><td> select the last </td></tr> -- <tr><td><kbd>Return </kbd></td><td> execute the entry </td></tr> -- <tr><td><kbd>C-Return </kbd></td><td> execute the command with awful.spawn </td></tr> -- <tr><td><kbd>C-M-Return </kbd></td><td> execute the command in a terminal </td></tr> -- </table> -- -- @author Alexander Yakushev &lt;yakushev.alex@gmail.com&gt; -- @copyright 2011-2012 Alexander Yakushev -- @popupmod menubar --------------------------------------------------------------------------- -- Grab environment we need local capi = { client = client, mouse = mouse, screen = screen } local gmath = require("gears.math") local awful = require("awful") local gfs = require("gears.filesystem") local common = require("awful.widget.common") local theme = require("beautiful") local wibox = require("wibox") local gcolor = require("gears.color") local gstring = require("gears.string") local gdebug = require("gears.debug") local function get_screen(s) return s and capi.screen[s] end --- Menubar normal text color. -- @beautiful beautiful.menubar_fg_normal -- @param color --- Menubar normal background color. -- @beautiful beautiful.menubar_bg_normal -- @param color --- Menubar border width. -- @beautiful beautiful.menubar_border_width -- @tparam[opt=0] number menubar_border_width --- Menubar border color. -- @beautiful beautiful.menubar_border_color -- @param color --- Menubar selected item text color. -- @beautiful beautiful.menubar_fg_focus -- @param color --- Menubar selected item background color. -- @beautiful beautiful.menubar_bg_focus -- @param color --- Menubar font. -- @beautiful beautiful.menubar_font -- @param[opt=beautiful.font] font -- menubar local menubar = { menu_entries = {} } menubar.menu_gen = require("menubar.menu_gen") menubar.utils = require("menubar.utils") -- Options section --- When true the .desktop files will be reparsed only when the -- extension is initialized. Use this if menubar takes much time to -- open. -- @tfield[opt=true] boolean cache_entries menubar.cache_entries = true --- When true the categories will be shown alongside application -- entries. -- @tfield[opt=true] boolean show_categories menubar.show_categories = true --- When false will hide results if the current query is empty -- @tfield[opt=true] boolean match_empty menubar.match_empty = true --- Specifies the geometry of the menubar. This is a table with the keys -- x, y, width and height. Missing values are replaced via the screen's -- geometry. However, missing height is replaced by the font size. -- @table geometry -- @tfield number geometry.x A forced horizontal position -- @tfield number geometry.y A forced vertical position -- @tfield number geometry.width A forced width -- @tfield number geometry.height A forced height menubar.geometry = { width = nil, height = nil, x = nil, y = nil } --- Width of blank space left in the right side. -- @tfield number right_margin menubar.right_margin = theme.xresources.apply_dpi(8) --- Label used for "Next page", default "▶▶". -- @tfield[opt="▶▶"] string right_label menubar.right_label = "▶▶" --- Label used for "Previous page", default "◀◀". -- @tfield[opt="◀◀"] string left_label menubar.left_label = "◀◀" -- awful.widget.common.list_update adds spacing of dpi(4) between items. -- @tfield number list_spacing local list_spacing = theme.xresources.apply_dpi(4) --- Allows user to specify custom parameters for prompt.run function -- (like colors). This will merge with the default parameters, overriding affected values. -- @see awful.prompt menubar.prompt_args = {} -- Private section local current_item = 1 local previous_item = nil local current_category = nil local shownitems = nil local instance = nil local common_args = { w = wibox.layout.fixed.horizontal(), data = setmetatable({}, { __mode = 'kv' }) } --- Wrap the text with the color span tag. -- @param s The text. -- @param c The desired text color. -- @return the text wrapped in a span tag. local function colortext(s, c) return "<span color='" .. gcolor.ensure_pango_color(c) .. "'>" .. s .. "</span>" end --- Get how the menu item should be displayed. -- @param o The menu item. -- @return item name, item background color, background image, item icon, item args. local function label(o) local fg_color = theme.menubar_fg_normal or theme.menu_fg_normal or theme.fg_normal local bg_color = theme.menubar_bg_normal or theme.menu_bg_normal or theme.bg_normal if o.focused then fg_color = theme.menubar_fg_focus or theme.menu_fg_focus or theme.fg_focus bg_color = theme.menubar_bg_focus or theme.menu_bg_focus or theme.bg_focus end return colortext(gstring.xml_escape(o.name), fg_color), bg_color, nil, o.icon, o.icon and {icon_size=instance.geometry.height} end local function load_count_table() if instance.count_table then return instance.count_table end instance.count_table = {} local count_file_name = gfs.get_cache_dir() .. "/menu_count_file" local count_file = io.open (count_file_name, "r") if count_file then for line in count_file:lines() do local name, count = string.match(line, "([^;]+);([^;]+)") if name ~= nil and count ~= nil then instance.count_table[name] = count end end count_file:close() end return instance.count_table end local function write_count_table(count_table) count_table = count_table or instance.count_table local count_file_name = gfs.get_cache_dir() .. "/menu_count_file" local count_file = assert(io.open(count_file_name, "w")) for name, count in pairs(count_table) do local str = string.format("%s;%d\n", name, count) count_file:write(str) end count_file:close() end --- Perform an action for the given menu item. -- @param o The menu item. -- @return if the function processed the callback, new awful.prompt command, new awful.prompt prompt text. local function perform_action(o) if not o then return end if o.key then current_category = o.key local new_prompt = shownitems[current_item].name .. ": " previous_item = current_item current_item = 1 return true, "", new_prompt elseif shownitems[current_item].cmdline then awful.spawn(shownitems[current_item].cmdline) -- load count_table from cache file local count_table = load_count_table() -- increase count local curname = shownitems[current_item].name count_table[curname] = (count_table[curname] or 0) + 1 -- write updated count table to cache file write_count_table(count_table) -- Let awful.prompt execute dummy exec_callback and -- done_callback to stop the keygrabber properly. return false end end -- Cut item list to return only current page. -- @tparam table all_items All items list. -- @tparam str query Search query. -- @tparam number|screen scr Screen -- @return table List of items for current page. local function get_current_page(all_items, query, scr) local compute_text_width = function(text, s) return wibox.widget.textbox.get_markup_geometry(text, s, instance.font)['width'] end scr = get_screen(scr) if not instance.prompt.width then instance.prompt.width = compute_text_width(instance.prompt.prompt, scr) end if not menubar.left_label_width then menubar.left_label_width = compute_text_width(menubar.left_label, scr) end if not menubar.right_label_width then menubar.right_label_width = compute_text_width(menubar.right_label, scr) end local border_width = theme.menubar_border_width or theme.menu_border_width or 0 local available_space = instance.geometry.width - menubar.right_margin - menubar.right_label_width - menubar.left_label_width - compute_text_width(query..' ', scr) - instance.prompt.width - border_width * 2 -- space character is added as input cursor placeholder local width_sum = 0 local current_page = {} for i, item in ipairs(all_items) do item.width = item.width or ( compute_text_width(label(item), scr) + (item.icon and (instance.geometry.height + list_spacing) or 0) + list_spacing * 2 ) if width_sum + item.width > available_space then if current_item < i then table.insert(current_page, { name = menubar.right_label, icon = nil }) break end current_page = { { name = menubar.left_label, icon = nil }, item, } width_sum = item.width else table.insert(current_page, item) width_sum = width_sum + item.width end end return current_page end --- Update the menubar according to the command entered by user. -- @tparam number|screen scr Screen local function menulist_update(scr) local query = instance.query or "" shownitems = {} local pattern = gstring.query_to_pattern(query) -- All entries are added to a list that will be sorted -- according to the priority (first) and weight (second) of its -- entries. -- If categories are used in the menu, we add the entries matching -- the current query with high priority as to ensure they are -- displayed first. Afterwards the non-category entries are added. -- All entries are weighted according to the number of times they -- have been executed previously (stored in count_table). local count_table = load_count_table() local command_list = {} local PRIO_NONE = 0 local PRIO_CATEGORY_MATCH = 2 -- Add the categories if menubar.show_categories then for _, v in pairs(menubar.menu_gen.all_categories) do v.focused = false if not current_category and v.use then -- check if current query matches a category if string.match(v.name, pattern) then v.weight = 0 v.prio = PRIO_CATEGORY_MATCH -- get use count from count_table if present -- and use it as weight if string.len(pattern) > 0 and count_table[v.name] ~= nil then v.weight = tonumber(count_table[v.name]) end -- check for prefix match if string.match(v.name, "^" .. pattern) then -- increase default priority v.prio = PRIO_CATEGORY_MATCH + 1 else v.prio = PRIO_CATEGORY_MATCH end table.insert (command_list, v) end end end end -- Add the applications according to their name and cmdline local add_entry = function(entry) entry.focused = false if not current_category or entry.category == current_category then -- check if the query matches either the name or the commandline -- of some entry if string.match(entry.name, pattern) or string.match(entry.cmdline, pattern) then entry.weight = 0 entry.prio = PRIO_NONE -- get use count from count_table if present -- and use it as weight if string.len(pattern) > 0 and count_table[entry.name] ~= nil then entry.weight = tonumber(count_table[entry.name]) end -- check for prefix match if string.match(entry.name, "^" .. pattern) or string.match(entry.cmdline, "^" .. pattern) then -- increase default priority entry.prio = PRIO_NONE + 1 else entry.prio = PRIO_NONE end table.insert (command_list, entry) end end end -- Add entries if required if query ~= "" or menubar.match_empty then for _, v in ipairs(menubar.menu_entries) do add_entry(v) end end local function compare_counts(a, b) if a.prio == b.prio then return a.weight > b.weight end return a.prio > b.prio end -- sort command_list by weight (highest first) table.sort(command_list, compare_counts) -- copy into showitems shownitems = command_list if #shownitems > 0 then -- Insert a run item value as the last choice table.insert(shownitems, { name = "Exec: " .. query, cmdline = query, icon = nil }) if current_item > #shownitems then current_item = #shownitems end shownitems[current_item].focused = true else table.insert(shownitems, { name = "", cmdline = query, icon = nil }) end common.list_update(common_args.w, nil, label, common_args.data, get_current_page(shownitems, query, scr)) end --- Refresh menubar's cache by reloading .desktop files. -- @tparam[opt=awful.screen.focused()] screen scr Screen. -- @noreturn -- @staticfct menubar.refresh function menubar.refresh(scr) scr = get_screen(scr or awful.screen.focused() or 1) menubar.menu_gen.generate(function(entries) menubar.menu_entries = entries if instance then menulist_update(scr) end end) end --- Awful.prompt keypressed callback to be used when the user presses a key. -- @param mod Table of key combination modifiers (Control, Shift). -- @param key The key that was pressed. -- @param comm The current command in the prompt. -- @return if the function processed the callback, new awful.prompt command, new awful.prompt prompt text. local function prompt_keypressed_callback(mod, key, comm) if key == "Left" or (mod.Control and key == "j") then current_item = math.max(current_item - 1, 1) return true elseif key == "Right" or (mod.Control and key == "k") then current_item = current_item + 1 return true elseif key == "BackSpace" then if comm == "" and current_category then current_category = nil current_item = previous_item return true, nil, "Run: " end elseif key == "Escape" then if current_category then current_category = nil current_item = previous_item return true, nil, "Run: " end elseif key == "Home" then current_item = 1 return true elseif key == "End" then current_item = #shownitems return true elseif key == "Return" or key == "KP_Enter" then if mod.Control then current_item = #shownitems if mod.Mod1 then -- add a terminal to the cmdline shownitems[current_item].cmdline = menubar.utils.terminal .. " -e " .. shownitems[current_item].cmdline end end return perform_action(shownitems[current_item]) end return false end --- Show the menubar on the given screen. -- @tparam[opt=awful.screen.focused()] screen scr Screen. -- @noreturn -- @staticfct menubar.show -- @usebeautiful beautiful.menubar_fg_normal -- @usebeautiful beautiful.menubar_bg_normal -- @usebeautiful beautiful.menubar_border_width -- @usebeautiful beautiful.menubar_border_color -- @usebeautiful beautiful.menubar_fg_focus -- @usebeautiful beautiful.menubar_bg_focus -- @usebeautiful beautiful.menubar_font function menubar.show(scr) scr = get_screen(scr or awful.screen.focused() or 1) local fg_color = theme.menubar_fg_normal or theme.menu_fg_normal or theme.fg_normal local bg_color = theme.menubar_bg_normal or theme.menu_bg_normal or theme.bg_normal local border_width = theme.menubar_border_width or theme.menu_border_width or 0 local border_color = theme.menubar_border_color or theme.menu_border_color local font = theme.menubar_font or theme.font or "Monospace 10" if not instance then -- Add to each category the name of its key in all_categories for k, v in pairs(menubar.menu_gen.all_categories) do v.key = k end if menubar.cache_entries then menubar.refresh(scr) end instance = { wibox = wibox{ ontop = true, bg = bg_color, fg = fg_color, border_width = border_width, border_color = border_color, font = font, }, widget = common_args.w, prompt = awful.widget.prompt(), query = nil, count_table = nil, font = font, } local layout = wibox.layout.fixed.horizontal() layout:add(instance.prompt) layout:add(instance.widget) instance.wibox:set_widget(layout) end if instance.wibox.visible then -- Menu already shown, exit return elseif not menubar.cache_entries then menubar.refresh(scr) end -- Set position and size local scrgeom = scr.workarea local geometry = menubar.geometry instance.geometry = {x = geometry.x or scrgeom.x, y = geometry.y or scrgeom.y, height = geometry.height or gmath.round(theme.get_font_height(font) * 1.5), width = (geometry.width or scrgeom.width) - border_width * 2} instance.wibox:geometry(instance.geometry) current_item = 1 current_category = nil menulist_update(scr) local default_prompt_args = { prompt = "Run: ", textbox = instance.prompt.widget, completion_callback = awful.completion.shell, history_path = gfs.get_cache_dir() .. "/history_menu", done_callback = menubar.hide, changed_callback = function(query) instance.query = query menulist_update(scr) end, keypressed_callback = prompt_keypressed_callback } awful.prompt.run(setmetatable(menubar.prompt_args, {__index=default_prompt_args})) instance.wibox.visible = true end --- Hide the menubar. -- @staticfct menubar.hide -- @noreturn function menubar.hide() if instance then instance.wibox.visible = false instance.query = nil end end --- Get a menubar wibox. -- @tparam[opt] screen scr Screen. -- @return menubar wibox. -- @deprecated get function menubar.get(scr) gdebug.deprecate("Use menubar.show() instead", { deprecated_in = 5 }) menubar.refresh(scr) -- Add to each category the name of its key in all_categories for k, v in pairs(menubar.menu_gen.all_categories) do v.key = k end return common_args.w end local mt = {} function mt.__call(_, ...) return menubar.get(...) end return setmetatable(menubar, mt) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
bnetcc/darkstar
scripts/zones/The_Boyahda_Tree/mobs/Modrons_Druid.lua
1
1451
----------------------------------- -- Area: EDIT ME -- VWNM: ME TO ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) -- setMobMod mob:setMobMod(MOBMOD_MAGIC_COOL, 45); -- addMod mob:addMod(MOD_MDEF,50); mob:addMod(MOD_DEF,50); mob:addMod(MOD_ATT,150); end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) -- setMod mob:setMod(MOD_REGEN, 100); mob:setMod(MOD_REGAIN, 10); mob:setMod(MOD_REFRESH, 250); mob:setMod(MOD_UFASTCAST, 55); mob:setMod(MOD_MACC,1950); mob:setMod(MOD_MATT,90); mob:setMod(MOD_DOUBLE_ATTACK,25); -- var -- mob:setLocalVar("depopTime", os.time(t) + 1800); -- despawn in 30 min end; ----------------------------------- -- onMobEngage Action ----------------------------------- function onMobEngaged(mob, target) end; ----------------------------------- -- onMobWeaponSkill Action ----------------------------------- function onMobWeaponSkill(target, mob, skill) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end;
gpl-3.0
bnetcc/darkstar
scripts/globals/spells/bluemagic/mind_blast.lua
5
1879
----------------------------------------- -- Spell: Mind Blast -- Deals lightning damage to an enemy. Additional effect: Paralysis -- Spell cost: 82 MP -- Monster Type: Demons -- Spell Type: Magical (Lightning) -- Blue Magic Points: 4 -- Stat Bonus: MP+5 MND+1 -- Level: 73 -- Casting Time: 3 seconds -- Recast Time: 30 seconds -- Magic Bursts on: Impaction, Fragmentation, and Light -- Combos: Clear Mind ----------------------------------------- require("scripts/globals/bluemagic"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local params = {}; params.diff = caster:getStat(MOD_INT) - target:getStat(MOD_INT); params.attribute = MOD_INT; params.skillType = BLUE_SKILL; params.bonus = 1.0; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.multiplier = 7.08; params.tMultiplier = 1.5; params.duppercap = 69; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0; local resist = applyResistance(caster, target, spell, params); local damage = BlueMagicalSpell(caster, target, spell, params, MND_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); if (caster:hasStatusEffect(EFFECT_AZURE_LORE)) then params.multiplier = params.multiplier + 0.50; end if (damage > 0 and resist > 0.3) then local typeEffect = EFFECT_PARALYSIS; target:addStatusEffect(typeEffect,20,0,getBlueEffectDuration(caster,resist,typeEffect)); -- https://www.bg-wiki.com/bg/Mind_Blast says 20% end return damage; end;
gpl-3.0
TurkeyMan/premake-core
binmodules/luasocket/src/mbox.lua
51
2654
local _M = {} if module then mbox = _M end function _M.split_message(message_s) local message = {} message_s = string.gsub(message_s, "\r\n", "\n") string.gsub(message_s, "^(.-\n)\n", function (h) message.headers = h end) string.gsub(message_s, "^.-\n\n(.*)", function (b) message.body = b end) if not message.body then string.gsub(message_s, "^\n(.*)", function (b) message.body = b end) end if not message.headers and not message.body then message.headers = message_s end return message.headers or "", message.body or "" end function _M.split_headers(headers_s) local headers = {} headers_s = string.gsub(headers_s, "\r\n", "\n") headers_s = string.gsub(headers_s, "\n[ ]+", " ") string.gsub("\n" .. headers_s, "\n([^\n]+)", function (h) table.insert(headers, h) end) return headers end function _M.parse_header(header_s) header_s = string.gsub(header_s, "\n[ ]+", " ") header_s = string.gsub(header_s, "\n+", "") local _, __, name, value = string.find(header_s, "([^%s:]-):%s*(.*)") return name, value end function _M.parse_headers(headers_s) local headers_t = _M.split_headers(headers_s) local headers = {} for i = 1, #headers_t do local name, value = _M.parse_header(headers_t[i]) if name then name = string.lower(name) if headers[name] then headers[name] = headers[name] .. ", " .. value else headers[name] = value end end end return headers end function _M.parse_from(from) local _, __, name, address = string.find(from, "^%s*(.-)%s*%<(.-)%>") if not address then _, __, address = string.find(from, "%s*(.+)%s*") end name = name or "" address = address or "" if name == "" then name = address end name = string.gsub(name, '"', "") return name, address end function _M.split_mbox(mbox_s) local mbox = {} mbox_s = string.gsub(mbox_s, "\r\n", "\n") .."\n\nFrom \n" local nj, i, j = 1, 1, 1 while 1 do i, nj = string.find(mbox_s, "\n\nFrom .-\n", j) if not i then break end local message = string.sub(mbox_s, j, i-1) table.insert(mbox, message) j = nj+1 end return mbox end function _M.parse(mbox_s) local mbox = _M.split_mbox(mbox_s) for i = 1, #mbox do mbox[i] = _M.parse_message(mbox[i]) end return mbox end function _M.parse_message(message_s) local message = {} message.headers, message.body = _M.split_message(message_s) message.headers = _M.parse_headers(message.headers) return message end return _M
bsd-3-clause
mwoz123/koreader
plugins/evernote.koplugin/JoplinClient.lua
2
4191
local http = require("socket.http") local json = require("json") local ltn12 = require("ltn12") local socketutil = require("socketutil") local JoplinClient = { server_ip = "localhost", server_port = 41184, auth_token = "" } function JoplinClient:new(o) o = o or {} self.__index = self setmetatable(o, self) return o end function JoplinClient:_makeRequest(url, method, request_body) local sink = {} local request_body_json = json.encode(request_body) local source = ltn12.source.string(request_body_json) socketutil:set_timeout(socketutil.LARGE_BLOCK_TIMEOUT, socketutil.LARGE_TOTAL_TIMEOUT) http.request{ url = url, method = method, sink = ltn12.sink.table(sink), source = source, headers = { ["Content-Length"] = #request_body_json, ["Content-Type"] = "application/json" }, } socketutil:reset_timeout() if not sink[1] then error("No response from Joplin Server") end local response = json.decode(sink[1]) if response.error then error(response.error) end return response end function JoplinClient:ping() local sink = {} http.request{ url = "http://"..self.server_ip..":"..self.server_port.."/ping", method = "GET", sink = ltn12.sink.table(sink) } if sink[1] == "JoplinClipperServer" then return true else return false end end -- If successful returns id of found note. function JoplinClient:findNoteByTitle(title, notebook_id) local url_base = "http://"..self.server_ip..":"..self.server_port.."/notes?".."token="..self.auth_token.."&fields=id,title,parent_id&page=" local url local page = 1 local has_more repeat url = url_base..page local notes = self:_makeRequest(url, "GET") has_more = notes.has_more for _, note in ipairs(notes.items) do if note.title == title then if notebook_id == nil or note.parent_id == notebook_id then return note.id end end end page = page + 1 until not has_more return false end -- If successful returns id of found notebook (folder). function JoplinClient:findNotebookByTitle(title) local url_base = "http://"..self.server_ip..":"..self.server_port.."/folders?".."token="..self.auth_token.."&".."query="..title.."&page=" local url local page = 1 local has_more repeat url = url_base..page local folders = self:_makeRequest(url, "GET") has_more = folders.has_more for _, folder in ipairs(folders.items) do if folder.title == title then return folder.id end end page = page + 1 until not has_more return false end -- If successful returns id of created notebook (folder). function JoplinClient:createNotebook(title, created_time) local request_body = { title = title, created_time = created_time } local url = "http://"..self.server_ip..":"..self.server_port.."/folders?".."token="..self.auth_token local response = self:_makeRequest(url, "POST", request_body) return response.id end -- If successful returns id of created note. function JoplinClient:createNote(title, note, parent_id, created_time) local request_body = { title = title, body = note, parent_id = parent_id, created_time = created_time } local url = "http://"..self.server_ip..":"..self.server_port.."/notes?".."token="..self.auth_token local response = self:_makeRequest(url, "POST", request_body) return response.id end -- If successful returns id of updated note. function JoplinClient:updateNote(note_id, note, title, parent_id) local request_body = { body = note, title = title, parent_id = parent_id } local url = "http://"..self.server_ip..":"..self.server_port.."/notes/"..note_id.."?token="..self.auth_token local response = self:_makeRequest(url, "PUT", request_body) return response.id end return JoplinClient
agpl-3.0
bnetcc/darkstar
scripts/zones/Foret_de_Hennetiel/Zone.lua
1
1200
----------------------------------- -- -- Zone: Foret de Hennetiel -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Foret_de_Hennetiel/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Foret_de_Hennetiel/TextIDs"); ----------------------------------- function onInitialize(zone) end; function onZoneIn(player,prevZone) local cs = -1; player:setVar("HpTeleportMask1a", 0); player:setVar("HpTeleportMask1b", 0); player:setVar("HpTeleportMask2a", 0); player:setVar("HpTeleportMask2b", 0); player:setVar("HpTeleportMask3a", 0); player:setVar("HpTeleportMask3b", 0); player:setVar("HpTeleportMask4a", 0); player:setVar("HpTeleportMask4b", 0); if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(360,6,455,93); end return cs; end; function onRegionEnter(player,region) end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
dragynbane222/awesome-dot-files
themes/cool-blue/theme.lua
2
2780
-- cool-blue, awesome3 theme, inspired by Adobe Kuler --{{{ Main local awful = require("awful") awful.util = require("awful.util") theme = {} home = os.getenv("HOME") config = awful.util.getdir("config") shared = "/usr/share/awesome" if not awful.util.file_readable(shared .. "/icons/awesome16.png") then shared = "/usr/share/local/awesome" end sharedicons = shared .. "/icons" sharedthemes = shared .. "/themes" themes = config .. "/themes" themename = "/cool-blue" if not awful.util.file_readable(themes .. themename .. "/theme.lua") then themes = sharedthemes end themedir = themes .. themename wallpaper1 = themedir .. "/background.jpg" wallpaper2 = themedir .. "/background.png" wallpaper3 = sharedthemes .. "/zenburn/zenburn-background.png" wallpaper4 = sharedthemes .. "/default/background.png" wpscript = home .. "/.wallpaper" if awful.util.file_readable(wallpaper1) then theme.wallpaper = wallpaper1 elseif awful.util.file_readable(wallpaper2) then theme.wallpaper = wallpaper2 elseif awful.util.file_readable(wpscript) then theme.wallpaper_cmd = { "sh " .. wpscript } elseif awful.util.file_readable(wallpaper3) then theme.wallpaper = wallpaper3 else theme.wallpaper = wallpaper4 end if awful.util.file_readable(config .. "/vain/init.lua") then theme.useless_gap_width = "3" end --}}} -- {{{ Styles theme.font = "Profont 8" -- {{{ Colors theme.fg_normal = "#54534B" theme.fg_focus = "#54534B" theme.fg_urgent = "#562630" --theme.fg_minimize = "#000000" theme.bg_normal = "#7D8C7C" theme.bg_focus = "#BCBDA5" theme.bg_urgent = "#DACEB1" --theme.bg_minimize = "#81654F" -- }}} -- {{{ Borders theme.border_width = "1" theme.border_normal = "#7D8C7C" theme.border_focus = "#BCBDA5" theme.border_marked = "#562630" -- }}} -- {{{ Titlebars theme.titlebar_bg_focus = "#BCBDA5" theme.titlebar_bg_normal = "#BCBDA5" --"#7D8C7C" -- }}} -- }}} -- {{{ Icons / Misc. theme.layout_fairh = themedir .. "/layouts/fairhw.png" theme.layout_fairv = themedir .. "/layouts/fairvw.png" theme.layout_floating = themedir .. "/layouts/floatingw.png" theme.layout_magnifier = themedir .. "/layouts/magnifierw.png" theme.layout_max = themedir .. "/layouts/maxw.png" theme.layout_fullscreen = themedir .. "/layouts/fullscreenw.png" theme.layout_tilebottom = themedir .. "/layouts/tilebottomw.png" theme.layout_tileleft = themedir .. "/layouts/tileleftw.png" theme.layout_tile = themedir .. "/layouts/tilew.png" theme.layout_tiletop = themedir .. "/layouts/tiletopw.png" theme.layout_spiral = themedir .. "/layouts/spiralw.png" theme.layout_dwindle = themedir .. "/layouts/dwindlew.png" theme.awesome_icon = themedir .. "/logo20_orange.png" -- }}} return theme
gpl-2.0
bnetcc/darkstar
scripts/globals/spells/bluemagic/dark_orb.lua
1
1097
----------------------------------------- -- Spell: Dark Orb ----------------------------------------- require("scripts/globals/bluemagic"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage local multi = 7.08; if (caster:hasStatusEffect(EFFECT_AZURE_LORE)) then multi = multi + 0.50; end params.multiplier = multi; params.tMultiplier = 2.5; params.duppercap = 90; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; local damage = BlueMagicalSpell(caster, target, spell, params, MND_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
bnetcc/darkstar
scripts/zones/West_Sarutabaruta/npcs/Banege_RK.lua
3
2981
----------------------------------- -- Area: West Sarutabaruta -- NPC: Banege, R.K. -- Type: Border Conquest Guards -- !pos 399.450 -25.858 727.545 115 ----------------------------------- package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/West_Sarutabaruta/TextIDs"); local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = SARUTABARUTA; local csid = 0x7ffa; function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
yswifi/APlan
build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/applications/luci-wol/luasrc/model/cbi/wol.lua
42
2521
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local sys = require "luci.sys" local fs = require "nixio.fs" m = SimpleForm("wol", translate("Wake on LAN"), translate("Wake on LAN is a mechanism to remotely boot computers in the local network.")) m.submit = translate("Wake up host") m.reset = false local has_ewk = fs.access("/usr/bin/etherwake") local has_wol = fs.access("/usr/bin/wol") s = m:section(SimpleSection) if has_ewk and has_wol then bin = s:option(ListValue, "binary", translate("WoL program"), translate("Sometimes only one of both tools work. If one of fails, try the other one")) bin:value("/usr/bin/etherwake", "Etherwake") bin:value("/usr/bin/wol", "WoL") end if has_ewk then iface = s:option(ListValue, "iface", translate("Network interface to use"), translate("Specifies the interface the WoL packet is sent on")) if has_wol then iface:depends("binary", "/usr/bin/etherwake") end iface:value("", translate("Broadcast on all interfaces")) for _, e in ipairs(sys.net.devices()) do if e ~= "lo" then iface:value(e) end end end host = s:option(Value, "mac", translate("Host to wake up"), translate("Choose the host to wake up or enter a custom MAC address to use")) sys.net.mac_hints(function(mac, name) host:value(mac, "%s (%s)" %{ mac, name }) end) function host.write(self, s, val) local host = luci.http.formvalue("cbid.wol.1.mac") if host and #host > 0 and host:match("^[a-fA-F0-9:]+$") then local cmd local util = luci.http.formvalue("cbid.wol.1.binary") or ( has_ewk and "/usr/bin/etherwake" or "/usr/bin/wol" ) if util == "/usr/bin/etherwake" then local iface = luci.http.formvalue("cbid.wol.1.iface") cmd = "%s -D%s %q" %{ util, (iface ~= "" and " -i %q" % iface or ""), host } else cmd = "%s -v %q" %{ util, host } end local msg = "<p><strong>%s</strong><br /><br /><code>%s<br /><br />" %{ translate("Starting WoL utility:"), cmd } local p = io.popen(cmd .. " 2>&1") if p then while true do local l = p:read("*l") if l then if #l > 100 then l = l:sub(1, 100) .. "..." end msg = msg .. l .. "<br />" else break end end p:close() end msg = msg .. "</code></p>" m.message = msg end end return m
gpl-2.0
bnetcc/darkstar
scripts/zones/Bastok_Markets/npcs/Foss.lua
5
1323
----------------------------------- -- Area: Bastok Markets -- NPC: Foss -- Starts & Finishes Repeatable Quest: Buckets of Gold -- !pos -283 -12 -37 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bastok_Markets/TextIDs"); require("scripts/globals/npc_util"); require("scripts/globals/quests"); require("scripts/globals/titles"); function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,BUCKETS_OF_GOLD) >= QUEST_ACCEPTED and npcUtil.tradeHas(trade, {{90,5}})) then player:startEvent(272); end end; function onTrigger(player,npc) if (player:getQuestStatus(BASTOK,BUCKETS_OF_GOLD) == QUEST_AVAILABLE) then player:startEvent(271); else player:startEvent(270); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 271 and option == 0) then player:addQuest(BASTOK,BUCKETS_OF_GOLD); elseif (csid == 272) then local fame = player:hasCompleteQuest(BASTOK, BUCKETS_OF_GOLD) and 8 or 75; if (npcUtil.completeQuest(player, BASTOK, BUCKETS_OF_GOLD, {title=BUCKET_FISHER, gil=300, fame=fame})) then player:confirmTrade(); end end end;
gpl-3.0