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
ara8586/9900
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
agpl-3.0
Aaa1r/DRAGON
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
ThingMesh/openwrt-luci
applications/luci-freifunk-widgets/luasrc/model/cbi/freifunk/widgets/widgets_overview.lua
78
2041
--[[ LuCI - Lua Configuration Interface Copyright 2012 Manuel Munz <freifunk at somakoma dot de> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local uci = require "luci.model.uci".cursor() local fs = require "luci.fs" local utl = require "luci.util" m = Map("freifunk-widgets", translate("Widgets"), translate("Configure installed widgets.")) wdg = m:section(TypedSection, "widget", translate("Widgets")) wdg.addremove = true wdg.extedit = luci.dispatcher.build_url("admin/freifunk/widgets/widget/%s") wdg.template = "cbi/tblsection" wdg.sortable = true --[[ function wdg.create(...) local sid = TypedSection.create(...) luci.http.redirect(wdg.extedit % sid) end ]]-- local en = wdg:option(Flag, "enabled", translate("Enable")) en.rmempty = false --en.default = "0" function en.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end local tmpl = wdg:option(ListValue, "template", translate("Template")) for k, v in ipairs(fs.dir('/usr/lib/lua/luci/view/freifunk/widgets/')) do if v ~= "." and v ~= ".." then tmpl:value(v) end end local title = wdg:option(Value, "title", translate("Title")) title.rmempty = true local width = wdg:option(Value, "width", translate("Width")) width.rmempty = true local height = wdg:option(Value, "height", translate("Height")) height.rmempty = true local pr = wdg:option(Value, "paddingright", translate("Padding right")) pr.rmempty = true function m.on_commit(self) -- clean custom text files whose config has been deleted local dir = "/usr/share/customtext/" local active = {} uci:foreach("freifunk-widgets", "widget", function(s) if s["template"] == "html" then table.insert(active, s[".name"]) end end ) for k, v in ipairs(fs.dir(dir)) do filename = string.gsub(v, ".html", "") if not utl.contains(active, filename) then fs.unlink(dir .. v) end end end return m
apache-2.0
Lsty/ygopro-scripts
c27243130.lua
5
1718
--禁じられた聖槍 function c27243130.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetHintTiming(TIMING_DAMAGE_STEP) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCondition(c27243130.condition) e1:SetTarget(c27243130.target) e1:SetOperation(c27243130.activate) c:RegisterEffect(e1) end function c27243130.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated() end function c27243130.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() end if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) end function c27243130.activate(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsFaceup() then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e1:SetValue(-800) tc:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetRange(LOCATION_MZONE) e2:SetCode(EFFECT_IMMUNE_EFFECT) e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e2:SetValue(c27243130.efilter) tc:RegisterEffect(e2) end end function c27243130.efilter(e,te) return te:IsActiveType(TYPE_SPELL+TYPE_TRAP) and te:GetOwner()~=e:GetOwner() end
gpl-2.0
MalRD/darkstar
scripts/zones/RoMaeve/Zone.lua
9
2289
----------------------------------- -- -- Zone: RoMaeve (122) -- ----------------------------------- local ID = require("scripts/zones/RoMaeve/IDs"); require("scripts/globals/conquest"); require("scripts/globals/missions"); require("scripts/globals/npc_util"); require("scripts/globals/weather"); require("scripts/globals/status"); ----------------------------------- function onInitialize(zone) local newPosition = npcUtil.pickNewPosition(ID.npc.BASTOK_7_1_QM, ID.npc.BASTOK_7_1_QM_POS, true); GetNPCByID(ID.npc.BASTOK_7_1_QM):setPos(newPosition.x, newPosition.y, newPosition.z); end; function onConquestUpdate(zone, updatetype) dsp.conq.onConquestUpdate(zone, updatetype) end; function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-0.008,-33.595,123.478,62); end if (player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.VAIN and player:getCharVar("MissionStatus") ==1) then cs = 3; -- doll telling "you're in the right area" end return cs; end; function onRegionEnter(player,region) end; function onGameDay() if (IsMoonFull() and GetNPCByID(ID.npc.MOONGATE_OFFSET):getWeather() == dsp.weather.SUNSHINE) then for i = ID.npc.MOONGATE_OFFSET, ID.npc.MOONGATE_OFFSET+7 do GetNPCByID(i):openDoor(432); end end end; function onZoneWeatherChange(weather) if (weather ~= dsp.weather.SUNSHINE and GetNPCByID(ID.npc.MOONGATE_OFFSET):getAnimation() ~= dsp.anim.CLOSE_DOOR) then for i = ID.npc.MOONGATE_OFFSET, ID.npc.MOONGATE_OFFSET+7 do GetNPCByID(i):setAnimation(dsp.anim.CLOSE_DOOR); end elseif (weather == dsp.weather.SUNSHINE and IsMoonFull() == true and VanadielHour() < 3) then -- reactivate things for the remainder of the time until 3AM local moonMinRemaining = math.floor(432 * (180 - VanadielHour() * 60 + VanadielMinute())/180) -- 180 minutes (ie 3AM) subtract the time that has passed since midnight for i = ID.npc.MOONGATE_OFFSET, ID.npc.MOONGATE_OFFSET+7 do GetNPCByID(i):openDoor(moonMinRemaining); end end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
MalRD/darkstar
scripts/globals/items/pork_cutlet_rice_bowl.lua
11
1782
----------------------------------------- -- ID: 6406 -- Item: pork_cutlet_rice_bowl -- Food Effect: 180Min, All Races ----------------------------------------- -- HP +60 -- MP +60 -- STR +7 -- VIT +3 -- AGI +5 -- INT -7 -- Fire resistance +20 -- Attack +23% (cap 125) -- Ranged Attack +23% (cap 125) -- Store TP +4 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,10800,6406) end function onEffectGain(target,effect) target:addMod(dsp.mod.HP, 60) target:addMod(dsp.mod.MP, 60) target:addMod(dsp.mod.STR, 7) target:addMod(dsp.mod.VIT, 3) target:addMod(dsp.mod.AGI, 5) target:addMod(dsp.mod.INT, -7) target:addMod(dsp.mod.FIRERES, 20) target:addMod(dsp.mod.FOOD_ATTP, 23) target:addMod(dsp.mod.FOOD_ATT_CAP, 125) target:addMod(dsp.mod.FOOD_RATTP, 23) target:addMod(dsp.mod.FOOD_RATT_CAP, 125) target:addMod(dsp.mod.STORETP, 4) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 60) target:delMod(dsp.mod.MP, 60) target:delMod(dsp.mod.STR, 7) target:delMod(dsp.mod.VIT, 3) target:delMod(dsp.mod.AGI, 5) target:delMod(dsp.mod.INT, -7) target:delMod(dsp.mod.FIRERES, 20) target:delMod(dsp.mod.FOOD_ATTP, 23) target:delMod(dsp.mod.FOOD_ATT_CAP, 125) target:delMod(dsp.mod.FOOD_RATTP, 23) target:delMod(dsp.mod.FOOD_RATT_CAP, 125) target:delMod(dsp.mod.STORETP, 4) end
gpl-3.0
Lsty/ygopro-scripts
c19505896.lua
5
1202
--ウィード function c19505896.initial_effect(c) --Destroy replace local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_DESTROY_REPLACE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetTarget(c19505896.desreptg) e1:SetOperation(c19505896.desrepop) c:RegisterEffect(e1) end function c19505896.repfilter(c) return c:IsFaceup() and c:IsRace(RACE_PLANT) and not c:IsStatus(STATUS_DESTROY_CONFIRMED) end function c19505896.desreptg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return not c:IsReason(REASON_REPLACE) and Duel.IsExistingMatchingCard(c19505896.repfilter,tp,LOCATION_MZONE,0,1,c) end if Duel.SelectYesNo(tp,aux.Stringid(19505896,0)) then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESREPLACE) local g=Duel.SelectMatchingCard(tp,c19505896.repfilter,tp,LOCATION_MZONE,0,1,1,c) e:SetLabelObject(g:GetFirst()) g:GetFirst():SetStatus(STATUS_DESTROY_CONFIRMED,true) return true else return false end end function c19505896.desrepop(e,tp,eg,ep,ev,re,r,rp) local tc=e:GetLabelObject() tc:SetStatus(STATUS_DESTROY_CONFIRMED,false) Duel.Destroy(tc,REASON_EFFECT+REASON_REPLACE) end
gpl-2.0
cshore-firmware/openwrt-luci
modules/luci-mod-rpc/luasrc/jsonrpc.lua
75
1979
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.jsonrpc", package.seeall) require "luci.json" function resolve(mod, method) local path = luci.util.split(method, ".") for j=1, #path-1 do if not type(mod) == "table" then break end mod = rawget(mod, path[j]) if not mod then break end end mod = type(mod) == "table" and rawget(mod, path[#path]) or nil if type(mod) == "function" then return mod end end function handle(tbl, rawsource, ...) local decoder = luci.json.Decoder() local stat = luci.ltn12.pump.all(rawsource, decoder:sink()) local json = decoder:get() local response local success = false if stat then if type(json.method) == "string" and (not json.params or type(json.params) == "table") then local method = resolve(tbl, json.method) if method then response = reply(json.jsonrpc, json.id, proxy(method, unpack(json.params or {}))) else response = reply(json.jsonrpc, json.id, nil, {code=-32601, message="Method not found."}) end else response = reply(json.jsonrpc, json.id, nil, {code=-32600, message="Invalid request."}) end else response = reply("2.0", nil, nil, {code=-32700, message="Parse error."}) end return luci.json.Encoder(response, ...):source() end function reply(jsonrpc, id, res, err) require "luci.json" id = id or luci.json.null -- 1.0 compatibility if jsonrpc ~= "2.0" then jsonrpc = nil res = res or luci.json.null err = err or luci.json.null end return {id=id, result=res, error=err, jsonrpc=jsonrpc} end function proxy(method, ...) local res = {luci.util.copcall(method, ...)} local stat = table.remove(res, 1) if not stat then return nil, {code=-32602, message="Invalid params.", data=table.remove(res, 1)} else if #res <= 1 then return res[1] or luci.json.null else return res end end end
apache-2.0
MalRD/darkstar
scripts/zones/Port_Bastok/npcs/Steel_Bones.lua
9
1162
----------------------------------- -- Area: Port Bastok -- NPC: Steel Bones -- Standard Info NPC -- Involved in Quest: Guest of Hauteur ----------------------------------- require("scripts/globals/status") require("scripts/globals/keyitems") require("scripts/globals/quests") local ID = require("scripts/zones/Port_Bastok/IDs") ----------------------------------- function onTrade(player,npc,trade) end function onTrigger(player,npc) local GuestofHauteur = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.GUEST_OF_HAUTEUR) local itemEquipped = player:getEquipID(dsp.slot.MAIN) if GuestofHauteur == QUEST_ACCEPTED and player:getCharVar("GuestofHauteur_Event") ~= 1 and (itemEquipped == 17045 or itemEquipped == 17426) then -- Maul / Replica Maul player:startEvent(57) else player:startEvent(29) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) if csid == 57 then player:setCharVar("GuestofHauteur_Event",1) player:addKeyItem(dsp.ki.LETTERS_FROM_DOMIEN) player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LETTERS_FROM_DOMIEN) end end
gpl-3.0
Lsty/ygopro-scripts
c102380.lua
3
2438
--溶岩魔神ラヴァ・ゴーレム function c102380.initial_effect(c) c:EnableReviveLimit() --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(102380,0)) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE+EFFECT_FLAG_SPSUM_PARAM) e1:SetRange(LOCATION_HAND) e1:SetTargetRange(POS_FACEUP,1) e1:SetCondition(c102380.spcon) e1:SetOperation(c102380.spop) c:RegisterEffect(e1) --damage local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetDescription(aux.Stringid(102380,1)) e2:SetCategory(CATEGORY_DAMAGE) e2:SetCode(EVENT_PHASE+PHASE_STANDBY) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetCondition(c102380.damcon) e2:SetTarget(c102380.damtg) e2:SetOperation(c102380.damop) c:RegisterEffect(e2) --spsummon cost local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_SPSUMMON_COST) e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e3:SetCost(c102380.spcost) e3:SetOperation(c102380.spcop) c:RegisterEffect(e3) end function c102380.spcon(e,c) if c==nil then return true end return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>-2 and Duel.IsExistingMatchingCard(Card.IsReleasable,c:GetControler(),0,LOCATION_MZONE,2,nil) end function c102380.spop(e,tp,eg,ep,ev,re,r,rp,c) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE) local g=Duel.SelectMatchingCard(tp,Card.IsReleasable,tp,0,LOCATION_MZONE,2,2,nil) Duel.Release(g,REASON_COST) end function c102380.damcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c102380.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(1000) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,0,0,tp,1000) end function c102380.damop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end function c102380.spcost(e,c,tp) return Duel.GetActivityCount(tp,ACTIVITY_NORMALSUMMON)==0 end function c102380.spcop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_SUMMON) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetReset(RESET_PHASE+RESET_END) e1:SetTargetRange(1,0) Duel.RegisterEffect(e1,tp) local e2=e1:Clone() e2:SetCode(EFFECT_CANNOT_MSET) Duel.RegisterEffect(e2,tp) end
gpl-2.0
bforbis/thrift
lib/lua/TFramedTransport.lua
19
2952
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- require 'TTransport' require 'libluabpack' TFramedTransport = TTransportBase:new{ __type = 'TFramedTransport', doRead = true, doWrite = true, wBuf = '', rBuf = '' } function TFramedTransport:new(obj) if ttype(obj) ~= 'table' then error(ttype(self) .. 'must be initialized with a table') end -- Ensure a transport is provided if not obj.trans then error('You must provide ' .. ttype(self) .. ' with a trans') end return TTransportBase.new(self, obj) end function TFramedTransport:isOpen() return self.trans:isOpen() end function TFramedTransport:open() return self.trans:open() end function TFramedTransport:close() return self.trans:close() end function TFramedTransport:read(len) if string.len(self.rBuf) == 0 then self:__readFrame() end if self.doRead == false then return self.trans:read(len) end if len > string.len(self.rBuf) then local val = self.rBuf self.rBuf = '' return val end local val = string.sub(self.rBuf, 0, len) self.rBuf = string.sub(self.rBuf, len+1) return val end function TFramedTransport:__readFrame() local buf = self.trans:readAll(4) local frame_len = libluabpack.bunpack('i', buf) self.rBuf = self.trans:readAll(frame_len) end function TFramedTransport:write(buf, len) if self.doWrite == false then return self.trans:write(buf, len) end if len and len < string.len(buf) then buf = string.sub(buf, 0, len) end self.wBuf = self.wBuf .. buf end function TFramedTransport:flush() if self.doWrite == false then return self.trans:flush() end -- If the write fails we still want wBuf to be clear local tmp = self.wBuf self.wBuf = '' local frame_len_buf = libluabpack.bpack("i", string.len(tmp)) tmp = frame_len_buf .. tmp self.trans:write(tmp) self.trans:flush() end TFramedTransportFactory = TTransportFactoryBase:new{ __type = 'TFramedTransportFactory' } function TFramedTransportFactory:getTransport(trans) if not trans then terror(TProtocolException:new{ message = 'Must supply a transport to ' .. ttype(self) }) end return TFramedTransport:new{trans = trans} end
apache-2.0
maxrio/luci981213
applications/luci-app-asterisk/luasrc/asterisk.lua
68
17804
-- Copyright 2009 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.asterisk", package.seeall) require("luci.asterisk.cc_idd") local _io = require("io") local uci = require("luci.model.uci").cursor() local sys = require("luci.sys") local util = require("luci.util") AST_BIN = "/usr/sbin/asterisk" AST_FLAGS = "-r -x" --- LuCI Asterisk - Resync uci context function uci_resync() uci = luci.model.uci.cursor() end --- LuCI Asterisk io interface -- Handles low level io. -- @type module io = luci.util.class() --- Execute command and return output -- @param command String containing the command to execute -- @return String containing the command output function io.exec(command) local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") local buffer = fh:read("*a") fh:close() return buffer end --- Execute command and invoke given callback for each readed line -- @param command String containing the command to execute -- @param callback Function to call back for each line -- @return Always true function io.execl(command, callback) local ln local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") repeat ln = fh:read("*l") callback(ln) until not ln fh:close() return true end --- Execute command and return an iterator that returns one line per invokation -- @param command String containing the command to execute -- @return Iterator function function io.execi(command) local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") return function() local ln = fh:read("*l") if not ln then fh:close() end return ln end end --- LuCI Asterisk - core status core = luci.util.class() --- Retrive version string. -- @return String containing the reported asterisk version function core.version(self) local version = io.exec("core show version") return version:gsub(" *\n", "") end --- LuCI Asterisk - SIP information. -- @type module sip = luci.util.class() --- Get a list of known SIP peers -- @return Table containing each SIP peer function sip.peers(self) local head = false local peers = { } for line in io.execi("sip show peers") do if not head then head = true elseif not line:match(" sip peers ") then local online, delay, id, uid local name, host, dyn, nat, acl, port, status = line:match("(.-) +(.-) +([D ]) ([N ]) (.) (%d+) +(.+)") if host == '(Unspecified)' then host = nil end if port == '0' then port = nil else port = tonumber(port) end dyn = ( dyn == 'D' and true or false ) nat = ( nat == 'N' and true or false ) acl = ( acl ~= ' ' and true or false ) online, delay = status:match("(OK) %((%d+) ms%)") if online == 'OK' then online = true delay = tonumber(delay) elseif status ~= 'Unmonitored' then online = false delay = 0 else online = nil delay = 0 end id, uid = name:match("(.+)/(.+)") if not ( id and uid ) then id = name .. "..." uid = nil end peers[#peers+1] = { online = online, delay = delay, name = id, user = uid, dynamic = dyn, nat = nat, acl = acl, host = host, port = port } end end return peers end --- Get informations of given SIP peer -- @param peer String containing the name of the SIP peer function sip.peer(peer) local info = { } local keys = { } for line in io.execi("sip show peer " .. peer) do if #line > 0 then local key, val = line:match("(.-) *: +(.*)") if key and val then key = key:gsub("^ +",""):gsub(" +$", "") val = val:gsub("^ +",""):gsub(" +$", "") if key == "* Name" then key = "Name" elseif key == "Addr->IP" then info.address, info.port = val:match("(.+) Port (.+)") info.port = tonumber(info.port) elseif key == "Status" then info.online, info.delay = val:match("(OK) %((%d+) ms%)") if info.online == 'OK' then info.online = true info.delay = tonumber(info.delay) elseif status ~= 'Unmonitored' then info.online = false info.delay = 0 else info.online = nil info.delay = 0 end end if val == 'Yes' or val == 'yes' or val == '<Set>' then val = true elseif val == 'No' or val == 'no' then val = false elseif val == '<Not set>' or val == '(none)' then val = nil end keys[#keys+1] = key info[key] = val end end end return info, keys end --- LuCI Asterisk - Internal helpers -- @type module tools = luci.util.class() --- Convert given value to a list of tokens. Split by white space. -- @param val String or table value -- @return Table containing tokens function tools.parse_list(v) local tokens = { } v = type(v) == "table" and v or { v } for _, v in ipairs(v) do if type(v) == "string" then for v in v:gmatch("(%S+)") do tokens[#tokens+1] = v end end end return tokens end --- Convert given list to a collection of hyperlinks -- @param list Table of tokens -- @param url String pattern or callback function to construct urls (optional) -- @param sep String containing the seperator (optional, default is ", ") -- @return String containing the html fragment function tools.hyperlinks(list, url, sep) local html local function mkurl(p, t) if type(p) == "string" then return p:format(t) elseif type(p) == "function" then return p(t) else return '#' end end list = list or { } url = url or "%s" sep = sep or ", " for _, token in ipairs(list) do html = ( html and html .. sep or '' ) .. '<a href="%s">%s</a>' %{ mkurl(url, token), token } end return html or '' end --- LuCI Asterisk - International Direct Dialing Prefixes -- @type module idd = luci.util.class() --- Lookup the country name for the given IDD code. -- @param country String containing IDD code -- @return String containing the country name function idd.country(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then for _, v2 in ipairs(v[3]) do if v2 == tostring(c) then return v[1] end end elseif v[3] == tostring(c) then return v[1] end end end --- Lookup the country code for the given IDD code. -- @param country String containing IDD code -- @return Table containing the country code(s) function idd.cc(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then for _, v2 in ipairs(v[3]) do if v2 == tostring(c) then return type(v[2]) == "table" and v[2] or { v[2] } end end elseif v[3] == tostring(c) then return type(v[2]) == "table" and v[2] or { v[2] } end end end --- Lookup the IDD code(s) for the given country. -- @param idd String containing the country name -- @return Table containing the IDD code(s) function idd.idd(c) for _, v in ipairs(cc_idd.CC_IDD) do if v[1]:lower():match(c:lower()) then return type(v[3]) == "table" and v[3] or { v[3] } end end end --- Populate given CBI field with IDD codes. -- @param field CBI option object -- @return (nothing) function idd.cbifill(o) for i, v in ipairs(cc_idd.CC_IDD) do o:value("_%i" % i, util.pcdata(v[1])) end o.formvalue = function(...) local val = luci.cbi.Value.formvalue(...) if val:sub(1,1) == "_" then val = tonumber((val:gsub("^_", ""))) if val then return type(cc_idd.CC_IDD[val][3]) == "table" and cc_idd.CC_IDD[val][3] or { cc_idd.CC_IDD[val][3] } end end return val end o.cfgvalue = function(...) local val = luci.cbi.Value.cfgvalue(...) if val then val = tools.parse_list(val) for i, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then if v[3][1] == val[1] then return "_%i" % i end else if v[3] == val[1] then return "_%i" % i end end end end return val end end --- LuCI Asterisk - Country Code Prefixes -- @type module cc = luci.util.class() --- Lookup the country name for the given CC code. -- @param country String containing CC code -- @return String containing the country name function cc.country(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then for _, v2 in ipairs(v[2]) do if v2 == tostring(c) then return v[1] end end elseif v[2] == tostring(c) then return v[1] end end end --- Lookup the international dialing code for the given CC code. -- @param cc String containing CC code -- @return String containing IDD code function cc.idd(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then for _, v2 in ipairs(v[2]) do if v2 == tostring(c) then return type(v[3]) == "table" and v[3] or { v[3] } end end elseif v[2] == tostring(c) then return type(v[3]) == "table" and v[3] or { v[3] } end end end --- Lookup the CC code(s) for the given country. -- @param country String containing the country name -- @return Table containing the CC code(s) function cc.cc(c) for _, v in ipairs(cc_idd.CC_IDD) do if v[1]:lower():match(c:lower()) then return type(v[2]) == "table" and v[2] or { v[2] } end end end --- Populate given CBI field with CC codes. -- @param field CBI option object -- @return (nothing) function cc.cbifill(o) for i, v in ipairs(cc_idd.CC_IDD) do o:value("_%i" % i, util.pcdata(v[1])) end o.formvalue = function(...) local val = luci.cbi.Value.formvalue(...) if val:sub(1,1) == "_" then val = tonumber((val:gsub("^_", ""))) if val then return type(cc_idd.CC_IDD[val][2]) == "table" and cc_idd.CC_IDD[val][2] or { cc_idd.CC_IDD[val][2] } end end return val end o.cfgvalue = function(...) local val = luci.cbi.Value.cfgvalue(...) if val then val = tools.parse_list(val) for i, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then if v[2][1] == val[1] then return "_%i" % i end else if v[2] == val[1] then return "_%i" % i end end end end return val end end --- LuCI Asterisk - Dialzone -- @type module dialzone = luci.util.class() --- Parse a dialzone section -- @param zone Table containing the zone info -- @return Table with parsed information function dialzone.parse(z) if z['.name'] then return { trunks = tools.parse_list(z.uses), name = z['.name'], description = z.description or z['.name'], addprefix = z.addprefix, matches = tools.parse_list(z.match), intlmatches = tools.parse_list(z.international), countrycode = z.countrycode, localzone = z.localzone, localprefix = z.localprefix } end end --- Get a list of known dial zones -- @return Associative table of zones and table of zone names function dialzone.zones() local zones = { } local znames = { } uci:foreach("asterisk", "dialzone", function(z) zones[z['.name']] = dialzone.parse(z) znames[#znames+1] = z['.name'] end) return zones, znames end --- Get a specific dial zone -- @param name Name of the dial zone -- @return Table containing zone information function dialzone.zone(n) local zone uci:foreach("asterisk", "dialzone", function(z) if z['.name'] == n then zone = dialzone.parse(z) end end) return zone end --- Find uci section hash for given zone number -- @param idx Zone number -- @return String containing the uci hash pointing to the section function dialzone.ucisection(i) local hash local index = 1 i = tonumber(i) uci:foreach("asterisk", "dialzone", function(z) if not hash and index == i then hash = z['.name'] end index = index + 1 end) return hash end --- LuCI Asterisk - Voicemailbox -- @type module voicemail = luci.util.class() --- Parse a voicemail section -- @param zone Table containing the mailbox info -- @return Table with parsed information function voicemail.parse(z) if z.number and #z.number > 0 then local v = { id = '%s@%s' %{ z.number, z.context or 'default' }, number = z.number, context = z.context or 'default', name = z.name or z['.name'] or 'OpenWrt', zone = z.zone or 'homeloc', password = z.password or '0000', email = z.email or '', page = z.page or '', dialplans = { } } uci:foreach("asterisk", "dialplanvoice", function(s) if s.dialplan and #s.dialplan > 0 and s.voicebox == v.number then v.dialplans[#v.dialplans+1] = s.dialplan end end) return v end end --- Get a list of known voicemail boxes -- @return Associative table of boxes and table of box numbers function voicemail.boxes() local vboxes = { } local vnames = { } uci:foreach("asterisk", "voicemail", function(z) local v = voicemail.parse(z) if v then local n = '%s@%s' %{ v.number, v.context } vboxes[n] = v vnames[#vnames+1] = n end end) return vboxes, vnames end --- Get a specific voicemailbox -- @param number Number of the voicemailbox -- @return Table containing mailbox information function voicemail.box(n) local box n = n:gsub("@.+$","") uci:foreach("asterisk", "voicemail", function(z) if z.number == tostring(n) then box = voicemail.parse(z) end end) return box end --- Find all voicemailboxes within the given dialplan -- @param plan Dialplan name or table -- @return Associative table containing extensions mapped to mailbox info function voicemail.in_dialplan(p) local plan = type(p) == "string" and p or p.name local boxes = { } uci:foreach("asterisk", "dialplanvoice", function(s) if s.extension and #s.extension > 0 and s.dialplan == plan then local box = voicemail.box(s.voicebox) if box then boxes[s.extension] = box end end end) return boxes end --- Remove voicemailbox and associated extensions from config -- @param box Voicemailbox number or table -- @param ctx UCI context to use (optional) -- @return Boolean indicating success function voicemail.remove(v, ctx) ctx = ctx or uci local box = type(v) == "string" and v or v.number local ok1 = ctx:delete_all("asterisk", "voicemail", {number=box}) local ok2 = ctx:delete_all("asterisk", "dialplanvoice", {voicebox=box}) return ( ok1 or ok2 ) and true or false end --- LuCI Asterisk - MeetMe Conferences -- @type module meetme = luci.util.class() --- Parse a meetme section -- @param room Table containing the room info -- @return Table with parsed information function meetme.parse(r) if r.room and #r.room > 0 then local v = { room = r.room, pin = r.pin or '', adminpin = r.adminpin or '', description = r._description or '', dialplans = { } } uci:foreach("asterisk", "dialplanmeetme", function(s) if s.dialplan and #s.dialplan > 0 and s.room == v.room then v.dialplans[#v.dialplans+1] = s.dialplan end end) return v end end --- Get a list of known meetme rooms -- @return Associative table of rooms and table of room numbers function meetme.rooms() local mrooms = { } local mnames = { } uci:foreach("asterisk", "meetme", function(r) local v = meetme.parse(r) if v then mrooms[v.room] = v mnames[#mnames+1] = v.room end end) return mrooms, mnames end --- Get a specific meetme room -- @param number Number of the room -- @return Table containing room information function meetme.room(n) local room uci:foreach("asterisk", "meetme", function(r) if r.room == tostring(n) then room = meetme.parse(r) end end) return room end --- Find all meetme rooms within the given dialplan -- @param plan Dialplan name or table -- @return Associative table containing extensions mapped to room info function meetme.in_dialplan(p) local plan = type(p) == "string" and p or p.name local rooms = { } uci:foreach("asterisk", "dialplanmeetme", function(s) if s.extension and #s.extension > 0 and s.dialplan == plan then local room = meetme.room(s.room) if room then rooms[s.extension] = room end end end) return rooms end --- Remove meetme room and associated extensions from config -- @param room Voicemailbox number or table -- @param ctx UCI context to use (optional) -- @return Boolean indicating success function meetme.remove(v, ctx) ctx = ctx or uci local room = type(v) == "string" and v or v.number local ok1 = ctx:delete_all("asterisk", "meetme", {room=room}) local ok2 = ctx:delete_all("asterisk", "dialplanmeetme", {room=room}) return ( ok1 or ok2 ) and true or false end --- LuCI Asterisk - Dialplan -- @type module dialplan = luci.util.class() --- Parse a dialplan section -- @param plan Table containing the plan info -- @return Table with parsed information function dialplan.parse(z) if z['.name'] then local plan = { zones = { }, name = z['.name'], description = z.description or z['.name'] } -- dialzones for _, name in ipairs(tools.parse_list(z.include)) do local zone = dialzone.zone(name) if zone then plan.zones[#plan.zones+1] = zone end end -- voicemailboxes plan.voicemailboxes = voicemail.in_dialplan(plan) -- meetme conferences plan.meetmerooms = meetme.in_dialplan(plan) return plan end end --- Get a list of known dial plans -- @return Associative table of plans and table of plan names function dialplan.plans() local plans = { } local pnames = { } uci:foreach("asterisk", "dialplan", function(p) plans[p['.name']] = dialplan.parse(p) pnames[#pnames+1] = p['.name'] end) return plans, pnames end --- Get a specific dial plan -- @param name Name of the dial plan -- @return Table containing plan information function dialplan.plan(n) local plan uci:foreach("asterisk", "dialplan", function(p) if p['.name'] == n then plan = dialplan.parse(p) end end) return plan end
apache-2.0
cshore-firmware/openwrt-luci
applications/luci-app-asterisk/luasrc/asterisk.lua
68
17804
-- Copyright 2009 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.asterisk", package.seeall) require("luci.asterisk.cc_idd") local _io = require("io") local uci = require("luci.model.uci").cursor() local sys = require("luci.sys") local util = require("luci.util") AST_BIN = "/usr/sbin/asterisk" AST_FLAGS = "-r -x" --- LuCI Asterisk - Resync uci context function uci_resync() uci = luci.model.uci.cursor() end --- LuCI Asterisk io interface -- Handles low level io. -- @type module io = luci.util.class() --- Execute command and return output -- @param command String containing the command to execute -- @return String containing the command output function io.exec(command) local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") local buffer = fh:read("*a") fh:close() return buffer end --- Execute command and invoke given callback for each readed line -- @param command String containing the command to execute -- @param callback Function to call back for each line -- @return Always true function io.execl(command, callback) local ln local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") repeat ln = fh:read("*l") callback(ln) until not ln fh:close() return true end --- Execute command and return an iterator that returns one line per invokation -- @param command String containing the command to execute -- @return Iterator function function io.execi(command) local fh = _io.popen( "%s %s %q" %{ AST_BIN, AST_FLAGS, command }, "r" ) assert(fh, "Failed to invoke asterisk") return function() local ln = fh:read("*l") if not ln then fh:close() end return ln end end --- LuCI Asterisk - core status core = luci.util.class() --- Retrive version string. -- @return String containing the reported asterisk version function core.version(self) local version = io.exec("core show version") return version:gsub(" *\n", "") end --- LuCI Asterisk - SIP information. -- @type module sip = luci.util.class() --- Get a list of known SIP peers -- @return Table containing each SIP peer function sip.peers(self) local head = false local peers = { } for line in io.execi("sip show peers") do if not head then head = true elseif not line:match(" sip peers ") then local online, delay, id, uid local name, host, dyn, nat, acl, port, status = line:match("(.-) +(.-) +([D ]) ([N ]) (.) (%d+) +(.+)") if host == '(Unspecified)' then host = nil end if port == '0' then port = nil else port = tonumber(port) end dyn = ( dyn == 'D' and true or false ) nat = ( nat == 'N' and true or false ) acl = ( acl ~= ' ' and true or false ) online, delay = status:match("(OK) %((%d+) ms%)") if online == 'OK' then online = true delay = tonumber(delay) elseif status ~= 'Unmonitored' then online = false delay = 0 else online = nil delay = 0 end id, uid = name:match("(.+)/(.+)") if not ( id and uid ) then id = name .. "..." uid = nil end peers[#peers+1] = { online = online, delay = delay, name = id, user = uid, dynamic = dyn, nat = nat, acl = acl, host = host, port = port } end end return peers end --- Get informations of given SIP peer -- @param peer String containing the name of the SIP peer function sip.peer(peer) local info = { } local keys = { } for line in io.execi("sip show peer " .. peer) do if #line > 0 then local key, val = line:match("(.-) *: +(.*)") if key and val then key = key:gsub("^ +",""):gsub(" +$", "") val = val:gsub("^ +",""):gsub(" +$", "") if key == "* Name" then key = "Name" elseif key == "Addr->IP" then info.address, info.port = val:match("(.+) Port (.+)") info.port = tonumber(info.port) elseif key == "Status" then info.online, info.delay = val:match("(OK) %((%d+) ms%)") if info.online == 'OK' then info.online = true info.delay = tonumber(info.delay) elseif status ~= 'Unmonitored' then info.online = false info.delay = 0 else info.online = nil info.delay = 0 end end if val == 'Yes' or val == 'yes' or val == '<Set>' then val = true elseif val == 'No' or val == 'no' then val = false elseif val == '<Not set>' or val == '(none)' then val = nil end keys[#keys+1] = key info[key] = val end end end return info, keys end --- LuCI Asterisk - Internal helpers -- @type module tools = luci.util.class() --- Convert given value to a list of tokens. Split by white space. -- @param val String or table value -- @return Table containing tokens function tools.parse_list(v) local tokens = { } v = type(v) == "table" and v or { v } for _, v in ipairs(v) do if type(v) == "string" then for v in v:gmatch("(%S+)") do tokens[#tokens+1] = v end end end return tokens end --- Convert given list to a collection of hyperlinks -- @param list Table of tokens -- @param url String pattern or callback function to construct urls (optional) -- @param sep String containing the seperator (optional, default is ", ") -- @return String containing the html fragment function tools.hyperlinks(list, url, sep) local html local function mkurl(p, t) if type(p) == "string" then return p:format(t) elseif type(p) == "function" then return p(t) else return '#' end end list = list or { } url = url or "%s" sep = sep or ", " for _, token in ipairs(list) do html = ( html and html .. sep or '' ) .. '<a href="%s">%s</a>' %{ mkurl(url, token), token } end return html or '' end --- LuCI Asterisk - International Direct Dialing Prefixes -- @type module idd = luci.util.class() --- Lookup the country name for the given IDD code. -- @param country String containing IDD code -- @return String containing the country name function idd.country(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then for _, v2 in ipairs(v[3]) do if v2 == tostring(c) then return v[1] end end elseif v[3] == tostring(c) then return v[1] end end end --- Lookup the country code for the given IDD code. -- @param country String containing IDD code -- @return Table containing the country code(s) function idd.cc(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then for _, v2 in ipairs(v[3]) do if v2 == tostring(c) then return type(v[2]) == "table" and v[2] or { v[2] } end end elseif v[3] == tostring(c) then return type(v[2]) == "table" and v[2] or { v[2] } end end end --- Lookup the IDD code(s) for the given country. -- @param idd String containing the country name -- @return Table containing the IDD code(s) function idd.idd(c) for _, v in ipairs(cc_idd.CC_IDD) do if v[1]:lower():match(c:lower()) then return type(v[3]) == "table" and v[3] or { v[3] } end end end --- Populate given CBI field with IDD codes. -- @param field CBI option object -- @return (nothing) function idd.cbifill(o) for i, v in ipairs(cc_idd.CC_IDD) do o:value("_%i" % i, util.pcdata(v[1])) end o.formvalue = function(...) local val = luci.cbi.Value.formvalue(...) if val:sub(1,1) == "_" then val = tonumber((val:gsub("^_", ""))) if val then return type(cc_idd.CC_IDD[val][3]) == "table" and cc_idd.CC_IDD[val][3] or { cc_idd.CC_IDD[val][3] } end end return val end o.cfgvalue = function(...) local val = luci.cbi.Value.cfgvalue(...) if val then val = tools.parse_list(val) for i, v in ipairs(cc_idd.CC_IDD) do if type(v[3]) == "table" then if v[3][1] == val[1] then return "_%i" % i end else if v[3] == val[1] then return "_%i" % i end end end end return val end end --- LuCI Asterisk - Country Code Prefixes -- @type module cc = luci.util.class() --- Lookup the country name for the given CC code. -- @param country String containing CC code -- @return String containing the country name function cc.country(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then for _, v2 in ipairs(v[2]) do if v2 == tostring(c) then return v[1] end end elseif v[2] == tostring(c) then return v[1] end end end --- Lookup the international dialing code for the given CC code. -- @param cc String containing CC code -- @return String containing IDD code function cc.idd(c) for _, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then for _, v2 in ipairs(v[2]) do if v2 == tostring(c) then return type(v[3]) == "table" and v[3] or { v[3] } end end elseif v[2] == tostring(c) then return type(v[3]) == "table" and v[3] or { v[3] } end end end --- Lookup the CC code(s) for the given country. -- @param country String containing the country name -- @return Table containing the CC code(s) function cc.cc(c) for _, v in ipairs(cc_idd.CC_IDD) do if v[1]:lower():match(c:lower()) then return type(v[2]) == "table" and v[2] or { v[2] } end end end --- Populate given CBI field with CC codes. -- @param field CBI option object -- @return (nothing) function cc.cbifill(o) for i, v in ipairs(cc_idd.CC_IDD) do o:value("_%i" % i, util.pcdata(v[1])) end o.formvalue = function(...) local val = luci.cbi.Value.formvalue(...) if val:sub(1,1) == "_" then val = tonumber((val:gsub("^_", ""))) if val then return type(cc_idd.CC_IDD[val][2]) == "table" and cc_idd.CC_IDD[val][2] or { cc_idd.CC_IDD[val][2] } end end return val end o.cfgvalue = function(...) local val = luci.cbi.Value.cfgvalue(...) if val then val = tools.parse_list(val) for i, v in ipairs(cc_idd.CC_IDD) do if type(v[2]) == "table" then if v[2][1] == val[1] then return "_%i" % i end else if v[2] == val[1] then return "_%i" % i end end end end return val end end --- LuCI Asterisk - Dialzone -- @type module dialzone = luci.util.class() --- Parse a dialzone section -- @param zone Table containing the zone info -- @return Table with parsed information function dialzone.parse(z) if z['.name'] then return { trunks = tools.parse_list(z.uses), name = z['.name'], description = z.description or z['.name'], addprefix = z.addprefix, matches = tools.parse_list(z.match), intlmatches = tools.parse_list(z.international), countrycode = z.countrycode, localzone = z.localzone, localprefix = z.localprefix } end end --- Get a list of known dial zones -- @return Associative table of zones and table of zone names function dialzone.zones() local zones = { } local znames = { } uci:foreach("asterisk", "dialzone", function(z) zones[z['.name']] = dialzone.parse(z) znames[#znames+1] = z['.name'] end) return zones, znames end --- Get a specific dial zone -- @param name Name of the dial zone -- @return Table containing zone information function dialzone.zone(n) local zone uci:foreach("asterisk", "dialzone", function(z) if z['.name'] == n then zone = dialzone.parse(z) end end) return zone end --- Find uci section hash for given zone number -- @param idx Zone number -- @return String containing the uci hash pointing to the section function dialzone.ucisection(i) local hash local index = 1 i = tonumber(i) uci:foreach("asterisk", "dialzone", function(z) if not hash and index == i then hash = z['.name'] end index = index + 1 end) return hash end --- LuCI Asterisk - Voicemailbox -- @type module voicemail = luci.util.class() --- Parse a voicemail section -- @param zone Table containing the mailbox info -- @return Table with parsed information function voicemail.parse(z) if z.number and #z.number > 0 then local v = { id = '%s@%s' %{ z.number, z.context or 'default' }, number = z.number, context = z.context or 'default', name = z.name or z['.name'] or 'OpenWrt', zone = z.zone or 'homeloc', password = z.password or '0000', email = z.email or '', page = z.page or '', dialplans = { } } uci:foreach("asterisk", "dialplanvoice", function(s) if s.dialplan and #s.dialplan > 0 and s.voicebox == v.number then v.dialplans[#v.dialplans+1] = s.dialplan end end) return v end end --- Get a list of known voicemail boxes -- @return Associative table of boxes and table of box numbers function voicemail.boxes() local vboxes = { } local vnames = { } uci:foreach("asterisk", "voicemail", function(z) local v = voicemail.parse(z) if v then local n = '%s@%s' %{ v.number, v.context } vboxes[n] = v vnames[#vnames+1] = n end end) return vboxes, vnames end --- Get a specific voicemailbox -- @param number Number of the voicemailbox -- @return Table containing mailbox information function voicemail.box(n) local box n = n:gsub("@.+$","") uci:foreach("asterisk", "voicemail", function(z) if z.number == tostring(n) then box = voicemail.parse(z) end end) return box end --- Find all voicemailboxes within the given dialplan -- @param plan Dialplan name or table -- @return Associative table containing extensions mapped to mailbox info function voicemail.in_dialplan(p) local plan = type(p) == "string" and p or p.name local boxes = { } uci:foreach("asterisk", "dialplanvoice", function(s) if s.extension and #s.extension > 0 and s.dialplan == plan then local box = voicemail.box(s.voicebox) if box then boxes[s.extension] = box end end end) return boxes end --- Remove voicemailbox and associated extensions from config -- @param box Voicemailbox number or table -- @param ctx UCI context to use (optional) -- @return Boolean indicating success function voicemail.remove(v, ctx) ctx = ctx or uci local box = type(v) == "string" and v or v.number local ok1 = ctx:delete_all("asterisk", "voicemail", {number=box}) local ok2 = ctx:delete_all("asterisk", "dialplanvoice", {voicebox=box}) return ( ok1 or ok2 ) and true or false end --- LuCI Asterisk - MeetMe Conferences -- @type module meetme = luci.util.class() --- Parse a meetme section -- @param room Table containing the room info -- @return Table with parsed information function meetme.parse(r) if r.room and #r.room > 0 then local v = { room = r.room, pin = r.pin or '', adminpin = r.adminpin or '', description = r._description or '', dialplans = { } } uci:foreach("asterisk", "dialplanmeetme", function(s) if s.dialplan and #s.dialplan > 0 and s.room == v.room then v.dialplans[#v.dialplans+1] = s.dialplan end end) return v end end --- Get a list of known meetme rooms -- @return Associative table of rooms and table of room numbers function meetme.rooms() local mrooms = { } local mnames = { } uci:foreach("asterisk", "meetme", function(r) local v = meetme.parse(r) if v then mrooms[v.room] = v mnames[#mnames+1] = v.room end end) return mrooms, mnames end --- Get a specific meetme room -- @param number Number of the room -- @return Table containing room information function meetme.room(n) local room uci:foreach("asterisk", "meetme", function(r) if r.room == tostring(n) then room = meetme.parse(r) end end) return room end --- Find all meetme rooms within the given dialplan -- @param plan Dialplan name or table -- @return Associative table containing extensions mapped to room info function meetme.in_dialplan(p) local plan = type(p) == "string" and p or p.name local rooms = { } uci:foreach("asterisk", "dialplanmeetme", function(s) if s.extension and #s.extension > 0 and s.dialplan == plan then local room = meetme.room(s.room) if room then rooms[s.extension] = room end end end) return rooms end --- Remove meetme room and associated extensions from config -- @param room Voicemailbox number or table -- @param ctx UCI context to use (optional) -- @return Boolean indicating success function meetme.remove(v, ctx) ctx = ctx or uci local room = type(v) == "string" and v or v.number local ok1 = ctx:delete_all("asterisk", "meetme", {room=room}) local ok2 = ctx:delete_all("asterisk", "dialplanmeetme", {room=room}) return ( ok1 or ok2 ) and true or false end --- LuCI Asterisk - Dialplan -- @type module dialplan = luci.util.class() --- Parse a dialplan section -- @param plan Table containing the plan info -- @return Table with parsed information function dialplan.parse(z) if z['.name'] then local plan = { zones = { }, name = z['.name'], description = z.description or z['.name'] } -- dialzones for _, name in ipairs(tools.parse_list(z.include)) do local zone = dialzone.zone(name) if zone then plan.zones[#plan.zones+1] = zone end end -- voicemailboxes plan.voicemailboxes = voicemail.in_dialplan(plan) -- meetme conferences plan.meetmerooms = meetme.in_dialplan(plan) return plan end end --- Get a list of known dial plans -- @return Associative table of plans and table of plan names function dialplan.plans() local plans = { } local pnames = { } uci:foreach("asterisk", "dialplan", function(p) plans[p['.name']] = dialplan.parse(p) pnames[#pnames+1] = p['.name'] end) return plans, pnames end --- Get a specific dial plan -- @param name Name of the dial plan -- @return Table containing plan information function dialplan.plan(n) local plan uci:foreach("asterisk", "dialplan", function(p) if p['.name'] == n then plan = dialplan.parse(p) end end) return plan end
apache-2.0
Lsty/ygopro-scripts
c72192100.lua
3
2871
--デスルークデーモン function c72192100.initial_effect(c) --maintain local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EVENT_PHASE+PHASE_STANDBY) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCondition(c72192100.mtcon) e1:SetOperation(c72192100.mtop) c:RegisterEffect(e1) --disable and destroy local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_CHAIN_SOLVING) e2:SetRange(LOCATION_MZONE) e2:SetOperation(c72192100.disop) c:RegisterEffect(e2) --special summon local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetDescription(aux.Stringid(72192100,0)) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_QUICK_O) e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP) e3:SetCode(EVENT_TO_GRAVE) e3:SetRange(LOCATION_HAND) e3:SetCost(c72192100.spcost) e3:SetTarget(c72192100.sptg) e3:SetOperation(c72192100.spop) c:RegisterEffect(e3) end function c72192100.mtcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c72192100.mtop(e,tp,eg,ep,ev,re,r,rp) if Duel.CheckLPCost(tp,500) then Duel.PayLPCost(tp,500) else Duel.Destroy(e:GetHandler(),REASON_RULE) end end function c72192100.disop(e,tp,eg,ep,ev,re,r,rp) if ep==tp then return end if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return false end local tg=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS) if not tg or not tg:IsContains(e:GetHandler()) or not Duel.IsChainDisablable(ev) then return false end local rc=re:GetHandler() local dc=Duel.TossDice(tp,1) if dc~=3 then return end Duel.NegateEffect(ev) if rc:IsRelateToEffect(re) then Duel.Destroy(rc,REASON_EFFECT) end end function c72192100.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end Duel.SendtoGrave(e:GetHandler(),REASON_COST) end function c72192100.filter(c,e,tp) return c:IsCode(35975813) and c:GetPreviousControler()==tp and c:IsPreviousLocation(LOCATION_ONFIELD) and c:IsCanBeEffectTarget(e) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c72192100.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return eg:IsContains(chkc) and c72192100.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and eg:IsExists(c72192100.filter,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=eg:FilterSelect(tp,c72192100.filter,1,1,nil,e,tp) Duel.SetTargetCard(g) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c72192100.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
Lsty/ygopro-scripts
c25727454.lua
5
1398
--名匠 ガミル function c25727454.initial_effect(c) --atkup local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(25727454,0)) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_QUICK_O) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(TIMING_DAMAGE_STEP) e1:SetRange(LOCATION_HAND) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e1:SetCondition(c25727454.condition) e1:SetCost(c25727454.cost) e1:SetOperation(c25727454.operation) c:RegisterEffect(e1) end function c25727454.condition(e,tp,eg,ep,ev,re,r,rp) local phase=Duel.GetCurrentPhase() if phase~=PHASE_DAMAGE or Duel.IsDamageCalculated() then return false end local a=Duel.GetAttacker() local d=Duel.GetAttackTarget() return (a:IsControler(tp) and a:IsRelateToBattle()) or (d and d:IsControler(tp) and d:IsRelateToBattle()) end function c25727454.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end Duel.SendtoGrave(e:GetHandler(),REASON_COST) end function c25727454.operation(e,tp,eg,ep,ev,re,r,rp) local a=Duel.GetAttacker() if Duel.GetTurnPlayer()~=tp then a=Duel.GetAttackTarget() end if not a:IsRelateToBattle() or a:IsFacedown() then return end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e1:SetValue(300) a:RegisterEffect(e1) end
gpl-2.0
Lsty/ygopro-scripts
c84764038.lua
3
2866
--彼岸の悪鬼 スカラマリオン function c84764038.initial_effect(c) --self destroy local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_SELF_DESTROY) e1:SetCondition(c84764038.sdcon) c:RegisterEffect(e1) --Special Summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(84764038,0)) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetRange(LOCATION_HAND) e2:SetCountLimit(1,84764038) e2:SetCondition(c84764038.sscon) e2:SetTarget(c84764038.sstg) e2:SetOperation(c84764038.ssop) c:RegisterEffect(e2) --to grave local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e3:SetCode(EVENT_TO_GRAVE) e3:SetOperation(c84764038.regop) c:RegisterEffect(e3) end function c84764038.sdfilter(c) return not c:IsFaceup() or not c:IsSetCard(0xb1) end function c84764038.sdcon(e) return Duel.IsExistingMatchingCard(c84764038.sdfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil) end function c84764038.filter(c) return c:IsType(TYPE_SPELL+TYPE_TRAP) end function c84764038.sscon(e,tp,eg,ep,ev,re,r,rp) return not Duel.IsExistingMatchingCard(c84764038.filter,tp,LOCATION_ONFIELD,0,1,nil) end function c84764038.sstg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c84764038.ssop(e,tp,eg,ep,ev,re,r,rp) if e:GetHandler():IsRelateToEffect(e) then Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP) end end function c84764038.regop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(84764038,1)) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetCountLimit(1,84764038) e1:SetRange(LOCATION_GRAVE) e1:SetTarget(c84764038.thtg) e1:SetOperation(c84764038.thop) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) c:RegisterEffect(e1) end function c84764038.thfilter(c) return c:GetLevel()==3 and c:IsAttribute(ATTRIBUTE_DARK) and c:IsRace(RACE_FIEND) and not c:IsCode(84764038) and c:IsAbleToHand() end function c84764038.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c84764038.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c84764038.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c84764038.thfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
gpl-2.0
gallenmu/MoonGen
libmoon/lua/lib/syscall/linux/ppc/nr.lua
6
11241
-- ppc syscall numbers local nr = { zeropad = true, SYS = { restart_syscall = 0, exit = 1, fork = 2, read = 3, write = 4, open = 5, close = 6, waitpid = 7, creat = 8, link = 9, unlink = 10, execve = 11, chdir = 12, time = 13, mknod = 14, chmod = 15, lchown = 16, ["break"] = 17, oldstat = 18, lseek = 19, getpid = 20, mount = 21, umount = 22, setuid = 23, getuid = 24, stime = 25, ptrace = 26, alarm = 27, oldfstat = 28, pause = 29, utime = 30, stty = 31, gtty = 32, access = 33, nice = 34, ftime = 35, sync = 36, kill = 37, rename = 38, mkdir = 39, rmdir = 40, dup = 41, pipe = 42, times = 43, prof = 44, brk = 45, setgid = 46, getgid = 47, signal = 48, geteuid = 49, getegid = 50, acct = 51, umount2 = 52, lock = 53, ioctl = 54, fcntl = 55, mpx = 56, setpgid = 57, ulimit = 58, oldolduname = 59, umask = 60, chroot = 61, ustat = 62, dup2 = 63, getppid = 64, getpgrp = 65, setsid = 66, sigaction = 67, sgetmask = 68, ssetmask = 69, setreuid = 70, setregid = 71, sigsuspend = 72, sigpending = 73, sethostname = 74, setrlimit = 75, getrlimit = 76, getrusage = 77, gettimeofday = 78, settimeofday = 79, getgroups = 80, setgroups = 81, select = 82, symlink = 83, oldlstat = 84, readlink = 85, uselib = 86, swapon = 87, reboot = 88, readdir = 89, mmap = 90, munmap = 91, truncate = 92, ftruncate = 93, fchmod = 94, fchown = 95, getpriority = 96, setpriority = 97, profil = 98, statfs = 99, fstatfs = 100, ioperm = 101, socketcall = 102, syslog = 103, setitimer = 104, getitimer = 105, stat = 106, lstat = 107, fstat = 108, olduname = 109, iopl = 110, vhangup = 111, idle = 112, vm86 = 113, wait4 = 114, swapoff = 115, sysinfo = 116, ipc = 117, fsync = 118, sigreturn = 119, clone = 120, setdomainname = 121, uname = 122, modify_ldt = 123, adjtimex = 124, mprotect = 125, sigprocmask = 126, create_module = 127, init_module = 128, delete_module = 129, get_kernel_syms = 130, quotactl = 131, getpgid = 132, fchdir = 133, bdflush = 134, sysfs = 135, personality = 136, afs_syscall = 137, setfsuid = 138, setfsgid = 139, _llseek = 140, getdents = 141, _newselect = 142, flock = 143, msync = 144, readv = 145, writev = 146, getsid = 147, fdatasync = 148, _sysctl = 149, mlock = 150, munlock = 151, mlockall = 152, munlockall = 153, sched_setparam = 154, sched_getparam = 155, sched_setscheduler = 156, sched_getscheduler = 157, sched_yield = 158, sched_get_priority_max= 159, sched_get_priority_min= 160, sched_rr_get_interval = 161, nanosleep = 162, mremap = 163, setresuid = 164, getresuid = 165, query_module = 166, poll = 167, nfsservctl = 168, setresgid = 169, getresgid = 170, prctl = 171, rt_sigreturn = 172, rt_sigaction = 173, rt_sigprocmask = 174, rt_sigpending = 175, rt_sigtimedwait = 176, rt_sigqueueinfo = 177, rt_sigsuspend = 178, pread64 = 179, pwrite64 = 180, chown = 181, getcwd = 182, capget = 183, capset = 184, sigaltstack = 185, sendfile = 186, getpmsg = 187, putpmsg = 188, vfork = 189, ugetrlimit = 190, readahead = 191, mmap2 = 192, truncate64 = 193, ftruncate64 = 194, stat64 = 195, lstat64 = 196, fstat64 = 197, pciconfig_read = 198, pciconfig_write = 199, pciconfig_iobase = 200, multiplexer = 201, getdents64 = 202, pivot_root = 203, fcntl64 = 204, madvise = 205, mincore = 206, gettid = 207, tkill = 208, setxattr = 209, lsetxattr = 210, fsetxattr = 211, getxattr = 212, lgetxattr = 213, fgetxattr = 214, listxattr = 215, llistxattr = 216, flistxattr = 217, removexattr = 218, lremovexattr = 219, fremovexattr = 220, futex = 221, sched_setaffinity = 222, sched_getaffinity = 223, tuxcall = 225, sendfile64 = 226, io_setup = 227, io_destroy = 228, io_getevents = 229, io_submit = 230, io_cancel = 231, set_tid_address = 232, fadvise64 = 233, exit_group = 234, lookup_dcookie = 235, epoll_create = 236, epoll_ctl = 237, epoll_wait = 238, remap_file_pages = 239, timer_create = 240, timer_settime = 241, timer_gettime = 242, timer_getoverrun = 243, timer_delete = 244, clock_settime = 245, clock_gettime = 246, clock_getres = 247, clock_nanosleep = 248, swapcontext = 249, tgkill = 250, utimes = 251, statfs64 = 252, fstatfs64 = 253, fadvise64_64 = 254, rtas = 255, sys_debug_setcontext = 256, migrate_pages = 258, mbind = 259, get_mempolicy = 260, set_mempolicy = 261, mq_open = 262, mq_unlink = 263, mq_timedsend = 264, mq_timedreceive = 265, mq_notify = 266, mq_getsetattr = 267, kexec_load = 268, add_key = 269, request_key = 270, keyctl = 271, waitid = 272, ioprio_set = 273, ioprio_get = 274, inotify_init = 275, inotify_add_watch = 276, inotify_rm_watch = 277, spu_run = 278, spu_create = 279, pselect6 = 280, ppoll = 281, unshare = 282, splice = 283, tee = 284, vmsplice = 285, openat = 286, mkdirat = 287, mknodat = 288, fchownat = 289, futimesat = 290, fstatat64 = 291, unlinkat = 292, renameat = 293, linkat = 294, symlinkat = 295, readlinkat = 296, fchmodat = 297, faccessat = 298, get_robust_list = 299, set_robust_list = 300, move_pages = 301, getcpu = 302, epoll_pwait = 303, utimensat = 304, signalfd = 305, timerfd_create = 306, eventfd = 307, sync_file_range2 = 308, fallocate = 309, subpage_prot = 310, timerfd_settime = 311, timerfd_gettime = 312, signalfd4 = 313, eventfd2 = 314, epoll_create1 = 315, dup3 = 316, pipe2 = 317, inotify_init1 = 318, perf_event_open = 319, preadv = 320, pwritev = 321, rt_tgsigqueueinfo = 322, fanotify_init = 323, fanotify_mark = 324, prlimit64 = 325, socket = 326, bind = 327, connect = 328, listen = 329, accept = 330, getsockname = 331, getpeername = 332, socketpair = 333, send = 334, sendto = 335, recv = 336, recvfrom = 337, shutdown = 338, setsockopt = 339, getsockopt = 340, sendmsg = 341, recvmsg = 342, recvmmsg = 343, accept4 = 344, name_to_handle_at = 345, open_by_handle_at = 346, clock_adjtime = 347, syncfs = 348, sendmmsg = 349, setns = 350, process_vm_readv = 351, process_vm_writev = 352, kcmp = 353, finit_module = 354, sched_setattr = 355, sched_getattr = 356, renameat2 = 357, seccomp = 358, getrandom = 359, memfd_create = 360, bpf = 361, } } return nr
mit
MahmoudDolah/Firmware-Entry-Points-In-Memory
openwrt/openwrt-generic-x86/usr/lib/lua/luci/model/cbi/admin_system/fstab.lua
39
5639
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. require("luci.tools.webadmin") local fs = require "nixio.fs" local util = require "nixio.util" local tp = require "luci.template.parser" local block = io.popen("block info", "r") local ln, dev, devices = nil, nil, {} repeat ln = block:read("*l") dev = ln and ln:match("^/dev/(.-):") if dev then local e, s, key, val = { } for key, val in ln:gmatch([[(%w+)="(.-)"]]) do e[key:lower()] = val devices[val] = e end s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev))) e.dev = "/dev/%s" % dev e.size = s and math.floor(s / 2048) devices[e.dev] = e end until not ln block:close() m = Map("fstab", translate("Mount Points")) local mounts = luci.sys.mounts() v = m:section(Table, mounts, translate("Mounted file systems")) fs = v:option(DummyValue, "fs", translate("Filesystem")) mp = v:option(DummyValue, "mountpoint", translate("Mount Point")) avail = v:option(DummyValue, "avail", translate("Available")) function avail.cfgvalue(self, section) return luci.tools.webadmin.byte_format( ( tonumber(mounts[section].available) or 0 ) * 1024 ) .. " / " .. luci.tools.webadmin.byte_format( ( tonumber(mounts[section].blocks) or 0 ) * 1024 ) end used = v:option(DummyValue, "used", translate("Used")) function used.cfgvalue(self, section) return ( mounts[section].percent or "0%" ) .. " (" .. luci.tools.webadmin.byte_format( ( tonumber(mounts[section].used) or 0 ) * 1024 ) .. ")" end mount = m:section(TypedSection, "mount", translate("Mount Points"), translate("Mount Points define at which point a memory device will be attached to the filesystem")) mount.anonymous = true mount.addremove = true mount.template = "cbi/tblsection" mount.extedit = luci.dispatcher.build_url("admin/system/fstab/mount/%s") mount.create = function(...) local sid = TypedSection.create(...) if sid then luci.http.redirect(mount.extedit % sid) return end end mount:option(Flag, "enabled", translate("Enabled")).rmempty = false dev = mount:option(DummyValue, "device", translate("Device")) dev.rawhtml = true dev.cfgvalue = function(self, section) local v, e v = m.uci:get("fstab", section, "uuid") e = v and devices[v:lower()] if v and e and e.size then return "UUID: %s (%s, %d MB)" %{ tp.pcdata(v), e.dev, e.size } elseif v and e then return "UUID: %s (%s)" %{ tp.pcdata(v), e.dev } elseif v then return "UUID: %s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") } end v = m.uci:get("fstab", section, "label") e = v and devices[v] if v and e and e.size then return "Label: %s (%s, %d MB)" %{ tp.pcdata(v), e.dev, e.size } elseif v and e then return "Label: %s (%s)" %{ tp.pcdata(v), e.dev } elseif v then return "Label: %s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") } end v = Value.cfgvalue(self, section) or "?" e = v and devices[v] if v and e and e.size then return "%s (%d MB)" %{ tp.pcdata(v), e.size } elseif v and e then return tp.pcdata(v) elseif v then return "%s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") } end end mp = mount:option(DummyValue, "target", translate("Mount Point")) mp.cfgvalue = function(self, section) if m.uci:get("fstab", section, "is_rootfs") == "1" then return "/overlay" else return Value.cfgvalue(self, section) or "?" end end fs = mount:option(DummyValue, "fstype", translate("Filesystem")) fs.cfgvalue = function(self, section) local v, e v = m.uci:get("fstab", section, "uuid") v = v and v:lower() or m.uci:get("fstab", section, "label") v = v or m.uci:get("fstab", section, "device") e = v and devices[v] return e and e.type or m.uci:get("fstab", section, "fstype") or "?" end op = mount:option(DummyValue, "options", translate("Options")) op.cfgvalue = function(self, section) return Value.cfgvalue(self, section) or "defaults" end rf = mount:option(DummyValue, "is_rootfs", translate("Root")) rf.cfgvalue = function(self, section) local target = m.uci:get("fstab", section, "target") if target == "/" then return translate("yes") elseif target == "/overlay" then return translate("overlay") else return translate("no") end end ck = mount:option(DummyValue, "enabled_fsck", translate("Check")) ck.cfgvalue = function(self, section) return Value.cfgvalue(self, section) == "1" and translate("yes") or translate("no") end swap = m:section(TypedSection, "swap", "SWAP", translate("If your physical memory is insufficient unused data can be temporarily swapped to a swap-device resulting in a higher amount of usable <abbr title=\"Random Access Memory\">RAM</abbr>. Be aware that swapping data is a very slow process as the swap-device cannot be accessed with the high datarates of the <abbr title=\"Random Access Memory\">RAM</abbr>.")) swap.anonymous = true swap.addremove = true swap.template = "cbi/tblsection" swap.extedit = luci.dispatcher.build_url("admin/system/fstab/swap/%s") swap.create = function(...) local sid = TypedSection.create(...) if sid then luci.http.redirect(swap.extedit % sid) return end end swap:option(Flag, "enabled", translate("Enabled")).rmempty = false dev = swap:option(DummyValue, "device", translate("Device")) dev.cfgvalue = function(self, section) local v v = m.uci:get("fstab", section, "uuid") if v then return "UUID: %s" % v end v = m.uci:get("fstab", section, "label") if v then return "Label: %s" % v end v = Value.cfgvalue(self, section) or "?" e = v and devices[v] if v and e and e.size then return "%s (%s MB)" % {v, e.size} else return v end end return m
apache-2.0
MalRD/darkstar
scripts/globals/items/pukatrice_egg.lua
11
1541
----------------------------------------- -- ID: 6274 -- Item: pukatrice_egg -- Food Effect: 30Min, All Races ----------------------------------------- -- HP +15 -- MP +15 -- STR +2 -- Fire resistance +20 -- Attack +20% (cap 85) -- Ranged Attack +20% (cap 85) -- Subtle Blow +8 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,1800,6274) end function onEffectGain(target,effect) target:addMod(dsp.mod.HP, 15) target:addMod(dsp.mod.MP, 15) target:addMod(dsp.mod.STR, 2) target:addMod(dsp.mod.FIRERES, 20) target:addMod(dsp.mod.FOOD_ATTP, 20) target:addMod(dsp.mod.FOOD_ATT_CAP, 85) target:addMod(dsp.mod.FOOD_RATTP, 20) target:addMod(dsp.mod.FOOD_RATT_CAP, 85) target:addMod(dsp.mod.SUBTLE_BLOW, 8) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 15) target:delMod(dsp.mod.MP, 15) target:delMod(dsp.mod.STR, 2) target:delMod(dsp.mod.FIRERES, 20) target:delMod(dsp.mod.FOOD_ATTP, 20) target:delMod(dsp.mod.FOOD_ATT_CAP, 85) target:delMod(dsp.mod.FOOD_RATTP, 20) target:delMod(dsp.mod.FOOD_RATT_CAP, 85) target:delMod(dsp.mod.SUBTLE_BLOW, 8) end
gpl-3.0
Lsty/ygopro-scripts
c76891401.lua
5
1085
--神海竜ギシルノドン function c76891401.initial_effect(c) --synchro summon aux.AddSynchroProcedure2(c,nil,aux.NonTuner(c76891401.synfilter)) c:EnableReviveLimit() --atk change local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(76891401,0)) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e1:SetCode(EVENT_TO_GRAVE) e1:SetRange(LOCATION_MZONE) e1:SetCondition(c76891401.atkcon) e1:SetOperation(c76891401.atkop) c:RegisterEffect(e1) end function c76891401.synfilter(c) return c:GetLevel()==3 end function c76891401.filter(c) return c:IsLevelBelow(3) and c:IsPreviousLocation(LOCATION_ONFIELD) and c:IsPreviousPosition(POS_FACEUP) end function c76891401.atkcon(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c76891401.filter,1,nil) end function c76891401.atkop(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SET_ATTACK_FINAL) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e1:SetValue(3000) c:RegisterEffect(e1) end
gpl-2.0
MalRD/darkstar
scripts/zones/The_Sanctuary_of_ZiTah/npcs/qm3.lua
9
1154
----------------------------------- -- Area: The Sanctuary of Zitah -- NPC: ??? -- Involved In Quest: The Sacred Katana -- !pos -416 0 46 121 ----------------------------------- local ID = require("scripts/zones/The_Sanctuary_of_ZiTah/IDs") require("scripts/globals/keyitems") require("scripts/globals/npc_util") require("scripts/globals/quests") ----------------------------------- function onTrade(player,npc,trade) if player:getQuestStatus(OUTLANDS, dsp.quest.id.outlands.THE_SACRED_KATANA) == QUEST_ACCEPTED then if npcUtil.tradeHas(trade, 1168) and npcUtil.popFromQM(player, npc, ID.mob.ISONADE, {hide = 0}) then -- Sack of Fish Bait player:confirmTrade() player:messageSpecial(ID.text.SENSE_OF_FOREBODING) end end end function onTrigger(player,npc) if player:getCharVar("IsonadeKilled") == 1 then player:setCharVar("IsonadeKilled", 0) npcUtil.giveKeyItem(player, dsp.ki.HANDFUL_OF_CRYSTAL_SCALES) else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
gpl-3.0
Aaa1r/DRAGON
plugins/inrealm.lua
183
36473
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.peer_id, result.peer_id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.peer_id, result.peer_id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then if msg.to.type == 'chat' and not is_realm(msg) then data[tostring(msg.to.id)]['group_type'] = 'Group' save_data(_config.moderation.data, data) elseif msg.to.type == 'channel' then data[tostring(msg.to.id)]['group_type'] = 'SuperGroup' save_data(_config.moderation.data, data) end end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid local channel = 'channel#id'..extra.chatid send_large_msg(chat, user..'\n'..name) send_large_msg(channel, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin1(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_arabic(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic/Persian is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic/Persian has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL char. in names is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL char. in names has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL char. in names is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL char. in names has been unlocked' end end local function lock_group_links(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Link posting is already locked' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Link posting has been locked' end end local function unlock_group_links(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Link posting is not locked' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Link posting has been unlocked' end end local function lock_group_spam(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return 'SuperGroup spam is already locked' else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'SuperGroup spam has been locked' end end local function unlock_group_spam(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return 'SuperGroup spam is not locked' else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup spam has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL char. in names is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL char. in names has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL char. in names is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL char. in names has been unlocked' end end local function lock_group_sticker(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker posting is already locked' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker posting has been locked' end end local function unlock_group_sticker(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker posting is already unlocked' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker posting has been unlocked' end end local function set_public_membermod(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_public_lock = data[tostring(target)]['settings']['public'] if group_public_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup is now: public' end local function unset_public_membermod(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_public_lock = data[tostring(target)]['settings']['public'] if group_public_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup is now: not public' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin1(msg) then return "For admins only!" end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "Group settings for "..target..":\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nPublic: "..settings.public end -- show SuperGroup settings local function show_super_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin1(msg) then return "For admins only!" end if data[tostring(msg.to.id)]['settings'] then if not data[tostring(msg.to.id)]['settings']['public'] then data[tostring(msg.to.id)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict return text end local function returnids(cb_extra, success, result) local i = 1 local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' (ID: '..result.peer_id..'):\n\n' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text ..i..' - '.. string.gsub(v.print_name,"_"," ") .. " [" .. v.peer_id .. "] \n\n" i = i + 1 end end local file = io.open("./groups/lists/"..result.peer_id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function cb_user_info(cb_extra, success, result) local receiver = cb_extra.receiver if result.first_name then first_name = result.first_name:gsub("_", " ") else first_name = "None" end if result.last_name then last_name = result.last_name:gsub("_", " ") else last_name = "None" end if result.username then username = "@"..result.username else username = "@[none]" end text = "User Info:\n\nID: "..result.peer_id.."\nFirst: "..first_name.."\nLast: "..last_name.."\nUsername: "..username send_large_msg(receiver, text) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_id..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List of global admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do if data[tostring(v)] then if data[tostring(v)]['settings'] then local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end end end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, '@'..member_username..' is already an admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then send_large_msg(receiver, "@"..member_username..' is not an admin.') return end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, 'Admin @'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.peer_id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function res_user_support(cb_extra, success, result) local receiver = cb_extra.receiver local get_cmd = cb_extra.get_cmd local support_id = result.peer_id if get_cmd == 'addsupport' then support_add(support_id) send_large_msg(receiver, "User ["..support_id.."] has been added to the support team") elseif get_cmd == 'removesupport' then support_remove(support_id) send_large_msg(receiver, "User ["..support_id.."] has been removed from the support team") end end local function set_log_group(target, data) if not is_admin1(msg) then return end local log_group = data[tostring(target)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(target)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin1(msg) then return end local log_group = data[tostring(target)]['log_group'] if log_group == 'no' then return 'Log group is not set' else data[tostring(target)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then local receiver = get_receiver(msg) savelog(msg.to.id, "log file created by owner/support/admin") send_document(receiver,"./groups/logs/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and msg.to.type == 'chat' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) local file = io.open("./groups/lists/"..msg.to.id.."memberlist.txt", "r") text = file:read("*a") send_large_msg(receiver,text) file:close() end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) send_document("chat#id"..msg.to.id,"./groups/lists/"..msg.to.id.."memberlist.txt", ok_cb, false) end if matches[1] == 'whois' and is_momod(msg) then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] user_info(user_id, cb_user_info, {receiver = receiver}) end if not is_sudo(msg) then if is_realm(msg) and is_admin1(msg) then print("Admin detected") else return end end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end --[[ Experimental if matches[1] == 'createsuper' and matches[2] then if not is_sudo(msg) or is_admin1(msg) and is_realm(msg) then return "You cant create groups!" end group_name = matches[2] group_type = 'super_group' return create_group(msg) end]] if matches[1] == 'createrealm' and matches[2] then if not is_sudo(msg) then return "Sudo users only !" end group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[1] == 'setabout' and matches[2] == 'group' and is_realm(msg) then local target = matches[3] local about = matches[4] return set_description(msg, data, target, about) end if matches[1] == 'setabout' and matches[2] == 'sgroup'and is_realm(msg) then local channel = 'channel#id'..matches[3] local about_text = matches[4] local data_cat = 'description' local target = matches[3] channel_set_about(channel, about_text, ok_cb, false) data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) return "Description has been set for ["..matches[2]..']' end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end if matches[2] == 'arabic' then return lock_group_arabic(msg, data, target) end if matches[3] == 'links' then return lock_group_links(msg, data, target) end if matches[3] == 'spam' then return lock_group_spam(msg, data, target) end if matches[3] == 'rtl' then return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' then return lock_group_sticker(msg, data, target) end end if matches[1] == 'unlock' then local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end if matches[3] == 'arabic' then return unlock_group_arabic(msg, data, target) end if matches[3] == 'links' then return unlock_group_links(msg, data, target) end if matches[3] == 'spam' then return unlock_group_spam(msg, data, target) end if matches[3] == 'rtl' then return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' then return unlock_group_sticker(msg, data, target) end end if matches[1] == 'settings' and matches[2] == 'group' and data[tostring(matches[3])]['settings'] then local target = matches[3] text = show_group_settingsmod(msg, target) return text.."\nID: "..target.."\n" end if matches[1] == 'settings' and matches[2] == 'sgroup' and data[tostring(matches[3])]['settings'] then local target = matches[3] text = show_supergroup_settingsmod(msg, target) return text.."\nID: "..target.."\n" end if matches[1] == 'setname' and is_realm(msg) then local settings = data[tostring(matches[2])]['settings'] local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin1(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local chat_to_rename = 'chat#id'..matches[2] local channel_to_rename = 'channel#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) rename_channel(channel_to_rename, group_name_set, ok_cb, false) savelog(matches[3], "Group { "..group_name_set.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end --[[if matches[1] == 'set' then if matches[2] == 'loggroup' and is_sudo(msg) then local target = msg.to.peer_id savelog(msg.to.peer_id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(target, data) end end if matches[1] == 'rem' then if matches[2] == 'loggroup' and is_sudo(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return unset_log_group(target, data) end end]] if matches[1] == 'kill' and matches[2] == 'chat' and matches[3] then if not is_admin1(msg) then return end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' and matches[3] then if not is_admin1(msg) then return end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'rem' and matches[2] then -- Group configuration removal data[tostring(matches[2])] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(matches[2])] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, 'Chat '..matches[2]..' removed') end if matches[1] == 'chat_add_user' then if not msg.service then return end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin1(msg) and is_realm(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if not is_sudo(msg) then-- Sudo only return end if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if not is_sudo(msg) then-- Sudo only return end if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'support' and matches[2] then if string.match(matches[2], '^%d+$') then local support_id = matches[2] print("User "..support_id.." has been added to the support team") support_add(support_id) return "User ["..support_id.."] has been added to the support team" else local member = string.gsub(matches[2], "@", "") local receiver = get_receiver(msg) local get_cmd = "addsupport" resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver}) end end if matches[1] == '-support' then if string.match(matches[2], '^%d+$') then local support_id = matches[2] print("User "..support_id.." has been removed from the support team") support_remove(support_id) return "User ["..support_id.."] has been removed from the support team" else local member = string.gsub(matches[2], "@", "") local receiver = get_receiver(msg) local get_cmd = "removesupport" resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' then if matches[2] == 'admins' then return admin_list(msg) end -- if matches[2] == 'support' and not matches[2] then -- return support_list() -- end end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' or msg.to.type == 'channel' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) send_document("channel#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' or msg.to.type == 'channel' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) send_document("channel#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return resolve_username(username, callbackres, cbres_extra) end end return { patterns = { "^[#!/](creategroup) (.*)$", "^[#!/](createsuper) (.*)$", "^[#!/](createrealm) (.*)$", "^[#!/](setabout) (%d+) (.*)$", "^[#!/](setrules) (%d+) (.*)$", "^[#!/](setname) (.*)$", "^[#!/](setgpname) (%d+) (.*)$", "^[#!/](setname) (%d+) (.*)$", "^[#!/](lock) (%d+) (.*)$", "^[#!/](unlock) (%d+) (.*)$", "^[#!/](mute) (%d+)$", "^[#!/](unmute) (%d+)$", "^[#!/](settings) (.*) (%d+)$", "^[#!/](wholist)$", "^[#!/](who)$", "^[#!/]([Ww]hois) (.*)", "^[#!/](type)$", "^[#!/](kill) (chat) (%d+)$", "^[#!/](kill) (realm) (%d+)$", "^[#!/](rem) (%d+)$", "^[#!/](addadmin) (.*)$", -- sudoers only "^[#!/](removeadmin) (.*)$", -- sudoers only "[#!/ ](support)$", "^[#!/](support) (.*)$", "^[#!/](-support) (.*)$", "^[#!/](list) (.*)$", "^[#!/](log)$", "^[#!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
tmeinlschmidt/domoticz
scripts/lua/script_device_demo.lua
54
1870
-- demo device script -- script names have three name components: script_trigger_name.lua -- trigger can be 'time' or 'device', name can be any string -- domoticz will execute all time and device triggers when the relevant trigger occurs -- -- copy this script and change the "name" part, all scripts named "demo" are ignored. -- -- Make sure the encoding is UTF8 of the file -- -- ingests tables: devicechanged, otherdevices,otherdevices_svalues -- -- device changed contains state and svalues for the device that changed. -- devicechanged['yourdevicename']=state -- devicechanged['svalues']=svalues string -- -- otherdevices and otherdevices_svalues are arrays for all devices: -- otherdevices['yourotherdevicename']="On" -- otherdevices_svalues['yourotherthermometer'] = string of svalues -- -- Based on your logic, fill the commandArray with device commands. Device name is case sensitive. -- -- Always, and I repeat ALWAYS start by checking for the state of the changed device. -- If you would only specify commandArray['AnotherDevice']='On', every device trigger will switch AnotherDevice on, which will trigger a device event, which will switch AnotherDevice on, etc. -- -- The print command will output lua print statements to the domoticz log for debugging. -- List all otherdevices states for debugging: -- for i, v in pairs(otherdevices) do print(i, v) end -- List all otherdevices svalues for debugging: -- for i, v in pairs(otherdevices_svalues) do print(i, v) end -- -- TBD: nice time example, for instance get temp from svalue string, if time is past 22.00 and before 00:00 and temp is bloody hot turn on fan. print('this will end up in the domoticz log') commandArray = {} if (devicechanged['MyDeviceName'] == 'On' and otherdevices['MyOtherDeviceName'] == 'Off') then commandArray['MyOtherDeviceName']='On' end return commandArray
gpl-3.0
Lsty/ygopro-scripts
c80908502.lua
3
1450
--E・HERO キャプテン・ゴールド function c80908502.initial_effect(c) --search local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(80908502,0)) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_HAND) e1:SetCost(c80908502.cost) e1:SetTarget(c80908502.target) e1:SetOperation(c80908502.operation) c:RegisterEffect(e1) --self destroy local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetRange(LOCATION_MZONE) e2:SetCode(EFFECT_SELF_DESTROY) e2:SetCondition(c80908502.descon) c:RegisterEffect(e2) end function c80908502.cost(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsAbleToGraveAsCost() and c:IsDiscardable() end Duel.SendtoGrave(c,REASON_COST+REASON_DISCARD) end function c80908502.filter(c) return c:GetCode()==63035430 and c:IsAbleToHand() end function c80908502.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chk==0 then return Duel.IsExistingMatchingCard(c80908502.filter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c80908502.operation(e,tp,eg,ep,ev,re,r,rp,chk) local tg=Duel.GetFirstMatchingCard(c80908502.filter,tp,LOCATION_DECK,0,nil) if tg then Duel.SendtoHand(tg,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,tg) end end function c80908502.descon(e) return not Duel.IsEnvironment(63035430) end
gpl-2.0
dani-sj/kirbot
bot/utils.lua
494
23873
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) if user_info and user_info.print_name then text = text..k.." - "..string.gsub(user_info.print_name, "_", " ").." ["..v.."]\n" else text = text..k.." - "..v.."\n" end end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) if user_info and user_info.print_name then text = text..k.." - "..string.gsub(user_info.print_name, "_", " ").." ["..v.."]\n" else text = text..k.." - "..v.."\n" end end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
nmabhi/Webface
training/dataset-issue-132.lua
8
14611
-- Source: https://github.com/soumith/imagenet-multiGPU.torch/blob/master/dataset.lua -- Modified by Brandon Amos in Sept 2015 for OpenFace by adding -- `samplePeople` and `sampleTriplet`. require 'torch' torch.setdefaulttensortype('torch.FloatTensor') local ffi = require 'ffi' local argcheck = require 'argcheck' require 'sys' require 'xlua' require 'image' tds = require 'tds' local dataset = torch.class('dataLoader') local initcheck = argcheck{ pack=true, help=[[ A dataset class for images in a flat folder structure (folder-name is class-name). Optimized for extremely large datasets (upwards of 14 million images). Tested only on Linux (as it uses command-line linux utilities to scale up) ]], {check=function(paths) local out = true; for _,v in ipairs(paths) do if type(v) ~= 'string' then print('paths can only be of string input'); out = false end end return out end, name="paths", type="table", help="Multiple paths of directories with images"}, {name="sampleSize", type="table", help="a consistent sample size to resize the images"}, {name="split", type="number", help="Percentage of split to go to Training" }, {name="samplingMode", type="string", help="Sampling mode: random | balanced ", default = "balanced"}, {name="verbose", type="boolean", help="Verbose mode during initialization", default = false}, {name="loadSize", type="table", help="a size to load the images to, initially", opt = true}, {name="forceClasses", type="table", help="If you want this loader to map certain classes to certain indices, " .. "pass a classes table that has {classname : classindex} pairs." .. " For example: {3 : 'dog', 5 : 'cat'}" .. "This function is very useful when you want two loaders to have the same " .. "class indices (trainLoader/testLoader for example)", opt = true}, {name="sampleHookTrain", type="function", help="applied to sample during training(ex: for lighting jitter). " .. "It takes the image path as input", opt = true}, {name="sampleHookTest", type="function", help="applied to sample during testing", opt = true}, } function dataset:__init(...) -- argcheck local args = initcheck(...) print(args) for k,v in pairs(args) do self[k] = v end if not self.loadSize then self.loadSize = self.sampleSize; end if not self.sampleHookTrain then self.sampleHookTrain = self.defaultSampleHook end if not self.sampleHookTest then self.sampleHookTest = self.defaultSampleHook end -- find class names print('finding class names') self.classes = {} local classPaths = tds.Hash() if self.forceClasses then print('Adding forceClasses class names') for k,v in pairs(self.forceClasses) do self.classes[k] = v classPaths[k] = tds.Hash() end end -- loop over each paths folder, get list of unique class names, -- also store the directory paths per class -- for each class, print('Adding all path folders') for _,path in ipairs(self.paths) do for dirpath in paths.iterdirs(path) do dirpath = path .. '/' .. dirpath local class = paths.basename(dirpath) self.classes[#self.classes + 1] = class classPaths[#classPaths + 1] = dirpath end end print(#self.classes .. ' class names found') self.classIndices = {} for k,v in ipairs(self.classes) do self.classIndices[v] = k end -- find the image path names print('Finding path for each image') self.imagePath = torch.CharTensor() -- path to each image in dataset self.imageClass = torch.LongTensor() -- class index of each image (class index in self.classes) self.classList = {} -- index of imageList to each image of a particular class self.classListSample = self.classList -- the main list used when sampling data local counts = tds.Hash() local maxPathLength = 0 print('Calculating maximum class name length and counting files') local length = 0 local fullPaths = tds.Hash() -- iterate over classPaths for _,path in pairs(classPaths) do local count = 0 -- iterate over files in the class path for f in paths.iterfiles(path) do local fullPath = path .. '/' .. f maxPathLength = math.max(fullPath:len(), maxPathLength) count = count + 1 length = length + 1 fullPaths[#fullPaths + 1] = fullPath end counts[path] = count end assert(length > 0, "Could not find any image file in the given input paths") assert(maxPathLength > 0, "paths of files are length 0?") maxPathLength = maxPathLength + 1 self.imagePath:resize(length, maxPathLength):fill(0) local s_data = self.imagePath:data() local count = 0 for _,line in pairs(fullPaths) do ffi.copy(s_data, line) s_data = s_data + maxPathLength if self.verbose and count % 10000 == 0 then xlua.progress(count, length) end; count = count + 1 end self.numSamples = self.imagePath:size(1) if self.verbose then print(self.numSamples .. ' samples found.') end --========================================================================== print('Updating classList and imageClass appropriately') self.imageClass:resize(self.numSamples) local runningIndex = 0 for i=1,#self.classes do if self.verbose then xlua.progress(i, #(self.classes)) end local clsLength = counts[classPaths[i]] if clsLength == 0 then error('Class has zero samples: ' .. self.classes[i]) else self.classList[i] = torch.linspace(runningIndex + 1, runningIndex + clsLength, clsLength):long() self.imageClass[{{runningIndex + 1, runningIndex + clsLength}}]:fill(i) end runningIndex = runningIndex + clsLength end --========================================================================== if self.split == 100 then self.testIndicesSize = 0 else print('Splitting training and test sets to a ratio of ' .. self.split .. '/' .. (100-self.split)) self.classListTrain = {} self.classListTest = {} self.classListSample = self.classListTrain local totalTestSamples = 0 -- split the classList into classListTrain and classListTest for i=1,#self.classes do local list = self.classList[i] count = self.classList[i]:size(1) local splitidx = math.floor((count * self.split / 100) + 0.5) -- +round local perm = torch.randperm(count) self.classListTrain[i] = torch.LongTensor(splitidx) for j=1,splitidx do self.classListTrain[i][j] = list[perm[j]] end if splitidx == count then -- all samples were allocated to train set self.classListTest[i] = torch.LongTensor() else self.classListTest[i] = torch.LongTensor(count-splitidx) totalTestSamples = totalTestSamples + self.classListTest[i]:size(1) local idx = 1 for j=splitidx+1,count do self.classListTest[i][idx] = list[perm[j]] idx = idx + 1 end end end -- Now combine classListTest into a single tensor self.testIndices = torch.LongTensor(totalTestSamples) self.testIndicesSize = totalTestSamples local tdata = self.testIndices:data() local tidx = 0 for i=1,#self.classes do local list = self.classListTest[i] if list:dim() ~= 0 then local ldata = list:data() for j=0,list:size(1)-1 do tdata[tidx] = ldata[j] tidx = tidx + 1 end end end end end -- size(), size(class) function dataset:size(class, list) list = list or self.classList if not class then return self.numSamples elseif type(class) == 'string' then return list[self.classIndices[class]]:size(1) elseif type(class) == 'number' then return list[class]:size(1) end end -- size(), size(class) function dataset:sizeTrain(class) if self.split == 0 then return 0; end if class then return self:size(class, self.classListTrain) else return self.numSamples - self.testIndicesSize end end -- size(), size(class) function dataset:sizeTest(class) if self.split == 100 then return 0 end if class then return self:size(class, self.classListTest) else return self.testIndicesSize end end -- by default, just load the image and return it function dataset:defaultSampleHook(imgpath) local out = image.load(imgpath, 3, 'float') out = image.scale(out, self.sampleSize[3], self.sampleSize[2]) return out end -- getByClass function dataset:getByClass(class) local index = math.ceil(torch.uniform() * self.classListSample[class]:nElement()) local imgpath = ffi.string(torch.data(self.imagePath[self.classListSample[class][index]])) return self:sampleHookTrain(imgpath) end -- converts a table of samples (and corresponding labels) to a clean tensor local function tableToOutput(self, dataTable, scalarTable) local data, scalarLabels, labels local quantity = #scalarTable local samplesPerDraw if dataTable[1]:dim() == 3 then samplesPerDraw = 1 else samplesPerDraw = dataTable[1]:size(1) end if quantity == 1 and samplesPerDraw == 1 then data = dataTable[1] scalarLabels = scalarTable[1] labels = torch.LongTensor(#(self.classes)):fill(-1) labels[scalarLabels] = 1 else data = torch.Tensor(quantity * samplesPerDraw, self.sampleSize[1], self.sampleSize[2], self.sampleSize[3]) scalarLabels = torch.LongTensor(quantity * samplesPerDraw) labels = torch.LongTensor(quantity * samplesPerDraw, #(self.classes)):fill(-1) for i=1,#dataTable do local idx = (i-1)*samplesPerDraw data[{{idx+1,idx+samplesPerDraw}}]:copy(dataTable[i]) scalarLabels[{{idx+1,idx+samplesPerDraw}}]:fill(scalarTable[i]) labels[{{idx+1,idx+samplesPerDraw},{scalarTable[i]}}]:fill(1) end end return data, scalarLabels, labels end -- sampler, samples from the training set. function dataset:sample(quantity) if self.split == 0 then error('No training mode when split is set to 0') end quantity = quantity or 1 local dataTable = tds.Hash() local scalarTable = tds.Hash() for _=1,quantity do local class = torch.random(1, #self.classes) local out = self:getByClass(class) dataTable[#dataTable + 1] = out scalarTable[#scalarTable + 1] = class end local data, scalarLabels, labels = tableToOutput(self, dataTable, scalarTable) return data, scalarLabels, labels end -- Naively sample random triplets. function dataset:sampleTriplet(quantity) if self.split == 0 then error('No training mode when split is set to 0') end quantity = quantity or 1 local dataTable = {} local scalarTable = {} -- Anchors for _=1,quantity do local anchorClass = torch.random(1, #self.classes) table.insert(dataTable, self:getByClass(anchorClass)) table.insert(scalarTable, anchorClass) end -- Positives for i=1,quantity do local posClass = scalarTable[i] table.insert(dataTable, self:getByClass(posClass)) table.insert(scalarTable, posClass) end -- Negatives for i=1,quantity do local posClass = scalarTable[i] local negClass = posClass while negClass == posClass do negClass = torch.random(1, #self.classes) end table.insert(dataTable, self:getByClass(negClass)) table.insert(scalarTable, negClass) end local data, scalarLabels, labels = tableToOutput(self, dataTable, scalarTable) return data, scalarLabels, labels end function dataset:samplePeople(peoplePerBatch, imagesPerPerson) if self.split == 0 then error('No training mode when split is set to 0') end local classes = torch.randperm(#trainLoader.classes)[{{1,peoplePerBatch}}]:int() local numPerClass = torch.Tensor(peoplePerBatch) for i=1,peoplePerBatch do local n = math.min(self.classListSample[classes[i]]:nElement(), imagesPerPerson) numPerClass[i] = n end local data = torch.Tensor(numPerClass:sum(), self.sampleSize[1], self.sampleSize[2], self.sampleSize[3]) local dataIdx = 1 for i=1,peoplePerBatch do local cls = classes[i] local n = numPerClass[i] local shuffle = torch.randperm(n) for j=1,n do imgNum = self.classListSample[cls][shuffle[j]] imgPath = ffi.string(torch.data(self.imagePath[imgNum])) data[dataIdx] = self:sampleHookTrain(imgPath) dataIdx = dataIdx + 1 end end assert(dataIdx - 1 == numPerClass:sum()) return data, numPerClass end function dataset:get(i1, i2) local indices, quantity if type(i1) == 'number' then if type(i2) == 'number' then -- range of indices indices = torch.range(i1, i2); quantity = i2 - i1 + 1; else -- single index indices = {i1}; quantity = 1 end elseif type(i1) == 'table' then indices = i1; quantity = #i1; -- table elseif (type(i1) == 'userdata' and i1:nDimension() == 1) then indices = i1; quantity = (#i1)[1]; -- tensor else error('Unsupported input types: ' .. type(i1) .. ' ' .. type(i2)) end assert(quantity > 0) -- now that indices has been initialized, get the samples local dataTable = {} local scalarTable = {} for i=1,quantity do -- load the sample local idx = self.testIndices[indices[i]] local imgpath = ffi.string(torch.data(self.imagePath[idx])) local out = self:sampleHookTest(imgpath) table.insert(dataTable, out) table.insert(scalarTable, self.imageClass[idx]) end local data, scalarLabels, labels = tableToOutput(self, dataTable, scalarTable) return data, scalarLabels, labels end function dataset:test(quantity) if self.split == 100 then error('No test mode when you are not splitting the data') end local i = 1 local n = self.testIndicesSize local qty = quantity or 1 return function () if i+qty-1 <= n then local data, scalarLabelss, labels = self:get(i, i+qty-1) i = i + qty return data, scalarLabelss, labels end end end return dataset
apache-2.0
robertbrook/Penlight
tests/test-tablex.lua
8
4509
local tablex = require 'pl.tablex' local utils = require ('pl.utils') local L = utils.string_lambda local test = require('pl.test') -- bring tablex funtions into global namespace utils.import(tablex) local asserteq = test.asserteq local cmp = deepcompare function asserteq_no_order (x,y) if not compare_no_order(x,y) then test.complain(x,y,"these lists contained different elements") end end asserteq( copy {10,20,30}, {10,20,30} ) asserteq( deepcopy {10,20,{30,40}}, {10,20,{30,40}} ) asserteq( pairmap(function(i,v) return v end,{10,20,30}), {10,20,30} ) asserteq_no_order( pairmap(L'_',{fred=10,bonzo=20}), {'fred','bonzo'} ) asserteq_no_order( pairmap(function(k,v) return v end,{fred=10,bonzo=20}), {10,20} ) asserteq_no_order( pairmap(function(i,v) return v,i end,{10,20,30}), {10,20,30} ) asserteq( pairmap(function(k,v) return {k,v},k end,{one=1,two=2}), {one={'one',1},two={'two',2}} ) -- same as above, using string lambdas asserteq( pairmap(L'|k,v|{k,v},k',{one=1,two=2}), {one={'one',1},two={'two',2}} ) asserteq( map(function(v) return v*v end,{10,20,30}), {100,400,900} ) -- extra arguments to map() are passed to the function; can use -- the abbreviations provided by pl.operator asserteq( map('+',{10,20,30},1), {11,21,31} ) asserteq( map(L'_+1',{10,20,30}), {11,21,31} ) -- map2 generalizes for operations on two tables asserteq( map2(math.max,{1,2,3},{0,4,2}), {1,4,3} ) -- mapn operates over an arbitrary number of input tables (but use map2 for n=2) asserteq( mapn(function(x,y,z) return x+y+z end, {1,2,3},{10,20,30},{100,200,300}), {111,222,333} ) asserteq( mapn(math.max, {1,20,300},{10,2,3},{100,200,100}), {100,200,300} ) asserteq( zip({10,20,30},{100,200,300}), {{10,100},{20,200},{30,300}} ) assert(compare_no_order({1,2,3,4},{2,1,4,3})==true) assert(compare_no_order({1,2,3,4},{2,1,4,4})==false) asserteq(range(10,9),{}) asserteq(range(10,10),{10}) asserteq(range(10,11),{10,11}) -- update inserts key-value pairs from the second table t1 = {one=1,two=2} t2 = {three=3,two=20,four=4} asserteq(update(t1,t2),{one=1,three=3,two=20,four=4}) -- the difference between move and icopy is that the second removes -- any extra elements in the destination after end of copy -- 3rd arg is the index to start in the destination, defaults to 1 asserteq(move({1,2,3,4,5,6},{20,30}),{20,30,3,4,5,6}) asserteq(move({1,2,3,4,5,6},{20,30},2),{1,20,30,4,5,6}) asserteq(icopy({1,2,3,4,5,6},{20,30},2),{1,20,30}) -- 5th arg determines how many elements to copy (default size of source) asserteq(icopy({1,2,3,4,5,6},{20,30},2,1,1),{1,20}) -- 4th arg is where to stop copying from the source (default s to 1) asserteq(icopy({1,2,3,4,5,6},{20,30},2,2,1),{1,30}) -- whereas insertvalues works like table.insert, but inserts a range of values -- from the given table. asserteq(insertvalues({1,2,3,4,5,6},2,{20,30}),{1,20,30,2,3,4,5,6}) asserteq(insertvalues({1,2},{3,4}),{1,2,3,4}) -- the 4th arg of move and icopy gives the start index in the source table asserteq(move({1,2,3,4,5,6},{20,30},2,2),{1,30,3,4,5,6}) asserteq(icopy({1,2,3,4,5,6},{20,30},2,2),{1,30}) t = {1,2,3,4,5,6} move(t,{20,30},2,1,1) asserteq(t,{1,20,3,4,5,6}) set(t,0,2,3) asserteq(t,{1,0,0,4,5,6}) insertvalues(t,1,{10,20}) asserteq(t,{10,20,1,0,0,4,5,6}) asserteq(merge({10,20,30},{nil, nil, 30, 40}), {[3]=30}) asserteq(merge({10,20,30},{nil, nil, 30, 40}, true), {10,20,30,40}) -- Function to check that the order of elements returned by the iterator -- match the order of the elements in the list. function assert_iter_order(iter,l) local i = 0 for k,v in iter do i = i + 1 asserteq(k,l[i][1]) asserteq(v,l[i][2]) end end local t = {a=10,b=9,c=8,d=7,e=6,f=5,g=4,h=3,i=2,j=1} assert_iter_order( sort(t), {{'a',10},{'b',9},{'c',8},{'d',7},{'e',6},{'f',5},{'g',4},{'h',3},{'i',2},{'j',1}}) assert_iter_order( sortv(t), {{'j',1},{'i',2},{'h',3},{'g',4},{'f',5},{'e',6},{'d',7},{'c',8},{'b',9},{'a',10}}) asserteq(difference({a = true, b = true},{a = true, b = true}),{}) -- no longer confused by false values ;) asserteq(difference({v = false},{v = false}),{}) asserteq(difference({a = true},{b = true}),{a=true}) -- symmetric difference asserteq(difference({a = true},{b = true},true),{a=true,b=true})
mit
MalRD/darkstar
scripts/zones/Korroloka_Tunnel/npcs/qm2.lua
9
2206
----------------------------------- -- Area: Korroloka Tunnel -- NPC: ??? (qm2) -- Involved In Quest: Ayame and Kaede -- !pos -208 -9 176 173 ----------------------------------- local ID = require("scripts/zones/Korroloka_Tunnel/IDs") require("scripts/globals/keyitems") require("scripts/globals/settings") require("scripts/globals/quests") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) if player:getQuestStatus(BASTOK, dsp.quest.id.bastok.AYAME_AND_KAEDE) == QUEST_ACCEPTED then if player:getCharVar("AyameAndKaede_Event") == 2 and not player:hasKeyItem(dsp.ki.STRANGELY_SHAPED_CORAL) then if not GetMobByID(ID.mob.KORROLOKA_LEECH_I):isSpawned() and not GetMobByID(ID.mob.KORROLOKA_LEECH_II):isSpawned() and not GetMobByID(ID.mob.KORROLOKA_LEECH_III):isSpawned() then if player:getCharVar("KorrolokaLeeches_Killed") > 0 then player:addKeyItem(dsp.ki.STRANGELY_SHAPED_CORAL) player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.STRANGELY_SHAPED_CORAL) player:setCharVar("KorrolokaLeeches_Killed", 0) if player:getCharVar("KorrolokaLeeches_SpawningPC") > 0 then player:setCharVar("KorrolokaLeeches_SpawningPC", 0) npc:hideNPC(FORCE_SPAWN_QM_RESET_TIME) end else player:messageSpecial(ID.text.SENSE_OF_BOREBODING) SpawnMob(ID.mob.KORROLOKA_LEECH_I) SpawnMob(ID.mob.KORROLOKA_LEECH_II) SpawnMob(ID.mob.KORROLOKA_LEECH_III) player:setCharVar("KorrolokaLeeches_SpawningPC", 1) end else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY) end else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY) end else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
gpl-3.0
marktsai0316/nodemcu-firmware
lua_examples/webap_toggle_pin.lua
70
1202
wifi.setmode(wifi.SOFTAP); wifi.ap.config({ssid="test",pwd="12345678"}); gpio.mode(1, gpio.OUTPUT) srv=net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive", function(client,request) local buf = ""; local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP"); if(method == nil)then _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP"); end local _GET = {} if (vars ~= nil)then for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do _GET[k] = v end end buf = buf.."<h1> Hello, NodeMcu.</h1><form src=\"/\">Turn PIN1 <select name=\"pin\" onchange=\"form.submit()\">"; local _on,_off = "","" if(_GET.pin == "ON")then _on = " selected=true"; gpio.write(1, gpio.HIGH); elseif(_GET.pin == "OFF")then _off = " selected=\"true\""; gpio.write(1, gpio.LOW); end buf = buf.."<option".._on..">ON</opton><option".._off..">OFF</option></select></form>"; client:send(buf); client:close(); collectgarbage(); end) end)
mit
MalRD/darkstar
scripts/globals/items/plate_of_mushroom_risotto.lua
11
1235
----------------------------------------- -- ID: 4434 -- Item: Plate of Mushroom Risotto -- Food Effect: 3 Hr, All Races ----------------------------------------- -- MP 30 -- Strength -1 -- Vitality 3 -- Mind 3 -- MP Recovered while healing 2 -- Enmity -4 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,10800,4434) end function onEffectGain(target, effect) target:addMod(dsp.mod.MP, 30) target:addMod(dsp.mod.STR, -1) target:addMod(dsp.mod.VIT, 3) target:addMod(dsp.mod.MND, 3) target:addMod(dsp.mod.MPHEAL, 2) target:addMod(dsp.mod.ENMITY, -4) end function onEffectLose(target, effect) target:delMod(dsp.mod.MP, 30) target:delMod(dsp.mod.STR, -1) target:delMod(dsp.mod.VIT, 3) target:delMod(dsp.mod.MND, 3) target:delMod(dsp.mod.MPHEAL, 2) target:delMod(dsp.mod.ENMITY, -4) end
gpl-3.0
Lsty/ygopro-scripts
c87910978.lua
3
1342
--洗脳-ブレインコントロール function c87910978.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_CONTROL) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(c87910978.cost) e1:SetTarget(c87910978.target) e1:SetOperation(c87910978.activate) c:RegisterEffect(e1) end function c87910978.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckLPCost(tp,800) else Duel.PayLPCost(tp,800) end end function c87910978.filter(c) return c:IsControlerCanBeChanged() and c:IsFaceup() end function c87910978.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c87910978.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c87910978.filter,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONTROL) local g=Duel.SelectTarget(tp,c87910978.filter,tp,0,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_CONTROL,g,1,0,0) end function c87910978.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsFaceup() and not Duel.GetControl(tc,tp,PHASE_END,1) then if not tc:IsImmuneToEffect(e) and tc:IsAbleToChangeControler() then Duel.Destroy(tc,REASON_EFFECT) end end end
gpl-2.0
Lsty/ygopro-scripts
c50400231.lua
5
1354
--サテライト・キャノン function c50400231.initial_effect(c) --ind local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e1:SetValue(c50400231.indval) c:RegisterEffect(e1) --atkup local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(50400231,0)) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetRange(LOCATION_MZONE) e2:SetCode(EVENT_PHASE+PHASE_END) e2:SetCountLimit(1) e2:SetCondition(c50400231.atkcon) e2:SetOperation(c50400231.atkop) c:RegisterEffect(e2) --atk clear local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e3:SetCode(EVENT_BATTLED) e3:SetOperation(c50400231.retop) c:RegisterEffect(e3) end function c50400231.indval(e,c) return c:IsLevelBelow(7) end function c50400231.atkcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c50400231.atkop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(1000) e1:SetReset(RESET_EVENT+0x1ff0000) c:RegisterEffect(e1) end end function c50400231.retop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c==Duel.GetAttacker() then c:ResetEffect(RESET_DISABLE,RESET_EVENT) end end
gpl-2.0
Lsty/ygopro-scripts
c91501248.lua
3
2810
--禁忌の壺 function c91501248.initial_effect(c) --flip local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_FLIP+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetCountLimit(1,91501248) e1:SetTarget(c91501248.target) e1:SetOperation(c91501248.operation) c:RegisterEffect(e1) end function c91501248.thfilter(c) return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsAbleToHand() end function c91501248.target(e,tp,eg,ep,ev,re,r,rp,chk) local b1=Duel.IsPlayerCanDraw(tp,2) local b2=Duel.IsExistingMatchingCard(c91501248.thfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) local b3=Duel.IsExistingMatchingCard(Card.IsDestructable,tp,0,LOCATION_MZONE,1,nil) local b4=Duel.IsExistingMatchingCard(Card.IsAbleToDeck,tp,0,LOCATION_HAND,1,nil) if chk==0 then return b1 or b2 or b3 or b4 end local off=1 local ops={} local opval={} if b1 then ops[off]=aux.Stringid(91501248,0) opval[off-1]=1 off=off+1 end if b2 then ops[off]=aux.Stringid(91501248,1) opval[off-1]=2 off=off+1 end if b3 then ops[off]=aux.Stringid(91501248,2) opval[off-1]=3 off=off+1 end if b4 then ops[off]=aux.Stringid(91501248,3) opval[off-1]=4 off=off+1 end local op=Duel.SelectOption(tp,table.unpack(ops)) local sel=opval[op] e:SetLabel(sel) if sel==1 then e:SetCategory(CATEGORY_DRAW) Duel.SetTargetPlayer(tp) Duel.SetTargetParam(2) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,2) elseif sel==2 then e:SetCategory(CATEGORY_TOHAND) local g=Duel.GetMatchingGroup(c91501248.thfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil) Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,g:GetCount(),0,0) elseif sel==3 then e:SetCategory(CATEGORY_DESTROY) local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,0,LOCATION_MZONE,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) else e:SetCategory(CATEGORY_TODECK) Duel.SetTargetPlayer(tp) Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,0,1-tp,LOCATION_HAND) end end function c91501248.operation(e,tp,eg,ep,ev,re,r,rp) local sel=e:GetLabel() if sel==1 then local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Draw(p,d,REASON_EFFECT) elseif sel==2 then local g=Duel.GetMatchingGroup(c91501248.thfilter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil) Duel.SendtoHand(g,nil,REASON_EFFECT) elseif sel==3 then local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,0,LOCATION_MZONE,nil) Duel.Destroy(g,REASON_EFFECT) else local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER) local g=Duel.GetFieldGroup(p,0,LOCATION_HAND) if g:GetCount()>0 then Duel.ConfirmCards(p,g) Duel.Hint(HINT_SELECTMSG,p,HINTMSG_TODECK) local sg=g:FilterSelect(p,Card.IsAbleToDeck,1,1,nil) Duel.SendtoDeck(sg,nil,2,REASON_EFFECT) Duel.ShuffleHand(1-p) end end end
gpl-2.0
Lsty/ygopro-scripts
c19808608.lua
3
1713
--DDバフォメット function c19808608.initial_effect(c) --lv change local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetCountLimit(1) e1:SetRange(LOCATION_MZONE) e1:SetTarget(c19808608.lvtg) e1:SetOperation(c19808608.lvop) c:RegisterEffect(e1) end function c19808608.filter(c) return c:IsFaceup() and c:IsSetCard(0xaf) and not c:IsCode(19808608) and c:GetLevel()>0 end function c19808608.lvtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c19808608.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c19808608.filter,tp,LOCATION_MZONE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) local g=Duel.SelectTarget(tp,c19808608.filter,tp,LOCATION_MZONE,0,1,1,nil) local t={} local i=1 local p=1 local lv=g:GetFirst():GetLevel() for i=1,8 do if lv~=i then t[p]=i p=p+1 end end t[p]=nil Duel.Hint(HINT_SELECTMSG,tp,567) e:SetLabel(Duel.AnnounceNumber(tp,table.unpack(t))) end function c19808608.lvop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CHANGE_LEVEL) e1:SetValue(e:GetLabel()) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1) end local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e2:SetTargetRange(1,0) e2:SetTarget(c19808608.splimit) e2:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e2,tp) end function c19808608.splimit(e,c) return not c:IsSetCard(0xaf) end
gpl-2.0
Lsty/ygopro-scripts
c10383554.lua
3
2121
--デストーイ・ホイールソウ・ライオ function c10383554.initial_effect(c) --fusion material c:EnableReviveLimit() aux.AddFusionProcCodeFun(c,34688023,aux.FilterBoolFunction(Card.IsSetCard,0xa9),1,true,false) --spsummon condition local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetValue(aux.fuslimit) c:RegisterEffect(e1) --destroy local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_DESTROY+CATEGORY_DAMAGE) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCountLimit(1,10383554) e2:SetRange(LOCATION_MZONE) e2:SetCost(c10383554.cost) e2:SetTarget(c10383554.target) e2:SetOperation(c10383554.operation) c:RegisterEffect(e2) end function c10383554.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return not e:GetHandler():IsDirectAttacked() end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_OATH) e1:SetCode(EFFECT_CANNOT_DIRECT_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END) e:GetHandler():RegisterEffect(e1) end function c10383554.filter(c) return c:IsFaceup() and c:IsDestructable() end function c10383554.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c10383554.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c10383554.filter,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,c10383554.filter,tp,0,LOCATION_MZONE,1,1,nil) local atk=g:GetFirst():GetTextAttack() if atk<0 then atk=0 end Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,atk) end function c10383554.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then local atk=tc:GetTextAttack() if atk<0 then atk=0 end if Duel.Destroy(tc,REASON_EFFECT)~=0 then Duel.Damage(1-tp,atk,REASON_EFFECT) end end end
gpl-2.0
jmattsson/nodemcu-firmware
lua_examples/pcm/play_network.lua
11
3038
-- **************************************************************************** -- Network streaming example -- -- stream = require("play_network") -- stream.init(pin) -- stream.play(pcm.RATE_8K, ip, port, "/jump_8k.u8", function () print("stream finished") end) -- -- Playback can be stopped with stream.stop(). -- And resources are free'd with stream.close(). -- local M, module = {}, ... _G[module] = M local _conn local _drv local _buf local _lower_thresh = 2 local _upper_thresh = 5 local _play_cb -- **************************************************************************** -- PCM local function stop_stream(cb) _drv:stop() if _conn then _conn:close() _conn = nil end _buf = nil if cb then cb() elseif _play_cb then _play_cb() end _play_cb = nil end local function cb_drained() print("drained "..node.heap()) stop_stream() end local function cb_data() if #_buf > 0 then local data = table.remove(_buf, 1) if #_buf <= _lower_thresh then -- unthrottle server to get further data into the buffer _conn:unhold() end return data end end local _rate local function start_play() print("starting playback") -- start playback _drv:play(_rate) end -- **************************************************************************** -- Networking functions -- local _skip_headers local _chunk local _buffering local function data_received(c, data) if _skip_headers then -- simple logic to filter the HTTP headers _chunk = _chunk..data local i, j = string.find(_chunk, '\r\n\r\n') if i then _skip_headers = false data = string.sub(_chunk, j+1, -1) _chunk = nil end end if not _skip_headers then _buf[#_buf+1] = data if #_buf > _upper_thresh then -- throttle server to avoid buffer overrun c:hold() if _buffering then -- buffer got filled, start playback start_play() _buffering = false end end end end local function cb_disconnected() if _buffering then -- trigger playback when disconnected but we're still buffering start_play() _buffering = false end end local _path local function cb_connected(c) c:send("GET ".._path.." HTTP/1.0\r\nHost: iot.nix.nix\r\n".."Connection: close\r\nAccept: /\r\n\r\n") _path = nil end function M.play(rate, ip, port, path, cb) _skip_headers = true _chunk = "" _buffering = true _buf = {} _rate = rate _path = path _play_cb = cb _conn = net.createConnection(net.TCP, 0) _conn:on("receive", data_received) _conn:on("disconnection", cb_disconnected) _conn:connect(port, ip, cb_connected) end function M.stop(cb) stop_stream(cb) end function M.init(pin) _drv = pcm.new(pcm.SD, pin) -- get called back when all samples were read from stream _drv:on("drained", cb_drained) _drv:on("data", cb_data) --_drv:on("stopped", cb_stopped) end function M.vu(cb, freq) _drv:on("vu", cb, freq) end function M.close() stop_stream() _drv:close() _drv = nil end return M
mit
Lsty/ygopro-scripts
c31385077.lua
5
2210
--カオス・ゴッデス-混沌の女神- function c31385077.initial_effect(c) --synchro summon aux.AddSynchroProcedure(c,aux.FilterBoolFunction(Card.IsAttribute,ATTRIBUTE_LIGHT),aux.NonTuner(Card.IsAttribute,ATTRIBUTE_DARK),2) c:EnableReviveLimit() --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(31385077,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetCountLimit(1) e1:SetRange(LOCATION_MZONE) e1:SetCost(c31385077.spcost) e1:SetTarget(c31385077.sptg) e1:SetOperation(c31385077.spop) c:RegisterEffect(e1) end function c31385077.costfilter(c) return c:IsType(TYPE_MONSTER) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsAbleToGraveAsCost() end function c31385077.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c31385077.costfilter,tp,LOCATION_HAND,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c31385077.costfilter,tp,LOCATION_HAND,0,1,1,nil) Duel.SendtoGrave(g,REASON_COST) end function c31385077.filter(c,e,tp) return c:IsLevelAbove(5) and c:IsAttribute(ATTRIBUTE_DARK) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c31385077.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:GetLocation()==LOCATION_GRAVE and chkc:IsControler(tp) and c31385077.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c31385077.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c31385077.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c31385077.spop(e,tp,eg,ep,ev,re,r,rp,chk) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)~=0 then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL) e1:SetReset(RESET_EVENT+0x1fe0000) e1:SetValue(1) tc:RegisterEffect(e1) end end
gpl-2.0
MalRD/darkstar
scripts/globals/items/bunch_of_pamamas.lua
11
1091
----------------------------------------- -- ID: 4468 -- Item: Bunch of Pamamas -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength -3 -- Intelligence 1 -- Additional Effect with Opo-Opo Crown -- HP 50 -- MP 50 -- CHR 14 -- Additional Effect with Kinkobo or -- Primate Staff -- DELAY -90 -- ACC 10 -- Additional Effect with Primate Staff +1 -- DELAY -80 -- ACC 12 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,1800,4468) end function onEffectGain(target, effect) target:addMod(dsp.mod.STR, -3) target:addMod(dsp.mod.INT, 1) end function onEffectLose(target, effect) target:delMod(dsp.mod.STR, -3) target:delMod(dsp.mod.INT, 1) end
gpl-3.0
LinusU/torch7
Tester.lua
58
7573
local Tester = torch.class('torch.Tester') function Tester:__init() self.errors = {} self.tests = {} self.testnames = {} self.curtestname = '' end function Tester:assert_sub (condition, message) self.countasserts = self.countasserts + 1 if not condition then local ss = debug.traceback('tester',2) --print(ss) ss = ss:match('[^\n]+\n[^\n]+\n([^\n]+\n[^\n]+)\n') self.errors[#self.errors+1] = self.curtestname .. '\n' .. (message or '') .. '\n' .. ss .. '\n' end end function Tester:assert (condition, message) self:assert_sub(condition,string.format('%s\n%s condition=%s',(message or ''),' BOOL violation ', tostring(condition))) end function Tester:assertlt (val, condition, message) self:assert_sub(val<condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' LT(<) violation ', tostring(val), tostring(condition))) end function Tester:assertgt (val, condition, message) self:assert_sub(val>condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' GT(>) violation ', tostring(val), tostring(condition))) end function Tester:assertle (val, condition, message) self:assert_sub(val<=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' LE(<=) violation ', tostring(val), tostring(condition))) end function Tester:assertge (val, condition, message) self:assert_sub(val>=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' GE(>=) violation ', tostring(val), tostring(condition))) end function Tester:asserteq (val, condition, message) self:assert_sub(val==condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' EQ(==) violation ', tostring(val), tostring(condition))) end function Tester:assertalmosteq (a, b, condition, message) condition = condition or 1e-16 local err = math.abs(a-b) self:assert_sub(err < condition, string.format('%s\n%s val=%s, condition=%s',(message or ''),' ALMOST_EQ(==) violation ', tostring(err), tostring(condition))) end function Tester:assertne (val, condition, message) self:assert_sub(val~=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' NE(~=) violation ', tostring(val), tostring(condition))) end function Tester:assertTensorEq(ta, tb, condition, message) if ta:dim() == 0 and tb:dim() == 0 then return end local diff = ta-tb local err = diff:abs():max() self:assert_sub(err<=condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' TensorEQ(==) violation ', tostring(err), tostring(condition))) end function Tester:assertTensorNe(ta, tb, condition, message) local diff = ta-tb local err = diff:abs():max() self:assert_sub(err>condition,string.format('%s\n%s val=%s, condition=%s',(message or ''),' TensorNE(~=) violation ', tostring(err), tostring(condition))) end local function areTablesEqual(ta, tb) local function isIncludedIn(ta, tb) if type(ta) ~= 'table' or type(tb) ~= 'table' then return ta == tb end for k, v in pairs(tb) do if not areTablesEqual(ta[k], v) then return false end end return true end return isIncludedIn(ta, tb) and isIncludedIn(tb, ta) end function Tester:assertTableEq(ta, tb, message) self:assert_sub(areTablesEqual(ta, tb), string.format('%s\n%s',(message or ''),' TableEQ(==) violation ')) end function Tester:assertTableNe(ta, tb, message) self:assert_sub(not areTablesEqual(ta, tb), string.format('%s\n%s',(message or ''),' TableEQ(==) violation ')) end function Tester:assertError(f, message) return self:assertErrorObj(f, function(err) return true end, message) end function Tester:assertErrorMsg(f, errmsg, message) return self:assertErrorObj(f, function(err) return err == errmsg end, message) end function Tester:assertErrorPattern(f, errPattern, message) return self:assertErrorObj(f, function(err) return string.find(err, errPattern) ~= nil end, message) end function Tester:assertErrorObj(f, errcomp, message) -- errcomp must be a function that compares the error object to its expected value local status, err = pcall(f) self:assert_sub(status == false and errcomp(err), string.format('%s\n%s err=%s', (message or ''),' ERROR violation ', tostring(err))) end function Tester:pcall(f) local nerr = #self.errors -- local res = f() local stat, result = xpcall(f, debug.traceback) if not stat then if result:find("interrupted!") then self:report() error("interrupted!") end self.errors[#self.errors+1] = self.curtestname .. '\n Function call failed \n' .. result .. '\n' end return stat, result, stat and (nerr == #self.errors) -- return true, res, nerr == #self.errors end function Tester:report(tests) if not tests then tests = self.tests end print('Completed ' .. self.countasserts .. ' asserts in ' .. #tests .. ' tests with ' .. #self.errors .. ' errors') print() print(string.rep('-',80)) for i,v in ipairs(self.errors) do print(v) print(string.rep('-',80)) end end function Tester:run(run_tests) local tests, testnames self.countasserts = 0 tests = self.tests testnames = self.testnames if type(run_tests) == 'string' then run_tests = {run_tests} end if type(run_tests) == 'table' then tests = {} testnames = {} for i,fun in ipairs(self.tests) do for j,name in ipairs(run_tests) do if self.testnames[i] == name or i == name then tests[#tests+1] = self.tests[i] testnames[#testnames+1] = self.testnames[i] end end end end self:_run(tests, testnames) self:report(tests) end --[[ Run exactly the given test functions with the given names. This doesn't do any matching or filtering, or produce a final report. It is internal to Tester:run(). ]] function Tester:_run(tests, testnames) print('Running ' .. #tests .. ' tests') local statstr = string.rep('_',#tests) local pstr = '' io.write(statstr .. '\r') for i,v in ipairs(tests) do self.curtestname = testnames[i] --clear io.write('\r' .. string.rep(' ', pstr:len())) io.flush() --write pstr = statstr:sub(1,i-1) .. '|' .. statstr:sub(i+1) .. ' ==> ' .. self.curtestname io.write('\r' .. pstr) io.flush() local stat, message, pass = self:pcall(v) if pass then --io.write(string.format('\b_')) statstr = statstr:sub(1,i-1) .. '_' .. statstr:sub(i+1) else statstr = statstr:sub(1,i-1) .. '*' .. statstr:sub(i+1) --io.write(string.format('\b*')) end if not stat then -- print() -- print('Function call failed: Test No ' .. i .. ' ' .. testnames[i]) -- print(message) end collectgarbage() end --clear io.write('\r' .. string.rep(' ', pstr:len())) io.flush() -- write finish pstr = statstr .. ' ==> Done ' io.write('\r' .. pstr) io.flush() print() print() end function Tester:add(f,name) name = name or 'unknown' if type(f) == "table" then local orderedNames = {} for n,_ in pairs(f) do table.insert(orderedNames, n) end table.sort(orderedNames) for _,n in pairs(orderedNames) do self:add(f[n], n) end elseif type(f) == "function" then self.tests[#self.tests+1] = f self.testnames[#self.tests] = name else error('Tester:add(f) expects a function or a table of functions') end end
bsd-3-clause
Lsty/ygopro-scripts
c96594609.lua
3
2268
--炎王獣 キリン function c96594609.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(96594609,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetRange(LOCATION_HAND) e1:SetCode(EVENT_DESTROYED) e1:SetCondition(c96594609.spcon) e1:SetTarget(c96594609.sptg) e1:SetOperation(c96594609.spop) c:RegisterEffect(e1) -- local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(96594609,1)) e2:SetCategory(CATEGORY_TOGRAVE) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e2:SetCode(EVENT_TO_GRAVE) e2:SetCondition(c96594609.tgcon) e2:SetTarget(c96594609.tgtg) e2:SetOperation(c96594609.tgop) c:RegisterEffect(e2) end function c96594609.cfilter(c,tp) return c:IsPreviousLocation(LOCATION_MZONE) and c:IsPreviousPosition(POS_FACEUP) and c:GetPreviousControler()==tp and c:IsReason(REASON_EFFECT) and c:IsSetCard(0x81) end function c96594609.spcon(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c96594609.cfilter,1,nil,tp) end function c96594609.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsRelateToEffect(e) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c96594609.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP) end end function c96594609.tgcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsReason(REASON_DESTROY) end function c96594609.tgfilter(c) return c:IsAttribute(ATTRIBUTE_FIRE) and c:IsAbleToGrave() end function c96594609.tgtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c96594609.tgfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK) end function c96594609.tgop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c96594609.tgfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoGrave(g,REASON_EFFECT) end end
gpl-2.0
Lsty/ygopro-scripts
c75417459.lua
6
1364
--拘束解除 function c75417459.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(c75417459.cost) e1:SetTarget(c75417459.target) e1:SetOperation(c75417459.activate) c:RegisterEffect(e1) end function c75417459.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckReleaseGroup(tp,Card.IsCode,1,nil,423705) end local g=Duel.SelectReleaseGroup(tp,Card.IsCode,1,1,nil,423705) Duel.Release(g,REASON_COST) end function c75417459.filter(c,e,tp) return c:IsCode(57046845) and c:IsCanBeSpecialSummoned(e,0,tp,true,false) end function c75417459.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 and Duel.IsExistingMatchingCard(c75417459.filter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_DECK) end function c75417459.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c75417459.filter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil,e,tp) if g:GetCount()>0 and Duel.SpecialSummon(g,0,tp,tp,true,false,POS_FACEUP)>0 then g:GetFirst():CompleteProcedure() end end
gpl-2.0
Lsty/ygopro-scripts
c75304793.lua
3
3056
--アンプリファイヤー function c75304793.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --counter local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_CHAIN_SOLVING) e2:SetRange(LOCATION_FZONE) e2:SetProperty(EFFECT_FLAG_DELAY) e2:SetCondition(c75304793.ctcon) e2:SetOperation(c75304793.ctop) c:RegisterEffect(e2) --atkup local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetCode(EFFECT_UPDATE_ATTACK) e3:SetRange(LOCATION_FZONE) e3:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE) e3:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0x1066)) e3:SetValue(c75304793.atkval) c:RegisterEffect(e3) --counter local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_IGNITION) e4:SetRange(LOCATION_FZONE) e4:SetCountLimit(1) e4:SetTarget(c75304793.target) e4:SetOperation(c75304793.operation) c:RegisterEffect(e4) end function c75304793.ctcon(e,tp,eg,ep,ev,re,r,rp) return re and re:GetHandler():IsSetCard(0x1066) and not re:IsHasType(EFFECT_TYPE_ACTIVATE) end function c75304793.ctop(e,tp,eg,ep,ev,re,r,rp) e:GetHandler():AddCounter(0x35,1) end function c75304793.atkval(e,c) return e:GetHandler():GetCounter(0x35)*100 end function c75304793.filter(c) return c:IsFaceup() and c:IsSetCard(0x1066) end function c75304793.target(e,tp,eg,ep,ev,re,r,rp,chk) local ct=Duel.GetMatchingGroupCount(c75304793.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil) local b1=e:GetHandler():IsCanRemoveCounter(tp,0x35,5,REASON_COST) local b2=e:GetHandler():IsCanRemoveCounter(tp,0x35,7,REASON_COST) and Duel.IsExistingMatchingCard(Card.IsAbleToRemove,tp,0,LOCATION_ONFIELD+LOCATION_GRAVE,1,nil) if chk==0 then return ct>0 and (b1 or b2) end local op=0 if b1 and b2 then op=Duel.SelectOption(tp,aux.Stringid(75304793,0),aux.Stringid(75304793,1)) elseif b1 then op=Duel.SelectOption(tp,aux.Stringid(75304793,0)) else op=Duel.SelectOption(tp,aux.Stringid(75304793,1))+1 end e:SetLabel(op) if op==0 then e:SetCategory(CATEGORY_DAMAGE) e:GetHandler():RemoveCounter(tp,0x35,5,REASON_COST) Duel.SetTargetPlayer(1-tp) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,ct*300) else e:SetCategory(CATEGORY_REMOVE) e:GetHandler():RemoveCounter(tp,0x35,7,REASON_COST) Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,0,LOCATION_ONFIELD+LOCATION_GRAVE) end end function c75304793.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end local ct=Duel.GetMatchingGroupCount(c75304793.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil) if ct==0 then return end if e:GetLabel()==0 then local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER) Duel.Damage(p,ct*300,REASON_EFFECT) else Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,Card.IsAbleToRemove,tp,0,LOCATION_ONFIELD+LOCATION_GRAVE,1,ct,nil) if g:GetCount()>0 then Duel.Remove(g,POS_FACEUP,REASON_EFFECT) end end end
gpl-2.0
MalRD/darkstar
scripts/globals/items/chocolate_crepe.lua
11
1277
----------------------------------------- -- ID: 5775 -- Item: Chocolate Crepe -- Food Effect: 30 Min, All Races ----------------------------------------- -- HP +5% (cap 15) -- MP Healing 2 -- Magic Accuracy +20% (cap 35) -- Magic Defense +1 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,1800,5775) end function onEffectGain(target,effect) target:addMod(dsp.mod.FOOD_HPP, 5) target:addMod(dsp.mod.FOOD_HP_CAP, 15) target:addMod(dsp.mod.MPHEAL, 2) target:addMod(dsp.mod.MDEF, 1) target:addMod(dsp.mod.FOOD_MACCP, 20) target:addMod(dsp.mod.FOOD_MACC_CAP, 35) end function onEffectLose(target, effect) target:delMod(dsp.mod.FOOD_HPP, 5) target:delMod(dsp.mod.FOOD_HP_CAP, 15) target:delMod(dsp.mod.MPHEAL, 2) target:delMod(dsp.mod.MDEF, 1) target:delMod(dsp.mod.FOOD_MACCP, 20) target:delMod(dsp.mod.FOOD_MACC_CAP, 35) end
gpl-3.0
Lsty/ygopro-scripts
c96300057.lua
3
3414
--W-ウィング・カタパルト function c96300057.initial_effect(c) --equip local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(96300057,0)) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCategory(CATEGORY_EQUIP) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetTarget(c96300057.eqtg) e1:SetOperation(c96300057.eqop) c:RegisterEffect(e1) --unequip local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(96300057,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_SZONE) e2:SetCondition(c96300057.uncon) e2:SetTarget(c96300057.sptg) e2:SetOperation(c96300057.spop) c:RegisterEffect(e2) --Atk up local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_EQUIP) e3:SetCode(EFFECT_UPDATE_ATTACK) e3:SetValue(400) e3:SetCondition(c96300057.uncon) c:RegisterEffect(e3) --Def up local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_EQUIP) e4:SetCode(EFFECT_UPDATE_DEFENCE) e4:SetValue(400) e4:SetCondition(c96300057.uncon) c:RegisterEffect(e4) --destroy sub local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_EQUIP) e5:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE) e5:SetCode(EFFECT_DESTROY_SUBSTITUTE) e5:SetCondition(c96300057.uncon) e5:SetValue(c96300057.repval) c:RegisterEffect(e5) --eqlimit local e6=Effect.CreateEffect(c) e6:SetType(EFFECT_TYPE_SINGLE) e6:SetCode(EFFECT_EQUIP_LIMIT) e6:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e6:SetValue(c96300057.eqlimit) c:RegisterEffect(e6) end function c96300057.uncon(e) return e:GetHandler():IsStatus(STATUS_UNION) end function c96300057.repval(e,re,r,rp) return bit.band(r,REASON_BATTLE)~=0 end function c96300057.eqlimit(e,c) return c:IsCode(51638941) end function c96300057.filter(c) return c:IsFaceup() and c:IsCode(51638941) and c:GetUnionCount()==0 end function c96300057.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c96300057.filter(chkc) end if chk==0 then return e:GetHandler():GetFlagEffect(96300057)==0 and Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingTarget(c96300057.filter,tp,LOCATION_MZONE,0,1,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) local g=Duel.SelectTarget(tp,c96300057.filter,tp,LOCATION_MZONE,0,1,1,e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_EQUIP,g,1,0,0) e:GetHandler():RegisterFlagEffect(96300057,RESET_EVENT+0x7e0000+RESET_PHASE+PHASE_END,0,1) end function c96300057.eqop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if not c:IsRelateToEffect(e) or c:IsFacedown() then return end if not tc:IsRelateToEffect(e) or not c96300057.filter(tc) then Duel.SendtoGrave(c,REASON_EFFECT) return end if not Duel.Equip(tp,c,tc,false) then return end c:SetStatus(STATUS_UNION,true) end function c96300057.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetFlagEffect(96300057)==0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,true,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) e:GetHandler():RegisterFlagEffect(96300057,RESET_EVENT+0x7e0000+RESET_PHASE+PHASE_END,0,1) end function c96300057.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP_ATTACK) end end
gpl-2.0
Lsty/ygopro-scripts
c67696066.lua
3
1692
--Emトリック・クラウン function c67696066.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_DAMAGE) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_TO_GRAVE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY) e1:SetCountLimit(1,67696066) e1:SetTarget(c67696066.sptg) e1:SetOperation(c67696066.spop) c:RegisterEffect(e1) end function c67696066.filter(c,e,tp) return c:IsSetCard(0xc6) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c67696066.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c67696066.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c67696066.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c67696066.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,tp,1000) end function c67696066.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SET_ATTACK) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetValue(0) e1:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_SET_DEFENCE) tc:RegisterEffect(e2) Duel.SpecialSummonComplete() Duel.BreakEffect() Duel.Damage(tp,1000,REASON_EFFECT) end end
gpl-2.0
Lsty/ygopro-scripts
c92266279.lua
3
3658
--潤いの風 function c92266279.initial_effect(c) --activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,TIMING_END_PHASE) e1:SetTarget(c92266279.target) c:RegisterEffect(e1) --to hand local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(92266279,1)) e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetCode(EVENT_FREE_CHAIN) e2:SetHintTiming(0,TIMING_END_PHASE) e2:SetRange(LOCATION_SZONE) e2:SetCountLimit(1,92266279) e2:SetCost(c92266279.thcost) e2:SetTarget(c92266279.thtg) e2:SetOperation(c92266279.thop) c:RegisterEffect(e2) --recover local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(92266279,2)) e3:SetCategory(CATEGORY_RECOVER) e3:SetType(EFFECT_TYPE_QUICK_O) e3:SetCode(EVENT_FREE_CHAIN) e3:SetHintTiming(0,TIMING_END_PHASE) e3:SetRange(LOCATION_SZONE) e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e3:SetCountLimit(1,92266280) e3:SetCondition(c92266279.reccon) e3:SetTarget(c92266279.rectg) e3:SetOperation(c92266279.recop) c:RegisterEffect(e3) end function c92266279.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local b1=c92266279.thcost(e,tp,eg,ep,ev,re,r,rp,0) and c92266279.thtg(e,tp,eg,ep,ev,re,r,rp,0) local b2=c92266279.reccon(e,tp,eg,ep,ev,re,r,rp) and c92266279.rectg(e,tp,eg,ep,ev,re,r,rp,0) if (b1 or b2) and Duel.SelectYesNo(tp,94) then local opt=0 if b1 and b2 then opt=Duel.SelectOption(tp,aux.Stringid(92266279,1),aux.Stringid(92266279,2)) elseif b1 then opt=Duel.SelectOption(tp,aux.Stringid(92266279,1)) else opt=Duel.SelectOption(tp,aux.Stringid(92266279,2))+1 end if opt==0 then e:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e:SetProperty(0) e:SetOperation(c92266279.thop) c92266279.thcost(e,tp,eg,ep,ev,re,r,rp,1) c92266279.thtg(e,tp,eg,ep,ev,re,r,rp,1) else e:SetCategory(CATEGORY_RECOVER) e:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e:SetOperation(c92266279.recop) c92266279.rectg(e,tp,eg,ep,ev,re,r,rp,1) end else e:SetCategory(0) e:SetProperty(0) e:SetOperation(nil) end end function c92266279.thcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckLPCost(tp,1000) and Duel.GetFlagEffect(tp,92266279)==0 end Duel.PayLPCost(tp,1000) Duel.RegisterFlagEffect(tp,92266279,RESET_PHASE+RESET_END,0,1) end function c92266279.thfilter(c) return c:IsSetCard(0xc9) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand() end function c92266279.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c92266279.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c92266279.thop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c92266279.thfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end function c92266279.reccon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetLP(tp)<Duel.GetLP(1-tp) end function c92266279.rectg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetFlagEffect(tp,92266280)==0 end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(500) Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,500) Duel.RegisterFlagEffect(tp,92266280,RESET_PHASE+RESET_END,0,1) end function c92266279.recop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Recover(p,d,REASON_EFFECT) end
gpl-2.0
MalRD/darkstar
scripts/globals/spells/knights_minne_ii.lua
10
1501
----------------------------------------- -- Spell: Knight's Minne II -- Grants Defense bonus to all allies. ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(dsp.skill.SINGING) -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(dsp.slot.RANGED) local power = 12 + math.floor((sLvl + iLvl)/10) if (power >= 69) then power = 69 end local iBoost = caster:getMod(dsp.mod.MINNE_EFFECT) + caster:getMod(dsp.mod.ALL_SONGS_EFFECT) if (iBoost > 0) then power = power + iBoost*7 end power = power + caster:getMerit(dsp.merit.MINNE_EFFECT) if (caster:hasStatusEffect(dsp.effect.SOUL_VOICE)) then power = power * 2 elseif (caster:hasStatusEffect(dsp.effect.MARCATO)) then power = power * 1.5 end caster:delStatusEffect(dsp.effect.MARCATO) local duration = 120 duration = duration * ((iBoost * 0.1) + (caster:getMod(dsp.mod.SONG_DURATION_BONUS)/100) + 1) if (caster:hasStatusEffect(dsp.effect.TROUBADOUR)) then duration = duration * 2 end if not (target:addBardSong(caster,dsp.effect.MINNE,power,0,duration,caster:getID(), 0, 2)) then spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end return dsp.effect.MINNE end
gpl-3.0
zhaozg/lit
libs/calculate-historic-deps.lua
2
3753
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local normalize = require('semver').normalize local gte = require('semver').gte local log = require('log').log local queryDb = require('pkg').queryDb local colorize = require('pretty-print').colorize return function (db, deps, newDeps, date) local addDep, processDeps function processDeps(dependencies) if not dependencies then return end for alias, dep in pairs(dependencies) do local name, version = dep:match("^([^@]+)@?(.*)$") if #version == 0 then version = nil end if type(alias) == "number" then alias = name:match("([^/]+)$") end if not name:find("/") then error("Package names must include owner/name at a minimum") end if version then local ok ok, version = pcall(normalize, version) if not ok then error("Invalid dependency version: " .. dep) end end addDep(alias, name, version) end end function addDep(alias, name, version) local meta = deps[alias] if meta then if name ~= meta.name then local message = string.format("%s %s ~= %s", alias, meta.name, name) log("alias conflict", message, "failure") return end if version then if not gte(meta.version, version) then local message = string.format("%s %s ~= %s", alias, meta.version, version) log("version conflict", message, "failure") return end end else local author, pname = name:match("^([^/]+)/(.*)$") local bestVersion = nil local availableVersions = {} for pversion in db.versions(author, pname) do local hash = db.read(author, pname, pversion) local tag = db.loadAs("tag", hash) local verdate = tag.tagger.date.seconds -- rule out anything newer than given date if verdate <= date then if bestVersion == nil or verdate > bestVersion.date or gte(pversion, bestVersion.version) then bestVersion = {date=verdate, hash=hash, version=pversion} end end table.insert(availableVersions, pversion) end -- TODO: fetch versions from remote in this case and try again -- since the suitable version might just not exist in the local db but -- does exist in the remote assert(bestVersion, "No suitable version found for "..name..": all versions in the db are newer than the given date.\n\nVersion specified in dependencies: "..version.."\n\nAvailable versions:\n" .. table.concat(availableVersions, '\n') .. '\n') local kind meta, kind, hash = assert(queryDb(db, bestVersion.hash)) meta.db = db meta.hash = hash meta.kind = kind deps[alias] = meta end processDeps(meta.dependencies) end processDeps(newDeps) local names = {} for k in pairs(deps) do names[#names + 1] = k end table.sort(names) for i = 1, #names do local name = names[i] local meta = deps[name] log("including dependency", string.format("%s (%s)", colorize("highlight", name), meta.path or meta.version)) end return deps end
apache-2.0
MalRD/darkstar
scripts/globals/spells/cura_ii.lua
12
4171
----------------------------------------- -- Spell: Cura -- Restores hp in area of effect. Self target only -- From what I understand, Cura's base potency is the same as Cure II's. -- With Afflatus Misery Bonus, it can be as potent as a Curaga III -- Modeled after our cure_ii.lua, which was modeled after the below reference -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) if (caster:getID() ~= target:getID()) then return dsp.msg.basic.CANNOT_PERFORM_TARG else return 0 end end function onSpellCast(caster,target,spell) local divisor = 0 local constant = 0 local basepower = 0 local power = 0 local basecure = 0 local final = 0 local minCure = 60 if (USE_OLD_CURE_FORMULA == true) then power = getCurePowerOld(caster) divisor = 1 constant = 20 if (power > 170) then divisor = 35.6666 constant = 87.62 elseif (power > 110) then divisor = 2 constant = 47.5 end else power = getCurePower(caster) if (power < 70) then divisor = 1 constant = 60 basepower = 40 elseif (power < 125) then divisor = 5.5 constant = 90 basepower = 70 elseif (power < 200) then divisor = 7.5 constant = 100 basepower = 125 elseif (power < 400) then divisor = 10 constant = 110 basepower = 200 elseif (power < 700) then divisor = 20 constant = 130 basepower = 400 else divisor = 999999 constant = 145 basepower = 0 end end if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCureOld(power,divisor,constant) else basecure = getBaseCure(power,divisor,constant,basepower) end --Apply Afflatus Misery Bonus to Final Result if (caster:hasStatusEffect(dsp.effect.AFFLATUS_MISERY)) then if (caster:getID() == target:getID()) then -- Let's use a local var to hold the power of Misery so the boost is applied to all targets, caster:setLocalVar("Misery_Power", caster:getMod(dsp.mod.AFFLATUS_MISERY)) end local misery = caster:getLocalVar("Misery_Power") --THIS IS LARELY SEMI-EDUCATED GUESSWORK. THERE IS NOT A --LOT OF CONCRETE INFO OUT THERE ON CURA THAT I COULD FIND --Not very much documentation for Cura II known at all. --As with Cura, the Afflatus Misery bonus can boost this spell up --to roughly the level of a Curaga 3. For Cura I vs Curaga II, --this is document at ~175HP, 15HP less than the cap of 190HP. So --for Cura II, i'll go with 15 less than the cap of Curaga III (390): 375 --So with lack of available formula documentation, I'll go with that. --printf("BEFORE AFFLATUS MISERY BONUS: %d", basecure) basecure = basecure + misery if (basecure > 375) then basecure = 375 end --printf("AFTER AFFLATUS MISERY BONUS: %d", basecure) --Afflatus Misery Mod Gets Used Up caster:setMod(dsp.mod.AFFLATUS_MISERY, 0) end final = getCureFinal(caster,spell,basecure,minCure,false) final = final + (final * (target:getMod(dsp.mod.CURE_POTENCY_RCVD)/100)) --Applying server mods.... final = final * CURE_POWER target:addHP(final) target:wakeUp() --Enmity for Cura is fixed, so its CE/VE is set in the SQL and not calculated with updateEnmityFromCure spell:setMsg(dsp.msg.basic.AOE_HP_RECOVERY) local mpBonusPercent = (final*caster:getMod(dsp.mod.CURE2MP_PERCENT))/100 if (mpBonusPercent > 0) then caster:addMP(mpBonusPercent) end return final end
gpl-3.0
MalRD/darkstar
scripts/globals/weaponskills/hard_slash.lua
10
1646
----------------------------------- -- Hard Slash -- Great Sword weapon skill -- Skill level: 5 -- Delivers a single-hit attack. Damage varies with TP. -- Modifiers: STR:30% -- 100%TP 200%TP 300%TP -- 1.5 1.75 2.0 ----------------------------------- require("scripts/globals/settings") require("scripts/globals/weaponskills") function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {} params.numHits = 1 -- ftp damage mods (for Damage Varies with TP lines are calculated in the function params.ftp100 = 1.5 params.ftp200 = 1.75 params.ftp300 = 2.0 -- wscs are in % so 0.2=20% params.str_wsc = 0.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.0 params.chr_wsc = 0.0 -- critical mods, again in % (ONLY USE FOR params.critICAL HIT VARIES WITH TP) params.crit100 = 0.0 params.crit200=0.0 params.crit300=0.0 params.canCrit = false -- accuracy mods (ONLY USE FOR accURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp. params.acc100 = 0 params.acc200=0 params.acc300=0 -- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default. params.atk100 = 1; params.atk200 = 1; params.atk300 = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 1.0 end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar) return tpHits, extraHits, criticalHit, damage end
gpl-3.0
Death15/Test
plugins/join.lua
26
1488
--[[ Bot can join into a group by replying a message contain an invite link or by typing !join [invite link]. URL.parse cannot parsing complicated message. So, this plugin only works for single [invite link] in a post. [invite link] may be preceeded but must not followed by another characters. --]] do local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) i = 0 for k,segment in pairs(parsed_path) do i = i + 1 if segment == 'joinchat' then invite_link = string.gsub(parsed_path[i+1], '[ %c].+$', '') break end end return invite_link end local function action_by_reply(extra, success, result) local hash = parsed_url(result.text) join = import_chat_link(hash, ok_cb, false) end function run(msg, matches) if is_sudo(msg.from.id) then if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) elseif matches[1] then local hash = parsed_url(matches[1]) join = import_chat_link(hash, ok_cb, false) end end end return { description = 'Invite the bot into a group chat via its invite link.', usage = { '!join : Join a group by replying a message containing invite link.', '!join [invite_link] : Join into a group by providing their [invite_link].' }, patterns = { '^!join$', '^!join (.*)$' }, run = run } end
gpl-2.0
Lsty/ygopro-scripts
c74923978.lua
5
1203
--強制接収 function c74923978.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_DISCARD) e1:SetCondition(c74923978.condition) c:RegisterEffect(e1) --handes local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(74923978,0)) e2:SetCategory(CATEGORY_HANDES) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetRange(LOCATION_SZONE) e2:SetCode(EVENT_DISCARD) e2:SetCondition(c74923978.condition) e2:SetTarget(c74923978.target) e2:SetOperation(c74923978.operation) c:RegisterEffect(e2) end function c74923978.cfilter(c,tp) return c:GetPreviousControler()==tp end function c74923978.condition(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c74923978.cfilter,1,nil,tp) end function c74923978.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsRelateToEffect(e) end local ct=eg:FilterCount(c74923978.cfilter,nil,tp) e:SetLabel(ct) Duel.SetOperationInfo(0,CATEGORY_HANDES,nil,0,1-tp,ct) end function c74923978.operation(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local ct=e:GetLabel() Duel.DiscardHand(1-tp,nil,ct,ct,REASON_EFFECT+REASON_DISCARD) end
gpl-2.0
EUOCheffe/easyuo
proj/openeuo/gui/main.lua
1
1567
---------------------------------------- -- Main Code --------------------------- ---------------------------------------- -- This is where the other GUI files are -- loaded and everything is tied together. ---------------------------------------- ---------------------------------------- ---------------------------------------- Version = "OpenEUO 0.91" dofile("const.lua") dofile("library.lua") dofile("layout.lua") dofile("menu.lua") dofile("instances.lua") ---------------------------------------- function ExitHandler() if Inst.Confirm("Exit OpenEUO?") then MainForm.Hide() Obj.Exit() end end ---------------------------------------- MenuHandler = { [11] = Inst.New, [12] = Inst.Open, [13] = Inst.Save, [14] = Inst.SaveAs, [15] = Inst.Close, [16] = Inst.CloseAll, [17] = ExitHandler, [21] = Inst.Cut, [22] = Inst.Copy, [23] = Inst.Paste, [24] = Inst.Delete, [25] = Inst.SelectAll, [26] = Inst.Undo, [31] = Inst.Start, [32] = Inst.Pause, [33] = Inst.Stop, [34] = Inst.StopAll, [35] = Inst.StepInto, [36] = Inst.StepOver, [37] = Inst.StepOut, [41] = function() Ctrl.Execute("http://www.easyuo.com/forum/viewforum.php?f=37") end, [42] = function() AboutDialog.Show(Version.."\r\nby Cheffe") end, } ---------------------------------------- local function Main() CreateLayout() CreateMenu() MainForm.Show() CreateInst(ProjectTabCtrl) Obj.Loop() FreeInst() FreeMenu() FreeLayout() end ---------------------------------------- Main()
bsd-2-clause
MalRD/darkstar
scripts/globals/items/slice_of_margherita_pizza_+1.lua
11
1190
----------------------------------------- -- ID: 6214 -- Item: slice of margherita pizza +1 -- Food Effect: 60 minutes, all Races ----------------------------------------- -- HP +35 -- Accuracy+10% (Max. 9) -- Attack+10% (Max. 11) ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,3600,6214) end function onEffectGain(target,effect) target:addMod(dsp.mod.HP, 35) target:addMod(dsp.mod.FOOD_ACCP, 10) target:addMod(dsp.mod.FOOD_ACC_CAP, 9) target:addMod(dsp.mod.FOOD_ATTP, 10) target:addMod(dsp.mod.FOOD_ATT_CAP, 11) end function onEffectLose(target, effect) target:delMod(dsp.mod.HP, 35) target:delMod(dsp.mod.FOOD_ACCP, 10) target:delMod(dsp.mod.FOOD_ACC_CAP, 9) target:delMod(dsp.mod.FOOD_ATTP, 10) target:delMod(dsp.mod.FOOD_ATT_CAP, 11) end
gpl-3.0
MalRD/darkstar
scripts/globals/spells/enchanting_etude.lua
12
1846
----------------------------------------- -- Spell: Enchanting Etude -- Static CHR Boost, BRD 22 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(dsp.skill.SINGING) -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(dsp.slot.RANGED) local power = 0 if (sLvl+iLvl <= 181) then power = 3 elseif ((sLvl+iLvl >= 182) and (sLvl+iLvl <= 235)) then power = 4 elseif ((sLvl+iLvl >= 236) and (sLvl+iLvl <= 288)) then power = 5 elseif ((sLvl+iLvl >= 289) and (sLvl+iLvl <= 342)) then power = 6 elseif ((sLvl+iLvl >= 343) and (sLvl+iLvl <= 396)) then power = 7 elseif ((sLvl+iLvl >= 397) and (sLvl+iLvl <= 449)) then power = 8 elseif (sLvl+iLvl >= 450) then power = 9 end local iBoost = caster:getMod(dsp.mod.ETUDE_EFFECT) + caster:getMod(dsp.mod.ALL_SONGS_EFFECT) power = power + iBoost if (caster:hasStatusEffect(dsp.effect.SOUL_VOICE)) then power = power * 2 elseif (caster:hasStatusEffect(dsp.effect.MARCATO)) then power = power * 1.5 end caster:delStatusEffect(dsp.effect.MARCATO) local duration = 120 duration = duration * ((iBoost * 0.1) + (caster:getMod(dsp.mod.SONG_DURATION_BONUS)/100) + 1) if (caster:hasStatusEffect(dsp.effect.TROUBADOUR)) then duration = duration * 2 end if not (target:addBardSong(caster,dsp.effect.ETUDE,power,0,duration,caster:getID(), dsp.mod.CHR, 1)) then spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end return dsp.effect.ETUDE end
gpl-3.0
Zanthra/GTTS
control.lua
1
5425
require "config" local function updatePlayerSettings() if settings.global["gtts-Adjust-HandCraftingSpeed"].value == true then for _,player in pairs(game.players) do if player.character then player.character.character_crafting_speed_modifier = gtts_time_scale - 1 end end else for _,player in pairs(game.players) do if player.character then player.character.character_crafting_speed_modifier = 0 end end end end --This turns an array of keys below the global "game" object into --a table reference and a key in that table as a tuple. -- --t,k = get_reference(keys) -- --the reference becomes t[k] local function get_reference(keys) local length = #keys local reftable = game for i = 1,length-1 do reftable = reftable[keys[i]] end return reftable,keys[length] end --Helper method for updating settings given the setting name, the --global variable to which the previous value of that variable is --saved, a list of keys to the variable to be changed, and a boolean --indicating whether it is a speed or duration. local function update_GTTS_setting(setting, save, targetvariable, speed) local t,k = get_reference(targetvariable) if settings.global[setting].value == true then if not global[save] then global[save] = t[k] end if speed then t[k] = global[save] * gtts_time_scale else t[k] = global[save] / gtts_time_scale end else if global[save] then t[k] = global[save] global[save] = nil end end end local function updateMapSettings() update_GTTS_setting("gtts-Adjust-Pollution", "initial-pollution-diffusionratio", {"map_settings", "pollution", "diffusion_ratio"}, true) update_GTTS_setting("gtts-Adjust-Pollution", "initial-pollution-ageing", {"map_settings", "pollution", "ageing"}, true) update_GTTS_setting("gtts-Adjust-Evolution", "initial-evolution-timefactor", {"map_settings", "enemy_evolution", "time_factor"}, true) update_GTTS_setting("gtts-Adjust-Expansion", "initial-expansion-minexpansioncooldown", {"map_settings", "enemy_expansion", "min_expansion_cooldown"}, false) update_GTTS_setting("gtts-Adjust-Expansion", "initial-expansion-maxexpansioncooldown", {"map_settings", "enemy_expansion", "max_expansion_cooldown"}, false) if game.surfaces["nauvis"] then update_GTTS_setting("gtts-Adjust-DayNight", "initial-day-night", {"surfaces", "nauvis", "ticks_per_day"}, false) update_GTTS_setting("gtts-Adjust-WindSpeed", "initial-windspeed", {"surfaces", "nauvis", "wind_speed"}, true) end update_GTTS_setting("gtts-Adjust-Groups", "initial-groups-mingroupgatheringtime", {"map_settings", "unit_group", "min_group_gathering_time"}, false) update_GTTS_setting("gtts-Adjust-Groups", "initial-groups-maxgroupgatheringtime", {"map_settings", "unit_group", "max_group_gathering_time"}, false) update_GTTS_setting("gtts-Adjust-Groups", "initial-groups-maxwaittimeforlatemembers", {"map_settings", "unit_group", "max_wait_time_for_late_members"}, false) update_GTTS_setting("gtts-Adjust-Groups", "initial-groups-ticktolerancewhenmemberarrives", {"map_settings", "unit_group", "tick_tolerance_when_member_arrives"}, false) end --Only add events if the safe mode setting is not enabled. if settings.startup["gtts-z-No-Runtime-Adjustments"].value == false then script.on_configuration_changed( function (event) global["previous-scale"] = 1.0 / game.speed end ) script.on_event(defines.events.on_tick, function(event) --Only change the game speed if the target frame rate has changed or Reset-GameSpeed was disabled. --For this we save "previous-speed" in the global table with the last adjusted game speed. This --prevents the game speed from being changed if the user, or another mod, changes the game speed. if ((not global["previous-speed"]) or (not (global["previous-speed"] == gtts_time_scale_inverse))) and game.tick > 1 then if (not global["previous-scale"]) or (not (global["previous-scale"] == gtts_time_scale)) then updateMapSettings() updatePlayerSettings() global["previous-scale"] = gtts_time_scale end if settings.global["gtts-Reset-GameSpeed"].value == false then if settings.startup["gtts-Adjust-GameSpeed"].value == true then game.speed = gtts_time_scale_inverse global["previous-speed"] = gtts_time_scale_inverse end end end end ) script.on_event(defines.events.on_runtime_mod_setting_changed, function(event) if settings.global["gtts-Reset-GameSpeed"].value == true then game.speed = 1.0 global["previous-speed"] = 1.0 end updateMapSettings() updatePlayerSettings() end ) script.on_event(defines.events.on_player_created, updatePlayerSettings) script.on_event(defines.events.on_player_joined_game, updatePlayerSettings) script.on_event(defines.events.on_player_respawned, updatePlayerSettings) end
mit
Lsty/ygopro-scripts
c67173574.lua
5
3570
--CNo.102 光堕天使ノーブル・デーモン function c67173574.initial_effect(c) Duel.EnableGlobalFlag(GLOBALFLAG_DETACH_EVENT) --xyz summon aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsAttribute,ATTRIBUTE_LIGHT),5,4) c:EnableReviveLimit() --destroy replace local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetCode(EFFECT_DESTROY_REPLACE) e1:SetRange(LOCATION_MZONE) e1:SetTarget(c67173574.reptg) c:RegisterEffect(e1) --damage local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(67173574,1)) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetCategory(CATEGORY_DAMAGE) e2:SetCode(EVENT_DETACH_MATERIAL) e2:SetCondition(c67173574.damcon) e2:SetTarget(c67173574.damtg) e2:SetOperation(c67173574.damop) c:RegisterEffect(e2) --disable local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_ATKCHANGE+CATEGORY_DISABLE) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetRange(LOCATION_MZONE) e3:SetProperty(EFFECT_FLAG_CARD_TARGET) e3:SetCountLimit(1) e3:SetCondition(c67173574.condition) e3:SetCost(c67173574.cost) e3:SetTarget(c67173574.target) e3:SetOperation(c67173574.operation) c:RegisterEffect(e3) end c67173574.xyz_number=102 function c67173574.reptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,2,REASON_EFFECT) end if Duel.SelectYesNo(tp,aux.Stringid(67173574,0)) then e:GetHandler():RemoveOverlayCard(tp,2,2,REASON_EFFECT) return true else return false end end function c67173574.damcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetOverlayCount()==0 end function c67173574.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsRelateToEffect(e) and e:GetHandler():IsFaceup() end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(1500) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,0,0,1-tp,1500) end function c67173574.damop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end function c67173574.condition(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,49678559) end function c67173574.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST) end function c67173574.filter(c) return c:IsFaceup() and c:GetAttack()>0 end function c67173574.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c67173574.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c67173574.filter,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c67173574.filter,tp,0,LOCATION_MZONE,1,1,nil) end function c67173574.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsFaceup() and tc:GetAttack()>0 and tc:IsControler(1-tp) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SET_ATTACK_FINAL) e1:SetValue(0) e1:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_DISABLE) e2:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e2) local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_DISABLE_EFFECT) e3:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e3) end end
gpl-2.0
Lsty/ygopro-scripts
c10485110.lua
5
2075
--海竜神-ネオダイダロス function c10485110.initial_effect(c) c:EnableReviveLimit() --cannot special summon local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetValue(aux.FALSE) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_SPSUMMON_PROC) e2:SetProperty(EFFECT_FLAG_UNCOPYABLE) e2:SetRange(LOCATION_HAND) e2:SetCondition(c10485110.spcon) e2:SetOperation(c10485110.spop) c:RegisterEffect(e2) --tograve local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(10485110,0)) e3:SetCategory(CATEGORY_TOGRAVE) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetRange(LOCATION_MZONE) e3:SetCost(c10485110.cost) e3:SetTarget(c10485110.target) e3:SetOperation(c10485110.operation) c:RegisterEffect(e3) end function c10485110.spcon(e,c) if c==nil then return true end return Duel.CheckReleaseGroup(c:GetControler(),Card.IsCode,1,nil,37721209) end function c10485110.spop(e,tp,eg,ep,ev,re,r,rp,c) local g=Duel.SelectReleaseGroup(tp,Card.IsCode,1,1,nil,37721209) Duel.Release(g,REASON_COST) end function c10485110.cfilter(c) return c:IsFaceup() and c:IsCode(22702055) and c:IsAbleToGraveAsCost() end function c10485110.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c10485110.cfilter,tp,LOCATION_ONFIELD,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c10485110.cfilter,tp,LOCATION_ONFIELD,0,1,1,nil) Duel.SendtoGrave(g,REASON_COST) end function c10485110.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(aux.TRUE,tp,0xe,0xe,1,e:GetHandler()) end local g=Duel.GetMatchingGroup(aux.TRUE,tp,0xe,0xe,e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,g,g:GetCount(),0,0) end function c10485110.operation(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(aux.TRUE,tp,0xe,0xe,e:GetHandler()) Duel.SendtoGrave(g,REASON_EFFECT) end
gpl-2.0
MalRD/darkstar
scripts/globals/items/moat_carp.lua
11
1048
----------------------------------------- -- ID: 4401 -- Item: moat_carp -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:getRace() ~= dsp.race.MITHRA) then result = dsp.msg.basic.CANNOT_EAT end if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then result = 0 end if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,300,4401) end function onEffectGain(target, effect) target:addMod(dsp.mod.DEX, 2) target:addMod(dsp.mod.MND, -4) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, 2) target:delMod(dsp.mod.MND, -4) end
gpl-3.0
Lsty/ygopro-scripts
c57108202.lua
3
3311
--D・リモコン function c57108202.initial_effect(c) --search local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(57108202,0)) e1:SetCategory(CATEGORY_REMOVE+CATEGORY_TOHAND+CATEGORY_SEARCH) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCountLimit(1) e1:SetRange(LOCATION_MZONE) e1:SetCondition(c57108202.cona) e1:SetTarget(c57108202.tga) e1:SetOperation(c57108202.opa) c:RegisterEffect(e1) --salvage local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(57108202,1)) e2:SetCategory(CATEGORY_TOGRAVE+CATEGORY_TOHAND) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetCountLimit(1) e2:SetRange(LOCATION_MZONE) e2:SetCondition(c57108202.cond) e2:SetTarget(c57108202.tgd) e2:SetOperation(c57108202.opd) c:RegisterEffect(e2) end function c57108202.filter(c,lv) return c:IsSetCard(0x26) and c:GetLevel()==lv and c:IsAbleToHand() end function c57108202.cona(e,tp,eg,ep,ev,re,r,rp) return not e:GetHandler():IsDisabled() and e:GetHandler():IsAttackPos() end function c57108202.filtera(c,tp) local lv=c:GetLevel() return c:IsSetCard(0x26) and lv>0 and c:IsAbleToRemove() and Duel.IsExistingMatchingCard(c57108202.filter,tp,LOCATION_DECK,0,1,nil,lv) end function c57108202.tga(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c57108202.filtera(chkc,tp) end if chk==0 then return Duel.IsExistingTarget(c57108202.filtera,tp,LOCATION_GRAVE,0,1,nil,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectTarget(tp,c57108202.filtera,tp,LOCATION_GRAVE,0,1,1,nil,tp) Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c57108202.opa(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)~=0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c57108202.filter,tp,LOCATION_DECK,0,1,1,nil,tc:GetLevel()) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end end function c57108202.cond(e,tp,eg,ep,ev,re,r,rp) return not e:GetHandler():IsDisabled() and e:GetHandler():IsDefencePos() end function c57108202.filterd(c,tp) local lv=c:GetLevel() return c:IsSetCard(0x26) and lv>0 and c:IsAbleToGrave() and Duel.IsExistingMatchingCard(c57108202.filter,tp,LOCATION_GRAVE,0,1,nil,lv) end function c57108202.tgd(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c57108202.filterd,tp,LOCATION_HAND,0,1,nil,tp) end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_HAND) Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_GRAVE) end function c57108202.opd(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c57108202.filterd,tp,LOCATION_HAND,0,1,1,nil,tp) local tc=g:GetFirst() if not tc then return end Duel.SendtoGrave(tc,REASON_EFFECT) if not tc:IsLocation(LOCATION_GRAVE) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local sg=Duel.SelectMatchingCard(tp,c57108202.filter,tp,LOCATION_GRAVE,0,1,1,tc,tc:GetLevel()) if sg:GetCount()>0 then Duel.SendtoHand(sg,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,sg) end end
gpl-2.0
Lsty/ygopro-scripts
c35848254.lua
7
1082
--フォトン・リード function c35848254.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c35848254.target) e1:SetOperation(c35848254.activate) c:RegisterEffect(e1) end function c35848254.filter(c,e,tp) return c:IsLevelBelow(4) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c35848254.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c35848254.filter,tp,LOCATION_HAND,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND) end function c35848254.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c35848254.filter,tp,LOCATION_HAND,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP_ATTACK) end end
gpl-2.0
gallenmu/MoonGen
libmoon/deps/luajit/dynasm/dasm_ppc.lua
27
57489
------------------------------------------------------------------------------ -- DynASM PPC/PPC64 module. -- -- Copyright (C) 2005-2017 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. -- -- Support for various extensions contributed by Caio Souza Oliveira. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "ppc", description = "DynASM PPC 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 = assert, setmetatable local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch = _s.match, _s.gmatch local concat, sort = table.concat, table.sort local bit = bit or require("bit") local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift local tohex = 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", "IMMSH" } -- 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 <= 0xffffff then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. local map_archdef = { sp = "r1" } -- Ext. register name -> int. name. local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) if s == "r1" then return "sp" end return s end local map_cond = { lt = 0, gt = 1, eq = 2, so = 3, ge = 4, le = 5, ne = 6, ns = 7, } ------------------------------------------------------------------------------ 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 -- Template strings for PPC instructions. map_op = { tdi_3 = "08000000ARI", twi_3 = "0c000000ARI", mulli_3 = "1c000000RRI", subfic_3 = "20000000RRI", cmplwi_3 = "28000000XRU", cmplwi_2 = "28000000-RU", cmpldi_3 = "28200000XRU", cmpldi_2 = "28200000-RU", cmpwi_3 = "2c000000XRI", cmpwi_2 = "2c000000-RI", cmpdi_3 = "2c200000XRI", cmpdi_2 = "2c200000-RI", addic_3 = "30000000RRI", ["addic._3"] = "34000000RRI", addi_3 = "38000000RR0I", li_2 = "38000000RI", la_2 = "38000000RD", addis_3 = "3c000000RR0I", lis_2 = "3c000000RI", lus_2 = "3c000000RU", bc_3 = "40000000AAK", bcl_3 = "40000001AAK", bdnz_1 = "42000000K", bdz_1 = "42400000K", sc_0 = "44000000", b_1 = "48000000J", bl_1 = "48000001J", rlwimi_5 = "50000000RR~AAA.", rlwinm_5 = "54000000RR~AAA.", rlwnm_5 = "5c000000RR~RAA.", ori_3 = "60000000RR~U", nop_0 = "60000000", oris_3 = "64000000RR~U", xori_3 = "68000000RR~U", xoris_3 = "6c000000RR~U", ["andi._3"] = "70000000RR~U", ["andis._3"] = "74000000RR~U", lwz_2 = "80000000RD", lwzu_2 = "84000000RD", lbz_2 = "88000000RD", lbzu_2 = "8c000000RD", stw_2 = "90000000RD", stwu_2 = "94000000RD", stb_2 = "98000000RD", stbu_2 = "9c000000RD", lhz_2 = "a0000000RD", lhzu_2 = "a4000000RD", lha_2 = "a8000000RD", lhau_2 = "ac000000RD", sth_2 = "b0000000RD", sthu_2 = "b4000000RD", lmw_2 = "b8000000RD", stmw_2 = "bc000000RD", lfs_2 = "c0000000FD", lfsu_2 = "c4000000FD", lfd_2 = "c8000000FD", lfdu_2 = "cc000000FD", stfs_2 = "d0000000FD", stfsu_2 = "d4000000FD", stfd_2 = "d8000000FD", stfdu_2 = "dc000000FD", ld_2 = "e8000000RD", -- NYI: displacement must be divisible by 4. ldu_2 = "e8000001RD", lwa_2 = "e8000002RD", std_2 = "f8000000RD", stdu_2 = "f8000001RD", subi_3 = op_alias("addi_3", function(p) p[3] = "-("..p[3]..")" end), subis_3 = op_alias("addis_3", function(p) p[3] = "-("..p[3]..")" end), subic_3 = op_alias("addic_3", function(p) p[3] = "-("..p[3]..")" end), ["subic._3"] = op_alias("addic._3", function(p) p[3] = "-("..p[3]..")" end), rotlwi_3 = op_alias("rlwinm_5", function(p) p[4] = "0"; p[5] = "31" end), rotrwi_3 = op_alias("rlwinm_5", function(p) p[3] = "32-("..p[3]..")"; p[4] = "0"; p[5] = "31" end), rotlw_3 = op_alias("rlwnm_5", function(p) p[4] = "0"; p[5] = "31" end), slwi_3 = op_alias("rlwinm_5", function(p) p[5] = "31-("..p[3]..")"; p[4] = "0" end), srwi_3 = op_alias("rlwinm_5", function(p) p[4] = p[3]; p[3] = "32-("..p[3]..")"; p[5] = "31" end), clrlwi_3 = op_alias("rlwinm_5", function(p) p[4] = p[3]; p[3] = "0"; p[5] = "31" end), clrrwi_3 = op_alias("rlwinm_5", function(p) p[5] = "31-("..p[3]..")"; p[3] = "0"; p[4] = "0" end), -- Primary opcode 4: mulhhwu_3 = "10000010RRR.", machhwu_3 = "10000018RRR.", mulhhw_3 = "10000050RRR.", nmachhw_3 = "1000005cRRR.", machhwsu_3 = "10000098RRR.", machhws_3 = "100000d8RRR.", nmachhws_3 = "100000dcRRR.", mulchwu_3 = "10000110RRR.", macchwu_3 = "10000118RRR.", mulchw_3 = "10000150RRR.", macchw_3 = "10000158RRR.", nmacchw_3 = "1000015cRRR.", macchwsu_3 = "10000198RRR.", macchws_3 = "100001d8RRR.", nmacchws_3 = "100001dcRRR.", mullhw_3 = "10000350RRR.", maclhw_3 = "10000358RRR.", nmaclhw_3 = "1000035cRRR.", maclhwsu_3 = "10000398RRR.", maclhws_3 = "100003d8RRR.", nmaclhws_3 = "100003dcRRR.", machhwuo_3 = "10000418RRR.", nmachhwo_3 = "1000045cRRR.", machhwsuo_3 = "10000498RRR.", machhwso_3 = "100004d8RRR.", nmachhwso_3 = "100004dcRRR.", macchwuo_3 = "10000518RRR.", macchwo_3 = "10000558RRR.", nmacchwo_3 = "1000055cRRR.", macchwsuo_3 = "10000598RRR.", macchwso_3 = "100005d8RRR.", nmacchwso_3 = "100005dcRRR.", maclhwo_3 = "10000758RRR.", nmaclhwo_3 = "1000075cRRR.", maclhwsuo_3 = "10000798RRR.", maclhwso_3 = "100007d8RRR.", nmaclhwso_3 = "100007dcRRR.", vaddubm_3 = "10000000VVV", vmaxub_3 = "10000002VVV", vrlb_3 = "10000004VVV", vcmpequb_3 = "10000006VVV", vmuloub_3 = "10000008VVV", vaddfp_3 = "1000000aVVV", vmrghb_3 = "1000000cVVV", vpkuhum_3 = "1000000eVVV", vmhaddshs_4 = "10000020VVVV", vmhraddshs_4 = "10000021VVVV", vmladduhm_4 = "10000022VVVV", vmsumubm_4 = "10000024VVVV", vmsummbm_4 = "10000025VVVV", vmsumuhm_4 = "10000026VVVV", vmsumuhs_4 = "10000027VVVV", vmsumshm_4 = "10000028VVVV", vmsumshs_4 = "10000029VVVV", vsel_4 = "1000002aVVVV", vperm_4 = "1000002bVVVV", vsldoi_4 = "1000002cVVVP", vpermxor_4 = "1000002dVVVV", vmaddfp_4 = "1000002eVVVV~", vnmsubfp_4 = "1000002fVVVV~", vaddeuqm_4 = "1000003cVVVV", vaddecuq_4 = "1000003dVVVV", vsubeuqm_4 = "1000003eVVVV", vsubecuq_4 = "1000003fVVVV", vadduhm_3 = "10000040VVV", vmaxuh_3 = "10000042VVV", vrlh_3 = "10000044VVV", vcmpequh_3 = "10000046VVV", vmulouh_3 = "10000048VVV", vsubfp_3 = "1000004aVVV", vmrghh_3 = "1000004cVVV", vpkuwum_3 = "1000004eVVV", vadduwm_3 = "10000080VVV", vmaxuw_3 = "10000082VVV", vrlw_3 = "10000084VVV", vcmpequw_3 = "10000086VVV", vmulouw_3 = "10000088VVV", vmuluwm_3 = "10000089VVV", vmrghw_3 = "1000008cVVV", vpkuhus_3 = "1000008eVVV", vaddudm_3 = "100000c0VVV", vmaxud_3 = "100000c2VVV", vrld_3 = "100000c4VVV", vcmpeqfp_3 = "100000c6VVV", vcmpequd_3 = "100000c7VVV", vpkuwus_3 = "100000ceVVV", vadduqm_3 = "10000100VVV", vmaxsb_3 = "10000102VVV", vslb_3 = "10000104VVV", vmulosb_3 = "10000108VVV", vrefp_2 = "1000010aV-V", vmrglb_3 = "1000010cVVV", vpkshus_3 = "1000010eVVV", vaddcuq_3 = "10000140VVV", vmaxsh_3 = "10000142VVV", vslh_3 = "10000144VVV", vmulosh_3 = "10000148VVV", vrsqrtefp_2 = "1000014aV-V", vmrglh_3 = "1000014cVVV", vpkswus_3 = "1000014eVVV", vaddcuw_3 = "10000180VVV", vmaxsw_3 = "10000182VVV", vslw_3 = "10000184VVV", vmulosw_3 = "10000188VVV", vexptefp_2 = "1000018aV-V", vmrglw_3 = "1000018cVVV", vpkshss_3 = "1000018eVVV", vmaxsd_3 = "100001c2VVV", vsl_3 = "100001c4VVV", vcmpgefp_3 = "100001c6VVV", vlogefp_2 = "100001caV-V", vpkswss_3 = "100001ceVVV", vadduhs_3 = "10000240VVV", vminuh_3 = "10000242VVV", vsrh_3 = "10000244VVV", vcmpgtuh_3 = "10000246VVV", vmuleuh_3 = "10000248VVV", vrfiz_2 = "1000024aV-V", vsplth_3 = "1000024cVV3", vupkhsh_2 = "1000024eV-V", vminuw_3 = "10000282VVV", vminud_3 = "100002c2VVV", vcmpgtud_3 = "100002c7VVV", vrfim_2 = "100002caV-V", vcmpgtsb_3 = "10000306VVV", vcfux_3 = "1000030aVVA~", vaddshs_3 = "10000340VVV", vminsh_3 = "10000342VVV", vsrah_3 = "10000344VVV", vcmpgtsh_3 = "10000346VVV", vmulesh_3 = "10000348VVV", vcfsx_3 = "1000034aVVA~", vspltish_2 = "1000034cVS", vupkhpx_2 = "1000034eV-V", vaddsws_3 = "10000380VVV", vminsw_3 = "10000382VVV", vsraw_3 = "10000384VVV", vcmpgtsw_3 = "10000386VVV", vmulesw_3 = "10000388VVV", vctuxs_3 = "1000038aVVA~", vspltisw_2 = "1000038cVS", vminsd_3 = "100003c2VVV", vsrad_3 = "100003c4VVV", vcmpbfp_3 = "100003c6VVV", vcmpgtsd_3 = "100003c7VVV", vctsxs_3 = "100003caVVA~", vupklpx_2 = "100003ceV-V", vsububm_3 = "10000400VVV", ["bcdadd._4"] = "10000401VVVy.", vavgub_3 = "10000402VVV", vand_3 = "10000404VVV", ["vcmpequb._3"] = "10000406VVV", vmaxfp_3 = "1000040aVVV", vsubuhm_3 = "10000440VVV", ["bcdsub._4"] = "10000441VVVy.", vavguh_3 = "10000442VVV", vandc_3 = "10000444VVV", ["vcmpequh._3"] = "10000446VVV", vminfp_3 = "1000044aVVV", vpkudum_3 = "1000044eVVV", vsubuwm_3 = "10000480VVV", vavguw_3 = "10000482VVV", vor_3 = "10000484VVV", ["vcmpequw._3"] = "10000486VVV", vpmsumw_3 = "10000488VVV", ["vcmpeqfp._3"] = "100004c6VVV", ["vcmpequd._3"] = "100004c7VVV", vpkudus_3 = "100004ceVVV", vavgsb_3 = "10000502VVV", vavgsh_3 = "10000542VVV", vorc_3 = "10000544VVV", vbpermq_3 = "1000054cVVV", vpksdus_3 = "1000054eVVV", vavgsw_3 = "10000582VVV", vsld_3 = "100005c4VVV", ["vcmpgefp._3"] = "100005c6VVV", vpksdss_3 = "100005ceVVV", vsububs_3 = "10000600VVV", mfvscr_1 = "10000604V--", vsum4ubs_3 = "10000608VVV", vsubuhs_3 = "10000640VVV", mtvscr_1 = "10000644--V", ["vcmpgtuh._3"] = "10000646VVV", vsum4shs_3 = "10000648VVV", vupkhsw_2 = "1000064eV-V", vsubuws_3 = "10000680VVV", vshasigmaw_4 = "10000682VVYp", veqv_3 = "10000684VVV", vsum2sws_3 = "10000688VVV", vmrgow_3 = "1000068cVVV", vshasigmad_4 = "100006c2VVYp", vsrd_3 = "100006c4VVV", ["vcmpgtud._3"] = "100006c7VVV", vupklsw_2 = "100006ceV-V", vupkslw_2 = "100006ceV-V", vsubsbs_3 = "10000700VVV", vclzb_2 = "10000702V-V", vpopcntb_2 = "10000703V-V", ["vcmpgtsb._3"] = "10000706VVV", vsum4sbs_3 = "10000708VVV", vsubshs_3 = "10000740VVV", vclzh_2 = "10000742V-V", vpopcnth_2 = "10000743V-V", ["vcmpgtsh._3"] = "10000746VVV", vsubsws_3 = "10000780VVV", vclzw_2 = "10000782V-V", vpopcntw_2 = "10000783V-V", ["vcmpgtsw._3"] = "10000786VVV", vsumsws_3 = "10000788VVV", vmrgew_3 = "1000078cVVV", vclzd_2 = "100007c2V-V", vpopcntd_2 = "100007c3V-V", ["vcmpbfp._3"] = "100007c6VVV", ["vcmpgtsd._3"] = "100007c7VVV", -- Primary opcode 19: mcrf_2 = "4c000000XX", isync_0 = "4c00012c", crnor_3 = "4c000042CCC", crnot_2 = "4c000042CC=", crandc_3 = "4c000102CCC", crxor_3 = "4c000182CCC", crclr_1 = "4c000182C==", crnand_3 = "4c0001c2CCC", crand_3 = "4c000202CCC", creqv_3 = "4c000242CCC", crset_1 = "4c000242C==", crorc_3 = "4c000342CCC", cror_3 = "4c000382CCC", crmove_2 = "4c000382CC=", bclr_2 = "4c000020AA", bclrl_2 = "4c000021AA", bcctr_2 = "4c000420AA", bcctrl_2 = "4c000421AA", bctar_2 = "4c000460AA", bctarl_2 = "4c000461AA", blr_0 = "4e800020", blrl_0 = "4e800021", bctr_0 = "4e800420", bctrl_0 = "4e800421", -- Primary opcode 31: cmpw_3 = "7c000000XRR", cmpw_2 = "7c000000-RR", cmpd_3 = "7c200000XRR", cmpd_2 = "7c200000-RR", tw_3 = "7c000008ARR", lvsl_3 = "7c00000cVRR", subfc_3 = "7c000010RRR.", subc_3 = "7c000010RRR~.", mulhdu_3 = "7c000012RRR.", addc_3 = "7c000014RRR.", mulhwu_3 = "7c000016RRR.", isel_4 = "7c00001eRRRC", isellt_3 = "7c00001eRRR", iselgt_3 = "7c00005eRRR", iseleq_3 = "7c00009eRRR", mfcr_1 = "7c000026R", mfocrf_2 = "7c100026RG", mtcrf_2 = "7c000120GR", mtocrf_2 = "7c100120GR", lwarx_3 = "7c000028RR0R", ldx_3 = "7c00002aRR0R", lwzx_3 = "7c00002eRR0R", slw_3 = "7c000030RR~R.", cntlzw_2 = "7c000034RR~", sld_3 = "7c000036RR~R.", and_3 = "7c000038RR~R.", cmplw_3 = "7c000040XRR", cmplw_2 = "7c000040-RR", cmpld_3 = "7c200040XRR", cmpld_2 = "7c200040-RR", lvsr_3 = "7c00004cVRR", subf_3 = "7c000050RRR.", sub_3 = "7c000050RRR~.", lbarx_3 = "7c000068RR0R", ldux_3 = "7c00006aRR0R", dcbst_2 = "7c00006c-RR", lwzux_3 = "7c00006eRR0R", cntlzd_2 = "7c000074RR~", andc_3 = "7c000078RR~R.", td_3 = "7c000088ARR", lvewx_3 = "7c00008eVRR", mulhd_3 = "7c000092RRR.", addg6s_3 = "7c000094RRR", mulhw_3 = "7c000096RRR.", dlmzb_3 = "7c00009cRR~R.", ldarx_3 = "7c0000a8RR0R", dcbf_2 = "7c0000ac-RR", lbzx_3 = "7c0000aeRR0R", lvx_3 = "7c0000ceVRR", neg_2 = "7c0000d0RR.", lharx_3 = "7c0000e8RR0R", lbzux_3 = "7c0000eeRR0R", popcntb_2 = "7c0000f4RR~", not_2 = "7c0000f8RR~%.", nor_3 = "7c0000f8RR~R.", stvebx_3 = "7c00010eVRR", subfe_3 = "7c000110RRR.", sube_3 = "7c000110RRR~.", adde_3 = "7c000114RRR.", stdx_3 = "7c00012aRR0R", ["stwcx._3"] = "7c00012dRR0R.", stwx_3 = "7c00012eRR0R", prtyw_2 = "7c000134RR~", stvehx_3 = "7c00014eVRR", stdux_3 = "7c00016aRR0R", ["stqcx._3"] = "7c00016dR:R0R.", stwux_3 = "7c00016eRR0R", prtyd_2 = "7c000174RR~", stvewx_3 = "7c00018eVRR", subfze_2 = "7c000190RR.", addze_2 = "7c000194RR.", ["stdcx._3"] = "7c0001adRR0R.", stbx_3 = "7c0001aeRR0R", stvx_3 = "7c0001ceVRR", subfme_2 = "7c0001d0RR.", mulld_3 = "7c0001d2RRR.", addme_2 = "7c0001d4RR.", mullw_3 = "7c0001d6RRR.", dcbtst_2 = "7c0001ec-RR", stbux_3 = "7c0001eeRR0R", bpermd_3 = "7c0001f8RR~R", lvepxl_3 = "7c00020eVRR", add_3 = "7c000214RRR.", lqarx_3 = "7c000228R:R0R", dcbt_2 = "7c00022c-RR", lhzx_3 = "7c00022eRR0R", cdtbcd_2 = "7c000234RR~", eqv_3 = "7c000238RR~R.", lvepx_3 = "7c00024eVRR", eciwx_3 = "7c00026cRR0R", lhzux_3 = "7c00026eRR0R", cbcdtd_2 = "7c000274RR~", xor_3 = "7c000278RR~R.", mfspefscr_1 = "7c0082a6R", mfxer_1 = "7c0102a6R", mflr_1 = "7c0802a6R", mfctr_1 = "7c0902a6R", lwax_3 = "7c0002aaRR0R", lhax_3 = "7c0002aeRR0R", mftb_1 = "7c0c42e6R", mftbu_1 = "7c0d42e6R", lvxl_3 = "7c0002ceVRR", lwaux_3 = "7c0002eaRR0R", lhaux_3 = "7c0002eeRR0R", popcntw_2 = "7c0002f4RR~", divdeu_3 = "7c000312RRR.", divweu_3 = "7c000316RRR.", sthx_3 = "7c00032eRR0R", orc_3 = "7c000338RR~R.", ecowx_3 = "7c00036cRR0R", sthux_3 = "7c00036eRR0R", or_3 = "7c000378RR~R.", mr_2 = "7c000378RR~%.", divdu_3 = "7c000392RRR.", divwu_3 = "7c000396RRR.", mtspefscr_1 = "7c0083a6R", mtxer_1 = "7c0103a6R", mtlr_1 = "7c0803a6R", mtctr_1 = "7c0903a6R", dcbi_2 = "7c0003ac-RR", nand_3 = "7c0003b8RR~R.", dsn_2 = "7c0003c6-RR", stvxl_3 = "7c0003ceVRR", divd_3 = "7c0003d2RRR.", divw_3 = "7c0003d6RRR.", popcntd_2 = "7c0003f4RR~", cmpb_3 = "7c0003f8RR~R.", mcrxr_1 = "7c000400X", lbdx_3 = "7c000406RRR", subfco_3 = "7c000410RRR.", subco_3 = "7c000410RRR~.", addco_3 = "7c000414RRR.", ldbrx_3 = "7c000428RR0R", lswx_3 = "7c00042aRR0R", lwbrx_3 = "7c00042cRR0R", lfsx_3 = "7c00042eFR0R", srw_3 = "7c000430RR~R.", srd_3 = "7c000436RR~R.", lhdx_3 = "7c000446RRR", subfo_3 = "7c000450RRR.", subo_3 = "7c000450RRR~.", lfsux_3 = "7c00046eFR0R", lwdx_3 = "7c000486RRR", lswi_3 = "7c0004aaRR0A", sync_0 = "7c0004ac", lwsync_0 = "7c2004ac", ptesync_0 = "7c4004ac", lfdx_3 = "7c0004aeFR0R", lddx_3 = "7c0004c6RRR", nego_2 = "7c0004d0RR.", lfdux_3 = "7c0004eeFR0R", stbdx_3 = "7c000506RRR", subfeo_3 = "7c000510RRR.", subeo_3 = "7c000510RRR~.", addeo_3 = "7c000514RRR.", stdbrx_3 = "7c000528RR0R", stswx_3 = "7c00052aRR0R", stwbrx_3 = "7c00052cRR0R", stfsx_3 = "7c00052eFR0R", sthdx_3 = "7c000546RRR", ["stbcx._3"] = "7c00056dRRR", stfsux_3 = "7c00056eFR0R", stwdx_3 = "7c000586RRR", subfzeo_2 = "7c000590RR.", addzeo_2 = "7c000594RR.", stswi_3 = "7c0005aaRR0A", ["sthcx._3"] = "7c0005adRRR", stfdx_3 = "7c0005aeFR0R", stddx_3 = "7c0005c6RRR", subfmeo_2 = "7c0005d0RR.", mulldo_3 = "7c0005d2RRR.", addmeo_2 = "7c0005d4RR.", mullwo_3 = "7c0005d6RRR.", dcba_2 = "7c0005ec-RR", stfdux_3 = "7c0005eeFR0R", stvepxl_3 = "7c00060eVRR", addo_3 = "7c000614RRR.", lhbrx_3 = "7c00062cRR0R", lfdpx_3 = "7c00062eF:RR", sraw_3 = "7c000630RR~R.", srad_3 = "7c000634RR~R.", lfddx_3 = "7c000646FRR", stvepx_3 = "7c00064eVRR", srawi_3 = "7c000670RR~A.", sradi_3 = "7c000674RR~H.", eieio_0 = "7c0006ac", lfiwax_3 = "7c0006aeFR0R", divdeuo_3 = "7c000712RRR.", divweuo_3 = "7c000716RRR.", sthbrx_3 = "7c00072cRR0R", stfdpx_3 = "7c00072eF:RR", extsh_2 = "7c000734RR~.", stfddx_3 = "7c000746FRR", divdeo_3 = "7c000752RRR.", divweo_3 = "7c000756RRR.", extsb_2 = "7c000774RR~.", divduo_3 = "7c000792RRR.", divwou_3 = "7c000796RRR.", icbi_2 = "7c0007ac-RR", stfiwx_3 = "7c0007aeFR0R", extsw_2 = "7c0007b4RR~.", divdo_3 = "7c0007d2RRR.", divwo_3 = "7c0007d6RRR.", dcbz_2 = "7c0007ec-RR", ["tbegin._1"] = "7c00051d1", ["tbegin._0"] = "7c00051d", ["tend._1"] = "7c00055dY", ["tend._0"] = "7c00055d", ["tendall._0"] = "7e00055d", tcheck_1 = "7c00059cX", ["tsr._1"] = "7c0005dd1", ["tsuspend._0"] = "7c0005dd", ["tresume._0"] = "7c2005dd", ["tabortwc._3"] = "7c00061dARR", ["tabortdc._3"] = "7c00065dARR", ["tabortwci._3"] = "7c00069dARS", ["tabortdci._3"] = "7c0006ddARS", ["tabort._1"] = "7c00071d-R-", ["treclaim._1"] = "7c00075d-R", ["trechkpt._0"] = "7c0007dd", lxsiwzx_3 = "7c000018QRR", lxsiwax_3 = "7c000098QRR", mfvsrd_2 = "7c000066-Rq", mfvsrwz_2 = "7c0000e6-Rq", stxsiwx_3 = "7c000118QRR", mtvsrd_2 = "7c000166QR", mtvsrwa_2 = "7c0001a6QR", lxvdsx_3 = "7c000298QRR", lxsspx_3 = "7c000418QRR", lxsdx_3 = "7c000498QRR", stxsspx_3 = "7c000518QRR", stxsdx_3 = "7c000598QRR", lxvw4x_3 = "7c000618QRR", lxvd2x_3 = "7c000698QRR", stxvw4x_3 = "7c000718QRR", stxvd2x_3 = "7c000798QRR", -- Primary opcode 30: rldicl_4 = "78000000RR~HM.", rldicr_4 = "78000004RR~HM.", rldic_4 = "78000008RR~HM.", rldimi_4 = "7800000cRR~HM.", rldcl_4 = "78000010RR~RM.", rldcr_4 = "78000012RR~RM.", rotldi_3 = op_alias("rldicl_4", function(p) p[4] = "0" end), rotrdi_3 = op_alias("rldicl_4", function(p) p[3] = "64-("..p[3]..")"; p[4] = "0" end), rotld_3 = op_alias("rldcl_4", function(p) p[4] = "0" end), sldi_3 = op_alias("rldicr_4", function(p) p[4] = "63-("..p[3]..")" end), srdi_3 = op_alias("rldicl_4", function(p) p[4] = p[3]; p[3] = "64-("..p[3]..")" end), clrldi_3 = op_alias("rldicl_4", function(p) p[4] = p[3]; p[3] = "0" end), clrrdi_3 = op_alias("rldicr_4", function(p) p[4] = "63-("..p[3]..")"; p[3] = "0" end), -- Primary opcode 56: lq_2 = "e0000000R:D", -- NYI: displacement must be divisible by 8. -- Primary opcode 57: lfdp_2 = "e4000000F:D", -- NYI: displacement must be divisible by 4. -- Primary opcode 59: fdivs_3 = "ec000024FFF.", fsubs_3 = "ec000028FFF.", fadds_3 = "ec00002aFFF.", fsqrts_2 = "ec00002cF-F.", fres_2 = "ec000030F-F.", fmuls_3 = "ec000032FF-F.", frsqrtes_2 = "ec000034F-F.", fmsubs_4 = "ec000038FFFF~.", fmadds_4 = "ec00003aFFFF~.", fnmsubs_4 = "ec00003cFFFF~.", fnmadds_4 = "ec00003eFFFF~.", fcfids_2 = "ec00069cF-F.", fcfidus_2 = "ec00079cF-F.", dadd_3 = "ec000004FFF.", dqua_4 = "ec000006FFFZ.", dmul_3 = "ec000044FFF.", drrnd_4 = "ec000046FFFZ.", dscli_3 = "ec000084FF6.", dquai_4 = "ec000086SF~FZ.", dscri_3 = "ec0000c4FF6.", drintx_4 = "ec0000c61F~FZ.", dcmpo_3 = "ec000104XFF", dtstex_3 = "ec000144XFF", dtstdc_3 = "ec000184XF6", dtstdg_3 = "ec0001c4XF6", drintn_4 = "ec0001c61F~FZ.", dctdp_2 = "ec000204F-F.", dctfix_2 = "ec000244F-F.", ddedpd_3 = "ec000284ZF~F.", dxex_2 = "ec0002c4F-F.", dsub_3 = "ec000404FFF.", ddiv_3 = "ec000444FFF.", dcmpu_3 = "ec000504XFF", dtstsf_3 = "ec000544XFF", drsp_2 = "ec000604F-F.", dcffix_2 = "ec000644F-F.", denbcd_3 = "ec000684YF~F.", diex_3 = "ec0006c4FFF.", -- Primary opcode 60: xsaddsp_3 = "f0000000QQQ", xsmaddasp_3 = "f0000008QQQ", xxsldwi_4 = "f0000010QQQz", xsrsqrtesp_2 = "f0000028Q-Q", xssqrtsp_2 = "f000002cQ-Q", xxsel_4 = "f0000030QQQQ", xssubsp_3 = "f0000040QQQ", xsmaddmsp_3 = "f0000048QQQ", xxpermdi_4 = "f0000050QQQz", xsresp_2 = "f0000068Q-Q", xsmulsp_3 = "f0000080QQQ", xsmsubasp_3 = "f0000088QQQ", xxmrghw_3 = "f0000090QQQ", xsdivsp_3 = "f00000c0QQQ", xsmsubmsp_3 = "f00000c8QQQ", xsadddp_3 = "f0000100QQQ", xsmaddadp_3 = "f0000108QQQ", xscmpudp_3 = "f0000118XQQ", xscvdpuxws_2 = "f0000120Q-Q", xsrdpi_2 = "f0000124Q-Q", xsrsqrtedp_2 = "f0000128Q-Q", xssqrtdp_2 = "f000012cQ-Q", xssubdp_3 = "f0000140QQQ", xsmaddmdp_3 = "f0000148QQQ", xscmpodp_3 = "f0000158XQQ", xscvdpsxws_2 = "f0000160Q-Q", xsrdpiz_2 = "f0000164Q-Q", xsredp_2 = "f0000168Q-Q", xsmuldp_3 = "f0000180QQQ", xsmsubadp_3 = "f0000188QQQ", xxmrglw_3 = "f0000190QQQ", xsrdpip_2 = "f00001a4Q-Q", xstsqrtdp_2 = "f00001a8X-Q", xsrdpic_2 = "f00001acQ-Q", xsdivdp_3 = "f00001c0QQQ", xsmsubmdp_3 = "f00001c8QQQ", xsrdpim_2 = "f00001e4Q-Q", xstdivdp_3 = "f00001e8XQQ", xvaddsp_3 = "f0000200QQQ", xvmaddasp_3 = "f0000208QQQ", xvcmpeqsp_3 = "f0000218QQQ", xvcvspuxws_2 = "f0000220Q-Q", xvrspi_2 = "f0000224Q-Q", xvrsqrtesp_2 = "f0000228Q-Q", xvsqrtsp_2 = "f000022cQ-Q", xvsubsp_3 = "f0000240QQQ", xvmaddmsp_3 = "f0000248QQQ", xvcmpgtsp_3 = "f0000258QQQ", xvcvspsxws_2 = "f0000260Q-Q", xvrspiz_2 = "f0000264Q-Q", xvresp_2 = "f0000268Q-Q", xvmulsp_3 = "f0000280QQQ", xvmsubasp_3 = "f0000288QQQ", xxspltw_3 = "f0000290QQg~", xvcmpgesp_3 = "f0000298QQQ", xvcvuxwsp_2 = "f00002a0Q-Q", xvrspip_2 = "f00002a4Q-Q", xvtsqrtsp_2 = "f00002a8X-Q", xvrspic_2 = "f00002acQ-Q", xvdivsp_3 = "f00002c0QQQ", xvmsubmsp_3 = "f00002c8QQQ", xvcvsxwsp_2 = "f00002e0Q-Q", xvrspim_2 = "f00002e4Q-Q", xvtdivsp_3 = "f00002e8XQQ", xvadddp_3 = "f0000300QQQ", xvmaddadp_3 = "f0000308QQQ", xvcmpeqdp_3 = "f0000318QQQ", xvcvdpuxws_2 = "f0000320Q-Q", xvrdpi_2 = "f0000324Q-Q", xvrsqrtedp_2 = "f0000328Q-Q", xvsqrtdp_2 = "f000032cQ-Q", xvsubdp_3 = "f0000340QQQ", xvmaddmdp_3 = "f0000348QQQ", xvcmpgtdp_3 = "f0000358QQQ", xvcvdpsxws_2 = "f0000360Q-Q", xvrdpiz_2 = "f0000364Q-Q", xvredp_2 = "f0000368Q-Q", xvmuldp_3 = "f0000380QQQ", xvmsubadp_3 = "f0000388QQQ", xvcmpgedp_3 = "f0000398QQQ", xvcvuxwdp_2 = "f00003a0Q-Q", xvrdpip_2 = "f00003a4Q-Q", xvtsqrtdp_2 = "f00003a8X-Q", xvrdpic_2 = "f00003acQ-Q", xvdivdp_3 = "f00003c0QQQ", xvmsubmdp_3 = "f00003c8QQQ", xvcvsxwdp_2 = "f00003e0Q-Q", xvrdpim_2 = "f00003e4Q-Q", xvtdivdp_3 = "f00003e8XQQ", xsnmaddasp_3 = "f0000408QQQ", xxland_3 = "f0000410QQQ", xscvdpsp_2 = "f0000424Q-Q", xscvdpspn_2 = "f000042cQ-Q", xsnmaddmsp_3 = "f0000448QQQ", xxlandc_3 = "f0000450QQQ", xsrsp_2 = "f0000464Q-Q", xsnmsubasp_3 = "f0000488QQQ", xxlor_3 = "f0000490QQQ", xscvuxdsp_2 = "f00004a0Q-Q", xsnmsubmsp_3 = "f00004c8QQQ", xxlxor_3 = "f00004d0QQQ", xscvsxdsp_2 = "f00004e0Q-Q", xsmaxdp_3 = "f0000500QQQ", xsnmaddadp_3 = "f0000508QQQ", xxlnor_3 = "f0000510QQQ", xscvdpuxds_2 = "f0000520Q-Q", xscvspdp_2 = "f0000524Q-Q", xscvspdpn_2 = "f000052cQ-Q", xsmindp_3 = "f0000540QQQ", xsnmaddmdp_3 = "f0000548QQQ", xxlorc_3 = "f0000550QQQ", xscvdpsxds_2 = "f0000560Q-Q", xsabsdp_2 = "f0000564Q-Q", xscpsgndp_3 = "f0000580QQQ", xsnmsubadp_3 = "f0000588QQQ", xxlnand_3 = "f0000590QQQ", xscvuxddp_2 = "f00005a0Q-Q", xsnabsdp_2 = "f00005a4Q-Q", xsnmsubmdp_3 = "f00005c8QQQ", xxleqv_3 = "f00005d0QQQ", xscvsxddp_2 = "f00005e0Q-Q", xsnegdp_2 = "f00005e4Q-Q", xvmaxsp_3 = "f0000600QQQ", xvnmaddasp_3 = "f0000608QQQ", ["xvcmpeqsp._3"] = "f0000618QQQ", xvcvspuxds_2 = "f0000620Q-Q", xvcvdpsp_2 = "f0000624Q-Q", xvminsp_3 = "f0000640QQQ", xvnmaddmsp_3 = "f0000648QQQ", ["xvcmpgtsp._3"] = "f0000658QQQ", xvcvspsxds_2 = "f0000660Q-Q", xvabssp_2 = "f0000664Q-Q", xvcpsgnsp_3 = "f0000680QQQ", xvnmsubasp_3 = "f0000688QQQ", ["xvcmpgesp._3"] = "f0000698QQQ", xvcvuxdsp_2 = "f00006a0Q-Q", xvnabssp_2 = "f00006a4Q-Q", xvnmsubmsp_3 = "f00006c8QQQ", xvcvsxdsp_2 = "f00006e0Q-Q", xvnegsp_2 = "f00006e4Q-Q", xvmaxdp_3 = "f0000700QQQ", xvnmaddadp_3 = "f0000708QQQ", ["xvcmpeqdp._3"] = "f0000718QQQ", xvcvdpuxds_2 = "f0000720Q-Q", xvcvspdp_2 = "f0000724Q-Q", xvmindp_3 = "f0000740QQQ", xvnmaddmdp_3 = "f0000748QQQ", ["xvcmpgtdp._3"] = "f0000758QQQ", xvcvdpsxds_2 = "f0000760Q-Q", xvabsdp_2 = "f0000764Q-Q", xvcpsgndp_3 = "f0000780QQQ", xvnmsubadp_3 = "f0000788QQQ", ["xvcmpgedp._3"] = "f0000798QQQ", xvcvuxddp_2 = "f00007a0Q-Q", xvnabsdp_2 = "f00007a4Q-Q", xvnmsubmdp_3 = "f00007c8QQQ", xvcvsxddp_2 = "f00007e0Q-Q", xvnegdp_2 = "f00007e4Q-Q", -- Primary opcode 61: stfdp_2 = "f4000000F:D", -- NYI: displacement must be divisible by 4. -- Primary opcode 62: stq_2 = "f8000002R:D", -- NYI: displacement must be divisible by 8. -- Primary opcode 63: fdiv_3 = "fc000024FFF.", fsub_3 = "fc000028FFF.", fadd_3 = "fc00002aFFF.", fsqrt_2 = "fc00002cF-F.", fsel_4 = "fc00002eFFFF~.", fre_2 = "fc000030F-F.", fmul_3 = "fc000032FF-F.", frsqrte_2 = "fc000034F-F.", fmsub_4 = "fc000038FFFF~.", fmadd_4 = "fc00003aFFFF~.", fnmsub_4 = "fc00003cFFFF~.", fnmadd_4 = "fc00003eFFFF~.", fcmpu_3 = "fc000000XFF", fcpsgn_3 = "fc000010FFF.", fcmpo_3 = "fc000040XFF", mtfsb1_1 = "fc00004cA", fneg_2 = "fc000050F-F.", mcrfs_2 = "fc000080XX", mtfsb0_1 = "fc00008cA", fmr_2 = "fc000090F-F.", frsp_2 = "fc000018F-F.", fctiw_2 = "fc00001cF-F.", fctiwz_2 = "fc00001eF-F.", ftdiv_2 = "fc000100X-F.", fctiwu_2 = "fc00011cF-F.", fctiwuz_2 = "fc00011eF-F.", mtfsfi_2 = "fc00010cAA", -- NYI: upshift. fnabs_2 = "fc000110F-F.", ftsqrt_2 = "fc000140X-F.", fabs_2 = "fc000210F-F.", frin_2 = "fc000310F-F.", friz_2 = "fc000350F-F.", frip_2 = "fc000390F-F.", frim_2 = "fc0003d0F-F.", mffs_1 = "fc00048eF.", -- NYI: mtfsf, mtfsb0, mtfsb1. fctid_2 = "fc00065cF-F.", fctidz_2 = "fc00065eF-F.", fmrgow_3 = "fc00068cFFF", fcfid_2 = "fc00069cF-F.", fctidu_2 = "fc00075cF-F.", fctiduz_2 = "fc00075eF-F.", fmrgew_3 = "fc00078cFFF", fcfidu_2 = "fc00079cF-F.", daddq_3 = "fc000004F:F:F:.", dquaq_4 = "fc000006F:F:F:Z.", dmulq_3 = "fc000044F:F:F:.", drrndq_4 = "fc000046F:F:F:Z.", dscliq_3 = "fc000084F:F:6.", dquaiq_4 = "fc000086SF:~F:Z.", dscriq_3 = "fc0000c4F:F:6.", drintxq_4 = "fc0000c61F:~F:Z.", dcmpoq_3 = "fc000104XF:F:", dtstexq_3 = "fc000144XF:F:", dtstdcq_3 = "fc000184XF:6", dtstdgq_3 = "fc0001c4XF:6", drintnq_4 = "fc0001c61F:~F:Z.", dctqpq_2 = "fc000204F:-F:.", dctfixq_2 = "fc000244F:-F:.", ddedpdq_3 = "fc000284ZF:~F:.", dxexq_2 = "fc0002c4F:-F:.", dsubq_3 = "fc000404F:F:F:.", ddivq_3 = "fc000444F:F:F:.", dcmpuq_3 = "fc000504XF:F:", dtstsfq_3 = "fc000544XF:F:", drdpq_2 = "fc000604F:-F:.", dcffixq_2 = "fc000644F:-F:.", denbcdq_3 = "fc000684YF:~F:.", diexq_3 = "fc0006c4F:FF:.", -- Primary opcode 4, SPE APU extension: evaddw_3 = "10000200RRR", evaddiw_3 = "10000202RAR~", evsubw_3 = "10000204RRR~", evsubiw_3 = "10000206RAR~", evabs_2 = "10000208RR", evneg_2 = "10000209RR", evextsb_2 = "1000020aRR", evextsh_2 = "1000020bRR", evrndw_2 = "1000020cRR", evcntlzw_2 = "1000020dRR", evcntlsw_2 = "1000020eRR", brinc_3 = "1000020fRRR", evand_3 = "10000211RRR", evandc_3 = "10000212RRR", evxor_3 = "10000216RRR", evor_3 = "10000217RRR", evmr_2 = "10000217RR=", evnor_3 = "10000218RRR", evnot_2 = "10000218RR=", eveqv_3 = "10000219RRR", evorc_3 = "1000021bRRR", evnand_3 = "1000021eRRR", evsrwu_3 = "10000220RRR", evsrws_3 = "10000221RRR", evsrwiu_3 = "10000222RRA", evsrwis_3 = "10000223RRA", evslw_3 = "10000224RRR", evslwi_3 = "10000226RRA", evrlw_3 = "10000228RRR", evsplati_2 = "10000229RS", evrlwi_3 = "1000022aRRA", evsplatfi_2 = "1000022bRS", evmergehi_3 = "1000022cRRR", evmergelo_3 = "1000022dRRR", evcmpgtu_3 = "10000230XRR", evcmpgtu_2 = "10000230-RR", evcmpgts_3 = "10000231XRR", evcmpgts_2 = "10000231-RR", evcmpltu_3 = "10000232XRR", evcmpltu_2 = "10000232-RR", evcmplts_3 = "10000233XRR", evcmplts_2 = "10000233-RR", evcmpeq_3 = "10000234XRR", evcmpeq_2 = "10000234-RR", evsel_4 = "10000278RRRW", evsel_3 = "10000278RRR", evfsadd_3 = "10000280RRR", evfssub_3 = "10000281RRR", evfsabs_2 = "10000284RR", evfsnabs_2 = "10000285RR", evfsneg_2 = "10000286RR", evfsmul_3 = "10000288RRR", evfsdiv_3 = "10000289RRR", evfscmpgt_3 = "1000028cXRR", evfscmpgt_2 = "1000028c-RR", evfscmplt_3 = "1000028dXRR", evfscmplt_2 = "1000028d-RR", evfscmpeq_3 = "1000028eXRR", evfscmpeq_2 = "1000028e-RR", evfscfui_2 = "10000290R-R", evfscfsi_2 = "10000291R-R", evfscfuf_2 = "10000292R-R", evfscfsf_2 = "10000293R-R", evfsctui_2 = "10000294R-R", evfsctsi_2 = "10000295R-R", evfsctuf_2 = "10000296R-R", evfsctsf_2 = "10000297R-R", evfsctuiz_2 = "10000298R-R", evfsctsiz_2 = "1000029aR-R", evfststgt_3 = "1000029cXRR", evfststgt_2 = "1000029c-RR", evfststlt_3 = "1000029dXRR", evfststlt_2 = "1000029d-RR", evfststeq_3 = "1000029eXRR", evfststeq_2 = "1000029e-RR", efsadd_3 = "100002c0RRR", efssub_3 = "100002c1RRR", efsabs_2 = "100002c4RR", efsnabs_2 = "100002c5RR", efsneg_2 = "100002c6RR", efsmul_3 = "100002c8RRR", efsdiv_3 = "100002c9RRR", efscmpgt_3 = "100002ccXRR", efscmpgt_2 = "100002cc-RR", efscmplt_3 = "100002cdXRR", efscmplt_2 = "100002cd-RR", efscmpeq_3 = "100002ceXRR", efscmpeq_2 = "100002ce-RR", efscfd_2 = "100002cfR-R", efscfui_2 = "100002d0R-R", efscfsi_2 = "100002d1R-R", efscfuf_2 = "100002d2R-R", efscfsf_2 = "100002d3R-R", efsctui_2 = "100002d4R-R", efsctsi_2 = "100002d5R-R", efsctuf_2 = "100002d6R-R", efsctsf_2 = "100002d7R-R", efsctuiz_2 = "100002d8R-R", efsctsiz_2 = "100002daR-R", efststgt_3 = "100002dcXRR", efststgt_2 = "100002dc-RR", efststlt_3 = "100002ddXRR", efststlt_2 = "100002dd-RR", efststeq_3 = "100002deXRR", efststeq_2 = "100002de-RR", efdadd_3 = "100002e0RRR", efdsub_3 = "100002e1RRR", efdcfuid_2 = "100002e2R-R", efdcfsid_2 = "100002e3R-R", efdabs_2 = "100002e4RR", efdnabs_2 = "100002e5RR", efdneg_2 = "100002e6RR", efdmul_3 = "100002e8RRR", efddiv_3 = "100002e9RRR", efdctuidz_2 = "100002eaR-R", efdctsidz_2 = "100002ebR-R", efdcmpgt_3 = "100002ecXRR", efdcmpgt_2 = "100002ec-RR", efdcmplt_3 = "100002edXRR", efdcmplt_2 = "100002ed-RR", efdcmpeq_3 = "100002eeXRR", efdcmpeq_2 = "100002ee-RR", efdcfs_2 = "100002efR-R", efdcfui_2 = "100002f0R-R", efdcfsi_2 = "100002f1R-R", efdcfuf_2 = "100002f2R-R", efdcfsf_2 = "100002f3R-R", efdctui_2 = "100002f4R-R", efdctsi_2 = "100002f5R-R", efdctuf_2 = "100002f6R-R", efdctsf_2 = "100002f7R-R", efdctuiz_2 = "100002f8R-R", efdctsiz_2 = "100002faR-R", efdtstgt_3 = "100002fcXRR", efdtstgt_2 = "100002fc-RR", efdtstlt_3 = "100002fdXRR", efdtstlt_2 = "100002fd-RR", efdtsteq_3 = "100002feXRR", efdtsteq_2 = "100002fe-RR", evlddx_3 = "10000300RR0R", evldd_2 = "10000301R8", evldwx_3 = "10000302RR0R", evldw_2 = "10000303R8", evldhx_3 = "10000304RR0R", evldh_2 = "10000305R8", evlwhex_3 = "10000310RR0R", evlwhe_2 = "10000311R4", evlwhoux_3 = "10000314RR0R", evlwhou_2 = "10000315R4", evlwhosx_3 = "10000316RR0R", evlwhos_2 = "10000317R4", evstddx_3 = "10000320RR0R", evstdd_2 = "10000321R8", evstdwx_3 = "10000322RR0R", evstdw_2 = "10000323R8", evstdhx_3 = "10000324RR0R", evstdh_2 = "10000325R8", evstwhex_3 = "10000330RR0R", evstwhe_2 = "10000331R4", evstwhox_3 = "10000334RR0R", evstwho_2 = "10000335R4", evstwwex_3 = "10000338RR0R", evstwwe_2 = "10000339R4", evstwwox_3 = "1000033cRR0R", evstwwo_2 = "1000033dR4", evmhessf_3 = "10000403RRR", evmhossf_3 = "10000407RRR", evmheumi_3 = "10000408RRR", evmhesmi_3 = "10000409RRR", evmhesmf_3 = "1000040bRRR", evmhoumi_3 = "1000040cRRR", evmhosmi_3 = "1000040dRRR", evmhosmf_3 = "1000040fRRR", evmhessfa_3 = "10000423RRR", evmhossfa_3 = "10000427RRR", evmheumia_3 = "10000428RRR", evmhesmia_3 = "10000429RRR", evmhesmfa_3 = "1000042bRRR", evmhoumia_3 = "1000042cRRR", evmhosmia_3 = "1000042dRRR", evmhosmfa_3 = "1000042fRRR", evmwhssf_3 = "10000447RRR", evmwlumi_3 = "10000448RRR", evmwhumi_3 = "1000044cRRR", evmwhsmi_3 = "1000044dRRR", evmwhsmf_3 = "1000044fRRR", evmwssf_3 = "10000453RRR", evmwumi_3 = "10000458RRR", evmwsmi_3 = "10000459RRR", evmwsmf_3 = "1000045bRRR", evmwhssfa_3 = "10000467RRR", evmwlumia_3 = "10000468RRR", evmwhumia_3 = "1000046cRRR", evmwhsmia_3 = "1000046dRRR", evmwhsmfa_3 = "1000046fRRR", evmwssfa_3 = "10000473RRR", evmwumia_3 = "10000478RRR", evmwsmia_3 = "10000479RRR", evmwsmfa_3 = "1000047bRRR", evmra_2 = "100004c4RR", evdivws_3 = "100004c6RRR", evdivwu_3 = "100004c7RRR", evmwssfaa_3 = "10000553RRR", evmwumiaa_3 = "10000558RRR", evmwsmiaa_3 = "10000559RRR", evmwsmfaa_3 = "1000055bRRR", evmwssfan_3 = "100005d3RRR", evmwumian_3 = "100005d8RRR", evmwsmian_3 = "100005d9RRR", evmwsmfan_3 = "100005dbRRR", evmergehilo_3 = "1000022eRRR", evmergelohi_3 = "1000022fRRR", evlhhesplatx_3 = "10000308RR0R", evlhhesplat_2 = "10000309R2", evlhhousplatx_3 = "1000030cRR0R", evlhhousplat_2 = "1000030dR2", evlhhossplatx_3 = "1000030eRR0R", evlhhossplat_2 = "1000030fR2", evlwwsplatx_3 = "10000318RR0R", evlwwsplat_2 = "10000319R4", evlwhsplatx_3 = "1000031cRR0R", evlwhsplat_2 = "1000031dR4", evaddusiaaw_2 = "100004c0RR", evaddssiaaw_2 = "100004c1RR", evsubfusiaaw_2 = "100004c2RR", evsubfssiaaw_2 = "100004c3RR", evaddumiaaw_2 = "100004c8RR", evaddsmiaaw_2 = "100004c9RR", evsubfumiaaw_2 = "100004caRR", evsubfsmiaaw_2 = "100004cbRR", evmheusiaaw_3 = "10000500RRR", evmhessiaaw_3 = "10000501RRR", evmhessfaaw_3 = "10000503RRR", evmhousiaaw_3 = "10000504RRR", evmhossiaaw_3 = "10000505RRR", evmhossfaaw_3 = "10000507RRR", evmheumiaaw_3 = "10000508RRR", evmhesmiaaw_3 = "10000509RRR", evmhesmfaaw_3 = "1000050bRRR", evmhoumiaaw_3 = "1000050cRRR", evmhosmiaaw_3 = "1000050dRRR", evmhosmfaaw_3 = "1000050fRRR", evmhegumiaa_3 = "10000528RRR", evmhegsmiaa_3 = "10000529RRR", evmhegsmfaa_3 = "1000052bRRR", evmhogumiaa_3 = "1000052cRRR", evmhogsmiaa_3 = "1000052dRRR", evmhogsmfaa_3 = "1000052fRRR", evmwlusiaaw_3 = "10000540RRR", evmwlssiaaw_3 = "10000541RRR", evmwlumiaaw_3 = "10000548RRR", evmwlsmiaaw_3 = "10000549RRR", evmheusianw_3 = "10000580RRR", evmhessianw_3 = "10000581RRR", evmhessfanw_3 = "10000583RRR", evmhousianw_3 = "10000584RRR", evmhossianw_3 = "10000585RRR", evmhossfanw_3 = "10000587RRR", evmheumianw_3 = "10000588RRR", evmhesmianw_3 = "10000589RRR", evmhesmfanw_3 = "1000058bRRR", evmhoumianw_3 = "1000058cRRR", evmhosmianw_3 = "1000058dRRR", evmhosmfanw_3 = "1000058fRRR", evmhegumian_3 = "100005a8RRR", evmhegsmian_3 = "100005a9RRR", evmhegsmfan_3 = "100005abRRR", evmhogumian_3 = "100005acRRR", evmhogsmian_3 = "100005adRRR", evmhogsmfan_3 = "100005afRRR", evmwlusianw_3 = "100005c0RRR", evmwlssianw_3 = "100005c1RRR", evmwlumianw_3 = "100005c8RRR", evmwlsmianw_3 = "100005c9RRR", -- NYI: Book E instructions. } -- Add mnemonics for "." variants. do local t = {} for k,v in pairs(map_op) do if type(v) == "string" and sub(v, -1) == "." then local v2 = sub(v, 1, 7)..char(byte(v, 8)+1)..sub(v, 9, -2) t[sub(k, 1, -3).."."..sub(k, -2)] = v2 end end for k,v in pairs(t) do map_op[k] = v end end -- Add more branch mnemonics. for cond,c in pairs(map_cond) do local b1 = "b"..cond local c1 = shl(band(c, 3), 16) + (c < 4 and 0x01000000 or 0) -- bX[l] map_op[b1.."_1"] = tohex(0x40800000 + c1).."K" map_op[b1.."y_1"] = tohex(0x40a00000 + c1).."K" map_op[b1.."l_1"] = tohex(0x40800001 + c1).."K" map_op[b1.."_2"] = tohex(0x40800000 + c1).."-XK" map_op[b1.."y_2"] = tohex(0x40a00000 + c1).."-XK" map_op[b1.."l_2"] = tohex(0x40800001 + c1).."-XK" -- bXlr[l] map_op[b1.."lr_0"] = tohex(0x4c800020 + c1) map_op[b1.."lrl_0"] = tohex(0x4c800021 + c1) map_op[b1.."ctr_0"] = tohex(0x4c800420 + c1) map_op[b1.."ctrl_0"] = tohex(0x4c800421 + c1) -- bXctr[l] map_op[b1.."lr_1"] = tohex(0x4c800020 + c1).."-X" map_op[b1.."lrl_1"] = tohex(0x4c800021 + c1).."-X" map_op[b1.."ctr_1"] = tohex(0x4c800420 + c1).."-X" map_op[b1.."ctrl_1"] = tohex(0x4c800421 + c1).."-X" end ------------------------------------------------------------------------------ local function parse_gpr(expr) local tname, ovreg = match(expr, "^([%w_]+):(r[1-3]?[0-9])$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local r = match(expr, "^r([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r, tp end end werror("bad register name `"..expr.."'") end local function parse_fpr(expr) local r = match(expr, "^f([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r end end werror("bad register name `"..expr.."'") end local function parse_vr(expr) local r = match(expr, "^v([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r end end werror("bad register name `"..expr.."'") end local function parse_vs(expr) local r = match(expr, "^vs([1-6]?[0-9])$") if r then r = tonumber(r) if r <= 63 then return r end end werror("bad register name `"..expr.."'") end local function parse_cr(expr) local r = match(expr, "^cr([0-7])$") if r then return tonumber(r) end werror("bad condition register name `"..expr.."'") end local function parse_cond(expr) local r, cond = match(expr, "^4%*cr([0-7])%+(%w%w)$") if r then r = tonumber(r) local c = map_cond[cond] if c and c < 4 then return r*4+c end end werror("bad condition bit name `"..expr.."'") 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) 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.."'") elseif match(imm, "^[rfv]([1-3]?[0-9])$") or match(imm, "^vs([1-6]?[0-9])$") or match(imm, "^([%w_]+):(r[1-3]?[0-9])$") then werror("expected immediate operand, got register") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_shiftmask(imm, isshift) local n = parse_number(imm) if n then if shr(n, 6) == 0 then local lsb = band(n, 31) local msb = n - lsb return isshift and (shl(lsb, 11)+shr(msb, 4)) or (shl(lsb, 6)+msb) end werror("out of range immediate `"..imm.."'") elseif match(imm, "^r([1-3]?[0-9])$") or match(imm, "^([%w_]+):(r[1-3]?[0-9])$") then werror("expected immediate operand, got register") else waction("IMMSH", isshift and 1 or 0, imm) return 0; end end local function parse_disp(disp) local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$") if imm then local r = parse_gpr(reg) if r == 0 then werror("cannot use r0 in displacement") end return shl(r, 16) + parse_imm(imm, 16, 0, 0, true) end local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local r, tp = parse_gpr(reg) if r == 0 then werror("cannot use r0 in displacement") end if tp then waction("IMM", 32768+16*32, format(tp.ctypefmt, tailr)) return shl(r, 16) end end werror("bad displacement `"..disp.."'") end local function parse_u5disp(disp, scale) local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$") if imm then local r = parse_gpr(reg) if r == 0 then werror("cannot use r0 in displacement") end return shl(r, 16) + parse_imm(imm, 5, 11, scale, false) end local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local r, tp = parse_gpr(reg) if r == 0 then werror("cannot use r0 in displacement") end if tp then waction("IMM", scale*1024+5*32+11, format(tp.ctypefmt, tailr)) return shl(r, 16) end end werror("bad displacement `"..disp.."'") end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. op_template = function(params, template, nparams) if not params then return sub(template, 9) end local op = tonumber(sub(template, 1, 8), 16) local n, rs = 1, 26 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 3 positions (rlwinm). if secpos+3 > maxsecpos then wflush() end local pos = wpos() -- Process each character. for p in gmatch(sub(template, 9), ".") do if p == "R" then rs = rs - 5; op = op + shl(parse_gpr(params[n]), rs); n = n + 1 elseif p == "F" then rs = rs - 5; op = op + shl(parse_fpr(params[n]), rs); n = n + 1 elseif p == "V" then rs = rs - 5; op = op + shl(parse_vr(params[n]), rs); n = n + 1 elseif p == "Q" then local vs = parse_vs(params[n]); n = n + 1; rs = rs - 5 local sh = rs == 6 and 2 or 3 + band(shr(rs, 1), 3) op = op + shl(band(vs, 31), rs) + shr(band(vs, 32), sh) elseif p == "q" then local vs = parse_vs(params[n]); n = n + 1 op = op + shl(band(vs, 31), 21) + shr(band(vs, 32), 5) elseif p == "A" then rs = rs - 5; op = op + parse_imm(params[n], 5, rs, 0, false); n = n + 1 elseif p == "S" then rs = rs - 5; op = op + parse_imm(params[n], 5, rs, 0, true); n = n + 1 elseif p == "I" then op = op + parse_imm(params[n], 16, 0, 0, true); n = n + 1 elseif p == "U" then op = op + parse_imm(params[n], 16, 0, 0, false); n = n + 1 elseif p == "D" then op = op + parse_disp(params[n]); n = n + 1 elseif p == "2" then op = op + parse_u5disp(params[n], 1); n = n + 1 elseif p == "4" then op = op + parse_u5disp(params[n], 2); n = n + 1 elseif p == "8" then op = op + parse_u5disp(params[n], 3); n = n + 1 elseif p == "C" then rs = rs - 5; op = op + shl(parse_cond(params[n]), rs); n = n + 1 elseif p == "X" then rs = rs - 5; op = op + shl(parse_cr(params[n]), rs+2); n = n + 1 elseif p == "1" then rs = rs - 5; op = op + parse_imm(params[n], 1, rs, 0, false); n = n + 1 elseif p == "g" then rs = rs - 5; op = op + parse_imm(params[n], 2, rs, 0, false); n = n + 1 elseif p == "3" then rs = rs - 5; op = op + parse_imm(params[n], 3, rs, 0, false); n = n + 1 elseif p == "P" then rs = rs - 5; op = op + parse_imm(params[n], 4, rs, 0, false); n = n + 1 elseif p == "p" then op = op + parse_imm(params[n], 4, rs, 0, false); n = n + 1 elseif p == "6" then rs = rs - 6; op = op + parse_imm(params[n], 6, rs, 0, false); n = n + 1 elseif p == "Y" then rs = rs - 5; op = op + parse_imm(params[n], 1, rs+4, 0, false); n = n + 1 elseif p == "y" then rs = rs - 5; op = op + parse_imm(params[n], 1, rs+3, 0, false); n = n + 1 elseif p == "Z" then rs = rs - 5; op = op + parse_imm(params[n], 2, rs+3, 0, false); n = n + 1 elseif p == "z" then rs = rs - 5; op = op + parse_imm(params[n], 2, rs+2, 0, false); n = n + 1 elseif p == "W" then op = op + parse_cr(params[n]); n = n + 1 elseif p == "G" then op = op + parse_imm(params[n], 8, 12, 0, false); n = n + 1 elseif p == "H" then op = op + parse_shiftmask(params[n], true); n = n + 1 elseif p == "M" then op = op + parse_shiftmask(params[n], false); n = n + 1 elseif p == "J" or p == "K" then local mode, n, s = parse_label(params[n], false) if p == "K" then n = n + 2048 end waction("REL_"..mode, n, s, 1) n = n + 1 elseif p == "0" then if band(shr(op, rs), 31) == 0 then werror("cannot use r0") end elseif p == "=" or p == "%" then local t = band(shr(op, p == "%" and rs+5 or rs), 31) rs = rs - 5 op = op + shl(t, rs) elseif p == "~" then local mm = shl(31, rs) local lo = band(op, mm) local hi = band(op, shl(mm, 5)) op = op - lo - hi + shl(lo, 5) + shr(hi, 5) elseif p == ":" then if band(shr(op, rs), 1) ~= 0 then werror("register pair expected") end elseif p == "-" then rs = rs - 5 elseif p == "." then -- Ignored. else assert(false) end end wputpos(pos, op) 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
rohitjoshi/lua-resty-pkcs11
src/resty/p11.lua
1
5013
local ffi = require "ffi" local ffi_new = ffi.new local ffi_gc = ffi.gc local ffi_typeof = ffi.typeof local ffi_cdef = ffi.cdef local ffi_load = ffi.load local ffi_str = ffi.string local C = ffi.C local tonumber = tonumber local setmetatable = setmetatable local error = error local _M = { _VERSION = '0.01' } local mt = { __index = _M } ffi_cdef [[ unsigned long ERR_get_error(void); const char * ERR_reason_error_string(unsigned long e); typedef struct PKCS11_key_st { char *label; unsigned char *id; size_t id_len; unsigned char isPrivate; /**< private key present? */ unsigned char needLogin; /**< login to read private key? */ EVP_PKEY *evp_key; /**< initially NULL, need to call PKCS11_load_key */ void *_private; } PKCS11_KEY; typedef struct PKCS11_cert_st { char *label; unsigned char *id; size_t id_len; X509 *x509; void *_private; } PKCS11_CERT; typedef struct PKCS11_token_st { char *label; char *manufacturer; char *model; char *serialnr; unsigned char initialized; unsigned char loginRequired; unsigned char secureLogin; unsigned char userPinSet; unsigned char readOnly; unsigned char hasRng; unsigned char userPinCountLow; unsigned char userPinFinalTry; unsigned char userPinLocked; unsigned char userPinToBeChanged; unsigned char soPinCountLow; unsigned char soPinFinalTry; unsigned char soPinLocked; unsigned char soPinToBeChanged; void *_private; } PKCS11_TOKEN; typedef struct PKCS11_slot_st { char *manufacturer; char *description; unsigned char removable; PKCS11_TOKEN *token; /**< NULL if no token present */ void *_private; } PKCS11_SLOT; typedef struct PKCS11_ctx_st { char *manufacturer; char *description; void *_private; } PKCS11_CTX; extern PKCS11_CTX* PKCS11_CTX_new(void); extern void PKCS11_CTX_free(PKCS11_CTX * ctx); extern int PKCS11_CTX_load(PKCS11_CTX * ctx, const char * ident); extern int PKCS11_CTX_reload(PKCS11_CTX * ctx); extern int PKCS11_open_session(PKCS11_SLOT * slot, int rw); extern int PKCS11_enumerate_slots(PKCS11_CTX * ctx, PKCS11_SLOT **slotsp, unsigned int *nslotsp); extern unsigned long PKCS11_get_slotid_from_slot(PKCS11_SLOT *slotp); extern void PKCS11_release_all_slots(PKCS11_CTX * ctx, PKCS11_SLOT *slots, unsigned int nslots); extern int PKCS11_enumerate_slots(PKCS11_CTX * ctx, PKCS11_SLOT **slotsp, unsigned int *nslotsp); PKCS11_SLOT *PKCS11_find_token(PKCS11_CTX * ctx, PKCS11_SLOT *slots, unsigned int nslots); extern int PKCS11_login(PKCS11_SLOT * slot, int so, const char *pin); ]] local lib = ffi_load ("/opt/capione/lualib/p11.so") local char_t = ffi_typeof "char[?]" local size_t = ffi_typeof "size_t[1]" local uint_ptr = ffi.typeof"unsigned int[1]" local ctx_ptr_type = ffi.typeof("PKCS11_CTX[1]") local pkcs_slot_ptr_type = ffi.typeof("PKCS11_SLOT[1]"); local function _err() local code = _C.ERR_get_error() if code == 0 then return code, "Zero error code (null arguments?)" end return code, ffi.string(_C.ERR_reason_error_string(code)) end function _M.new(self, pkcsmodule) local ctx = lib.PKCS11_CTX_new() local r = lib.PKCS11_CTX_load(ctx, pkcsmodule) if r ~= 0 then ffi_gc(ctx, lib.PKCS11_CTX_free) return nil, _err() end ffi_gc(ctx, lib.PKCS11_CTX_free) return setmetatable({ _ctx = ctx }, mt) end function _M.enumerate_slots(self) local nslots = uint_ptr() local slots = ffi.new("PKCS11_SLOT *[1]") local rc = lib.PKCS11_enumerate_slots(self._ctx, slots, nslots) if rc < 0 then return nil, _err() end print(nslots[0] .. ":") local slot = lib.PKCS11_find_token(self._ctx, slots[0], nslots[0]) if not slot[0] then print("slot not found") lib.PKCS11_release_all_slots(self._ctx, slots[0], nslots[0]) return nil, 0, "no token available" end print("slot found") if not slot[0].token then print("slot token not found") lib.PKCS11_release_all_slots(self._ctx, slots[0], nslots[0]) return nil, 0, "no token available" end print("Slot manufacturer......: %s\n", ffi.string(slot.manufacturer)) print("Slot description.......: %s\n", ffi.string(slot.description)) print("Slot token label.......: %s\n", ffi.string(slot.token.label)) print("Slot token manufacturer: %s\n", ffi.string(slot.token.manufacturer)) print("Slot token model.......: %s\n", ffi.string(slot.token.model)) print("Slot token serialnr....: %s\n", ffi.string(slot.token.serialnr)) if slot.token.loginRequired == 1 then print("login required...") local rc = lib.PKCS11_login(slot, 0, "1234") if rc ~= 0 then print("Login failed") return nil, 0, "login failed" end print("Login success") end lib.PKCS11_release_all_slots(self._ctx, slots[0], nslots[0]); end --[[usage local softhsm = "/usr/local/lib/softhsm/libsofthsm.so" local p11 = pkcs11:new(softhsm) if not p11 then log_msg(log.ERROR, "Failed to load :" , softhsm) return end local ok, code, msg = p11:enumerate_slots() ]] return _M
apache-2.0
MalRD/darkstar
scripts/zones/Windurst_Woods/npcs/Varun.lua
9
1417
----------------------------------- -- Area: Windurst Woods -- NPC: Varun -- Type: Standard NPC -- !pos 7.800 -3.5 -10.064 241 ----------------------------------- require("scripts/globals/npc_util") require("scripts/globals/quests") ----------------------------------- function onTrade(player,npc,trade) if player:getCharVar("rockracketeer_sold") == 5 and npcUtil.tradeHas(trade, 598) then -- Sharp Stone player:startEvent(102, 2100) end end function onTrigger(player,npc) local rockRacketeer = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.ROCK_RACKETEER) local rockRacketeerCS = player:getCharVar("rockracketeer_sold") if rockRacketeer == QUEST_ACCEPTED and rockRacketeerCS == 3 then player:startEvent(100) -- talk about lost stone elseif rockRacketeer == QUEST_ACCEPTED and rockRacketeerCS == 4 then player:startEvent(101, 0, 598) -- send player to Palborough Mines else player:startEvent(432) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) if csid == 100 then player:setCharVar("rockracketeer_sold", 4) elseif csid == 101 then player:setCharVar("rockracketeer_sold", 5) elseif csid == 102 and npcUtil.completeQuest(player, WINDURST, dsp.quest.id.windurst.ROCK_RACKETEER, {gil=2100, var="rockracketeer_sold"}) then player:confirmTrade() end end
gpl-3.0
Lsty/ygopro-scripts
c96012004.lua
3
2096
--ラッキー・チャンス! function c96012004.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c96012004.cointg) e1:SetOperation(c96012004.coinop) c:RegisterEffect(e1) --coin local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(96012004,0)) e2:SetCategory(CATEGORY_DRAW) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_QUICK_F) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e2:SetCode(EVENT_CHAINING) e2:SetRange(LOCATION_SZONE) e2:SetCondition(c96012004.coincon) e2:SetOperation(c96012004.coinop) e2:SetLabel(1) c:RegisterEffect(e2) end function c96012004.coincon(e,tp,eg,ep,ev,re,r,rp) local ex,eg,et,cp,ct=Duel.GetOperationInfo(ev,CATEGORY_COIN) if ex and ct==1 and re:IsActiveType(TYPE_MONSTER) then e:SetLabelObject(re) return true else return false end end function c96012004.cointg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end e:SetLabel(0) local cc=Duel.GetCurrentChain() if cc==1 then return end local te=Duel.GetChainInfo(cc-1,CHAININFO_TRIGGERING_EFFECT) local ex,eg,et,cp,ct=Duel.GetOperationInfo(cc-1,CATEGORY_COIN) if ex and ct==1 and te:IsActiveType(TYPE_MONSTER) then e:SetLabel(1) e:SetLabelObject(te) end end function c96012004.coinop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if e:GetLabel()==0 or not c:IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_COIN) local res=1-Duel.SelectOption(tp,60,61) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetCode(EVENT_TOSS_COIN) e1:SetCondition(c96012004.drcon) e1:SetOperation(c96012004.drop) e1:SetCountLimit(1) e1:SetReset(RESET_CHAIN) e1:SetLabelObject(e:GetLabelObject()) e1:SetLabel(res) Duel.RegisterEffect(e1,tp) end function c96012004.drcon(e,tp,eg,ep,ev,re,r,rp) local res=Duel.GetCoinResult() return re==e:GetLabelObject() and res==e:GetLabel() end function c96012004.drop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_CARD,0,96012004) Duel.Draw(tp,1,REASON_EFFECT) end
gpl-2.0
ThingMesh/openwrt-luci
libs/nixio/docsrc/nixio.TLSContext.lua
173
1393
--- Transport Layer Security Context Object. -- @cstyle instance module "nixio.TLSContext" --- Create a TLS Socket from a socket descriptor. -- @class function -- @name TLSContext.create -- @param socket Socket Object -- @return TLSSocket Object --- Assign a PEM certificate to this context. -- @class function -- @name TLSContext.set_cert -- @usage This function calls SSL_CTX_use_certificate_chain_file(). -- @param path Certificate File path -- @return true --- Assign a PEM private key to this context. -- @class function -- @name TLSContext.set_key -- @usage This function calls SSL_CTX_use_PrivateKey_file(). -- @param path Private Key File path -- @return true --- Set the available ciphers for this context. -- @class function -- @name TLSContext.set_ciphers -- @usage This function calls SSL_CTX_set_cipher_list(). -- @param cipherlist String containing a list of ciphers -- @return true --- Set the verification depth of this context. -- @class function -- @name TLSContext.set_verify_depth -- @usage This function calls SSL_CTX_set_verify_depth(). -- @param depth Depth -- @return true --- Set the verification flags of this context. -- @class function -- @name TLSContext.set_verify -- @usage This function calls SSL_CTX_set_verify(). -- @param flag1 First Flag ["none", "peer", "verify_fail_if_no_peer_cert", -- "client_once"] -- @param ... More Flags [-"-] -- @return true
apache-2.0
cshore-firmware/openwrt-luci
libs/luci-lib-nixio/docsrc/nixio.TLSContext.lua
173
1393
--- Transport Layer Security Context Object. -- @cstyle instance module "nixio.TLSContext" --- Create a TLS Socket from a socket descriptor. -- @class function -- @name TLSContext.create -- @param socket Socket Object -- @return TLSSocket Object --- Assign a PEM certificate to this context. -- @class function -- @name TLSContext.set_cert -- @usage This function calls SSL_CTX_use_certificate_chain_file(). -- @param path Certificate File path -- @return true --- Assign a PEM private key to this context. -- @class function -- @name TLSContext.set_key -- @usage This function calls SSL_CTX_use_PrivateKey_file(). -- @param path Private Key File path -- @return true --- Set the available ciphers for this context. -- @class function -- @name TLSContext.set_ciphers -- @usage This function calls SSL_CTX_set_cipher_list(). -- @param cipherlist String containing a list of ciphers -- @return true --- Set the verification depth of this context. -- @class function -- @name TLSContext.set_verify_depth -- @usage This function calls SSL_CTX_set_verify_depth(). -- @param depth Depth -- @return true --- Set the verification flags of this context. -- @class function -- @name TLSContext.set_verify -- @usage This function calls SSL_CTX_set_verify(). -- @param flag1 First Flag ["none", "peer", "verify_fail_if_no_peer_cert", -- "client_once"] -- @param ... More Flags [-"-] -- @return true
apache-2.0
Lsty/ygopro-scripts
c81218874.lua
9
1364
--侵略の波紋 function c81218874.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(0,TIMING_END_PHASE) e1:SetCost(c81218874.cost) e1:SetTarget(c81218874.target) e1:SetOperation(c81218874.activate) c:RegisterEffect(e1) end function c81218874.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckLPCost(tp,500) end Duel.PayLPCost(tp,500) end function c81218874.filter(c,e,tp) return c:IsLevelBelow(4) and c:IsSetCard(0x100a) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c81218874.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c81218874.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c81218874.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c81218874.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c81218874.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
zhaozg/lit
libs/install-deps.lua
4
2361
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local import = require('import') local modes = require('git').modes local export = require('export') local pathJoin = require('luvi').path.join local filterTree = require('rules').filterTree local log = require('log').log -- Given a db tree and a set of dependencies, create a new tree with the deps -- folder synthisized from the deps list. local function toDb(db, rootHash, deps, nativeOnly) local tree = db.loadAs("tree", rootHash) local depsTree = {} for alias, meta in pairs(deps) do local entry = {} local kind, hash if meta.hash then hash = meta.hash kind = meta.kind if nativeOnly and kind == "tree" then hash = filterTree(db, "deps/" .. alias, hash, nil, nativeOnly) end else kind, hash = import(db, meta.fs, meta.path, nil, nativeOnly) end if kind == "blob" then entry.name = alias .. ".lua" else entry.name = alias end entry.mode = assert(modes[kind]) entry.hash = hash depsTree[#depsTree + 1] = entry end if #depsTree == 0 then return rootHash end tree[#tree + 1] = { name = "deps", mode = modes.tree, hash = db.saveAs("tree", depsTree) } return db.saveAs("tree", tree) end local function toFs(db, fs, rootPath, deps, nativeOnly) for alias, meta in pairs(deps) do if meta.hash then local path = pathJoin(rootPath, "deps", alias) local hash = meta.hash if meta.kind == "blob" then path = path .. ".lua" elseif nativeOnly then hash = filterTree(db, path, hash, nil, nativeOnly) end log("installing package", string.format("%s@v%s", meta.name, meta.version), "highlight") export(meta.db, hash, fs, path) end end end return { toDb = toDb, toFs = toFs, }
apache-2.0
sagarwaghmare69/nn
VolumetricFullConvolution.lua
2
7314
local VolumetricFullConvolution, parent = torch.class('nn.VolumetricFullConvolution','nn.Module') function VolumetricFullConvolution:__init(nInputPlane, nOutputPlane, kT, kW, kH, -- kernel size dT, dW, dH, -- stride padT, padW, padH, -- padding adjT, adjW, adjH) -- extra output adjustment parent.__init(self) dW = dW or 1 dH = dH or 1 dT = dT or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.kT = kT self.dW = dW self.dH = dH self.dT = dT self.padW = padW or 0 self.padH = padH or 0 self.padT = padT or 0 self.adjW = adjW or 0 self.adjH = adjH or 0 self.adjT = adjT or 0 if self.adjW > self.dW - 1 or self.adjH > self.dH - 1 or self.adjT > self.dT - 1 then error('adjW, adjH and adjT must be smaller than self.dW - 1,' .. ' self.dH - 1 and self.dT - 1 respectively') end self.weight = torch.Tensor(nInputPlane, nOutputPlane, kT, kH, kW) self.gradWeight = torch.Tensor(nInputPlane, nOutputPlane, kT, kH, kW) self.bias = torch.Tensor(self.nOutputPlane) self.gradBias = torch.Tensor(self.nOutputPlane) self.ones = torch.Tensor() self.finput = torch.Tensor() self.fgradInput = torch.Tensor() self:reset() end function VolumetricFullConvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else local nInputPlane = self.nInputPlane local kT = self.kT local kH = self.kH local kW = self.kW stdv = 1/math.sqrt(kW*kH*kT*nInputPlane) end self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end local function calculateAdj(targetSize, ker, pad, stride) return (targetSize + 2 * pad - ker) % stride end function VolumetricFullConvolution:backCompatibility() -- Transpose the weight when loading from an old version if not self.adjW then self.weight = self.weight:transpose(1, 2):contiguous() end -- Rename the padding when loading from an old version self.padW = self.padW or self.pW self.padH = self.padH or self.pH self.padT = self.padT or self.pT self.adjW = self.adjW or 0 self.adjH = self.adjH or 0 self.adjT = self.adjT or 0 end function VolumetricFullConvolution:updateOutput(input) self:backCompatibility() local inputTensor = input local adjT, adjW, adjH = self.adjT, self.adjW, self.adjH -- The input can be a table where the second element indicates the target -- output size, in which case the adj factors are computed automatically if type(inputTensor) == 'table' then inputTensor = input[1] local targetTensor = input[2] local tDims = targetTensor:dim() local tT = targetTensor:size(tDims-2) local tH = targetTensor:size(tDims-1) local tW = targetTensor:size(tDims) adjT = calculateAdj(tT, self.kT, self.padT, self.dT) adjW = calculateAdj(tW, self.kW, self.padW, self.dW) adjH = calculateAdj(tH, self.kH, self.padH, self.dH) end inputTensor.THNN.VolumetricFullConvolution_updateOutput( inputTensor:cdata(), self.output:cdata(), self.weight:cdata(), self.bias:cdata(), self.finput:cdata(), self.fgradInput:cdata(), self.dT, self.dW, self.dH, self.padT, self.padW, self.padH, adjT, adjW, adjH ) return self.output end function VolumetricFullConvolution:updateGradInput(input, gradOutput) self:backCompatibility() local inputTensor = input local adjT, adjW, adjH = self.adjT, self.adjW, self.adjH -- The input can be a table where the second element indicates the target -- output size, in which case the adj factors are computed automatically if type(inputTensor) == 'table' then inputTensor = input[1] local targetTensor = input[2] local tDims = targetTensor:dim() local tT = targetTensor:size(tDims-2) local tH = targetTensor:size(tDims-1) local tW = targetTensor:size(tDims) adjT = calculateAdj(tT, self.kT, self.padT, self.dT) adjW = calculateAdj(tW, self.kW, self.padW, self.dW) adjH = calculateAdj(tH, self.kH, self.padH, self.dH) -- Momentarily extract the gradInput tensor if type(self.gradInput) == 'table' then self.gradInput = self.gradInput[1] end end inputTensor.THNN.VolumetricFullConvolution_updateGradInput( inputTensor:cdata(), gradOutput:cdata(), self.gradInput:cdata(), self.weight:cdata(), self.finput:cdata(), self.fgradInput:cdata(), self.dT, self.dW, self.dH, self.padT, self.padW, self.padH, adjT, adjW, adjH ) if type(input) == 'table' then -- Create a zero tensor to be expanded and used as gradInput[2]. self.zeroScalar = self.zeroScalar or input[2].new(1):zero() self.ones:resize(input[2]:dim()):fill(1) local zeroTensor = self.zeroScalar :view(table.unpack(self.ones:totable())) :expandAs(input[2]) self.gradInput = {self.gradInput, zeroTensor} end return self.gradInput end function VolumetricFullConvolution:accGradParameters(input, gradOutput, scale) self:backCompatibility() local inputTensor = input local adjT, adjW, adjH = self.adjT, self.adjW, self.adjH -- The input can be a table where the second element indicates the target -- output size, in which case the adj factors are computed automatically if type(inputTensor) == 'table' then inputTensor = input[1] local targetTensor = input[2] local tDims = targetTensor:dim() local tT = targetTensor:size(tDims-2) local tH = targetTensor:size(tDims-1) local tW = targetTensor:size(tDims) adjT = calculateAdj(tT, self.kT, self.padT, self.dT) adjW = calculateAdj(tW, self.kW, self.padW, self.dW) adjH = calculateAdj(tH, self.kH, self.padH, self.dH) end inputTensor.THNN.VolumetricFullConvolution_accGradParameters( inputTensor:cdata(), gradOutput:cdata(), self.gradWeight:cdata(), self.gradBias:cdata(), self.finput:cdata(), self.fgradInput:cdata(), self.dT, self.dW, self.dH, self.padT, self.padW, self.padH, adjT, adjW, adjH, scale or 1 ) end function VolumetricFullConvolution:type(type, tensorCache) self.finput = torch.Tensor() self.fgradInput = torch.Tensor() return parent.type(self, type, tensorCache) end function VolumetricFullConvolution:__tostring__() local s = string.format('%s(%d -> %d, %dx%dx%d', torch.type(self), self.nInputPlane, self.nOutputPlane, self.kT, self.kW, self.kH) if self.dT ~= 1 or self.dW ~= 1 or self.dH ~= 1 or self.padT ~= 0 or self.padW ~= 0 or self.padH ~= 0 then s = s .. string.format(', %d,%d,%d', self.dT, self.dW, self.dH) end if (self.padT or self.padW or self.padH) and (self.padT ~= 0 or self.padW ~= 0 or self.padH ~= 0) then s = s .. ', ' .. self.padT .. ',' .. self.padW .. ',' .. self.padH end if (self.adjT or self.adjW or self.adjH) and (self.adjT ~= 0 or self.adjW ~= 0 or self.adjH ~= 0) then s = s .. ', ' .. self.adjT .. ',' .. self.adjW .. ',' .. self.adjH end return s .. ')' end
bsd-3-clause
Lsty/ygopro-scripts
c28754338.lua
3
1870
--真海皇 トライドン function c28754338.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(28754338,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCost(c28754338.spcost) e1:SetTarget(c28754338.sptg) e1:SetOperation(c28754338.spop) c:RegisterEffect(e1) end function c28754338.spcost(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsReleasable() and Duel.CheckReleaseGroup(tp,Card.IsRace,1,c,RACE_SEASERPENT) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE) local rg=Duel.SelectReleaseGroup(tp,Card.IsRace,1,1,c,RACE_SEASERPENT) rg:AddCard(c) Duel.Release(rg,REASON_COST) end function c28754338.filter(c,e,tp) return c:GetCode()==47826112 and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c28754338.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-2 and Duel.IsExistingMatchingCard(c28754338.filter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK+LOCATION_HAND) end function c28754338.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c28754338.filter,tp,LOCATION_DECK+LOCATION_HAND,0,1,1,nil,e,tp) if g:GetCount()>0 and Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)>0 then Duel.BreakEffect() local tg=Duel.GetMatchingGroup(Card.IsFaceup,tp,0,LOCATION_MZONE,nil) local tc=tg:GetFirst() while tc do local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(-300) e1:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e1) tc=tg:GetNext() end end end
gpl-2.0
ThingMesh/openwrt-luci
libs/sgi-uhttpd/luasrc/sgi/uhttpd.lua
54
2488
--[[ LuCI - Server Gateway Interface for the uHTTPd server Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- require "nixio.util" require "luci.http" require "luci.sys" require "luci.dispatcher" require "luci.ltn12" function handle_request(env) exectime = os.clock() local renv = { CONTENT_LENGTH = env.CONTENT_LENGTH, CONTENT_TYPE = env.CONTENT_TYPE, REQUEST_METHOD = env.REQUEST_METHOD, REQUEST_URI = env.REQUEST_URI, PATH_INFO = env.PATH_INFO, SCRIPT_NAME = env.SCRIPT_NAME:gsub("/+$", ""), SCRIPT_FILENAME = env.SCRIPT_NAME, SERVER_PROTOCOL = env.SERVER_PROTOCOL, QUERY_STRING = env.QUERY_STRING } local k, v for k, v in pairs(env.headers) do k = k:upper():gsub("%-", "_") renv["HTTP_" .. k] = v end local len = tonumber(env.CONTENT_LENGTH) or 0 local function recv() if len > 0 then local rlen, rbuf = uhttpd.recv(4096) if rlen >= 0 then len = len - rlen return rbuf end end return nil end local send = uhttpd.send local req = luci.http.Request( renv, recv, luci.ltn12.sink.file(io.stderr) ) local x = coroutine.create(luci.dispatcher.httpdispatch) local hcache = { } local active = true while coroutine.status(x) ~= "dead" do local res, id, data1, data2 = coroutine.resume(x, req) if not res then send("Status: 500 Internal Server Error\r\n") send("Content-Type: text/plain\r\n\r\n") send(tostring(id)) break end if active then if id == 1 then send("Status: ") send(tostring(data1)) send(" ") send(tostring(data2)) send("\r\n") elseif id == 2 then hcache[data1] = data2 elseif id == 3 then for k, v in pairs(hcache) do send(tostring(k)) send(": ") send(tostring(v)) send("\r\n") end send("\r\n") elseif id == 4 then send(tostring(data1 or "")) elseif id == 5 then active = false elseif id == 6 then data1:copyz(nixio.stdout, data2) end end end end
apache-2.0
Lsty/ygopro-scripts
c60879050.lua
3
2554
--機関連結 function c60879050.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_EQUIP) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCost(c60879050.cost) e1:SetTarget(c60879050.target) e1:SetOperation(c60879050.operation) c:RegisterEffect(e1) --Equip limit local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_EQUIP_LIMIT) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e2:SetValue(c60879050.eqlimit) c:RegisterEffect(e2) --Atk Change local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_EQUIP) e3:SetCode(EFFECT_SET_ATTACK) e3:SetValue(c60879050.value) c:RegisterEffect(e3) --Pierce local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_EQUIP) e4:SetCode(EFFECT_PIERCE) c:RegisterEffect(e4) --cannot attack local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_FIELD) e5:SetCode(EFFECT_CANNOT_ATTACK) e5:SetProperty(EFFECT_FLAG_OATH) e5:SetRange(LOCATION_SZONE) e5:SetTargetRange(LOCATION_MZONE,0) e5:SetTarget(c60879050.ftarget) c:RegisterEffect(e5) end function c60879050.eqlimit(e,c) return e:GetHandler():GetEquipTarget()==c and c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_EARTH) end function c60879050.filter(c) return c:IsFaceup() and c:IsRace(RACE_MACHINE) and c:IsAttribute(ATTRIBUTE_EARTH) end function c60879050.rmfilter(c) return c:IsRace(RACE_MACHINE) and c:IsLevelAbove(10) and c:IsAbleToRemoveAsCost() end function c60879050.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c60879050.rmfilter,tp,LOCATION_GRAVE,0,2,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c60879050.rmfilter,tp,LOCATION_GRAVE,0,2,2,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c60879050.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and c60879050.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c60879050.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) Duel.SelectTarget(tp,c60879050.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) end function c60879050.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then Duel.Equip(tp,c,tc) end end function c60879050.value(e,c) return c:GetBaseAttack()*2 end function c60879050.ftarget(e,c) return e:GetHandler():GetEquipTarget()~=c end
gpl-2.0
ThingMesh/openwrt-luci
applications/luci-coovachilli/luasrc/model/cbi/coovachilli_radius.lua
79
1768
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("coovachilli") -- radius server s1 = m:section(TypedSection, "radius") s1.anonymous = true s1:option( Value, "radiusserver1" ) s1:option( Value, "radiusserver2" ) s1:option( Value, "radiussecret" ).password = true s1:option( Value, "radiuslisten" ).optional = true s1:option( Value, "radiusauthport" ).optional = true s1:option( Value, "radiusacctport" ).optional = true s1:option( Value, "radiusnasid" ).optional = true s1:option( Value, "radiusnasip" ).optional = true s1:option( Value, "radiuscalled" ).optional = true s1:option( Value, "radiuslocationid" ).optional = true s1:option( Value, "radiuslocationname" ).optional = true s1:option( Value, "radiusnasporttype" ).optional = true s1:option( Flag, "radiusoriginalurl" ) s1:option( Value, "adminuser" ).optional = true rs = s1:option( Value, "adminpassword" ) rs.optional = true rs.password = true s1:option( Flag, "swapoctets" ) s1:option( Flag, "openidauth" ) s1:option( Flag, "wpaguests" ) s1:option( Flag, "acctupdate" ) s1:option( Value, "coaport" ).optional = true s1:option( Flag, "coanoipcheck" ) -- radius proxy s2 = m:section(TypedSection, "proxy") s2.anonymous = true s2:option( Value, "proxylisten" ).optional = true s2:option( Value, "proxyport" ).optional = true s2:option( Value, "proxyclient" ).optional = true ps = s2:option( Value, "proxysecret" ) ps.optional = true ps.password = true return m
apache-2.0
Lsty/ygopro-scripts
c48086335.lua
6
2307
--アーティファクト-フェイルノート function c48086335.initial_effect(c) --set local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_MONSTER_SSET) e1:SetValue(TYPE_SPELL) c:RegisterEffect(e1) --spsummon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(48086335,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_TO_GRAVE) e2:SetCondition(c48086335.spcon) e2:SetTarget(c48086335.sptg) e2:SetOperation(c48086335.spop) c:RegisterEffect(e2) --sset local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(48086335,1)) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_SPSUMMON_SUCCESS) e3:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_CARD_TARGET) e3:SetCondition(c48086335.setcon) e3:SetTarget(c48086335.settg) e3:SetOperation(c48086335.setop) c:RegisterEffect(e3) end function c48086335.spcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsPreviousLocation(LOCATION_SZONE) and c:IsPreviousPosition(POS_FACEDOWN) and c:IsReason(REASON_DESTROY) and Duel.GetTurnPlayer()~=tp end function c48086335.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c48086335.spop(e,tp,eg,ep,ev,re,r,rp) if e:GetHandler():IsRelateToEffect(e) then Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP) end end function c48086335.setcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()~=tp end function c48086335.filter(c) return c:IsSetCard(0x97) and c:IsType(TYPE_MONSTER) and c:IsSSetable() end function c48086335.settg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c48086335.filter(chkc) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingTarget(c48086335.filter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET) Duel.SelectTarget(tp,c48086335.filter,tp,LOCATION_GRAVE,0,1,1,nil) end function c48086335.setop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsSSetable() then Duel.SSet(tp,tc) Duel.ConfirmCards(1-tp,tc) end end
gpl-2.0
Lsty/ygopro-scripts
c40048324.lua
6
1155
--アーケイン・ファイロ function c40048324.initial_effect(c) --search local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(40048324,0)) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DELAY) e1:SetCode(EVENT_BE_MATERIAL) e1:SetCondition(c40048324.condition) e1:SetTarget(c40048324.target) e1:SetOperation(c40048324.operation) c:RegisterEffect(e1) end function c40048324.condition(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsLocation(LOCATION_GRAVE) and r==REASON_SYNCHRO end function c40048324.filter(c) return c:IsCode(80280737) and c:IsAbleToHand() end function c40048324.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c40048324.filter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c40048324.operation(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local tc=Duel.GetFirstMatchingCard(c40048324.filter,tp,LOCATION_DECK,0,nil) if tc then Duel.SendtoHand(tc,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,tc) end end
gpl-2.0
RamiLego4Game/PlatformerWorld
Modes/Loading.lua
1
2440
--Author : Ramilego4Game - This File Is Part Of Platformer World-- --Type : Class/Screen-- --Imports-- require 'Modes.LevelEditor' Loading = class:new() function Loading:init() self.LOGO = love.graphics.newImage("Lib/RL4G/Platformerworld-LOGO.png") --self.BG = love.graphics.newImage("assets/textures/gui/Loading-Background.png") self.alpha = 255 self.stage = 1 self.done = false self.prog = 0 self.speed = 25 Loader:init({_Images,_Sounds,_Fonts,_ImageDatas,_rawJData,_rawINIData}) local files = love.filesystem.getDirectoryItems("Lib/Themes/") for k, folder in ipairs(files) do if love.filesystem.isDirectory("Lib/Themes/"..folder) then Loader:LoadDirectory("Lib/Themes/"..folder.."/") end end Loader:LoadFolder("Lib/RL4G/") if love.system.getOS() == "Android" or _AndroidDebug then Loader:LoadFolder("Lib/Android/") end self.progbar = loveframes.Create("progressbar") self.progbar:SetWidth(_Width/3):SetMinMax(0,100):SetText("0%") self.progbar:SetPos(_Width/2,_Height/2+80,true):SetLerp(false):SetLerpRate(10) self.progbar.OnComplete = function(object) self.done = true _Loaded = true _TilesList = {} local files = loveframes.util.GetDirectoryContents("Engine/Tiles/") for k, v in ipairs(files) do if v.extension == "lua" then require(v.requirepath) Tile = Tile:new() _TilesList[Tile.name] = Tile Tile = nil end end end love.graphics.setBackgroundColor(208,244,247,255) end function Loading:update() Loader:Update() self.prog = math.floor(Loader:getProgress()*100) self.progbar:SetValue(self.prog):SetText(tostring(self.prog).."%") end function Loading:draw() if self.stage == 4 then self.progbar:Remove() return LevelEditor:new() end love.graphics.setColor(255,255,255,255) love.graphics.draw(self.LOGO,_Width/2,_Height/2,0,1,1,self.LOGO:getWidth()/2,self.LOGO:getHeight()/2) end function Loading:fade() love.graphics.setColor(0,0,0,self.alpha) love.graphics.rectangle("fill",0,0,_Width,_Height) if self.stage == 1 then self.alpha = self.alpha - self.speed if self.alpha <= 0 then self.stage = 2 self.alpha = 0 end elseif self.stage == 2 then if self.done then self.stage = 3 end elseif self.stage == 3 then self.alpha = self.alpha + self.speed if self.alpha >= 255 then self.stage = 4 self.alpha = 255 end end end
gpl-2.0
Lsty/ygopro-scripts
c56460688.lua
5
2155
--異次元隔離マシーン function c56460688.initial_effect(c) --remove local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_REMOVE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c56460688.target) e1:SetOperation(c56460688.operation) c:RegisterEffect(e1) --return local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_TO_GRAVE) e2:SetOperation(c56460688.retop) e2:SetLabelObject(e1) c:RegisterEffect(e2) end function c56460688.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return false end if chk==0 then return Duel.IsExistingTarget(Card.IsAbleToRemove,tp,LOCATION_MZONE,0,1,nil) and Duel.IsExistingTarget(Card.IsAbleToRemove,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g1=Duel.SelectTarget(tp,Card.IsAbleToRemove,tp,LOCATION_MZONE,0,1,1,nil) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g2=Duel.SelectTarget(tp,Card.IsAbleToRemove,tp,0,LOCATION_MZONE,1,1,nil) g1:Merge(g2) if e:GetLabelObject() then e:GetLabelObject():DeleteGroup() e:SetLabelObject(nil) end Duel.SetOperationInfo(0,CATEGORY_REMOVE,g1,2,0,0) end function c56460688.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end local tg=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e) if Duel.Remove(tg,0,REASON_EFFECT+REASON_TEMPORARY)~=0 then local g=Duel.GetOperatedGroup() local tc=g:GetFirst() while tc do tc:RegisterFlagEffect(56460688,RESET_EVENT+0x1fe0000,0,1) tc=g:GetNext() end c:RegisterFlagEffect(56460688,RESET_EVENT+0x17a0000,0,1) g:KeepAlive() e:SetLabelObject(g) end end function c56460688.retop(e,tp,eg,ep,ev,re,r,rp) if e:GetHandler():GetFlagEffect(56460688)==0 then return end if bit.band(r,REASON_DESTROY)~=0 then local g=e:GetLabelObject():GetLabelObject() local tc=g:GetFirst() while tc do if tc:GetFlagEffect(56460688)>0 then Duel.ReturnToField(tc) end tc=g:GetNext() end g:DeleteGroup() e:GetLabelObject():SetLabelObject(nil) end end
gpl-2.0
MalRD/darkstar
scripts/zones/Bastok_Mines/npcs/Virnage.lua
11
1920
----------------------------------- -- Area: Bastok Mines -- NPC: Virnage -- Starts Quest: Altana's Sorrow -- !pos 0 0 51 234 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); local ID = require("scripts/zones/Bastok_Mines/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) AltanaSorrow = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.ALTANA_S_SORROW); if (AltanaSorrow == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >= 4 and player:getMainLvl() >= 10) then player:startEvent(141); -- Start quest "Altana's Sorrow" elseif (AltanaSorrow == QUEST_ACCEPTED) then if (player:hasKeyItem(dsp.ki.BUCKET_OF_DIVINE_PAINT) == true) then player:startEvent(143); -- CS with Bucket of Divine Paint KI elseif (player:hasKeyItem(dsp.ki.LETTER_FROM_VIRNAGE) == true) then --player:showText(npc,ID.text.VIRNAGE_DIALOG_2); player:startEvent(144); -- During quest (after KI) else -- player:showText(npc,ID.text.VIRNAGE_DIALOG_1); player:startEvent(142); -- During quest "Altana's Sorrow" (before KI) end elseif (AltanaSorrow == QUEST_COMPLETED) then player:startEvent(145); -- New standard dialog else player:startEvent(140); -- Standard dialog end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 141 and option == 0) then player:addQuest(BASTOK,dsp.quest.id.bastok.ALTANA_S_SORROW); elseif (csid == 143) then player:delKeyItem(dsp.ki.BUCKET_OF_DIVINE_PAINT); player:addKeyItem(dsp.ki.LETTER_FROM_VIRNAGE); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LETTER_FROM_VIRNAGE); end end;
gpl-3.0
maxrio/luci981213
protocols/luci-proto-ipv6/luasrc/model/network/proto_6x4.lua
63
1066
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local netmod = luci.model.network local _, p for _, p in ipairs({"6in4", "6to4", "6rd"}) do local proto = netmod:register_protocol(p) function proto.get_i18n(self) if p == "6in4" then return luci.i18n.translate("IPv6-in-IPv4 (RFC4213)") elseif p == "6to4" then return luci.i18n.translate("IPv6-over-IPv4 (6to4)") elseif p == "6rd" then return luci.i18n.translate("IPv6-over-IPv4 (6rd)") end end function proto.ifname(self) return p .. "-" .. self.sid end function proto.opkg_package(self) return p end function proto.is_installed(self) return nixio.fs.access("/lib/netifd/proto/" .. p .. ".sh") end function proto.is_floating(self) return true end function proto.is_virtual(self) return true end function proto.get_interfaces(self) return nil end function proto.contains_interface(self, ifname) return (netmod:ifnameof(ifc) == self:ifname()) end netmod:register_pattern_virtual("^%s-%%w" % p) end
apache-2.0
T-L-N/Dev_TLN
plugins/kkk.lua
1
1479
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY Memo ▀▄ ▄▀ ▀▄ ▄▀ BY Memo (@ii02iI) ▀▄ ▄▀ ▀▄ ▄▀ Making the file by Memo ▀▄ ▄▀ ▀▄ ▄▀ kikebot : طرد البوت ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ —]] do local function run(msg, matches) local bot_id = our_id local receiver = get_receiver(msg) if matches[1] == 'طرد البوت' and is_admin1(msg) then chat_del_user("chat#id"..msg.to.id, 'user#id'..bot_id, ok_cb, false) leave_channel(receiver, ok_cb, false) elseif msg.service and msg.action.type == "chat_add_user" and msg.action.user.id == tonumber(bot_id) and not is_admin1(msg) then send_large_msg(receiver, 'آنہٰتہٰ لہٰيہٰس آلہٰمہٰطہٰور 🙇🏻🍷 تہٰفہٰظہٰل آدخہٰلہٰ @Ch_Dev 🌚😹 . ', ok_cb, false) chat_del_user(receiver, 'user#id'..bot_id, ok_cb, false) leave_channel(receiver, ok_cb, false) end end return { patterns = { "^(طرد البوت)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
Death15/Test
plugins/plugins.lua
25
5271
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled(name) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists(name) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_plugins(only_enabled) local text = '' local psum = 0 for k, v in pairs(plugins_names()) do -- ✅ enabled, ❌ disabled local status = '❌' psum = psum+1 pact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✅' end pact = pact+1 end if not only_enabled or status == '✅' then -- get the name v = string.match (v, "(.*)%.lua") text = text..status..' '..v..'\n' end end local text = text..'\n'..psum..' plugins installed.\n✅ ' ..pact..' enabled.\n❌ '..psum-pact..' disabled.' return text end local function reload_plugins() plugins = {} load_plugins() return list_plugins(true) end local function run(msg, matches) if is_mod(msg.from.id, msg.to.id) then -- Show the available plugins if matches[1] == '!plugins' then return list_plugins() -- Re-enable a plugin for this chat elseif matches[1] == 'enable' and matches[3] == 'chat' then print("enable "..matches[2]..' on this chat') if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins for this chat.' end if not _config.disabled_plugin_on_chat[get_receiver(msg)] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[get_receiver(msg)][matches[2]] then return 'Plugin '..matches[2]..' is not disabled for this chat.' end _config.disabled_plugin_on_chat[get_receiver(msg)][matches[2]] = false save_config() return 'Plugin '..matches[2]..' is enabled again for this chat.' -- Disable a plugin on a chat elseif matches[1] == 'disable' and matches[3] == 'chat' then print('disable '..matches[2]..' on this chat') if not plugin_exists(matches[2]) then return 'Plugin '..matches[2]..' doesn\'t exists' end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[get_receiver(msg)] then _config.disabled_plugin_on_chat[get_receiver(msg)] = {} end _config.disabled_plugin_on_chat[get_receiver(msg)][matches[2]] = true save_config() return 'Plugin '..matches[2]..' disabled for this chat' end end if is_sudo(msg.from.id) then -- Enable a plugin if matches[1] == 'enable' then print('enable: '..matches[2]) print('checking if '..matches[2]..' exists') -- Check if plugin is enabled if plugin_enabled(matches[2]) then return 'Plugin '..matches[2]..' is enabled' end -- Checks if plugin exists if plugin_exists(matches[2]) then -- Add to the config table table.insert(_config.enabled_plugins, matches[2]) print(matches[2]..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return 'Plugin '..matches[2]..' does not exists' end -- Disable a plugin elseif matches[1] == 'disable' then print('disable: '..matches[2]) -- Check if plugins exists if not plugin_exists(matches[2]) then return 'Plugin '..matches[2]..' does not exists' end local k = plugin_enabled(matches[2]) -- Check if plugin is enabled if not k then return 'Plugin '..matches[2]..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) -- Reload all the plugins! elseif matches[1] == 'reload' then return reload_plugins(true) end end end return { description = 'Plugin to manage other plugins. Enable, disable or reload.', usage = { moderator = { '!plugins: list all plugins.', '!plugins enable [plugin] chat: re-enable plugin only this chat.', '!plugins disable [plugin] chat: disable plugin only this chat.' }, sudo = { '!plugins enable [plugin]: enable plugin.', '!plugins disable [plugin]: disable plugin.', '!plugins reload: reloads all plugins.' }, }, patterns = { "^!plugins$", "^!plugins? (enable) ([%w_%.%-]+)$", "^!plugins? (disable) ([%w_%.%-]+)$", "^!plugins? (enable) ([%w_%.%-]+) (chat)$", "^!plugins? (disable) ([%w_%.%-]+) (chat)$", "^!plugins? (reload)$" }, run = run, moderated = true } end
gpl-2.0
Lsty/ygopro-scripts
c86197239.lua
3
1978
--インフェルニティ・ミラージュ function c86197239.initial_effect(c) --cannot special summon local e1=Effect.CreateEffect(c) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE+EFFECT_FLAG_SINGLE_RANGE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetRange(LOCATION_GRAVE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetValue(aux.FALSE) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(86197239,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCondition(c86197239.spcon) e2:SetCost(c86197239.spcost) e2:SetTarget(c86197239.sptg) e2:SetOperation(c86197239.spop) c:RegisterEffect(e2) end function c86197239.spcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)==0 end function c86197239.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsReleasable() end Duel.Release(e:GetHandler(),REASON_COST) end function c86197239.filter(c,e,tp) return c:IsSetCard(0xb) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c86197239.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c86197239.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c86197239.filter,tp,LOCATION_GRAVE,0,2,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c86197239.filter,tp,LOCATION_GRAVE,0,2,2,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,g:GetCount(),0,0) end function c86197239.spop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) local sg=g:Filter(Card.IsRelateToEffect,nil,e) if Duel.GetLocationCount(tp,LOCATION_MZONE)<sg:GetCount() then return end if sg:GetCount()>0 then Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
maxrio/luci981213
applications/luci-app-p910nd/luasrc/model/cbi/p910nd.lua
78
1340
-- Copyright 2008 Yanira <forum-2008@email.de> -- Copyright 2012 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local uci = luci.model.uci.cursor_state() local net = require "luci.model.network" local m, s, p, b m = Map("p910nd", translate("p910nd - Printer server"), translatef("First you have to install the packages to get support for USB (kmod-usb-printer) or parallel port (kmod-lp).")) net = net.init(m.uci) s = m:section(TypedSection, "p910nd", translate("Settings")) s.addremove = true s.anonymous = true s:option(Flag, "enabled", translate("enable")) s:option(Value, "device", translate("Device")).rmempty = true b = s:option(Value, "bind", translate("Interface"), translate("Specifies the interface to listen on.")) b.template = "cbi/network_netlist" b.nocreate = true b.unspecified = true function b.cfgvalue(...) local v = Value.cfgvalue(...) if v then return (net:get_status_by_address(v)) end end function b.write(self, section, value) local n = net:get_network(value) if n and n:ipaddr() then Value.write(self, section, n:ipaddr()) end end p = s:option(ListValue, "port", translate("Port"), translate("TCP listener port.")) p.rmempty = true for i=0,9 do p:value(i, 9100+i) end s:option(Flag, "bidirectional", translate("Bidirectional mode")) return m
apache-2.0
morfeo642/mta_plr_server
hedit/shared/variables/handlingMTA.lua
3
4260
handlingLimits = { ["identifier"] = { id = 1, input = "string", limits = { "", "" }, }, ["mass"] = { id = 2, input = "float", limits = { "1.0", "100000.0" } }, ["turnMass"] = { id = 3, input = "float", limits = { "0.0", "1000000.0" } }, ["dragCoeff"] = { id = 4, input = "float", limits = { "0.0", "200.0" } }, ["centerOfMassX"] = { id = 5, input = "float", limits = { "-10", "10" } }, ["centerOfMassY"] = { id = 6, input = "float", limits = { "-10", "10" } }, ["centerOfMassZ"] = { id = 7, input = "float", limits = { "-10", "10" } }, ["percentSubmerged"] = { id = 8, input = "integer", limits = { "1", "120" } }, ["tractionMultiplier"] = { id = 9, input = "float", limits = { "0.0", "100000.0" } }, ["tractionLoss"] = { id = 10, input = "float", limits = { "0.0", "100.0" } }, ["tractionBias"] = { id = 11, input = "float", limits = { "0.0", "1.0" } }, ["numberOfGears"] = { id = 12, input = "integer", limits = { "1", "5" } }, ["maxVelocity"] = { id = 13, input = "float", limits = { "0.1", "200000.0" } }, ["engineAcceleration"] = { id = 14, input = "float", limits = { "0.0", "100000.0" } }, ["engineInertia"] = { id = 15, input = "float", limits = { "-1000.0", "1000.0" } }, ["driveType"] = { id = 16, input = "string", limits = { "", "" }, options = { "f","r","4" } }, ["engineType"] = { id = 17, input = "string", limits = { "", "" }, options = { "p","d","e" } }, ["brakeDeceleration"] = { id = 18, input = "float", limits = { "0.1", "100000.0" } }, ["brakeBias"] = { id = 19, input = "float", limits = { "0.0", "1.0" } }, ["ABS"] = { id = 20, input = "boolean", limits = { "", "" }, options = { "true","false" } }, ["steeringLock"] = { id = 21, input = "float", limits = { "0.0", "360.0" } }, ["suspensionForceLevel"] = { id = 22, input = "float", limits = { "0.0", "100.0" } }, ["suspensionDamping"] = { id = 23, input = "float", limits = { "0.0", "100.0" } }, ["suspensionHighSpeedDamping"] = { id = 24, input = "float", limits = { "0.0", "600.0" } }, ["suspensionUpperLimit"] = { id = 25, input = "float", limits = { "-50.0", "50.0" } }, ["suspensionLowerLimit"] = { id = 26, input = "float", limits = { "-50.0", "50.0" } }, ["suspensionFrontRearBias"] = { id = 27, input = "float", limits = { "0.0", "1.0" } }, ["suspensionAntiDiveMultiplier"] = { id = 28, input = "float", limits = { "0.0", "30.0" } }, ["seatOffsetDistance"] = { id = 29, input = "float", limits = { "0.0", "20.0" } }, ["collisionDamageMultiplier"] = { id = 30, input = "float", limits = { "0.0", "100.0" } }, ["monetary"] = { id = 31, input = "integer", limits = { "0", "230195200" } }, ["modelFlags"] = { id = 32, input = "hexadecimal", limits = { "", "" }, }, ["handlingFlags"] = { id = 33, input = "hexadecimal", limits = { "", "" }, }, ["headLight"] = { id = 34, input = "integer", limits = { "0", "3" }, options = { 0,1,2,3 } }, ["tailLight"] = { id = 35, input = "integer", limits = { "0", "3" }, options = { 0,1,2,3 } }, ["animGroup"] = { id = 36, input = "integer", limits = { "0", "30" } } } propertyID = {} for k,v in pairs ( handlingLimits ) do propertyID[v.id] = k end
mit
MalRD/darkstar
scripts/globals/abilities/pets/magic_mortar.lua
11
1395
--------------------------------------------------- -- Magic Mortar --------------------------------------------------- require("scripts/globals/status") require("scripts/globals/settings") require("scripts/globals/automatonweaponskills") --------------------------------------------------- function onMobSkillCheck(target, automaton, skill) local master = automaton:getMaster() return master:countEffect(dsp.effect.LIGHT_MANEUVER) end function onPetAbility(target, automaton, skill, master, action) local ftp local tp = skill:getTP() if not USE_ADOULIN_WEAPON_SKILL_CHANGES then ftp = 0.5 + ((0.5/3000) * tp) else -- Might be wrong, it may only use max hp in its new form, also it may be able to miss and take defense into account as well if tp >= 3000 then ftp = 2.5 elseif tp >= 2000 then ftp = 1.75 + ((0.75/3000) * tp) else ftp = 1.5 + ((0.25/3000) * tp) end end local hpdamage = (automaton:getMaxHP() - automaton:getHP()) * ftp local skilldamage = automaton:getSkillLevel(dsp.skill.AUTOMATON_MELEE) * ftp local damage = (hpdamage > skilldamage) and hpdamage or skilldamage if damage > 0 then target:addTP(20) automaton:addTP(80) end target:takeDamage(damage, pet, dsp.attackType.MAGICAL, dsp.damageType.LIGHT) return damage end
gpl-3.0
robertbrook/Penlight
lua/pl/Map.lua
26
2783
--- A Map class. -- -- > Map = require 'pl.Map' -- > m = Map{one=1,two=2} -- > m:update {three=3,four=4,two=20} -- > = m == M{one=1,two=20,three=3,four=4} -- true -- -- Dependencies: `pl.utils`, `pl.class`, `pl.tablex`, `pl.pretty` -- @classmod pl.Map local tablex = require 'pl.tablex' local utils = require 'pl.utils' local stdmt = utils.stdmt local tmakeset,deepcompare,merge,keys,difference,tupdate = tablex.makeset,tablex.deepcompare,tablex.merge,tablex.keys,tablex.difference,tablex.update local pretty_write = require 'pl.pretty' . write local Map = stdmt.Map local Set = stdmt.Set local List = stdmt.List local class = require 'pl.class' -- the Map class --------------------- class(nil,nil,Map) local function makemap (m) return setmetatable(m,Map) end function Map:_init (t) local mt = getmetatable(t) if mt == Set or mt == Map then self:update(t) else return t -- otherwise assumed to be a map-like table end end local function makelist(t) return setmetatable(t,List) end --- list of keys. Map.keys = tablex.keys --- list of values. Map.values = tablex.values --- return an iterator over all key-value pairs. function Map:iter () return pairs(self) end --- return a List of all key-value pairs, sorted by the keys. function Map:items() local ls = makelist(tablex.pairmap (function (k,v) return makelist {k,v} end, self)) ls:sort(function(t1,t2) return t1[1] < t2[1] end) return ls end -- Will return the existing value, or if it doesn't exist it will set -- a default value and return it. function Map:setdefault(key, defaultval) return self[key] or self:set(key,defaultval) or defaultval end --- size of map. -- note: this is a relatively expensive operation! -- @class function -- @name Map:len Map.len = tablex.size --- put a value into the map. -- @param key the key -- @param val the value function Map:set (key,val) self[key] = val end --- get a value from the map. -- @param key the key -- @return the value, or nil if not found. function Map:get (key) return rawget(self,key) end local index_by = tablex.index_by --- get a list of values indexed by a list of keys. -- @param keys a list-like table of keys -- @return a new list function Map:getvalues (keys) return makelist(index_by(self,keys)) end --- update the map using key/value pairs from another table. -- @tab table -- @function Map:update Map.update = tablex.update --- equality between maps. -- @within metamethods -- @tparam Map m another map. function Map:__eq (m) -- note we explicitly ask deepcompare _not_ to use __eq! return deepcompare(self,m,true) end --- string representation of a map. -- @within metamethods function Map:__tostring () return pretty_write(self,'') end return Map
mit
Distrotech/vlc
share/lua/playlist/lelombrik.lua
108
1985
--[[ French humor site: http://lelombrik.net $Id$ Copyright © 2007 the VideoLAN team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] -- Probe function. function probe() return vlc.access == "http" and string.match( vlc.path, "lelombrik.net/videos" ) end -- Parse function. function parse() while true do line = vlc.readline() if not line then vlc.msg.err("Couldn't extract the video URL from lelombrik") return { } end if string.match( line, "id=\"nom_fichier\">" ) then title = string.gsub( line, ".*\"nom_fichier\">([^<]*).*", "%1" ) if title then title = vlc.strings.from_charset( "ISO_8859-1", title ) end elseif string.match( line, "'file'" ) then _,_,path = string.find( line, "'file', *'([^']*)") elseif string.match( line, "flashvars=" ) then path = string.gsub( line, "flashvars=.*&file=([^&]*).*", "%1" ) arturl = string.gsub( line, "flashvars=.*&image=([^&]*).*", "%1" ) elseif string.match( line, "'image'" ) then _,_,arturl = string.find( line, "'image', *'([^']*)") end if path and arturl and title then return { { path = path; arturl = arturl; title = title } } end end end
gpl-2.0
MalRD/darkstar
scripts/zones/Western_Adoulin/npcs/Vaulois.lua
9
1542
----------------------------------- -- Area: Western Adoulin -- NPC: Vaulois -- Type: Standard NPC and Quest Giver -- Starts, Involved with, and Finishes Quest: 'Transporting' -- !pos 20 0 85 256 ----------------------------------- require("scripts/globals/quests"); local ID = require("scripts/zones/Western_Adoulin/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local Transporting = player:getQuestStatus(ADOULIN, dsp.quest.id.adoulin.TRANSPORTING); if ((Transporting == QUEST_ACCEPTED) and (player:getCharVar("Transporting_Status") >= 2)) then -- Finishing Quest: 'Transporting' player:startEvent(2591); elseif ((Transporting == QUEST_AVAILABLE) and (player:getFameLevel(ADOULIN) >= 2)) then -- Starts Quest: 'Transporting' player:startEvent(2590); else -- Standard dialogue player:startEvent(520); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 2590) then -- Starting Quest: 'Transporting' player:addQuest(ADOULIN, dsp.quest.id.adoulin.TRANSPORTING); elseif (csid == 2591) then -- Finishing Quest: 'Transporting' player:completeQuest(ADOULIN, dsp.quest.id.adoulin.TRANSPORTING); player:addExp(1000 * EXP_RATE); player:addCurrency('bayld', 300 * BAYLD_RATE); player:messageSpecial(ID.text.BAYLD_OBTAINED, 300 * BAYLD_RATE); player:addFame(ADOULIN); end end;
gpl-3.0
moody2020/TH3_BOSS
plugins/arabic_lock.lua
234
1405
antiarabic = {}-- An empty table for solving multiple kicking problem do local function run(msg, matches) if is_momod(msg) then -- Ignore mods,owner,admins return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)]['settings']['lock_arabic'] then if data[tostring(msg.to.id)]['settings']['lock_arabic'] == 'yes' then if is_whitelisted(msg.from.id) then return end if antiarabic[msg.from.id] == true then return end if msg.to.type == 'chat' then local receiver = get_receiver(msg) local username = msg.from.username local name = msg.from.first_name if username and is_super_group(msg) then send_large_msg(receiver , "Arabic/Persian is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked/msg deleted") else send_large_msg(receiver , "Arabic/Persian is not allowed here\nName: "..name.."["..msg.from.id.."]\nStatus: User kicked/msg deleted") end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked (arabic was locked) ") local chat_id = msg.to.id local user_id = msg.from.id kick_user(user_id, chat_id) end antiarabic[msg.from.id] = true end end return end local function cron() antiarabic = {} -- Clear antiarabic table end return { patterns = { "([\216-\219][\128-\191])" }, run = run, cron = cron } end
gpl-2.0
asterite/mal
lua/step3_env.lua
40
2478
#!/usr/bin/env lua local table = require('table') local readline = require('readline') local utils = require('utils') local types = require('types') local reader = require('reader') local printer = require('printer') local Env = require('env') local List, Vector, HashMap = types.List, types.Vector, types.HashMap -- read function READ(str) return reader.read_str(str) end -- eval function eval_ast(ast, env) if types._symbol_Q(ast) then return env:get(ast) elseif types._list_Q(ast) then return List:new(utils.map(function(x) return EVAL(x,env) end,ast)) elseif types._vector_Q(ast) then return Vector:new(utils.map(function(x) return EVAL(x,env) end,ast)) elseif types._hash_map_Q(ast) then local new_hm = {} for k,v in pairs(ast) do new_hm[EVAL(k, env)] = EVAL(v, env) end return HashMap:new(new_hm) else return ast end end function EVAL(ast, env) --print("EVAL: "..printer._pr_str(ast,true)) if not types._list_Q(ast) then return eval_ast(ast, env) end local a0,a1,a2 = ast[1], ast[2],ast[3] local a0sym = types._symbol_Q(a0) and a0.val or "" if 'def!' == a0sym then return env:set(a1, EVAL(a2, env)) elseif 'let*' == a0sym then local let_env = Env:new(env) for i = 1,#a1,2 do let_env:set(a1[i], EVAL(a1[i+1], let_env)) end return EVAL(a2, let_env) else local args = eval_ast(ast, env) local f = table.remove(args, 1) return f(unpack(args)) end end -- print function PRINT(exp) return printer._pr_str(exp, true) end -- repl local repl_env = Env:new() function rep(str) return PRINT(EVAL(READ(str),repl_env)) end repl_env:set(types.Symbol:new('+'), function(a,b) return a+b end) repl_env:set(types.Symbol:new('-'), function(a,b) return a-b end) repl_env:set(types.Symbol:new('*'), function(a,b) return a*b end) repl_env:set(types.Symbol:new('/'), function(a,b) return math.floor(a/b) end) if #arg > 0 and arg[1] == "--raw" then readline.raw = true end while true do line = readline.readline("user> ") if not line then break end xpcall(function() print(rep(line)) end, function(exc) if exc then if types._malexception_Q(exc) then exc = printer._pr_str(exc.val, true) end print("Error: " .. exc) print(debug.traceback()) end end) end
mpl-2.0
Lsty/ygopro-scripts
c52346240.lua
3
1624
--ロックキャット function c52346240.initial_effect(c) --summon success local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(52346240,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetTarget(c52346240.sptg) e1:SetOperation(c52346240.spop) c:RegisterEffect(e1) end function c52346240.filter(c,e,tp) return c:GetLevel()==1 and c:IsRace(RACE_BEAST) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c52346240.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c52346240.filter(chkc,e,tp) end if chk==0 then return Duel.IsExistingTarget(c52346240.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c52346240.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c52346240.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP_DEFENCE) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_DISABLE) e1:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_DISABLE_EFFECT) e2:SetReset(RESET_EVENT+0x1fe0000) tc:RegisterEffect(e2) end Duel.SpecialSummonComplete() end
gpl-2.0
Lsty/ygopro-scripts
c54366836.lua
3
2348
--No.54 反骨の闘士ライオンハート function c54366836.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,nil,1,3) c:EnableReviveLimit() --ind local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e1:SetCondition(c54366836.indcon) e1:SetValue(1) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(54366836,0)) e2:SetCategory(CATEGORY_DAMAGE) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_BATTLE_DAMAGE) e2:SetRange(LOCATION_MZONE) e2:SetCondition(c54366836.damcon) e2:SetTarget(c54366836.damtg) e2:SetOperation(c54366836.damop) c:RegisterEffect(e2) --damage local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(54366836,0)) e3:SetType(EFFECT_TYPE_QUICK_O) e3:SetCode(EVENT_PRE_DAMAGE_CALCULATE) e3:SetRange(LOCATION_MZONE) e3:SetCondition(c54366836.damcon2) e3:SetCost(c54366836.damcost2) e3:SetOperation(c54366836.damop2) c:RegisterEffect(e3) end c54366836.xyz_number=54 function c54366836.damcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return ep==tp and c:IsRelateToBattle() end function c54366836.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(ev) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,ev) end function c54366836.damop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end function c54366836.damcon2(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetBattleTarget()~=nil end function c54366836.damcost2(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:GetFlagEffect(54366836)==0 and c:CheckRemoveOverlayCard(tp,1,REASON_COST) end c:RemoveOverlayCard(tp,1,1,REASON_COST) c:RegisterFlagEffect(54366836,RESET_CHAIN,0,1) end function c54366836.damop2(e,tp,eg,ep,ev,re,r,rp) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_REFLECT_BATTLE_DAMAGE) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetReset(RESET_PHASE+PHASE_DAMAGE_CAL) Duel.RegisterEffect(e1,tp) end function c54366836.indcon(e) return e:GetHandler():IsPosition(POS_FACEUP_ATTACK) end
gpl-2.0
openwrt/luci
modules/luci-mod-admin-mini/luasrc/controller/mini/system.lua
3
6439
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.mini.system", package.seeall) function index() entry({"mini", "system"}, alias("mini", "system", "index"), _("System"), 40).index = true entry({"mini", "system", "index"}, cbi("mini/system", {autoapply=true}), _("General"), 1) entry({"mini", "system", "passwd"}, form("mini/passwd"), _("Admin Password"), 10) entry({"mini", "system", "backup"}, call("action_backup"), _("Backup / Restore"), 80) entry({"mini", "system", "upgrade"}, call("action_upgrade"), _("Flash Firmware"), 90) entry({"mini", "system", "reboot"}, call("action_reboot"), _("Reboot"), 100) end function action_backup() local reset_avail = os.execute([[grep '"rootfs_data"' /proc/mtd >/dev/null 2>&1]]) == 0 local restore_cmd = "gunzip | tar -xC/ >/dev/null 2>&1" local backup_cmd = "tar -c %s | gzip 2>/dev/null" local restore_fpi luci.http.setfilehandler( function(meta, chunk, eof) if not restore_fpi then restore_fpi = io.popen(restore_cmd, "w") end if chunk then restore_fpi:write(chunk) end if eof then restore_fpi:close() end end ) local upload = luci.http.formvalue("archive") local backup = luci.http.formvalue("backup") local reset = reset_avail and luci.http.formvalue("reset") if upload and #upload > 0 then luci.template.render("mini/applyreboot") luci.sys.reboot() elseif backup then local reader = ltn12_popen(backup_cmd:format(_keep_pattern())) luci.http.header('Content-Disposition', 'attachment; filename="backup-%s-%s.tar.gz"' % { luci.sys.hostname(), os.date("%Y-%m-%d")}) luci.http.prepare_content("application/x-targz") luci.ltn12.pump.all(reader, luci.http.write) elseif reset then luci.template.render("mini/applyreboot") luci.util.exec("mtd -r erase rootfs_data") else luci.template.render("mini/backup", {reset_avail = reset_avail}) end end function action_reboot() local reboot = luci.http.formvalue("reboot") luci.template.render("mini/reboot", {reboot=reboot}) if reboot then luci.sys.reboot() end end function action_upgrade() require("luci.model.uci") local tmpfile = "/tmp/firmware.img" local function image_supported() -- XXX: yay... return ( 0 == os.execute( ". /lib/functions.sh; " .. "include /lib/upgrade; " .. "platform_check_image %q >/dev/null" % tmpfile ) ) end local function image_checksum() return (luci.sys.exec("md5sum %q" % tmpfile):match("^([^%s]+)")) end local function storage_size() local size = 0 if nixio.fs.access("/proc/mtd") then for l in io.lines("/proc/mtd") do local d, s, e, n = l:match('^([^%s]+)%s+([^%s]+)%s+([^%s]+)%s+"([^%s]+)"') if n == "linux" then size = tonumber(s, 16) break end end elseif nixio.fs.access("/proc/partitions") then for l in io.lines("/proc/partitions") do local x, y, b, n = l:match('^%s*(%d+)%s+(%d+)%s+([^%s]+)%s+([^%s]+)') if b and n and not n:match('[0-9]') then size = tonumber(b) * 1024 break end end end return size end -- Install upload handler local file luci.http.setfilehandler( function(meta, chunk, eof) if not nixio.fs.access(tmpfile) and not file and chunk and #chunk > 0 then file = io.open(tmpfile, "w") end if file and chunk then file:write(chunk) end if file and eof then file:close() end end ) -- Determine state local keep_avail = true local step = tonumber(luci.http.formvalue("step") or 1) local has_image = nixio.fs.access(tmpfile) local has_support = image_supported() local has_platform = nixio.fs.access("/lib/upgrade/platform.sh") local has_upload = luci.http.formvalue("image") -- This does the actual flashing which is invoked inside an iframe -- so don't produce meaningful errors here because the the -- previous pages should arrange the stuff as required. if step == 4 then if has_platform and has_image and has_support then -- Mimetype text/plain luci.http.prepare_content("text/plain") luci.http.write("Starting luci-flash...\n") -- Now invoke sysupgrade local keepcfg = keep_avail and luci.http.formvalue("keepcfg") == "1" local flash = ltn12_popen("/sbin/luci-flash %s %q" %{ keepcfg and "-k %q" % _keep_pattern() or "", tmpfile }) luci.ltn12.pump.all(flash, luci.http.write) -- Make sure the device is rebooted luci.sys.reboot() end -- -- This is step 1-3, which does the user interaction and -- image upload. -- -- Step 1: file upload, error on unsupported image format elseif not has_image or not has_support or step == 1 then -- If there is an image but user has requested step 1 -- or type is not supported, then remove it. if has_image then nixio.fs.unlink(tmpfile) end luci.template.render("mini/upgrade", { step=1, bad_image=(has_image and not has_support or false), keepavail=keep_avail, supported=has_platform } ) -- Step 2: present uploaded file, show checksum, confirmation elseif step == 2 then luci.template.render("mini/upgrade", { step=2, checksum=image_checksum(), filesize=nixio.fs.stat(tmpfile).size, flashsize=storage_size(), keepconfig=(keep_avail and luci.http.formvalue("keepcfg") == "1") } ) -- Step 3: load iframe which calls the actual flash procedure elseif step == 3 then luci.template.render("mini/upgrade", { step=3, keepconfig=(keep_avail and luci.http.formvalue("keepcfg") == "1") } ) end end function _keep_pattern() local kpattern = "" local files = luci.model.uci.cursor():get_all("luci", "flash_keep") if files then kpattern = "" for k, v in pairs(files) do if k:sub(1,1) ~= "." and nixio.fs.glob(v)() then kpattern = kpattern .. " " .. v end end end return kpattern end function ltn12_popen(command) local fdi, fdo = nixio.pipe() local pid = nixio.fork() if pid > 0 then fdo:close() local close return function() local buffer = fdi:read(2048) local wpid, stat = nixio.waitpid(pid, "nohang") if not close and wpid and stat == "exited" then close = true end if buffer and #buffer > 0 then return buffer elseif close then fdi:close() return nil end end elseif pid == 0 then nixio.dup(fdo, nixio.stdout) fdi:close() fdo:close() nixio.exec("/bin/sh", "-c", command) end end
apache-2.0
Nuthen/ludum-dare-39
entities/fx/particle.lua
1
5382
local ParticleSystem = Class('ParticleSystem') function ParticleSystem:initialize() self.systems = {} self.drawLater = {"sparks"} self.defaultImage = love.graphics.newImage("assets/images/particles/1x1white.png") self.sparkImage = love.graphics.newImage("assets/images/particles/spark.png") self.gibImage = love.graphics.newImage("assets/images/particles/gib.png") -- How many particles each system can have self.particleLimit = 500 self.systems.default = love.graphics.newParticleSystem(self.defaultImage, self.particleLimit) self.systems.default:stop() self.systems.sparks = self.systems.default:clone() self.systems.sparks:setColors( 255, 255, 255, 255, 255, 255, 0, 255, 255, 215, 0, 255, 255, 127, 0, 255 ) self.systems.sparks:setTexture(self.sparkImage) self.systems.sparks:setSizes(2, 1.5, 0.75, 0.25) self.systems.sparks:setSizeVariation(1) self.systems.sparks:setSpeed(100, 300) self.systems.sparks:setLinearAcceleration(0, 400) self.systems.sparks:setTangentialAcceleration(-100, 100) self.systems.sparks:setRadialAcceleration(-100, 100) self.systems.sparks:setSpread(math.pi / 2) self.systems.sparks:setDirection(-math.pi/2) self.systems.sparks:setParticleLifetime(0.25, 1) self.systems.sparks:setEmissionRate(25) self.systems.sparks:setRelativeRotation(true) self.systems.gibs = self.systems.default:clone() self.systems.gibs:setTexture(self.gibImage) self.systems.gibs:setSizes(2, 1, 0.5, 0.25) self.systems.gibs:setSizeVariation(1) self.systems.gibs:setSpeed(100, 300) self.systems.gibs:setLinearAcceleration(0, 400) self.systems.gibs:setTangentialAcceleration(-100, 100) self.systems.gibs:setRadialAcceleration(-100, 100) self.systems.gibs:setSpread(math.pi / 2) self.systems.gibs:setDirection(-math.pi/2) self.systems.gibs:setParticleLifetime(0.25, 1) self.systems.gibs:setEmissionRate(25) self.systems.gibs:setRelativeRotation(true) -- For now, particle emitters and the ParticleSystem (this class) use different tables -- ParticleSystem uses object pooling, and ParticleEmitters just get 1 system per instance self.usedSystems = {} self.pool = {} for name, system in pairs(self.systems) do self.pool[name] = {} end local function createSystem(name) for i=#self.pool[name], 1, -1 do local system = self.pool[name][i] if not system:isActive() then return system end end local s = self.systems[name]:clone() table.insert(self.pool[name], s) return s end Signal.register('emitterCreated', function(emitter, kind) -- Default system if kind == "" or kind == nil then kind = "default" end local system = self.systems[kind]:clone() Signal.emit('systemCreated', system, emitter) table.insert(self.usedSystems, system) end) Signal.register('Dynamo Correct', function(sourceType, position) local s = createSystem("sparks") s:setPosition(position:unpack()) s:start() s:emit(20) s:setEmitterLifetime(.1) end) Signal.register('Enemy Hurt', function(isCurrentRoom, stage, position) if isCurrentRoom then local s = createSystem("gibs") s:setSizes(1, 0.5, 0.25) s:setSpeed(50, 150) s:setPosition(position:unpack()) s:start() s:emit(10) s:setEmitterLifetime(.1) end end) Signal.register('enemyDeath', function(isCurrentRoom, stage, position) if isCurrentRoom then local s = createSystem("gibs") s:setSizes(2, 1, 0.5, 0.25) s:setSpeed(100, 300) s:setPosition(position:unpack()) s:start() s:emit(20 * stage) s:setEmitterLifetime(.1) end end) end function ParticleSystem:update(dt) for _, system in ipairs(self.usedSystems) do system:update(dt) end for _, kind in pairs(self.pool) do for _, system in ipairs(kind) do system:update(dt) end end end function ParticleSystem:draw() love.graphics.setColor(255, 255, 255) for k, system in ipairs(self.usedSystems) do if not Lume.find(self.drawLater, k) then love.graphics.setColor(255, 255, 255) love.graphics.draw(system) end end for k, kind in pairs(self.pool) do for _, system in ipairs(kind) do if not Lume.find(self.drawLater, k) then love.graphics.setColor(255, 255, 255) love.graphics.draw(system) end end end end function ParticleSystem:drawAfter() love.graphics.setColor(255, 255, 255) for k, system in ipairs(self.usedSystems) do if Lume.find(self.drawLater, k) then love.graphics.setColor(255, 255, 255) love.graphics.draw(system) end end for k, kind in pairs(self.pool) do for _, system in ipairs(kind) do if Lume.find(self.drawLater, k) then love.graphics.setColor(255, 255, 255) love.graphics.draw(system) end end end end return ParticleSystem
mit
Lsty/ygopro-scripts
c24701235.lua
3
3442
--和魂 function c24701235.initial_effect(c) --cannot special summon local e1=Effect.CreateEffect(c) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) c:RegisterEffect(e1) --summon,flip local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e2:SetCode(EVENT_SUMMON_SUCCESS) e2:SetOperation(c24701235.retreg) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EVENT_FLIP) c:RegisterEffect(e3) --extra summon local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e4:SetCode(EVENT_SUMMON_SUCCESS) e4:SetOperation(c24701235.sumop) c:RegisterEffect(e4) local e5=e4:Clone() e5:SetCode(EVENT_FLIP) c:RegisterEffect(e5) --draw local e6=Effect.CreateEffect(c) e6:SetDescription(aux.Stringid(24701235,1)) e6:SetCategory(CATEGORY_DRAW) e6:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e6:SetCode(EVENT_TO_GRAVE) e6:SetTarget(c24701235.target) e6:SetOperation(c24701235.operation) c:RegisterEffect(e6) end function c24701235.retreg(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() --to hand local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e1:SetDescription(aux.Stringid(24701235,0)) e1:SetCategory(CATEGORY_TOHAND) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetReset(RESET_EVENT+0x1ee0000+RESET_PHASE+PHASE_END) e1:SetCondition(c24701235.retcon) e1:SetTarget(c24701235.rettg) e1:SetOperation(c24701235.retop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) c:RegisterEffect(e2) end function c24701235.retcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:GetFlagEffect(24701235)>0 or c:IsHasEffect(EFFECT_SPIRIT_DONOT_RETURN) then return false end if e:IsHasType(EFFECT_TYPE_TRIGGER_F) then return not c:IsHasEffect(EFFECT_SPIRIT_MAYNOT_RETURN) else return c:IsHasEffect(EFFECT_SPIRIT_MAYNOT_RETURN) end end function c24701235.rettg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_TOHAND,e:GetHandler(),1,0,0) end function c24701235.retop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SendtoHand(c,nil,REASON_EFFECT) end end function c24701235.sumop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetFlagEffect(tp,24701235)~=0 then return end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetTargetRange(LOCATION_HAND+LOCATION_MZONE,0) e1:SetCode(EFFECT_EXTRA_SUMMON_COUNT) e1:SetTarget(aux.TargetBoolFunction(Card.IsType,TYPE_SPIRIT)) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) Duel.RegisterFlagEffect(tp,24701235,RESET_PHASE+PHASE_END,0,1) end function c24701235.cfilter(c) return c:IsFaceup() and c:IsType(TYPE_SPIRIT) end function c24701235.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c24701235.cfilter,tp,LOCATION_MZONE,0,1,nil) end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(1) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c24701235.operation(e,tp,eg,ep,ev,re,r,rp) if not Duel.IsExistingMatchingCard(c24701235.cfilter,tp,LOCATION_MZONE,0,1,nil) then return end local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Draw(p,d,REASON_EFFECT) end
gpl-2.0
Lsty/ygopro-scripts
c45133463.lua
3
1452
--死神の呼び声 function c45133463.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_SPSUMMON_SUCCESS) e1:SetCondition(c45133463.condition) e1:SetTarget(c45133463.target) e1:SetOperation(c45133463.activate) c:RegisterEffect(e1) end function c45133463.cfiltetr(c,tp) return c:IsPreviousLocation(LOCATION_GRAVE) and c:GetPreviousControler()==tp end function c45133463.condition(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c45133463.cfiltetr,1,nil,tp) end function c45133463.filter(c,e,tp) local code=c:GetCode() return (code==78552773 or code==78275321) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c45133463.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c45133463.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c45133463.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c45133463.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c45133463.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
Lsty/ygopro-scripts
c17189677.lua
9
1181
--スネーク・レイン function c17189677.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_TOGRAVE) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(c17189677.cost) e1:SetTarget(c17189677.target) e1:SetOperation(c17189677.activate) c:RegisterEffect(e1) end function c17189677.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,e:GetHandler()) end Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD) end function c17189677.tgfilter(c) return c:IsRace(RACE_REPTILE) and c:IsType(TYPE_MONSTER) and c:IsAbleToGrave() end function c17189677.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c17189677.tgfilter,tp,LOCATION_DECK,0,4,nil) end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,4,tp,LOCATION_DECK) end function c17189677.activate(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(c17189677.tgfilter,tp,LOCATION_DECK,0,nil) if g:GetCount()>=4 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local sg=g:Select(tp,4,4,nil) Duel.SendtoGrave(sg,REASON_EFFECT) end end
gpl-2.0
Lsty/ygopro-scripts
c93946239.lua
9
1273
--無の煉獄 function c93946239.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DRAW) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCondition(c93946239.condition) e1:SetTarget(c93946239.target) e1:SetOperation(c93946239.activate) c:RegisterEffect(e1) end function c93946239.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)>2 end function c93946239.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(1) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c93946239.activate(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Draw(p,d,REASON_EFFECT) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetCountLimit(1) e1:SetReset(RESET_PHASE+PHASE_END) e1:SetOperation(c93946239.disop) Duel.RegisterEffect(e1,p) end function c93946239.disop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetFieldGroup(e:GetOwnerPlayer(),LOCATION_HAND,0) Duel.SendtoGrave(g,REASON_EFFECT+REASON_DISCARD) end
gpl-2.0
MalRD/darkstar
scripts/globals/instance.lua
48
1990
function updateInstanceTime(instance, elapsed, texttable) local players = instance:getChars(); local lastTimeUpdate = instance:getLastTimeUpdate(); local remainingTimeLimit = (instance:getTimeLimit()) * 60 - (elapsed / 1000); local wipeTime = instance:getWipeTime(); local message = 0; if (remainingTimeLimit < 0) then instance:fail(); return; end if (wipeTime == 0) then local wipe = true; for i,v in pairs(players) do if v:getHP() ~= 0 then wipe = false; break; end end if (wipe) then for i,v in pairs(players) do v:messageSpecial(texttable.PARTY_FALLEN, 3); end instance:setWipeTime(elapsed); end else if (elapsed - wipeTime) / 1000 > 180 then instance:fail(); return; else for i,v in pairs(players) do if v:getHP() ~= 0 then instance:setWipeTime(0); break; end end end end if (lastTimeUpdate == 0 and remainingTimeLimit < 600) then message = 600; elseif (lastTimeUpdate == 600 and remainingTimeLimit < 300) then message = 300; elseif (lastTimeUpdate == 300 and remainingTimeLimit < 60) then message = 60; elseif (lastTimeUpdate == 60 and remainingTimeLimit < 30) then message = 30; elseif (lastTimeUpdate == 30 and remainingTimeLimit < 10) then message = 10; end if (message ~= 0) then for i,v in pairs(players) do if (remainingTimeLimit >= 60) then v:messageSpecial(texttable.TIME_REMAINING_MINUTES, remainingTimeLimit / 60); else v:messageSpecial(texttable.TIME_REMAINING_SECONDS, remainingTimeLimit); end end instance:setLastTimeUpdate(message); end end
gpl-3.0