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
DrayChou/telegram-bot
bot/utils.lua
239
13499
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end
gpl-2.0
vilarion/Illarion-Content
item/id_3894_mystical_cracker.lua
1
24554
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.id_3894_mystical_cracker' WHERE itm_id=3894; local common = require("base.common") local M = {} -- That list contains nearly all items a player can carry. local itemList = { 306,-- Schinken ham 307 ,--Schweinefleisch pork 354 ,--Erdbeertorte strawberry cake 755 ,--Feuerwurz fire root 756 ,--Frommbeeren pious berry 41 ,--Glasblock glass ingot 227 ,--Kochlöffel cooking spoon 335 ,--Laute lute 353 ,--Apfelkuchen apple pie 355 ,--Lachs salmon 356 ,--Schlapphut hat 357 ,--blauer Zauberhut blue wizard hat 358 ,--roter Zauberhut red wizard hat 363 ,--Lederschuppenrüstung leather scale armour 364 ,--leichte Jagdrüstung light hunting armour 365 ,--halbe Lederrüstung half leather armour 366 ,--Lederbeinschienen leather leggings 367 ,--kurze Lederbeinschienen short leather leggings 400 ,--Kerze candle 534 ,--Zwiebelsamen onion seeds 43 ,--Kerzen candles 1840 ,--Kupferkelch copper goblet 1908 ,--Glaskrug glass mug 1909 ,--Bierkrug beer mug 1910 ,--Bierkrug beer mug 2056 ,--Glas mit Met glass with mead 2057 ,--Glas mit Wein glass with wine 2058 ,--Glas mit Wasser glass with water 2059 ,--Glas mit Cider glass with cider 2112 ,--kurze Kettenhose short chain trousers 2114 ,--kurze Fellhose short fur trousers 2116 ,--eiserne Beinschienen iron greaves 2117 ,--kurze eiserne Beinschienen short iron greaves 766 ,--Trugblüte con blossom 2683 ,--weiße Farbe white dye 3076 ,--Kupferstücke copper coins 17 ,--Holzschild wooden shield 34 ,--schwarze Hose black trousers 78 ,--Kurzschwert short sword 181 ,--blaues Hemd blue shirt 559 ,--Lamm mit Beilage lamb dish 726 ,--grober Sand coarse sand 733 ,--Steinquader stone block 767 ,--Wasserblüte water blossom 734 ,--Ziegelform brick mould 768 ,--Wolfsfarn wolverine fern 769 ,--Wüstenbeere desert berry 735 ,--roher Stein raw stone 737 ,--Meißel chisel 738 ,--Drachenei dragon egg 770 ,--Ritterstiefel knight boots 182 ,--schwarzes Hemd black shirt 184 ,--Visierhelm visored helmet 728 ,--Hopfenwurzel hop seeds 765 ,--Tagtraum daydream 916 ,--verzierter Turmschild ornate tower shield 917 ,--verfluchter Schild cursed shield 2678 ,--schwarze Farbe black dye 2680 ,--blaue Farbe blue dye 92 ,--Öllampe oil lamp 118 ,--Nudelholz rolling pin 121 ,--Brotschieber peel 177 ,--gelber Stoff yellow cloth 178 ,--weißer Stoff white cloth 179 ,--blauer Stoff blue cloth 180 ,--rotes Hemd red shirt 155 ,--Sibanacblatt sibanac leaf 156 ,--Steppenfarn steppe fern 158 ,--Knollenschwammpilz bulbsponge mushroom 159 ,--Fliegenpilz toadstool 160 ,--Rotköpfchen red head 161 ,--Hirtenpilz herder's mushroom 162 ,--Geburtspilz birth mushroom 163 ,--Champignon champignon 164 ,--leere Flasche empty bottle 168 ,--Wollknäuel ball of wool 174 ,--roter Stoff red cloth 175 ,--schwarzer Stoff black cloth 176 ,--grauer Stoff grey cloth 772 ,--Tabak tobacco 773 ,--Tabaksamen tobacco seeds 764 ,--Dunkelmoos dark moss 170 ,--Wollballen bale of wool 90 ,--Flöte flute 94 ,--Topfhelm pot helmet 95 ,--Wappenschild heraldic shield 96 ,--Stahlturmschild steel tower shield 97 ,--Ledertasche leather bag 101 ,--Kettenhemd chain mail 104 ,--Silberbarren silver ingot 126 ,--Sichel sickle 135 ,--Gelbkraut yellow weed 136 ,--Wutbeere anger berry 137 ,--Flammkelchblüte flamegoblet blossom 138 ,--Nachtengelsblüte night angels blossom 76 ,--Magierstab mage's staff 88 ,--Langaxt longaxe 89 ,--Schleuder sling 140 ,--Donfblatt donf blade 141 ,--schwarze Distel black thistle 142 ,--Sandbeere sandberry 143 ,--roter Holunder red elder 145 ,--Heideblüte heath flower 146 ,--Wüstenhimmelkapsel desert sky capsule 147 ,--Brombeere blackberry 148 ,--Firnisblüte firnis blossom 149 ,--Tannen-Sproß fir tree sprout 151 ,--Erdbeere strawberry 153 ,--Fussblatt foot leaf 154 ,--Hopfen hop 778 ,--Zuckerrohr sugarcane 779 ,--Zuckerrohrsamen sugarcane seeds 39 ,--Schädelstab skull staff 45 ,--Smaragd emerald 57 ,--einfacher Magierstab simple mage's staff 1317 ,--kleine leere Flasche small empty bottle 223 ,--Eisenkelch iron goblet 224 ,--Goldkelch golden goblet 225 ,--Krone crown 226 ,--Kriegshammer warhammer 230 ,--Streitkolben mace 235 ,--Goldring golden ring 236 ,--Goldbarren gold ingot 251 ,--Roher Amethyst raw amethyst 254 ,--Rohdiamant raw diamond 256 ,--Roher Smaragd raw emerald 258 ,--Dreschflegel flail 784 ,--Flasche mit Mandarinensaft bottle of tangerine juice 786 ,--Flasche mit Kohlsaft bottle of cabbage juice 152 ,--Lebenswurzel life root 788 ,--Flasche mit Karottensaft bottle of carrot juice 789 ,--Flasche mit Erdbeersaft bottle of strawberry juice 91 ,--Malachíndolch Malachín dagger 253 ,--Roher Saphir raw sapphire 252 ,--Roher Obsidian raw obsidian 231 ,--Streitflegel battle flail 787 ,--Flasche mit Jungfernkrauttee bottle of virgins weed tea 144 ,--Jungfernkraut virgin's weed 271 ,--Sense scythe 277 ,--Amethystring amethyst ring 280 ,--Diamantring diamond ring 281 ,--Smaragdring emerald ring 285 ,--Diamant diamond 293 ,--Wurfspeer javelin 294 ,--Wurfstern throwing star 315 ,--Vase vase 799 ,--Weidenkorb wicker basket 800 ,--blaues Gewand blue dress 801 ,--gelbes Gewand yellow dress 802 ,--graues Gewand grey dress 803 ,--grünes Gewand green dress 804 ,--rotes Gewand red dress 805 ,--schwarzes Gewand black dress 806 ,--weißes Gewand white dress 807 ,--blaues Wams blue doublet 808 ,--gelbes Wams yellow doublet 1318 ,--Flasche Elfenwein bottle of Elven wine 185 ,--schwarzer Visierhelm black visored helmet 189 ,--Dolch dagger 208 ,--verzierter Magierstab ornate mage's staff 249 ,--Getreidebündel bundle of grain 2536 ,--Kupfererz copper ore 2547 ,--Leder leather 2548 ,--Streitkolbengriff mace handle 2549 ,--Morgensterngriff morning star handle 2550 ,--Kupferbarren copper ingot 383 ,--Kriegsaxt waraxe 384 ,--Diebeshandschuhe thief's gloves 385 ,--blaues Kleid blue dress 831 ,--grüner Hut mit Feder green hat with feather 832 ,--roter Hut mit Feder red hat with feather 833 ,--schwarz-blaues Kleid black blue dress 834 ,--schwarz-gelbes Kleid black yellow dress 836 ,--schwarz-grünes Kleid black green dress 837 ,--schwarz-rotes Kleid black red dress 838 ,--schwarz-weißes Kleid black white dress 839 ,--blau-weißer Rock blue white skirt 840 ,--gelb-weißer Rock yellow white skirt 2551 ,--reine Luft pure air 841 ,--grau-weißer Rock grey white skirt 842 ,--grün-weißer Rock green white skirt 843 ,--rot-weißer Rock red white skirt 844 ,--schwarz-weißer Rock black white skirt 845 ,--blau-grünes Wappenkleid blue green heraldic dress 1319 ,--Flasche mit Kirschschnaps bottle of cherry schnapps 283 ,--Obsidian obsidian 284 ,--Saphir sapphire 279 ,--Saphirring sapphire ring 278 ,--Obsidianring obsidian ring 846 ,--blau-rotes Wappenkleid blue red heraldic dress 2552 ,--reine Erde pure earth 2553 ,--reines Feuer pure fire 2554 ,--reines Wasser pure water 2681 ,--rote Farbe red dye 2682 ,--gelbe Farbe yellow dye 2685 ,--Elfen-Kurzbogen elven shortbow 255 ,--Roher Rubin raw ruby 282 ,--Topasring topaz ring 310 ,--Humpen mit Deckel mug with lid 2917 ,--Tomatensamen tomato seeds 3051 ,--Wurst sausage 2493 ,--Karotten carrots 2494 ,--Samen seeds 2640 ,--riesige Feuer-Kriegsaxt large fire-waraxe 2642 ,--Orkaxt orc axe 2645 ,--Wurfbeil throwing axe 2646 ,--Serinjah-Reiterbogen serinjah-rider's bow 2658 ,--Breitschwert broadsword 2659 ,--Nagelbrett nail board 2660 ,--Zwergenaxt dwarven axe 2662 ,--magische Zwergenaxt magical dwarven axe 2664 ,--Keule club 2668 ,--vergifteter einfacher Dolch poisoned simple dagger 2675 ,--Degen rapier 2723 ,--Henkersaxt executioner's axe 2725 ,--vergiftete Henkersaxt poisoned executioner's axe 2727 ,--Feuer-Jagdbogen fire hunter's bow 2731 ,--Zweihänder two-handed sword 2738 ,--Nägel pins 2739 ,--Drowbogen drow bow 2740 ,--roter Dolch red dagger 2742 ,--roter Feuerdolch red fire dagger 2744 ,--Pfeife pipe 2647 ,--Besteck cutlery 2140 ,--Zange tongs 2654 ,--magisches Breitschwert magical broadsword 2655 ,--vergiftetes Breitschwert poisoned broadsword 2031 ,--Auffangschale collection pan 2172 ,--Stahlbeinschienen steel greaves 2183 ,--Tonkrug clay mug 2184 ,--Tonbecher clay cup 847 ,--gelb-blaues Wappenkleid yellow blue heraldic dress 848 ,--gelb-grünes Wappenkleid yellow green heraldic dress 1858 ,--Kelch goblet 2113 ,--Fellhose fur trousers 2185 ,--Holzbecher wooden cup 2456 ,--Pilzsuppe mushroom soup 2457 ,--Weinglas wine glass 2459 ,--Forellenfilet mit Beilage trout fillet dish 2656 ,--Feuerbreitschwert fire broadsword 2365 ,--salkamaersche Offiziersrüstung salkamaerian officer's armour 2367 ,--albarische Adeligenrüstung albarian noble's armour 2496 ,--Wasserflasche bottle of water 2369 ,--albarischer Stahlharnisch albarian steel plate 2377 ,--rote Magierrobe red mage robe 2393 ,--schwerer Stahlharnisch heavy plate armour 2395 ,--Zwergenpanzer dwarvenplate 2399 ,--leichte Elfenrüstung light elven armour 2400 ,--Elfen-Prunkrüstung elven state armour 2402 ,--Drowrüstung drow armour 2403 ,--Elfen-Silberstahlrüstung elven silversteel armour 2407 ,--leichte Brustplatte light breastplate 2420 ,--schwarze Priesterrobe black priest robe 2421 ,--weiße Priesterrobe white priest robe 2439 ,--Wolkenschild cloud shield 2441 ,--Sturmhaube storm cap 2378 ,--Schwarzkult-Robe black cult robe 2444 ,--Serinjah-Helm serinjah helmet 2445 ,--kleiner Holzschild small wooden shield 2448 ,--Legionärsturmschild legionnaire's tower shield 2495 ,--Pfanne pan 2498 ,--große leere Flasche large empty bottle 2525 ,--Axtgriff axe handle 2380 ,--blauer Mantel blue coat 2384 ,--schwarzer Mantel black coat 2388 ,--roter Stahlschild red steel shield 2416 ,--braune Priesterrobe brown priest robe 2527 ,--großer, verzierter Griff large ornamented handle 2528 ,--kleiner Griff small handle 2529 ,--Honigwaben honeycomb 2530 ,--Dolchgriff dagger handle 2534 ,--Meriniumerz merinium ore 2535 ,--Eisenbarren iron ingot 2541 ,--Hammergriff hammer handle 2543 ,--Nadelholzbretter conifer wooden boards 2544 ,--großer Griff large handle 850 ,--graues Wappenkleid grey heraldic dress 2193 ,--Hartholzbeinschienen hardwood greaves 2194 ,--kurze Hartholzbeinschienen short hardwood greaves 2276 ,--Eintopf mulligan 2277 ,--Fleischgericht mit Beilage meat dish 2278 ,--Kohlsuppe cabbage stew 2284 ,--Himmelsschild shield of the sky 2286 ,--Flammenhelm flame helmet 2290 ,--runder Stahlhut round steel hat 2291 ,--salkamaerischer Paladinhelm salkamaerian paladin's helmet 2295 ,--Stoffhandschuhe cloth gloves 2303 ,--Drowhelm drow helmet 2357 ,--Schattenharnisch shadowplate 2360 ,--Lor-Angur-Wächterrüstung Lor-Angur guardian's armour 2363 ,--Nachtharnisch nightplate 2364 ,--Stahlharnisch steel plate 2389 ,--salkamaerische Rüstung salkamaerian armour 2390 ,--Zwergen-Prunkrüstung dwarven state armour 2418 ,--graue Priesterrobe grey priest robe 2419 ,--rote Priesterrobe red priest robe 849 ,--rot-gelbes Wappenkleid red yellow heraldic dress 2287 ,--albarischer Soldatenhelm albarian soldier's helmet 2922 ,--Würstchen mit Beilage sausages dish 545 ,--Kirschholzbretter cherry wood boards 546 ,--Naldorholzbretter naldor wood boards 548 ,--Magierrobe mage robe 549 ,--Giftpfeil poisoned arrow 851 ,--schwarz-rotes Wappenkleid black red heraldic dress 852 ,--weißes Wappenkleid white heraldic dress 2497 ,--Metflasche bottle of mead 2499 ,--Ciderflasche bottle of cider 2500 ,--Weinflasche bottle of wine 2501 ,--Bierflasche bottle of beer 40 ,--Priesterstecken cleric's staff 2923 ,--Zwiebelsuppe onion soup 186 ,--Metallrundschild round metal shield 187 ,--Stahlhut steel hat 190 ,--verzierter Dolch ornate dagger 191 ,--Brötchen bread roll 193 ,--blaue Robe blue robe 2934 ,--Lammkeule lamb meat 2935 ,--Suppenschüssel soup bowl 2940 ,--Steak steak 2946 ,--Streitaxt battle axe 2952 ,--Teller plate 3035 ,--Drowschwert drow sword 2 ,--Mehl flour 3 ,--Nadelholz conifer wood 194 ,--schwarze Robe black robe 195 ,--gelbe Robe yellow robe 196 ,--grauer Mantel grey coat 197 ,--Amethyst amethyst 199 ,--Mandarine tangerine 200 ,--Tomate tomato 201 ,--Zwiebel onion 202 ,--Stahlkappe steel cap 543 ,--Kirschholz cherry wood 544 ,--Naldorholz naldor wood 122 ,--Feinschmiedehammer finesmithing hammer 133 ,--Sonnenkraut sun herb 183 ,--grüne Hose green trousers 205 ,--Doppelaxt double axe 3113 ,--versiegelte Pergamentrolle sealed pell 204 ,--Großschwert greatsword 206 ,--Feuer-Langschwert fire longsword 207 ,--Kampfstab battle staff 222 ,--Amulett amulet 311 ,--Glasblasrohr glass blow pipe 388 ,--Weintrauben grapes 1 ,--Serinjahschwert serinjah sword 52 ,--Eimer mit Wasser bucket of water 526 ,--beschlagene Lederhandschuhe studded leather gloves 553 ,--Hasenfleisch rabbit meat 554 ,--Wildgericht mit Beilage venison dish 555 ,--Hasenbraten rabbit dish 556 ,--Lachsgericht mit Beilage salmon dish 2708 ,--Langbogen long bow 2709 ,--Zimmermannshammer carpenter hammer 2710 ,--Gussform mould 2711 ,--Halblingsaxt halfling axe 2714 ,--Jagdbogen hunting bow 2717 ,--Nägel und Keile pins and cotters 2718 ,--Elfen-Kompositlangbogen elven composite longbow 2719 ,--Kamm comb 2745 ,--Pergament parchment 2746 ,--Rasierklinge razor blade 557 ,--Steak mit Beilage steak dish 2701 ,--Langschwert longsword 2704 ,--magisches Langschwert magical longsword 2705 ,--vergiftetes Langschwert poisoned longsword 558 ,--Erzmagierrobe archmage robe 2559 ,--Ring des Erzmagiers ring of the archmage 2586 ,--Fell fur 3112 ,--versiegelte Pergamentrolle sealed pell 70 ,--Armbrust crossbow 79 ,--Amethystkette amethyst amulet 188 ,--große Kriegsaxt large waraxe 552 ,--Rehrücken deer meat 67 ,--Rubinkette ruby amulet 98 ,--versilbertes Langschwert silvered longsword 124 ,--vergoldete Kriegsaxt gilded battle axe 771 ,--albarische Stahlstiefel albarian steel boots 192 ,--verkupferte Kriegsaxt coppered battle axe 209 ,--Elfen-Magierstab elven mage's staff 229 ,--versilberte Kriegsaxt silvered battle axe 296 ,--merinium-beschichtete Axt merinium-plated battle axe 389 ,--versilberter Dolch silvered dagger 398 ,--verkupferter Dolch coppered dagger 399 ,--Kerzenhalter candlestick 444 ,--merinium-beschichteter Dolch merinium-plated dagger 445 ,--Holzschwert wooden sword 447 ,--Rubinstaub ruby powder 448 ,--Smaragdstaub emerald powder 450 ,--Amethyststaub amethyst powder 451 ,--Topasstaub topaz powder 452 ,--Diamantstaub diamond powder 1843 ,--Kelch mit Met goblet with mead 1844 ,--Kelch mit Cider goblet with cider 1853 ,--Kelch mit Met goblet with mead 1854 ,--Kelch mit Wasser goblet with water 1855 ,--Kelch mit Wasser goblet with water 1856 ,--Kelch mit Met goblet with mead 1857 ,--Kelch mit Wein goblet with wine 1859 ,--Kelch mit Cider goblet with cider 1861 ,--Kelch mit Cider goblet with cider 1906 ,--Bierkrug beer mug 1907 ,--Bierkrug beer mug 2186 ,--Becher mit Wasser cup with water 2187 ,--Becher mit Wein cup with wine 446 ,--Saphirstaub sapphire powder 449 ,--Obsidianstaub obsidian powder 2622 ,--Buch der Alchemie Alchemy Book 2188 ,--Becher mit Met cup with mead 2189 ,--Becher mit Cider cup with cider 2447 ,--Mosaikschild mosaic shield 2537 ,--Eisenplatte iron plate 1841 ,--Kelch mit Wasser goblet with water 1842 ,--Kelch mit Wein goblet with wine 2751 ,--Tiegelzange crucible-pincers 2752 ,--Schnitzmesser carving tools 2757 ,--Krummsäbel scimitar 2760 ,--Seil rope 2763 ,--Spitzhacke pick-axe 817 ,--grüne Tunika green tunic 257 ,--Roher Topas raw topaz 753 ,--blaue Vogelbeere blue birdsberry 754 ,--einblättrige Vierbeere oneleaved fourberry 759 ,--Nüsse nuts 761 ,--Regenkraut rain weed 809 ,--graues Wams grey doublet 810 ,--grünes Wams green doublet 811 ,--rotes Wams red doublet 812 ,--schwarzes Wams black doublet 813 ,--weißes Wams white doublet 814 ,--blaue Tunika blue tunic 815 ,--gelbe Tunika yellow tunic 816 ,--graue Tunika grey tunic 818 ,--rote Tunika red tunic 819 ,--schwarze Tunika black tunic 820 ,--weiße Tunika white tunic 821 ,--blaue Hose blue trousers 822 ,--gelbe Hose yellow trousers 823 ,--graue Hose grey trousers 824 ,--grüne Hose green trousers 825 ,--rote Hose red trousers 826 ,--schwarze Hose black trousers 827 ,--weiße Hose white trousers 828 ,--blauer Hut mit Feder blue hat with feather 829 ,--gelber Hut mit Feder yellow hat with feather 1001 ,--Teller plate 1860 ,--goblet with wine goblet with wine 2111 ,--Kettenhose chain pants 2775 ,--Elfen-Regenbogenschwert elven rainbowsword 2776 ,--Kurzschwert short sword 2777 ,--Drow-Klinge drow blade 2778 ,--Elfenschwert elvensword 2784 ,--Stab des Wassers wand of water 2788 ,--Schlangenschwert snake sword 83 ,--Topaskette topaz amulet 198 ,--Topas topaz 2780 ,--Ebenholzbogen ebony wood bow 2783 ,--Stab des Feuers wand of fire 757 ,--Tybaltstern tybalt star 758 ,--Herzblut heart blood 760 ,--Eisblatt ice leaf 2781 ,--Färberstab dyeing rod 2785 ,--Stab der Luft wand of air 752 ,--Alraune mandrake 547 ,--Novizenrobe novice robe 830 ,--grauer Hut mit Feder grey hat with feather 2359 ,--Söldnerrüstung mercenary armour 2671 ,--magischer Dolch magical dagger 2694 ,--vergiftetes Serinjah-Schwert poisoned serinjah-sword 2696 ,--Metallteile metal pieces 2697 ,--Feile rasp 2782 ,--Stab der Erde wand of earth 3077 ,--Silberstücke silver coins 763 ,--Sumpfblume marsh flower 2679 ,--grüne Farbe green dye 2689 ,--vergifteter verzierter Dolch poisoned ornate dagger 2693 ,--magisches Serinjah-Schwert magical serinjah-sword 18 ,--leichter Schild light shield 19 ,--Metallschild metal shield 123 ,--merinium-beschichtetes Schwert merinium-plated longsword 134 ,--vierblättrige Einbeere fourleafed oneberry 157 ,--Faulbaumrinde rotten tree bark 234 ,--Goldnuggets gold nuggets 291 ,--verblühter Kohl (Saatgut) withered cabbage (seeds) 334 ,--Eisvogelamulett charm of the icebird 362 ,--volle Lederrüstung full leather armour 6 ,--Schere scissors 7 ,--Hörnerhelm horned helmet 9 ,--Säge saw 16 ,--Orkhelm orc helmet 20 ,--Ritterschild knight shield 21 ,--Kohle coal 22 ,--Eisenerz iron ore 23 ,--Hammer hammer 24 ,--Schaufel shovel 25 ,--Säbel sabre 26 ,--Lehm clay 27 ,--einfacher Dolch simple dagger 46 ,--Rubin ruby 47 ,--Nadel needle 48 ,--Lederhandschuhe leather gloves 49 ,--Brot bread 50 ,--Garn thread 51 ,--Eimer bucket 53 ,--Lederstiefel leather boots 54 ,--grüner Stoff green cloth 55 ,--grüne Robe green robe 56 ,--Ast bough 58 ,--Mörser mortar 61 ,--Goldstücke gold coins 62 ,--Smaragdamulett emerald amulet 63 ,--Eingeweide entrails 64 ,--Pfeil arrow 65 ,--Kurzbogen short bow 68 ,--Rubinring ruby ring 69 ,--Rohleder raw leather 237 ,--Armbrustbolzen crossbow bolt 259 ,--Getreide grain 312 ,--Holzkelle wooden shovel 316 ,--Quarzsand quartz sand 322 ,--Windpfeile wind arrows 323 ,--Zauberstab wand 324 ,--Kettenhelm chain helmet 325 ,--Stahlhandschuhe steel gloves 326 ,--Stahlschuhe steel boots 332 ,--Harfe harp 333 ,--Horn horn 336 ,--Spiegel mirror 431 ,--Wachs wax 3109 ,--offene Pergamentrolle open pell 3110 ,--Pergamentrolle pell 3111 ,--versiegelte Pergamentrolle sealed pell 3114 ,--versiegelte Pergamentrolle sealed pell 3115 ,--Schriftrolle scroll 3116 ,--Schriftrolle scroll 4 ,--Plattenpanzer plate armour 72 ,--Angel fishing rod 73 ,--Forelle trout 74 ,--Beil hatchet 77 ,--Hellebarde halberd 80 ,--Banane banana 81 ,--Beeren berries 84 ,--vergoldetes Langschwert gilded longsword 297 ,--vergoldeter Dolch gilded dagger 302 ,--Kirschen cherries 303 ,--Kirschtorte cherry cake 368 ,--gelbe Priesterrobe yellow priest robe 369 ,--Lederschuhe leather shoes 370 ,--bunter Zauberhut colourful wizard hat 371 ,--feiner Zauberhut fine wizard hat 391 ,--Fackel torch 392 ,--Fackel torch 393 ,--Laterne lantern 314 ,--Pottasche potash 453 ,--Kekse cookies 454 ,--Brombeermuffin blackberry muffin 455 ,--geräucherter Forelle smoked trout 3914,-- smoked horse mackerel 3915,-- smoked rose fish 3916,-- smoked salmon 456 ,--Schneeball snowball 85 ,--verkupfertes Langschwert coppered longsword 460 ,--gelbe Hose yellow trousers 461 ,--blaue Hose blue trousers 463 ,--Schreibfeder quill 465 ,--Diadem diadem 505 ,--Schatzkarte treasure map 527 ,--Serinjah-Lederhandschuhe serinjah leather gloves 528 ,--salkamaerische Stahlhandschuhe Salkamarian steel gloves 71 ,--Saphirkette sapphire amulet 529 ,--zwergische Metallhandschuhe dwarven metal gloves 530 ,--albarische Stahlhandschuhe Albarian steelgloves 531 ,--Ritterhandschuhe knight gloves 532 ,--Panflöte panpipe 533 ,--Trommel drum 696 ,--Echsenrüstung lizard armour 697 ,--Fellstiefel fur boots 698 ,--Serinjah-Lederstiefel serinjah leather boots 699 ,--salkamarische Stahlschuhe salkamarian steel boots 2561 ,--Sägengriff saw handle 2566 ,--Sensengriff scythe handle 2567 ,--Schaufelgriff shovel handle 2570 ,--Sichelgriff sickle handle 2571 ,--Meriniumbarren merinium ingot 2572 ,--Stabgriff staff handle 2584 ,--Schwertgriff sword handle 2585 ,--großer Schwertgriff big sword handle 2588 ,--Ziegelsteine bricks 2626 ,--magische Kriegsaxt magical waraxe 2627 ,--Feuer-Kriegsaxt fire waraxe 2629 ,--leichte Schlachtaxt light battleaxe 2635 ,--vergiftete Halblingsaxt poisoned halfling axe 2636 ,--vergiftete Doppelaxt poisoned longaxe 457 ,--grünes Hemd green shirt 459 ,--rote Hose red trousers 458 ,--gelbes Hemd yellow shirt 2573 ,--langer Stabgriff long staff handle 517 ,--Flasche mit Rum bottle of rum 1315 ,--Flasche mit Beerensaft bottle of berry booze 783 ,--Flasche mit Brombeersaft bottle of blackberry juice 785 ,--Flasche mit Bananensaft bottle of banana juice 791 ,--Flasche mit Traubensaft bottle of grape juice 2715 ,--Hobel plane 1316 ,--Flasche mit Bärentöter bottle of bear slayer 762 ,--Goldbruchkraut gold crak herb 82 ,--Obsidiankette obsidian amulet 2302 ,--gynkesischer Söldnerhelm gynkese mercenary's helmet 2737 ,--Kriegsflegel war flail 1038 ,--Schlangenspeer snake spear 1039 ,--Doppelklingenranseur twinblade ranseur 1040 ,--Ranseur ranseur 1041 ,--Stachelkeule spiked mace 1042 ,--Partisane partisan 1043 ,--Zwergenhammer dwarven hammer 1044 ,--Schlachthammer battle hammer 1045 ,--Holzdolch wooden dagger 1046 ,--Einfacher Speer simple spear 1047 ,--Glefe glaive 1048 ,--Voulge voulge 1049 ,--Vipernspeer viper spear 1051 ,--Partisane des Lichtes partisan of light 1052 ,--Zwergen-Sturmhammer dwarven stormhammer 1053 ,--Heilige Voulge divine voulge 1050 ,--Schattenranseur shadow ranseur 835 ,--schwarz-graues Kleid black grey dress 790 ,--Leere Saftflasche empty juice bottle 518 ,--leere bauchige Flasche empty round body bottle 2560 ,--Apfelholz applewood 1062 ,--Silbererz silver ore 1059 ,--Würfelbecher dice cup 1054 ,--verzierte Lederstiefel ornate leatherboots 1055 ,--Zwergenstiefel dwarven boots 1056 ,--Lor-Angur-Wächterstiefel Lor-Angur guardians boots 1057 ,--robuste Fellstiefel robust fur boots 1058 ,--Elfen Silberstahl Stiefel elven silversteel boots 2672 ,--Glasdolch glass dagger 1090 ,--Wanderstab Walking stick 1209 ,--Stachelmakrele horse mackerel 429 ,--Kerzenform candle mould 1151 ,--Hühnchenfleisch chicken meat 1152 ,--Hühnchensuppe chicken soup 1153 ,--Eiercremetorte custard pie 1155 ,--Hühnchen mit Beilage chicken dish 1210 ,--Rotbarsch rose fish 1149 ,--Ei egg 1150 ,--Ei egg 1154 ,--Spiegelei mit Beilage egg dish 2716 ,--Apfelholzbretter apple wood boards 2502 ,--Milchflasche bottle of milk 1207 ,--Orange orange 3607 ,--pure spirit } local gfxList = { 2,5,16,32,35,37,41,53,52 } function M.createMysticalCracker(user, amount) common.CreateItem(user, 3894, amount, 333,nil) end function M.UseItem(User, SourceItem) User:talk(Character.say, "#me zieht die bunte Verpackung des Knallbonbons auseinander.","#me pulls apart the colourful wrapping of the cracker.") world:erase(SourceItem, 1) local itemId = itemList[math.random(1,#itemList)] local itemQuality = 100*math.random(4,9) + math.random(44,99) User:inform("Du findest etwas als die bunte Verpackung aufreißt: "..world:getItemName(itemId,Player.german), "You find something as you pull apart the colourful wrapping: "..world:getItemName(itemId,Player.english),Player.mediumPriority) common.CreateItem(User, itemId, 1, itemQuality, nil) world:gfx(gfxList[math.random(1,#gfxList)],User.pos) world:makeSound(13, User.pos) end return M
agpl-3.0
ffxiphoenix/darkstar
scripts/zones/Port_Windurst/npcs/Honorio.lua
17
1385
----------------------------------- -- Area: Port Windurst -- NPC: Honorio -- @zone 240 -- @pos 218 -5 114 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(AIRSHIP_PASS) == true and player:getGil() >= 200) then player:startEvent(0x00b5,0,8,0,0,0,0,0,200); else player:startEvent(0x00b7,0,8); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x00b5) then X = player:getXPos(); if (X >= 222 and X <= 225) then player:delGil(200); end end end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Beaucedine_Glacier/mobs/Calcabrina.lua
13
2011
----------------------------------- -- Area: Beaucedine Glacier -- NM: Calcabrina ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) -- wiki just says "low proc rate". No actual data to go on - going with 15% for now. local chance = 15; local LV_diff = target:getMainLvl() - mob:getMainLvl(); if (target:getMainLvl() > mob:getMainLvl()) then chance = chance - 5 * LV_diff chance = utils.clamp(chance, 5, 95); end if (math.random(0,99) >= chance) then return 0,0,0; else local INT_diff = mob:getStat(MOD_INT) - target:getStat(MOD_INT); if (INT_diff > 20) then INT_diff = 20 + (INT_diff - 20) / 2; end local drain = INT_diff+LV_diff+damage/2; local params = {}; params.bonusmab = 0; params.includemab = false; drain = addBonusesAbility(mob, ELE_DARK, target, drain, params); drain = drain * applyResistanceAddEffect(mob,target,ELE_DARK,0); drain = adjustForTarget(target,drain,ELE_DARK); drain = finalMagicNonSpellAdjustments(target,mob,ELE_DARK,drain); if (drain <= 0) then drain = 0; else mob:addHP(drain); end return SUBEFFECT_HP_DRAIN, MSGBASIC_ADD_EFFECT_HP_DRAIN, drain; end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random((5400),(6000))); end;
gpl-3.0
dualface/cocos2dx_luatests
scripts/luaScript/SceneTest/SceneTest.lua
8
5995
local MID_PUSHSCENE = 100 local MID_PUSHSCENETRAN = 101 local MID_QUIT = 102 local MID_REPLACESCENE = 103 local MID_REPLACESCENETRAN = 104 local MID_GOBACK = 105 local SceneTestLayer1 = nil local SceneTestLayer2 = nil local SceneTestLayer3 = nil -------------------------------------------------------------------- -- -- SceneTestLayer1 -- -------------------------------------------------------------------- SceneTestLayer1 = function() local ret = CCLayer:create() local function onPushScene(tag, pSender) local scene = CCScene:create() local layer = SceneTestLayer2() scene:addChild(layer, 0) scene:addChild(CreateBackMenuItem()) CCDirector:sharedDirector():pushScene( scene ) end local function onPushSceneTran(tag, pSender) local scene = CCScene:create() local layer = SceneTestLayer2() scene:addChild(layer, 0) scene:addChild(CreateBackMenuItem()) CCDirector:sharedDirector():pushScene( CCTransitionSlideInT:create(1, scene) ) end local function onQuit(tag, pSender) cclog("onQuit") end local item1 = CCMenuItemFont:create( "Test pushScene") item1:registerScriptTapHandler(onPushScene) local item2 = CCMenuItemFont:create( "Test pushScene w/transition") item2:registerScriptTapHandler(onPushSceneTran) local item3 = CCMenuItemFont:create( "Quit") item3:registerScriptTapHandler(onQuit) local arr = CCArray:create() arr:addObject(item1) arr:addObject(item2) arr:addObject(item3) local menu = CCMenu:createWithArray(arr) menu:alignItemsVertically() ret:addChild( menu ) local s = CCDirector:sharedDirector():getWinSize() local sprite = CCSprite:create(s_pPathGrossini) ret:addChild(sprite) sprite:setPosition( ccp(s.width-40, s.height/2) ) local rotate = CCRotateBy:create(2, 360) local repeatAction = CCRepeatForever:create(rotate) sprite:runAction(repeatAction) local function onNodeEvent(event) if event == "enter" then cclog("SceneTestLayer1#onEnter") elseif event == "enterTransitionFinish" then cclog("SceneTestLayer1#onEnterTransitionDidFinish") end end ret:registerScriptHandler(onNodeEvent) return ret end -------------------------------------------------------------------- -- -- SceneTestLayer2 -- -------------------------------------------------------------------- SceneTestLayer2 = function() local ret = CCLayer:create() local m_timeCounter = 0 local function onGoBack(tag, pSender) CCDirector:sharedDirector():popScene() end local function onReplaceScene(tag, pSender) local scene = CCScene:create() local layer = SceneTestLayer3() scene:addChild(layer, 0) scene:addChild(CreateBackMenuItem()) CCDirector:sharedDirector():replaceScene( scene ) end local function onReplaceSceneTran(tag, pSender) local scene = CCScene:create() local layer = SceneTestLayer3() scene:addChild(layer, 0) scene:addChild(CreateBackMenuItem()) CCDirector:sharedDirector():replaceScene( CCTransitionFlipX:create(2, scene) ) end local item1 = CCMenuItemFont:create( "replaceScene") item1:registerScriptTapHandler(onReplaceScene) local item2 = CCMenuItemFont:create( "replaceScene w/transition") item2:registerScriptTapHandler(onReplaceSceneTran) local item3 = CCMenuItemFont:create( "Go Back") item3:registerScriptTapHandler(onGoBack) local arr = CCArray:create() arr:addObject(item1) arr:addObject(item2) arr:addObject(item3) local menu = CCMenu:createWithArray(arr) menu:alignItemsVertically() ret:addChild( menu ) local s = CCDirector:sharedDirector():getWinSize() local sprite = CCSprite:create(s_pPathGrossini) ret:addChild(sprite) sprite:setPosition( ccp(s.width-40, s.height/2) ) local rotate = CCRotateBy:create(2, 360) local repeat_action = CCRepeatForever:create(rotate) sprite:runAction(repeat_action) return ret end -------------------------------------------------------------------- -- -- SceneTestLayer3 -- -------------------------------------------------------------------- SceneTestLayer3 = function() local ret = CCLayerColor:create(ccc4(0,0,255,255)) local s = CCDirector:sharedDirector():getWinSize() local function item0Clicked(tag, pSender) local newScene = CCScene:create() newScene:addChild(SceneTestLayer3()) CCDirector:sharedDirector():pushScene(CCTransitionFade:create(0.5, newScene, ccc3(0,255,255))) end local function item1Clicked(tag, pSender) CCDirector:sharedDirector():popScene() end local function item2Clicked(tag, pSender) CCDirector:sharedDirector():popToRootScene() end local item0 = CCMenuItemFont:create("Touch to pushScene (self)") item0:registerScriptTapHandler(item0Clicked) local item1 = CCMenuItemFont:create("Touch to popScene") item1:registerScriptTapHandler(item1Clicked) local item2 = CCMenuItemFont:create("Touch to popToRootScene") item2:registerScriptTapHandler(item2Clicked) local arr = CCArray:create() arr:addObject(item0) arr:addObject(item1) arr:addObject(item2) local menu = CCMenu:createWithArray(arr) ret:addChild(menu) menu:alignItemsVertically() local sprite = CCSprite:create(s_pPathGrossini) ret:addChild(sprite) sprite:setPosition( ccp(s.width/2, 40) ) local rotate = CCRotateBy:create(2, 360) local repeatAction = CCRepeatForever:create(rotate) sprite:runAction(repeatAction) return ret end function SceneTestMain() cclog("SceneTestMain") local scene = CCScene:create() local layer = SceneTestLayer1() scene:addChild(layer, 0) scene:addChild(CreateBackMenuItem()) return scene end
mit
Quenty/NevermoreEngine
src/nocollisionconstraintutils/src/Shared/NoCollisionConstraintUtils.lua
1
2010
--[=[ Utility functions to create and manipulate [NoCollisionConstraint] objects between Roblox parts. See [getMechanismParts]. @class NoCollisionConstraintUtils ]=] local require = require(script.Parent.loader).load(script) local getMechanismParts = require("getMechanismParts") local Maid = require("Maid") local NoCollisionConstraintUtils = {} --[=[ Creates a new [NoCollisionConstraint] between the two parts. @param part0 BasePart @param part1 BasePart @return NoCollisionConstraint ]=] function NoCollisionConstraintUtils.create(part0, part1) local noCollision = Instance.new("NoCollisionConstraint") noCollision.Part0 = part0 noCollision.Part1 = part1 return noCollision end --[=[ Creates [NoCollisionConstraint] objects between the two part lists, and adds them all to a [Maid] for cleanup. @param parts0 { BasePart } @param parts1 { BasePart } @return Maid ]=] function NoCollisionConstraintUtils.tempNoCollision(parts0, parts1) local maid = Maid.new() for _, item in pairs(NoCollisionConstraintUtils.createBetweenPartsLists(parts0, parts1)) do maid:GiveTask(item) end return maid end --[=[ Creates [NoCollisionConstraint] objects between the two part lists. @param parts0 { BasePart } @param parts1 { BasePart } @return { NoCollisionConstraint } ]=] function NoCollisionConstraintUtils.createBetweenPartsLists(parts0, parts1) local collisionConstraints = {} for _, part0 in pairs(parts0) do for _, part1 in pairs(parts1) do table.insert(collisionConstraints, NoCollisionConstraintUtils.create(part0, part1)) end end return collisionConstraints end --[=[ Creates [NoCollisionConstraint] objects between the two mechanisms. @param adornee0 BasePart @param adornee1 BasePart @return { NoCollisionConstraint } ]=] function NoCollisionConstraintUtils.createBetweenMechanisms(adornee0, adornee1) return NoCollisionConstraintUtils.createBetweenPartsLists(getMechanismParts(adornee0), getMechanismParts(adornee1)) end return NoCollisionConstraintUtils
mit
ffxiphoenix/darkstar
scripts/zones/Mine_Shaft_2716/Zone.lua
32
1656
----------------------------------- -- -- Zone: Mine_Shaft_2716 (13) -- ----------------------------------- package.loaded["scripts/zones/Mine_Shaft_2716/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Mine_Shaft_2716/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-116.599,-122.103,-620.01,253); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
noooway/love2d_arkanoid_tutorial
2-08_GameOver/walls.lua
8
1601
local vector = require "vector" local walls = {} walls.side_walls_thickness = 34 walls.top_wall_thickness = 26 walls.right_border_x_pos = 576 walls.current_level_walls = {} function walls.new_wall( position, width, height ) return( { position = position, width = width, height = height } ) end function walls.update_wall( single_wall ) end function walls.draw_wall( single_wall ) love.graphics.rectangle( 'line', single_wall.position.x, single_wall.position.y, single_wall.width, single_wall.height ) local r, g, b, a = love.graphics.getColor( ) love.graphics.setColor( 255, 0, 0, 100 ) love.graphics.rectangle( 'fill', single_wall.position.x, single_wall.position.y, single_wall.width, single_wall.height ) love.graphics.setColor( r, g, b, a ) end function walls.construct_walls() local left_wall = walls.new_wall( vector( 0, 0 ), walls.side_walls_thickness, love.graphics.getHeight() ) local right_wall = walls.new_wall( vector( walls.right_border_x_pos, 0 ), walls.side_walls_thickness, love.graphics.getHeight() ) local top_wall = walls.new_wall( vector( 0, 0 ), walls.right_border_x_pos, walls.top_wall_thickness ) walls.current_level_walls["left"] = left_wall walls.current_level_walls["right"] = right_wall walls.current_level_walls["top"] = top_wall end function walls.update( dt ) end function walls.draw() for _, wall in pairs( walls.current_level_walls ) do walls.draw_wall( wall ) end end return walls
mit
noooway/love2d_arkanoid_tutorial
3-05_BonusesEffects/walls.lua
8
1601
local vector = require "vector" local walls = {} walls.side_walls_thickness = 34 walls.top_wall_thickness = 26 walls.right_border_x_pos = 576 walls.current_level_walls = {} function walls.new_wall( position, width, height ) return( { position = position, width = width, height = height } ) end function walls.update_wall( single_wall ) end function walls.draw_wall( single_wall ) love.graphics.rectangle( 'line', single_wall.position.x, single_wall.position.y, single_wall.width, single_wall.height ) local r, g, b, a = love.graphics.getColor( ) love.graphics.setColor( 255, 0, 0, 100 ) love.graphics.rectangle( 'fill', single_wall.position.x, single_wall.position.y, single_wall.width, single_wall.height ) love.graphics.setColor( r, g, b, a ) end function walls.construct_walls() local left_wall = walls.new_wall( vector( 0, 0 ), walls.side_walls_thickness, love.graphics.getHeight() ) local right_wall = walls.new_wall( vector( walls.right_border_x_pos, 0 ), walls.side_walls_thickness, love.graphics.getHeight() ) local top_wall = walls.new_wall( vector( 0, 0 ), walls.right_border_x_pos, walls.top_wall_thickness ) walls.current_level_walls["left"] = left_wall walls.current_level_walls["right"] = right_wall walls.current_level_walls["top"] = top_wall end function walls.update( dt ) end function walls.draw() for _, wall in pairs( walls.current_level_walls ) do walls.draw_wall( wall ) end end return walls
mit
ffxiphoenix/darkstar
scripts/zones/Dynamis-Beaucedine/bcnms/dynamis_beaucedine.lua
16
1101
----------------------------------- -- Area: Dynamis Beaucedine -- Name: Dynamis Beaucedine ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[DynaBeaucedine]UniqueID",player:getDynamisUniqueID(1284)); SetServerVariable("[DynaBeaucedine]Already_Received",0); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("DynamisID",GetServerVariable("[DynaBeaucedine]UniqueID")); local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then player:setVar("dynaWaitxDay",realDay); end end; -- Leaving the Dynamis by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then SetServerVariable("[DynaBeaucedine]UniqueID",0); end end;
gpl-3.0
dail8859/ScintilluaPlusPlus
ext/scintillua/lexers/nemerle.lua
5
2529
-- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE. -- Nemerle LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local M = {_NAME = 'nemerle'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local line_comment = '//' * l.nonnewline_esc^0 local block_comment = '/*' * (l.any - '*/')^0 * P('*/')^-1 local comment = token(l.COMMENT, line_comment + block_comment) -- Strings. local sq_str = P('L')^-1 * l.delimited_range("'", true) local dq_str = P('L')^-1 * l.delimited_range('"', true) local string = token(l.STRING, sq_str + dq_str) -- Numbers. local number = token(l.NUMBER, l.float + l.integer) -- Preprocessor. local preproc_word = word_match{ 'define', 'elif', 'else', 'endif', 'endregion', 'error', 'if', 'ifdef', 'ifndef', 'line', 'pragma', 'region', 'undef', 'using', 'warning' } local preproc = token(l.PREPROCESSOR, l.starts_line('#') * S('\t ')^0 * preproc_word) -- Keywords. local keyword = token(l.KEYWORD, word_match{ '_', 'abstract', 'and', 'array', 'as', 'base', 'catch', 'class', 'def', 'do', 'else', 'extends', 'extern', 'finally', 'foreach', 'for', 'fun', 'if', 'implements', 'in', 'interface', 'internal', 'lock', 'macro', 'match', 'module', 'mutable', 'namespace', 'new', 'out', 'override', 'params', 'private', 'protected', 'public', 'ref', 'repeat', 'sealed', 'static', 'struct', 'syntax', 'this', 'throw', 'try', 'type', 'typeof', 'unless', 'until', 'using', 'variant', 'virtual', 'when', 'where', 'while', -- Values. 'null', 'true', 'false' }) -- Types. local type = token(l.TYPE, word_match{ 'bool', 'byte', 'char', 'decimal', 'double', 'float', 'int', 'list', 'long', 'object', 'sbyte', 'short', 'string', 'uint', 'ulong', 'ushort', 'void' }) -- Identifiers. local identifier = token(l.IDENTIFIER, l.word) -- Operators. local operator = token(l.OPERATOR, S('+-/*%<>!=^&|?~:;.()[]{}')) M._rules = { {'whitespace', ws}, {'keyword', keyword}, {'type', type}, {'identifier', identifier}, {'string', string}, {'comment', comment}, {'number', number}, {'preproc', preproc}, {'operator', operator}, } M._foldsymbols = { _patterns = {'%l+', '[{}]', '/%*', '%*/', '//'}, [l.PREPROCESSOR] = { region = 1, endregion = -1, ['if'] = 1, ifdef = 1, ifndef = 1, endif = -1 }, [l.OPERATOR] = {['{'] = 1, ['}'] = -1}, [l.COMMENT] = {['/*'] = 1, ['*/'] = -1, ['//'] = l.fold_line_comments('//')} } return M
gpl-2.0
lxl1140989/sdk-for-tb
feeds/luci/modules/base/luasrc/cbi.lua
76
40152
--[[ LuCI - Configuration Bind Interface Description: Offers an interface for binding configuration values to certain data types. Supports value and range validation and basic dependencies. FileId: $Id$ License: Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 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. ]]-- module("luci.cbi", package.seeall) require("luci.template") local util = require("luci.util") require("luci.http") --local event = require "luci.sys.event" local fs = require("nixio.fs") local uci = require("luci.model.uci") local datatypes = require("luci.cbi.datatypes") local class = util.class local instanceof = util.instanceof FORM_NODATA = 0 FORM_PROCEED = 0 FORM_VALID = 1 FORM_DONE = 1 FORM_INVALID = -1 FORM_CHANGED = 2 FORM_SKIP = 4 AUTO = true CREATE_PREFIX = "cbi.cts." REMOVE_PREFIX = "cbi.rts." RESORT_PREFIX = "cbi.sts." FEXIST_PREFIX = "cbi.cbe." -- Loads a CBI map from given file, creating an environment and returns it function load(cbimap, ...) local fs = require "nixio.fs" local i18n = require "luci.i18n" require("luci.config") require("luci.util") local upldir = "/lib/uci/upload/" local cbidir = luci.util.libpath() .. "/model/cbi/" local func, err if fs.access(cbidir..cbimap..".lua") then func, err = loadfile(cbidir..cbimap..".lua") elseif fs.access(cbimap) then func, err = loadfile(cbimap) else func, err = nil, "Model '" .. cbimap .. "' not found!" end assert(func, err) local env = { translate=i18n.translate, translatef=i18n.translatef, arg={...} } setfenv(func, setmetatable(env, {__index = function(tbl, key) return rawget(tbl, key) or _M[key] or _G[key] end})) local maps = { func() } local uploads = { } local has_upload = false for i, map in ipairs(maps) do if not instanceof(map, Node) then error("CBI map returns no valid map object!") return nil else map:prepare() if map.upload_fields then has_upload = true for _, field in ipairs(map.upload_fields) do uploads[ field.config .. '.' .. (field.section.sectiontype or '1') .. '.' .. field.option ] = true end end end end if has_upload then local uci = luci.model.uci.cursor() local prm = luci.http.context.request.message.params local fd, cbid luci.http.setfilehandler( function( field, chunk, eof ) if not field then return end if field.name and not cbid then local c, s, o = field.name:gmatch( "cbid%.([^%.]+)%.([^%.]+)%.([^%.]+)" )() if c and s and o then local t = uci:get( c, s ) or s if uploads[c.."."..t.."."..o] then local path = upldir .. field.name fd = io.open(path, "w") if fd then cbid = field.name prm[cbid] = path end end end end if field.name == cbid and fd then fd:write(chunk) end if eof and fd then fd:close() fd = nil cbid = nil end end ) end return maps end -- -- Compile a datatype specification into a parse tree for evaluation later on -- local cdt_cache = { } function compile_datatype(code) local i local pos = 0 local esc = false local depth = 0 local stack = { } for i = 1, #code+1 do local byte = code:byte(i) or 44 if esc then esc = false elseif byte == 92 then esc = true elseif byte == 40 or byte == 44 then if depth <= 0 then if pos < i then local label = code:sub(pos, i-1) :gsub("\\(.)", "%1") :gsub("^%s+", "") :gsub("%s+$", "") if #label > 0 and tonumber(label) then stack[#stack+1] = tonumber(label) elseif label:match("^'.*'$") or label:match('^".*"$') then stack[#stack+1] = label:gsub("[\"'](.*)[\"']", "%1") elseif type(datatypes[label]) == "function" then stack[#stack+1] = datatypes[label] stack[#stack+1] = { } else error("Datatype error, bad token %q" % label) end end pos = i + 1 end depth = depth + (byte == 40 and 1 or 0) elseif byte == 41 then depth = depth - 1 if depth <= 0 then if type(stack[#stack-1]) ~= "function" then error("Datatype error, argument list follows non-function") end stack[#stack] = compile_datatype(code:sub(pos, i-1)) pos = i + 1 end end end return stack end function verify_datatype(dt, value) if dt and #dt > 0 then if not cdt_cache[dt] then local c = compile_datatype(dt) if c and type(c[1]) == "function" then cdt_cache[dt] = c else error("Datatype error, not a function expression") end end if cdt_cache[dt] then return cdt_cache[dt][1](value, unpack(cdt_cache[dt][2])) end end return true end -- Node pseudo abstract class Node = class() function Node.__init__(self, title, description) self.children = {} self.title = title or "" self.description = description or "" self.template = "cbi/node" end -- hook helper function Node._run_hook(self, hook) if type(self[hook]) == "function" then return self[hook](self) end end function Node._run_hooks(self, ...) local f local r = false for _, f in ipairs(arg) do if type(self[f]) == "function" then self[f](self) r = true end end return r end -- Prepare nodes function Node.prepare(self, ...) for k, child in ipairs(self.children) do child:prepare(...) end end -- Append child nodes function Node.append(self, obj) table.insert(self.children, obj) end -- Parse this node and its children function Node.parse(self, ...) for k, child in ipairs(self.children) do child:parse(...) end end -- Render this node function Node.render(self, scope) scope = scope or {} scope.self = self luci.template.render(self.template, scope) end -- Render the children function Node.render_children(self, ...) local k, node for k, node in ipairs(self.children) do node.last_child = (k == #self.children) node:render(...) end end --[[ A simple template element ]]-- Template = class(Node) function Template.__init__(self, template) Node.__init__(self) self.template = template end function Template.render(self) luci.template.render(self.template, {self=self}) end function Template.parse(self, readinput) self.readinput = (readinput ~= false) return Map.formvalue(self, "cbi.submit") and FORM_DONE or FORM_NODATA end --[[ Map - A map describing a configuration file ]]-- Map = class(Node) function Map.__init__(self, config, ...) Node.__init__(self, ...) self.config = config self.parsechain = {self.config} self.template = "cbi/map" self.apply_on_parse = nil self.readinput = true self.proceed = false self.flow = {} self.uci = uci.cursor() self.save = true self.changed = false if not self.uci:load(self.config) then error("Unable to read UCI data: " .. self.config) end end function Map.formvalue(self, key) return self.readinput and luci.http.formvalue(key) end function Map.formvaluetable(self, key) return self.readinput and luci.http.formvaluetable(key) or {} end function Map.get_scheme(self, sectiontype, option) if not option then return self.scheme and self.scheme.sections[sectiontype] else return self.scheme and self.scheme.variables[sectiontype] and self.scheme.variables[sectiontype][option] end end function Map.submitstate(self) return self:formvalue("cbi.submit") end -- Chain foreign config function Map.chain(self, config) table.insert(self.parsechain, config) end function Map.state_handler(self, state) return state end -- Use optimized UCI writing function Map.parse(self, readinput, ...) self.readinput = (readinput ~= false) self:_run_hooks("on_parse") if self:formvalue("cbi.skip") then self.state = FORM_SKIP return self:state_handler(self.state) end Node.parse(self, ...) if self.save then self:_run_hooks("on_save", "on_before_save") for i, config in ipairs(self.parsechain) do self.uci:save(config) end self:_run_hooks("on_after_save") if self:submitstate() and ((not self.proceed and self.flow.autoapply) or luci.http.formvalue("cbi.apply")) then self:_run_hooks("on_before_commit") for i, config in ipairs(self.parsechain) do self.uci:commit(config) -- Refresh data because commit changes section names self.uci:load(config) end self:_run_hooks("on_commit", "on_after_commit", "on_before_apply") if self.apply_on_parse then self.uci:apply(self.parsechain) self:_run_hooks("on_apply", "on_after_apply") else -- This is evaluated by the dispatcher and delegated to the -- template which in turn fires XHR to perform the actual -- apply actions. self.apply_needed = true end -- Reparse sections Node.parse(self, true) end for i, config in ipairs(self.parsechain) do self.uci:unload(config) end if type(self.commit_handler) == "function" then self:commit_handler(self:submitstate()) end end if self:submitstate() then if not self.save then self.state = FORM_INVALID elseif self.proceed then self.state = FORM_PROCEED else self.state = self.changed and FORM_CHANGED or FORM_VALID end else self.state = FORM_NODATA end return self:state_handler(self.state) end function Map.render(self, ...) self:_run_hooks("on_init") Node.render(self, ...) end -- Creates a child section function Map.section(self, class, ...) if instanceof(class, AbstractSection) then local obj = class(self, ...) self:append(obj) return obj else error("class must be a descendent of AbstractSection") end end -- UCI add function Map.add(self, sectiontype) return self.uci:add(self.config, sectiontype) end -- UCI set function Map.set(self, section, option, value) if type(value) ~= "table" or #value > 0 then if option then return self.uci:set(self.config, section, option, value) else return self.uci:set(self.config, section, value) end else return Map.del(self, section, option) end end -- UCI del function Map.del(self, section, option) if option then return self.uci:delete(self.config, section, option) else return self.uci:delete(self.config, section) end end -- UCI get function Map.get(self, section, option) if not section then return self.uci:get_all(self.config) elseif option then return self.uci:get(self.config, section, option) else return self.uci:get_all(self.config, section) end end --[[ Compound - Container ]]-- Compound = class(Node) function Compound.__init__(self, ...) Node.__init__(self) self.template = "cbi/compound" self.children = {...} end function Compound.populate_delegator(self, delegator) for _, v in ipairs(self.children) do v.delegator = delegator end end function Compound.parse(self, ...) local cstate, state = 0 for k, child in ipairs(self.children) do cstate = child:parse(...) state = (not state or cstate < state) and cstate or state end return state end --[[ Delegator - Node controller ]]-- Delegator = class(Node) function Delegator.__init__(self, ...) Node.__init__(self, ...) self.nodes = {} self.defaultpath = {} self.pageaction = false self.readinput = true self.allow_reset = false self.allow_cancel = false self.allow_back = false self.allow_finish = false self.template = "cbi/delegator" end function Delegator.set(self, name, node) assert(not self.nodes[name], "Duplicate entry") self.nodes[name] = node end function Delegator.add(self, name, node) node = self:set(name, node) self.defaultpath[#self.defaultpath+1] = name end function Delegator.insert_after(self, name, after) local n = #self.chain + 1 for k, v in ipairs(self.chain) do if v == after then n = k + 1 break end end table.insert(self.chain, n, name) end function Delegator.set_route(self, ...) local n, chain, route = 0, self.chain, {...} for i = 1, #chain do if chain[i] == self.current then n = i break end end for i = 1, #route do n = n + 1 chain[n] = route[i] end for i = n + 1, #chain do chain[i] = nil end end function Delegator.get(self, name) local node = self.nodes[name] if type(node) == "string" then node = load(node, name) end if type(node) == "table" and getmetatable(node) == nil then node = Compound(unpack(node)) end return node end function Delegator.parse(self, ...) if self.allow_cancel and Map.formvalue(self, "cbi.cancel") then if self:_run_hooks("on_cancel") then return FORM_DONE end end if not Map.formvalue(self, "cbi.delg.current") then self:_run_hooks("on_init") end local newcurrent self.chain = self.chain or self:get_chain() self.current = self.current or self:get_active() self.active = self.active or self:get(self.current) assert(self.active, "Invalid state") local stat = FORM_DONE if type(self.active) ~= "function" then self.active:populate_delegator(self) stat = self.active:parse() else self:active() end if stat > FORM_PROCEED then if Map.formvalue(self, "cbi.delg.back") then newcurrent = self:get_prev(self.current) else newcurrent = self:get_next(self.current) end elseif stat < FORM_PROCEED then return stat end if not Map.formvalue(self, "cbi.submit") then return FORM_NODATA elseif stat > FORM_PROCEED and (not newcurrent or not self:get(newcurrent)) then return self:_run_hook("on_done") or FORM_DONE else self.current = newcurrent or self.current self.active = self:get(self.current) if type(self.active) ~= "function" then self.active:populate_delegator(self) local stat = self.active:parse(false) if stat == FORM_SKIP then return self:parse(...) else return FORM_PROCEED end else return self:parse(...) end end end function Delegator.get_next(self, state) for k, v in ipairs(self.chain) do if v == state then return self.chain[k+1] end end end function Delegator.get_prev(self, state) for k, v in ipairs(self.chain) do if v == state then return self.chain[k-1] end end end function Delegator.get_chain(self) local x = Map.formvalue(self, "cbi.delg.path") or self.defaultpath return type(x) == "table" and x or {x} end function Delegator.get_active(self) return Map.formvalue(self, "cbi.delg.current") or self.chain[1] end --[[ Page - A simple node ]]-- Page = class(Node) Page.__init__ = Node.__init__ Page.parse = function() end --[[ SimpleForm - A Simple non-UCI form ]]-- SimpleForm = class(Node) function SimpleForm.__init__(self, config, title, description, data) Node.__init__(self, title, description) self.config = config self.data = data or {} self.template = "cbi/simpleform" self.dorender = true self.pageaction = false self.readinput = true end SimpleForm.formvalue = Map.formvalue SimpleForm.formvaluetable = Map.formvaluetable function SimpleForm.parse(self, readinput, ...) self.readinput = (readinput ~= false) if self:formvalue("cbi.skip") then return FORM_SKIP end if self:formvalue("cbi.cancel") and self:_run_hooks("on_cancel") then return FORM_DONE end if self:submitstate() then Node.parse(self, 1, ...) end local valid = true for k, j in ipairs(self.children) do for i, v in ipairs(j.children) do valid = valid and (not v.tag_missing or not v.tag_missing[1]) and (not v.tag_invalid or not v.tag_invalid[1]) and (not v.error) end end local state = not self:submitstate() and FORM_NODATA or valid and FORM_VALID or FORM_INVALID self.dorender = not self.handle if self.handle then local nrender, nstate = self:handle(state, self.data) self.dorender = self.dorender or (nrender ~= false) state = nstate or state end return state end function SimpleForm.render(self, ...) if self.dorender then Node.render(self, ...) end end function SimpleForm.submitstate(self) return self:formvalue("cbi.submit") end function SimpleForm.section(self, class, ...) if instanceof(class, AbstractSection) then local obj = class(self, ...) self:append(obj) return obj else error("class must be a descendent of AbstractSection") end end -- Creates a child field function SimpleForm.field(self, class, ...) local section for k, v in ipairs(self.children) do if instanceof(v, SimpleSection) then section = v break end end if not section then section = self:section(SimpleSection) end if instanceof(class, AbstractValue) then local obj = class(self, section, ...) obj.track_missing = true section:append(obj) return obj else error("class must be a descendent of AbstractValue") end end function SimpleForm.set(self, section, option, value) self.data[option] = value end function SimpleForm.del(self, section, option) self.data[option] = nil end function SimpleForm.get(self, section, option) return self.data[option] end function SimpleForm.get_scheme() return nil end Form = class(SimpleForm) function Form.__init__(self, ...) SimpleForm.__init__(self, ...) self.embedded = true end --[[ AbstractSection ]]-- AbstractSection = class(Node) function AbstractSection.__init__(self, map, sectiontype, ...) Node.__init__(self, ...) self.sectiontype = sectiontype self.map = map self.config = map.config self.optionals = {} self.defaults = {} self.fields = {} self.tag_error = {} self.tag_invalid = {} self.tag_deperror = {} self.changed = false self.optional = true self.addremove = false self.dynamic = false end -- Define a tab for the section function AbstractSection.tab(self, tab, title, desc) self.tabs = self.tabs or { } self.tab_names = self.tab_names or { } self.tab_names[#self.tab_names+1] = tab self.tabs[tab] = { title = title, description = desc, childs = { } } end -- Check whether the section has tabs function AbstractSection.has_tabs(self) return (self.tabs ~= nil) and (next(self.tabs) ~= nil) end -- Appends a new option function AbstractSection.option(self, class, option, ...) if instanceof(class, AbstractValue) then local obj = class(self.map, self, option, ...) self:append(obj) self.fields[option] = obj return obj elseif class == true then error("No valid class was given and autodetection failed.") else error("class must be a descendant of AbstractValue") end end -- Appends a new tabbed option function AbstractSection.taboption(self, tab, ...) assert(tab and self.tabs and self.tabs[tab], "Cannot assign option to not existing tab %q" % tostring(tab)) local l = self.tabs[tab].childs local o = AbstractSection.option(self, ...) if o then l[#l+1] = o end return o end -- Render a single tab function AbstractSection.render_tab(self, tab, ...) assert(tab and self.tabs and self.tabs[tab], "Cannot render not existing tab %q" % tostring(tab)) local k, node for k, node in ipairs(self.tabs[tab].childs) do node.last_child = (k == #self.tabs[tab].childs) node:render(...) end end -- Parse optional options function AbstractSection.parse_optionals(self, section) if not self.optional then return end self.optionals[section] = {} local field = self.map:formvalue("cbi.opt."..self.config.."."..section) for k,v in ipairs(self.children) do if v.optional and not v:cfgvalue(section) and not self:has_tabs() then if field == v.option then field = nil self.map.proceed = true else table.insert(self.optionals[section], v) end end end if field and #field > 0 and self.dynamic then self:add_dynamic(field) end end -- Add a dynamic option function AbstractSection.add_dynamic(self, field, optional) local o = self:option(Value, field, field) o.optional = optional end -- Parse all dynamic options function AbstractSection.parse_dynamic(self, section) if not self.dynamic then return end local arr = luci.util.clone(self:cfgvalue(section)) local form = self.map:formvaluetable("cbid."..self.config.."."..section) for k, v in pairs(form) do arr[k] = v end for key,val in pairs(arr) do local create = true for i,c in ipairs(self.children) do if c.option == key then create = false end end if create and key:sub(1, 1) ~= "." then self.map.proceed = true self:add_dynamic(key, true) end end end -- Returns the section's UCI table function AbstractSection.cfgvalue(self, section) return self.map:get(section) end -- Push events function AbstractSection.push_events(self) --luci.util.append(self.map.events, self.events) self.map.changed = true end -- Removes the section function AbstractSection.remove(self, section) self.map.proceed = true return self.map:del(section) end -- Creates the section function AbstractSection.create(self, section) local stat if section then stat = section:match("^[%w_]+$") and self.map:set(section, nil, self.sectiontype) else section = self.map:add(self.sectiontype) stat = section end if stat then for k,v in pairs(self.children) do if v.default then self.map:set(section, v.option, v.default) end end for k,v in pairs(self.defaults) do self.map:set(section, k, v) end end self.map.proceed = true return stat end SimpleSection = class(AbstractSection) function SimpleSection.__init__(self, form, ...) AbstractSection.__init__(self, form, nil, ...) self.template = "cbi/nullsection" end Table = class(AbstractSection) function Table.__init__(self, form, data, ...) local datasource = {} local tself = self datasource.config = "table" self.data = data or {} datasource.formvalue = Map.formvalue datasource.formvaluetable = Map.formvaluetable datasource.readinput = true function datasource.get(self, section, option) return tself.data[section] and tself.data[section][option] end function datasource.submitstate(self) return Map.formvalue(self, "cbi.submit") end function datasource.del(...) return true end function datasource.get_scheme() return nil end AbstractSection.__init__(self, datasource, "table", ...) self.template = "cbi/tblsection" self.rowcolors = true self.anonymous = true end function Table.parse(self, readinput) self.map.readinput = (readinput ~= false) for i, k in ipairs(self:cfgsections()) do if self.map:submitstate() then Node.parse(self, k) end end end function Table.cfgsections(self) local sections = {} for i, v in luci.util.kspairs(self.data) do table.insert(sections, i) end return sections end function Table.update(self, data) self.data = data end --[[ NamedSection - A fixed configuration section defined by its name ]]-- NamedSection = class(AbstractSection) function NamedSection.__init__(self, map, section, stype, ...) AbstractSection.__init__(self, map, stype, ...) -- Defaults self.addremove = false self.template = "cbi/nsection" self.section = section end function NamedSection.parse(self, novld) local s = self.section local active = self:cfgvalue(s) if self.addremove then local path = self.config.."."..s if active then -- Remove the section if self.map:formvalue("cbi.rns."..path) and self:remove(s) then self:push_events() return end else -- Create and apply default values if self.map:formvalue("cbi.cns."..path) then self:create(s) return end end end if active then AbstractSection.parse_dynamic(self, s) if self.map:submitstate() then Node.parse(self, s) end AbstractSection.parse_optionals(self, s) if self.changed then self:push_events() end end end --[[ TypedSection - A (set of) configuration section(s) defined by the type addremove: Defines whether the user can add/remove sections of this type anonymous: Allow creating anonymous sections validate: a validation function returning nil if the section is invalid ]]-- TypedSection = class(AbstractSection) function TypedSection.__init__(self, map, type, ...) AbstractSection.__init__(self, map, type, ...) self.template = "cbi/tsection" self.deps = {} self.anonymous = false end -- Return all matching UCI sections for this TypedSection function TypedSection.cfgsections(self) local sections = {} self.map.uci:foreach(self.map.config, self.sectiontype, function (section) if self:checkscope(section[".name"]) then table.insert(sections, section[".name"]) end end) return sections end -- Limits scope to sections that have certain option => value pairs function TypedSection.depends(self, option, value) table.insert(self.deps, {option=option, value=value}) end function TypedSection.parse(self, novld) if self.addremove then -- Remove local crval = REMOVE_PREFIX .. self.config local name = self.map:formvaluetable(crval) for k,v in pairs(name) do if k:sub(-2) == ".x" then k = k:sub(1, #k - 2) end if self:cfgvalue(k) and self:checkscope(k) then self:remove(k) end end end local co for i, k in ipairs(self:cfgsections()) do AbstractSection.parse_dynamic(self, k) if self.map:submitstate() then Node.parse(self, k, novld) end AbstractSection.parse_optionals(self, k) end if self.addremove then -- Create local created local crval = CREATE_PREFIX .. self.config .. "." .. self.sectiontype local origin, name = next(self.map:formvaluetable(crval)) if self.anonymous then if name then created = self:create(nil, origin) end else if name then -- Ignore if it already exists if self:cfgvalue(name) then name = nil; end name = self:checkscope(name) if not name then self.err_invalid = true end if name and #name > 0 then created = self:create(name, origin) and name if not created then self.invalid_cts = true end end end end if created then AbstractSection.parse_optionals(self, created) end end if self.sortable then local stval = RESORT_PREFIX .. self.config .. "." .. self.sectiontype local order = self.map:formvalue(stval) if order and #order > 0 then local sid local num = 0 for sid in util.imatch(order) do self.map.uci:reorder(self.config, sid, num) num = num + 1 end self.changed = (num > 0) end end if created or self.changed then self:push_events() end end -- Verifies scope of sections function TypedSection.checkscope(self, section) -- Check if we are not excluded if self.filter and not self:filter(section) then return nil end -- Check if at least one dependency is met if #self.deps > 0 and self:cfgvalue(section) then local stat = false for k, v in ipairs(self.deps) do if self:cfgvalue(section)[v.option] == v.value then stat = true end end if not stat then return nil end end return self:validate(section) end -- Dummy validate function function TypedSection.validate(self, section) return section end --[[ AbstractValue - An abstract Value Type null: Value can be empty valid: A function returning the value if it is valid otherwise nil depends: A table of option => value pairs of which one must be true default: The default value size: The size of the input fields rmempty: Unset value if empty optional: This value is optional (see AbstractSection.optionals) ]]-- AbstractValue = class(Node) function AbstractValue.__init__(self, map, section, option, ...) Node.__init__(self, ...) self.section = section self.option = option self.map = map self.config = map.config self.tag_invalid = {} self.tag_missing = {} self.tag_reqerror = {} self.tag_error = {} self.deps = {} self.subdeps = {} --self.cast = "string" self.track_missing = false self.rmempty = true self.default = nil self.size = nil self.optional = false end function AbstractValue.prepare(self) self.cast = self.cast or "string" end -- Add a dependencie to another section field function AbstractValue.depends(self, field, value) local deps if type(field) == "string" then deps = {} deps[field] = value else deps = field end table.insert(self.deps, {deps=deps, add=""}) end -- Generates the unique CBID function AbstractValue.cbid(self, section) return "cbid."..self.map.config.."."..section.."."..self.option end -- Return whether this object should be created function AbstractValue.formcreated(self, section) local key = "cbi.opt."..self.config.."."..section return (self.map:formvalue(key) == self.option) end -- Returns the formvalue for this object function AbstractValue.formvalue(self, section) return self.map:formvalue(self:cbid(section)) end function AbstractValue.additional(self, value) self.optional = value end function AbstractValue.mandatory(self, value) self.rmempty = not value end function AbstractValue.add_error(self, section, type, msg) self.error = self.error or { } self.error[section] = msg or type self.section.error = self.section.error or { } self.section.error[section] = self.section.error[section] or { } table.insert(self.section.error[section], msg or type) if type == "invalid" then self.tag_invalid[section] = true elseif type == "missing" then self.tag_missing[section] = true end self.tag_error[section] = true self.map.save = false end function AbstractValue.parse(self, section, novld) local fvalue = self:formvalue(section) local cvalue = self:cfgvalue(section) -- If favlue and cvalue are both tables and have the same content -- make them identical if type(fvalue) == "table" and type(cvalue) == "table" then local equal = #fvalue == #cvalue if equal then for i=1, #fvalue do if cvalue[i] ~= fvalue[i] then equal = false end end end if equal then fvalue = cvalue end end if fvalue and #fvalue > 0 then -- If we have a form value, write it to UCI local val_err fvalue, val_err = self:validate(fvalue, section) fvalue = self:transform(fvalue) if not fvalue and not novld then self:add_error(section, "invalid", val_err) end if fvalue and (self.forcewrite or not (fvalue == cvalue)) then if self:write(section, fvalue) then -- Push events self.section.changed = true --luci.util.append(self.map.events, self.events) end end else -- Unset the UCI or error if self.rmempty or self.optional then if self:remove(section) then -- Push events self.section.changed = true --luci.util.append(self.map.events, self.events) end elseif cvalue ~= fvalue and not novld then -- trigger validator with nil value to get custom user error msg. local _, val_err = self:validate(nil, section) self:add_error(section, "missing", val_err) end end end -- Render if this value exists or if it is mandatory function AbstractValue.render(self, s, scope) if not self.optional or self.section:has_tabs() or self:cfgvalue(s) or self:formcreated(s) then scope = scope or {} scope.section = s scope.cbid = self:cbid(s) Node.render(self, scope) end end -- Return the UCI value of this object function AbstractValue.cfgvalue(self, section) local value if self.tag_error[section] then value = self:formvalue(section) else value = self.map:get(section, self.option) end if not value then return nil elseif not self.cast or self.cast == type(value) then return value elseif self.cast == "string" then if type(value) == "table" then return value[1] end elseif self.cast == "table" then return { value } end end -- Validate the form value function AbstractValue.validate(self, value) if self.datatype and value then if type(value) == "table" then local v for _, v in ipairs(value) do if v and #v > 0 and not verify_datatype(self.datatype, v) then return nil end end else if not verify_datatype(self.datatype, value) then return nil end end end return value end AbstractValue.transform = AbstractValue.validate -- Write to UCI function AbstractValue.write(self, section, value) return self.map:set(section, self.option, value) end -- Remove from UCI function AbstractValue.remove(self, section) return self.map:del(section, self.option) end --[[ Value - A one-line value maxlength: The maximum length ]]-- Value = class(AbstractValue) function Value.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/value" self.keylist = {} self.vallist = {} end function Value.reset_values(self) self.keylist = {} self.vallist = {} end function Value.value(self, key, val) val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end -- DummyValue - This does nothing except being there DummyValue = class(AbstractValue) function DummyValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/dvalue" self.value = nil end function DummyValue.cfgvalue(self, section) local value if self.value then if type(self.value) == "function" then value = self:value(section) else value = self.value end else value = AbstractValue.cfgvalue(self, section) end return value end function DummyValue.parse(self) end --[[ Flag - A flag being enabled or disabled ]]-- Flag = class(AbstractValue) function Flag.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/fvalue" self.enabled = "1" self.disabled = "0" self.default = self.disabled end -- A flag can only have two states: set or unset function Flag.parse(self, section) local fexists = self.map:formvalue( FEXIST_PREFIX .. self.config .. "." .. section .. "." .. self.option) if fexists then local fvalue = self:formvalue(section) and self.enabled or self.disabled if fvalue ~= self.default or (not self.optional and not self.rmempty) then self:write(section, fvalue) else self:remove(section) end else self:remove(section) end end function Flag.cfgvalue(self, section) return AbstractValue.cfgvalue(self, section) or self.default end --[[ ListValue - A one-line value predefined in a list widget: The widget that will be used (select, radio) ]]-- ListValue = class(AbstractValue) function ListValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/lvalue" self.keylist = {} self.vallist = {} self.size = 1 self.widget = "select" end function ListValue.reset_values(self) self.keylist = {} self.vallist = {} end function ListValue.value(self, key, val, ...) if luci.util.contains(self.keylist, key) then return end val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) for i, deps in ipairs({...}) do self.subdeps[#self.subdeps + 1] = {add = "-"..key, deps=deps} end end function ListValue.validate(self, val) if luci.util.contains(self.keylist, val) then return val else return nil end end --[[ MultiValue - Multiple delimited values widget: The widget that will be used (select, checkbox) delimiter: The delimiter that will separate the values (default: " ") ]]-- MultiValue = class(AbstractValue) function MultiValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/mvalue" self.keylist = {} self.vallist = {} self.widget = "checkbox" self.delimiter = " " end function MultiValue.render(self, ...) if self.widget == "select" and not self.size then self.size = #self.vallist end AbstractValue.render(self, ...) end function MultiValue.reset_values(self) self.keylist = {} self.vallist = {} end function MultiValue.value(self, key, val) if luci.util.contains(self.keylist, key) then return end val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function MultiValue.valuelist(self, section) local val = self:cfgvalue(section) if not(type(val) == "string") then return {} end return luci.util.split(val, self.delimiter) end function MultiValue.validate(self, val) val = (type(val) == "table") and val or {val} local result for i, value in ipairs(val) do if luci.util.contains(self.keylist, value) then result = result and (result .. self.delimiter .. value) or value end end return result end StaticList = class(MultiValue) function StaticList.__init__(self, ...) MultiValue.__init__(self, ...) self.cast = "table" self.valuelist = self.cfgvalue if not self.override_scheme and self.map:get_scheme(self.section.sectiontype, self.option) then local vs = self.map:get_scheme(self.section.sectiontype, self.option) if self.value and vs.values and not self.override_values then for k, v in pairs(vs.values) do self:value(k, v) end end end end function StaticList.validate(self, value) value = (type(value) == "table") and value or {value} local valid = {} for i, v in ipairs(value) do if luci.util.contains(self.keylist, v) then table.insert(valid, v) end end return valid end DynamicList = class(AbstractValue) function DynamicList.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/dynlist" self.cast = "table" self.keylist = {} self.vallist = {} end function DynamicList.reset_values(self) self.keylist = {} self.vallist = {} end function DynamicList.value(self, key, val) val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function DynamicList.write(self, section, value) local t = { } if type(value) == "table" then local x for _, x in ipairs(value) do if x and #x > 0 then t[#t+1] = x end end else t = { value } end if self.cast == "string" then value = table.concat(t, " ") else value = t end return AbstractValue.write(self, section, value) end function DynamicList.cfgvalue(self, section) local value = AbstractValue.cfgvalue(self, section) if type(value) == "string" then local x local t = { } for x in value:gmatch("%S+") do if #x > 0 then t[#t+1] = x end end value = t end return value end function DynamicList.formvalue(self, section) local value = AbstractValue.formvalue(self, section) if type(value) == "string" then if self.cast == "string" then local x local t = { } for x in value:gmatch("%S+") do t[#t+1] = x end value = t else value = { value } end end return value end --[[ TextValue - A multi-line value rows: Rows ]]-- TextValue = class(AbstractValue) function TextValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/tvalue" end --[[ Button ]]-- Button = class(AbstractValue) function Button.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/button" self.inputstyle = nil self.rmempty = true end FileUpload = class(AbstractValue) function FileUpload.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/upload" if not self.map.upload_fields then self.map.upload_fields = { self } else self.map.upload_fields[#self.map.upload_fields+1] = self end end function FileUpload.formcreated(self, section) return AbstractValue.formcreated(self, section) or self.map:formvalue("cbi.rlf."..section.."."..self.option) or self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") end function FileUpload.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) if val and fs.access(val) then return val end return nil end function FileUpload.formvalue(self, section) local val = AbstractValue.formvalue(self, section) if val then if not self.map:formvalue("cbi.rlf."..section.."."..self.option) and not self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") then return val end fs.unlink(val) self.value = nil end return nil end function FileUpload.remove(self, section) local val = AbstractValue.formvalue(self, section) if val and fs.access(val) then fs.unlink(val) end return AbstractValue.remove(self, section) end FileBrowser = class(AbstractValue) function FileBrowser.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/browser" end
gpl-2.0
ffxiphoenix/darkstar
scripts/globals/items/plate_of_tentacle_sushi.lua
14
1878
----------------------------------------- -- ID: 5215 -- Item: plate_of_tentacle_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 20 -- Dexterity 3 -- Agility 3 -- Mind -1 -- Accuracy % 19 (cap 18) -- Ranged Accuracy % 19 (cap 18) -- Double Attack 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5215); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_DEX, 3); target:addMod(MOD_AGI, 3); target:addMod(MOD_MND, -1); target:addMod(MOD_FOOD_ACCP, 20); target:addMod(MOD_FOOD_ACC_CAP, 18); target:addMod(MOD_FOOD_RACCP, 20); target:addMod(MOD_FOOD_RACC_CAP, 18); target:addMod(MOD_DOUBLE_ATTACK, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_DEX, 3); target:delMod(MOD_AGI, 3); target:delMod(MOD_MND, -1); target:delMod(MOD_FOOD_ACCP, 20); target:delMod(MOD_FOOD_ACC_CAP, 18); target:delMod(MOD_FOOD_RACCP, 20); target:delMod(MOD_FOOD_RACC_CAP, 18); target:delMod(MOD_DOUBLE_ATTACK, 1); end;
gpl-3.0
guker/nn
Linear.lua
2
2957
local Linear, parent = torch.class('nn.Linear', 'nn.Module') function Linear:__init(inputSize, outputSize) parent.__init(self) self.weight = torch.Tensor(outputSize, inputSize) self.bias = torch.Tensor(outputSize) self.gradWeight = torch.Tensor(outputSize, inputSize) self.gradBias = torch.Tensor(outputSize) self:reset() end function Linear:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(2)) end if nn.oldSeed then for i=1,self.weight:size(1) do self.weight:select(1, i):apply(function() return torch.uniform(-stdv, stdv) end) self.bias[i] = torch.uniform(-stdv, stdv) end else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end function Linear:updateOutput(input) if input:dim() == 1 then self.output:resize(self.bias:size(1)) self.output:copy(self.bias) self.output:addmv(1, self.weight, input) elseif input:dim() == 2 then local nframe = input:size(1) local nunit = self.bias:size(1) self.output:resize(nframe, nunit) if nunit == 1 then -- Special case to fix output size of 1 bug: self.output:zero():add(self.bias[1]) self.output:select(2,1):addmv(1, input, self.weight:select(1,1)) else self.output:zero():addr(1, input.new(nframe):fill(1), self.bias) self.output:addmm(1, input, self.weight:t()) end else error('input must be vector or matrix') end return self.output end function Linear:updateGradInput(input, gradOutput) if self.gradInput then local nElement = self.gradInput:nElement() self.gradInput:resizeAs(input) if self.gradInput:nElement() ~= nElement then self.gradInput:zero() end if input:dim() == 1 then self.gradInput:addmv(0, 1, self.weight:t(), gradOutput) elseif input:dim() == 2 then self.gradInput:addmm(0, 1, gradOutput, self.weight) end return self.gradInput end end function Linear:accGradParameters(input, gradOutput, scale) scale = scale or 1 if input:dim() == 1 then self.gradWeight:addr(scale, gradOutput, input) self.gradBias:add(scale, gradOutput) elseif input:dim() == 2 then local nframe = input:size(1) local nunit = self.bias:size(1) if nunit == 1 then -- Special case to fix output size of 1 bug: self.gradWeight:select(1,1):addmv(scale, input:t(), gradOutput:select(2,1)) self.gradBias:addmv(scale, gradOutput:t(), input.new(nframe):fill(1)) else self.gradWeight:addmm(scale, gradOutput:t(), input) self.gradBias:addmv(scale, gradOutput:t(), input.new(nframe):fill(1)) end end end -- we do not need to accumulate parameters when sharing Linear.sharedAccUpdateGradParameters = Linear.accUpdateGradParameters
bsd-3-clause
vilarion/Illarion-Content
monster/race_89_red_imp/id_892_cursed.lua
3
1205
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local mageBehaviour = require("monster.base.behaviour.mage") local monstermagic = require("monster.base.monstermagic") local redImps = require("monster.race_89_red_imp.base") local magic = monstermagic() magic.addWarping{probability = 0.15, usage = magic.ONLY_NEAR_ENEMY} magic.addFireball{probability = 0.05, damage = {from = 500, to = 1500}} magic.addFlamestrike{probability = 0.005, damage = {from = 250, to = 750}, targetCount = 3} local M = redImps.generateCallbacks() M = magic.addCallbacks(M) return mageBehaviour.addCallbacks(magic, M)
agpl-3.0
AfuSensi/Mr.Green-MTA-Resources
resources/[admin]/admin/server/admin_screenshot.lua
7
3910
--[[********************************** * * Multi Theft Auto - Admin Panel * * admin_screenshot.lua * * Original File by MCvarial * **************************************]] local con = dbConnect("sqlite", ":/registry.db") dbExec(con, "CREATE TABLE IF NOT EXISTS `admin_screenshots` (`id` INTEGER, `player` TEXT, `serial` TEXT, `admin` TEXT, `realtime` TEXT)") local screenshots = {} local currentid = 0 addEventHandler("onResourceStart", resourceRoot, function() dbQuery(resourceStartedCallback, {}, con, "SELECT `id` FROM `admin_screenshots`") end ) function resourceStartedCallback(qh) local result = dbPoll(qh, 0) for i, screenshot in ipairs(result) do if screenshot.id > currentid then currentid = screenshot.id end end end addEvent("aScreenShot",true) addEventHandler("aScreenShot",resourceRoot, function (action,admin,player,arg1,arg2) if not isElement(admin) then return end if not hasObjectPermissionTo(admin,"command.takescreenshot") then return end if action == "new" then if not isElement(player) then return end if screenshots[player] then table.insert(screenshots[player].admins,admin) else local t = getRealTime() screenshots[player] = {player=player,admin=getPlayerName(admin),admins={admin},realtime=t.monthday.."/"..(t.month+1).."/"..(t.year+1900).." "..t.hour..":"..t.minute..":"..t.second} takePlayerScreenShot(player,800,600,getPlayerName(player)) triggerClientEvent(admin,"aClientScreenShot",resourceRoot,"new",player) end elseif action == "list" then dbQuery(clientScreenShotCallback, {admin}, con, "SELECT `id`,`player`,`admin`,`realtime` FROM `admin_screenshots`") elseif action == "delete" then if fileExists("screenshots/"..player..".jpg") then fileDelete("screenshots/"..player..".jpg") end dbExec(con, "DELETE FROM `admin_screenshots` WHERE `id`=?", player) elseif action == "view" then if fileExists("screenshots/"..player..".jpg") then local file = fileOpen("screenshots/"..player..".jpg") local imagedata = fileRead(file,fileGetSize(file)) fileClose(file) triggerClientEvent(admin,"aClientScreenShot",resourceRoot,"new",arg1) triggerLatentClientEvent(admin,"aClientScreenShot",resourceRoot,"view",arg1,imagedata) end end end ) function clientScreenShotCallback(qh, admin) local result = dbPoll(qh, 0) if (not isElement(admin)) then return end triggerClientEvent(admin, "aClientScreenShot", resourceRoot, "list", nil, result) end addEventHandler("onPlayerScreenShot",root, function (resource,status,imagedata,timestamp,tag) if resource == getThisResource() then local screenshot = screenshots[source] if not screenshot then return end if status == "ok" then currentid = currentid + 1 dbExec(con, "INSERT INTO `admin_screenshots`(`id`,`player`,`serial`,`admin`,`realtime`) VALUES(?,?,?,?,?)",currentid,getPlayerName(source),getPlayerSerial(source),screenshot.admin,screenshot.realtime) if fileExists("screenshots/"..currentid..".jpg") then fileDelete("screenshots/"..currentid..".jpg") end local file = fileCreate("screenshots/"..currentid..".jpg") fileWrite(file,imagedata) fileClose(file) for i,admin in ipairs (screenshot.admins) do if isElement(admin) then triggerLatentClientEvent(admin,"aClientScreenShot",resourceRoot,"view",source,imagedata,screenshot.admin,screenshot.realtime,currentid) end end else for i,admin in ipairs (screenshot.admins) do if isElement(admin) then triggerClientEvent(admin,"aClientScreenShot",resourceRoot,status,source) end end end screenshots[source] = nil end end ) addEventHandler("onPlayerQuit",root, function () if screenshots[source] then for i,admin in ipairs (screenshots[source].admins) do triggerClientEvent(admin,"aClientScreenShot",resourceRoot,"quit",source) end screenshots[source] = nil end end )
mit
ffxiphoenix/darkstar
scripts/zones/Rabao/npcs/Shiny_Teeth.lua
36
1675
----------------------------------- -- Area: Rabao -- NPC: Shiny Teeth -- Standard Merchant NPC -- @pos -30 8 99 247 ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Rabao/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,SHINY_TEETH_SHOP_DIALOG); stock = {0x4042,1867, --Dagger 1867 - 2111 0x404C,11128, --Kris 11128 - 12096 0x4052,2231, --Knife 2231 - 2522 0x40A8,4163, --Scimitar 4163 - 4706 0x40A9,35308, --Tulwar 35308 0x40AE,62560, --Falchion 62560 - 70720 0x42A4,2439, --Rod 2439 - 4680 0x4011,103803, --Jamadhars 103803 - 104944 0x4303,23887, --Composite Bow 23887 - 24150 0x4392,294, --Tathlum 294 - 332 0x43A8,7, --Iron Arrow 7 - 10 0x43BC,92, --Bullet 92 - 174 0x43A3,5460, --Riot Grenade 5460 - 5520 0x4384,8996} --Chakram 8996 - 10995 showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
ffxiphoenix/darkstar
scripts/globals/weaponskills/blade_to.lua
30
1253
----------------------------------- -- Blade To -- Katana weapon skill -- Skill Level: 100 -- Deals ice elemental damage. Damage varies with TP. -- Aligned with the Snow Gorget & Breeze Gorget. -- Aligned with the Snow Belt & Breeze Belt. -- Element: Ice -- Modifiers: STR:30% ; INT:30% -- 100%TP 200%TP 300%TP -- 0.50 0.75 1.00 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 0.5; params.ftp200 = 0.75; params.ftp300 = 1; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.3; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_ICE; params.skill = SKILL_KAT; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.4; params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
AfuSensi/Mr.Green-MTA-Resources
resources/[gameplay]/-shaders-bloom_fix/c_bloom.lua
4
6191
-- -- c_bloom.lua -- local orderPriority = "-1.0" -- The lower this number, the later the effect is applied Settings = {} Settings.var = {} ---------------------------------------------------------------- -- enableBloom ---------------------------------------------------------------- function enableBloom() if bEffectEnabled then return end -- Create things myScreenSource = dxCreateScreenSource( scx/2, scy/2 ) blurHShader,tecName = dxCreateShader( "fx/blurH.fx" ) -- outputDebugString( "blurHShader is using technique " .. tostring(tecName) ) blurVShader,tecName = dxCreateShader( "fx/blurV.fx" ) -- outputDebugString( "blurVShader is using technique " .. tostring(tecName) ) brightPassShader,tecName = dxCreateShader( "fx/brightPass.fx" ) -- outputDebugString( "brightPassShader is using technique " .. tostring(tecName) ) addBlendShader,tecName = dxCreateShader( "fx/addBlend.fx" ) -- outputDebugString( "addBlendShader is using technique " .. tostring(tecName) ) -- Get list of all elements used effectParts = { myScreenSource, blurVShader, blurHShader, brightPassShader, addBlendShader, } -- Check list of all elements used bAllValid = true for _,part in ipairs(effectParts) do bAllValid = part and bAllValid end setEffectVariables () bEffectEnabled = true if not bAllValid then outputChatBox( "Bloom: Could not create some things." ) disableBloom() end end ----------------------------------------------------------------------------------- -- disableBloom ----------------------------------------------------------------------------------- function disableBloom() if not bEffectEnabled then return end -- Destroy all shaders for _,part in ipairs(effectParts) do if part then destroyElement( part ) end end effectParts = {} bAllValid = false RTPool.clear() -- Flag effect as stopped bEffectEnabled = false end --------------------------------- -- Settings for effect --------------------------------- function setEffectVariables() local v = Settings.var -- Bloom v.cutoff = 0.08 v.power = 1.88 v.blur = 0.9 v.bloom = 1.7 v.blendR = 204 v.blendG = 153 v.blendB = 130 v.blendA = 100 -- Debugging v.PreviewEnable=0 v.PreviewPosY=0 v.PreviewPosX=100 v.PreviewSize=70 end ----------------------------------------------------------------------------------- -- onClientHUDRender ----------------------------------------------------------------------------------- addEventHandler( "onClientHUDRender", root, function() if not bAllValid or not Settings.var then return end local v = Settings.var -- Reset render target pool RTPool.frameStart() DebugResults.frameStart() -- Update screen dxUpdateScreenSource( myScreenSource, true ) -- Start with screen local current = myScreenSource -- Apply all the effects, bouncing from one render target to another current = applyBrightPass( current, v.cutoff, v.power ) current = applyDownsample( current ) current = applyDownsample( current ) current = applyGBlurH( current, v.bloom, v.blur ) current = applyGBlurV( current, v.bloom, v.blur ) -- When we're done, turn the render target back to default dxSetRenderTarget() -- Mix result onto the screen using 'add' rather than 'alpha blend' if current then dxSetShaderValue( addBlendShader, "TEX0", current ) local col = tocolor(v.blendR, v.blendG, v.blendB, v.blendA) dxDrawImage( 0, 0, scx, scy, addBlendShader, 0,0,0, col ) end -- Debug stuff if v.PreviewEnable > 0.5 then DebugResults.drawItems ( v.PreviewSize, v.PreviewPosX, v.PreviewPosY ) end end ,true ,"low" .. orderPriority ) ----------------------------------------------------------------------------------- -- Apply the different stages ----------------------------------------------------------------------------------- function applyDownsample( Src, amount ) if not Src then return nil end amount = amount or 2 local mx,my = dxGetMaterialSize( Src ) mx = mx / amount my = my / amount local newRT = RTPool.GetUnused(mx,my) if not newRT then return nil end dxSetRenderTarget( newRT ) dxDrawImage( 0, 0, mx, my, Src ) DebugResults.addItem( newRT, "applyDownsample" ) return newRT end function applyGBlurH( Src, bloom, blur ) if not Src then return nil end local mx,my = dxGetMaterialSize( Src ) local newRT = RTPool.GetUnused(mx,my) if not newRT then return nil end dxSetRenderTarget( newRT, true ) dxSetShaderValue( blurHShader, "TEX0", Src ) dxSetShaderValue( blurHShader, "TEX0SIZE", mx,my ) dxSetShaderValue( blurHShader, "BLOOM", bloom ) dxSetShaderValue( blurHShader, "BLUR", blur ) dxDrawImage( 0, 0, mx, my, blurHShader ) DebugResults.addItem( newRT, "applyGBlurH" ) return newRT end function applyGBlurV( Src, bloom, blur ) if not Src then return nil end local mx,my = dxGetMaterialSize( Src ) local newRT = RTPool.GetUnused(mx,my) if not newRT then return nil end dxSetRenderTarget( newRT, true ) dxSetShaderValue( blurVShader, "TEX0", Src ) dxSetShaderValue( blurVShader, "TEX0SIZE", mx,my ) dxSetShaderValue( blurVShader, "BLOOM", bloom ) dxSetShaderValue( blurVShader, "BLUR", blur ) dxDrawImage( 0, 0, mx,my, blurVShader ) DebugResults.addItem( newRT, "applyGBlurV" ) return newRT end function applyBrightPass( Src, cutoff, power ) if not Src then return nil end local mx,my = dxGetMaterialSize( Src ) local newRT = RTPool.GetUnused(mx,my) if not newRT then return nil end dxSetRenderTarget( newRT, true ) dxSetShaderValue( brightPassShader, "TEX0", Src ) dxSetShaderValue( brightPassShader, "CUTOFF", cutoff ) dxSetShaderValue( brightPassShader, "POWER", power ) dxDrawImage( 0, 0, mx,my, brightPassShader ) DebugResults.addItem( newRT, "applyBrightPass" ) return newRT end ---------------------------------------------------------------- -- Avoid errors messages when memory is low ---------------------------------------------------------------- _dxDrawImage = dxDrawImage function xdxDrawImage(posX, posY, width, height, image, ... ) if not image then return false end return _dxDrawImage( posX, posY, width, height, image, ... ) end
mit
Quenty/NevermoreEngine
src/multipleclickutils/src/Client/MultipleClickUtils.lua
1
3191
--[=[ Utility library for detecting multiple clicks or taps. Not good UX, but good for opening up a debug menus. @class MultipleClickUtils ]=] local require = require(script.Parent.loader).load(script) local Signal = require("Signal") local Maid = require("Maid") local Observable = require("Observable") local MultipleClickUtils = {} local TIME_TO_CLICK_AGAIN = 0.5 -- Based upon windows default local VALID_TYPES = { [Enum.UserInputType.MouseButton1] = true; [Enum.UserInputType.Touch] = true; } --[=[ Observes a double click on the Gui @param gui GuiBase @return Observable<InputObject> ]=] function MultipleClickUtils.observeDoubleClick(gui) return MultipleClickUtils.observeMultipleClicks(gui, 2) end --[=[ Returns a signal that fires when the player clicks or taps on a Gui twice. @param maid Maid @param gui GuiBase @return Signal<InputObject> ]=] function MultipleClickUtils.getDoubleClickSignal(maid, gui) return MultipleClickUtils.getDoubleClickSignal(maid, gui, 2) end --[=[ Observes multiple clicks click on the Gui @param gui GuiBase @param requiredCount number @return Observable<InputObject> ]=] function MultipleClickUtils.observeMultipleClicks(gui, requiredCount) assert(typeof(gui) == "Instance", "Bad gui") assert(type(requiredCount) == "number", "Bad requiredCount") return Observable.new(function(sub) local maid = Maid.new() maid:GiveTask(MultipleClickUtils.getMultipleClickSignal(maid, gui, requiredCount) :Connect(function(...) sub:Fire(...) end)) return maid end) end --[=[ For use in Blend. Observes multiple clicks. ```lua Blend.New "TextButton" { [MultipleClickUtils.onMultipleClicks(3)] = function() print("Clicked") end; }; ``` @param requiredCount number @return (gui: GuiBase) -> Observable<InputObject> ]=] function MultipleClickUtils.onMultipleClicks(requiredCount) assert(type(requiredCount) == "number", "Bad requiredCount") return function(gui) return MultipleClickUtils.observeMultipleClicks(gui, requiredCount) end end --[=[ Returns a signal that fires when the player clicks or taps on a Gui a certain amount of times. @param maid Maid @param gui GuiBase @param requiredCount number @return Signal<InputObject> ]=] function MultipleClickUtils.getMultipleClickSignal(maid, gui, requiredCount) assert(Maid.isMaid(maid), "Bad maid") assert(typeof(gui) == "Instance", "Bad gui") assert(type(requiredCount) == "number", "Bad requiredCount") local signal = Signal.new() maid:GiveTask(signal) local lastInputTime = 0 local lastInputObject = nil local inputCount = 0 maid:GiveTask(gui.InputBegan:Connect(function(inputObject) if not VALID_TYPES[inputObject.UserInputType] then return end if lastInputObject and inputObject.UserInputType == lastInputObject.UserInputType and (tick() - lastInputTime) <= TIME_TO_CLICK_AGAIN then inputCount = inputCount + 1 if inputCount >= requiredCount then inputCount = 0 lastInputTime = 0 lastInputObject = nil signal:Fire(lastInputObject) end else inputCount = 1 lastInputTime = tick() lastInputObject = inputObject end end)) return signal end return MultipleClickUtils
mit
ProjectSkyfire/SkyFire-Community-Tools
FireAdmin/Locales/huHU.lua
1
10967
------------------------------------------------------------------------------------------------------------- -- -- FireAdmin Version 5.x -- FireAdmin is a derivative of FireAdmin, which is a derivative of MangAdmin. -- -- Copyright (C) 2007 Free Software Foundation, Inc. -- License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> -- This is free software: you are free to change and redistribute it. -- There is NO WARRANTY, to the extent permitted by law. -- -- 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- -- Official Forums: http://groups.google.com/group/trinityadmin -- GoogleCode Website: http://code.google.com/p/trinityadmin/ -- Subversion Repository: http://trinityadmin.googlecode.com/svn/ -- Dev Blog: http://trinityadmin.blogspot.com/ ------------------------------------------------------------------------------------------------------------- function Return_huHU() return { ["slashcmds"] = { "/mangadmin", "/ma" }, ["lang"] = "Magyar", ["realm"] = "|cFF00FF00Realm:|r "..GetCVar("realmName"), ["char"] = "|cFF00FF00Karakter:|r "..UnitName("player"), ["guid"] = "|cFF00FF00Guid:|r ", ["tickets"] = "|cFF00FF00Tickets:|r ", ["gridnavigator"] = "Grid-Navigátor", ["selectionerror1"] = "Válaszd ki magad, egy másik player-t vagy semmit!", ["selectionerror2"] = "Válaszd ki magad vagy semmit!", ["selectionerror3"] = "Válassz ki egy másik player-t!", ["selectionerror4"] = "Válassz ki egy NPC-t!", ["searchResults"] = "|cFF00FF00Keresési eredmény:|r ", ["tabmenu_Main"] = "Föoldal", ["tabmenu_Char"] = "Karakter", ["tabmenu_Tele"] = "Teleport", ["tabmenu_Ticket"] = "Ticket rendszer", ["tabmenu_Misc"] = "Egyéb", ["tabmenu_Server"] = "Szerver", ["tabmenu_Log"] = "Napló", ["tt_Default"] = "Vidd a kurzort bármelyik gomb fölé infó mutatásához!", ["tt_MainButton"] = "Kattints, hogy megnyissa a MangAdmint.", ["tt_CharButton"] = "Kattints a karakterekre vonatkozó műveleteket tartalmazó ablak megjelenítéséhez.", ["tt_TeleButton"] = "Kattints a teleport műveleteket tartalmazó ablak megjelenítéséhez.", ["tt_TicketButton"] = "Kattints a ticketek listázásához.", ["tt_MiscButton"] = "Kattints az egyéb műveletek megjelenítéséhez.", ["tt_ServerButton"] = "Kattins a szerverinformációk és a szerverrel kapcsolatos műveletek megjelenítéséhez.", ["tt_LogButton"] = "Kattints ide a MangAdminnal eddig végrehajtott parancsok naplójához.", ["tt_LanguageButton"] = "Kattints ide a nyelv megváltoztatásához és a MangAdmin újratöltéséhez.", ["tt_GMOnButton"] = "GM-mód bekapcsolása.", ["tt_GMOffButton"] = "GM-mód kikapcsolása.", ["tt_FlyOnButton"] = "Repülés bekapcsolása a kijelölt karakteren.", ["tt_FlyOffButton"] = "Repülés kikapcsolása a kijelölt karakteren.", ["tt_HoverOnButton"] = "Lebegés bekapcsolása.", ["tt_HoverOffButton"] = "Lebegés kikapcsolása.", ["tt_WhispOnButton"] = "Whisperek fogadása más playerektöl.", ["tt_WhispOffButton"] = "Whisperek tiltása más playerektöl", ["tt_InvisOnButton"] = "Láthatatlanság bekapcsolása.", ["tt_InvisOffButton"] = "Láthatatlanság kikapcsolása.", ["tt_TaxiOnButton"] = "Kiválasztott player minden taxi-útvonalának mutatása. Ez a cheat logoutnál kikapcsolódik.", ["tt_TaxiOffButton"] = "Taxi-cheat kikapcsolása és az ismert taxi-útvonalának visszaállítása.", ["tt_BankButton"] = "Bankod mutatása.", ["tt_ScreenButton"] = "Képernyömentés", ["tt_SpeedSlider"] = "Kijelölt karakter sebességének változtatása.", ["tt_ScaleSlider"] = "Kijelölt karakter méretének változtatása.", ["tt_ItemButton"] = "Item keresö ablak megnyitása.", ["tt_ItemSetButton"] = "ItemSet keresö ablak megnyitása.", ["tt_SpellButton"] = "Spell keresö ablak megnyitása.", ["tt_QuestButton"] = "Quest keresö ablak megnyitása.", ["tt_CreatureButton"] = "Creature keresö ablak megnyitása.", ["tt_ObjectButton"] = "Object keresö ablak megnyitása.", ["tt_SearchDefault"] = "Adj meg egy kulcsszót a kereséshez.", ["tt_AnnounceButton"] = "Rendszerüzenet küldése.", ["tt_KickButton"] = "Kiválasztott player kickelése a szerverröl.", ["tt_ShutdownButton"] = "Szerver leállítása megadott másodperc múlva. Ha nincs megadva érték, a szerver azonnal leáll!", ["ma_ItemButton"] = "Item keresés", ["ma_ItemSetButton"] = "ItemSet keresés", ["ma_SpellButton"] = "Spell keresés", ["ma_QuestButton"] = "Quest keresés", ["ma_CreatureButton"] = "Creature keresés", ["ma_ObjectButton"] = "Object keresés", ["ma_TeleSearchButton"] = "Teleport-Search", ["ma_LanguageButton"] = "Nyelv választás", ["ma_GMOnButton"] = "GM-mód be", ["ma_FlyOnButton"] = "Repülés be", ["ma_HoverOnButton"] = "Lebegés be", ["ma_WhisperOnButton"] = "Whisper be", ["ma_InvisOnButton"] = "Láthatatlanság be", ["ma_TaxiOnButton"] = "Taxicheat be", ["ma_ScreenshotButton"] = "Screenshot", ["ma_BankButton"] = "Bank", ["ma_OffButton"] = "Ki", ["ma_LearnAllButton"] = "Minden spell", ["ma_LearnCraftsButton"] = "Minden foglalkozás és recept", ["ma_LearnGMButton"] = "Alap GM spellek", ["ma_LearnLangButton"] = "Összes nyelv", ["ma_LearnClassButton"] = "Összes kaszt spell", ["ma_SearchButton"] = "Keresés...", ["ma_ResetButton"] = "Reset", ["ma_KickButton"] = "Kick", ["ma_KillButton"] = "Kill", ["ma_DismountButton"] = "Dismount", ["ma_ReviveButton"] = "Élesztés", ["ma_SaveButton"] = "Mentés", ["ma_AnnounceButton"] = "Rendszerüzenet", ["ma_ShutdownButton"] = "Leállítás!", ["ma_ItemVar1Button"] = "Másodperc", ["ma_ObjectVar1Button"] = "Loot Template", ["ma_ObjectVar2Button"] = "Spawn Time", ["ma_LoadTicketsButton"] = "Ticketek mutatása", ["ma_GetCharTicketButton"] = "Player ide", ["ma_GoCharTicketButton"] = "Tele playerhez", ["ma_AnswerButton"] = "Válasz", ["ma_DeleteButton"] = "Törlés", ["ma_TicketCount"] = "|cFF00FF00Ticketek:|r ", ["ma_TicketsNoNew"] = "Nincs új ticket.", ["ma_TicketsNewNumber"] = "|cffeda55f%s|r új ticketed van!", ["ma_TicketsGoLast"] = "Teleport az utolsó ticket létrehozójához (%s).", ["ma_TicketsGetLast"] = "%s idehozása.", ["ma_IconHint"] = "|cffeda55fKattints|r a MangAdmin megnyitásához. |cffeda55fShift-Kattints|r az UI újratöltéséhez. |cffeda55fAlt-Kattints|r a ticket számláló törléséhez.", ["ma_Reload"] = "Újratöltés", ["ma_LoadMore"] = "Több betöltése...", ["ma_MailRecipient"] = "Címzett", ["ma_Mail"] = "Levél küldése", ["ma_Send"] = "Küldés", ["ma_MailSubject"] = "Tárgy", ["ma_MailYourMsg"] = "Üzeneted", ["ma_Online"] = "Online", ["ma_Offline"] = "Offline", ["ma_TicketsInfoPlayer"] = "|cFF00FF00Player:|r ", ["ma_TicketsInfoStatus"] = "|cFF00FF00Állapot:|r ", ["ma_TicketsInfoAccount"] = "|cFF00FF00Account:|r ", ["ma_TicketsInfoAccLevel"] = "|cFF00FF00Account szint:|r ", ["ma_TicketsInfoLastIP"] = "|cFF00FF00Utolsó IP:|r ", ["ma_TicketsInfoPlayedTime"] = "|cFF00FF00Játszott idö:|r ", ["ma_TicketsInfoLevel"] = "|cFF00FF00Szint:|r ", ["ma_TicketsInfoMoney"] = "|cFF00FF00Pénz:|r ", ["ma_TicketsInfoLatency"] = "|cFF00FF00Latency:|r ", ["ma_TicketsNoInfo"] = "Nem érhetö el ticket infó...", ["ma_TicketsNotLoaded"] = "Nincs betöltve ticket...", ["ma_TicketsNoTickets"] = "Nincs ticket!", ["ma_TicketTicketLoaded"] = "|cFF00FF00Betöltött Ticket:|r %s\n\nPlayer Információ\n\n", ["ma_FavAdd"] = "Add selected", ["ma_FavRemove"] = "Remove selected", ["ma_SelectAllButton"] = "Select all", ["ma_DeselectAllButton"] = "Deselect all", ["ma_MailBytesLeft"] = "Bytes left: ", ["ma_WeatherFine"] = "Fine", ["ma_WeatherFog"] = "Fog", ["ma_WeatherRain"] = "Rain", ["ma_WeatherSnow"] = "Snow", ["ma_WeatherSand"] = "Sand", ["ma_LevelUp"] = "Level up", ["ma_LevelDown"] = "Level down", ["ma_Money"] = "Money", ["ma_Energy"] = "Energy", ["ma_Rage"] = "Rage", ["ma_Mana"] = "Mana", ["ma_Healthpoints"] = "Healthpoints", ["ma_Talents"] = "Talents", ["ma_Stats"] = "Stats", ["ma_Spells"] = "Spells", ["ma_Honor"] = "Honor", ["ma_Level"] = "Level", ["ma_AllLang"] = "All Languages", -- languages ["Common"] = "Common", ["Orcish"] = "Orcish", ["Taurahe"] = "Taurahe", ["Darnassian"] = "Darnassian", ["Dwarvish"] = "Dwarvish", ["Thalassian"] = "Thalassian", ["Demonic"] = "Demonic", ["Draconic"] = "Draconic", ["Titan"] = "Titan", ["Kalimag"] = "Kalimag", ["Gnomish"] = "Gnomish", ["Troll"] = "Troll", ["Gutterspeak"] = "Gutterspeak", ["Draenei"] = "Draenei", ["ma_NoFavorites"] = "There are currently no saved favorites!", ["ma_NoZones"] = "No zones!", ["ma_NoSubZones"] = "No subzones!", ["favoriteResults"] = "|cFF00FF00Favorites:|r ", ["Zone"] = "|cFF00FF00Zone:|r ", ["tt_DisplayAccountLevel"] = "Display your account level", ["tt_TicketOn"] = "Announce new tickets.", ["tt_TicketOff"] = "Don't announce new tickets.", ["info_revision"] = "|cFF00FF00MaNGOS Revision:|r ", ["info_platform"] = "|cFF00FF00Server Platform:|r ", ["info_online"] = "|cFF00FF00Players Online:|r ", ["info_maxonline"] = "|cFF00FF00Maximum Online:|r ", ["info_uptime"] = "|cFF00FF00Uptime:|r ", ["cmd_toggle"] = "Toggle the main window", ["cmd_transparency"] = "Toggle the basic transparency (0.5 or 1.0)", ["cmd_tooltip"] = "Toggle wether the button tooltips are shown or not", ["tt_SkillButton"] = "Toggle a popup with the function to search for skills and manage your favorites.", ["tt_RotateLeft"] = "Rotate left.", ["tt_RotateRight"] = "Rotate right.", ["tt_FrmTrSlider"] = "Change frame transparency.", ["tt_BtnTrSlider"] = "Change button transparency.", ["ma_SkillButton"] = "Skill-Search", ["ma_SkillVar1Button"] = "Skill", ["ma_SkillVar2Button"] = "Max Skill", ["tt_DisplayAccountLvl"] = "Display your account level.", --linkifier ["lfer_Spawn"] = "Spawn", ["lfer_List"] = "List", ["lfer_Reload"] = "Reload", ["lfer_Goto"] = "Goto", ["lfer_Move"] = "Move", ["lfer_Turn"] = "Turn", ["lfer_Delete"] = "Delete", ["lfer_Teleport"] = "Teleport", ["lfer_Morph"] = "Morph", ["lfer_Add"] = "Add", ["lfer_Remove"] = "Remove", ["lfer_Learn"] = "Learn", ["lfer_Unlearn"] = "Unlearn", ["lfer_Error"] = "Error Search String Matched but an error occured or unable to find type" } end
gpl-3.0
cryptdb-org/mysql-proxy-0.8-hacks
lib/admin-sql.lua
6
8864
--[[ $%BEGINLICENSE%$ Copyright (c) 2008, 2012, 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%$ --]] --- -- map SQL commands to the hidden MySQL Protocol commands -- -- some protocol commands are only available through the mysqladmin tool like -- * ping -- * shutdown -- * debug -- * statistics -- -- ... while others are avaible -- * process info (SHOW PROCESS LIST) -- * process kill (KILL <id>) -- -- ... and others are ignored -- * time -- -- that way we can test MySQL Servers more easily with "mysqltest" -- --- -- recognize special SQL commands and turn them into COM_* sequences -- function read_query(packet) if packet:byte() ~= proxy.COM_QUERY then return end if packet:sub(2) == "COMMIT SUICIDE" then proxy.queries:append(proxy.COM_SHUTDOWN, string.char(proxy.COM_SHUTDOWN), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "PING" then proxy.queries:append(proxy.COM_PING, string.char(proxy.COM_PING), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "STATISTICS" then proxy.queries:append(proxy.COM_STATISTICS, string.char(proxy.COM_STATISTICS), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "PROCINFO" then proxy.queries:append(proxy.COM_PROCESS_INFO, string.char(proxy.COM_PROCESS_INFO), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "TIME" then proxy.queries:append(proxy.COM_TIME, string.char(proxy.COM_TIME), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "DEBUG" then proxy.queries:append(proxy.COM_DEBUG, string.char(proxy.COM_DEBUG), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "PROCKILL" then proxy.queries:append(proxy.COM_PROCESS_KILL, string.char(proxy.COM_PROCESS_KILL), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "SETOPT" then proxy.queries:append(proxy.COM_SET_OPTION, string.char(proxy.COM_SET_OPTION), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "BINLOGDUMP" then proxy.queries:append(proxy.COM_BINLOG_DUMP, string.char(proxy.COM_BINLOG_DUMP), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "BINLOGDUMP1" then proxy.queries:append(proxy.COM_BINLOG_DUMP, string.char(proxy.COM_BINLOG_DUMP) .. "\004\000\000\000" .. "\000\000" .. "\002\000\000\000" .. "\000" .. "" , { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "REGSLAVE" then proxy.queries:append(proxy.COM_REGISTER_SLAVE, string.char(proxy.COM_REGISTER_SLAVE), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "REGSLAVE1" then proxy.queries:append(proxy.COM_REGISTER_SLAVE, string.char(proxy.COM_REGISTER_SLAVE) .. "\001\000\000\000" .. -- server-id "\000" .. -- report-host "\000" .. -- report-user "\000" .. -- report-password ? "\001\000" .. -- our port "\000\000\000\000" .. -- recovery rank "\001\000\000\000" .. -- master id ... what ever that is "" , { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "PREP" then proxy.queries:append(proxy.COM_STMT_PREPARE, string.char(proxy.COM_STMT_PREPARE), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "PREP1" then proxy.queries:append(proxy.COM_STMT_PREPARE, string.char(proxy.COM_STMT_PREPARE) .. "SELECT ?", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "EXEC" then proxy.queries:append(proxy.COM_STMT_EXECUTE, string.char(proxy.COM_STMT_EXECUTE), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "EXEC1" then proxy.queries:append(proxy.COM_STMT_EXECUTE, string.char(proxy.COM_STMT_EXECUTE) .. "\001\000\000\000" .. -- stmt-id "\000" .. -- flags "\001\000\000\000" .. -- iteration count "\000" .. -- null-bits "\001" .. -- new-parameters "\000\254" .. "\004" .. "1234" .. "", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "DEAL" then proxy.queries:append(proxy.COM_STMT_CLOSE, string.char(proxy.COM_STMT_CLOSE), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "DEAL1" then proxy.queries:append(proxy.COM_STMT_CLOSE, string.char(proxy.COM_STMT_CLOSE) .. "\001\000\000\000", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "RESET" then proxy.queries:append(proxy.COM_STMT_RESET, string.char(proxy.COM_STMT_RESET), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "RESET1" then proxy.queries:append(proxy.COM_STMT_RESET, string.char(proxy.COM_STMT_RESET) .. "\001\000\000\000", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "FETCH" then proxy.queries:append(proxy.COM_STMT_FETCH, string.char(proxy.COM_STMT_FETCH), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "FETCH1" then proxy.queries:append(proxy.COM_STMT_FETCH, string.char(proxy.COM_STMT_FETCH) .. "\001\000\000\000" .. "\128\000\000\000", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "FLIST" then proxy.queries:append(proxy.COM_FIELD_LIST, string.char(proxy.COM_FIELD_LIST), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "FLIST1" then proxy.queries:append(proxy.COM_FIELD_LIST, string.char(proxy.COM_FIELD_LIST) .. "t1\000id\000\000\000", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "TDUMP" then proxy.queries:append(proxy.COM_TABLE_DUMP, string.char(proxy.COM_TABLE_DUMP), { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "TDUMP1" then proxy.queries:append(proxy.COM_TABLE_DUMP, string.char(proxy.COM_TABLE_DUMP) .. "\004test\002t1", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY elseif packet:sub(2) == "TDUMP2" then proxy.queries:append(proxy.COM_TABLE_DUMP, string.char(proxy.COM_TABLE_DUMP) .. "\004test\002t2", { resultset_is_needed = true }) return proxy.PROXY_SEND_QUERY end end --- -- adjust the response to match the needs of COM_QUERY -- where neccesary -- -- * some commands return EOF (COM_SHUTDOWN), -- * some are plain-text (COM_STATISTICS) -- -- in the end the client sent us a COM_QUERY and we have to hide -- all those specifics function read_query_result(inj) if inj.id == proxy.COM_SHUTDOWN or inj.id == proxy.COM_SET_OPTION or inj.id == proxy.COM_BINLOG_DUMP or inj.id == proxy.COM_STMT_PREPARE or inj.id == proxy.COM_STMT_FETCH or inj.id == proxy.COM_FIELD_LIST or inj.id == proxy.COM_TABLE_DUMP or inj.id == proxy.COM_DEBUG then -- translate the EOF packet from the COM_SHUTDOWN into a OK packet -- to match the needs of the COM_QUERY we got if inj.resultset.raw:byte() ~= 255 then proxy.response = { type = proxy.MYSQLD_PACKET_OK, } return proxy.PROXY_SEND_RESULT end elseif inj.id == proxy.COM_PING or inj.id == proxy.COM_TIME or inj.id == proxy.COM_PROCESS_KILL or inj.id == proxy.COM_REGISTER_SLAVE or inj.id == proxy.COM_STMT_EXECUTE or inj.id == proxy.COM_STMT_RESET or inj.id == proxy.COM_PROCESS_INFO then -- no change needed elseif inj.id == proxy.COM_STATISTICS then -- the response a human readable plain-text -- -- just turn it into a proper result-set proxy.response = { type = proxy.MYSQLD_PACKET_OK, resultset = { fields = { { name = "statisitics" } }, rows = { { inj.resultset.raw } } } } return proxy.PROXY_SEND_RESULT else -- we don't know them yet, just return ERR to the client to -- match the needs of COM_QUERY print(("got: %q"):format(inj.resultset.raw)) proxy.response = { type = proxy.MYSQLD_PACKET_ERR, } return proxy.PROXY_SEND_RESULT end end
gpl-2.0
ffxiphoenix/darkstar
scripts/globals/items/pogaca.lua
35
1247
----------------------------------------- -- ID: 5637 -- Item: pogaca -- Food Effect: 5Min, All Races ----------------------------------------- -- HP Recovered While Healing 4 -- MP Recovered While Healing 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5637); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HPHEAL, 4); target:addMod(MOD_MPHEAL, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HPHEAL, 4); target:delMod(MOD_MPHEAL, 4); end;
gpl-3.0
jhegg/eso-crafting-material-level-display
lib/LibStub/LibStub.lua
9
1535
-- LibStub is a simple versioning stub meant for use in Libraries. http://www.wowace.com/wiki/LibStub for more info -- LibStub is hereby placed in the Public Domain Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel, joshborke -- LibStub developed for World of Warcraft by above members of the WowAce community. -- Ported to Elder Scrolls Online by Seerah local LIBSTUB_MAJOR, LIBSTUB_MINOR = "LibStub", 1 -- NEVER MAKE THIS AN SVN REVISION! IT NEEDS TO BE USABLE IN ALL REPOS! local LibStub = _G[LIBSTUB_MAJOR] local strformat = string.format if not LibStub or LibStub.minor < LIBSTUB_MINOR then LibStub = LibStub or {libs = {}, minors = {} } _G[LIBSTUB_MAJOR] = LibStub LibStub.minor = LIBSTUB_MINOR function LibStub:NewLibrary(major, minor) assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)") minor = assert(tonumber(zo_strmatch(minor, "%d+")), "Minor version must either be a number or contain a number.") local oldminor = self.minors[major] if oldminor and oldminor >= minor then return nil end self.minors[major], self.libs[major] = minor, self.libs[major] or {} return self.libs[major], oldminor end function LibStub:GetLibrary(major, silent) if not self.libs[major] and not silent then error(("Cannot find a library instance of %q."):strformat(tostring(major)), 2) end return self.libs[major], self.minors[major] end function LibStub:IterateLibraries() return pairs(self.libs) end setmetatable(LibStub, { __call = LibStub.GetLibrary }) end
mit
ffxiphoenix/darkstar
scripts/zones/Outer_Horutoto_Ruins/npcs/_5ef.lua
17
3319
----------------------------------- -- Area: Inner Horutoto Ruins -- NPC: Ancient Magical Gizmo #2 (F out of E, F, G, H, I, J) -- Involved In Mission: The Heart of the Matter ----------------------------------- package.loaded["scripts/zones/Outer_Horutoto_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Outer_Horutoto_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Check if we are on Windurst Mission 1-2 if (player:getCurrentMission(WINDURST) == THE_HEART_OF_THE_MATTER) then MissionStatus = player:getVar("MissionStatus"); if (MissionStatus == 2) then -- Entered a Dark Orb if (player:getVar("MissionStatus_orb2") == 1) then player:startEvent(0x002f); else player:messageSpecial(ORB_ALREADY_PLACED); end elseif (MissionStatus == 4) then -- Took out a Glowing Orb if (player:getVar("MissionStatus_orb2") == 2) then player:startEvent(0x002f); else player:messageSpecial(G_ORB_ALREADY_GOTTEN); end else player:messageSpecial(DARK_MANA_ORB_RECHARGER); end else player:messageSpecial(DARK_MANA_ORB_RECHARGER); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x002f) then orb_value = player:getVar("MissionStatus_orb2"); if (orb_value == 1) then player:setVar("MissionStatus_orb2",2); -- Push the text that the player has placed the orb player:messageSpecial(SECOND_DARK_ORB_IN_PLACE); --Delete the key item player:delKeyItem(SECOND_DARK_MANA_ORB); -- Check if all orbs have been placed or not if (player:getVar("MissionStatus_orb1") == 2 and player:getVar("MissionStatus_orb3") == 2 and player:getVar("MissionStatus_orb4") == 2 and player:getVar("MissionStatus_orb5") == 2 and player:getVar("MissionStatus_orb6") == 2) then player:messageSpecial(ALL_DARK_MANA_ORBS_SET); player:setVar("MissionStatus",3); end elseif (orb_value == 2) then player:setVar("MissionStatus_orb2",3); -- Time to get the glowing orb out player:addKeyItem(SECOND_GLOWING_MANA_ORB); player:messageSpecial(KEYITEM_OBTAINED,SECOND_GLOWING_MANA_ORB); -- Check if all orbs have been placed or not if (player:getVar("MissionStatus_orb1") == 3 and player:getVar("MissionStatus_orb3") == 3 and player:getVar("MissionStatus_orb4") == 3 and player:getVar("MissionStatus_orb5") == 3 and player:getVar("MissionStatus_orb6") == 3) then player:messageSpecial(RETRIEVED_ALL_G_ORBS); player:setVar("MissionStatus",5); end end end end;
gpl-3.0
farrajota/human_pose_estimation_torch
models/test/hg-generic-ensemblev4.lua
1
1070
paths.dofile('../layers/Residual.lua') local function lin(numIn,numOut,inp) -- Apply 1x1 convolution, stride 1, no padding local dropout = nn.SpatialDropout(0.2)(inp) local bn_relu = nn.ReLU(true)(nn.SpatialBatchNormalization(numIn)(dropout)) return nn.SpatialConvolution(numIn,numOut,1,1,1,1,0,0)(bn_relu) end local function createModel() if not nn.NoBackprop then paths.dofile('modules/NoBackprop.lua') end print('Load model: ' .. paths.concat(opt.ensemble, 'final_model.t7')) local trained_model = torch.load(paths.concat(opt.ensemble, 'final_model.t7')) trained_model:evaluate() -- craft network local inp = nn.Identity()() local hg_net = nn.NoBackprop(trained_model)(inp) -- disable backprop local concat_outputs = nn.JoinTable(2)(hg_net) local ll1 = lin(outputDim[1][1]*8, 512, concat_outputs) local out = lin(512, outputDim[1][1], ll1) opt.nOutputs = 1 -- Final model local model = nn.gModule({inp}, {out}) return model end ------------------------- return createModel
mit
ffxiphoenix/darkstar
scripts/globals/items/slice_of_grilled_hare.lua
35
1397
----------------------------------------- -- ID: 4371 -- Item: slice_of_grilled_hare -- Food Effect: 180Min, All Races ----------------------------------------- -- Strength 2 -- Intelligence -1 -- Attack % 30 -- Attack Cap 15 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4371); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 2); target:addMod(MOD_INT, -1); target:addMod(MOD_FOOD_ATTP, 30); target:addMod(MOD_FOOD_ATT_CAP, 15); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 2); target:delMod(MOD_INT, -1); target:delMod(MOD_FOOD_ATTP, 30); target:delMod(MOD_FOOD_ATT_CAP, 15); end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Port_Bastok/npcs/_6k9.lua
34
1073
----------------------------------- -- Area: Port Bastok -- NPC: Door: Arrivals Entrance -- @pos -80 1 -26 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x008C); return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
mcseemka/vlc
share/lua/playlist/pinkbike.lua
97
2080
--[[ $Id$ Copyright © 2009 the VideoLAN team Authors: Konstantin Pavlov (thresh@videolan.org) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "pinkbike.com/video/%d+" ) end -- Parse function. function parse() p = {} if string.match ( vlc.path, "pinkbike.com/video/%d+" ) then while true do line = vlc.readline() if not line then break end -- Try to find video id if string.match( line, "video_src.+swf.id=(.*)\"") then _,_,videoid = string.find( line, "video_src.+swf.id=(.*)\"") catalog = math.floor( tonumber( videoid ) / 10000 ) end -- Try to find the video's title if string.match( line, "<title>(.*)</title>" ) then _,_,name = string.find (line, "<title>(.*)</title>") end -- Try to find server which has our video if string.match( line, "<link rel=\"videothumbnail\" href=\"http://(.*)/vt/svt-") then _,_,server = string.find (line, '<link rel="videothumbnail" href="http://(.*)/vt/svt-' ) end if string.match( line, "<link rel=\"videothumbnail\" href=\"(.*)\" type=\"image/jpeg\"") then _,_,arturl = string.find (line, '<link rel="videothumbnail" href="(.*)" type="image/jpeg"') end end end table.insert( p, { path = "http://" .. server .. "/vf/" .. catalog .. "/pbvid-" .. videoid .. ".flv"; name = name; arturl = arturl } ) return p end
gpl-2.0
bgarrels/vlc-2.1
share/lua/meta/art/00_musicbrainz.lua
11
3106
--[[ Gets an artwork from the Cover Art Archive or Amazon $Id$ Copyright © 2007-2010 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] function try_query(mbid) local relquery = "http://mb.videolan.org/ws/2/release/" .. mbid local s = vlc.stream( relquery ) if not s then return nil end local page = s:read( 65653 ) found, _ = string.find( page, "<artwork>true</artwork>" ) if found then return "http://coverartarchive.org/release/"..mbid.."/front-500" end -- FIXME: multiple results may be available _, _, asin = string.find( page, "<asin>(%w+)</asin>" ) if asin then return "http://images.amazon.com/images/P/"..asin..".01._SCLZZZZZZZ_.jpg" end vlc.msg.dbg("Neither coverartarchive.org nor amazon have cover art for this release") return nil end -- Return the mbid for the first release returned by the MusicBrainz search server for query function get_releaseid(query) local s = vlc.stream( query ) if not s then return nil end local page = s:read( 65653 ) -- FIXME: multiple results may be available and the first one is not -- guaranteed to have asin, so if it doesnt, we wouldnt get any art _, _, releaseid = string.find( page, "<release id=\"([%x%-]-)\"" ) if releaseid then return releaseid end return nil end -- Return the artwork function fetch_art() local meta = vlc.item:metas() if meta["Listing Type"] == "radio" or meta["Listing Type"] == "tv" then return nil end local releaseid = nil for _, k in ipairs({"MUSICBRAINZ_ALBUMID", "MusicBrainz Album Id"}) do if meta[k] then releaseid = meta[k] end end if not releaseid and meta["artist"] and meta["album"] then query = "artist:\"" .. meta["artist"] .. "\" AND release:\"" .. meta["album"] .. "\"" relquery = "http://mb.videolan.org/ws/2/release/?query=" .. vlc.strings.encode_uri_component( query ) releaseid = get_releaseid( relquery ) end if not releaseid and meta["artist"] and meta["title"] then query = "artist:\"" .. meta["artist"] .. "\" AND recording:\"" .. meta["title"] .. "\"" recquery = "http://mb.videolan.org/ws/2/recording/?query=" .. vlc.strings.encode_uri_component( query ) releaseid = get_releaseid( recquery ) end if releaseid then return try_query( releaseid ) else return nil end end
gpl-2.0
kuoruan/packages
utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/cpu.lua
74
1429
-- stat/cpu collector local function scrape() local stat = get_contents("/proc/stat") -- system boot time, seconds since epoch metric("node_boot_time_seconds", "gauge", nil, string.match(stat, "btime ([0-9]+)")) -- context switches since boot (all CPUs) metric("node_context_switches_total", "counter", nil, string.match(stat, "ctxt ([0-9]+)")) -- cpu times, per CPU, per mode local cpu_mode = {"user", "nice", "system", "idle", "iowait", "irq", "softirq", "steal", "guest", "guest_nice"} local i = 0 local cpu_metric = metric("node_cpu_seconds_total", "counter") while true do local cpu = {string.match(stat, "cpu"..i.." (%d+) (%d+) (%d+) (%d+) (%d+) (%d+) (%d+) (%d+) (%d+) (%d+)")} if #cpu ~= 10 then break end for ii, mode in ipairs(cpu_mode) do cpu_metric({cpu="cpu"..i, mode=mode}, cpu[ii] / 100) end i = i + 1 end -- interrupts served metric("node_intr_total", "counter", nil, string.match(stat, "intr ([0-9]+)")) -- processes forked metric("node_forks_total", "counter", nil, string.match(stat, "processes ([0-9]+)")) -- processes running metric("node_procs_running_total", "gauge", nil, string.match(stat, "procs_running ([0-9]+)")) -- processes blocked for I/O metric("node_procs_blocked_total", "gauge", nil, string.match(stat, "procs_blocked ([0-9]+)")) end return { scrape = scrape }
gpl-2.0
WUTiAM/uLua2
Assets/LuaScripts/pb/__common_enums_pb.lua
1
3977
-- Generated By protoc-gen-lua Do not Edit local protobuf = require( "depends/protobuf/protobuf" ) --module('__common_enums_pb') local __common_enums_pb = {} _ERRORTYPE = protobuf.EnumDescriptor(); _ERRORTYPE_ERROR_GOODS_ITEM_NOT_ENOUGH_ENUM = protobuf.EnumValueDescriptor(); _ERRORTYPE_ERROR_GOODS_ITEM_AMOUNT_OVERFLOW_ENUM = protobuf.EnumValueDescriptor(); _SYSTEMID = protobuf.EnumDescriptor(); _SYSTEMID_XXX_SYSTEM_ENUM = protobuf.EnumValueDescriptor(); _ASSETTYPE = protobuf.EnumDescriptor(); _ASSETTYPE_XXX_XXXX_ENUM = protobuf.EnumValueDescriptor(); _LOGINRESULT = protobuf.EnumDescriptor(); _LOGINRESULT_LOGIN_SUCCESS_ENUM = protobuf.EnumValueDescriptor(); _LOGINRESULT_LOGIN_CHARACTER_NOT_EXIST_ENUM = protobuf.EnumValueDescriptor(); _LOGINRESULT_LOGIN_SESSION_EXPIRED_ENUM = protobuf.EnumValueDescriptor(); _CREATEPLAYERRESULT = protobuf.EnumDescriptor(); _CREATEPLAYERRESULT_CREATE_PLAYER_DUPLICATED_NAME_ENUM = protobuf.EnumValueDescriptor(); _CREATEPLAYERRESULT_CREATE_PLAYER_SENSITIVE_WORD_ENUM = protobuf.EnumValueDescriptor(); _ERRORTYPE_ERROR_GOODS_ITEM_NOT_ENOUGH_ENUM.name = "ERROR_GOODS_ITEM_NOT_ENOUGH" _ERRORTYPE_ERROR_GOODS_ITEM_NOT_ENOUGH_ENUM.index = 0 _ERRORTYPE_ERROR_GOODS_ITEM_NOT_ENOUGH_ENUM.number = 1 _ERRORTYPE_ERROR_GOODS_ITEM_AMOUNT_OVERFLOW_ENUM.name = "ERROR_GOODS_ITEM_AMOUNT_OVERFLOW" _ERRORTYPE_ERROR_GOODS_ITEM_AMOUNT_OVERFLOW_ENUM.index = 1 _ERRORTYPE_ERROR_GOODS_ITEM_AMOUNT_OVERFLOW_ENUM.number = 2 _ERRORTYPE.name = "_ErrorType" _ERRORTYPE.full_name = ".my_project._ErrorType" _ERRORTYPE.values = {_ERRORTYPE_ERROR_GOODS_ITEM_NOT_ENOUGH_ENUM,_ERRORTYPE_ERROR_GOODS_ITEM_AMOUNT_OVERFLOW_ENUM} _SYSTEMID_XXX_SYSTEM_ENUM.name = "XXX_SYSTEM" _SYSTEMID_XXX_SYSTEM_ENUM.index = 0 _SYSTEMID_XXX_SYSTEM_ENUM.number = 1 _SYSTEMID.name = "_SystemId" _SYSTEMID.full_name = ".my_project._SystemId" _SYSTEMID.values = {_SYSTEMID_XXX_SYSTEM_ENUM} _ASSETTYPE_XXX_XXXX_ENUM.name = "XXX_XXXX" _ASSETTYPE_XXX_XXXX_ENUM.index = 0 _ASSETTYPE_XXX_XXXX_ENUM.number = 1 _ASSETTYPE.name = "_AssetType" _ASSETTYPE.full_name = ".my_project._AssetType" _ASSETTYPE.values = {_ASSETTYPE_XXX_XXXX_ENUM} _LOGINRESULT_LOGIN_SUCCESS_ENUM.name = "LOGIN_SUCCESS" _LOGINRESULT_LOGIN_SUCCESS_ENUM.index = 0 _LOGINRESULT_LOGIN_SUCCESS_ENUM.number = 0 _LOGINRESULT_LOGIN_CHARACTER_NOT_EXIST_ENUM.name = "LOGIN_CHARACTER_NOT_EXIST" _LOGINRESULT_LOGIN_CHARACTER_NOT_EXIST_ENUM.index = 1 _LOGINRESULT_LOGIN_CHARACTER_NOT_EXIST_ENUM.number = 1 _LOGINRESULT_LOGIN_SESSION_EXPIRED_ENUM.name = "LOGIN_SESSION_EXPIRED" _LOGINRESULT_LOGIN_SESSION_EXPIRED_ENUM.index = 2 _LOGINRESULT_LOGIN_SESSION_EXPIRED_ENUM.number = 2 _LOGINRESULT.name = "_LoginResult" _LOGINRESULT.full_name = ".my_project._LoginResult" _LOGINRESULT.values = {_LOGINRESULT_LOGIN_SUCCESS_ENUM,_LOGINRESULT_LOGIN_CHARACTER_NOT_EXIST_ENUM,_LOGINRESULT_LOGIN_SESSION_EXPIRED_ENUM} _CREATEPLAYERRESULT_CREATE_PLAYER_DUPLICATED_NAME_ENUM.name = "CREATE_PLAYER_DUPLICATED_NAME" _CREATEPLAYERRESULT_CREATE_PLAYER_DUPLICATED_NAME_ENUM.index = 0 _CREATEPLAYERRESULT_CREATE_PLAYER_DUPLICATED_NAME_ENUM.number = 1 _CREATEPLAYERRESULT_CREATE_PLAYER_SENSITIVE_WORD_ENUM.name = "CREATE_PLAYER_SENSITIVE_WORD" _CREATEPLAYERRESULT_CREATE_PLAYER_SENSITIVE_WORD_ENUM.index = 1 _CREATEPLAYERRESULT_CREATE_PLAYER_SENSITIVE_WORD_ENUM.number = 2 _CREATEPLAYERRESULT.name = "_CreatePlayerResult" _CREATEPLAYERRESULT.full_name = ".my_project._CreatePlayerResult" _CREATEPLAYERRESULT.values = {_CREATEPLAYERRESULT_CREATE_PLAYER_DUPLICATED_NAME_ENUM,_CREATEPLAYERRESULT_CREATE_PLAYER_SENSITIVE_WORD_ENUM} __common_enums_pb.CREATE_PLAYER_DUPLICATED_NAME = 1 __common_enums_pb.CREATE_PLAYER_SENSITIVE_WORD = 2 __common_enums_pb.ERROR_GOODS_ITEM_AMOUNT_OVERFLOW = 2 __common_enums_pb.ERROR_GOODS_ITEM_NOT_ENOUGH = 1 __common_enums_pb.LOGIN_CHARACTER_NOT_EXIST = 1 __common_enums_pb.LOGIN_SESSION_EXPIRED = 2 __common_enums_pb.LOGIN_SUCCESS = 0 __common_enums_pb.XXX_SYSTEM = 1 __common_enums_pb.XXX_XXXX = 1 return __common_enums_pb
mit
ffxiphoenix/darkstar
scripts/commands/exec.lua
54
1121
--------------------------------------------------------------------------------------------------- -- func: exec -- desc: Allows you to execute a Lua string directly from chat. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 4, parameters = "s" }; function onTrigger(player, str) -- Ensure a command was given.. if (str == nil or string.len(str) == 0) then player:PrintToPlayer("You must enter a string to execute."); return; end -- For safety measures we will nuke the os table.. local old_os = os; os = nil; -- Ensure the command compiles / is valid.. local scriptObj, err = loadstring(str); if (scriptObj == nil) then player:PrintToPlayer("Failed to load the given string."); player:PrintToPlayer(err); os = old_os; return; end -- Execute the string.. local status, err = pcall(scriptObj); if (status == false) then player:PrintToPlayer(err); end -- Restore the os table.. os = old_os; end
gpl-3.0
Phrohdoh/OpenRA
mods/d2k/maps/harkonnen-05/harkonnen05-AI.lua
4
2450
--[[ Copyright 2007-2020 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] AttackGroupSize = { easy = 6, normal = 8, hard = 10 } AttackDelays = { easy = { DateTime.Seconds(4), DateTime.Seconds(7) }, normal = { DateTime.Seconds(2), DateTime.Seconds(5) }, hard = { DateTime.Seconds(1), DateTime.Seconds(3) } } OrdosInfantryTypes = { "light_inf", "light_inf", "light_inf", "trooper", "trooper" } OrdosVehicleTypes = { "raider", "raider", "quad" } OrdosTankType = { "combat_tank_o" } ActivateAI = function() IdlingUnits[ordos_main] = Reinforcements.Reinforce(ordos_main, InitialOrdosReinforcements[1], InitialOrdosPaths[1]), Reinforcements.Reinforce(ordos_main, InitialOrdosReinforcements[2], InitialOrdosPaths[2]) IdlingUnits[ordos_small] = Reinforcements.Reinforce(ordos_small, InitialOrdosReinforcements[1], InitialOrdosPaths[3]) IdlingUnits[corrino] = { CSaraukar1, CSaraukar2, CSaraukar3, CSaraukar4, CSaraukar5 } DefendAndRepairBase(ordos_main, OrdosMainBase, 0.75, AttackGroupSize[Difficulty]) DefendAndRepairBase(ordos_small, OrdosSmallBase, 0.75, AttackGroupSize[Difficulty]) DefendAndRepairBase(corrino, CorrinoBase, 0.75, AttackGroupSize[Difficulty]) local delay = function() return Utils.RandomInteger(AttackDelays[Difficulty][1], AttackDelays[Difficulty][2] + 1) end local infantryToBuild = function() return { Utils.Random(OrdosInfantryTypes) } end local vehilcesToBuild = function() return { Utils.Random(OrdosVehicleTypes) } end local tanksToBuild = function() return OrdosTankType end local attackThresholdSize = AttackGroupSize[Difficulty] * 2.5 ProduceUnits(ordos_main, OBarracks1, delay, infantryToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(ordos_main, OLightFactory1, delay, vehilcesToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(ordos_main, OHeavyFactory, delay, tanksToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(ordos_small, OBarracks3, delay, infantryToBuild, AttackGroupSize[Difficulty], attackThresholdSize) ProduceUnits(ordos_small, OLightFactory2, delay, vehilcesToBuild, AttackGroupSize[Difficulty], attackThresholdSize) end
gpl-3.0
w1ndf4k3r/cleanflightOpenTxTelemetry
SD/SCRIPTS/UTILS/stickCommands.lua
1
2670
------- STICK COMMAND HANDLING ----------- ----------------------------------------------------------------------------------- --| |-- --|ONLY CALL processStickCommands() ONCE PER SCRIPT, IT WILL NOT WORK OTHERWISE |-- --| |-- ----------------------------------------------------------------------------------- --do not touch this, flags... THR_LO = 1 THR_HI = 2 YAW_LO = 4 YAW_HI = 8 ELE_LO = 16 ELE_HI = 32 AIL_LO = 64 AIL_HI = 128 --uncomment for mode 2 -- ELE_LO = 1 -- ELE_HI = 2 -- YAW_LO = 4 -- YAW_HI = 8 -- THR_LO = 16 -- THR_HI = 32 -- AIL_LO = 64 -- AIL_HI = 128 local commands = {} local minCommand = -1000 local maxCommand = 1000 local commandDelay = 50 local stickCmd = 0 local commandTime = 0 local executeCommand = false --do not touch this, flags... --will process stick commands, commands will only be called once each time they are detected, see warning above local function processStickCommands() local tmpCmd = 0 --get stick values local thrStick = getValue('thr') -- throttle input local eleStick = getValue('ele') -- elevator input local ailStick = getValue('ail') -- aileron input local yawStick = getValue('rud') -- rudder input -- because of lack of native bitwise operators code sucks if(thrStick > maxCommand) then tmpCmd = tmpCmd + THR_HI elseif thrStick < minCommand then tmpCmd = tmpCmd +THR_LO end if(eleStick > maxCommand) then tmpCmd = tmpCmd + ELE_HI elseif eleStick < minCommand then tmpCmd = tmpCmd + ELE_LO end if(ailStick > maxCommand) then tmpCmd = tmpCmd + AIL_HI elseif ailStick < minCommand then tmpCmd = tmpCmd + AIL_LO end if(yawStick > maxCommand) then tmpCmd = tmpCmd + YAW_HI elseif yawStick < minCommand then tmpCmd = tmpCmd + YAW_LO end -- reset time if the stick cmd change if (tmpCmd == stickCmd) then if(commandTime+50 < getTime()) then if executeCommand then return else executeCommand = true end end else commandTime = getTime() end stickCmd = tmpCmd; if not executeCommand then return end --process commands (will call the defined function in commands for k,v in pairs(commands) do if(v.cmd == stickCmd) then v.func() --calling multiple commands is prevented (only one will execute) so care for order in command spec return end end executeCommand = false return end local function init(commandsP,minCommandP,maxCommandP,commandDelayP) commands= commandsP minCommand = minCommandP maxCommand=maxCommandP commandDelay=commandDelayP end return {process=processStickCommands,init=init}
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Zeruhn_Mines/npcs/Makarim.lua
17
1514
----------------------------------- -- Area: Zeruhn Mines -- NPC: Makarim -- Involved In Mission: The Zeruhn Report -- @pos -58 8 -333 172 ----------------------------------- package.loaded["scripts/zones/Zeruhn_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Zeruhn_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(BASTOK) == THE_ZERUHN_REPORT) then if (player:hasKeyItem(ZERUHN_REPORT)) then player:messageSpecial(MAKARIM_DIALOG_I); else player:startEvent(0x0079); end else player:startEvent(0x0068); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0079) then player:addKeyItem(ZERUHN_REPORT); player:messageSpecial(KEYITEM_OBTAINED,ZERUHN_REPORT); end end;
gpl-3.0
azukiapp/busted
src/languages/zh.lua
1
1234
local s = require('say') s:set_namespace("zh") -- "Pending: test.lua @ 12 \n description s:set("output.pending", "开发中") s:set("output.failure", "失败") s:set("output.success", "成功") s:set("output.pending_plural", "开发中") s:set("output.failure_plural", "失败") s:set("output.success_plural", "成功") s:set("output.pending_zero", "开发中") s:set("output.failure_zero", "失败") s:set("output.success_zero", "成功") s:set("output.pending_single", "开发中") s:set("output.failure_single", "失败") s:set("output.success_single", "成功") s:set("output.seconds", "秒") -- definitions following are not used within the 'say' namespace return { failure_messages = { "你一共提交了[%d]个测试用例", "又出错了!", "到底哪里不对呢?", "出错了,又要加班了!", "囧,出Bug了!", "据说比尔盖兹也写了一堆Bug,别灰心!", "又出错了,休息一下吧", "Bug好多,心情好坏!" }, success_messages = { "牛X,测试通过了!", "测试通过了,感觉不错吧,兄弟!", "哥们,干得漂亮!", "终于通过了!干一杯先!", "阿弥陀佛~,菩萨显灵了!", } }
mit
ffxiphoenix/darkstar
scripts/globals/items/green_quiche.lua
35
1461
----------------------------------------- -- ID: 5170 -- Item: green_quiche -- Food Effect: 30Min, All Races ----------------------------------------- -- Magic 10 -- Agility 1 -- Vitality -1 -- Ranged ACC % 7 -- Ranged ACC Cap 15 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5170); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 10); target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -1); target:addMod(MOD_FOOD_RACCP, 7); target:addMod(MOD_FOOD_RACC_CAP, 15); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 10); target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -1); target:delMod(MOD_FOOD_RACCP, 7); target:delMod(MOD_FOOD_RACC_CAP, 15); end;
gpl-3.0
vilarion/Illarion-Content
quest/milo_deepdelver_106_runewick.lua
3
2789
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- INSERT INTO "quests" ("qst_id", "qst_script") VALUES (106, 'quest.milo_deepdelver_106_runewick'); local common = require("base.common") local M = {} local GERMAN = Player.german local ENGLISH = Player.english -- Insert the quest title here, in both languages local Title = {} Title[GERMAN] = "Milos Ochse" Title[ENGLISH] = "Milo's ox" -- Insert an extensive description of each status here, in both languages -- Make sure that the player knows exactly where to go and what to do local Description = {} Description[GERMAN] = {} Description[ENGLISH] = {} Description[GERMAN][1] = "Besorge zehn Karotten und bringe sie Milo. Du kannst sie entweder am Feld anbauen oder beim Händler kaufen." Description[ENGLISH][1] = "Obtain ten carrots and bring them back to Milo. You can plant seeds on the fields or buy them from a merchant." Description[GERMAN][2] = "Du hast Milo seine Karotten gebracht. Jetzt kann er nach Hause zurück kehren." Description[ENGLISH][2] = "You brought Milo the carrots. Now he can go home." -- Insert the position of the quest start here (probably the position of an NPC or item) local Start = {883, 634, 0} -- For each status insert a list of positions where the quest will continue, i.e. a new status can be reached there local QuestTarget = {} QuestTarget[1] = {position(883, 634, 0), position(858, 832, 0), position (939, 822, 0)} -- Feld, Händler QuestTarget[2] = {position(883, 634, 0)} -- Insert the quest status which is reached at the end of the quest local FINAL_QUEST_STATUS = 2 function M.QuestTitle(user) return common.GetNLS(user, Title[GERMAN], Title[ENGLISH]) end function M.QuestDescription(user, status) local german = Description[GERMAN][status] or "" local english = Description[ENGLISH][status] or "" return common.GetNLS(user, german, english) end function M.QuestStart() return Start end function M.QuestTargets(user, status) return QuestTarget[status] end function M.QuestFinalStatus() return FINAL_QUEST_STATUS end return M
agpl-3.0
obi-two/Unofficial_Hope
data/script/TatooineNpcTest4.lua
1
1519
-- Tatooine NPC test -- This script will not start until Zoneserver is ready. print("Tatooine NPC test"); LuaScriptEngine.WaitMSec(1000); local MM = require 'script/TatooineNpcTest2' local myPos = "SR"; local prevPos = ""; -- npcObjects to use in formation. local npcMembers = { }; local spawnPosX = -1371.0 local defaultYPos = 12 local spawnPosZ = -3726.0 -- LuaScriptEngine.WaitMSec(10000); -- Create the npc, "an elit sand trooper". local noOfLines = 1; local columnWidth = 2; local noOfNpcsInTheFormation = 2; local none = 0; table.insert(npcMembers, noOfNpcsInTheFormation); table.insert(npcMembers, noOfLines); table.insert(npcMembers, columnWidth); -- Insert center point for this formation. This is the position that everything is relative to. table.insert(npcMembers, spawnPosX); table.insert(npcMembers, defaultYPos); table.insert(npcMembers, spawnPosZ); -- Insert leader. -- local npc = MM.createAndSpawnNpc(47513075899, "", "", spawnPosX, defaultYPos, spawnPosZ); local npc = MM.createAndSpawnNpc(1, "", "", spawnPosX, defaultYPos, spawnPosZ); table.insert(npcMembers, npc); -- Insert our stormie -- local npc = MM.createAndSpawnNpc(47513075899, "", "", spawnPosX, defaultYPos, spawnPosZ); local npc = MM.createAndSpawnNpc(1, "", "", spawnPosX, defaultYPos, spawnPosZ); table.insert(npcMembers, npc); table.insert(npcMembers, none); -- print("Starting to move gang"); while (1) do local temp; temp = myPos; myPos = MM.executeRoutes(npcMembers, myPos, prevPos); prevPos = temp; end;
gpl-3.0
ffxiphoenix/darkstar
scripts/globals/mobskills/Typhoon.lua
25
1072
--------------------------------------------- -- Typhoon -- -- Description: Spins around dealing damage to targets in an area of effect. -- Type: Physical -- Utsusemi/Blink absorb: 2-4 shadows -- Range: 10' radial -- Notes: --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 4; local accmod = 1; local dmgmod = 0.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); target:delHP(dmg); if (mob:getName() == "Faust") then if (mob:getLocalVar("Typhoon") == 0) then mob:useMobAbility(283); mob:setLocalVar("Typhoon", 1); else mob:setLocalVar("Typhoon", 0); end end return dmg; end;
gpl-3.0
floodlight/ivs
oftests/lua/tables.lua
2
1986
-- Copyright 2015, Big Switch Networks, Inc. -- -- Licensed under the Eclipse Public License, Version 1.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.eclipse.org/legal/epl-v10.html -- -- 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. -- Register a couple of tables for testing with no-op add/remove ops local l2_table = hashtable.create({ "vlan", "mac_hi", "mac_lo" }, { "port" }) register_table("l2", { parse_key=function(r) return { vlan=r.uint(), mac_hi=r.uint(), mac_lo=r.uint(), } end, parse_value=function(r) return { port=r.uint(), } end, add=function(k, v) log("l2_add: vlan=%u mac=%04x%08x -> port %u", k.vlan, k.mac_hi, k.mac_lo, v.port) end, modify=function(k, v) log("l2_modify: vlan=%u mac=%04x%08x -> port %u", k.vlan, k.mac_hi, k.mac_lo, v.port) end, delete=function(k) log("l2_delete: vlan=%u mac=%04x%08x", k.vlan, k.mac_hi, k.mac_lo) end, }) local vlan_table = hashtable.create({ "vlan" }, { "port_bitmap" }) register_table("vlan", { parse_key=function(r) return { vlan=r.uint(), } end, parse_value=function(r) return { port_bitmap=r.uint(), } end, add=function(k, v) log("vlan_add: vlan=%u -> port_bitmap %08x", k.vlan, v.port_bitmap) end, modify=function(k, v) log("vlan_modify: vlan=%u -> port_bitmap %08x", k.vlan, v.port_bitmap) end, delete=function(k) log("vlan_delete: vlan=%u", k.vlan) end, })
epl-1.0
ffxiphoenix/darkstar
scripts/globals/items/ulbukan_lobster.lua
18
1342
----------------------------------------- -- ID: 5960 -- Item: Ulbukan Lobster -- Food Effect: 5 Min, Mithra only ----------------------------------------- -- Dexterity -3 -- Vitality 1 -- Defense +9% ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5960); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, -3); target:addMod(MOD_VIT, 1); target:addMod(MOD_DEFP, 9); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, -3); target:delMod(MOD_VIT, 1); target:delMod(MOD_DEFP, 9); end;
gpl-3.0
azekillDIABLO/Voxellar
mods/TOOLS/3d_armor/hazmat_suit/init.lua
2
3137
if not minetest.get_modpath("technic") then minetest.log("warning", "hazmat_suit: Mod loaded but unused.") return end local S = function(s) return s end if minetest.global_exists("intllib") then S = intllib.Getter() end minetest.register_craftitem("hazmat_suit:helmet_hazmat", { description = S("Hazmat Helmet"), inventory_image = "hazmat_suit_inv_helmet_hazmat.png", stack_max = 1, }) minetest.register_craftitem("hazmat_suit:chestplate_hazmat", { description = S("Hazmat Chestplate"), inventory_image = "hazmat_suit_inv_chestplate_hazmat.png", stack_max = 1, }) minetest.register_craftitem("hazmat_suit:sleeve_hazmat", { description = S("Hazmat Sleeve"), inventory_image = "hazmat_suit_inv_sleeve_hazmat.png", stack_max = 1, }) minetest.register_craftitem("hazmat_suit:leggings_hazmat", { description = S("Hazmat Leggins"), inventory_image = "hazmat_suit_inv_leggings_hazmat.png", stack_max = 1, }) minetest.register_craftitem("hazmat_suit:boots_hazmat", { description = S("Hazmat Boots"), inventory_image = "hazmat_suit_inv_boots_hazmat.png", stack_max = 1, }) armor:register_armor("hazmat_suit:suit_hazmat", { description = S("Hazmat Suit"), inventory_image = "hazmat_suit_inv_suit_hazmat.png", groups = {armor_head=1, armor_torso=1, armor_legs=1, armor_feet=1, armor_heal=20, armor_fire=4, armor_water=1, armor_use=1000, physics_jump=-0.1, physics_speed=-0.2, physics_gravity=0.1}, armor_groups = {fleshy=35, radiation=50}, damage_groups = {cracky=3, snappy=3, choppy=2, crumbly=2, level=1}, }) minetest.register_craft({ output = "hazmat_suit:helmet_hazmat", recipe = { {"", "technic:stainless_steel_ingot", ""}, {"technic:stainless_steel_ingot", "default:glass", "technic:stainless_steel_ingot"}, {"technic:rubber", "technic:rubber", "technic:rubber"}, }, }) minetest.register_craft({ output = "hazmat_suit:chestplate_hazmat", recipe = { {"technic:lead_ingot", "dye:yellow", "technic:lead_ingot"}, {"technic:stainless_steel_ingot", "technic:lead_ingot", "technic:stainless_steel_ingot"}, {"technic:lead_ingot", "technic:stainless_steel_ingot", "technic:lead_ingot"}, }, }) minetest.register_craft({ output = "hazmat_suit:sleeve_hazmat", recipe = { {"technic:rubber", "dye:yellow"}, {"", "technic:stainless_steel_ingot"}, {"", "technic:rubber"}, }, }) minetest.register_craft({ output = "hazmat_suit:leggings_hazmat", recipe = { {"technic:rubber", "technic:lead_ingot", "technic:rubber"}, {"technic:stainless_steel_ingot", "technic:rubber", "technic:stainless_steel_ingot"}, {"technic:lead_ingot", "", "technic:lead_ingot"}, }, }) minetest.register_craft({ output = "hazmat_suit:boots_hazmat", recipe = { {"", "", ""}, {"technic:rubber", "", "technic:rubber"}, {"technic:stainless_steel_ingot", "", "technic:stainless_steel_ingot"}, }, }) minetest.register_craft({ output = "hazmat_suit:suit_hazmat", type = "shapeless", recipe = { "hazmat_suit:helmet_hazmat", "hazmat_suit:chestplate_hazmat", "hazmat_suit:leggings_hazmat", "hazmat_suit:boots_hazmat", "hazmat_suit:sleeve_hazmat", "hazmat_suit:sleeve_hazmat", }, })
lgpl-2.1
Lord-Mohammad/uzzy
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
ffxiphoenix/darkstar
scripts/zones/Tahrongi_Canyon/TextIDs.lua
9
2172
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6552; -- You cannot obtain the item <item> come back again after sorting your inventory. ITEM_OBTAINED = 6557; -- Obtained: <item>. GIL_OBTAINED = 6558; -- Obtained <number> gil. KEYITEM_OBTAINED = 6560; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7216; -- You can't fish here. ALREADY_OBTAINED_TELE = 7311; -- You already possess the gate crystal for this telepoint. NOTHING_HAPPENS = 292; -- Nothing happens. -- Mining MINING_IS_POSSIBLE_HERE = 7413; -- Mining is possible here if you have -- ??? that spawns NM Yara Ma Yha Who SPROUT_LOOKS_WITHERED = 7537; -- There is something sprouting from the ground here. It looks a little withered. REPULSIVE_CREATURE_EMERGES = 7538; -- A repulsive creature emerges from the ground! SPROUT_DOES_NOT_NEED_WATER = 7539; -- The sprout does not need any more water now. SPROUT_LOOKING_BETTER = 7541; -- The sprout is looking better. -- Tahrongi Cactus BUD_BREAKS_OFF = 7390; -- The bud breaks off. You obtain POISONOUS_LOOKING_BUDS = 7391; -- The flowers have poisonous-looking buds. CANT_TAKE_ANY_MORE = 7392; -- You can't take any more. -- Other Texts TELEPOINT_HAS_BEEN_SHATTERED = 7494; -- The telepoint has been shattered into a thousand pieces... TELEPOINT_DISAPPEARED = 7312; -- The telepoint has disappeared... -- Signs SIGN_1 = 7386; -- North: Meriphataud Mountains Northeast: Crag of Mea South: East Sarutabaruta SIGN_3 = 7387; -- North: Meriphataud Mountains East: Crag of Mea South: East Sarutabaruta SIGN_5 = 7388; -- North: Meriphataud Mountains East: Buburimu Peninsula South: East Sarutabaruta SIGN_7 = 7389; -- East: Buburimu Peninsula West: East Sarutabaruta -- conquest Base CONQUEST_BASE = 0; -- chocobo digging DIG_THROW_AWAY = 7229; -- You dig up ?Possible Special Code: 01??Possible Special Code: 01??Possible Special Code: 01? ?Possible Special Code: 01??Possible Special Code: 05?$?BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?, but your inventory is full. FIND_NOTHING = 7231; -- You dig and you dig, but find nothing.
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Bastok_Markets_[S]/npcs/GentleTiger.lua
31
1775
---------------------------------- -- Area: Bastok Markets [S] -- NPC: GentleTiger -- Type: Quest -- @pos -203 -10 1 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bastok_Markets_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local onSabbatical = player:getQuestStatus(CRYSTAL_WAR,ON_SABBATICAL); local onSabbaticalProgress = player:getVar("OnSabbatical"); if (onSabbatical == QUEST_ACCEPTED) then if (onSabbaticalProgress == 1) then player:startEvent(0x002E); else player:startEvent(0x002F); end elseif (player:getQuestStatus(CRYSTAL_WAR,FIRES_OF_DISCONTENT) == QUEST_ACCEPTED) then if (player:getVar("FiresOfDiscProg") == 5) then player:startEvent(0x00A0); else player:startEvent(0x00A1); end else player:startEvent(0x006D); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x002E) then player:setVar("OnSabbatical", 2); elseif (csid == 0x00A0) then player:setVar("FiresOfDiscProg",6); end end;
gpl-3.0
keshwans/vlc
share/lua/playlist/koreus.lua
57
4037
--[[ Copyright © 2009 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() if vlc.access ~= "http" and vlc.access ~= "https" then return false end koreus_site = string.match( vlc.path, "koreus" ) if not koreus_site then return false end return ( string.match( vlc.path, "video" ) ) -- http://www.koreus.com/video/pouet.html end -- Parse function. function parse() while true do line = vlc.readline() if not line then break end if string.match( line, "<meta name=\"title\"" ) then _,_,name = string.find( line, "content=\"(.-)\"" ) name = vlc.strings.resolve_xml_special_chars( name ) end if string.match( line, "<meta property=\"og:description\"" ) then _,_,description = string.find( line, "content=\"(.-)\"" ) if (description ~= nil) then description = vlc.strings.resolve_xml_special_chars( description ) end end if string.match( line, "<span id=\"spoil\" style=\"display:none\">" ) then _,_,desc_spoil = string.find( line, "<span id=\"spoil\" style=\"display:none\">(.-)</span>" ) desc_spoil = vlc.strings.resolve_xml_special_chars( desc_spoil ) description = description .. "\n\r" .. desc_spoil end if string.match( line, "<meta name=\"author\"" ) then _,_,artist = string.find( line, "content=\"(.-)\"" ) artist = vlc.strings.resolve_xml_special_chars( artist ) end if string.match( line, "link rel=\"image_src\"" ) then _,_,arturl = string.find( line, "href=\"(.-)\"" ) end vid_url = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.mp4)' ) if vid_url then path_url = vid_url end vid_url_hd = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%-hd%.mp4)' ) if vid_url_hd then path_url_hd = vid_url_hd end vid_url_webm = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.webm)' ) if vid_url_webm then path_url_webm = vid_url_webm end vid_url_flv = string.match( line, '(http://embed%.koreus%.com/%d+/%d+/[%w-]*%.flv)' ) if vid_ulr_flv then path_url_flv = vid_url_flv end end if path_url_hd then if vlc.access == 'https' then path_url_hd = path_url_hd:gsub('http','https') end return { { path = path_url_hd; name = name; description = description; artist = artist; arturl = arturl } } elseif path_url then if vlc.access == 'https' then path_url = path_url:gsub('http','https') end return { { path = path_url; name = name; description = description; artist = artist; arturl = arturl } } elseif path_url_webm then if vlc.access == 'https' then path_url_webm = path_url_webm:gsub('http','https') end return { { path = path_url_webm; name = name; description = description; artist = artist; arturl = arturl } } elseif path_url_flv then if vlc.access == 'https' then path_url_flv = path_url_flv:gsub('http','https') end return { { path = path_url_flv; name = name; description = description; artist = artist; arturl = arturl } } else return {} end end
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Western_Altepa_Desert/npcs/_3h8.lua
17
1901
----------------------------------- -- Area: Western Altepa Desert -- NPC: _3h8 (Sapphire Column) -- Notes: Mechanism for Altepa Gate -- @pos -499 10 224 125 ----------------------------------- package.loaded["scripts/zones/Western_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Western_Altepa_Desert/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local SapphireID = npc:getID(); local Ruby = GetNPCByID(SapphireID-3):getAnimation(); local Topaz = GetNPCByID(SapphireID-2):getAnimation(); local Emerald = GetNPCByID(SapphireID-1):getAnimation(); local Sapphire = npc:getAnimation(); if (Sapphire ~= 8) then npc:setAnimation(8); GetNPCByID(SapphireID-4):setAnimation(8); else player:messageSpecial(DOES_NOT_RESPOND); end if (Emerald == 8 and Ruby == 8 and Topaz == 8) then local rand = math.random(15,30); local timeDoor = rand * 60; -- Add timer for the door GetNPCByID(SapphireID-8):openDoor(timeDoor); -- Add same timer for the 4 center lights GetNPCByID(SapphireID-7):openDoor(timeDoor); GetNPCByID(SapphireID-6):openDoor(timeDoor); GetNPCByID(SapphireID-5):openDoor(timeDoor); GetNPCByID(SapphireID-4):openDoor(timeDoor); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
deadknight1/zspammerbot
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Northern_San_dOria/npcs/Miageau.lua
17
2459
----------------------------------- -- Area: Northern San d'Oria -- NPC: Miageau -- Type: Quest Giver NPC -- @zone: 231 -- @pos 115 0 108 -- -- Starts and Finishes: Waters of Cheval ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then player:messageSpecial(FLYER_REFUSED); end end if (player:getQuestStatus(SANDORIA,WATER_OF_THE_CHEVAL) == QUEST_ACCEPTED) then if (trade:getItemCount() == 1 and trade:hasItemQty(603, 1)) then player:startEvent(0x0203); end; end; end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) watersOfTheCheval = player:getQuestStatus(SANDORIA,WATER_OF_THE_CHEVAL); if (watersOfTheCheval == QUEST_ACCEPTED) then if (player:hasItem(602) == true) then player:startEvent(0x0200); else player:startEvent(0x0207); end; elseif (watersOfTheCheval == QUEST_AVAILABLE) then player:startEvent(0x01f8); else player:startEvent(0x0205); end; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0203) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 13183); else player:tradeComplete(); player:addItem(13183); player:messageSpecial(ITEM_OBTAINED, 13183); player:addFame(SANDORIA,SAN_FAME*30); player:addTitle(THE_PURE_ONE); player:completeQuest(SANDORIA,WATER_OF_THE_CHEVAL); end; elseif (csid == 0x01f8) then player:addQuest(SANDORIA, WATER_OF_THE_CHEVAL); end; end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/RuLude_Gardens/npcs/Archanne.lua
38
1047
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Archanne -- Type: Event Scene Replayer -- @zone: 243 -- @pos -54.104 10.999 -34.144 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x2717); 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
AfuSensi/Mr.Green-MTA-Resources
resources/[admin]/admin/client/colorpicker/colorpicker.lua
7
9602
sw, sh = guiGetScreenSize() pickerTable = {} colorPicker = {} colorPicker.__index = colorPicker function openPicker(id, start, title) if id and not pickerTable[id] then pickerTable[id] = colorPicker.create(id, start, title) pickerTable[id]:updateColor() return true end return false end function closePicker(id) if id and pickerTable[id] then pickerTable[id]:destroy() return true end return false end function colorPicker.create(id, start, title) local cp = {} setmetatable(cp, colorPicker) cp.id = id cp.color = {} cp.color.h, cp.color.s, cp.color.v, cp.color.r, cp.color.g, cp.color.b, cp.color.hex = 0, 1, 1, 255, 0, 0, "#FF0000" cp.color.white = tocolor(255,255,255,255) cp.color.black = tocolor(0,0,0,255) cp.color.current = tocolor(255,0,0,255) cp.color.huecurrent = tocolor(255,0,0,255) if start and getColorFromString(start) then cp.color.h, cp.color.s, cp.color.v = rgb2hsv(getColorFromString(start)) end cp.gui = {} cp.gui.width = 416 cp.gui.height = 304 cp.gui.snaptreshold = 0.02 cp.gui.window = guiCreateWindow((sw-cp.gui.width)/2, (sh-cp.gui.height)/2, cp.gui.width, cp.gui.height, tostring(title or "COLORPICKER"), false) cp.gui.svmap = guiCreateStaticImage(16, 32, 256, 256, "client/colorpicker/blank.png", false, cp.gui.window) cp.gui.hbar = guiCreateStaticImage(288, 32, 32, 256, "client/colorpicker/blank.png", false, cp.gui.window) cp.gui.blank = guiCreateStaticImage(336, 32, 64, 64, "client/colorpicker/blank.png", false, cp.gui.window) cp.gui.edith = guiCreateLabel(338, 106, 64, 20, "H: 0°", false, cp.gui.window) cp.gui.edits = guiCreateLabel(338, 126, 64, 20, "S: 100%", false, cp.gui.window) cp.gui.editv = guiCreateLabel(338, 146, 64, 20, "V: 100%", false, cp.gui.window) cp.gui.editr = guiCreateLabel(338, 171, 64, 20, "R: 255", false, cp.gui.window) cp.gui.editg = guiCreateLabel(338, 191, 64, 20, "G: 0", false, cp.gui.window) cp.gui.editb = guiCreateLabel(338, 211, 64, 20, "B: 0", false, cp.gui.window) cp.gui.okb = guiCreateButton(336, 235, 64, 24, "OK", false, cp.gui.window) cp.gui.closeb = guiCreateButton(336, 265, 64, 24, "Cancel", false, cp.gui.window) guiWindowSetSizable(cp.gui.window, false) cp.handlers = {} cp.handlers.mouseDown = function() cp:mouseDown() end cp.handlers.mouseSnap = function() cp:mouseSnap() end cp.handlers.mouseUp = function(b,s) cp:mouseUp(b,s) end cp.handlers.mouseMove = function(x,y) cp:mouseMove(x,y) end cp.handlers.render = function() cp:render() end cp.handlers.guiFocus = function() cp:guiFocus() end cp.handlers.guiBlur = function() cp:guiBlur() end cp.handlers.pickColor = function() cp:pickColor() end cp.handlers.destroy = function() cp:destroy() end addEventHandler("onClientGUIMouseDown", cp.gui.svmap, cp.handlers.mouseDown, false) addEventHandler("onClientMouseLeave", cp.gui.svmap, cp.handlers.mouseSnap, false) addEventHandler("onClientMouseMove", cp.gui.svmap, cp.handlers.mouseMove, false) addEventHandler("onClientGUIMouseDown", cp.gui.hbar, cp.handlers.mouseDown, false) addEventHandler("onClientMouseMove", cp.gui.hbar, cp.handlers.mouseMove, false) addEventHandler("onClientClick", root, cp.handlers.mouseUp) addEventHandler("onClientGUIMouseUp", root, cp.handlers.mouseUp) addEventHandler("onClientRender", root, cp.handlers.render) addEventHandler("onClientGUIFocus", cp.gui.window, cp.handlers.guiFocus, false) addEventHandler("onClientGUIBlur", cp.gui.window, cp.handlers.guiBlur, false) addEventHandler("onClientGUIClick", cp.gui.okb, cp.handlers.pickColor, false) addEventHandler("onClientGUIClick", cp.gui.closeb, cp.handlers.destroy, false) showCursor(true) return cp end function colorPicker:render() -- if not self.gui.focus then return end local x,y = guiGetPosition(self.gui.window, false) dxDrawRectangle(x+16, y+32, 256, 256, self.color.huecurrent, self.gui.focus) dxDrawImage(x+16, y+32, 256, 256, "client/colorpicker/sv.png", 0, 0, 0, self.color.white, self.gui.focus) dxDrawImage(x+288, y+32, 32, 256, "client/colorpicker/h.png", 0, 0, 0, self.color.white, self.gui.focus) dxDrawImageSection(x+8+math.floor(256*self.color.s), y+24+(256-math.floor(256*self.color.v)), 16, 16, 0, 0, 16, 16, "client/colorpicker/cursor.png", 0, 0, 0, self.color.white, self.gui.focus) dxDrawImageSection(x+280, y+24+(256-math.floor(256*self.color.h)), 48, 16, 16, 0, 48, 16, "client/colorpicker/cursor.png", 0, 0, 0, self.color.huecurrent, self.gui.focus) dxDrawRectangle(x+336, y+32, 64, 64, self.color.current, self.gui.focus) dxDrawText(self.color.hex, x+336, y+32, x+400, y+96, self.color.v < 0.5 and self.color.white or self.color.black, 1, "default", "center", "center", true, true, self.gui.focus) end function colorPicker:mouseDown() if source == self.gui.svmap or source == self.gui.hbar then self.gui.track = source local cx, cy = getCursorPosition() self:mouseMove(sw*cx, sh*cy) end end function colorPicker:mouseUp(button, state) if not state or state ~= "down" then if self.gui.track then triggerEvent("onColorPickerChange", root, self.id, self.color.hex, self.color.r, self.color.g, self.color.b) end self.gui.track = false end end function colorPicker:mouseMove(x,y) if self.gui.track and source == self.gui.track then local gx,gy = guiGetPosition(self.gui.window, false) if source == self.gui.svmap then local offsetx, offsety = x - (gx + 16), y - (gy + 32) self.color.s = offsetx/255 self.color.v = (255-offsety)/255 elseif source == self.gui.hbar then local offset = y - (gy + 32) self.color.h = (255-offset)/255 end self:updateColor() end end function colorPicker:mouseSnap() if self.gui.track and source == self.gui.track then if self.color.s < self.gui.snaptreshold or self.color.s > 1-self.gui.snaptreshold then self.color.s = math.round(self.color.s) end if self.color.v < self.gui.snaptreshold or self.color.v > 1-self.gui.snaptreshold then self.color.v = math.round(self.color.v) end self:updateColor() end end function colorPicker:updateColor() self.color.r, self.color.g, self.color.b = hsv2rgb(self.color.h, self.color.s, self.color.v) self.color.current = tocolor(self.color.r, self.color.g, self.color.b,255) self.color.huecurrent = tocolor(hsv2rgb(self.color.h, 1, 1)) self.color.hex = string.format("#%02X%02X%02X", self.color.r, self.color.g, self.color.b) guiSetText(self.gui.edith, "H: "..tostring(math.round(self.color.h*360)).."°") guiSetText(self.gui.edits, "S: "..tostring(math.round(self.color.s*100)).."%") guiSetText(self.gui.editv, "V: "..tostring(math.round(self.color.v*100)).."%") guiSetText(self.gui.editr, "R: "..tostring(self.color.r)) guiSetText(self.gui.editg, "G: "..tostring(self.color.g)) guiSetText(self.gui.editb, "B: "..tostring(self.color.b)) end function colorPicker:guiFocus() self.gui.focus = true guiSetAlpha(self.gui.window, 1) end function colorPicker:guiBlur() self.gui.focus = false guiSetAlpha(self.gui.window, 0.5) end function colorPicker:pickColor() triggerEvent("onColorPickerOK", root, self.id, self.color.hex, self.color.r, self.color.g, self.color.b) self:destroy() end function colorPicker:destroy() removeEventHandler("onClientGUIMouseDown", self.gui.svmap, self.handlers.mouseDown) removeEventHandler("onClientMouseLeave", self.gui.svmap, self.handlers.mouseSnap) removeEventHandler("onClientMouseMove", self.gui.svmap, self.handlers.mouseMove) removeEventHandler("onClientGUIMouseDown", self.gui.hbar, self.handlers.mouseDown) removeEventHandler("onClientMouseMove", self.gui.hbar, self.handlers.mouseMove) removeEventHandler("onClientClick", root, self.handlers.mouseUp) removeEventHandler("onClientGUIMouseUp", root, self.handlers.mouseUp) removeEventHandler("onClientRender", root, self.handlers.render) removeEventHandler("onClientGUIFocus", self.gui.window, self.handlers.guiFocus) removeEventHandler("onClientGUIBlur", self.gui.window, self.handlers.guiBlur) removeEventHandler("onClientGUIClick", self.gui.okb, self.handlers.pickColor) removeEventHandler("onClientGUIClick", self.gui.closeb, self.handlers.destroy) destroyElement(self.gui.window) pickerTable[self.id] = nil setmetatable(self, nil) --showCursor(areThereAnyPickers()) end function areThereAnyPickers() for _ in pairs(pickerTable) do return true end return false end function hsv2rgb(h, s, v) local r, g, b local i = math.floor(h * 6) local f = h * 6 - i local p = v * (1 - s) local q = v * (1 - f * s) local t = v * (1 - (1 - f) * s) local switch = i % 6 if switch == 0 then r = v g = t b = p elseif switch == 1 then r = q g = v b = p elseif switch == 2 then r = p g = v b = t elseif switch == 3 then r = p g = q b = v elseif switch == 4 then r = t g = p b = v elseif switch == 5 then r = v g = p b = q end return math.floor(r*255), math.floor(g*255), math.floor(b*255) end function rgb2hsv(r, g, b) r, g, b = r/255, g/255, b/255 local max, min = math.max(r, g, b), math.min(r, g, b) local h, s local v = max local d = max - min s = max == 0 and 0 or d/max if max == min then h = 0 elseif max == r then h = (g - b) / d + (g < b and 6 or 0) elseif max == g then h = (b - r) / d + 2 elseif max == b then h = (r - g) / d + 4 end h = h/6 return h, s, v end function math.round(v) return math.floor(v+0.5) end addEvent("onColorPickerOK", true) addEvent("onColorPickerChange", true)
mit
WUTiAM/uLua2
Tools/uLua/Source/LuaJIT-2.1.0-beta2/dynasm/dasm_arm64.lua
33
34807
------------------------------------------------------------------------------ -- DynASM ARM64 module. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "arm", description = "DynASM ARM64 module", version = "1.4.0", vernum = 10400, release = "2015-10-18", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable, rawget = assert, setmetatable, rawget local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub local concat, sort, insert = table.concat, table.sort, table.insert local bit = bit or require("bit") local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift local ror, tohex = bit.ror, bit.tohex -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "IMM", "IMM6", "IMM12", "IMM13W", "IMM13X", "IMML", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n <= 0x000fffff then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") if n <= 0x000fffff then insert(actlist, pos+1, n) n = map_action.ESC * 0x10000 end actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. -- Ext. register name -> int. name. local map_archdef = { xzr = "@x31", wzr = "@w31", lr = "x30", } -- Int. register name -> ext. name. local map_reg_rev = { ["@x31"] = "xzr", ["@w31"] = "wzr", x30 = "lr", } local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) return map_reg_rev[s] or s end local map_shift = { lsl = 0, lsr = 1, asr = 2, } local map_extend = { uxtb = 0, uxth = 1, uxtw = 2, uxtx = 3, sxtb = 4, sxth = 5, sxtw = 6, sxtx = 7, } local map_cond = { eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7, hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14, hs = 2, lo = 3, } ------------------------------------------------------------------------------ local parse_reg_type local function parse_reg(expr) if not expr then werror("expected register name") end local tname, ovreg = match(expr, "^([%w_]+):(@?%l%d+)$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local ok31, rt, r = match(expr, "^(@?)([xwqdshb])([123]?[0-9])$") if r then r = tonumber(r) if r <= 30 or (r == 31 and ok31 ~= "" or (rt ~= "w" and rt ~= "x")) then if not parse_reg_type then parse_reg_type = rt elseif parse_reg_type ~= rt then werror("register size mismatch") end return r, tp end end werror("bad register name `"..expr.."'") end local function parse_reg_base(expr) if expr == "sp" then return 0x3e0 end local base, tp = parse_reg(expr) if parse_reg_type ~= "x" then werror("bad register type") end parse_reg_type = false return shl(base, 5), tp end local parse_ctx = {} local loadenv = setfenv and function(s) local code = loadstring(s, "") if code then setfenv(code, parse_ctx) end return code end or function(s) return load(s, "", nil, parse_ctx) end -- Try to parse simple arithmetic, too, since some basic ops are aliases. local function parse_number(n) local x = tonumber(n) if x then return x end local code = loadenv("return "..n) if code then local ok, y = pcall(code) if ok then return y end end return nil end local function parse_imm(imm, bits, shift, scale, signed) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_imm12(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then if shr(n, 12) == 0 then return shl(n, 10) elseif band(n, 0xff000fff) == 0 then return shr(n, 2) + 0x00400000 end werror("out of range immediate `"..imm.."'") else waction("IMM12", 0, imm) return 0 end end local function parse_imm13(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) local r64 = parse_reg_type == "x" if n and n % 1 == 0 and n >= 0 and n <= 0xffffffff then local inv = false if band(n, 1) == 1 then n = bit.bnot(n); inv = true end local t = {} for i=1,32 do t[i] = band(n, 1); n = shr(n, 1) end local b = table.concat(t) b = b..(r64 and (inv and "1" or "0"):rep(32) or b) local p0, p1, p0a, p1a = b:match("^(0+)(1+)(0*)(1*)") if p0 then local w = p1a == "" and (r64 and 64 or 32) or #p1+#p0a if band(w, w-1) == 0 and b == b:sub(1, w):rep(64/w) then local s = band(-2*w, 0x3f) - 1 if w == 64 then s = s + 0x1000 end if inv then return shl(w-#p1-#p0, 16) + shl(s+w-#p1, 10) else return shl(w-#p0, 16) + shl(s+#p1, 10) end end end werror("out of range immediate `"..imm.."'") elseif r64 then waction("IMM13X", 0, format("(unsigned int)(%s)", imm)) actargs[#actargs+1] = format("(unsigned int)((unsigned long long)(%s)>>32)", imm) return 0 else waction("IMM13W", 0, imm) return 0 end end local function parse_imm6(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then if n >= 0 and n <= 63 then return shl(band(n, 0x1f), 19) + (n >= 32 and 0x80000000 or 0) end werror("out of range immediate `"..imm.."'") else waction("IMM6", 0, imm) return 0 end end local function parse_imm_load(imm, scale) local n = parse_number(imm) if n then local m = sar(n, scale) if shl(m, scale) == n and m >= 0 and m < 0x1000 then return shl(m, 10) + 0x01000000 -- Scaled, unsigned 12 bit offset. elseif n >= -256 and n < 256 then return shl(band(n, 511), 12) -- Unscaled, signed 9 bit offset. end werror("out of range immediate `"..imm.."'") else waction("IMML", 0, imm) return 0 end end local function parse_fpimm(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = parse_number(imm) if n then local m, e = math.frexp(n) local s, e2 = 0, band(e-2, 7) if m < 0 then m = -m; s = 0x00100000 end m = m*32-16 if m % 1 == 0 and m >= 0 and m <= 15 and sar(shl(e2, 29), 29)+2 == e then return s + shl(e2, 17) + shl(m, 13) end werror("out of range immediate `"..imm.."'") else werror("NYI fpimm action") end end local function parse_shift(expr) local s, s2 = match(expr, "^(%S+)%s*(.*)$") s = map_shift[s] if not s then werror("expected shift operand") end return parse_imm(s2, 6, 10, 0, false) + shl(s, 22) end local function parse_lslx16(expr) local n = match(expr, "^lsl%s*#(%d+)$") n = tonumber(n) if not n then werror("expected shift operand") end if band(n, parse_reg_type == "x" and 0xffffffcf or 0xffffffef) ~= 0 then werror("bad shift amount") end return shl(n, 17) end local function parse_extend(expr) local s, s2 = match(expr, "^(%S+)%s*(.*)$") if s == "lsl" then s = parse_reg_type == "x" and 3 or 2 else s = map_extend[s] end if not s then werror("expected extend operand") end return (s2 == "" and 0 or parse_imm(s2, 3, 10, 0, false)) + shl(s, 13) end local function parse_cond(expr, inv) local c = map_cond[expr] if not c then werror("expected condition operand") end return shl(bit.bxor(c, inv), 12) end local function parse_load(params, nparams, n, op) if params[n+2] then werror("too many operands") end local pn, p2 = params[n], params[n+1] local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") if not p1 then if not p2 then local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local base, tp = parse_reg_base(reg) if tp then waction("IMML", 0, format(tp.ctypefmt, tailr)) return op + base end end end werror("expected address operand") end local scale = shr(op, 30) if p2 then if wb == "!" then werror("bad use of '!'") end op = op + parse_reg_base(p1) + parse_imm(p2, 9, 12, 0, true) + 0x400 elseif wb == "!" then local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$") if not p1a then werror("bad use of '!'") end op = op + parse_reg_base(p1a) + parse_imm(p2a, 9, 12, 0, true) + 0xc00 else local p1a, p2a = match(p1, "^([^,%s]*)%s*(.*)$") op = op + parse_reg_base(p1a) if p2a ~= "" then local imm = match(p2a, "^,%s*#(.*)$") if imm then op = op + parse_imm_load(imm, scale) else local p2b, p3b, p3s = match(p2a, "^,%s*([^,%s]*)%s*,?%s*(%S*)%s*(.*)$") op = op + shl(parse_reg(p2b), 16) + 0x00200800 if parse_reg_type ~= "x" and parse_reg_type ~= "w" then werror("bad index register type") end if p3b == "" then if parse_reg_type ~= "x" then werror("bad index register type") end op = op + 0x6000 else if p3s == "" or p3s == "#0" then elseif p3s == "#"..scale then op = op + 0x1000 else werror("bad scale") end if parse_reg_type == "x" then if p3b == "lsl" and p3s ~= "" then op = op + 0x6000 elseif p3b == "sxtx" then op = op + 0xe000 else werror("bad extend/shift specifier") end else if p3b == "uxtw" then op = op + 0x4000 elseif p3b == "sxtw" then op = op + 0xc000 else werror("bad extend/shift specifier") end end end end else if wb == "!" then werror("bad use of '!'") end op = op + 0x01000000 end end return op end local function parse_load_pair(params, nparams, n, op) if params[n+2] then werror("too many operands") end local pn, p2 = params[n], params[n+1] local scale = shr(op, 30) == 0 and 2 or 3 local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") if not p1 then if not p2 then local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local base, tp = parse_reg_base(reg) if tp then waction("IMM", 32768+7*32+15+scale*1024, format(tp.ctypefmt, tailr)) return op + base + 0x01000000 end end end werror("expected address operand") end if p2 then if wb == "!" then werror("bad use of '!'") end op = op + 0x00800000 else local p1a, p2a = match(p1, "^([^,%s]*)%s*,%s*(.*)$") if p1a then p1, p2 = p1a, p2a else p2 = "#0" end op = op + (wb == "!" and 0x01800000 or 0x01000000) end return op + parse_reg_base(p1) + parse_imm(p2, 7, 15, scale, true) end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end local function branch_type(op) if band(op, 0x7c000000) == 0x14000000 then return 0 -- B, BL elseif shr(op, 24) == 0x54 or band(op, 0x7e000000) == 0x34000000 or band(op, 0x3b000000) == 0x18000000 then return 0x800 -- B.cond, CBZ, CBNZ, LDR* literal elseif band(op, 0x7e000000) == 0x36000000 then return 0x1000 -- TBZ, TBNZ elseif band(op, 0x9f000000) == 0x10000000 then return 0x2000 -- ADR elseif band(op, 0x9f000000) == band(0x90000000) then return 0x3000 -- ADRP else assert(false, "unknown branch type") end end ------------------------------------------------------------------------------ local map_op, op_template local function op_alias(opname, f) return function(params, nparams) if not params then return "-> "..opname:sub(1, -3) end f(params, nparams) op_template(params, map_op[opname], nparams) end end local function alias_bfx(p) p[4] = "#("..p[3]:sub(2)..")+("..p[4]:sub(2)..")-1" end local function alias_bfiz(p) parse_reg(p[1]) if parse_reg_type == "w" then p[3] = "#-("..p[3]:sub(2)..")%32" p[4] = "#("..p[4]:sub(2)..")-1" else p[3] = "#-("..p[3]:sub(2)..")%64" p[4] = "#("..p[4]:sub(2)..")-1" end end local alias_lslimm = op_alias("ubfm_4", function(p) parse_reg(p[1]) local sh = p[3]:sub(2) if parse_reg_type == "w" then p[3] = "#-("..sh..")%32" p[4] = "#31-("..sh..")" else p[3] = "#-("..sh..")%64" p[4] = "#63-("..sh..")" end end) -- Template strings for ARM instructions. map_op = { -- Basic data processing instructions. add_3 = "0b000000DNMg|11000000pDpNIg|8b206000pDpNMx", add_4 = "0b000000DNMSg|0b200000DNMXg|8b200000pDpNMXx|8b200000pDpNxMwX", adds_3 = "2b000000DNMg|31000000DpNIg|ab206000DpNMx", adds_4 = "2b000000DNMSg|2b200000DNMXg|ab200000DpNMXx|ab200000DpNxMwX", cmn_2 = "2b00001fNMg|3100001fpNIg|ab20601fpNMx", cmn_3 = "2b00001fNMSg|2b20001fNMXg|ab20001fpNMXx|ab20001fpNxMwX", sub_3 = "4b000000DNMg|51000000pDpNIg|cb206000pDpNMx", sub_4 = "4b000000DNMSg|4b200000DNMXg|cb200000pDpNMXx|cb200000pDpNxMwX", subs_3 = "6b000000DNMg|71000000DpNIg|eb206000DpNMx", subs_4 = "6b000000DNMSg|6b200000DNMXg|eb200000DpNMXx|eb200000DpNxMwX", cmp_2 = "6b00001fNMg|7100001fpNIg|eb20601fpNMx", cmp_3 = "6b00001fNMSg|6b20001fNMXg|eb20001fpNMXx|eb20001fpNxMwX", neg_2 = "4b0003e0DMg", neg_3 = "4b0003e0DMSg", negs_2 = "6b0003e0DMg", negs_3 = "6b0003e0DMSg", adc_3 = "1a000000DNMg", adcs_3 = "3a000000DNMg", sbc_3 = "5a000000DNMg", sbcs_3 = "7a000000DNMg", ngc_2 = "5a0003e0DMg", ngcs_2 = "7a0003e0DMg", and_3 = "0a000000DNMg|12000000pDNig", and_4 = "0a000000DNMSg", orr_3 = "2a000000DNMg|32000000pDNig", orr_4 = "2a000000DNMSg", eor_3 = "4a000000DNMg|52000000pDNig", eor_4 = "4a000000DNMSg", ands_3 = "6a000000DNMg|72000000DNig", ands_4 = "6a000000DNMSg", tst_2 = "6a00001fNMg|7200001fNig", tst_3 = "6a00001fNMSg", bic_3 = "0a200000DNMg", bic_4 = "0a200000DNMSg", orn_3 = "2a200000DNMg", orn_4 = "2a200000DNMSg", eon_3 = "4a200000DNMg", eon_4 = "4a200000DNMSg", bics_3 = "6a200000DNMg", bics_4 = "6a200000DNMSg", movn_2 = "12800000DWg", movn_3 = "12800000DWRg", movz_2 = "52800000DWg", movz_3 = "52800000DWRg", movk_2 = "72800000DWg", movk_3 = "72800000DWRg", -- TODO: this doesn't cover all valid immediates for mov reg, #imm. mov_2 = "2a0003e0DMg|52800000DW|320003e0pDig|11000000pDpNg", mov_3 = "2a0003e0DMSg", mvn_2 = "2a2003e0DMg", mvn_3 = "2a2003e0DMSg", adr_2 = "10000000DBx", adrp_2 = "90000000DBx", csel_4 = "1a800000DNMCg", csinc_4 = "1a800400DNMCg", csinv_4 = "5a800000DNMCg", csneg_4 = "5a800400DNMCg", cset_2 = "1a9f07e0Dcg", csetm_2 = "5a9f03e0Dcg", cinc_3 = "1a800400DNmcg", cinv_3 = "5a800000DNmcg", cneg_3 = "5a800400DNmcg", ccmn_4 = "3a400000NMVCg|3a400800N5VCg", ccmp_4 = "7a400000NMVCg|7a400800N5VCg", madd_4 = "1b000000DNMAg", msub_4 = "1b008000DNMAg", mul_3 = "1b007c00DNMg", mneg_3 = "1b00fc00DNMg", smaddl_4 = "9b200000DxNMwAx", smsubl_4 = "9b208000DxNMwAx", smull_3 = "9b207c00DxNMw", smnegl_3 = "9b20fc00DxNMw", smulh_3 = "9b407c00DNMx", umaddl_4 = "9ba00000DxNMwAx", umsubl_4 = "9ba08000DxNMwAx", umull_3 = "9ba07c00DxNMw", umnegl_3 = "9ba0fc00DxNMw", umulh_3 = "9bc07c00DNMx", udiv_3 = "1ac00800DNMg", sdiv_3 = "1ac00c00DNMg", -- Bit operations. sbfm_4 = "13000000DN12w|93400000DN12x", bfm_4 = "33000000DN12w|b3400000DN12x", ubfm_4 = "53000000DN12w|d3400000DN12x", extr_4 = "13800000DNM2w|93c00000DNM2x", sxtb_2 = "13001c00DNw|93401c00DNx", sxth_2 = "13003c00DNw|93403c00DNx", sxtw_2 = "93407c00DxNw", uxtb_2 = "53001c00DNw", uxth_2 = "53003c00DNw", sbfx_4 = op_alias("sbfm_4", alias_bfx), bfxil_4 = op_alias("bfm_4", alias_bfx), ubfx_4 = op_alias("ubfm_4", alias_bfx), sbfiz_4 = op_alias("sbfm_4", alias_bfiz), bfi_4 = op_alias("bfm_4", alias_bfiz), ubfiz_4 = op_alias("ubfm_4", alias_bfiz), lsl_3 = function(params, nparams) if params and params[3]:byte() == 35 then return alias_lslimm(params, nparams) else return op_template(params, "1ac02000DNMg", nparams) end end, lsr_3 = "1ac02400DNMg|53007c00DN1w|d340fc00DN1x", asr_3 = "1ac02800DNMg|13007c00DN1w|9340fc00DN1x", ror_3 = "1ac02c00DNMg|13800000DNm2w|93c00000DNm2x", clz_2 = "5ac01000DNg", cls_2 = "5ac01400DNg", rbit_2 = "5ac00000DNg", rev_2 = "5ac00800DNw|dac00c00DNx", rev16_2 = "5ac00400DNg", rev32_2 = "dac00800DNx", -- Loads and stores. ["strb_*"] = "38000000DwL", ["ldrb_*"] = "38400000DwL", ["ldrsb_*"] = "38c00000DwL|38800000DxL", ["strh_*"] = "78000000DwL", ["ldrh_*"] = "78400000DwL", ["ldrsh_*"] = "78c00000DwL|78800000DxL", ["str_*"] = "b8000000DwL|f8000000DxL|bc000000DsL|fc000000DdL", ["ldr_*"] = "18000000DwB|58000000DxB|1c000000DsB|5c000000DdB|b8400000DwL|f8400000DxL|bc400000DsL|fc400000DdL", ["ldrsw_*"] = "98000000DxB|b8800000DxL", -- NOTE: ldur etc. are handled by ldr et al. ["stp_*"] = "28000000DAwP|a8000000DAxP|2c000000DAsP|6c000000DAdP", ["ldp_*"] = "28400000DAwP|a8400000DAxP|2c400000DAsP|6c400000DAdP", ["ldpsw_*"] = "68400000DAxP", -- Branches. b_1 = "14000000B", bl_1 = "94000000B", blr_1 = "d63f0000Nx", br_1 = "d61f0000Nx", ret_0 = "d65f03c0", ret_1 = "d65f0000Nx", -- b.cond is added below. cbz_2 = "34000000DBg", cbnz_2 = "35000000DBg", tbz_3 = "36000000DTBw|36000000DTBx", tbnz_3 = "37000000DTBw|37000000DTBx", -- Miscellaneous instructions. -- TODO: hlt, hvc, smc, svc, eret, dcps[123], drps, mrs, msr -- TODO: sys, sysl, ic, dc, at, tlbi -- TODO: hint, yield, wfe, wfi, sev, sevl -- TODO: clrex, dsb, dmb, isb nop_0 = "d503201f", brk_0 = "d4200000", brk_1 = "d4200000W", -- Floating point instructions. fmov_2 = "1e204000DNf|1e260000DwNs|1e270000DsNw|9e660000DxNd|9e670000DdNx|1e201000DFf", fabs_2 = "1e20c000DNf", fneg_2 = "1e214000DNf", fsqrt_2 = "1e21c000DNf", fcvt_2 = "1e22c000DdNs|1e624000DsNd", -- TODO: half-precision and fixed-point conversions. fcvtas_2 = "1e240000DwNs|9e240000DxNs|1e640000DwNd|9e640000DxNd", fcvtau_2 = "1e250000DwNs|9e250000DxNs|1e650000DwNd|9e650000DxNd", fcvtms_2 = "1e300000DwNs|9e300000DxNs|1e700000DwNd|9e700000DxNd", fcvtmu_2 = "1e310000DwNs|9e310000DxNs|1e710000DwNd|9e710000DxNd", fcvtns_2 = "1e200000DwNs|9e200000DxNs|1e600000DwNd|9e600000DxNd", fcvtnu_2 = "1e210000DwNs|9e210000DxNs|1e610000DwNd|9e610000DxNd", fcvtps_2 = "1e280000DwNs|9e280000DxNs|1e680000DwNd|9e680000DxNd", fcvtpu_2 = "1e290000DwNs|9e290000DxNs|1e690000DwNd|9e690000DxNd", fcvtzs_2 = "1e380000DwNs|9e380000DxNs|1e780000DwNd|9e780000DxNd", fcvtzu_2 = "1e390000DwNs|9e390000DxNs|1e790000DwNd|9e790000DxNd", scvtf_2 = "1e220000DsNw|9e220000DsNx|1e620000DdNw|9e620000DdNx", ucvtf_2 = "1e230000DsNw|9e230000DsNx|1e630000DdNw|9e630000DdNx", frintn_2 = "1e244000DNf", frintp_2 = "1e24c000DNf", frintm_2 = "1e254000DNf", frintz_2 = "1e25c000DNf", frinta_2 = "1e264000DNf", frintx_2 = "1e274000DNf", frinti_2 = "1e27c000DNf", fadd_3 = "1e202800DNMf", fsub_3 = "1e203800DNMf", fmul_3 = "1e200800DNMf", fnmul_3 = "1e208800DNMf", fdiv_3 = "1e201800DNMf", fmadd_4 = "1f000000DNMAf", fmsub_4 = "1f008000DNMAf", fnmadd_4 = "1f200000DNMAf", fnmsub_4 = "1f208000DNMAf", fmax_3 = "1e204800DNMf", fmaxnm_3 = "1e206800DNMf", fmin_3 = "1e205800DNMf", fminnm_3 = "1e207800DNMf", fcmp_2 = "1e202000NMf|1e202008NZf", fcmpe_2 = "1e202010NMf|1e202018NZf", fccmp_4 = "1e200400NMVCf", fccmpe_4 = "1e200410NMVCf", fcsel_4 = "1e200c00DNMCf", -- TODO: crc32*, aes*, sha*, pmull -- TODO: SIMD instructions. } for cond,c in pairs(map_cond) do map_op["b"..cond.."_1"] = tohex(0x54000000+c).."B" end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. local function parse_template(params, template, nparams, pos) local op = tonumber(sub(template, 1, 8), 16) local n = 1 local rtt = {} parse_reg_type = false -- Process each character. for p in gmatch(sub(template, 9), ".") do local q = params[n] if p == "D" then op = op + parse_reg(q); n = n + 1 elseif p == "N" then op = op + shl(parse_reg(q), 5); n = n + 1 elseif p == "M" then op = op + shl(parse_reg(q), 16); n = n + 1 elseif p == "A" then op = op + shl(parse_reg(q), 10); n = n + 1 elseif p == "m" then op = op + shl(parse_reg(params[n-1]), 16) elseif p == "p" then if q == "sp" then params[n] = "@x31" end elseif p == "g" then if parse_reg_type == "x" then op = op + 0x80000000 elseif parse_reg_type ~= "w" then werror("bad register type") end parse_reg_type = false elseif p == "f" then if parse_reg_type == "d" then op = op + 0x00400000 elseif parse_reg_type ~= "s" then werror("bad register type") end parse_reg_type = false elseif p == "x" or p == "w" or p == "d" or p == "s" then if parse_reg_type ~= p then werror("register size mismatch") end parse_reg_type = false elseif p == "L" then op = parse_load(params, nparams, n, op) elseif p == "P" then op = parse_load_pair(params, nparams, n, op) elseif p == "B" then local mode, v, s = parse_label(q, false); n = n + 1 local m = branch_type(op) waction("REL_"..mode, v+m, s, 1) elseif p == "I" then op = op + parse_imm12(q); n = n + 1 elseif p == "i" then op = op + parse_imm13(q); n = n + 1 elseif p == "W" then op = op + parse_imm(q, 16, 5, 0, false); n = n + 1 elseif p == "T" then op = op + parse_imm6(q); n = n + 1 elseif p == "1" then op = op + parse_imm(q, 6, 16, 0, false); n = n + 1 elseif p == "2" then op = op + parse_imm(q, 6, 10, 0, false); n = n + 1 elseif p == "5" then op = op + parse_imm(q, 5, 16, 0, false); n = n + 1 elseif p == "V" then op = op + parse_imm(q, 4, 0, 0, false); n = n + 1 elseif p == "F" then op = op + parse_fpimm(q); n = n + 1 elseif p == "Z" then if q ~= "#0" and q ~= "#0.0" then werror("expected zero immediate") end n = n + 1 elseif p == "S" then op = op + parse_shift(q); n = n + 1 elseif p == "X" then op = op + parse_extend(q); n = n + 1 elseif p == "R" then op = op + parse_lslx16(q); n = n + 1 elseif p == "C" then op = op + parse_cond(q, 0); n = n + 1 elseif p == "c" then op = op + parse_cond(q, 1); n = n + 1 else assert(false) end end wputpos(pos, op) end function op_template(params, template, nparams) if not params then return template:gsub("%x%x%x%x%x%x%x%x", "") end -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 3 positions. if secpos+3 > maxsecpos then wflush() end local pos = wpos() local lpos, apos, spos = #actlist, #actargs, secpos local ok, err for t in gmatch(template, "[^|]+") do ok, err = pcall(parse_template, params, t, nparams, pos) if ok then return end secpos = spos actlist[lpos+1] = nil actlist[lpos+2] = nil actlist[lpos+3] = nil actargs[apos+1] = nil actargs[apos+2] = nil actargs[apos+3] = nil end error(err, 0) end map_op[".template__"] = op_template ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. map_op[".long_*"] = function(params) if not params then return "imm..." end for _,p in ipairs(params) do local n = tonumber(p) if not n then werror("bad immediate `"..p.."'") end if n < 0 then n = n + 2^32 end wputw(n) if secpos+2 > maxsecpos then wflush() end end end -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
mit
mahdikord/mahdib0
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
farrajota/human_pose_estimation_torch
models/test/SML_v4_1.lua
1
10204
--[[ This network is coined SML (Small-Medium-Large). It is a variation of the stacked hourglass with our modified version. It should run faster than the modified hg due to having less convolutions and less stacks, concentrating the bulk of the processing needs on 1/2 networks instead of spreading it through 8+ stacks of networks. This network is designed/composed by three stacked auto-encoders: - (S) an auto-encoder with fewer parameters; (Note: This gives as an initial/rough estimation of the body parts regions.) - (M) has more layers+parameters than the (S) network; (Note: This improves the intial estimation and feeds a better map to the next and final layer) - (L) has the most layers+parameters+lowest resolution of all networks. Also, it produces the final output. (Note: This final layer contains more parameters than the two previous networks combined. The resulting output map should be the most accurate map of them all.) ]] local Residual, relu = paths.dofile('../layers/ResidualSML.lua') ------------------------------------------------------------------------------------------------------------ local function beautify_modules(modules) -- auto-encoder small if modules.ae_small then modules.ae_small:annotate{ name = 'Auto-Encoder (Small)', description = 'Auto-Encoder network with I/O resolution 64x64', graphAttributes = { color = 'red', style = 'filled', fillcolor = 'yellow'} } end -- auto-encoder medium if modules.ae_medium then modules.ae_medium:annotate{ name = 'Auto-Encoder (Medium)', description = 'Auto-Encoder network with I/O resolution 128x128', graphAttributes = { color = 'red', style = 'filled', fillcolor = 'yellow'} } end -- auto-encoder large if modules.ae_large then modules.ae_large:annotate{ name = 'Auto-Encoder (Large)', description = 'Auto-Encoder network with I/O resolution 256x256', graphAttributes = { color = 'red', style = 'filled', fillcolor = 'yellow'} } end -- linear layers if modules.lin then for k, lin_layer in pairs(modules.lin) do lin_layer:annotate{ name = 'Linear layer', description = 'Linear layer with 1x1 convolutions', graphAttributes = {color = 'blue', fontcolor = 'green'} } end end -- linear layers if modules.out then for k, output_layer in pairs(modules.out) do output_layer:annotate{ name = 'Output layer', description = 'Output heatmaps', graphAttributes = { color = 'black', style = 'filled', fillcolor = 'blue'} } end end end ------------------------------------------------------------------------------------------------------------ local function AE_small(n, numIn, numOut, f) ---- local feat_inc = 32 --16 local function hourglass(n, f, inp) -- Upper branch local up1 = Residual(f,f)(inp) -- Lower branch local low1 = Residual(f,f+feat_inc, 'D')(inp) local low2 if n > 1 then low2 = hourglass(n-1,f+feat_inc,low1) else low2 = Residual(f+feat_inc,f+feat_inc)(low1) end local up2 = Residual(f+feat_inc,f, 'U')(low2) -- Bring two branches together return nn.CAddTable()({up1,up2}) end ---- local input = nn.Identity()() local r1 = Residual(numIn,f)(input) local hg = hourglass(n, f, r1) local output = Residual(f,numOut)(hg) local network = nn.gModule({input}, {output}) network.name = 'AE_small' return network end ------------------------------------------------------------------------------------------------------------ local function AE_medium(n, numIn, numOut, f) ---- local feat_inc = 64 --32 local function hourglass(n, f, inp) -- Upper branch local up1 = Residual(f,f+feat_inc)(inp) local up2 = Residual(f+feat_inc,f)(up1) -- Lower branch local low1 = Residual(f,f+feat_inc, 'D')(inp) local low2 = Residual(f+feat_inc,f+feat_inc)(low1) local low3 if n > 1 then low3 = hourglass(n-1,f+feat_inc, low2) else low3 = Residual(f+feat_inc, f+feat_inc)(low2) end local up3 = Residual(f+feat_inc, f, 'U')(low3) -- Bring two branches together return nn.CAddTable()({up2,up3}) end ---- local input = nn.Identity()() local r1 = Residual(numIn,f)(input) local hg = hourglass(n, f, r1) local output = Residual(f,numOut)(hg) local network = nn.gModule({input}, {output}) network.name = 'AE_medium' return network end ------------------------------------------------------------------------------------------------------------ local function AE_large(n, numIn, numOut, f) ---- local feat_inc = 128 --96 local function hourglass(n, f, inp) -- Upper branch local up1 = Residual(f,f+feat_inc)(inp) local up2 = Residual(f+feat_inc,f+feat_inc)(up1) local up4 = Residual(f+feat_inc,f)(up2) -- Lower branch local low1 = Residual(f,f+feat_inc, 'D')(inp) local low2 = Residual(f+feat_inc,f+feat_inc)(low1) local low5 = Residual(f+feat_inc,f+feat_inc)(low2) local low6 if n > 1 then low6 = hourglass(n-1,f+feat_inc,low5) else low6 = Residual(f+feat_inc,f+feat_inc)(low5) end local up5 = Residual(f+feat_inc,f, 'U')(low6) -- Bring two branches together return nn.CAddTable()({up4,up5}) end ---- local input = nn.Identity()() local r1 = Residual(numIn,f)(input) local hg = hourglass(n, f, r1) local output = Residual(f,numOut)(hg) local network = nn.gModule({input}, {output}) network.name = 'AE_large' return network end ------------------------------------------------------------------------------------------------------------ local function lin(numIn,numOut) -- Apply 1x1 convolution, stride 1, no padding return nn.Sequential() :add(nn.SpatialConvolution(numIn,numOut,1,1,1,1,0,0)) :add(nn.SpatialBatchNormalization(numOut)) :add(relu()) end ------------------------------------------------------------------------------------------------------------ local function createModel() local input = nn.Identity()() -- Initial processing of the image local cnv1 = nn.Sequential() :add(nn.SpatialConvolution(3,64,7,7,2,2,3,3)) -- 128 :add(nn.SpatialBatchNormalization(64)) :add(relu())(input) local r1 = Residual(64,128, 'D')(cnv1) -- 64 local r2 = Residual(128,128)(r1) local r3 = Residual(128,128)(r2) local r4 = Residual(128,256)(r3) -------------------------------------------------------------------------------- -- Small Auto-Encoder Network -------------------------------------------------------------------------------- local autoencoder_s = AE_small(4, 256, 512, 128) -- small AE local autoencoder_s_out = autoencoder_s(r4) -- Linear layers to produce first set of predictions local l1_s = lin(512,512)(autoencoder_s_out) local l2_s = lin(512,512)(l1_s) -- First predicted heatmaps (small AE) local out_s = nn.SpatialConvolution(512,outputDim[1][1],1,1,1,1,0,0)(l2_s) local out_s_ = nn.SpatialConvolution(outputDim[1][1],256,1,1,1,1,0,0)(out_s) -- Concatenate with previous linear features local cat1 = nn.JoinTable(2)({l2_s,r1}) local cat1_ = nn.SpatialConvolution(512+128,256,1,1,1,1,0,0)(cat1) local int1 = nn.CAddTable()({cat1_,out_s_}) -------------------------------------------------------------------------------- -- Medium Auto-Encoder Network -------------------------------------------------------------------------------- local autoencoder_m = AE_medium(5, 256, 512, 256) -- medium AE local autoencoder_m_out = autoencoder_m(int1) -- Linear layers to produce the second set of predictions local l1_m = lin(512,512)(autoencoder_m_out) local l2_m = lin(512,512)(l1_m) -- Second predicted heatmaps (small AE) local out_m = nn.SpatialConvolution(512,outputDim[1][1],1,1,1,1,0,0)(l2_m) local out_m_ = nn.SpatialConvolution(outputDim[1][1],512,1,1,1,1,0,0)(out_m) -- Concatenate with previous linear features local cat2 = nn.JoinTable(2)({l2_m,r1}) local cat2_ = nn.SpatialConvolution(512+128,512,1,1,1,1,0,0)(cat2) local int2 = nn.CAddTable()({cat2_,out_m_}) -------------------------------------------------------------------------------- -- Large Auto-Encoder Network -------------------------------------------------------------------------------- local autoencoder_l = AE_large(6, 512, 512+256, 256+128) -- large AE local autoencoder_l_out = autoencoder_l(int2) -- Linear layers to produce the second set of predictions local l1_l = lin(512+256,512+256)(autoencoder_l_out) local l2_l = lin(512+256,512+256)(l1_l) -- Second predicted heatmaps (small AE) local out_l = nn.SpatialConvolution(512+256,outputDim[1][1],1,1,1,1,0,0)(l2_l) beautify_modules({ ae_small = autoencoder_s_out, ae_medium = autoencoder_m_out, ae_large = autoencoder_l_out, lin = {l1_s, l2_s, l1_m, l2_m, l1_l, l2_l}, out = {out_s, out_m, out_l} }) -- Final model --local out_s_up = nn.SpatialUpSamplingNearest(4)(out_s) -- local out_m_up = nn.SpatialUpSamplingNearest(2)(out_m) local model = nn.gModule({input}, {out_s, out_m, out_l}) return model end ------------------------------------------------------------------------------------------------------------ return createModel
mit
Quenty/NevermoreEngine
src/httppromise/src/Server/HttpPromise.lua
1
3237
--[=[ Provides a wrapper around HttpService with a promise API By combining functions in HttpPromise, we can get a generic request result in a very clean way. ```lua local function logToDiscord(body) return HttpPromise.request({ Headers = { ["Content-Type"] = "application/json"; }; Url = DISCORD_LOG_URL; Body = HttpService:JSONEncode(data); Method = "POST"; }) :Then(HttpPromise.decodeJson) :Catch(HttpPromise.logFailedRequests) end ``` @server @class HttpPromise ]=] local require = require(script.Parent.loader).load(script) local HttpService = game:GetService("HttpService") local Promise = require("Promise") local DEBUG_REQUEST = false local DEBUG_RESPONSE = false local HttpPromise = {} --[=[ Decodes JSON from the response ```lua local requestPromise = HttpPromise.request({ Headers = { ["Content-Type"] = "application/json"; }; Url = DISCORD_LOG_URL; Body = HttpService:JSONEncode(data); Method = "POST"; }) ``` @param request table @return Promise<table> ]=] function HttpPromise.request(request) if DEBUG_REQUEST then print("Sending request", HttpService:JSONEncode(request)) end return Promise.spawn(function(resolve, reject) local response local ok, err = pcall(function() response = HttpService:RequestAsync(request) end) if DEBUG_RESPONSE then print(("Response: %d %s %s"):format(response.StatusCode, request.Method, request.Url), response.Body) end if not ok then reject(err) return end if not response.Success then reject(response) return end resolve(response) return end) end --[=[ Makes a GET JSON request and then expects JSON as a result from said request ```lua HttpPromise.json("https://quenty.org/banned/4397833/status") :Then(print) ``` @param request table | string @return Promise<table> ]=] function HttpPromise.json(request) if type(request) == "string" then request = { Method = "GET"; Url = request; } end return HttpPromise.request(request) :Then(HttpPromise.decodeJson) end --[=[ Logs failed requests and any errors retrieved ```lua HttpPromise.json("https://quenty.org/banned/4397833/status") :Catch(HttpPromise.logFailedRequests) ``` @param ... any -- A list of requests to retrieve. Meant to be used ]=] function HttpPromise.logFailedRequests(...) for _, item in pairs({...}) do if type(item) == "string" then warn(item) elseif type(item) == "table" and type(item.StatusCode) == "number" then warn(("Failed request %d %q"):format(item.StatusCode, tostring(item.Body))) end end end --[=[ Decodes JSON from the response @param response { Body: string } @return table ]=] function HttpPromise.decodeJson(response) assert(response, "Bad response") if type(response.Body) ~= "string" then return Promise.rejected(("Body is not of type string, but says %q"):format(tostring(response.Body))) end return Promise.new(function(resolve, reject) local decoded local ok, err = pcall(function() decoded = HttpService:JSONDecode(response.Body) end) if not ok then reject(err) return elseif decoded then resolve(decoded) return else reject("decoded nothing") return end end) end return HttpPromise
mit
AfuSensi/Mr.Green-MTA-Resources
resources/[gameplay]/-shaders-contrast/c_rtpool.lua
12
2366
-- -- c_rtpool.lua -- scx, scy = guiGetScreenSize () ----------------------------------------------------------------------------------- -- Pool of render targets ----------------------------------------------------------------------------------- RTPool = {} RTPool.list = {} function RTPool.frameStart() for rt,info in pairs(RTPool.list) do info.bInUse = false end end function RTPool.GetUnused( sx, sy ) -- Find unused existing for rt,info in pairs(RTPool.list) do if not info.bInUse and info.sx == sx and info.sy == sy then info.bInUse = true return rt end end -- Add new -- outputDebugString( "creating new RT " .. tostring(sx) .. " x " .. tostring(sx) ) local rt = dxCreateRenderTarget( sx, sy ) if rt then RTPool.list[rt] = { bInUse = true, sx = sx, sy = sy } end return rt end function RTPool.clear() for rt,info in pairs(RTPool.list) do destroyElement(rt) end RTPool.list = {} end ----------------------------------------------------------------------------------- -- DebugResults -- Store all the rendertarget results for debugging ----------------------------------------------------------------------------------- DebugResults = {} DebugResults.items = {} function DebugResults.frameStart() DebugResults.items = {} end function DebugResults.addItem( rt, label ) table.insert( DebugResults.items, { rt=rt, label=label } ) end function DebugResults.drawItems( sizeX, sliderX, sliderY ) local posX = 5 local gapX = 4 local sizeY = sizeX * 90 / 140 local textSizeY = 15 + 10 local posY = 5 local textColor = tocolor(0,255,0,255) local textShad = tocolor(0,0,0,255) local numImages = #DebugResults.items local totalWidth = numImages * sizeX + (numImages-1) * gapX local totalHeight = sizeY + textSizeY posX = posX - (totalWidth - (scx-10)) * sliderX / 100 posY = posY - (totalHeight - scy) * sliderY / 100 local textY = posY+sizeY+1 for index,item in ipairs(DebugResults.items) do dxDrawImage( posX, posY, sizeX, sizeY, item.rt ) local sizeLabel = string.format( "%d) %s %dx%d", index, item.label, dxGetMaterialSize( item.rt ) ) dxDrawText( sizeLabel, posX+1.0, textY+1, posX+sizeX+1.0, textY+16, textShad, 1, "arial", "center", "top", true ) dxDrawText( sizeLabel, posX, textY, posX+sizeX, textY+15, textColor, 1, "arial", "center", "top", true ) posX = posX + sizeX + gapX end end
mit
ffxiphoenix/darkstar
scripts/zones/Port_San_dOria/npcs/Bellue.lua
36
1372
----------------------------------- -- Area: Port San d'Oria -- NPC: Bellue -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x255); 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
azekillDIABLO/Voxellar
mods/MAPGEN/mg_villages/name_gen.lua
3
3491
namegen = {}; namegen.prefixes = {'ac','ast','lang','pen','shep','ship'} namegen.suffixes = {'beck','ey','ay','bury','burgh','brough','by','by','caster', 'cester','cum','den','don','field','firth','ford','ham','ham','ham', 'hope','ing','kirk','hill','law','leigh','mouth','ness','pool','shaw', 'stead','ster','tun','ton','ton','ton','ton','wold','worth','worthy', 'ville','river','forrest','lake'} -- people/environmental features namegen.silben = { 'a', 'an', 'ab', 'ac', 'am', 'be', 'ba', 'bi', 'bl', 'bm', 'bn', 'bo', 'br', 'bst', 'bu', 'ca', 'ce', 'ch', 'ci', 'ck', 'cl', 'cm', 'cn', 'co', 'cv', 'da', 'de', 'df', 'di', 'dl', 'dm', 'dn', 'do', 'dr', 'ds', 'dt', 'du', 'dv', 'do','ren','nav','ben','ada','min','org','san','pa','re','ne','en','er','ich', 'the','and','tha','ent','ing','ion','tio','for','nde', 'has','nce','edt','tis','oft','sth','mem', 'ich','ein','und','der','nde','sch','die','den','end','cht', 'the','and','tha','ent','ing','ion','for','de', 'has','ce','ed','is','ft','sth','mem', 'ch','ei','un','der','ie','den','end', 'do','ren','nav','ben','ada','min','org','san','pa','re','ne','en','er','ich', 'ta','bek','nik','le','lan','nem', 'bal','cir','da','en','fan','fir','fern','fa','oak','nut','gen','ga','hu','hi','hal', 'in','ig','ir','im','ja','je','jo','kla','kon','ker','log','lag','leg','lil', 'lon','las','leve','lere','mes','mir','mon','mm','mer','mig', 'na','nn','nerv','neu','oto','on','opt','oll','ome','ott', 'pen','par','pi','pa','po','pel','pig','qu','ren','rig','raf','res','ring', 'rib','rast','rost','ru','rum','rem','sem','sim','su','spring', 'cotton','cot','wood','palm', 'do','na','ik','ke','gen','bra','bn','lla','lle','st','aa','kir', 'nn','en','fo','fn','gi','ja','jn','ke','kr','kon','lis','on','ok','or','op', 'pp','p','qu','re','ra','rn','ri','so','sn','se','ti','tu', 'a','e','i','o','u', 're','ro','pe','pn','ci','co','cl', 'no','en','wi','we','er','en','ba','ki','nn','va','wu','x','tel','or', 'so','me','mi','em','en','eg','ge','kn'}; namegen.generate_village_name = function( pr ) local anz_silben = pr:next(2,5); local name = ''; local prefix = ''; local postfix = ''; if( pr:next(1,8)==1) then prefix = namegen.prefixes[ #namegen.prefixes ]; anz_silben = anz_silben -1; end if( pr:next(1,4)==1) then postfix = name..namegen.suffixes[ #namegen.suffixes ]; anz_silben = anz_silben -2; end if( anz_silben < 2 ) then anz_silben = 2; end for i = 1, anz_silben do name = name..namegen.silben[ pr:next( 1, #namegen.silben )]; end name = prefix..name..postfix; name = string.upper( string.sub( name, 1, 1 ) )..string.sub( name, 2 ); return name; end namegen.generate_village_name_with_prefix = function( pr, village ) local name = namegen.generate_village_name( pr ); -- if a village consists of a single house, it gets a prefix depending on the house type if( village.is_single_house and village.to_add_data and village.to_add_data.bpos ) then -- the building got removed from mg_villages.BUILDINGS in the meantime if( not( mg_villages.BUILDINGS[ village.to_add_data.bpos[1].btype] )) then return 'Abandomed building'; end local btyp = mg_villages.BUILDINGS[ village.to_add_data.bpos[1].btype].typ; local bdata = mg_villages.village_type_data[ btyp ]; if( bdata and (bdata.name_prefix or bdata.name_postfix )) then name = (bdata.name_prefix or '')..name..(bdata.name_postfix or ''); else name = 'House '..name; end end return name; end
lgpl-2.1
ffxiphoenix/darkstar
scripts/globals/items/blowfish.lua
18
1257
----------------------------------------- -- ID: 5812 -- Item: Blowfish -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 1 -- Mind -3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5812); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 3); target:addMod(MOD_MND, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 3); target:delMod(MOD_MND, -5); end;
gpl-3.0
hewei-chn/resurgence
lib/proxy/auto-config.lua
6
6670
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2012, 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%$ --]] --- -- automatic configure of modules -- -- SHOW CONFIG module("proxy.auto-config", package.seeall) local l = require("lpeg") --- -- local function parse_value(fld, token) local t = type(fld) local errmsg if t == "boolean" then if token[1] == "boolean" then return token[2] == "true" and true and false else return nil, "(auto-config) expected a boolean, got " .. token[1] end elseif t == "number" then if token[1] == "number" then return tonumber(token[2]) else return nil, "(auto-config) expected a number, got " .. token[1] end elseif t == "string" then if token[1] == "string" then return tostring(token[2]) else return nil, "(auto-config) expected a string, got " .. token[1] end else return nil, "(auto-config) type: " .. t .. " isn't handled yet" end return nil, "(auto-config) should not be reached" end --- -- transform a table into loadable string local function tbl2str(tbl, indent) local s = "" indent = indent or "" -- set a default for k, v in pairs(tbl) do s = s .. indent .. ("[%q] --[[%s]]-- = "):format(k, type(k)) if type(v) == "table" then s = s .. "{\n" .. tbl2str(v, indent .. " ") .. indent .. "}" elseif type(v) == "string" then s = s .. ("%q"):format(v) else s = s .. tostring(v) end s = s .. ",\n" end return s end --- -- turn a string into a case-insensitive lpeg-pattern -- local function lpeg_ci_str(s) local p for i = 1, #s do local c = s:sub(i, i) local lp = l.S(c:upper() .. c:lower() ) if p then p = p * lp else p = lp end end return p end local WS = l.S(" \t\n") local PROXY = lpeg_ci_str("PROXY") * WS^1 local SHOW = lpeg_ci_str("SHOW") * WS^1 local SET = lpeg_ci_str("SET") * WS^1 local GLOBAL = lpeg_ci_str("GLOBAL") * WS^1 local CONFIG = lpeg_ci_str("CONFIG") local SAVE = lpeg_ci_str("SAVE") * WS^1 local LOAD = lpeg_ci_str("LOAD") * WS^1 local INTO = lpeg_ci_str("INTO") * WS^1 local FROM = lpeg_ci_str("FROM") * WS^1 local DOT = l.P(".") local EQ = WS^0 * l.P("=") * WS^0 local literal = l.R("az", "AZ") ^ 1 local string_quoted = l.P("\"") * ( 1 - l.P("\"") )^0 * l.P("\"") -- /".*"/ local digit = l.R("09") -- [0-9] local number = (l.P("-") + "") * digit^1 -- [0-9]+ local bool = l.P("true") + l.P("false") local l_proxy = l.Ct(PROXY * ((SHOW / "SHOW" * CONFIG) + (SET / "SET" * GLOBAL * l.C(literal) * DOT * l.C(literal) * EQ * l.Ct( l.Cc("string") * l.C(string_quoted) + l.Cc("number") * l.C(number) + l.Cc("boolean") * l.C(bool) )) + (SAVE / "SAVE" * CONFIG * WS^1 * INTO * l.C(string_quoted)) + (LOAD / "LOAD" * CONFIG * WS^1 * FROM * l.C(string_quoted))) * -1) function handle(tbl, cmd) --- -- support old, deprecated API: -- -- auto_config.handle(cmd) -- -- and map it to -- -- proxy.global.config:handle(cmd) if cmd == nil and tbl.type and type(tbl.type) == "number" then cmd = tbl tbl = proxy.global.config end -- handle script-options first if cmd.type ~= proxy.COM_QUERY then return nil end -- don't try to tokenize log SQL queries if #cmd.query > 128 then return nil end local tokens = l_proxy:match(cmd.query) if not tokens then return nil end -- print(tbl2str(tokens)) if tokens[1] == "SET" then if not tbl[tokens[2]] then proxy.response = { type = proxy.MYSQLD_PACKET_ERR, errmsg = "module not known" } elseif not tbl[tokens[2]][tokens[3]] then proxy.response = { type = proxy.MYSQLD_PACKET_ERR, errmsg = "option not know" } else -- do the assignment local val, errmsg = parse_value(tbl[tokens[2]][tokens[3]], tokens[4]) if not val then proxy.response = { type = proxy.MYSQLD_PACKET_ERR, errmsg = errmsg } else tbl[tokens[2]][tokens[3]] = val proxy.response = { type = proxy.MYSQLD_PACKET_OK, affected_rows = 1 } end end elseif tokens[1] == "SHOW" then local rows = { } for mod, options in pairs(tbl) do for option, val in pairs(options) do rows[#rows + 1] = { mod, option, tostring(val), type(val) } end end proxy.response = { type = proxy.MYSQLD_PACKET_OK, resultset = { fields = { { name = "module", type = proxy.MYSQL_TYPE_STRING }, { name = "option", type = proxy.MYSQL_TYPE_STRING }, { name = "value", type = proxy.MYSQL_TYPE_STRING }, { name = "type", type = proxy.MYSQL_TYPE_STRING }, }, rows = rows } } elseif tokens[1] == "SAVE" then -- save the config into this filename local filename = tokens[2] local ret, errmsg = tbl:save(filename) if ret then proxy.response = { type = proxy.MYSQLD_PACKET_OK, affected_rows = 0 } else proxy.response = { type = proxy.MYSQLD_PACKET_ERR, errmsg = errmsg } end elseif tokens[1] == "LOAD" then local filename = tokens[2] local ret, errmsg = tbl:load(filename) if ret then proxy.response = { type = proxy.MYSQLD_PACKET_OK, affected_rows = 0 } else proxy.response = { type = proxy.MYSQLD_PACKET_ERR, errmsg = errmsg } end else assert(false) end return proxy.PROXY_SEND_RESULT end function save(tbl, filename) local content = "return {\n" .. tbl2str(tbl, " ") .. "}" local file, errmsg = io.open(filename, "w") if not file then return false, errmsg end file:write(content) return true end function load(tbl, filename) local func, errmsg = loadfile(filename) if not func then return false, errmsg end local v = func() for mod, options in pairs(v) do if tbl[mod] then -- weave the loaded options in for option, value in pairs(options) do tbl[mod][option] = value end else tbl[mod] = options end end return true end local mt = getmetatable(proxy.global.config) or {} mt.__index = { handle = handle, load = load, save = save } setmetatable(proxy.global.config, mt)
gpl-2.0
ostinelli/gin
spec/spec/runners/integration_spec.lua
4
6179
require 'spec.spec_helper' describe("Integration", function() before_each(function() IntegrationRunner = require 'gin.spec.runners.integration' end) after_each(function() package.loaded['gin.spec.runners.integration'] = nil IntegrationRunner = nil end) describe(".encode_table", function() it("encodes a table into querystring params", function() args = { arg1 = 1.0, arg2 = { "two/string", "another/string" }, ['arg~3'] = "a tag", [5] = "five" } local urlencoded = IntegrationRunner.encode_table(args) assert.are.equal(67, #urlencoded) local amppos = urlencoded:find("&", 6, true) assert.is.number(amppos) amppos = urlencoded:find("&", 1 + amppos, true) assert.is.number(amppos) amppos = urlencoded:find("&", 1 + amppos, true) assert.is.number(amppos) amppos = urlencoded:find("&", 1 + amppos, true) assert.is.number(amppos) assert.is_nil(urlencoded:find("&", 1 + amppos, true)) assert.is_number(urlencoded:find("arg~3=a%20tag", 1, true)) assert.is_number(urlencoded:find("arg2=two%2fstring", 1, true)) assert.is_number(urlencoded:find("arg2=another%2fstring", 1, true)) assert.is_number(urlencoded:find("5=five", 1, true)) assert.is_number(urlencoded:find("arg1=1", 1, true)) end) end) describe(".hit", function() before_each(function() require 'gin.cli.launcher' stub(package.loaded['gin.cli.launcher'], "start") stub(package.loaded['gin.cli.launcher'], "stop") require 'socket.http' request = nil package.loaded['socket.http'].request = function(...) request = ... return true, 201, { ['Some-Header'] = 'some-header-value' } end local info IntegrationRunner.source_for_caller_at = function(...) return "/controllers/1/controller_spec.lua" end end) after_each(function() package.loaded['gin.cli.launcher'] = nil package.loaded['socket.http'] = nil request = nil end) it("ensures content length is set", function() IntegrationRunner.hit({ method = 'GET', path = "/", body = { name = 'gin' } }) assert.are.same(14, request.headers["Content-Length"]) end) it("raises an error when the caller major version cannot be retrieved", function() IntegrationRunner.source_for_caller_at = function(...) return "controller_spec.lua" end local ok, err = pcall(function() return IntegrationRunner.hit({ method = 'GET', path = "/" }) end) assert.are.equal(false, ok) assert.are.equal(true, string.find(err, "Could not determine API major version from controller spec file. Ensure to follow naming conventions") > 0) end) it("raises an error when the caller major version does not match the specified api_version", function() local ok, err = pcall(function() return IntegrationRunner.hit({ api_version = '2', method = 'GET', path = "/" }) end) assert.are.equal(false, ok) assert.are.equal(true, string.find(err, "Specified API version 2 does not match controller spec namespace %(1%)") > 0) end) describe("Accept header", function() describe("when no api_version is specified", function() it("sets the accept header from the namespace", function() local response = IntegrationRunner.hit({ method = 'GET', path = "/" }) assert.are.same("application/vnd.ginapp.v1+json", request.headers["Accept"]) end) end) describe("when a specifid api_version is specified", function() it("sets the accept header from the namespace", function() local response = IntegrationRunner.hit({ api_version = '1.2.3-p247', method = 'GET', path = "/" }) assert.are.same("application/vnd.ginapp.v1.2.3-p247+json", request.headers["Accept"]) end) end) end) it("calls the server with the correct parameters", function() local request_body_arg ltn12.source.string = function(request_body) request_body_arg = request_body return request_body end local request_body_arg ltn12.sink.table = function(request_body) request_body_arg = request_body return request_body end IntegrationRunner.hit({ method = 'GET', path = "/", headers = { ['Test-Header'] = 'test-header-value' }, body = { name = 'gin' } }) assert.are.equal("http://127.0.0.1:7201/?", request.url) assert.are.equal('GET', request.method) assert.are.same('test-header-value', request.headers['Test-Header']) assert.are.same('{"name":"gin"}', request.source) assert.are.same(request_body_arg, request.sink) end) it("returns a ResponseSpec", function() local response = IntegrationRunner.hit({ method = 'GET', path = "/" }) assert.are.equal(201, response.status) assert.are.same({ ['Some-Header'] = 'some-header-value' }, response.headers) end) end) end)
mit
AfuSensi/Mr.Green-MTA-Resources
resources/[gameplay]/gcshop/horns/horns_s.lua
3
7915
local price = 1500 local unlimitedUses = 5000 local canHornBeUsed = {} local howManyTimes = {} local newMap = nil local coolOffTimer = {} local coolOff = {} local keyTable = { "mouse1", "mouse2", "mouse3", "mouse4", "mouse5", "mouse_wheel_up", "mouse_wheel_down", "arrow_l", "arrow_u", "arrow_r", "arrow_d", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "num_0", "num_1", "num_2", "num_3", "num_4", "num_5", "num_6", "num_7", "num_8", "num_9", "num_mul", "num_add", "num_sep", "num_sub", "num_div", "num_dec", "num_enter", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10", "F11", "F12", "escape", "backspace", "tab", "lalt", "ralt", "enter", "space", "pgup", "pgdn", "end", "home", "insert", "delete", "lshift", "rshift", "lctrl", "rctrl", "[", "]", "pause", "capslock", "scroll", ";", ",", "-", ".", "/", "#", "\\", "=" } addEventHandler('onMapStarting', root, function() newMap = true end ) addEvent('onRaceStateChanging', true) addEventHandler('onRaceStateChanging', root, function(new) if (new == 'Running') and (newMap == true) then for i,j in ipairs(getElementsByType('player')) do canHornBeUsed[j] = true howManyTimes[j] = 0 end newMap = false end end ) addEvent("onGCShopLogout", true) addEventHandler("onGCShopLogout", root, function() triggerClientEvent(source, "hornsLogout", source) end ) addEvent("onGCShopLogin", true) addEventHandler("onGCShopLogin", root, function(forumid) local query = dbQuery(handlerConnect, "SELECT unlimited FROM gc_horns WHERE forumid = ?", forumid) local sql = dbPoll(query,-1) local unlimited = false if #sql >= 1 then if sql[1].unlimited == 1 then unlimited = true else unlimited = false end end triggerClientEvent(source, "hornsLogin", source, unlimited, forumid) end ) addEventHandler('onPlayerJoin', root, function() canHornBeUsed[source] = true howManyTimes[source] = 0 coolOff[source] = true end ) addEventHandler('onPlayerQuit', root, function() canHornBeUsed[source] = nil howManyTimes[source] = nil coolOff[source] = nil coolOffTimer[source] = nil end ) addEventHandler('onResourceStart', resourceRoot, function() for i,j in ipairs(getElementsByType('player')) do canHornBeUsed[j] = true howManyTimes[j] = 0 coolOff[j] = true end end ) function useHorn(player, arg1, arg2, hornID) if (canHornBeUsed[player]) and (coolOff[player] == true) and (isPedInVehicle(player)) and (not isVehicleBlown(getPedOccupiedVehicle(player))) and (getElementHealth(getPedOccupiedVehicle(player)) > 250) and (getElementData(player, "state") == "alive") then local logged = exports.gc:isPlayerLoggedInGC(player) if logged then local forumid = exports.gc:getPlayerForumID(player) forumid = tostring(forumid) if tonumber(hornID or arg2) then local query = dbQuery(handlerConnect, "SELECT horns, unlimited FROM gc_horns WHERE forumid = ?", forumid) local sql = dbPoll(query,-1) if #sql > 0 then local allHorns = split(sql[1].horns, string.byte(',')) local useHorn = false for i,j in ipairs(allHorns) do if tonumber(j) == tonumber(hornID or arg2) then useHorn = true break end end if not useHorn then outputChatBox("Please buy the horn (".. tostring(hornID or arg2) ..") first before using it",player,255,0,0) return end local car = getPedOccupiedVehicle(player) coolOffTimer[player] = setTimer(function(player) coolOff[player] = true end, 10000, 1, player) triggerClientEvent("onPlayerUsingHorn", player, hornID or arg2, car) coolOff[player] = false howManyTimes[player] = howManyTimes[player] + 1 if sql[1].unlimited == 1 then howManyTimes[player] = 0 end if howManyTimes[player] == 3 then canHornBeUsed[player] = false end end else outputChatBox("Something went wrong",player,255,0,0) end end end end addCommandHandler("gchorn",useHorn) addEvent("bindHorn", true) addEventHandler("bindHorn", root, function(key, hornID, hornName) if not isKeyBound(client, key, "down", useHorn) then bindKey(client, key, "down", useHorn, hornID) end end ) addEvent("unbindHorn", true) addEventHandler("unbindHorn", root, function(key) unbindKey(client, key, "down", useHorn) end ) addEvent("unbindAllHorns", true) addEventHandler("unbindAllHorns", root, function() for i=1, #keyTable do unbindKey(client, keyTable[i], "down", useHorn) end end ) addEvent('onPlayerBuyUnlimitedHorn', true) addEventHandler('onPlayerBuyUnlimitedHorn', root, function() local logged = exports.gc:isPlayerLoggedInGC(source) if logged then local forumid = exports.gc:getPlayerForumID(source) forumid = tostring(forumid) local query = dbQuery(handlerConnect, "SELECT unlimited FROM gc_horns WHERE forumid = ?", forumid) local sql = dbPoll(query,-1) if #sql > 0 then if sql[1].unlimited == 1 then outputChatBox("You already have unlimited horn usage.", source) return else local money = exports.gc:getPlayerGreencoins(source) if money >= unlimitedUses then local ok = gcshopBuyItem ( source, unlimitedUses, 'Unlimited horns' ) if ok then local result = dbExec(handlerConnect, "UPDATE gc_horns SET unlimited=? WHERE forumid=?", 1, forumid) outputChatBox("You have bought unlimited horn usage for 5000 GC.", source) triggerClientEvent(source, 'onClientSuccessBuyUnlimitedUsage', source, true) addToLog ( '"' .. getPlayerName(source) .. '" (' .. tostring(forumid) .. ') bought Unlimited horns ' .. tostring(result)) end else outputChatBox("You do not have enough GreenCoins", source) end end else outputChatBox("You have no horns bought.", source) end else outputChatBox("You are not logged in GreenCoins", source) end end ) addEvent('onPlayerBuyHorn', true) addEventHandler('onPlayerBuyHorn', root, function(horn) local logged = exports.gc:isPlayerLoggedInGC(source) if logged then local forumid = exports.gc:getPlayerForumID(source) forumid = tostring(forumid) local query = dbQuery(handlerConnect, "SELECT horns FROM gc_horns WHERE forumid = ?", forumid) local sql = dbPoll(query,-1) if #sql > 0 then local allHorns = split(sql[1].horns, string.byte(',')) for i,j in ipairs(allHorns) do if j == tostring(horn) then triggerClientEvent(source, 'onClientSuccessBuyHorn', source, false) return end end end local money = exports.gc:getPlayerGreencoins(source) if money >= price then local ok = gcshopBuyItem ( source, price, 'Horn:' .. horn) if ok then local result if #sql == 0 then result = dbExec(handlerConnect, "INSERT INTO gc_horns (forumid,horns) VALUES (?,?)", forumid, tostring(horn)) else local hornString = sql[1].horns..","..tostring(horn) result = dbExec(handlerConnect, "UPDATE gc_horns SET horns=? WHERE forumid=?", hornString, forumid) end triggerClientEvent(source, 'onClientSuccessBuyHorn', source, true, horn) addToLog ( '"' .. getPlayerName(source) .. '" (' .. tostring(forumid) .. ') bought horn=' .. tostring(horn) .. ' ' .. tostring(result)) end else triggerClientEvent(source, 'onClientSuccessBuyHorn', source, false, nil) end else triggerClientEvent(source, 'onClientSuccessBuyHorn', source, false) end end ) addEvent('getHornsData', true) addEventHandler('getHornsData', root, function() local logged = exports.gc:isPlayerLoggedInGC(source) if logged then local forumid = exports.gc:getPlayerForumID(source) forumid = tostring(forumid) local query = dbQuery(handlerConnect, "SELECT horns FROM gc_horns WHERE forumid = ?", forumid) local sql = dbPoll(query,-1) if #sql > 0 then local allHorns = split(sql[1].horns, string.byte(',')) triggerClientEvent(source, 'sendHornsData', source, allHorns) end end end )
mit
Ne02ptzero/Grog-Knight
Tools/BuildScripts/lua-lib/penlight-1.0.2/tests/test-set.lua
10
3233
class = require 'pl.class' M = require 'pl.Map' S = require 'pl.Set' List = require 'pl.List' asserteq = require 'pl.test' . asserteq asserteq2 = require 'pl.test' . asserteq2 MultiMap = require 'pl.MultiMap' OrderedMap = require 'pl.OrderedMap' s1 = S{1,2} s2 = S{1,2} -- equality asserteq(s1,s2) -- union asserteq(S{1,2} + S{2,3},S{1,2,3}) -- intersection asserteq(S{1,2} * S{2,3}, S{2}) -- symmetric_difference asserteq(S{1,2} ^ S{2,3}, S{1,3}) m = M{one=1,two=2} asserteq(m,M{one=1,two=2}) m:update {three=3,four=4} asserteq(m,M{one=1,two=2,three=3,four=4}) class.Animal() function Animal:_init(name) self.name = name end function Animal:__tostring() return self.name..': '..self:speak() end class.Dog(Animal) function Dog:speak() return 'bark' end class.Cat(Animal) function Cat:_init(name,breed) self:super(name) -- must init base! self.breed = breed end function Cat:speak() return 'meow' end Lion = class(Cat) function Lion:speak() return 'roar' end fido = Dog('Fido') felix = Cat('Felix','Tabby') leo = Lion('Leo','African') asserteq(tostring(fido),'Fido: bark') asserteq(tostring(felix),'Felix: meow') asserteq(tostring(leo),'Leo: roar') assert(Dog:class_of(fido)) assert(fido:is_a(Dog)) assert(leo:is_a(Animal)) m = MultiMap() m:set('john',1) m:set('jane',3) m:set('john',2) ms = MultiMap{john={1,2},jane={3}} asserteq(m,ms) m = OrderedMap() m:set('one',1) m:set('two',2) m:set('three',3) asserteq(m:values(),List{1,2,3}) -- usually exercized like this: --for k,v in m:iter() do print(k,v) end fn = m:iter() asserteq2 ('one',1,fn()) asserteq2 ('two',2,fn()) asserteq2 ('three',3,fn()) o1 = OrderedMap {{z=2},{beta=1},{name='fred'}} asserteq(tostring(o1),'{z=2,beta=1,name="fred"}') -- order of keys is not preserved here! o2 = OrderedMap {z=4,beta=1.1,name='alice',extra='dolly'} o1:update(o2) asserteq(tostring(o1),'{z=4,beta=1.1,name="alice",extra="dolly"}') o1:set('beta',nil) asserteq(o1,OrderedMap{{z=4},{name='alice'},{extra='dolly'}}) o3 = OrderedMap() o3:set('dog',10) o3:set('cat',20) o3:set('mouse',30) asserteq(o3:keys(),{'dog','cat','mouse'}) o3:set('dog',nil) asserteq(o3:keys(),{'cat','mouse'}) -- Vadim found a problem when clearing a key which did not exist already. -- The keys list would then contain the key, although the map would not o3:set('lizard',nil) asserteq(o3:keys(),{'cat','mouse'}) asserteq(o3:values(), {20,30}) asserteq(tostring(o3),'{cat=20,mouse=30}') -- copy constructor o4 = OrderedMap(o3) asserteq(o4,o3) -- constructor throws an error if the argument is bad -- (errors same as OrderedMap:update) asserteq(false,pcall(function() m = OrderedMap('string') end)) ---- changing order of key/value pairs ---- o3 = OrderedMap{{cat=20},{mouse=30}} o3:insert(1,'bird',5) -- adds key/value before specified position o3:insert(1,'mouse') -- moves key keeping old value asserteq(o3:keys(),{'mouse','bird','cat'}) asserteq(tostring(o3),'{mouse=30,bird=5,cat=20}') o3:insert(2,'cat',21) -- moves key and sets new value asserteq(tostring(o3),'{mouse=30,cat=21,bird=5}') -- if you don't specify a value for an unknown key, nothing happens to the map o3:insert(3,'alligator') asserteq(tostring(o3),'{mouse=30,cat=21,bird=5}')
apache-2.0
ffxiphoenix/darkstar
scripts/globals/spells/raiton_ni.lua
17
1255
----------------------------------------- -- Spell: Raiton: Ni -- Deals lightning damage to an enemy and lowers its resistance against earth. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) local duration = 15 + caster:getMerit(MERIT_RAITON_EFFECT) -- T1 bonus debuff duration local bonusAcc = 0; local bonusMab = caster:getMerit(MERIT_RAITON_EFFECT) + caster:getMod(MOD_NIN_NUKE_BONUS); -- T1 mag atk + "enhances Ninjustu damage" mod if (caster:isBehind(target,15) and caster:hasStatusEffect(EFFECT_INNIN)) then -- Innin mag atk bonus from behind, guesstimating angle at 15 degrees bonusMab = bonusMab + caster:getStatusEffect(EFFECT_INNIN):getPower(); end local dmg = doNinjutsuNuke(68,1,caster,spell,target,false,bonusAcc,bonusMab); handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_EARTHRES); return dmg; end;
gpl-3.0
hughperkins/cltorch
src/test/test-tensor.lua
1
23607
-- this is mostly for trying things -- for unit tests, see cltorch-unit-tensor.lua print("running require cltorch...") require 'cltorch' print("... require cltorch done") print(cltorch.getDeviceProperties(cltorch.getDevice()).deviceName) if os.getenv('TRACE') ~= nil then cltorch.setTrace(1) end if false then a = torch.Tensor{3,5,2} print('a\n', a) c = torch.ClTensor{7,4,5} print('c1\n', c) c = torch.ClTensor(3,2) print('c2\n', c) a = torch.Tensor{2,6,9} c = a:cl() print('c3\n', c) b = c:float() print('b\n', b) c = torch.ClTensor{{3,1,6},{2.1,5.2,3.9}} print('c4', c) d = torch.ClTensor(2,3) print('d', d) d:copy(c) print('d2', d) b = torch.Tensor{{4,2,-2},{3.1,1.2,4.9}} b[1][2] = 2.123 print('b2\n', b) --c = torch.ClTensor{{4,2,-2},{3.1,1.2,4.9}} --c[1][2] = 2.123 --print('c5\n', c) b[1][2] = 5.432 c:copy(b) print('c6\n', c) print('collect garbage') collectgarbage() -- ============================= d = torch.ClTensor{{3,5,-2},{2.1,2.2,3.9}} c = torch.ClTensor{{4,2,-1},{3.1,1.2,4.9}} c:add(d) print('c2\n', c) a = c:float() b = d:float() a:cmul(b) print('a', a) c:cmul(d) print('c2\n', c) c:cdiv(d) print('c2\n', c) c = c + d print('c3\n', c) c = c - d print('c3\n', c) c:abs() print('c3\n', c) c:sqrt() print('c3\n', c) for _,name in ipairs({'log','exp', 'cos', 'acos', 'sin', 'asin', 'atan', 'tanh', 'ceil', 'floor', 'abs', 'round'}) do print('name', name) c = torch.ClTensor{{4,2,-1},{3.1,1.2,4.9}} loadstring('c:' .. name .. '()')() print('c3\n', c) end collectgarbage() end if false then c = c:float() d = d:float() c[2][1] = d[2][1] c[1][2] = d[1][2] c = c:cl() d = d:cl() for _,name in ipairs({'lt','le','gt','ge','ne','eq'}) do print('name', name) print(loadstring('return torch.' .. name .. '(c,d)')()) end print('c\n', c) print('torch.add', torch.add(c,3)) c:add(3) print('c\n', c) c:mul(3) print('c\n', c) c:div(2) print('c\n', c) c = torch.mul(c, 4) print('c\n', c) c = torch.div(c, 3) print('c\n', c) c = c / 2 print('c\n', c) c = c * 1.5 print('c\n', c) c = c + 4 print('c\n', c) c = c - 5 print('c\n', c) for _,name in ipairs({'lt','le','gt','ge','ne','eq'}) do print('name', name) print(loadstring('return c:' .. name .. '(5)')()) end print('c\n', c) print(torch.pow(2,c)) c:pow(2) print('c\n', c) print(torch.pow(c,2)) print('c\n', c) print(torch.clamp(c, 50, 100)) c:clamp(50, 100) print('c\n', c) print(torch.cpow(c,d)) print(torch.cdiv(c,d)) print(-c) collectgarbage() -- print(c:t()) end if false then A = torch.ClTensor{{1,2,-1}, {3,4,0}} B = torch.ClTensor{{0,1}, {1,2}, {4,5}} print('A\n', A) print('B\n', B) print(torch.mm(A,B)) end if false then print(torch.mm(A:float(), B:float())) C = torch.ClTensor{{0,0},{0,0}} C:mm(A,B) print(C) print( A * B ) C:fill(1.345) print('C\n', C) s = torch.LongStorage{3,2} print('s\n', s) --C = cltorch.ones(s) --print('C\n', C) C:zero() print('C\n', C) --C:reshape({4,1}) --print('C\n', C) end if false then v1 = torch.ClTensor{3,5,1} v2 = torch.ClTensor{2,4,8} --print(v1 * v2) print(torch.dot(v1,v2)) fv1 = torch.FloatTensor{3,5,1} fv2 = torch.FloatTensor{2,4,8} print(fv1*fv2) print(torch.dot(v1,v2)) print(torch.ClTensor.zeros(torch.ClTensor.new(), 3, 5)) print(torch.ClTensor.ones(torch.ClTensor.new(), 3, 5)) -- print(torch.ClTensor.eye(torch.ClTensor.new(), 3)) -- print(torch.ClTensor.diag(torch.ClTensor{{3,5,4},{2,3,4},{7,6,5}})) print(torch.mv(A,v1)) end collectgarbage() ------------------- if false then A = torch.ClTensor{{3,5,2},{4,5,6}} print('A\n', A) print('A:sum()', A:sum()) end print(torch.Tensor.__eq) function torch.Tensor.__eq(self, b) print('self', self) diff = self:ne(b) print('diff', diff) sum = diff:sum() print('sum', sum) if sum == 0 then return true else return false end end function torch.ClTensor.__eq(self, b) print('self', self) diff = self:ne(b) print('diff', diff) sum = diff:sum() print('sum', sum) if sum == 0 then return true else return false end end --print(torch.Tensor({3,5,2}) == torch.Tensor({3,5,2})) --print(torch.Tensor({{3,5,2},{4,5,6}}) == torch.Tensor({{3,5,2},{4,5,6}})) if false then print(torch.ClTensor({{3,5,2},{4,5,6}}) == torch.ClTensor({{3,5,2},{4,5,6}})) --print('end') end if false then A = torch.ClTensor{{3,2,4},{9,7,5}} print('A\n', A) print('A:sum(2)', A:sum(2)) print('A:sum(1)', A:sum(1)) print('A:max()', A:max()) print('A:min()', A:min()) print('torch.max(A,1)', torch.max(A,1)) print('torch.max(A,2)', torch.max(A,2)) end if false then c = torch.ClTensor{3,5,2} print('torch.isTensor(c)', torch.isTensor(c)) print('c:nDimension()', c:nDimension()) C = torch.ClTensor{{3,2,4},{9,7,5}} print('C:nDimension()', C:nDimension()) print('c:dim()', C:dim()) print('C:size()', C:size()) print('C:size(1)', C:size(1)) print('C:size(2)', C:size(2)) print('#C', #C) print('C:stride()', C:stride()) print('C:stride(1)', C:stride(1)) print('C:stride(2)', C:stride(2)) print('C:storage()', C:storage()) print('C:nElement()', C:nElement()) print('C:storageOffset()', C:storageOffset()) end if false then c = torch.ClTensor{{3,1,6},{2.1,5.2,3.9}} c:fill(1.345) print('c\n', c) c:zero() print('c\n', c) c:resize(3,2) print('c\n', c) c:resize(2,2) print('c\n', c) c:resize(2,4) print('c\n', c) l = torch.LongStorage{3,3} c:resize(l) print('c\n', c) d = torch.ClTensor(2,2) print('d\n', d) d:resizeAs(c) print('d\n', d) end if false then C = torch.ClTensor{{3,2,4},{9,7,5}} A = C:float() print('C\n', C) D = C:reshape(3,2) print('D\n', D) B = A:reshape(3,2) print('B\n', B) print('C\n', C) print(C:t()) end if false then C = torch.ClTensor{{3,2},{9,7}} D = torch.ClTensor{{3,1,7},{3,2,4}} E = torch.ClTensor{{3,1},{2,9},{3,2}} print(torch.addmm(C,D,E)) c = torch.ClTensor{3,2} D = torch.ClTensor{{3,1,7},{3,2,4}} e = torch.ClTensor{3,1,2} print(torch.addmv(c,D,e)) C = torch.ClTensor{{3,1,7},{3,2,4},{8,5,3}} d = torch.ClTensor{3,2,5} e = torch.ClTensor{3,1,2} print(torch.addr(C,d,e)) print(torch.addr(C:float(), d:float(), e:float())) end collectgarbage() if false then E = torch.ClTensor{{3,1},{2,9},{3,2},{7,8},{6,4}} print('E\n', E) F = E:narrow(1,2,3) print('F\n', F) F:fill(7) print('F\n', F) print('E\n', E) E = torch.ClTensor{{3,1},{2,9},{3,2},{7,8},{6,4}} print('E\n', E) F = E:sub(2,3,2,2) print('F\n', F) F:fill(0) print('F\n', F) print('E\n', E) E = torch.ClTensor{{3,1},{2,9},{3,2},{7,8},{6,4}} print('E\n', E) F = E:select(1,2):fill(99) print('F\n', F) print('E\n', E) x = torch.ClTensor(5, 6):zero() print('x\n', x) x[{ 2,{2,4} }] = 2 print('x\n', x) x[{ {},4 }] = -1 print('x\n', x) x[{ {},2 }] = torch.range(1,5) print('x\n', x) x[torch.lt(x,0)] = -2 print('x\n', x) end collectgarbage() if false then -- bias:fill(0.1) -- addBuffer:fill(0.1) -- bias = torch.ClTensor{0.1, -0.2} -- output = torch.ClTensor() -- weight = torch.ClTensor{{0.2, -0.2, 0.3}, -- {0.4,-0.1, -0.5}} -- output:resize(bias:size(1)) -- print('bias', bias) -- print('bias.storage', bias:storage()) -- output:addr(1,addBuffer,bias) ---- self.output:addr(1, self.addBuffer, self.bias) -- print('output\n', output) A = torch.Tensor(5,3):uniform() B = torch.Tensor(5,3):uniform() print('Res', torch.cmul(A,B)) Acl = A:clone():cl() Bcl = B:clone():cl() print('tocl done') rescl = torch.cmul(Acl, Bcl) print('cmul done') print('ResCl', rescl) print('pow', torch.pow(A,2)) print('pow cl', torch.pow(A:clone():cl(),2)) print('- op', - A) print('- op', - A:clone():cl()) Aclneg = A:clone():cl() Aclneg:neg() print('Aclneg', Aclneg) print('torch.add(A,B)', torch.add(A,B)) Acladd = A:clone():cl() Acladd:add(B:clone():cl()) print('Acladd', Acladd) print('A-B', A - B) Aclsub = A:clone():cl() Aclsub:csub(B:clone():cl()) print('Aclsub', Aclsub) addBuffer = torch.Tensor(128):fill(0.1):cl() bias = torch.Tensor(10):fill(0.1):cl() output = torch.Tensor(128,10):fill(0.1):cl() C = torch.ClTensor(128,10) D = torch.ClTensor(128,10) print('docalcs') C:fill(3) D:fill(1) res = C - D -- print(C - D) end collectgarbage() if false then A = torch.Tensor(3,2):uniform() print('A\n', A) A:apply(function(x) return x + 3 end) print('A\n', A) C = A:clone():cl() print('C\n', C) C:apply("*out = sqrt(*out + 3.5)") print('C\n', C) A = torch.Tensor(3,2):uniform() B = torch.Tensor(3,2):uniform() print('A\n', A) print('B\n', B) Acopy = A:clone() Acopy:map(B, function(a, b) return 1000 * a + b * 10 end) print('A\n', Acopy) Acl = A:clone():cl() Bcl = B:clone():cl() Acopycl = Acl:clone() Acopycl:map(Bcl, "*out = 1000 * *out + *in1 * 10") print('Acopycl\n', Acopycl) A = torch.Tensor(3,2):uniform() B = torch.Tensor(3,2):uniform() C = torch.Tensor(3,2):uniform() print('A\n', A) print('B\n', B) print('C\n', C) Acopy = A:clone() Acopy:map2(B, C, function(a, b, c) return 1000 * a + 100 * b + c * 10 end) print('A\n', Acopy) Acl = A:clone():cl() Bcl = B:clone():cl() Ccl = C:clone():cl() Acopycl = Acl:clone() Acopycl:map2(Bcl, Ccl, "*out = 1000 * *out + 100 * *in1 + *in2 * 10") print('Acopycl\n', Acopycl) A = torch.Tensor(28*28*1280,10):uniform() -- A:fill(2.5) print(A[100][5]) A = A + 2 print(A[100][5]) print(torch.sum(A)) Acl = A:clone():cl() print('torch.sum(Acl)\n', torch.sum(Acl)) end collectgarbage() if false then A = torch.Tensor(3,2):uniform() -- A = torch.Tensor{3} print('torch.norm(A)', torch.norm(A)) Acl = A:cl() print('torch.norm(Acl)', torch.norm(Acl)) print('torch.norm(A, 1)', torch.norm(A, 1)) print('torch.norm(Acl, 1)', torch.norm(Acl, 1)) print('torch.norm(A, 0)', torch.norm(A, 0)) print('torch.norm(Acl, 0)', torch.norm(Acl, 0)) print('torch.numel(A)', torch.numel(A)) print('torch.numel(Acl)', torch.numel(Acl)) -- print('torch.trace(A)', torch.trace(A)) -- print('torch.trace(Acl)', torch.trace(Acl)) Aclt = Acl:t() print('Aclt', Aclt) print('Acl.transpose(1,2)', Acl:transpose(1,2)) print('torch.prod(A)', torch.prod(A)) print('torch.prod(Acl)', torch.prod(Acl)) collectgarbage() local s = torch.LongStorage{5,2} local A = torch.Tensor(s):uniform() - 0.5 local Acl = A:cl() local Amax, Aind = A:max(2) local Aclmax, Aclind = Acl:max(2) print('A max', Amax, Aind) print('Acl max', Aclmax, Aclind) collectgarbage() print('after gc') local s = torch.LongStorage{5,4} local A = torch.Tensor(s):uniform() - 0.5 local Acl = A:cl() local Amax, Aind = A:min(2) local Aclmax, Aclind = Acl:min(2) print('A min', Amax, Aind) print('Acl min', Aclmax, Aclind) -- print('Aind:select(2,1)', Aind:select(2,1)) -- print('A', A) -- print('A:gather(2, Aind)', A:gather(2, Aind)) -- print('Acl:gather(2, Aclind)', Acl:gather(2, Aclind)) A = torch.Tensor{{1,1,1},{1,1,1}} A2 = torch.Tensor{{1,1,0},{1,1,1}} A3 = torch.Tensor{{0,1,0},{0,0,0}} A4 = torch.Tensor{{0,0,0},{0,0,0}} print('torch.all(A)', torch.all(A:byte())) print('torch.all(A2:byte())', torch.all(A2:byte())) print('torch.all(A:cl())', torch.all(A:cl())) print('torch.all(A2:cl())', torch.all(A2:cl())) print('torch.any(A:cl())', torch.any(A:cl())) print('torch.any(A2:cl())', torch.any(A2:cl())) print('torch.any(A3:cl())', torch.any(A3:cl())) print('torch.any(A4:cl())', torch.any(A4:cl())) collectgarbage() x = torch.Tensor(5,5):uniform():cl() print('x', x) z = torch.ClTensor(5,2) z:select(2,1):fill(-1) z:select(2,2):fill(-2) print('z', z) x:indexCopy(2,torch.LongTensor{5,1},z) print('x', x) collectgarbage() A = torch.Tensor{{3,1,7},{3,2,4}} print('A', A) Afill = A:clone() Afill:indexFill(2, torch.LongTensor{1,3}, -12) print('Afill', Afill) Afillcl = A:cl() Afillcl:indexFill(2, torch.LongTensor{1,3}, -12) print('Afillcl', Afillcl) x = torch.Tensor(5,6):zero():cl() print('x', x) y = x:select(1, 2):fill(2) -- select row 2 and fill up print('y', y) print('x', x) z = x:select(2,5):fill(5) -- select column 5 and fill up print('z', z) print('x', x) x = torch.Tensor(5,5):uniform():cl() print('x', x) z = torch.ClTensor(5,2) z:select(2,1):fill(-1) z:select(2,2):fill(-2) print('z', z) x:indexCopy(2,torch.LongTensor{5,1},z) print('x', x) x = torch.rand(5,5):cl() print('x', x) y = x:index(1,torch.LongTensor{3,1}) print('y', y) y:fill(1) print('y', y) print('x', x) x = torch.range(1,4):double():resize(1,4):cl() print('x', x) mask = torch.ByteTensor(2,2):bernoulli():cl() print('mask', mask) x:maskedFill(mask, -1) print('x', x) A = torch.Tensor{{3,1,7},{3,2,4}} print('A', A) print('torch.cumsum(A, 2)\n', torch.cumsum(A, 2)) print('A', A) print('torch.cumsum(A:cl(), 2)\n', torch.cumsum(A:cl(), 2)) print('torch.cumsum(A:cl(), 1)\n', torch.cumsum(A:cl(), 1)) print('torch.cumprod(A, 2)\n', torch.cumprod(A, 2)) print('A', A) print('torch.cumprod(A:cl(), 2)\n', torch.cumprod(A:cl(), 2)) -- print('torch.cumsum(A:cl(), 2)\n', torch.cumsum(A:cl(), 2)) print('torch.cumprod(A, 1)\n', torch.cumprod(A, 1)) print('torch.cumprod(A:cl(), 1)\n', torch.cumprod(A:cl(), 1)) end if false then a = torch.Tensor(5,4) a:copy(torch.range(1, a:nElement())) acl = a:clone():cl() print('a', a) print('a:narrow(1,2,2)', a:narrow(1,2,2)) print('a:narrow(1,2,2):sum(1)', a:narrow(1,2,2):sum(1)) print('acl:narrow(1,2,2)', acl:narrow(1,2,2)) print('acl:narrow(1,2,2):sum(1)', acl:narrow(1,2,2):sum(1)) print('a:narrow(1,2,2):t()', a:narrow(1,2,2):t()) print('a:narrow(1,2,2):t():sum(1)', a:narrow(1,2,2):t():sum(1)) print('acl:narrow(1,2,2):t()', acl:narrow(1,2,2):t()) print('acl:narrow(1,2,2):t():sum(1)', acl:narrow(1,2,2):t():sum(1)) print('a:narrow(1,2,2):t():sum()', a:narrow(1,2,2):t():sum()) print('acl:narrow(1,2,2):t():sum()', acl:narrow(1,2,2):t():sum()) print('a:narrow(1,2,2):t():sum(2)', a:narrow(1,2,2):t():sum(2)) print('acl:narrow(1,2,2):t():sum(2)', acl:narrow(1,2,2):t():sum(2)) x = torch.Tensor(6,5):uniform() - 0.5 xcopy = x:clone() print('xcopy:select(1, 2)', xcopy:select(1, 2)) xcopy:select(1, 2):fill(2) -- select row 2 and fill up print('xcopy:select(1, 2)', xcopy:select(1, 2)) xcopy:select(2, 5):fill(5) -- select column 5 and fill up print('xcopy', xcopy) xcopycl = x:clone():cl() print('xcopycl', xcopycl) local sel = xcopycl:select(1, 2) print('sel', sel) sel:fill(2) print('sel:storageOffset()', sel:storageOffset()) print('sel:stride()', sel:stride()) print('sel:size()', sel:size()) print('sel', sel) -- local sel = xcopycl:select(1, 2):fill(2) -- select row 2 and fill up print('xcopycl:select(1, 2)', xcopycl:select(1, 2)) -- print('xcopycl:select(1, 2)', xcopycl:select(1, 2)) -- xcopycl:select(2, 5):fill(5) -- select column 5 and fill up print('xcopycl', xcopycl) a = torch.Tensor(3,4) a:copy(torch.range(1,a:nElement())) print('a', a) idx = torch.LongTensor({{2,1,3,1}}) print('idx', idx) print('a:gather(1, idx)', a:gather(1, idx)) idx = torch.LongTensor({{2},{4},{1}}) print('idx', idx) print('a:gather(2, idx)', a:gather(2, idx)) a = torch.Tensor(3,4) a:copy(torch.range(1,a:nElement())) print('a', a) acl = a:clone():cl() idx = torch.LongTensor({{2,1,3,1}}) idxcl = idx:clone():cl() print('idxcl', idxcl) res = acl:clone():fill(-1) --torch.gather(res, acl, 1, idxcl) print('res', res) -- print('gather cl', torch.gather(acl, 1, idxcl)) print('a:gather(1, idx)', a:gather(1, idx)) print('torch.gather(1, idxcl)', torch.gather(acl, 1, idxcl)) print('acl:gather(1, idxcl)', acl:gather(1, idxcl)) a = torch.ClTensor({{3,5,2}}):t() print('a', a) print('expanding...') b = torch.expand(a, 3, 2) print('...expanded') -- print(torch.expand(a,3,2)) -- b = a:expand(3, 2) print('b', b) a:copy(torch.Tensor{7,2,1}) print('b', b) c = torch.ClTensor(3, 4) c:copy(torch.range(1, c:nElement())) print('c', c) print('expanding...') b = torch.expandAs(a, c) print('...expanded') print('b', b) reptarget = torch.ClTensor(3, 4):fill(-1) print('reptarget', reptarget) -- print('after b resize') print('a\n', a) d = a:repeatTensor(1, 4) print('a:repeatTensor(1,4)\n', d) print('before repeat') reptarget:repeatTensor(a, 1, 4) print('after repeatTensor') print('reptarget', reptarget) print('a\n', a) as = a:squeeze() print('after squeeze') print('as\n', as) end if false then x = torch.Tensor(2,5) x = x:copy(torch.range(1, x:nElement())):cl() print('x\n', x) y = torch.zeros(3,5):cl() idx = torch.LongTensor{{1,2,3,1,1},{3,1,1,2,3}}:cl() z = y:scatter(1, idx, x) print('z\n', z) y = torch.zeros(3,5):cl() idx = torch.LongTensor{{1,2,3,1,1},{3,1,1,2,3}}:cl() z = y:scatter(1, idx, 3.4567) print('z\n', z) c = torch.ClTensor(4, 7) print('c\n', c) c:bernoulli() print('c\n', c) c:bernoulli(0.1) print('c\n', c) c:uniform() print('c\n', c) end local function eval(expression) loadstring('res=' .. expression)() print(expression, res) end if false then if cltorch.getDeviceCount() >= 2 then -- Switch to dedicated GPU. Everything breaks if we uncomment those lines. cltorch.setDevice(2) cltorch.synchronize() cltorch.finish() -- not sure this line is needed print('Current device: ', cltorch.getDevice()) -- this prints out, but then hangs. -- Things print out properly on the integrated GPU (device(1)) C = torch.ClTensor{{3,2,4},{9,7,5}} print(C:t()) print(C:transpose(1,2)) eval('cltorch.getDeviceCount()') eval('cltorch.getDevice()') b = torch.ClTensor({3,5,2}) eval('b') eval('cltorch.setDevice(1)') eval('cltorch.getDevice()') a = torch.ClTensor({2,4,7}) eval('a') eval('a:add(2)') eval('cltorch.setDevice(2)') eval('b:add(2)') eval('a:add(2)') eval('cltorch.setDevice(1)') eval('b:add(2)') eval('b:sum()') b = torch.ClTensor({{3,5,2},{4,7,8}}) eval('b:sum(1)') eval('b:sum(2)') end end if os.getenv('PROTOTYPING') ~= nil then cltorch.setDevice(cltorch.getDeviceCount()) local s = torch.LongStorage{60,50} local A = torch.Tensor(s):uniform() - 0.5 local B = torch.Tensor(s):uniform() - 0.5 local C = torch.Tensor(s):uniform() - 0.5 local res = A:cl():addcmul(1.234,B:cl(), C:cl()) -- tester:asserteq(torch.addcmul(A,1.234,B,C), torch.addcmul(A:clone():cl(), 1.234, B:clone():cl(), C:clone():cl()):double()) -- tester:asserteq(A:clone():addcmul(1.234,B,C), (A:clone():cl():addcmul(1.234, B:clone():cl(),C:clone():cl())):double()) c = torch.ClTensor{{4, 2, -1}, {3.1,1.2, 4.9}} res = c - 3.4 c = torch.ClTensor{{4, 2, -1}, {3.1,1.2, 4.9}} torch.div(c, 3.4) a = torch.ClTensor(20,30):uniform() b = torch.ClTensor() b:sum(a) print('b\n', b) print('a:sum()\n', a:sum()) print('--------') a = torch.ClTensor(torch.LongStorage()) print('a\n', a) -- print('a[1]\n', a[1]) a_fl = torch.Storage(1) a_fl:copy(a:storage()) print('a_fl', a_fl) a = torch.ClTensor(torch.LongStorage()) a:sum(torch.ClTensor({3,5,3})) print('a\n', a) a_float = torch.Storage(1) a_float:copy(a:storage()) print('a_fl', a_float) print('a:s()', a:s()) c = torch.ClTensor(3,4):uniform() print('c\n', c) print('c:clone():div(10)\n', c:clone():div(11)) print('c:clone():div(a)\n', c:clone():div(a)) c = torch.ClTensor(3,4):uniform() a = c:clone() a_sum = a:sum() print('a:div(a_sum)', a:div(a_sum)) c_sum = torch.ClTensor() c_sum:sum(c) print('c:div(c_sum)', c:div(c_sum)) print('c_sum', c_sum) print('c:mul(c_sum)', c:mul(c_sum)) print('a:mul(a_sum)', a:mul(a_sum)) print('c:add(c_sum)', c:add(c_sum)) print('a:add(a_sum)', a:add(a_sum)) print('c:csub(c_sum)', c:csub(c_sum)) print('a:add(-a_sum)', a:add(-a_sum)) c = torch.ClTensor{{4, 2, -1}, {0.8,1.2, 1.9}} d = torch.ClTensor{{3, 5, -2}, {2.1,2.2, 0.9}} a = c:float() b = d:float() op = 'add' loadstring('a:' .. op .. '(b)')() loadstring('c:' .. op .. '(d)')() print('a\n', a) print('c\n', c) c = torch.ClTensor(3,4):uniform() res = torch.ClTensor() res:prod(c) print('res', res) print('c:prod()', c:prod()) res:min(c) print('res', res) print('c:min()', c:min()) res:max(c) print('res', res) print('c:max()', c:max()) c = torch.ClTensor({0,0,0}) res:all(c) print('res', res) res:any(c) print('res', res) c = torch.ClTensor({0,0,1}) res:all(c) print('res', res) res:any(c) print('res', res) c = torch.ClTensor({1,1,1}) res:all(c) print('res', res) res:any(c) print('res', res) c:fill(res) print('c', c) res:sum(c) c:fill(res) print('c', c) c = torch.ClTensor({1,3,2,5,4,6}) a = torch.ClTensor() a:sum(torch.ClTensor({2})) a_s = a:s() print('a', a, 'a_s', a_s) for _,name in pairs({'lt', 'gt', 'eq', 'ne', 'ge', 'le'}) do c = torch.ClTensor({1,3,2,5,4,6}) c_clone = c:clone() loadstring('c_clone = c_clone:' .. name .. '(a_s)')() print(name .. ' c_clone', c_clone) loadstring('c = c:' .. name .. '(a)')() print(name .. ' c', c) end local x = torch.Tensor(60,50):uniform() - 0.5 xcopy = x:clone() xcopy:select(1, 2):fill(2) -- select row 2 and fill up xcopy:select(2, 5):fill(5) -- select column 5 and fill up xcopycl = x:cl() xcopycl:select(1, 2):fill(2) -- select row 2 and fill up xcopycl:select(2, 5):fill(5) -- select column 5 and fill up -- x = torch.range(1,12):double():resize(3,4):cl() -- print('x', x) -- mask = torch.ByteTensor(2,6):bernoulli():cl() -- print('mask', mask) -- y = x:maskedSelect(mask) -- print('y', y) -- z = torch.DoubleTensor():cl() -- z:maskedSelect(x, mask) -- print('z', z) -- x = torch.range(1,8):double():resize(1,8) -- print('x', x) -- mask = torch.ByteTensor(1,8):bernoulli() -- print('mask', mask) -- y = torch.DoubleTensor(2,4):fill(0) -- print('y', y) -- y:maskedCopy(mask, x) -- print('y', y) -- x = torch.range(1,8):double():resize(1,8):cl() -- print('x', x) -- mask = torch.ByteTensor(1,8):bernoulli():cl() -- print('mask', mask) -- y = torch.DoubleTensor(2,4):fill(0):cl() -- print('y', y) -- y:maskedCopy(mask, x) -- print('y', y) -- x = torch.ClTensor(5, 6):zero() -- myprint('x\n', x) -- x[{ 1,3 }] = 1 -- myprint('x\n', x) -- x[{ 2,{2,4} }] = 2 -- myprint('x\n', x) -- x[{ {},4 }] = -1 -- myprint('x\n', x) -- print('create range...') -- myrange = torch.range(1,5) -- print('...done') -- x[{ {},2 }] = myrange -- myprint('x\n', x) -- x = torch.range(1,12):double():resize(3,4):cl() -- print('x\n', x) -- mask = torch.ByteTensor(2,6):bernoulli():cl() -- print('mask\n', mask) -- y = x:maskedSelect(mask) -- print('y\n', y) -- z = torch.ClTensor() -- z:maskedSelect(x, mask) -- print('z\n', z) end collectgarbage() if os.getenv('TRACE') ~= nil then cltorch.setTrace(0) end
bsd-3-clause
fusedl/ardupilot
Tools/CHDK-Scripts/kap_uav.lua
183
28512
--[[ KAP UAV Exposure Control Script v3.1 -- Released under GPL by waterwingz and wayback/peabody http://chdk.wikia.com/wiki/KAP_%26_UAV_Exposure_Control_Script @title KAP UAV 3.1 @param i Shot Interval (sec) @default i 15 @range i 2 120 @param s Total Shots (0=infinite) @default s 0 @range s 0 10000 @param j Power off when done? @default j 0 @range j 0 1 @param e Exposure Comp (stops) @default e 6 @values e -2.0 -1.66 -1.33 -1.0 -0.66 -0.33 0.0 0.33 0.66 1.00 1.33 1.66 2.00 @param d Start Delay Time (sec) @default d 0 @range d 0 10000 @param y Tv Min (sec) @default y 0 @values y None 1/60 1/100 1/200 1/400 1/640 @param t Target Tv (sec) @default t 5 @values t 1/100 1/200 1/400 1/640 1/800 1/1000 1/1250 1/1600 1/2000 @param x Tv Max (sec) @default x 3 @values x 1/1000 1/1250 1/1600 1/2000 1/5000 1/10000 @param f Av Low(f-stop) @default f 4 @values f 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0 @param a Av Target (f-stop) @default a 7 @values a 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0 @param m Av Max (f-stop) @default m 13 @values m 1.8 2.0 2.2 2.6 2.8 3.2 3.5 4.0 4.5 5.0 5.6 6.3 7.1 8.0 @param p ISO Min @default p 1 @values p 80 100 200 400 800 1250 1600 @param q ISO Max1 @default q 2 @values q 100 200 400 800 1250 1600 @param r ISO Max2 @default r 3 @values r 100 200 400 800 1250 1600 @param n Allow use of ND filter? @default n 1 @values n No Yes @param z Zoom position @default z 0 @values z Off 0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100% @param c Focus @ Infinity Mode @default c 0 @values c None @Shot AFL MF @param v Video Interleave (shots) @default v 0 @values v Off 1 5 10 25 50 100 @param w Video Duration (sec) @default w 10 @range w 5 300 @param u USB Shot Control? @default u 0 @values u None On/Off OneShot PWM @param b Backlight Off? @default b 0 @range b 0 1 @param l Logging @default l 3 @values l Off Screen SDCard Both --]] props=require("propcase") capmode=require("capmode") -- convert user parameter to usable variable names and values tv_table = { -320, 576, 640, 736, 832, 896, 928, 960, 992, 1024, 1056, 1180, 1276} tv96target = tv_table[t+3] tv96max = tv_table[x+8] tv96min = tv_table[y+1] sv_table = { 381, 411, 507, 603, 699, 761, 795 } sv96min = sv_table[p+1] sv96max1 = sv_table[q+2] sv96max2 = sv_table[r+2] av_table = { 171, 192, 218, 265, 285, 322, 347, 384, 417, 446, 477, 510, 543, 576 } av96target = av_table[a+1] av96minimum = av_table[f+1] av96max = av_table[m+1] ec96adjust = (e - 6)*32 video_table = { 0, 1, 5, 10, 25, 50, 100 } video_mode = video_table[v+1] video_duration = w interval = i*1000 max_shots = s poff_if_done = j start_delay = d backlight = b log_mode= l focus_mode = c usb_mode = u if ( z==0 ) then zoom_setpoint = nil else zoom_setpoint = (z-1)*10 end -- initial configuration values nd96offset=3*96 -- ND filter's number of equivalent f-stops (f * 96) infx = 50000 -- focus lock distance in mm (approximately 55 yards) shot_count = 0 -- shot counter blite_timer = 300 -- backlight off delay in 100mSec increments old_console_timeout = get_config_value( 297 ) shot_request = false -- pwm mode flag to request a shot be taken -- check camera Av configuration ( variable aperture and/or ND filter ) if n==0 then -- use of nd filter allowed? if get_nd_present()==1 then -- check for ND filter only Av_mode = 0 -- 0 = ND disabled and no iris available else Av_mode = 1 -- 1 = ND disabled and iris available end else Av_mode = get_nd_present()+1 -- 1 = iris only , 2=ND filter only, 3= both ND & iris end function printf(...) if ( log_mode == 0) then return end local str=string.format(...) if (( log_mode == 1) or (log_mode == 3)) then print(str) end if ( log_mode > 1 ) then local logname="A/KAP.log" log=io.open(logname,"a") log:write(os.date("%Y%b%d %X ")..string.format(...),"\n") log:close() end end tv_ref = { -- note : tv_ref values set 1/2 way between shutter speed values -608, -560, -528, -496, -464, -432, -400, -368, -336, -304, -272, -240, -208, -176, -144, -112, -80, -48, -16, 16, 48, 80, 112, 144, 176, 208, 240, 272, 304, 336, 368, 400, 432, 464, 496, 528, 560, 592, 624, 656, 688, 720, 752, 784, 816, 848, 880, 912, 944, 976, 1008, 1040, 1072, 1096, 1129, 1169, 1192, 1225, 1265, 1376 } tv_str = { ">64", "64", "50", "40", "32", "25", "20", "16", "12", "10", "8.0", "6.0", "5.0", "4.0", "3.2", "2.5", "2.0", "1.6", "1.3", "1.0", "0.8", "0.6", "0.5", "0.4", "0.3", "1/4", "1/5", "1/6", "1/8", "1/10", "1/13", "1/15", "1/20", "1/25", "1/30", "1/40", "1/50", "1/60", "1/80", "1/100", "1/125", "1/160", "1/200", "1/250", "1/320", "1/400", "1/500", "1/640", "1/800", "1/1000","1/1250", "1/1600","1/2000","1/2500","1/3200","1/4000","1/5000","1/6400","1/8000","1/10000","hi" } function print_tv(val) if ( val == nil ) then return("-") end local i = 1 while (i <= #tv_ref) and (val > tv_ref[i]) do i=i+1 end return tv_str[i] end av_ref = { 160, 176, 208, 243, 275, 304, 336, 368, 400, 432, 464, 480, 496, 512, 544, 592, 624, 656, 688, 720, 752, 784 } av_str = {"n/a","1.8", "2.0","2.2","2.6","2.8","3.2","3.5","4.0","4.5","5.0","5.6","5.9","6.3","7.1","8.0","9.0","10.0","11.0","13.0","14.0","16.0","hi"} function print_av(val) if ( val == nil ) then return("-") end local i = 1 while (i <= #av_ref) and (val > av_ref[i]) do i=i+1 end return av_str[i] end sv_ref = { 370, 397, 424, 456, 492, 523, 555, 588, 619, 651, 684, 731, 779, 843, 907 } sv_str = {"n/a","80","100","120","160","200","250","320","400","500","640","800","1250","1600","3200","hi"} function print_sv(val) if ( val == nil ) then return("-") end local i = 1 while (i <= #sv_ref) and (val > sv_ref[i]) do i=i+1 end return sv_str[i] end function pline(message, line) -- print line function fg = 258 bg=259 end -- switch between shooting and playback modes function switch_mode( m ) if ( m == 1 ) then if ( get_mode() == false ) then set_record(1) -- switch to shooting mode while ( get_mode() == false ) do sleep(100) end sleep(1000) end else if ( get_mode() == true ) then set_record(0) -- switch to playback mode while ( get_mode() == true ) do sleep(100) end sleep(1000) end end end -- focus lock and unlock function lock_focus() if (focus_mode > 1) then -- focus mode requested ? if ( focus_mode == 2 ) then -- method 1 : set_aflock() command enables MF if (chdk_version==120) then set_aflock(1) set_prop(props.AF_LOCK,1) else set_aflock(1) end if (get_prop(props.AF_LOCK) == 1) then printf(" AFL enabled") else printf(" AFL failed ***") end else -- mf mode requested if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode if call_event_proc("SS.Create") ~= -1 then if call_event_proc("SS.MFOn") == -1 then call_event_proc("PT_MFOn") end elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then if call_event_proc("PT_MFOn") == -1 then call_event_proc("MFOn") end end if (get_prop(props.FOCUS_MODE) == 0 ) then -- MF not set - try levent PressSw1AndMF post_levent_for_npt("PressSw1AndMF") sleep(500) end elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf() if ( set_mf(1) == 0 ) then set_aflock(1) end -- as a fall back, try setting AFL is set_mf fails end if (get_prop(props.FOCUS_MODE) == 1) then printf(" MF enabled") else printf(" MF enable failed ***") end end sleep(1000) set_focus(infx) sleep(1000) end end function unlock_focus() if (focus_mode > 1) then -- focus mode requested ? if (focus_mode == 2 ) then -- method 1 : AFL if (chdk_version==120) then set_aflock(0) set_prop(props.AF_LOCK,0) else set_aflock(0) end if (get_prop(props.AF_LOCK) == 0) then printf(" AFL unlocked") else printf(" AFL unlock failed") end else -- mf mode requested if (chdk_version==120) then -- CHDK 1.2.0 : call event proc or levents to try and enable MF mode if call_event_proc("SS.Create") ~= -1 then if call_event_proc("SS.MFOff") == -1 then call_event_proc("PT_MFOff") end elseif call_event_proc("RegisterShootSeqEvent") ~= -1 then if call_event_proc("PT_MFOff") == -1 then call_event_proc("MFOff") end end if (get_prop(props.FOCUS_MODE) == 1 ) then -- MF not reset - try levent PressSw1AndMF post_levent_for_npt("PressSw1AndMF") sleep(500) end elseif (chdk_version >= 130) then -- CHDK 1.3.0 : set_mf() if ( set_mf(0) == 0 ) then set_aflock(0) end -- fall back so reset AFL is set_mf fails end if (get_prop(props.FOCUS_MODE) == 0) then printf(" MF disabled") else printf(" MF disable failed") end end sleep(100) end end -- zoom position function update_zoom(zpos) local count = 0 if(zpos ~= nil) then zstep=((get_zoom_steps()-1)*zpos)/100 printf("setting zoom to "..zpos.." percent step="..zstep) sleep(200) set_zoom(zstep) sleep(2000) press("shoot_half") repeat sleep(100) count = count + 1 until (get_shooting() == true ) or (count > 40 ) release("shoot_half") end end -- restore camera settings on shutdown function restore() set_config_value(121,0) -- USB remote disable set_config_value(297,old_console_timeout) -- restore console timeout value if (backlight==1) then set_lcd_display(1) end -- display on unlock_focus() if( zoom_setpoint ~= nil ) then update_zoom(0) end if( shot_count >= max_shots) and ( max_shots > 1) then if ( poff_if_done == 1 ) then -- did script ending because # of shots done ? printf("power off - shot count at limit") -- complete power down sleep(2000) post_levent_to_ui('PressPowerButton') else set_record(0) end -- just retract lens end end -- Video mode function check_video(shot) local capture_mode if ((video_mode>0) and(shot>0) and (shot%video_mode == 0)) then unlock_focus() printf("Video mode started. Button:"..tostring(video_button)) if( video_button ) then click "video" else capture_mode=capmode.get() capmode.set('VIDEO_STD') press("shoot_full") sleep(300) release("shoot_full") end local end_second = get_day_seconds() + video_duration repeat wait_click(500) until (is_key("menu")) or (get_day_seconds() > end_second) if( video_button ) then click "video" else press("shoot_full") sleep(300) release("shoot_full") capmode.set(capture_mode) end printf("Video mode finished.") sleep(1000) lock_focus() return(true) else return(false) end end -- PWM USB pulse functions function ch1up() printf(" * usb pulse = ch1up") shot_request = true end function ch1mid() printf(" * usb pulse = ch1mid") if ( get_mode() == false ) then switch_mode(1) lock_focus() end end function ch1down() printf(" * usb pulse = ch1down") switch_mode(0) end function ch2up() printf(" * usb pulse = ch2up") update_zoom(100) end function ch2mid() printf(" * usb pulse = ch2mid") if ( zoom_setpoint ~= nil ) then update_zoom(zoom_setpoint) else update_zoom(50) end end function ch2down() printf(" * usb pulse = ch2down") update_zoom(0) end function pwm_mode(pulse_width) if pulse_width > 0 then if pulse_width < 5 then ch1up() elseif pulse_width < 8 then ch1mid() elseif pulse_width < 11 then ch1down() elseif pulse_width < 14 then ch2up() elseif pulse_width < 17 then ch2mid() elseif pulse_width < 20 then ch2down() else printf(" * usb pulse width error") end end end -- Basic exposure calculation using shutter speed and ISO only -- called for Tv-only and ND-only cameras (cameras without an iris) function basic_tv_calc() tv96setpoint = tv96target av96setpoint = nil local min_av = get_prop(props.MIN_AV) -- calculate required ISO setting sv96setpoint = tv96setpoint + min_av - bv96meter -- low ambient light ? if (sv96setpoint > sv96max2 ) then -- check if required ISO setting is too high sv96setpoint = sv96max2 -- clamp at max2 ISO if so tv96setpoint = math.max(bv96meter+sv96setpoint-min_av,tv96min) -- recalculate required shutter speed down to Tv min -- high ambient light ? elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low sv96setpoint = sv96min -- clamp at minimum ISO setting if so tv96setpoint = bv96meter + sv96setpoint - min_av -- recalculate required shutter speed and hope for the best end end -- Basic exposure calculation using shutter speed, iris and ISO -- called for iris-only and "both" cameras (cameras with an iris & ND filter) function basic_iris_calc() tv96setpoint = tv96target av96setpoint = av96target -- calculate required ISO setting sv96setpoint = tv96setpoint + av96setpoint - bv96meter -- low ambient light ? if (sv96setpoint > sv96max1 ) then -- check if required ISO setting is too high sv96setpoint = sv96max1 -- clamp at first ISO limit av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting if ( av96setpoint < av96min ) then -- check if new setting is goes below lowest f-stop av96setpoint = av96min -- clamp at lowest f-stop sv96setpoint = tv96setpoint + av96setpoint - bv96meter -- recalculate ISO setting if (sv96setpoint > sv96max2 ) then -- check if the result is above max2 ISO sv96setpoint = sv96max2 -- clamp at highest ISO setting if so tv96setpoint = math.max(bv96meter+sv96setpoint-av96setpoint,tv96min) -- recalculate required shutter speed down to tv minimum end end -- high ambient light ? elseif (sv96setpoint < sv96min ) then -- check if required ISO setting is too low sv96setpoint = sv96min -- clamp at minimum ISO setting if so tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate required shutter speed if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast tv96setpoint = tv96max -- clamp at maximum shutter speed if so av96setpoint = bv96meter + sv96setpoint - tv96setpoint -- calculate new aperture setting if ( av96setpoint > av96max ) then -- check if new setting is goes above highest f-stop av96setpoint = av96max -- clamp at highest f-stop tv96setpoint = bv96meter + sv96setpoint - av96setpoint -- recalculate shutter speed needed and hope for the best end end end end -- calculate exposure for cams without adjustable iris or ND filter function exposure_Tv_only() insert_ND_filter = nil basic_tv_calc() end -- calculate exposure for cams with ND filter only function exposure_NDfilter() insert_ND_filter = false basic_tv_calc() if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast insert_ND_filter = true -- flag the ND filter to be inserted bv96meter = bv96meter - nd96offset -- adjust meter for ND offset basic_tv_calc() -- start over, but with new meter value bv96meter = bv96meter + nd96offset -- restore meter for later logging end end -- calculate exposure for cams with adjustable iris only function exposure_iris() insert_ND_filter = nil basic_iris_calc() end -- calculate exposure for cams with both adjustable iris and ND filter function exposure_both() insert_ND_filter = false -- NOTE : assume ND filter never used automatically by Canon firmware basic_iris_calc() if (tv96setpoint > tv96max ) then -- check if shutter speed now too fast insert_ND_filter = true -- flag the ND filter to be inserted bv96meter = bv96meter - nd96offset -- adjust meter for ND offset basic_iris_calc() -- start over, but with new meter value bv96meter = bv96meter + nd96offset -- restore meter for later logging end end -- ========================== Main Program ================================= set_console_layout(1 ,1, 45, 14 ) printf("KAP 3.1 started - press MENU to exit") bi=get_buildinfo() printf("%s %s-%s %s %s %s", bi.version, bi.build_number, bi.build_revision, bi.platform, bi.platsub, bi.build_date) chdk_version= tonumber(string.sub(bi.build_number,1,1))*100 + tonumber(string.sub(bi.build_number,3,3))*10 + tonumber(string.sub(bi.build_number,5,5)) if ( tonumber(bi.build_revision) > 0 ) then build = tonumber(bi.build_revision) else build = tonumber(string.match(bi.build_number,'-(%d+)$')) end if ((chdk_version<120) or ((chdk_version==120)and(build<3276)) or ((chdk_version==130)and(build<3383))) then printf("CHDK 1.2.0 build 3276 or higher required") else if( props.CONTINUOUS_AF == nil ) then caf=-999 else caf = get_prop(props.CONTINUOUS_AF) end if( props.SERVO_AF == nil ) then saf=-999 else saf = get_prop(props.SERVO_AF) end cmode = capmode.get_name() printf("Mode:%s,Continuous_AF:%d,Servo_AF:%d", cmode,caf,saf) printf(" Tv:"..print_tv(tv96target).." max:"..print_tv(tv96max).." min:"..print_tv(tv96min).." ecomp:"..(ec96adjust/96).."."..(math.abs(ec96adjust*10/96)%10) ) printf(" Av:"..print_av(av96target).." minAv:"..print_av(av96minimum).." maxAv:"..print_av(av96max) ) printf(" ISOmin:"..print_sv(sv96min).." ISO1:"..print_sv(sv96max1).." ISO2:"..print_sv(sv96max2) ) printf(" MF mode:"..focus_mode.." Video:"..video_mode.." USB:"..usb_mode) printf(" AvM:"..Av_mode.." int:"..(interval/1000).." Shts:"..max_shots.." Dly:"..start_delay.." B/L:"..backlight) sleep(500) if (start_delay > 0 ) then printf("entering start delay of ".. start_delay.." seconds") sleep( start_delay*1000 ) end -- enable USB remote in USB remote moded if (usb_mode > 0 ) then set_config_value(121,1) -- make sure USB remote is enabled if (get_usb_power(1) == 0) then -- can we start ? printf("waiting on USB signal") repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu"))) else sleep(1000) end printf("USB signal received") end -- switch to shooting mode switch_mode(1) -- set zoom position update_zoom(zoom_setpoint) -- lock focus at infinity lock_focus() -- disable flash and AF assist lamp set_prop(props.FLASH_MODE, 2) -- flash off set_prop(props.AF_ASSIST_BEAM,0) -- AF assist off if supported for this camera set_config_value( 297, 60) -- set console timeout to 60 seconds if (usb_mode > 2 ) then repeat until (get_usb_power(2) == 0 ) end -- flush pulse buffer next_shot_time = get_tick_count() script_exit = false if( get_video_button() == 1) then video_button = true else video_button = false end set_console_layout(2 ,0, 45, 4 ) repeat if( ( (usb_mode < 2 ) and ( next_shot_time <= get_tick_count() ) ) or ( (usb_mode == 2 ) and (get_usb_power(2) > 0 ) ) or ( (usb_mode == 3 ) and (shot_request == true ) ) ) then -- time to insert a video sequence ? if( check_video(shot_count) == true) then next_shot_time = get_tick_count() end -- intervalometer timing next_shot_time = next_shot_time + interval -- set focus at infinity ? (maybe redundant for AFL & MF mode but makes sure its set right) if (focus_mode > 0) then set_focus(infx) sleep(100) end -- check exposure local count = 0 local timeout = false press("shoot_half") repeat sleep(50) count = count + 1 if (count > 40 ) then timeout = true end until (get_shooting() == true ) or (timeout == true) -- shoot in auto mode if meter reading invalid, else calculate new desired exposure if ( timeout == true ) then release("shoot_half") repeat sleep(50) until get_shooting() == false shoot() -- shoot in Canon auto mode if we don't have a valid meter reading shot_count = shot_count + 1 printf(string.format('IMG_%04d.JPG',get_exp_count()).." : shot in auto mode, meter reading invalid") else -- get meter reading values (and add in exposure compensation) bv96raw=get_bv96() bv96meter=bv96raw-ec96adjust tv96meter=get_tv96() av96meter=get_av96() sv96meter=get_sv96() -- set minimum Av to larger of user input or current min for zoom setting av96min= math.max(av96minimum,get_prop(props.MIN_AV)) if (av96target < av96min) then av96target = av96min end -- calculate required setting for current ambient light conditions if (Av_mode == 1) then exposure_iris() elseif (Av_mode == 2) then exposure_NDfilter() elseif (Av_mode == 3) then exposure_both() else exposure_Tv_only() end -- set up all exposure overrides set_tv96_direct(tv96setpoint) set_sv96(sv96setpoint) if( av96setpoint ~= nil) then set_av96_direct(av96setpoint) end if(Av_mode > 1) and (insert_ND_filter == true) then -- ND filter available and needed? set_nd_filter(1) -- activate the ND filter nd_string="NDin" else set_nd_filter(2) -- make sure the ND filter does not activate nd_string="NDout" end -- and finally shoot the image press("shoot_full_only") sleep(100) release("shoot_full") repeat sleep(50) until get_shooting() == false shot_count = shot_count + 1 -- update shooting statistic and log as required shot_focus=get_focus() if(shot_focus ~= -1) and (shot_focus < 20000) then focus_string=" foc:"..(shot_focus/1000).."."..(((shot_focus%1000)+50)/100).."m" if(focus_mode>0) then error_string=" **WARNING : focus not at infinity**" end else focus_string=" foc:infinity" error_string=nil end printf(string.format('%d) IMG_%04d.JPG',shot_count,get_exp_count())) printf(" meter : Tv:".. print_tv(tv96meter) .." Av:".. print_av(av96meter) .." Sv:"..print_sv(sv96meter).." "..bv96raw ..":"..bv96meter) printf(" actual: Tv:".. print_tv(tv96setpoint).." Av:".. print_av(av96setpoint).." Sv:"..print_sv(sv96setpoint)) printf(" AvMin:".. print_av(av96min).." NDF:"..nd_string..focus_string ) if ((max_shots>0) and (shot_count >= max_shots)) then script_exit = true end shot_request = false -- reset shot request flag end collectgarbage() end -- check if USB remote enabled in intervalometer mode and USB power is off -> pause if so if ((usb_mode == 1 ) and (get_usb_power(1) == 0)) then printf("waiting on USB signal") unlock_focus() switch_mode(0) repeat wait_click(20) until ((get_usb_power(1) == 1) or ( is_key("menu"))) switch_mode(1) lock_focus() if ( is_key("menu")) then script_exit = true end printf("USB wait finished") sleep(100) end if (usb_mode == 3 ) then pwm_mode(get_usb_power(2)) end if (blite_timer > 0) then blite_timer = blite_timer-1 if ((blite_timer==0) and (backlight==1)) then set_lcd_display(0) end end if( error_string ~= nil) then draw_string( 16, 144, string.sub(error_string.." ",0,42), 258, 259) end wait_click(100) if( not( is_key("no_key"))) then if ((blite_timer==0) and (backlight==1)) then set_lcd_display(1) end blite_timer=300 if ( is_key("menu") ) then script_exit = true end end until (script_exit==true) printf("script halt requested") restore() end --[[ end of file ]]--
gpl-3.0
ffxiphoenix/darkstar
scripts/globals/items/eggplant.lua
35
1203
----------------------------------------- -- ID: 4388 -- Item: eggplant -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility 3 -- Vitality -5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4388); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 3); target:addMod(MOD_VIT, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 3); target:delMod(MOD_VIT, -5); end;
gpl-3.0
amiranony/anonybot
bot/utils.lua
356
14963
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has superuser privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- user has admins privileges function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- user has moderator privileges function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) -- Berfungsi utk mengecek user jika plugin moderated = true if plugin.moderated and not is_momod(msg) then --Cek apakah user adalah momod if plugin.moderated and not is_admin(msg) then -- Cek apakah user adalah admin if plugin.moderated and not is_sudo(msg) then -- Cek apakah user adalah sudoers return false end end end -- Berfungsi mengecek user jika plugin privileged = true if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end
gpl-2.0
federicodotta/proxmark3
client/scripts/emul2html.lua
27
1676
-- The getopt-functionality is loaded from pm3/getopt.lua -- Have a look there for further details getopt = require('getopt') bin = require('bin') dumplib = require('html_dumplib') example = "script run emul2html -o dumpdata.eml " author = "Martin Holst Swende" usage = "script run htmldump [-i <file>] [-o <file>]" desc =[[ This script takes a dumpfile on EML (ASCII) format and produces a html based dump, which is a bit more easily analyzed. Arguments: -h This help -i <file> Specifies the dump-file (input). If omitted, 'dumpdata.eml' is used -o <filename> Speciies the output file. If omitted, <curdate>.html is used. ]] ------------------------------- -- Some utilities ------------------------------- --- -- A debug printout-function function dbg(args) if DEBUG then print("###", args) end end --- -- This is only meant to be used when errors occur function oops(err) print("ERROR: ",err) end --- -- Usage help function help() print(desc) print("Example usage") print(example) end local function main(args) local input = "dumpdata.eml" local output = os.date("%Y-%m-%d_%H%M%S.html"); for o, a in getopt.getopt(args, 'i:o:h') do if o == "h" then return help() end if o == "i" then input = a end if o == "o" then output = a end end local filename, err = dumplib.convert_eml_to_html(input,output) if err then return oops(err) end print(("Wrote a HTML dump to the file %s"):format(filename)) end --[[ In the future, we may implement so that scripts are invoked directly into a 'main' function, instead of being executed blindly. For future compatibility, I have done so, but I invoke my main from here. --]] main(args)
gpl-2.0
Quenty/NevermoreEngine
src/rotatinglabel/src/Client/RotatingCharacter.lua
1
4334
--[=[ Character that rotates for animations @class RotatingCharacter ]=] local require = require(script.Parent.loader).load(script) local Math = require("Math") local Spring = require("Spring") local SpringUtils = require("SpringUtils") local RotatingCharacter = {} RotatingCharacter.ClassName = "RotatingCharacter" RotatingCharacter._transparency = 0 -- The key to use (ASCII) that acts as a space. So we get animations that move to this as a hidden value. local SPACE_CODE = 96 local SPRING_VALUES = { Target = true; Velocity = true; Speed = true; Position = true; Value = true; Damper = true; } function RotatingCharacter.new(Gui) local self = setmetatable({}, RotatingCharacter) self.Gui = Gui self._label = self.Gui.Label self._labelTwo = self._label.SecondLabel self._spring = Spring.new(0) self._label.TextXAlignment = Enum.TextXAlignment.Left self._labelTwo.TextXAlignment = Enum.TextXAlignment.Left -- hack self.TargetCharacter = " " self.Character = self.TargetCharacter self.TransparencyList = setmetatable({}, { __newindex = function(transparencyList, index, value) rawset(transparencyList, index, { Gui = value; Default = { TextTransparency = value.TextTransparency; TextStrokeTransparency = value.TextStrokeTransparency; }; }) end; }) self.TransparencyList[1] = self._label self.TransparencyList[2] = self._labelTwo self.Transparency = self.Transparency -- Force update return self end function RotatingCharacter:__index(index) if index == "Character" then return self:_intToChar(self.Value) elseif index == "IsDoneAnimating" then return not SpringUtils.animating(self._spring) elseif index == "NextCharacter" then return self:_intToChar(self.Value+1) -- For rendering purposes. elseif index == "Position" then local _, position = SpringUtils.animating(self._spring) return position elseif SPRING_VALUES[index] then return self._spring[index] elseif index == "TargetCharacter" then return self:_intToChar(self.Target) elseif index == "Transparency" then return self._transparency elseif index == "TransparencyMap" then local default = (self.Position % 1) -- Adjust transparency upwards based upon velocity default = Math.map(default, 0, 1, math.clamp(math.abs(self.Velocity*2/self.Speed), 0, 0.25), 1) local transparency = self.Transparency return { [self._label] = Math.map(default, 0, 1, transparency, 1); [self._labelTwo] = Math.map(default, 1, 0, transparency, 1); } else return RotatingCharacter[index] end end function RotatingCharacter:__newindex(index, value) if index == "Character" then assert(#value == 1, "Character must be length 1 (at) " .. #value) self.Value = self:CharToInt(value) elseif index == "TargetCharacter" then assert(#value == 1, "Character must be length 1 (at) " .. #value) self.Target = self:CharToInt(value) elseif SPRING_VALUES[index] then self._spring[index] = value elseif index == "Transparency" then self._transparency = value -- We need to call this because if transparency updates and we hit past "IsDoneAnimating" but not past -- actual d updates, the TransparencyMap is wrong. self:UpdatePositionRender() local transparencyMap = self.TransparencyMap for _, data in pairs(self.TransparencyList) do local transparency = transparencyMap[data.Gui] or error("Gui not in transparency map"); for property, propValue in pairs(data.Default) do data.Gui[property] = Math.map(transparency, 0, 1, propValue, 1) end end else rawset(self, index, value) end end function RotatingCharacter:UpdatePositionRender() self._label.Text = self.Character self._labelTwo.Text = self.NextCharacter self._label.Position = UDim2.new(0, 0, -(self.Position % 1), 0) end function RotatingCharacter:UpdateRender() --self:UpdatePositionRender() -- Covered by setting transparency. Yeah. This is weird. self.Transparency = self.Transparency return self.IsDoneAnimating end function RotatingCharacter:_intToChar(value) value = math.floor(value) return value == SPACE_CODE and " " or string.char(value) end function RotatingCharacter:CharToInt(char) return char == " " and SPACE_CODE or string.byte(char) end function RotatingCharacter:Destroy() self.Gui:Destroy() self.Gui = nil setmetatable(self, nil) end return RotatingCharacter
mit
hfjgjfg/uzzz
plugins/vote.lua
615
2128
do local _file_votes = './data/votes.lua' function read_file_votes () local f = io.open(_file_votes, "r+") if f == nil then print ('Created voting file '.._file_votes) serialize_to_file({}, _file_votes) else print ('Values loaded: '.._file_votes) f:close() end return loadfile (_file_votes)() end function clear_votes (chat) local _votes = read_file_votes () _votes [chat] = {} serialize_to_file(_votes, _file_votes) end function votes_result (chat) local _votes = read_file_votes () local results = {} local result_string = "" if _votes [chat] == nil then _votes[chat] = {} end for user,vote in pairs (_votes[chat]) do if (results [vote] == nil) then results [vote] = user else results [vote] = results [vote] .. ", " .. user end end for vote,users in pairs (results) do result_string = result_string .. vote .. " : " .. users .. "\n" end return result_string end function save_vote(chat, user, vote) local _votes = read_file_votes () if _votes[chat] == nil then _votes[chat] = {} end _votes[chat][user] = vote serialize_to_file(_votes, _file_votes) end function run(msg, matches) if (matches[1] == "ing") then if (matches [2] == "reset") then clear_votes (tostring(msg.to.id)) return "Voting statistics reset.." elseif (matches [2] == "stats") then local votes_result = votes_result (tostring(msg.to.id)) if (votes_result == "") then votes_result = "[No votes registered]\n" end return "Voting statistics :\n" .. votes_result end else save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2]))) return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2])) end end return { description = "Plugin for voting in groups.", usage = { "!voting reset: Reset all the votes.", "!vote [number]: Cast the vote.", "!voting stats: Shows the statistics of voting." }, patterns = { "^!vot(ing) (reset)", "^!vot(ing) (stats)", "^!vot(e) ([0-9]+)$" }, run = run } end
gpl-2.0
SeonghoBaek/RealtimeCamera
openface/batch-represent/batch-represent.lua
14
2090
local ffi = require 'ffi' local batchNumber, nImgs = 0 torch.setdefaulttensortype('torch.FloatTensor') function batchRepresent() local loadSize = {3, opt.imgDim, opt.imgDim} print(opt.data) local cacheFile = paths.concat(opt.data, 'cache.t7') print('cache lotation: ', cacheFile) local dumpLoader if paths.filep(cacheFile) then print('Loading metadata from cache.') print('If your dataset has changed, delete the cache file.') dumpLoader = torch.load(cacheFile) else print('Creating metadata for cache.') dumpLoader = dataLoader{ paths = {opt.data}, loadSize = loadSize, sampleSize = loadSize, split = 0, verbose = true } torch.save(cacheFile, dumpLoader) end collectgarbage() nImgs = dumpLoader:sizeTest() print('nImgs: ', nImgs) assert(nImgs > 0, "Failed to get nImgs") batchNumber = 0 for i=1,math.ceil(nImgs/opt.batchSize) do local indexStart = (i-1) * opt.batchSize + 1 local indexEnd = math.min(nImgs, indexStart + opt.batchSize - 1) local batchSz = indexEnd-indexStart+1 local inputs, labels = dumpLoader:get(indexStart, indexEnd) local paths = {} for j=indexStart,indexEnd do table.insert(paths, ffi.string(dumpLoader.imagePath[dumpLoader.testIndices[j]]:data())) end repBatch(paths, inputs, labels, batchSz) if i % 5 == 0 then collectgarbage() end end if opt.cuda then cutorch.synchronize() end end function repBatch(paths, inputs, labels, batchSz) batchNumber = batchNumber + batchSz if opt.cuda then inputs = inputs:cuda() end local embeddings = model:forward(inputs):float() if opt.cuda then cutorch.synchronize() end if batchSz == 1 then embeddings = embeddings:reshape(1, embeddings:size(1)) end for i=1,batchSz do labelsCSV:write({labels[i], paths[i]}) repsCSV:write(embeddings[i]:totable()) end print(('Represent: %d/%d'):format(batchNumber, nImgs)) end
apache-2.0
madmaxoft/EBW-NearestAvoid
Main.lua
1
9380
-- Main.lua -- Implements the entire NearestAvoid AI controller -- The bots target the nearest enemy, but avoid going through a friend bot in front of it --- Returns true if the first number is between the second and third numbers, inclusive local function isBetweenOrEqual(a_Val, a_Bounds1, a_Bounds2) -- Check params: assert(type(a_Val) == "number") assert(type(a_Bounds1) == "number") assert(type(a_Bounds2) == "number") if (a_Bounds1 < a_Bounds2) then return (a_Val >= a_Bounds1) and (a_Val <= a_Bounds2) else return (a_Val >= a_Bounds2) and (a_Val <= a_Bounds1) end end --- Returns the coords of the specified point projected onto the specified line local function projectPtToLine(a_X, a_Y, a_LineX1, a_LineY1, a_LineX2, a_LineY2) -- Check params: assert(tonumber(a_X)) assert(tonumber(a_Y)) assert(tonumber(a_LineX1)) assert(tonumber(a_LineY1)) assert(tonumber(a_LineX2)) assert(tonumber(a_LineY2)) -- Calculate the coords: local dx = a_LineX2 - a_LineX1; local dy = a_LineY2 - a_LineY1; local divisor = (dx * dx + dy * dy) if (divisor < 0.0001) then -- The divisor is too small, the line is too short, so return the first point's coords as the projection: return a_LineX1, a_LineY1 end local k = (dy * (a_Y - a_LineY1) + dx * (a_X - a_LineX1)) / divisor; return a_LineX1 + dx * k, a_LineY1 + dy * k; end --- Returns the distance of the specified point from the specified line local function distPtFromLine(a_X, a_Y, a_LineX1, a_LineY1, a_LineX2, a_LineY2) -- Check params: assert(tonumber(a_X)) assert(tonumber(a_Y)) assert(tonumber(a_LineX1)) assert(tonumber(a_LineY1)) assert(tonumber(a_LineX2)) assert(tonumber(a_LineY2)) -- Calculate the distance, divisor first: local deltaX = a_LineX1 - a_LineX2 local deltaY = a_LineY1 - a_LineY2 local divisor = math.sqrt(deltaY * deltaY + deltaX * deltaX) if (divisor < 0.0001) then return 0 end local numerator = math.abs(deltaY * a_X - deltaX * a_Y + a_LineX2 * a_LineY1 - a_LineY2 * a_LineX1) return numerator / divisor end --- Returns the Euclidean distance between two points local function distPtFromPt(a_X1, a_Y1, a_X2, a_Y2) -- Check params: assert(tonumber(a_X1)) assert(tonumber(a_Y1)) assert(tonumber(a_X2)) assert(tonumber(a_Y2)) -- Calculate the distance: return math.sqrt((a_X1 - a_X2) * (a_X1 - a_X2) + (a_Y1 - a_Y2) * (a_Y1 - a_Y2)) end --- Returns the Euclidean of the distance between two bots local function botDistance(a_Bot1, a_Bot2) -- Check params: assert(type(a_Bot1) == "table") assert(type(a_Bot2) == "table") -- Calculate the distance: return distPtFromPt(a_Bot1.x, a_Bot1.y, a_Bot2.x, a_Bot2.y) end --- Returns the command for srcBot to target dstBot local function cmdTargetBot(a_SrcBot, a_DstBot, a_Game) -- Check params: assert(type(a_SrcBot) == "table") assert(type(a_DstBot) == "table") assert(type(a_Game) == "table") local wantAngle = math.atan2(a_DstBot.y - a_SrcBot.y, a_DstBot.x - a_SrcBot.x) * 180 / math.pi local angleDiff = wantAngle - a_SrcBot.angle if (angleDiff < -180) then angleDiff = angleDiff + 360 elseif (angleDiff > 180) then angleDiff = angleDiff - 360 end -- If the current heading is too off, adjust: if (math.abs(angleDiff) > 5) then if ((a_SrcBot.speedLevel > 1) and (math.abs(angleDiff) > 3 * a_SrcBot.maxAngularSpeed)) then -- We're going too fast to steer, brake: aiLog(a_SrcBot.id, "Too fast to steer, breaking. Angle is " .. a_SrcBot.angle .. ", wantAngle is " .. wantAngle .. ", angleDiff is " .. angleDiff) return { cmd = "brake" } else aiLog( a_SrcBot.id, "Steering, angle is " .. a_SrcBot.angle .. ", wantAngle is " .. wantAngle .. ", angleDiff is " .. angleDiff .. ", maxAngularSpeed is " .. a_SrcBot.maxAngularSpeed .. ", speed is " .. a_SrcBot.speed ) return { cmd = "steer", angle = angleDiff } end end -- If the enemy is further than 20 pixels away, accellerate, else nop: local dist = botDistance(a_SrcBot, a_DstBot) if ((dist > 20) and (a_SrcBot.speed < a_Game.maxBotSpeed)) then aiLog(a_SrcBot.id, "Accellerating (dist is " .. dist .. ")") return { cmd = "accelerate" } else aiLog(a_SrcBot.id, "En route to dst, no command") return nil end end --- Converts bot speed to speed level index: local function getSpeedLevelIdxFromSpeed(a_Game, a_Speed) -- Try the direct lookup first: local level = a_Game.speedToSpeedLevel[a_Speed] if (level) then return level end -- Direct lookup failed, do a manual lookup: print("speed level lookup failed for speed " .. a_Speed) for idx, lvl in ipairs(a_Game.speedLevels) do if (a_Speed <= lvl.linearSpeed) then print("Manual speed lookup for speed " .. a_Speed .. " is idx " .. idx .. ", linear speed " .. lvl.linearSpeed) return idx end end return 1 end --- Returns true if there is a bot (from a_Bots) between a_Bot1 and a_Bot2 within the specified distance of the line local function isBotBetweenBots(a_Bot1, a_Bot2, a_Bots, a_Dist) -- Check params: assert(type(a_Bot1) == "table") assert(type(a_Bot2) == "table") assert(type(a_Bots) == "table") assert(tonumber(a_Dist)) -- Check each friend's distance from the line between bot1 and bot2: local minDist = 1500 local minDistId = 0 for _, f in ipairs(a_Bots) do if ((f.id ~= a_Bot1.id) and (f.id ~= a_Bot2.id)) then local x, y = projectPtToLine(f.x, f.y, a_Bot1.x, a_Bot1.y, a_Bot2.x, a_Bot2.y) if (isBetweenOrEqual(x, a_Bot1.x, a_Bot2.x) and isBetweenOrEqual(y, a_Bot1.y, a_Bot2.y)) then local dist = distPtFromPt(x, y, f.x, f.y) if (dist < minDist) then minDist = dist minDistId = f.id end if (dist < a_Dist) then aiLog(a_Bot1.id, "Cannot aim towards #" .. a_Bot2.id .. ", #" .. f.id .. " is in the way") return true end end end end -- for f - a_Bots[] aiLog(a_Bot1.id, "Friend nearest to the line of fire to #" .. a_Bot2.id .. " is #" .. minDistId .. " at distance " .. minDist) return false end --- Updates each bot to target the nearest enemy: local function updateTargets(a_Game) -- Check params: assert(type(a_Game) == "table") assert(type(a_Game.world) == "table") assert(tonumber(a_Game.world.botRadius)) -- Update each bot's stats, based on their speed level: for _, m in ipairs(a_Game.myBots) do m.speedLevel = getSpeedLevelIdxFromSpeed(a_Game, m.speed) m.maxAngularSpeed = a_Game.speedLevels[m.speedLevel].maxAngularSpeed end for _, m in ipairs(a_Game.myBots) do -- Pick the nearest target: local minDist = a_Game.world.width * a_Game.world.width + a_Game.world.height * a_Game.world.height local target for _, e in ipairs(a_Game.enemyBots) do if not(isBotBetweenBots(m, e, a_Game.myBots, 2 * a_Game.world.botRadius)) then local dist = botDistance(m, e) if (dist < minDist) then minDist = dist target = e end else aiLog(m.id, "Cannot target enemy #" .. e.id .. ", there's a friend in the way") end end -- for idx2, e - enemyBots[] -- Navigate towards the target: if (target) then aiLog(m.id, "Targetting enemy #" .. target.id) a_Game.botCommands[m.id] = cmdTargetBot(m, target, a_Game) else -- No target available, wander around a bit: local cmd if (m.speed > 100) then cmd = { cmd = "brake" } else cmd = { cmd = "steer", angle = 120 } end aiLog(m.id, "No a clear line of attack to any enemy. Idling at " .. cmd.cmd) a_Game.botCommands[m.id] = cmd end end end function onGameStarted(a_Game) -- Collect all my bots into an array, and enemy bots to another array: a_Game.myBots = {} a_Game.enemyBots = {} for _, bot in pairs(a_Game.allBots) do if (bot.isEnemy) then table.insert(a_Game.enemyBots, bot) else table.insert(a_Game.myBots, bot) end end -- Initialize the speed-to-speedLevel table, find min and max: a_Game.speedToSpeedLevel = {} local minSpeed = a_Game.speedLevels[1].linearSpeed local maxSpeed = minSpeed for idx, level in ipairs(a_Game.speedLevels) do a_Game.speedToSpeedLevel[level.linearSpeed] = idx if (level.linearSpeed < minSpeed) then minSpeed = level.linearSpeed end if (level.linearSpeed > maxSpeed) then maxSpeed = level.linearSpeed end end a_Game.speedToSpeedLevel[0] = 1 -- Special case - bots with zero speed are handled as having the lowest speed a_Game.maxBotSpeed = maxSpeed a_Game.minBotSpeed = minSpeed end function onGameUpdate(a_Game) assert(type(a_Game) == "table") -- Nothing needed yet end function onGameFinished(a_Game) assert(type(a_Game) == "table") -- Nothing needed yet end function onBotDied(a_Game, a_BotID) -- Remove the bot from one of the myBots / enemyBots arrays: local whichArray if (a_Game.allBots[a_BotID].isEnemy) then whichArray = a_Game.enemyBots else whichArray = a_Game.myBots end for idx, bot in ipairs(whichArray) do if (bot.id == a_BotID) then table.remove(whichArray, idx) break; end end -- for idx, bot - whichArray[] -- Print an info message: local friendliness if (a_Game.allBots[a_BotID].isEnemy) then friendliness = "(enemy)" else friendliness = "(my)" end print("LUA: onBotDied: bot #" .. a_BotID .. friendliness) end function onSendingCommands(a_Game) -- Update the bot targets: updateTargets(a_Game) end function onCommandsSent(a_Game) assert(type(a_Game) == "table") -- Nothing needed end
unlicense
usstwxy/luarocks
lfw/rocks/luafilesystem/1.5.0-1/tests/test.lua
40
4634
#!/usr/local/bin/lua5.1 local tmp = "/tmp" local sep = "/" local upper = ".." require"lfs" print (lfs._VERSION) function attrdir (path) for file in lfs.dir(path) do if file ~= "." and file ~= ".." then local f = path..sep..file print ("\t=> "..f.." <=") local attr = lfs.attributes (f) assert (type(attr) == "table") if attr.mode == "directory" then attrdir (f) else for name, value in pairs(attr) do print (name, value) end end end end end -- Checking changing directories local current = assert (lfs.currentdir()) local reldir = string.gsub (current, "^.*%"..sep.."([^"..sep.."])$", "%1") assert (lfs.chdir (upper), "could not change to upper directory") assert (lfs.chdir (reldir), "could not change back to current directory") assert (lfs.currentdir() == current, "error trying to change directories") assert (lfs.chdir ("this couldn't be an actual directory") == nil, "could change to a non-existent directory") -- Changing creating and removing directories local tmpdir = current..sep.."lfs_tmp_dir" local tmpfile = tmpdir..sep.."tmp_file" -- Test for existence of a previous lfs_tmp_dir -- that may have resulted from an interrupted test execution and remove it if lfs.chdir (tmpdir) then assert (lfs.chdir (upper), "could not change to upper directory") assert (os.remove (tmpfile), "could not remove file from previous test") assert (lfs.rmdir (tmpdir), "could not remove directory from previous test") end -- tries to create a directory assert (lfs.mkdir (tmpdir), "could not make a new directory") local attrib, errmsg = lfs.attributes (tmpdir) if not attrib then error ("could not get attributes of file `"..tmpdir.."':\n"..errmsg) end local f = io.open(tmpfile, "w") f:close() -- Change access time local testdate = os.time({ year = 2007, day = 10, month = 2, hour=0}) assert (lfs.touch (tmpfile, testdate)) local new_att = assert (lfs.attributes (tmpfile)) assert (new_att.access == testdate, "could not set access time") assert (new_att.modification == testdate, "could not set modification time") -- Change access and modification time local testdate1 = os.time({ year = 2007, day = 10, month = 2, hour=0}) local testdate2 = os.time({ year = 2007, day = 11, month = 2, hour=0}) assert (lfs.touch (tmpfile, testdate2, testdate1)) local new_att = assert (lfs.attributes (tmpfile)) assert (new_att.access == testdate2, "could not set access time") assert (new_att.modification == testdate1, "could not set modification time") local res, err = lfs.symlinkattributes(tmpfile) if err ~= "symlinkattributes not supported on this platform" then -- Checking symbolic link information (does not work in Windows) assert (os.execute ("ln -s "..tmpfile.." _a_link_for_test_")) assert (lfs.attributes"_a_link_for_test_".mode == "file") assert (lfs.symlinkattributes"_a_link_for_test_".mode == "link") assert (os.remove"_a_link_for_test_") end if lfs.setmode then -- Checking text/binary modes (works only in Windows) local f = io.open(tmpfile, "w") local result, mode = lfs.setmode(f, "binary") assert((result and mode == "text") or (not result and mode == "setmode not supported on this platform")) result, mode = lfs.setmode(f, "text") assert((result and mode == "binary") or (not result and mode == "setmode not supported on this platform")) f:close() end -- Restore access time to current value assert (lfs.touch (tmpfile, attrib.access, attrib.modification)) new_att = assert (lfs.attributes (tmpfile)) assert (new_att.access == attrib.access) assert (new_att.modification == attrib.modification) -- Remove new file and directory assert (os.remove (tmpfile), "could not remove new file") assert (lfs.rmdir (tmpdir), "could not remove new directory") assert (lfs.mkdir (tmpdir..sep.."lfs_tmp_dir") == nil, "could create a directory inside a non-existent one") -- Trying to get attributes of a non-existent file assert (lfs.attributes ("this couldn't be an actual file") == nil, "could get attributes of a non-existent file") assert (type(lfs.attributes (upper)) == "table", "couldn't get attributes of upper directory") -- Stressing directory iterator count = 0 for i = 1, 4000 do for file in lfs.dir (tmp) do count = count + 1 end end -- Stressing directory iterator, explicit version count = 0 for i = 1, 4000 do local iter, dir = lfs.dir(tmp) local file = dir:next() while file do count = count + 1 file = dir:next() end assert(not pcall(dir.next, dir)) end -- directory explicit close local iter, dir = lfs.dir(tmp) dir:close() assert(not pcall(dir.next, dir)) print"Ok!"
mit
ffxiphoenix/darkstar
scripts/globals/items/vulcan_claymore.lua
42
1451
----------------------------------------- -- ID: 18379 -- Item: Vulcan Claymore -- Additional Effect: Fire Damage -- Enchantment: Enfire ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(3,10); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0); dmg = adjustForTarget(target,dmg,ELE_FIRE); dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_FIRE_DAMAGE,message,dmg; end end; ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) return 0; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) local effect = EFFECT_ENFIRE; doEnspell(target,target,nil,effect); end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Windurst_Woods/npcs/Dahjal.lua
38
1038
----------------------------------- -- Area: Windurst Woods -- NPC: Dahjal -- Type: Conquest Troupe -- @zone: 241 -- @pos 11.639 1.267 -57.706 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0030); 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
amiranony/anonybot
plugins/lyrics.lua
695
2113
do local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs' local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5' local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect' local function getInfo(query) print('Getting info of ' .. query) local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY ..'&q='..URL.escape(query) local b, c = http.request(url) if c ~= 200 then return nil end local result = json:decode(b) local artist = result[1].artist.name local track = result[1].title return artist, track end local function getLyrics(query) local artist, track = getInfo(query) if artist and track then local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist) ..'&song='..URL.escape(track) local b, c = http.request(url) if c ~= 200 then return nil end local xml = require("xml") local result = xml.load(b) if not result then return nil end if xml.find(result, 'LyricSong') then track = xml.find(result, 'LyricSong')[1] end if xml.find(result, 'LyricArtist') then artist = xml.find(result, 'LyricArtist')[1] end local lyric if xml.find(result, 'Lyric') then lyric = xml.find(result, 'Lyric')[1] else lyric = nil end local cover if xml.find(result, 'LyricCovertArtUrl') then cover = xml.find(result, 'LyricCovertArtUrl')[1] else cover = nil end return artist, track, lyric, cover else return nil end end local function run(msg, matches) local artist, track, lyric, cover = getLyrics(matches[1]) if track and artist and lyric then if cover then local receiver = get_receiver(msg) send_photo_from_url(receiver, cover) end return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric else return 'Oops! Lyrics not found or something like that! :/' end end return { description = 'Getting lyrics of a song', usage = '!lyrics [track or artist - track]: Search and get lyrics of the song', patterns = { '^!lyrics? (.*)$' }, run = run } end
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Port_Bastok/npcs/Ominous_Cloud.lua
19
5284
----------------------------------- -- Area: Port Bastok -- NPC: Ominous Cloud -- Type: Traveling Merchant NPC -- @zone: 236 -- @pos 146.962 7.499 -63.316 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local wijinruit = trade:getItemQty(951) local uchitake = (trade:getItemQty(1161) / 99) local tsurara = (trade:getItemQty(1164) / 99) local kawahori = (trade:getItemQty(1167) / 99) local makibishi = (trade:getItemQty(1170) / 99) local hiraishin = (trade:getItemQty(1173) / 99) local mizu = (trade:getItemQty(1176) / 99) local shihei = (trade:getItemQty(1179) / 99) local jusatsu = (trade:getItemQty(1182) / 99) local kaginawa = (trade:getItemQty(1185) / 99) local sairui = (trade:getItemQty(1188) / 99) local kodoku = (trade:getItemQty(1191) / 99) local shinobi = (trade:getItemQty(1194) / 99) local sanjaku = (trade:getItemQty(2553) / 99) local soushi = (trade:getItemQty(2555) / 99) local kabenro = (trade:getItemQty(2642) / 99) local jinko = (trade:getItemQty(2643) / 99) local mokujin = (trade:getItemQty(2970) / 99) local inoshi = (trade:getItemQty(2971) / 99) local shikan = (trade:getItemQty(2972) / 99) local chono = (trade:getItemQty(2973) / 99) local tools = (uchitake + tsurara + kawahori + makibishi + hiraishin + mizu + shihei + jusatsu + kaginawa + sairui + kodoku + shinobi + sanjaku + soushi + kabenro + jinko + mokujin + inoshi + shikan + chono) if (((tools * 99) + wijinruit) == trade:getItemCount()) then if ((tools == math.floor(tools)) and (tools == wijinruit) and (player:getFreeSlotsCount() >= wijinruit)) then player:tradeComplete(); if (uchitake > 0) then player:addItem(5308,uchitake); player:messageSpecial(ITEM_OBTAINED,5308); end if (tsurara > 0) then player:addItem(5309,tsurara); player:messageSpecial(ITEM_OBTAINED,5309); end if (kawahori > 0) then player:addItem(5310,kawahori); player:messageSpecial(ITEM_OBTAINED,5310); end if (makibishi > 0) then player:addItem(5311,makibishi); player:messageSpecial(ITEM_OBTAINED,5311); end if (hiraishin > 0) then player:addItem(5312,hiraishin); player:messageSpecial(ITEM_OBTAINED,5312); end if (mizu > 0) then player:addItem(5313,mizu); player:messageSpecial(ITEM_OBTAINED,5313); end if (shihei > 0) then player:addItem(5314,shihei); player:messageSpecial(ITEM_OBTAINED,5314); end if (jusatsu > 0) then player:addItem(5315,jusatsu); player:messageSpecial(ITEM_OBTAINED,5315); end if (kaginawa > 0) then player:addItem(5316,kaginawa); player:messageSpecial(ITEM_OBTAINED,5316); end if (sairui > 0) then player:addItem(5317,sairui); player:messageSpecial(ITEM_OBTAINED,5317); end if (kodoku > 0) then player:addItem(5318,kodoku); player:messageSpecial(ITEM_OBTAINED,5318); end if (shinobi > 0) then player:addItem(5319,shinobi); player:messageSpecial(ITEM_OBTAINED,5319); end if (sanjaku > 0) then player:addItem(5417,sanjaku); player:messageSpecial(ITEM_OBTAINED,5417); end if (soushi > 0) then player:addItem(5734,soushi); player:messageSpecial(ITEM_OBTAINED,5734); end if (kabenro > 0) then player:addItem(5863,kabenro); player:messageSpecial(ITEM_OBTAINED,5863); end if (jinko > 0) then player:addItem(5864,jinko); player:messageSpecial(ITEM_OBTAINED,5864); end if (mokujin > 0) then player:addItem(5866,mokujin); player:messageSpecial(ITEM_OBTAINED,5866); end if (inoshi > 0) then player:addItem(5867,inoshi); player:messageSpecial(ITEM_OBTAINED,5867); end if (shikan > 0) then player:addItem(5868,shikan); player:messageSpecial(ITEM_OBTAINED,5868); end if (chono > 0) then player:addItem(5869,chono); player:messageSpecial(ITEM_OBTAINED,5869); end end end -- 951 Wijinruit -- 1161 Uchitake 5308 -- 1164 Tsurara 5309 -- 1167 Kawahori-ogi 5310 -- 1170 Makibishi 5311 -- 1173 Hiraishin 5312 -- 1176 Mizu-deppo 5313 -- 1179 Shihei 5314 -- 1182 Jusatsu 5315 -- 1185 Kaginawa 5316 -- 1188 Sairui-ran 5317 -- 1191 Kodoku 5318 -- 1194 Shinobi-tabi 5319 -- 2553 Sanjaku-tengui 5417 -- 2555 Soshi 5734 -- 2642 Kabenro 5863 -- 2643 Jinko 5864 -- 2970 Mokujin 5866 -- 2971 Inoshishinofuda 5867 -- 2972 Shikanofuda 5868 -- 2973 Chonofuda 5869 end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0159); 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
ffxiphoenix/darkstar
scripts/zones/Dynamis-Valkurm/mobs/Adamantking_Effigy.lua
12
2272
----------------------------------- -- Area: Dynamis Valkurm -- NPC: Adamantking_Effigy ----------------------------------- package.loaded["scripts/zones/Dynamis-Valkurm/TextIDs"] = nil; ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Valkurm/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) local X = mob:getXPos(); local Y = mob:getYPos(); local Z = mob:getZPos(); local spawnList = ValkurmQuadavList; if (mob:getStatPoppedMobs() == false) then mob:setStatPoppedMobs(true); for nb = 1, table.getn(spawnList), 2 do if (mob:getID() == spawnList[nb]) then -- si l'id du mob engager correpond a un ID de la list for nbi = 1, table.getn(spawnList[nb + 1]), 1 do if ((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end local mobNBR = spawnList[nb + 1][nbi]; --printf("Serjeant_Tombstone => mob %u \n",mobNBR); if (mobNBR ~= nil) then -- Spawn Mob SpawnMob(mobNBR):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetMobByID(mobNBR):setPos(X,Y,Z); GetMobByID(mobNBR):setSpawn(X,Y,Z); -- Spawn Pet for BST, DRG, and SMN local MJob = GetMobByID(mobNBR):getMainJob(); -- printf("Serjeant_Tombstone => mob %u \n",mobNBR); -- printf("mobjob %u \n",MJob); if (MJob == 9 or MJob == 14 or MJob == 15) then -- Spawn Pet for BST , DRG , and SMN SpawnMob(mobNBR + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetMobByID(mobNBR + 1):setPos(X,Y,Z); GetMobByID(mobNBR + 1):setSpawn(X,Y,Z); end end end end end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); if ( mobID == 16937233) then --hp killer:messageBasic(024,(killer:getMaxHP()-killer:getHP())); killer:restoreHP(3000); end end;
gpl-3.0
Jigoku/starphase
src/hud.lua
1
15395
--[[ * Copyright (C) 2016-2019 Ricky K. Thomson * * 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. * u should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. --]] hud = {} hud.life_gfx = love.graphics.newImage("data/gfx/life.png") --cyan theme hud.colors = { ["frame"] = {0.607,1,1,0.196}, ["face"] = {0.607,1,1,0.9}, ["frame_dark"] = {0.039,0.039,0.039,0.65}, ["lives"] = {0.39,0.745,0.784,0.470}, } --pink/purple --[[ hud.colors = { ["frame"] = {1,0.607,1,0.196}, ["face"] = {1,0.607,1}, ["frame_dark"] = {0.039,0.039,0.039,0.39}, ["lives"] = {0.745,0.39,0.784,0.470}, } --]] hud.console = { w = 720, h = 250, x = 10, y = -250, canvas = love.graphics.newCanvas(w, h), speed = 400, opacity = 1, } function hud:init() hud.display = { w = 900, h = 30, offset = 30, canvas = love.graphics.newCanvas(w, h), progress = 0.0, --progress_speed = 1.5, -- 1 minute progress_speed = 1.0, -- 1 minute 30 seconds progress_speed = 5.0, wave = 1, timer = os.time(), } hud.warp = false hud.time = 0 hud.warning = false hud.warninggfx = love.graphics.newImage("data/gfx/warning.png") hud.warning_quad = love.graphics.newQuad(0,0, love.graphics.getWidth(), love.graphics.getHeight(), hud.warninggfx:getDimensions() ) hud.warningmin = 0 hud.warningmax = 0.5 hud.warningspeed = 1.0 hud.warning_text = "SHIELD LOW" end function hud:update(dt) if hud.display.progress > hud.display.w then hud.display.progress = hud.display.w print ("reached destination") --implement scoreboard / statistic screen end if paused then return end hud.display.progress = hud.display.progress + hud.display.progress_speed *dt hud.time = hud.time + 1 *dt if hud.warp then end if hud.warning then if hud.warningmin <=0 then hud.warningmin = hud.warningmax else hud.warningmin = hud.warningmin - hud.warningspeed *dt end end end function hud:updateconsole(dt) if debug then hud.console.y = hud.console.y + hud.console.speed *dt if hud.console.y >= 0 then hud.console.y = 0 end else hud.console.y = hud.console.y - hud.console.speed *dt if hud.console.y <= -hud.console.h then hud.console.y = -hud.console.h end end end function hud:drawFrames() if hud.warp then love.graphics.setColor(hud.colors["frame"][1],hud.colors["frame"][2],hud.colors["frame"][3],hud.colors["frame"][4]) else love.graphics.setColor(hud.colors["frame"][1],hud.colors["frame"][2],hud.colors["frame"][3],hud.colors["frame"][4]) end --dynamic decor/lines --[[love.graphics.setColor( starfield.nebulae.red, starfield.nebulae.green, starfield.nebulae.blue, 50 )--]] love.graphics.setLineWidth(2) love.graphics.setLineStyle("smooth") --left side love.graphics.line( 60,love.graphics.getHeight()-20, 20,love.graphics.getHeight()-40 ) love.graphics.line( love.graphics.getWidth()/5+1,love.graphics.getHeight()-20, love.graphics.getWidth()/5+40,love.graphics.getHeight()-40 ) love.graphics.line( 61,love.graphics.getHeight()-20, love.graphics.getWidth()/5,love.graphics.getHeight()-20 ) love.graphics.line( 20,41, 20,love.graphics.getHeight()-41 ) love.graphics.line( 60,20, 20,40 ) love.graphics.line( love.graphics.getWidth()/5+1,20, love.graphics.getWidth()/5+40,40 ) love.graphics.line( 61,20, love.graphics.getWidth()/5,20 ) --right side love.graphics.line( love.graphics.getWidth()-60,love.graphics.getHeight()-20, love.graphics.getWidth()-20,love.graphics.getHeight()-40 ) love.graphics.line( love.graphics.getWidth()-love.graphics.getWidth()/5-1,love.graphics.getHeight()-20, love.graphics.getWidth()-love.graphics.getWidth()/5-40,love.graphics.getHeight()-40 ) love.graphics.line( love.graphics.getWidth()-61,love.graphics.getHeight()-20, love.graphics.getWidth()-love.graphics.getWidth()/5,love.graphics.getHeight()-20 ) love.graphics.line( love.graphics.getWidth()-20,41, love.graphics.getWidth()-20,love.graphics.getHeight()-41 ) love.graphics.line( love.graphics.getWidth()-60,20, love.graphics.getWidth()-20,40 ) love.graphics.line( love.graphics.getWidth()-love.graphics.getWidth()/5-1,20, love.graphics.getWidth()-love.graphics.getWidth()/5-40,40 ) love.graphics.line( love.graphics.getWidth()-61,20, love.graphics.getWidth()-love.graphics.getWidth()/5,20 ) -- hud frame for bottom of screen local w = 510 local a = 20 local points = { love.graphics.getWidth()/2-w,love.graphics.getHeight()+1, love.graphics.getWidth()/2-w+a,love.graphics.getHeight()-70, love.graphics.getWidth()/2+w-a,love.graphics.getHeight()-70, love.graphics.getWidth()/2+w,love.graphics.getHeight()+1 } love.graphics.setColor(hud.colors["frame_dark"][1],hud.colors["frame_dark"][2],hud.colors["frame_dark"][3],hud.colors["frame_dark"][4]) love.graphics.polygon("fill", points) love.graphics.setColor(hud.colors["frame"][1],hud.colors["frame"][2],hud.colors["frame"][3],hud.colors["frame"][4]) love.graphics.polygon("line", points) love.graphics.setLineWidth(1) end function hud:draw() if hud.warning then love.graphics.setColor(1,0,0,hud.warningmin) love.graphics.draw( hud.warninggfx, hud.warning_quad, 0,0, 0, love.graphics.getWidth()/hud.warninggfx:getWidth(), love.graphics.getHeight()/hud.warninggfx:getHeight() ) end if paused and not debug then love.graphics.setColor(0,0,0,0.549) love.graphics.rectangle("fill",0,0,love.graphics.getWidth(), love.graphics.getHeight()) love.graphics.setFont(fonts.paused_large) love.graphics.setColor(1,1,1,0.784) love.graphics.printf("PAUSED", love.graphics.getWidth()/2-150,love.graphics.getHeight()/3,300,"center") love.graphics.setFont(fonts.default) local wrap = 200 love.graphics.setFont(fonts.paused_small) love.graphics.setColor(1,1,1,0.784) love.graphics.printf("Press "..string.upper(binds.pausequit).." to quit", love.graphics.getWidth()/2-wrap/2,love.graphics.getHeight()/3+50,wrap,"center",0,1,1) love.graphics.setFont(fonts.default) return end --hud --decor / lines if not debug then hud:drawFrames() end if debugarcade then love.graphics.setFont(fonts.default) love.graphics.setColor(0.588,1,1,0.784) love.graphics.print("DEBUG:\npress M for message system\npress [ or ] to adjust starfield speed\npress 1-9 to spawn enemies\npress space to set new starfield seed\npress ` for console/debug overlay\npress k to spawn powerup", 30, starfield.h-400) end --warning text if hud.warning then love.graphics.setFont(fonts.hud_warning) love.graphics.setColor(1,0.2,0.2,1-hud.warningmin) love.graphics.print(hud.warning_text,love.graphics.getWidth()-350,love.graphics.getHeight()-80) love.graphics.setColor(1,1,1,hud.warningmin) love.graphics.print(hud.warning_text,love.graphics.getWidth()-350+5,love.graphics.getHeight()-80) end --time love.graphics.setColor(1,1,1,0.4) love.graphics.setFont(fonts.timer) love.graphics.printf(misc:formatTime(hud.time), love.graphics.getWidth()/2-150,20,300,"center",0,1,1) love.graphics.setFont(fonts.default) --lives (temporary) love.graphics.printf("lives: ", love.graphics.getWidth()/2,60,0,"center",0,1,1) for i=1,player.lives do love.graphics.setColor( hud.colors["lives"][1],hud.colors["lives"][2],hud.colors["lives"][3],hud.colors["lives"][4] ) love.graphics.draw(hud.life_gfx,(25*i)+50,love.graphics.getHeight()-80,0,1,1) end --display love.graphics.setCanvas(hud.display.canvas) love.graphics.clear() love.graphics.setColor(1,1,1,1) hud:drawProgress() love.graphics.setFont(fonts.hud) --progress love.graphics.setColor(1,1,1,0.607) love.graphics.print("Wave Progress : " .. math.floor(hud.display.progress/hud.display.w*100).."%", 10,hud.display.h) --score love.graphics.setColor(1,1,1,0.607) love.graphics.print("Score : " .. player.score, 10+hud.display.w/4,hud.display.h) --shield bar love.graphics.setLineWidth(5) love.graphics.setColor(1,1,1,0.607) love.graphics.print("shield", 10+hud.display.w-400,hud.display.h) love.graphics.setColor(0.39,0.784,0.39,0.3) love.graphics.rectangle("fill", 70+hud.display.w-400,hud.display.h+10,hud.display.w/8, hud.display.h/3,5,5) love.graphics.setColor(0.39,0.784,0.39,0.7) love.graphics.rectangle("fill", 70+hud.display.w-400,hud.display.h+10,player.shield/player.shieldmax*(hud.display.w/8), hud.display.h/3,5,5) love.graphics.setColor(0.607,1,1,0.3) love.graphics.rectangle("line", 70+hud.display.w-400,hud.display.h+10,hud.display.w/8, hud.display.h/3,5,5) --energy bar love.graphics.setColor(1,1,1,0.607) love.graphics.print("energy", 10+hud.display.w-200,hud.display.h) love.graphics.setColor(0.39,0.784,0.39,0.3) love.graphics.rectangle("fill", 70+hud.display.w-200,hud.display.h+10,hud.display.w/8, hud.display.h/3,5,5) love.graphics.setColor(0.39,0.745,0.784,0.7) love.graphics.rectangle("fill", 70+hud.display.w-200,hud.display.h+10,player.energy/player.energymax*(hud.display.w/8), hud.display.h/3,5,5) love.graphics.setColor(0.607,1,1,0.3) love.graphics.rectangle("line", 70+hud.display.w-200,hud.display.h+10,hud.display.w/8, hud.display.h/3,5,5) love.graphics.setFont(fonts.default) love.graphics.setCanvas() love.graphics.setColor(1,1,1,1) love.graphics.draw(hud.display.canvas, love.graphics.getWidth()/2-hud.display.w/2, love.graphics.getHeight()-hud.display.h-hud.display.offset ) love.graphics.setLineWidth(1) end function hud:drawProgress() --wave progress marker love.graphics.setColor(0.607,1,1,0.607) for i=0,hud.display.w, hud.display.w/10 do love.graphics.line(i+1,10, i,hud.display.h-1) end --progress marker love.graphics.setLineWidth(1) for i=0,hud.display.w, hud.display.w/100 do if i < hud.display.progress then love.graphics.setColor(0,1,0.607,1) else love.graphics.setColor(0.607,1,1,0.784) end love.graphics.line(i,hud.display.h/3, i,hud.display.h/2) end --wave progress bar indicator love.graphics.setColor(0.607,1,1,0.4) love.graphics.rectangle("fill", 0,hud.display.h/2, hud.display.progress ,5) --progress marker arrow love.graphics.setColor(0,1,0.588,1) love.graphics.setLineWidth(2) love.graphics.line(hud.display.progress,hud.display.h/3, hud.display.progress-3,6) love.graphics.line(hud.display.progress,hud.display.h/3, hud.display.progress+3,6) end function hud:drawconsole() love.graphics.setFont(fonts.default) if hud.console.y > -hud.console.h then love.graphics.setCanvas(hud.console.canvas) love.graphics.clear() love.graphics.setColor(1,1,1,1) --debug console --frame love.graphics.setColor(0.04,0.05,0.08,0.75) --love.graphics.rectangle("fill", hud.console.x,hud.console.y, hud.console.w,hud.console.h) local points = { hud.console.x, hud.console.y, hud.console.x+hud.console.w, hud.console.y, hud.console.x+hud.console.w, hud.console.y+hud.console.h-40, hud.console.x+hud.console.w-40, hud.console.y+hud.console.h, hud.console.x, hud.console.y+hud.console.h, } love.graphics.polygon("fill", points) love.graphics.setColor(0.039,0.235,0.235,0.607) love.graphics.setLineWidth(2) love.graphics.polygon("line", points) love.graphics.setColor(0.607,1,1,0.39) love.graphics.line(hud.console.x,hud.console.y+hud.console.h, hud.console.x+hud.console.w-40,hud.console.y+hud.console.h) love.graphics.setLineWidth(1) --sysinfo love.graphics.setColor(0.784,0.39,0.784,1) love.graphics.print( "fps: " .. love.timer.getFPS() .. " | vsync: " ..tostring(game.flags.vsync).. " | res: ".. love.graphics.getWidth().."x"..love.graphics.getHeight() .. " | garbage: " .. gcinfo() .. "kB" .. string.format(" | vram: %.2fMB", love.graphics.getStats().texturememory / 1024 / 1024), hud.console.x+10,hud.console.y+10 ) love.graphics.setColor(0.784,0.784,0.39,1) love.graphics.print("bgmtrack: #" .. tostring(sound.bgmtrack) .. " | snd srcs: "..love.audio.getActiveSourceCount() .. " | [Seed: "..love.math.getRandomSeed().."]",hud.console.x+10,hud.console.y+30) -- --divider love.graphics.setColor(0.607,1,1,0.39) love.graphics.line(hud.console.x+10,hud.console.y+60, hud.console.x+hud.console.w-10,hud.console.y+60) --player info if mode == "arcade" then love.graphics.setColor(0.39,0.745,0.784,1) love.graphics.print("player yvel: " .. math.round(player.yvel,4),hud.console.x+10,hud.console.y+70) love.graphics.print("player xvel: " .. math.round(player.xvel,4),hud.console.x+10,hud.console.y+90) love.graphics.print("player posx: " .. math.round(player.x,4),hud.console.x+10,hud.console.y+110) love.graphics.print("player posy: " .. math.round(player.y,4),hud.console.x+10,hud.console.y+130) love.graphics.print("player idle: " .. tostring(player.idle),hud.console.x+10,hud.console.y+150) end --divider love.graphics.setColor(0.607,1,1,0.39) love.graphics.line(hud.console.x+10,hud.console.y+180, hud.console.x+200,hud.console.y+180) --mission info if mode == "arcade" then love.graphics.setColor(0.39,0.745,0.784,1) love.graphics.print("progress : " .. string.format("%.2f",hud.display.progress/hud.display.w*100,4) .."%",hud.console.x+10,hud.console.y+190) love.graphics.print("elapsed : " .. misc:formatTime(hud.time), hud.console.x+10,hud.console.y+210) love.graphics.print("wave delay: " .. string.format("%.3f",enemies.waveDelay), hud.console.x+10,hud.console.y+230) end --vertical divider love.graphics.setColor(0.607,1,1,0.39) love.graphics.line(hud.console.x+201,hud.console.y+60, hud.console.x+201,hud.console.y+249) --arena info love.graphics.setColor(0.39,0.745,0.784,1) love.graphics.print("[starfield:" .. string.format("%04d",#starfield.objects) .. "|st:" .. string.format("%04d",starfield.count.star) .. "|no:" .. string.format("%02d",starfield.count.nova) .. "|ne:" .. string.format("%02d",starfield.count.nebulae) .. "|pl:" .. string.format("%02d",starfield.count.planet) .. "][speed:" .. string.format("%04d",starfield.speed) .. "]" ,hud.console.x+215,hud.console.y+70 ) if mode == "arcade" then love.graphics.print("projectiles: " .. #projectiles.missiles,hud.console.x+215,hud.console.y+90) love.graphics.print("enemies : " .. #enemies.wave,hud.console.x+215,hud.console.y+110) love.graphics.print("pickups : " .. #pickups.items,hud.console.x+215,hud.console.y+130) love.graphics.print("explosions : " .. #explosions.objects,hud.console.x+215,hud.console.y+150) love.graphics.print("kill/spawn : " .. player.kills.."/"..enemies.spawned,hud.console.x+215,hud.console.y+170) end love.graphics.setCanvas() love.graphics.setColor(1,1,1,hud.console.opacity) love.graphics.draw(hud.console.canvas,hud.console.x,hud.console.y) end love.graphics.setFont(fonts.default) end
gpl-3.0
chasing0819/Sample_CPP_Cocos2dx
tools/cocos2d-console/plugins/plugin_luacompile/bin/lua/jit/bcsave.lua
78
18123
---------------------------------------------------------------------------- -- LuaJIT module to save/list bytecode. -- -- Copyright (C) 2005-2013 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module saves or lists the bytecode for an input file. -- It's run by the -b command line option. -- ------------------------------------------------------------------------------ local jit = require("jit") assert(jit.version_num == 20001, "LuaJIT core/library version mismatch") local bit = require("bit") -- Symbol name prefix for LuaJIT bytecode. local LJBC_PREFIX = "luaJIT_BC_" ------------------------------------------------------------------------------ local function usage() io.stderr:write[[ Save LuaJIT bytecode: luajit -b[options] input output -l Only list bytecode. -s Strip debug info (default). -g Keep debug info. -n name Set module name (default: auto-detect from input name). -t type Set output file type (default: auto-detect from output name). -a arch Override architecture for object files (default: native). -o os Override OS for object files (default: native). -e chunk Use chunk string as input. -- Stop handling options. - Use stdin as input and/or stdout as output. File types: c h obj o raw (default) ]] os.exit(1) end local function check(ok, ...) if ok then return ok, ... end io.stderr:write("luajit: ", ...) io.stderr:write("\n") os.exit(1) end local function readfile(input) if type(input) == "function" then return input end if input == "-" then input = nil end return check(loadfile(input)) end local function savefile(name, mode) if name == "-" then return io.stdout end return check(io.open(name, mode)) end ------------------------------------------------------------------------------ local map_type = { raw = "raw", c = "c", h = "h", o = "obj", obj = "obj", } local map_arch = { x86 = true, x64 = true, arm = true, ppc = true, ppcspe = true, mips = true, mipsel = true, } local map_os = { linux = true, windows = true, osx = true, freebsd = true, netbsd = true, openbsd = true, solaris = true, } local function checkarg(str, map, err) str = string.lower(str) local s = check(map[str], "unknown ", err) return s == true and str or s end local function detecttype(str) local ext = string.match(string.lower(str), "%.(%a+)$") return map_type[ext] or "raw" end local function checkmodname(str) check(string.match(str, "^[%w_.%-]+$"), "bad module name") return string.gsub(str, "[%.%-]", "_") end local function detectmodname(str) if type(str) == "string" then local tail = string.match(str, "[^/\\]+$") if tail then str = tail end local head = string.match(str, "^(.*)%.[^.]*$") if head then str = head end str = string.match(str, "^[%w_.%-]+") else str = nil end check(str, "cannot derive module name, use -n name") return string.gsub(str, "[%.%-]", "_") end ------------------------------------------------------------------------------ local function bcsave_tail(fp, output, s) local ok, err = fp:write(s) if ok and output ~= "-" then ok, err = fp:close() end check(ok, "cannot write ", output, ": ", err) end local function bcsave_raw(output, s) local fp = savefile(output, "wb") bcsave_tail(fp, output, s) end local function bcsave_c(ctx, output, s) local fp = savefile(output, "w") if ctx.type == "c" then fp:write(string.format([[ #ifdef _cplusplus extern "C" #endif #ifdef _WIN32 __declspec(dllexport) #endif const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname)) else fp:write(string.format([[ #define %s%s_SIZE %d static const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname)) end local t, n, m = {}, 0, 0 for i=1,#s do local b = tostring(string.byte(s, i)) m = m + #b + 1 if m > 78 then fp:write(table.concat(t, ",", 1, n), ",\n") n, m = 0, #b + 1 end n = n + 1 t[n] = b end bcsave_tail(fp, output, table.concat(t, ",", 1, n).."\n};\n") end local function bcsave_elfobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint32_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF32header; typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint64_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF64header; typedef struct { uint32_t name, type, flags, addr, ofs, size, link, info, align, entsize; } ELF32sectheader; typedef struct { uint32_t name, type; uint64_t flags, addr, ofs, size; uint32_t link, info; uint64_t align, entsize; } ELF64sectheader; typedef struct { uint32_t name, value, size; uint8_t info, other; uint16_t sectidx; } ELF32symbol; typedef struct { uint32_t name; uint8_t info, other; uint16_t sectidx; uint64_t value, size; } ELF64symbol; typedef struct { ELF32header hdr; ELF32sectheader sect[6]; ELF32symbol sym[2]; uint8_t space[4096]; } ELF32obj; typedef struct { ELF64header hdr; ELF64sectheader sect[6]; ELF64symbol sym[2]; uint8_t space[4096]; } ELF64obj; ]] local symname = LJBC_PREFIX..ctx.modname local is64, isbe = false, false if ctx.arch == "x64" then is64 = true elseif ctx.arch == "ppc" or ctx.arch == "ppcspe" or ctx.arch == "mips" then isbe = true end -- Handle different host/target endianess. local function f32(x) return x end local f16, fofs = f32, f32 if ffi.abi("be") ~= isbe then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end if is64 then local two32 = ffi.cast("int64_t", 2^32) function fofs(x) return bit.bswap(x)*two32 end else fofs = f32 end end -- Create ELF object and fill in header. local o = ffi.new(is64 and "ELF64obj" or "ELF32obj") local hdr = o.hdr if ctx.os == "bsd" or ctx.os == "other" then -- Determine native hdr.eosabi. local bf = assert(io.open("/bin/ls", "rb")) local bs = bf:read(9) bf:close() ffi.copy(o, bs, 9) check(hdr.emagic[0] == 127, "no support for writing native object files") else hdr.emagic = "\127ELF" hdr.eosabi = ({ freebsd=9, netbsd=2, openbsd=12, solaris=6 })[ctx.os] or 0 end hdr.eclass = is64 and 2 or 1 hdr.eendian = isbe and 2 or 1 hdr.eversion = 1 hdr.type = f16(1) hdr.machine = f16(({ x86=3, x64=62, arm=40, ppc=20, ppcspe=20, mips=8, mipsel=8 })[ctx.arch]) if ctx.arch == "mips" or ctx.arch == "mipsel" then hdr.flags = 0x50001006 end hdr.version = f32(1) hdr.shofs = fofs(ffi.offsetof(o, "sect")) hdr.ehsize = f16(ffi.sizeof(hdr)) hdr.shentsize = f16(ffi.sizeof(o.sect[0])) hdr.shnum = f16(6) hdr.shstridx = f16(2) -- Fill in sections and symbols. local sofs, ofs = ffi.offsetof(o, "space"), 1 for i,name in ipairs{ ".symtab", ".shstrtab", ".strtab", ".rodata", ".note.GNU-stack", } do local sect = o.sect[i] sect.align = fofs(1) sect.name = f32(ofs) ffi.copy(o.space+ofs, name) ofs = ofs + #name+1 end o.sect[1].type = f32(2) -- .symtab o.sect[1].link = f32(3) o.sect[1].info = f32(1) o.sect[1].align = fofs(8) o.sect[1].ofs = fofs(ffi.offsetof(o, "sym")) o.sect[1].entsize = fofs(ffi.sizeof(o.sym[0])) o.sect[1].size = fofs(ffi.sizeof(o.sym)) o.sym[1].name = f32(1) o.sym[1].sectidx = f16(4) o.sym[1].size = fofs(#s) o.sym[1].info = 17 o.sect[2].type = f32(3) -- .shstrtab o.sect[2].ofs = fofs(sofs) o.sect[2].size = fofs(ofs) o.sect[3].type = f32(3) -- .strtab o.sect[3].ofs = fofs(sofs + ofs) o.sect[3].size = fofs(#symname+1) ffi.copy(o.space+ofs+1, symname) ofs = ofs + #symname + 2 o.sect[4].type = f32(1) -- .rodata o.sect[4].flags = fofs(2) o.sect[4].ofs = fofs(sofs + ofs) o.sect[4].size = fofs(#s) o.sect[5].type = f32(1) -- .note.GNU-stack o.sect[5].ofs = fofs(sofs + ofs + #s) -- Write ELF object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_peobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint16_t arch, nsects; uint32_t time, symtabofs, nsyms; uint16_t opthdrsz, flags; } PEheader; typedef struct { char name[8]; uint32_t vsize, vaddr, size, ofs, relocofs, lineofs; uint16_t nreloc, nline; uint32_t flags; } PEsection; typedef struct __attribute((packed)) { union { char name[8]; uint32_t nameref[2]; }; uint32_t value; int16_t sect; uint16_t type; uint8_t scl, naux; } PEsym; typedef struct __attribute((packed)) { uint32_t size; uint16_t nreloc, nline; uint32_t cksum; uint16_t assoc; uint8_t comdatsel, unused[3]; } PEsymaux; typedef struct { PEheader hdr; PEsection sect[2]; // Must be an even number of symbol structs. PEsym sym0; PEsymaux sym0aux; PEsym sym1; PEsymaux sym1aux; PEsym sym2; PEsym sym3; uint32_t strtabsize; uint8_t space[4096]; } PEobj; ]] local symname = LJBC_PREFIX..ctx.modname local is64 = false if ctx.arch == "x86" then symname = "_"..symname elseif ctx.arch == "x64" then is64 = true end local symexport = " /EXPORT:"..symname..",DATA " -- The file format is always little-endian. Swap if the host is big-endian. local function f32(x) return x end local f16 = f32 if ffi.abi("be") then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end end -- Create PE object and fill in header. local o = ffi.new("PEobj") local hdr = o.hdr hdr.arch = f16(({ x86=0x14c, x64=0x8664, arm=0x1c0, ppc=0x1f2, mips=0x366, mipsel=0x366 })[ctx.arch]) hdr.nsects = f16(2) hdr.symtabofs = f32(ffi.offsetof(o, "sym0")) hdr.nsyms = f32(6) -- Fill in sections and symbols. o.sect[0].name = ".drectve" o.sect[0].size = f32(#symexport) o.sect[0].flags = f32(0x00100a00) o.sym0.sect = f16(1) o.sym0.scl = 3 o.sym0.name = ".drectve" o.sym0.naux = 1 o.sym0aux.size = f32(#symexport) o.sect[1].name = ".rdata" o.sect[1].size = f32(#s) o.sect[1].flags = f32(0x40300040) o.sym1.sect = f16(2) o.sym1.scl = 3 o.sym1.name = ".rdata" o.sym1.naux = 1 o.sym1aux.size = f32(#s) o.sym2.sect = f16(2) o.sym2.scl = 2 o.sym2.nameref[1] = f32(4) o.sym3.sect = f16(-1) o.sym3.scl = 2 o.sym3.value = f32(1) o.sym3.name = "@feat.00" -- Mark as SafeSEH compliant. ffi.copy(o.space, symname) local ofs = #symname + 1 o.strtabsize = f32(ofs + 4) o.sect[0].ofs = f32(ffi.offsetof(o, "space") + ofs) ffi.copy(o.space + ofs, symexport) ofs = ofs + #symexport o.sect[1].ofs = f32(ffi.offsetof(o, "space") + ofs) -- Write PE object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_machobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint32_t magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags; } mach_header; typedef struct { mach_header; uint32_t reserved; } mach_header_64; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint32_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint64_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command_64; typedef struct { char sectname[16], segname[16]; uint32_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2; } mach_section; typedef struct { char sectname[16], segname[16]; uint64_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2, reserved3; } mach_section_64; typedef struct { uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize; } mach_symtab_command; typedef struct { int32_t strx; uint8_t type, sect; int16_t desc; uint32_t value; } mach_nlist; typedef struct { uint32_t strx; uint8_t type, sect; uint16_t desc; uint64_t value; } mach_nlist_64; typedef struct { uint32_t magic, nfat_arch; } mach_fat_header; typedef struct { uint32_t cputype, cpusubtype, offset, size, align; } mach_fat_arch; typedef struct { struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[1]; mach_nlist sym_entry; uint8_t space[4096]; } mach_obj; typedef struct { struct { mach_header_64 hdr; mach_segment_command_64 seg; mach_section_64 sec; mach_symtab_command sym; } arch[1]; mach_nlist_64 sym_entry; uint8_t space[4096]; } mach_obj_64; typedef struct { mach_fat_header fat; mach_fat_arch fat_arch[4]; struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[4]; mach_nlist sym_entry; uint8_t space[4096]; } mach_fat_obj; ]] local symname = '_'..LJBC_PREFIX..ctx.modname local isfat, is64, align, mobj = false, false, 4, "mach_obj" if ctx.arch == "x64" then is64, align, mobj = true, 8, "mach_obj_64" elseif ctx.arch == "arm" then isfat, mobj = true, "mach_fat_obj" else check(ctx.arch == "x86", "unsupported architecture for OSX") end local function aligned(v, a) return bit.band(v+a-1, -a) end local be32 = bit.bswap -- Mach-O FAT is BE, supported archs are LE. -- Create Mach-O object and fill in header. local o = ffi.new(mobj) local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align) local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12,12,12} })[ctx.arch] local cpusubtype = ({ x86={3}, x64={3}, arm={3,6,9,11} })[ctx.arch] if isfat then o.fat.magic = be32(0xcafebabe) o.fat.nfat_arch = be32(#cpusubtype) end -- Fill in sections and symbols. for i=0,#cpusubtype-1 do local ofs = 0 if isfat then local a = o.fat_arch[i] a.cputype = be32(cputype[i+1]) a.cpusubtype = be32(cpusubtype[i+1]) -- Subsequent slices overlap each other to share data. ofs = ffi.offsetof(o, "arch") + i*ffi.sizeof(o.arch[0]) a.offset = be32(ofs) a.size = be32(mach_size-ofs+#s) end local a = o.arch[i] a.hdr.magic = is64 and 0xfeedfacf or 0xfeedface a.hdr.cputype = cputype[i+1] a.hdr.cpusubtype = cpusubtype[i+1] a.hdr.filetype = 1 a.hdr.ncmds = 2 a.hdr.sizeofcmds = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)+ffi.sizeof(a.sym) a.seg.cmd = is64 and 0x19 or 0x1 a.seg.cmdsize = ffi.sizeof(a.seg)+ffi.sizeof(a.sec) a.seg.vmsize = #s a.seg.fileoff = mach_size-ofs a.seg.filesize = #s a.seg.maxprot = 1 a.seg.initprot = 1 a.seg.nsects = 1 ffi.copy(a.sec.sectname, "__data") ffi.copy(a.sec.segname, "__DATA") a.sec.size = #s a.sec.offset = mach_size-ofs a.sym.cmd = 2 a.sym.cmdsize = ffi.sizeof(a.sym) a.sym.symoff = ffi.offsetof(o, "sym_entry")-ofs a.sym.nsyms = 1 a.sym.stroff = ffi.offsetof(o, "sym_entry")+ffi.sizeof(o.sym_entry)-ofs a.sym.strsize = aligned(#symname+2, align) end o.sym_entry.type = 0xf o.sym_entry.sect = 1 o.sym_entry.strx = 1 ffi.copy(o.space+1, symname) -- Write Macho-O object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, mach_size)) bcsave_tail(fp, output, s) end local function bcsave_obj(ctx, output, s) local ok, ffi = pcall(require, "ffi") check(ok, "FFI library required to write this file type") if ctx.os == "windows" then return bcsave_peobj(ctx, output, s, ffi) elseif ctx.os == "osx" then return bcsave_machobj(ctx, output, s, ffi) else return bcsave_elfobj(ctx, output, s, ffi) end end ------------------------------------------------------------------------------ local function bclist(input, output) local f = readfile(input) require("jit.bc").dump(f, savefile(output, "w"), true) end local function bcsave(ctx, input, output) local f = readfile(input) local s = string.dump(f, ctx.strip) local t = ctx.type if not t then t = detecttype(output) ctx.type = t end if t == "raw" then bcsave_raw(output, s) else if not ctx.modname then ctx.modname = detectmodname(input) end if t == "obj" then bcsave_obj(ctx, output, s) else bcsave_c(ctx, output, s) end end end local function docmd(...) local arg = {...} local n = 1 local list = false local ctx = { strip = true, arch = jit.arch, os = string.lower(jit.os), type = false, modname = false, } while n <= #arg do local a = arg[n] if type(a) == "string" and string.sub(a, 1, 1) == "-" and a ~= "-" then table.remove(arg, n) if a == "--" then break end for m=2,#a do local opt = string.sub(a, m, m) if opt == "l" then list = true elseif opt == "s" then ctx.strip = true elseif opt == "g" then ctx.strip = false else if arg[n] == nil or m ~= #a then usage() end if opt == "e" then if n ~= 1 then usage() end arg[1] = check(loadstring(arg[1])) elseif opt == "n" then ctx.modname = checkmodname(table.remove(arg, n)) elseif opt == "t" then ctx.type = checkarg(table.remove(arg, n), map_type, "file type") elseif opt == "a" then ctx.arch = checkarg(table.remove(arg, n), map_arch, "architecture") elseif opt == "o" then ctx.os = checkarg(table.remove(arg, n), map_os, "OS name") else usage() end end end else n = n + 1 end end if list then if #arg == 0 or #arg > 2 then usage() end bclist(arg[1], arg[2] or "-") else if #arg ~= 2 then usage() end bcsave(ctx, arg[1], arg[2]) end end ------------------------------------------------------------------------------ -- Public module functions. module(...) start = docmd -- Process -b command line option.
mit
Shulyaka/packages
net/prosody/files/prosody.cfg.lua
65
9428
-- Prosody Example Configuration File -- -- Information on configuring Prosody can be found on our -- website at https://prosody.im/doc/configure -- -- Tip: You can check that the syntax of this file is correct -- when you have finished by running this command: -- prosodyctl check config -- If there are any errors, it will let you know what and where -- they are, otherwise it will keep quiet. -- -- The only thing left to do is rename this file to remove the .dist ending, and fill in the -- blanks. Good luck, and happy Jabbering! ---------- Server-wide settings ---------- -- Settings in this section apply to the whole server and are the default settings -- for any virtual hosts -- This is a (by default, empty) list of accounts that are admins -- for the server. Note that you must create the accounts separately -- (see https://prosody.im/doc/creating_accounts for info) -- Example: admins = { "user1@example.com", "user2@example.net" } admins = { } -- Enable use of libevent for better performance under high load -- For more information see: https://prosody.im/doc/libevent --use_libevent = true -- Prosody will always look in its source directory for modules, but -- this option allows you to specify additional locations where Prosody -- will look for modules first. For community modules, see https://modules.prosody.im/ --plugin_paths = {} -- This is the list of modules Prosody will load on startup. -- It looks for mod_modulename.lua in the plugins folder, so make sure that exists too. -- Documentation on modules can be found at: http://prosody.im/doc/modules modules_enabled = { -- Generally required "roster"; -- Allow users to have a roster. Recommended ;) "saslauth"; -- Authentication for clients and servers. Recommended if you want to log in. "tls"; -- Add support for secure TLS on c2s/s2s connections "dialback"; -- s2s dialback support "disco"; -- Service discovery -- Not essential, but recommended "carbons"; -- Keep multiple clients in sync "pep"; -- Enables users to publish their avatar, mood, activity, playing music and more "private"; -- Private XML storage (for room bookmarks, etc.) "blocklist"; -- Allow users to block communications with other users "vcard4"; -- User profiles (stored in PEP) "vcard_legacy"; -- Conversion between legacy vCard and PEP Avatar, vcard -- Nice to have "version"; -- Replies to server version requests "uptime"; -- Report how long server has been running "time"; -- Let others know the time here on this server "ping"; -- Replies to XMPP pings with pongs "register"; -- Allow users to register on this server using a client and change passwords --"mam"; -- Store messages in an archive and allow users to access it --"csi_simple"; -- Simple Mobile optimizations -- Admin interfaces "admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands --"admin_telnet"; -- Opens telnet console interface on localhost port 5582 -- HTTP modules --"bosh"; -- Enable BOSH clients, aka "Jabber over HTTP" --"websocket"; -- XMPP over WebSockets --"http_files"; -- Serve static files from a directory over HTTP -- Other specific functionality --"limits"; -- Enable bandwidth limiting for XMPP connections --"groups"; -- Shared roster support --"server_contact_info"; -- Publish contact information for this service --"announce"; -- Send announcement to all online users --"welcome"; -- Welcome users who register accounts --"watchregistrations"; -- Alert admins of registrations --"motd"; -- Send a message to users when they log in --"legacyauth"; -- Legacy authentication. Only used by some old clients and bots. --"proxy65"; -- Enables a file transfer proxy service which clients behind NAT can use } -- These modules are auto-loaded, but should you want -- to disable them then uncomment them here: modules_disabled = { -- "offline"; -- Store offline messages -- "c2s"; -- Handle client connections -- "s2s"; -- Handle server-to-server connections -- "posix"; -- POSIX functionality, sends server to background, enables syslog, etc. } -- Disable account creation by default, for security -- For more information see https://prosody.im/doc/creating_accounts allow_registration = false -- Force clients to use encrypted connections? This option will -- prevent clients from authenticating unless they are using encryption. c2s_require_encryption = true -- Force servers to use encrypted connections? This option will -- prevent servers from authenticating unless they are using encryption. s2s_require_encryption = true -- Force certificate authentication for server-to-server connections? s2s_secure_auth = false -- Some servers have invalid or self-signed certificates. You can list -- remote domains here that will not be required to authenticate using -- certificates. They will be authenticated using DNS instead, even -- when s2s_secure_auth is enabled. --s2s_insecure_domains = { "insecure.example" } -- Even if you disable s2s_secure_auth, you can still require valid -- certificates for some domains by specifying a list here. --s2s_secure_domains = { "jabber.org" } -- Select the authentication backend to use. The 'internal' providers -- use Prosody's configured data storage to store the authentication data. authentication = "internal_hashed" -- Select the storage backend to use. By default Prosody uses flat files -- in its configured data directory, but it also supports more backends -- through modules. An "sql" backend is included by default, but requires -- additional dependencies. See https://prosody.im/doc/storage for more info. --storage = "sql" -- Default is "internal" -- For the "sql" backend, you can uncomment *one* of the below to configure: --sql = { driver = "SQLite3", database = "prosody.sqlite" } -- Default. 'database' is the filename. --sql = { driver = "MySQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" } --sql = { driver = "PostgreSQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" } -- Archiving configuration -- If mod_mam is enabled, Prosody will store a copy of every message. This -- is used to synchronize conversations between multiple clients, even if -- they are offline. This setting controls how long Prosody will keep -- messages in the archive before removing them. archive_expires_after = "1w" -- Remove archived messages after 1 week -- You can also configure messages to be stored in-memory only. For more -- archiving options, see https://prosody.im/doc/modules/mod_mam -- Logging configuration -- For advanced logging see http://prosody.im/doc/logging log = { info = "/var/log/prosody/prosody.log"; -- Change 'info' to 'debug' for verbose logging error = "/var/log/prosody/prosody.err"; -- "*syslog"; -- Uncomment this for logging to syslog; needs mod_posix -- "*console"; -- Log to the console, useful for debugging with daemonize=false } -- Uncomment to enable statistics -- For more info see https://prosody.im/doc/statistics -- statistics = "internal" -- Pidfile, used by prosodyctl and the init.d script pidfile = "/var/run/prosody/prosody.pid" -- User and group, used for daemon prosody_user = "prosody" prosody_group = "prosody" -- Certificates -- Every virtual host and component needs a certificate so that clients and -- servers can securely verify its identity. Prosody will automatically load -- certificates/keys from the directory specified here. -- For more information, including how to use 'prosodyctl' to auto-import certificates -- (from e.g. Let's Encrypt) see https://prosody.im/doc/certificates -- Location of directory to find certificates in (relative to main config file): --certificates = "certs" -- HTTPS currently only supports a single certificate, specify it here: --https_certificate = "certs/localhost.crt" ----------- Virtual hosts ----------- -- You need to add a VirtualHost entry for each domain you wish Prosody to serve. -- Settings under each VirtualHost entry apply *only* to that host. VirtualHost "localhost" VirtualHost "example.com" enabled = false -- Remove this line to enable this host -- Assign this host a certificate for TLS, otherwise it would use the one -- set in the global section (if any). -- Note that old-style SSL on port 5223 only supports one certificate, and will always -- use the global one. ssl = { key = "/etc/prosody/certs/example.com.key"; certificate = "/etc/prosody/certs/example.com.crt"; } ------ Components ------ -- You can specify components to add hosts that provide special services, -- like multi-user conferences, and transports. -- For more information on components, see http://prosody.im/doc/components ---Set up a MUC (multi-user chat) room server on conference.example.com: --Component "conference.example.com" "muc" -- Set up a SOCKS5 bytestream proxy for server-proxied file transfers: --Component "proxy.example.com" "proxy65" --- Store MUC messages in an archive and allow users to access it --modules_enabled = { "muc_mam" } ---Set up an external component (default component port is 5347) -- -- External components allow adding various services, such as gateways/ -- transports to other networks like ICQ, MSN and Yahoo. For more info -- see: http://prosody.im/doc/components#adding_an_external_component -- --Component "gateway.example.com" -- component_secret = "password"
gpl-2.0
ffxiphoenix/darkstar
scripts/globals/items/weavers_belt.lua
30
1206
----------------------------------------- -- ID: 15447 -- Item: Weaver's Belt -- Enchantment: Synthesis image support -- 2Min, All Races ----------------------------------------- -- Enchantment: Synthesis image support -- Duration: 2Min -- Clothcraft Skill +3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY) == true) then result = 239; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY,3,0,120); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_SKILL_CLT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_SKILL_CLT, 1); end;
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Zaranf.lua
34
1031
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Zaranf -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x029C); 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
powerboat9/computercraft
apis/Learn_v1/core.lua
1
1766
function findInsertSpot(t) lastK = 0 for k, v in pairs(t) do if lastK + 1 < k then return lastK + 1 elseif v == nil then return k else lastK++ end end end local nodeMeta = { name = "(Unregistered)" binary = true value = 0 unstable = 0 ticksStable = 0 hold = 0 holdValue = 0 setValue = function(self, reason, params) reason = reason or "Unknown" if reason == "EMP" then self.stage = 2 self.ticksStable = params["ticks"] elseif reason == "Hold" self.stage = 3 self.ticksStable = 0 self.holdValue = params["newValue"] elseif reason == "Reset Stage" self.stage = 1 elseif reason == "Basic_IO" self.value = params["newValue"] else if doPrint = 1 then print("You tried to call setValue() on " .. self.name .. "with no valid reason. You may see unexpected results") end end end } local nodeNetMeta = { nodeDictionary = {}, nodes = {}, newNode addNode = function(self, name) if nodes[name] == nil then local newNode = {} set nodes[name] = } local actionMeta = { fire = {}, pointer = 1, setPointer = function(self, newPointer) self.pointer = newPointer end, resetPointer = function(self) self:setPointer(1) end, writeData = function(self, nodes) self.fire[self.pointer] = nodes end } function newAction() local action = {} setmetatable(action, actionMeta) return action end doPrint = 1
mit
ffxiphoenix/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Gevarg.lua
38
1052
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Gevarg -- Type: Past Event Watcher -- @zone: 94 -- @pos -46.448 -6.312 212.384 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0000); 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
Ankoku/df-webfort
dist/shared/hack/scripts/webfort/deify.lua
2
2426
-- Renames a random dwarf or deity. local json = require 'dkjson' local utils = require 'utils' function get_hfig(hf_id) return utils.binsearch(df.global.world.history.figures, hf_id, 'id') end function unit_to_hfig(unit) if unit and unit.hist_figure_id then return get_hfig(unit.hist_figure_id) end return nil end function get_hfig_name(hfig, in_english) return dfhack.TranslateName(hfig.name, in_english or false) end function get_citizens() local dorfs = {} for _, u in ipairs(df.global.world.units.all) do if dfhack.units.isCitizen(u) then table.insert(dorfs, u) end end return dorfs end function get_current_gods() local gods = {} local dorfs = get_citizens() for _, dorf in ipairs(dorfs) do local hdorf = unit_to_hfig(dorf) for _, link in ipairs(hdorf.histfig_links) do if link:getType() == df.histfig_hf_link_type.DEITY then gods[link.target_hf] = true end end end return gods end function make_list(set) local list = {} for k in pairs(set) do table.insert(list, k) end return list end function make_set(list) local set = {} for _, v in ipairs(list) do set[v] = true end return set end function choice(list) if #list < 1 then return nil end return list[math.random(#list)] end function serialize(state) dfhack.persistent.save { key = 'deifyState', value = json.encode(state) } end local default = { value = [[ { "used_gods": {} } ]] } function deserialize() return json.decode((dfhack.persistent.get('deifyState') or default).value) end function get_new_gods(state, gods) local new_gods = {} local old_gods = make_set(state.used_gods) for god in pairs(gods) do if not old_gods[god] then new_gods[god] = true end end return make_list(new_gods) end function find_named_god(state, name) for _, god_id in ipairs(state.used_gods) do if get_hfig(god_id).name.first_name == name then return god_id end end return nil end function name_god(state, god_id, name) if find_named_god(state, name) then return false end local godfig = get_hfig(god_id) godfig.name.first_name = name table.insert(state.used_gods, god_id) return true end function main(name) if not name then print("specify a name.") return end local state = deserialize() local new_gods = get_new_gods(state, get_current_gods()) local new_god = choice(new_gods) if new_god then name_god(state, new_god, name) end serialize(state) end main(...)
isc
Ne02ptzero/Grog-Knight
Tools/BuildScripts/lua-lib/penlight-1.0.2/lua/pl/pretty.lua
12
8296
--- Pretty-printing Lua tables. -- Also provides a sandboxed Lua table reader and -- a function to present large numbers in human-friendly format. -- -- Dependencies: `pl.utils`, `pl.lexer` -- @module pl.pretty local append = table.insert local concat = table.concat local utils = require 'pl.utils' local lexer = require 'pl.lexer' local assert_arg = utils.assert_arg local pretty = {} local function save_string_index () local SMT = getmetatable '' if SMT then SMT.old__index = SMT.__index SMT.__index = nil end return SMT end local function restore_string_index (SMT) if SMT then SMT.__index = SMT.old__index end end --- read a string representation of a Lua table. -- Uses load(), but tries to be cautious about loading arbitrary code! -- It is expecting a string of the form '{...}', with perhaps some whitespace -- before or after the curly braces. A comment may occur beforehand. -- An empty environment is used, and -- any occurance of the keyword 'function' will be considered a problem. -- in the given environment - the return value may be `nil`. -- @param s {string} string of the form '{...}', with perhaps some whitespace -- before or after the curly braces. -- @return a table function pretty.read(s) assert_arg(1,s,'string') if s:find '^%s*%-%-' then -- may start with a comment.. s = s:gsub('%-%-.-\n','') end if not s:find '^%s*%b{}%s*$' then return nil,"not a Lua table" end if s:find '[^\'"%w_]function[^\'"%w_]' then local tok = lexer.lua(s) for t,v in tok do if t == 'keyword' then return nil,"cannot have functions in table definition" end end end s = 'return '..s local chunk,err = utils.load(s,'tbl','t',{}) if not chunk then return nil,err end local SMT = save_string_index() local ok,ret = pcall(chunk) restore_string_index(SMT) if ok then return ret else return nil,ret end end --- read a Lua chunk. -- @param s Lua code -- @param env optional environment -- @param paranoid prevent any looping constructs and disable string methods -- @return the environment function pretty.load (s, env, paranoid) env = env or {} if paranoid then local tok = lexer.lua(s) for t,v in tok do if t == 'keyword' and (v == 'for' or v == 'repeat' or v == 'function' or v == 'goto') then return nil,"looping not allowed" end end end local chunk,err = utils.load(s,'tbl','t',env) if not chunk then return nil,err end local SMT = paranoid and save_string_index() local ok,err = pcall(chunk) restore_string_index(SMT) if not ok then return nil,err end return env end local function quote_if_necessary (v) if not v then return '' else if v:find ' ' then v = '"'..v..'"' end end return v end local keywords local function is_identifier (s) return type(s) == 'string' and s:find('^[%a_][%w_]*$') and not keywords[s] end local function quote (s) if type(s) == 'table' then return pretty.write(s,'') else return ('%q'):format(tostring(s)) end end local function index (numkey,key) if not numkey then key = quote(key) end return '['..key..']' end --- Create a string representation of a Lua table. -- This function never fails, but may complain by returning an -- extra value. Normally puts out one item per line, using -- the provided indent; set the second parameter to '' if -- you want output on one line. -- @param tbl {table} Table to serialize to a string. -- @param space {string} (optional) The indent to use. -- Defaults to two spaces; make it the empty string for no indentation -- @param not_clever {bool} (optional) Use for plain output, e.g {['key']=1}. -- Defaults to false. -- @return a string -- @return a possible error message function pretty.write (tbl,space,not_clever) if type(tbl) ~= 'table' then local res = tostring(tbl) if type(tbl) == 'string' then res = '"'..res..'"' end return res, 'not a table' end if not keywords then keywords = lexer.get_keywords() end local set = ' = ' if space == '' then set = '=' end space = space or ' ' local lines = {} local line = '' local tables = {} local function put(s) if #s > 0 then line = line..s end end local function putln (s) if #line > 0 then line = line..s append(lines,line) line = '' else append(lines,s) end end local function eat_last_comma () local n,lastch = #lines local lastch = lines[n]:sub(-1,-1) if lastch == ',' then lines[n] = lines[n]:sub(1,-2) end end local writeit writeit = function (t,oldindent,indent) local tp = type(t) if tp ~= 'string' and tp ~= 'table' then putln(quote_if_necessary(tostring(t))..',') elseif tp == 'string' then if t:find('\n') then putln('[[\n'..t..']],') else putln(quote(t)..',') end elseif tp == 'table' then if tables[t] then putln('<cycle>,') return end tables[t] = true local newindent = indent..space putln('{') local used = {} if not not_clever then for i,val in ipairs(t) do put(indent) writeit(val,indent,newindent) used[i] = true end end for key,val in pairs(t) do local numkey = type(key) == 'number' if not_clever then key = tostring(key) put(indent..index(numkey,key)..set) writeit(val,indent,newindent) else if not numkey or not used[key] then -- non-array indices if numkey or not is_identifier(key) then key = index(numkey,key) end put(indent..key..set) writeit(val,indent,newindent) end end end eat_last_comma() putln(oldindent..'},') else putln(tostring(t)..',') end end writeit(tbl,'',space) eat_last_comma() return concat(lines,#space > 0 and '\n' or '') end --- Dump a Lua table out to a file or stdout. -- @param t {table} The table to write to a file or stdout. -- @param ... {string} (optional) File name to write too. Defaults to writing -- to stdout. function pretty.dump (t,...) if select('#',...)==0 then print(pretty.write(t)) return true else return utils.writefile(...,pretty.write(t)) end end local memp,nump = {'B','KiB','MiB','GiB'},{'','K','M','B'} local comma function comma (val) local thou = math.floor(val/1000) if thou > 0 then return comma(thou)..','..(val % 1000) else return tostring(val) end end --- format large numbers nicely for human consumption. -- @param num a number -- @param kind one of 'M' (memory in KiB etc), 'N' (postfixes are 'K','M' and 'B') -- and 'T' (use commas as thousands separator) -- @param prec number of digits to use for 'M' and 'N' (default 1) function pretty.number (num,kind,prec) local fmt = '%.'..(prec or 1)..'f%s' if kind == 'T' then return comma(num) else local postfixes, fact if kind == 'M' then fact = 1024 postfixes = memp else fact = 1000 postfixes = nump end local div = fact local k = 1 while num >= div and k <= #postfixes do div = div * fact k = k + 1 end div = div / fact if k > #postfixes then k = k - 1; div = div/fact end if k > 1 then return fmt:format(num/div,postfixes[k] or 'duh') else return num..postfixes[1] end end end return pretty
apache-2.0
ffxiphoenix/darkstar
scripts/zones/RuLude_Gardens/npcs/Rainhard.lua
38
1037
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Rainhard -- Type: Standard NPC -- @zone: 243 -- @pos -2.397 -5.999 68.749 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0022); 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
farrajota/human_pose_estimation_torch
models/test/hg-generic-maxpool.lua
1
1792
paths.dofile('../layers/Residual.lua') local function hourglass(n, f, inp) -- Upper branch local up1 = Residual(f,f)(inp) -- Lower branch local pool = nn.SpatialMaxPooling(2,2,2,2)(inp) local low1 = Residual(f,f)(pool) local low2 if n > 1 then low2 = hourglass(n-1,f,low1) else low2 = Residual(f,f)(low1) end local low3 = Residual(f,f)(low2) local up2 = nn.SpatialUpSamplingNearest(2)(low3) -- Bring two branches together return nn.CAddTable()({up1,up2}) end local function lin(numIn,numOut,inp) -- Apply 1x1 convolution, stride 1, no padding local l = nn.SpatialConvolution(numIn,numOut,1,1,1,1,0,0)(inp) return nn.ReLU(true)(nn.SpatialBatchNormalization(numOut)(l)) end local function createModel() local inp = nn.Identity()() -- Initial processing of the image local cnv1_ = nn.SpatialConvolution(3,64,7,7,2,2,3,3)(inp) -- 128 local cnv1 = nn.ReLU(true)(nn.SpatialBatchNormalization(64)(cnv1_)) local r1 = Residual(64,128)(cnv1) local pool = nn.SpatialMaxPooling(2,2,2,2)(r1) -- 64 local r4 = Residual(128,128)(pool) local r5 = Residual(128,opt.nFeats)(r4) local out = {} local inter = r5 for i = 1,opt.nStack do local hg = hourglass(6,opt.nFeats,inter) --max 6 -- Linear layer to produce first set of predictions local ll = lin(opt.nFeats,opt.nFeats,hg) -- Predicted heatmaps local tmpOut = nn.SpatialConvolution(opt.nFeats,outputDim[1][1],1,1,1,1,0,0)(ll) table.insert(out,tmpOut) if i < opt.nStack then inter = nn.CAddTable()({inter, hg}) end end -- Final model local model = nn.gModule({inp}, out) return model end ------------------------- return createModel
mit
ffxiphoenix/darkstar
scripts/globals/spells/bluemagic/reactor_cool.lua
17
2109
----------------------------------------- -- Spell: Reactor Cool -- Enhances defense and covers you with magical ice spikes. Enemies that hit you take ice damage -- Spell cost: 28 MP -- Monster Type: Luminions -- Spell Type: Magical (Ice) -- Blue Magic Points: 5 -- Stat Bonus: INT+3 MND+3 -- Level: 74 -- Casting Time: 3 seconds -- Recast Time: 60 seconds -- Duration: 120 seconds (2 minutes) -- -- Combos: Magic Attack Bonus ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffectOne = EFFECT_ICE_SPIKES local typeEffectTwo = EFFECT_DEFENSE_BOOST local powerOne = 5; local powerTwo = 12 local duration = 120; local returnEffect = typeEffectOne; if (caster:hasStatusEffect(EFFECT_DIFFUSION)) then local diffMerit = caster:getMerit(MERIT_DIFFUSION); if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit; end; caster:delStatusEffect(EFFECT_DIFFUSION); end; if (target:addStatusEffect(typeEffectOne,powerOne,0,duration) == false and target:addStatusEffect(typeEffectTwo,powerTwo,0,duration) == false) then -- both statuses fail to apply spell:setMsg(75); elseif (target:addStatusEffect(typeEffectOne,powerOne,0,duration) == false) then -- the first status fails to apply target:addStatusEffect(typeEffectTwo,powerTwo,0,duration) spell:setMsg(230); returnEffect = typeEffectTwo; else target:addStatusEffect(typeEffectOne,powerOne,0,duration) target:addStatusEffect(typeEffectTwo,powerTwo,0,duration) spell:setMsg(230); end; return returnEffect; end;
gpl-3.0
vilarion/Illarion-Content
craft/base/crafts.lua
1
31327
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- basic function for craft handling -- Nitram -- added object orientation by vilarion -- rewritten for VBU by vilarion local common = require("base.common") local shared = require("craft.base.shared") local lookat = require("base.lookat") local licence = require("base.licence") local gems = require("base.gems") local glypheffects = require("magic.glypheffects") local OFFSET_PRODUCTS_REPAIR = 235 local repairItemList = {} --[[productId for craftable items: id in products table. productId for repairable items position in inventory plus offset. Inventory has 17 positions, max productId = 255 ]]-- local REPAIR_RESOURCE_USAGE = 0.3 -- 0-1; 0.5 means: probability to need ingedient for 100% repair local REPAIR_QUALITY_INCREASE_GENERAL = 0.6 -- probability for quality increase at 100% repair local REPAIR_QUALITY_INCREASE_KNOWN_CRAFTER = 0.4 -- additional probability for quality increase at 100% repair if item made by player local DUMMY_MIN_SKILL_REPAIR_ONLY = 200 -- not reachable skill for group 'repair only', need to hide not craftable items local M = {} local Product = { quantity = 1, ingredients = {}, difficulty = 0, remnants = {}, } function Product:new(p) -- new: constructor p = p or {} -- if p=nil then create an empty list setmetatable(p, self) -- metatable: holds functions of a class. loads product-stuff into this new product p. self.__index = self return p end local Craft = { products = {}, categories = {}, skill = nil, handTool = 0, tool = {}, activeTool = {}, toolLink = {}, sfx = 0, sfxDuration = 0, fallbackCraft = nil, } -- constructor --[[ Usage: myCraft = Craft:new{ craftEN = "CRAFT_EN", craftDE = "CRAFT_DE", handTool = ID, [leadSkill = SKILL | leadSkill = function(user)], [sfx = SFX, sfxDuration = DURATION,] [fallbackCraft = CRAFTWITHSAMEHANDTOOL,] [npcCraft = true,] [lookAtFilter = (lookAt function(user, lookAt, data)),] } --]] function Craft:new(c) c = c or {} setmetatable(c, self) self.__index = self c.products = {} c.categories = {} c.tool = {} c.activeTool = {} c.toolLink = {} c.defaultProduct = Product:new{} return c end function Craft:addTool(itemId) if not self.defaultTool then self.defaultTool = itemId end self.tool[itemId] = true end function Craft:addActiveTool(inactiveItemId, itemId) self.activeTool[itemId] = true self.toolLink[itemId] = inactiveItemId self.toolLink[inactiveItemId] = itemId end function Craft:addCategory(categoryNameEN, categoryNameDE) table.insert(self.categories, {nameEN = categoryNameEN, nameDE = categoryNameDE, minSkill = nil}) return #self.categories end function Product:addIngredient(item, quantity, data) quantity = quantity or 1 data = data or {} table.insert(self["ingredients"], {["item"]=item, ["quantity"]=quantity, ["data"]=data}) end function Product:addRemnant(item, quantity, data) quantity = quantity or 1 data = data or {} table.insert(self["remnants"], {["item"]=item, ["quantity"]=quantity, ["data"]=data}) end function Craft:addProduct(categoryId, itemId, quantity, data) local difficulty = math.min(world:getItemStatsFromId(itemId).Level, 100) local learnLimit = math.min(difficulty + 20, 100) quantity = quantity or 1 data = data or {} if categoryId > 0 and categoryId <= #self.categories then table.insert(self.products, self.defaultProduct:new{ ["category"] = categoryId, ["item"] = itemId, ["difficulty"] = difficulty, ["learnLimit"] = learnLimit, ["quantity"] = quantity, ["data"] = data, ["ingredients"] = {}, ["remnants"] = {}, }) if self.categories[categoryId].minSkill then self.categories[categoryId].minSkill = math.min(self.categories[categoryId].minSkill, difficulty) else self.categories[categoryId].minSkill = difficulty end if self:isRepairCategory(categoryId) then self.categories[categoryId].minSkill = DUMMY_MIN_SKILL_REPAIR_ONLY end return self.products[#self.products] end return nil end function Craft:showDialog(user, source) if not self:allowCrafting(user, source) then if self.fallbackCraft then self.fallbackCraft:showDialog(user, source) end return end local callback = function(dialog) local result = dialog:getResult() if result == CraftingDialog.playerCrafts then local productId = dialog:getCraftableId() if self:isRepairItem(productId) then productId = self:findReferenceProductId(user,productId) end local neededFood = 0 local foodOK = false local product = self.products[productId] foodOK, neededFood = self:checkRequiredFood(user, product:getCraftingTime(self:getSkill(user))) local canWork = self:allowCrafting(user, source) and self:checkMaterial(user, productId) and foodOK if canWork then self:swapToActiveItem(user) end return canWork elseif result == CraftingDialog.playerLooksAtItem then local productId = dialog:getCraftableId() return self:getProductLookAt(user, productId) elseif result == CraftingDialog.playerLooksAtIngredient then local productId = dialog:getCraftableId() local ingredientId = dialog:getIngredientIndex() + 1 return self:getIngredientLookAt(user, productId, ingredientId) elseif result == CraftingDialog.playerCraftingComplete then local productId = dialog:getCraftableId() local skillGain if self:isRepairItem(productId) then skillGain = self:repairItem(user, productId) else skillGain = self:craftItem(user, productId) end if skillGain then self:refreshDialog(dialog, user) end return skillGain elseif result == CraftingDialog.playerCraftingAborted then self:swapToInactiveItem(user) else self:swapToInactiveItem(user) end end local dialog = CraftingDialog(self:getName(user), self.sfx, self.sfxDuration, callback) self:loadDialog(dialog, user) user:requestCraftingDialog(dialog) end -------------------------------------------------------------------------------- function Craft:allowCrafting(user, source) if not self.npcCraft then return self:allowUserCrafting(user, source) else return self:allowNpcCrafting(user, source) end return false end function Craft:allowUserCrafting(user, source) if source:getType() == scriptItem.field and self.tool[source.id] then common.TurnTo(user, source.pos) if not self:userHasLicense(user) then return false end if not self:isHandToolEquipped(user) then local germanTool = world:getItemName(self.handTool, Player.german) germanTool = germanTool:gsub("^%l", string.upper) --Upper case local englishTool = world:getItemName(self.handTool, Player.english) englishTool = englishTool:gsub("^%l", string.upper) --Upper case common.HighInformNLS(user, "Dir fehlt ein intaktes Werkzeug in deiner Hand um hier zu arbeiten: " .. germanTool, "To work here you have to hold an intact tool in your hand: " .. englishTool) return false end else if not self:locationFine(user) then return false end if not self:userHasLicense(user) then return false end if not self:isHandToolEquipped(user) then self:swapToInactiveItem(user) common.HighInformNLS(user, "Du musst ein intaktes Werkzeug in die Hand nehmen um damit zu arbeiten.", "You must have an intact tool in your hand to work with.") return false end end return true end function Craft:userHasLicense(user) return not licence.licence(user) end function Craft:isHandToolEquipped(user) local leftTool = user:getItemAt(Character.left_tool) local rightTool = user:getItemAt(Character.right_tool) if leftTool.id == self.handTool and common.isBroken(leftTool) == false then return true elseif rightTool.id == self.handTool and common.isBroken(rightTool) == false then return true end return false end function Craft:getHandToolEquipped(user) local leftTool = user:getItemAt(Character.left_tool) local rightTool = user:getItemAt(Character.right_tool) if leftTool.id == self.handTool and common.isBroken(leftTool) == false then return leftTool elseif rightTool.id == self.handTool and common.isBroken(rightTool) == false then return rightTool end return nil end function Craft:getCurrentGemBonus(user) local handItem = self:getHandToolEquipped(user) if handItem ~= nil then return gems.getGemBonus(handItem) else return 0 end end function Craft:allowNpcCrafting(user, source) return user:isInRange(source, 2) end function Craft:getProductLookAt(user, productId) local lookAt if self:isRepairItem(productId) then lookAt = lookat.GenerateLookAt(user, user:getItemAt( productId - OFFSET_PRODUCTS_REPAIR ), 0) else local product = self.products[productId] lookAt = self:getLookAt(user, product) end return lookAt end function Craft:getIngredientLookAt(user, productId, ingredientId) local lookAt if self:isRepairItem(productId) then productId = self:findReferenceProductId(user, productId) end local ingredient = self.products[productId].ingredients[ingredientId] lookAt = self:getLookAt(user, ingredient) return lookAt end function Craft:getLookAt(user, object) local item = object.item local quantity = object.quantity local data = object.data local lookAt = lookat.GenerateItemLookAtFromId(user, item, quantity, data) if self.lookAtFilter then lookAt = self.lookAtFilter(user, lookAt, data) end return lookAt end function Craft:getName(user) local isGerman = (user:getPlayerLanguage() == Player.german) local craft if isGerman then craft = self.craftDE else craft = self.craftEN end craft = craft or "unknown craft" return craft end function Craft:cleanRepairItemList (user) local limitTime = common.GetCurrentTimestamp() - 18000 --5hrs ago for _, listEntry in ipairs(repairItemList) do if listEntry[1] < limitTime then listEntry = nil end end end function Craft:loadDialog(dialog, user) local skill = self:getSkill(user) local categoryListId = {} local listId = 0 for i = 1,#self.categories do local category = self.categories[i] local categoryRequirement = category.minSkill if categoryRequirement and categoryRequirement <= skill then if(category.nameEN~="Rare Items") then if user:getPlayerLanguage() == Player.german then dialog:addGroup(category.nameDE) else dialog:addGroup(category.nameEN) end categoryListId[i] = listId listId = listId + 1 end end end local repairListId = listId local glyphEffect = 1 glyphEffect = glypheffects.effectOnCraftingTime(user) local gemBonus = self:getCurrentGemBonus(user) for i = 1,#self.products do local product = self.products[i] local productRequirement = product.difficulty if productRequirement <= skill and self:isRepairCategory(product.category) == false then local craftingTime = self:getCraftingTime(product, skill) * glyphEffect dialog:addCraftable(i, categoryListId[product.category], product.item, self:getLookAt(user, product).name, craftingTime, product.quantity) for j = 1, #product.ingredients do local ingredient = product.ingredients[j] dialog:addCraftableIngredient(ingredient.item, ingredient.quantity) end end end local repairPositions = {12, 13, 14, 15, 16, 17} -- all belt positions local showRepairGroup = false local repairSkill = self:getRepairSkill(user) local glyphEffect = 1 local repairItemListSub = {} local hasDataRepairItemListSub = false for k = 1, #repairPositions do local itemAtCharacter = user:getItemAt( repairPositions[k] ) local itemStats = world:getItemStatsFromId(itemAtCharacter.id) local durability = common.getItemDurability(itemAtCharacter) if itemStats.MaxStack == 1 then for i = 1, #self.products do local product = self.products[i] local productRequirement = product.difficulty local craftingTime = self:getCraftingTime(product, repairSkill) if product.item == itemAtCharacter.id and productRequirement <= repairSkill and ((craftingTime * (99 - durability)/99) > 9 or durability < 91 ) then if showRepairGroup == false then dialog:addGroup(user:getPlayerLanguage() == Player.german and "Reparieren" or "Repair") showRepairGroup = true glyphEffect = glypheffects.effectOnRepairTime(user) end craftingTime = craftingTime * glyphEffect * (99 - durability)/99 local listPosition = OFFSET_PRODUCTS_REPAIR+repairPositions[k] dialog:addCraftable(listPosition, repairListId, product.item, self:getLookAt(user, product).name, craftingTime, product.quantity) repairItemListSub[listPosition] = {product.item, durability} hasDataRepairItemListSub = true for j = 1, #product.ingredients do local ingredient = product.ingredients[j] dialog:addCraftableIngredient(ingredient.item, ingredient.quantity) end end end end end self:cleanRepairItemList (user) if hasDataRepairItemListSub then repairItemListSub[1] = common.GetCurrentTimestamp() repairItemList[user.id] = repairItemListSub else repairItemList[user.id]=nil end end function Craft:refreshDialog(dialog, user) dialog:clearGroupsAndProducts() self:loadDialog(dialog, user) end function Craft:getCraftingTime(product, skill) if not self.npcCraft then return product:getCraftingTime(skill) else return 10 --default time end end function Product:getCraftingTime(skill) --This function returns the crafting time, scaled by the price of the item. local learnProgress if (self.learnLimit == self.difficulty) then learnProgress = 50 --This is a temporary solution until we get "effective" skills beyond 100 as proposed by Bloodraven, see Ars Magica else learnProgress = (skill - self.difficulty) / (self.learnLimit - self.difficulty) * 100 end local theItem = world:getItemStatsFromId(self.item) local minimum = math.max (((30+((self.quantity * theItem.Worth)-200)*(1500-30)/(133300-200))),30) --30: Minimum time; 200: Minimum price; 1500: maximum time; 133300: maximum price local craftingTime = common.Scale(minimum * 2, minimum, learnProgress) if craftingTime > 99 then craftingTime = 10 * math.floor(craftingTime/10 + 0.5) -- Round correctly to whole seconds end return craftingTime end function Craft:swapToActiveItem(user) if self.npcCraft then return end local frontItem = common.GetFrontItem(user) if not self.toolLink[frontItem.id] then return end if not self.tool[frontItem.id] then return end if self.activeTool[frontItem.id] then return end frontItem.id = self.toolLink[frontItem.id] frontItem.wear = 2 world:changeItem(frontItem) end function Craft:swapToInactiveItem(user) if self.npcCraft then return end local frontItem = common.GetFrontItem(user) if not self.toolLink[frontItem.id] then return end if self.tool[frontItem.id] then return end if not self.activeTool[frontItem.id] then return end if frontItem.id ~= self.toolLink[frontItem.id] then frontItem.id = self.toolLink[frontItem.id] frontItem.wear = 255 world:changeItem(frontItem) end end function Craft:checkRequiredFood(user, craftingTime) local neededFood=craftingTime*4 --One second of crafting takes 40 food points if common.FitForHardWork(user, math.ceil(neededFood+craftingTime*0.1)) then --Each second, one spends one food point per default. return true, neededFood else return false, 0 end end function Craft:getSkill(user) local skillType = type(self.leadSkill) if skillType == "number" then return user:getSkill(self.leadSkill) elseif skillType == "function" then return self.leadSkill(user) else return 0 end end function Craft:checkMaterial(user, productId) local product = self.products[productId] if product == nil then return false end local materialsAvailable = true local lackText = "" local enoughText = "" for i = 1, #product.ingredients do local ingredient = product.ingredients[i] local available = user:countItemAt("all", ingredient.item, ingredient.data) if available < ingredient.quantity then materialsAvailable = false local ingredientName = self:getLookAt(user, ingredient).name if available == 0 then lackText = lackText..ingredientName..", " else enoughText = enoughText..ingredientName..", " end end end if lackText ~= "" then lackText=string.sub(lackText,1,-3) common.HighInformNLS( user, "Dir fehlt: "..lackText.."!", "You lack: "..lackText..".") end if enoughText ~= "" then enoughText=string.sub(enoughText,1,-3) common.HighInformNLS(user, "Zu wenig: "..enoughText..".", "Not enough: "..enoughText..".") end return materialsAvailable end function Craft:generateQuality(user, productId, toolItem) local product = self.products[productId] if self.npcCraft then return 999 end local gemBonus = tonumber(self:getCurrentGemBonus(user)) local userDexterity = user:increaseAttrib("dexterity", 0) local meanQuality = 5 meanQuality = meanQuality*(1+common.GetAttributeBonusHigh(userDexterity)+common.GetQualityBonusStandard(toolItem))+gemBonus/100 --Apply boni of dexterity, tool quality and gems. meanQuality = common.Limit(meanQuality, 1, 8.5) --Limit to a reasonable maximum to avoid overflow ("everything quality 9"). The value here needs unnatural attributes. local quality = 1 --Minimum quality value. local rolls = 8 --There are eight chances to increase the quality by one. This results in a quality distribution 1-9. local probability = (meanQuality-1)/rolls --This will result in a binominal distribution of quality with meanQuality as average value. for i=1,rolls do if math.random()<probability then quality=quality+1 end end quality = common.Limit(quality, 1, common.ITEM_MAX_QUALITY) local durability = common.ITEM_MAX_DURABILITY return common.calculateItemQualityDurability(quality, durability) end function Craft:locationFine(user) self:turnToTool(user) local staticTool = common.GetFrontItemID(user) if self.activeTool[staticTool] then if not self.fallbackCraft then common.HighInformNLS(user, "Hier arbeitet schon jemand.", "Someone is working here already.") end return false elseif not self.tool[staticTool] then if not self.fallbackCraft then local germanTool = world:getItemName(self.defaultTool, Player.german) local englishTool = world:getItemName(self.defaultTool, Player.english) common.HighInformNLS(user, "Du stehst nicht neben dem benötigten Werkzeug: " .. germanTool, "There is no " .. englishTool .. " close by to work with.") end return false elseif common.GetFrontItem(user).id == 359 and common.GetFrontItem(user).quality == 100 then if not self.fallbackCraft then common.HighInformNLS(user, "Aus irgendeinem Grund liefert die Flamme nicht die benötigte Hitze.", "For some reason the flame does not provide the required heat.") end return false end return true end -- Turn to a static tool, keeping the turning radius as small as possible and searching -- in the following order around the user (u), starting at the frontal position (1): -- 2 1 3 -- 4 u 5 -- 6 8 7 function Craft:turnToTool(user) local dir = user:getFaceTo() local right = dir local left = (right - 1) % 8 for i=1,4 do local staticTool = common.GetFrontItemID(user, right) if self.tool[staticTool] then user:turn(right) return true end staticTool = common.GetFrontItemID(user, left) if self.tool[staticTool] then user:turn(left) return true end right = (right + 1) % 8 left = (left - 1) % 8 end return false end function Craft:craftItem(user, productId) local product = self.products[productId] local skill = self:getSkill(user) local skillGain = false local toolItem = self:getHandToolEquipped(user) if product.difficulty > skill then common.HighInformNLS(user, "Du bist nicht fähig genug um das zu tun.", "You are not skilled enough to do this.") self:swapToInactiveItem(user) return false end local neededFood = 0 if not self.npcCraft then local foodOK = false foodOK, neededFood = self:checkRequiredFood(user, product:getCraftingTime(skill)) if not foodOK then self:swapToInactiveItem(user) return false end end if self:checkMaterial(user, productId) then self:createItem(user, productId, toolItem) if not self.npcCraft then local originalDurability = common.getItemDurability(toolItem) if not shared.toolBreaks(user, toolItem, product:getCraftingTime(skill)) then glypheffects.effectToolSelfRepair(user, toolItem, originalDurability) end common.GetHungry(user, neededFood) end if type(self.leadSkill) == "number" then user:learn(self.leadSkill, product:getCraftingTime(skill), product.learnLimit) local newSkill = self:getSkill(user) skillGain = (newSkill > skill) end end self:swapToInactiveItem(user) return skillGain end function Craft:createItem(user, productId, toolItem) local product = self.products[productId] for i = 1, #product.ingredients do if not glypheffects.effectSaveMaterialOnProduction(user) then local ingredient = product.ingredients[i] user:eraseItem(ingredient.item, ingredient.quantity, ingredient.data) end end local quality = self:generateQuality(user, productId, toolItem) local itemStats = world:getItemStatsFromId(product.item) if itemStats.MaxStack == 1 then product.data.craftedBy = user.name else product.data.craftedBy = nil end common.CreateItem(user, product.item, product.quantity, quality, product.data) for i=1, #product.remnants do local remnant = product.remnants[i] common.CreateItem(user, remnant.item, remnant.quantity, 333, remnant.data) end end function Craft:repairItem(user, productIdList) local productId = self:findReferenceProductId(user, productIdList) local product = self.products[productId] local itemToRepair = user:getItemAt( productIdList - OFFSET_PRODUCTS_REPAIR ) local skill = self:getSkill(user) local repairSkill = self:getRepairSkill(user) local repairTime = product:getCraftingTime(skill) * (99 - common.getItemDurability(itemToRepair))/99 local skillGain = false local toolItem = self:getHandToolEquipped(user) if itemToRepair.id ~= repairItemList[user.id][productIdList][1] or common.getItemDurability(itemToRepair) ~= repairItemList[user.id][productIdList][2] then common.HighInformNLS(user, "[Info] Bitte tausche die Gegenstände in deinem Inventar nicht während der Reparatur.", "[Info] Please don't move items in your inventory during the repair.") return false end if product.difficulty > repairSkill then -- safty grid common.HighInformNLS(user, "Du bist nicht fähig genug um das zu tun.", "You are not skilled enough to do this.") self:swapToInactiveItem(user) return false end if common.getItemDurability(itemToRepair) == 99 then -- safty grid common.InformNLS(user, "Du findest nichts, was du an dem Werkstück reparieren könntest.", "There is nothing to repair on that item.") return false end local neededFood = 0 if not self.npcCraft then local foodOK = false foodOK, neededFood = self:checkRequiredFood(user, repairTime) if not foodOK then self:swapToInactiveItem(user) return false end end if self:checkMaterial(user, productId) then self:createRepairedItem(user, productId, itemToRepair) if not self.npcCraft then local originalDurability = common.getItemDurability(toolItem) if not shared.toolBreaks(user, toolItem, repairTime) then glypheffects.effectToolSelfRepair(user, toolItem, originalDurability) end common.GetHungry(user, neededFood) end if type(self.leadSkill) == "number" then user:learn(self.leadSkill, repairTime, product.learnLimit) local newSkill = self:getSkill(user) skillGain = (newSkill > skill) end end self:swapToInactiveItem(user) return skillGain end function Craft:createRepairedItem(user, productId, itemToRepair) local product = self.products[productId] local itemDamage = (100 - common.getItemDurability(itemToRepair))/100 local quality = common.getItemQuality(itemToRepair) for i = 1, #product.ingredients do local ingredient = product.ingredients[i] if math.random() < itemDamage * REPAIR_RESOURCE_USAGE then if not glypheffects.effectSaveMaterialOnRepair(user) then user:eraseItem(ingredient.item, ingredient.quantity, ingredient.data) end end end local bestQuality = itemToRepair:getData("qualityAtCreation") local repairQualityIncrease local glyphBonus = 0 if common.IsNilOrEmpty(bestQuality) then itemToRepair:setData("qualityAtCreation", quality) else if (quality < tonumber(bestQuality)) then glyphBonus = glypheffects.effectOnUserRepairQuality(user,itemToRepair) if Craft:isKnownCrafter(itemToRepair) then repairQualityIncrease = REPAIR_QUALITY_INCREASE_GENERAL + REPAIR_QUALITY_INCREASE_KNOWN_CRAFTER + glyphBonus else repairQualityIncrease = REPAIR_QUALITY_INCREASE_GENERAL + glyphBonus end if (math.random() < itemDamage * repairQualityIncrease) then quality = quality +1 common.InformNLS(user, "Dir gelingt es, die Qualität des Gegenstands "..world:getItemName(itemToRepair.id,Player.german).." etwas zu verbessern.", "You have succeeded in improving the quality of the item "..world:getItemName(itemToRepair.id,Player.english)..".") else common.InformNLS(user, "Du reparierst "..world:getItemName(itemToRepair.id,Player.german)..".", "You repair "..world:getItemName(itemToRepair.id,Player.english)..".") end else common.InformNLS(user, "Du reparierst "..world:getItemName(itemToRepair.id,Player.german)..".", "You repair "..world:getItemName(itemToRepair.id,Player.english)..".") end end itemToRepair.quality = common.calculateItemQualityDurability(quality, common.ITEM_MAX_DURABILITY) world:changeItem(itemToRepair) end function Craft:isKnownCrafter(item) if not common.IsNilOrEmpty(item:getData("craftedBy")) then return true end if not common.IsNilOrEmpty(item:getData("nameEn")) then return true end if not common.IsNilOrEmpty(item:getData("descriptionEn")) then return true end return false end function Craft:findReferenceProductId(user, productId) if self:isRepairItem(productId) then local itemAtCharacter = user:getItemAt( productId - OFFSET_PRODUCTS_REPAIR ) for i = 1, #self.products do local product = self.products[i] if product.item == itemAtCharacter.id then return i end end else return productId end return 0 end function Craft:getRepairSkill(user) local repairSkill = self:getSkill(user) + tonumber (self:getCurrentGemBonus(user)) return repairSkill end function Craft:isRepairItem(productId) if productId > OFFSET_PRODUCTS_REPAIR then return true end return false end function Craft:isRepairCategory(categoryId) if self.categories[categoryId].nameEN == "repair only" then return true end return false end M.Product = Product M.Craft = Craft return M
agpl-3.0
lxl1140989/sdk-for-tb
feeds/luci/applications/luci-statistics/luasrc/statistics/rrdtool/definitions/iptables.lua
86
1131
--[[ Luci statistics - iptables plugin diagram definition (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: ipt_bytes.lua 2276 2008-06-03 23:18:37Z jow $ ]]-- module("luci.statistics.rrdtool.definitions.iptables", package.seeall) function rrdargs( graph, plugin, plugin_instance, dtype ) return { { title = "%H: Firewall: Processed bytes in %pi", vlabel = "Bytes/s", number_format = "%5.0lf%sB/s", totals_format = "%5.0lf%sB", data = { types = { "ipt_bytes" }, options = { ipt_bytes = { total = true, title = "%di" } } } }, { title = "%H: Firewall: Processed packets in %pi", vlabel = "Packets/s", number_format = "%5.1lf P/s", totals_format = "%5.0lf%s", data = { types = { "ipt_packets" }, options = { ipt_packets = { total = true, title = "%di" } } } } } end
gpl-2.0
ffxiphoenix/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Duke_Gomory.lua
16
1252
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Duke Gomory ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger"); if (mob:isInBattlefieldList() == false) then mob:addInBattlefieldList(); Animate_Trigger = Animate_Trigger + 2; SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger); if (Animate_Trigger == 32767) then SpawnMob(17330911); -- 142 SpawnMob(17330912); -- 143 SpawnMob(17330183); -- 177 SpawnMob(17330184); -- 178 activateAnimatedWeapon(); -- Change subanim of all animated weapon end end if (Animate_Trigger == 32767) then killer:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE); end end;
gpl-3.0
TeleDALAD/spam1
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
ffxiphoenix/darkstar
scripts/globals/mobskills/Throat_Stab.lua
18
1115
--------------------------------------------- -- Throat Stab -- -- Description: Deals damage to a single target reducing their HP to 5%. Resets enmity. -- Type: Physical -- Utsusemi/Blink absorb: No -- Range: Single Target -- Notes: Very short range, easily evaded by walking away from it. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/magic"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local currentHP = target:getHP(); -- remove all by 5% local damage = 0; -- if have more hp then 30%, then reduce to 5% if (currentHP / target:getMaxHP() > 0.2) then damage = currentHP * .95; else -- else you die damage = currentHP; end local dmg = MobFinalAdjustments(damage,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_PIERCE,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); mob:resetEnmity(target); return dmg; end;
gpl-3.0
lxl1140989/sdk-for-tb
feeds/luci/applications/luci-openvpn/luasrc/model/cbi/openvpn-basic.lua
71
3274
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.ip") require("luci.model.uci") local basicParams = { -- -- Widget, Name, Default(s), Description -- { ListValue, "verb", { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, translate("Set output verbosity") }, { Value, "nice",0, translate("Change process priority") }, { Value,"port",1194, translate("TCP/UDP port # for both local and remote") }, { ListValue,"dev_type",{ "tun", "tap" }, translate("Type of used device") }, { Flag,"tun_ipv6",0, translate("Make tun device IPv6 capable") }, { Value,"ifconfig","10.200.200.3 10.200.200.1", translate("Set tun/tap adapter parameters") }, { Value,"server","10.200.200.0 255.255.255.0", translate("Configure server mode") }, { Value,"server_bridge","192.168.1.1 255.255.255.0 192.168.1.128 192.168.1.254", translate("Configure server bridge") }, { Flag,"nobind",0, translate("Do not bind to local address and port") }, { Flag,"comp_lzo",0, translate("Use fast LZO compression") }, { Value,"keepalive","10 60", translate("Helper directive to simplify the expression of --ping and --ping-restart in server mode configurations") }, { ListValue,"proto",{ "udp", "tcp" }, translate("Use protocol") }, { Flag,"client",0, translate("Configure client mode") }, { Flag,"client_to_client",0, translate("Allow client-to-client traffic") }, { DynamicList,"remote","vpnserver.example.org", translate("Remote host name or ip address") }, { FileUpload,"secret","/etc/openvpn/secret.key 1", translate("Enable Static Key encryption mode (non-TLS)") }, { FileUpload,"pkcs12","/etc/easy-rsa/keys/some-client.pk12", translate("PKCS#12 file containing keys") }, { FileUpload,"ca","/etc/easy-rsa/keys/ca.crt", translate("Certificate authority") }, { FileUpload,"dh","/etc/easy-rsa/keys/dh1024.pem", translate("Diffie Hellman parameters") }, { FileUpload,"cert","/etc/easy-rsa/keys/some-client.crt", translate("Local certificate") }, { FileUpload,"key","/etc/easy-rsa/keys/some-client.key", translate("Local private key") }, } local m = Map("openvpn") local p = m:section( SimpleSection ) p.template = "openvpn/pageswitch" p.mode = "basic" p.instance = arg[1] local s = m:section( NamedSection, arg[1], "openvpn" ) for _, option in ipairs(basicParams) do local o = s:option( option[1], option[2], option[2], option[4] ) o.optional = true if option[1] == DummyValue then o.value = option[3] else if option[1] == DynamicList then o.cast = nil function o.cfgvalue(...) local val = AbstractValue.cfgvalue(...) return ( val and type(val) ~= "table" ) and { val } or val end end if type(option[3]) == "table" then if o.optional then o:value("", "-- remove --") end for _, v in ipairs(option[3]) do v = tostring(v) o:value(v) end o.default = tostring(option[3][1]) else o.default = tostring(option[3]) end end for i=5,#option do if type(option[i]) == "table" then o:depends(option[i]) end end end return m
gpl-2.0
Ekdohibs/minetest_game
mods/default/torch.lua
13
4487
--[[ Torch mod - formerly mod "Torches" ====================== (c) Copyright BlockMen (2013-2015) (C) Copyright sofar <sofar@foo-projects.org> (2016) This mod changes the default torch drawtype from "torchlike" to "mesh", giving the torch a three dimensional appearance. The mesh contains the proper pixel mapping to make the animation appear as a particle above the torch, while in fact the animation is just the texture of the mesh. License: ~~~~~~~~ (c) Copyright BlockMen (2013-2015) Textures and Meshes/Models: CC-BY 3.0 BlockMen Note that the models were entirely done from scratch by sofar. Code: Licensed under the GNU LGPL version 2.1 or higher. You can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA See LICENSE.txt and http://www.gnu.org/licenses/lgpl-2.1.txt --]] minetest.register_node("default:torch", { description = "Torch", drawtype = "mesh", mesh = "torch_floor.obj", inventory_image = "default_torch_on_floor.png", wield_image = "default_torch_on_floor.png", tiles = {{ name = "default_torch_on_floor_animated.png", animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3} }}, paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, walkable = false, liquids_pointable = false, light_source = 12, groups = {choppy=2, dig_immediate=3, flammable=1, attached_node=1, torch=1}, drop = "default:torch", selection_box = { type = "wallmounted", wall_bottom = {-1/8, -1/2, -1/8, 1/8, 2/16, 1/8}, }, sounds = default.node_sound_wood_defaults(), on_place = function(itemstack, placer, pointed_thing) local under = pointed_thing.under local node = minetest.get_node(under) local def = minetest.registered_nodes[node.name] if def and def.on_rightclick and ((not placer) or (placer and not placer:get_player_control().sneak)) then return def.on_rightclick(under, node, placer, itemstack, pointed_thing) or itemstack end local above = pointed_thing.above local wdir = minetest.dir_to_wallmounted(vector.subtract(under, above)) local fakestack = itemstack if wdir == 0 then fakestack:set_name("default:torch_ceiling") elseif wdir == 1 then fakestack:set_name("default:torch") else fakestack:set_name("default:torch_wall") end itemstack = minetest.item_place(fakestack, placer, pointed_thing, wdir) itemstack:set_name("default:torch") return itemstack end }) minetest.register_node("default:torch_wall", { drawtype = "mesh", mesh = "torch_wall.obj", tiles = {{ name = "default_torch_on_floor_animated.png", animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3} }}, paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, walkable = false, light_source = 12, groups = {choppy=2, dig_immediate=3, flammable=1, not_in_creative_inventory=1, attached_node=1, torch=1}, drop = "default:torch", selection_box = { type = "wallmounted", wall_side = {-1/2, -1/2, -1/8, -1/8, 1/8, 1/8}, }, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:torch_ceiling", { drawtype = "mesh", mesh = "torch_ceiling.obj", tiles = {{ name = "default_torch_on_floor_animated.png", animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3} }}, paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, walkable = false, light_source = 12, groups = {choppy=2, dig_immediate=3, flammable=1, not_in_creative_inventory=1, attached_node=1, torch=1}, drop = "default:torch", selection_box = { type = "wallmounted", wall_top = {-1/8, -1/16, -5/16, 1/8, 1/2, 1/8}, }, sounds = default.node_sound_wood_defaults(), }) minetest.register_lbm({ name = "default:3dtorch", nodenames = {"default:torch", "torches:floor", "torches:wall"}, action = function(pos, node) if node.param2 == 0 then minetest.set_node(pos, {name = "default:torch_ceiling", param2 = node.param2}) elseif node.param2 == 1 then minetest.set_node(pos, {name = "default:torch", param2 = node.param2}) else minetest.set_node(pos, {name = "default:torch_wall", param2 = node.param2}) end end })
lgpl-2.1