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 |
|---|---|---|---|---|---|
anshkumar/yugioh-glaze | assets/script/c95929069.lua | 3 | 1841 | --アイス・ハンド
function c95929069.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(95929069,0))
e1:SetCategory(CATEGORY_DESTROY+CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c95929069.condition)
e1:SetTarget(c95929069.target)
e1:SetOperation(c95929069.operation)
c:RegisterEffect(e1)
end
function c95929069.condition(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:GetPreviousControler()==tp and c:IsReason(REASON_DESTROY) and rp~=tp
end
function c95929069.dfilter(c)
return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsDestructable()
end
function c95929069.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) and c95929069.dfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c95929069.dfilter,tp,0,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c95929069.dfilter,tp,0,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c95929069.spfilter(c,e,tp)
return c:IsCode(68535320) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c95929069.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.Destroy(tc,REASON_EFFECT)~=0 then
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local g=Duel.GetMatchingGroup(c95929069.spfilter,tp,LOCATION_DECK,0,nil,e,tp)
if g:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(95929069,1)) then
Duel.BreakEffect()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:Select(tp,1,1,nil)
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP)
end
end
end
| gpl-2.0 |
zwhfly/openwrt-luci | modules/admin-full/luasrc/model/cbi/admin_network/iface_add.lua | 79 | 3091 | --[[
LuCI - Lua Configuration Interface
Copyright 2009-2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local nw = require "luci.model.network".init()
local fw = require "luci.model.firewall".init()
local utl = require "luci.util"
local uci = require "luci.model.uci".cursor()
m = SimpleForm("network", translate("Create Interface"))
m.redirect = luci.dispatcher.build_url("admin/network/network")
m.reset = false
newnet = m:field(Value, "_netname", translate("Name of the new interface"),
translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " ..
"<code>0-9</code> and <code>_</code>"
))
newnet:depends("_attach", "")
newnet.default = arg[1] and "net_" .. arg[1]:gsub("[^%w_]+", "_")
newnet.datatype = "uciname"
newproto = m:field(ListValue, "_netproto", translate("Protocol of the new interface"))
netbridge = m:field(Flag, "_bridge", translate("Create a bridge over multiple interfaces"))
sifname = m:field(Value, "_ifname", translate("Cover the following interface"))
sifname.widget = "radio"
sifname.template = "cbi/network_ifacelist"
sifname.nobridges = true
mifname = m:field(Value, "_ifnames", translate("Cover the following interfaces"))
mifname.widget = "checkbox"
mifname.template = "cbi/network_ifacelist"
mifname.nobridges = true
local _, p
for _, p in ipairs(nw:get_protocols()) do
if p:is_installed() then
newproto:value(p:proto(), p:get_i18n())
if not p:is_virtual() then netbridge:depends("_netproto", p:proto()) end
if not p:is_floating() then
sifname:depends({ _bridge = "", _netproto = p:proto()})
mifname:depends({ _bridge = "1", _netproto = p:proto()})
end
end
end
function newproto.validate(self, value, section)
local name = newnet:formvalue(section)
if not name or #name == 0 then
newnet:add_error(section, translate("No network name specified"))
elseif m:get(name) then
newnet:add_error(section, translate("The given network name is not unique"))
end
local proto = nw:get_protocol(value)
if proto and not proto:is_floating() then
local br = (netbridge:formvalue(section) == "1")
local ifn = br and mifname:formvalue(section) or sifname:formvalue(section)
for ifn in utl.imatch(ifn) do
return value
end
return nil, translate("The selected protocol needs a device assigned")
end
return value
end
function newproto.write(self, section, value)
local name = newnet:formvalue(section)
if name and #name > 0 then
local br = (netbridge:formvalue(section) == "1") and "bridge" or nil
local net = nw:add_network(name, { proto = value, type = br })
if net then
local ifn
for ifn in utl.imatch(
br and mifname:formvalue(section) or sifname:formvalue(section)
) do
net:add_interface(ifn)
end
nw:save("network")
nw:save("wireless")
end
luci.http.redirect(luci.dispatcher.build_url("admin/network/network", name))
end
end
return m
| apache-2.0 |
m-a-hicks/Simulacrum | Resources/Loaders/OrthoLoader.lua | 2 | 2193 | --==============================================================================
--------------------------- Generic Ortho Loader -------------------------------
--==============================================================================
-- Return a name to represent the functions of this loader
function loaderName()
return "Ortho Layout"
end
-- Recommend a layout for the above set of SSaces
function layoutRecommendation(resource,path)
local result = ""
if (resource:getRoot():NodePathExists(path) and
resource:hasSSpace(path)) then
local node = resource:getRoot():NodeByPath(path)
local vpname = node:NodeValue()
result = "<hsplit border=\"1\" size1=\"600\" size2=\"240\"><viewportslicer precedent=\"1\" name=\"" .. vpname .. "\" /><vsplit border=\"1\" size1=\"418\" size2=\"204\"><vsplit border=\"1\" precedent=\"1\" size1=\"207\" size2=\"207\"><viewportslicer precedent=\"1\" vpconf=\"nohud;\" name=\"" .. vpname .. "\" /><viewportslicer spconf=\"1;0;1;1;0;0;0;0;1;\" vpconf=\"nohud;\" name=\"" .. vpname .. "\" /></vsplit><viewportslicer spconf=\"0;1;1;0;0;1;0;1;0;\" vpconf=\"nohud;\" name=\"" .. vpname .. "\" /></vsplit></hsplit>"
end
return result
end
-- Return a proposed title for the path requested inside the resource
function sspaceListTitle(resource,path)
local retval = "Untitled"
if (resource:getRoot():NodePathExists(path)) then
local reqnode = resource:getRoot():NodeByPath(path)
retval = reqnode:NodeValue()
end
return retval
end
-- Add strings to a result list which names the available volumes
function sspaceList(resource,path,resultlist)
if (resource:getRoot():NodePathExists(path)) then
local node = resource:getRoot():NodeByPath(path)
if resource:hasSSpace(node:NodePath(true)) then
resultlist:push_back(node:NodeValue())
end
end
end
-- Add the loaded SSpace volumes into a list of the SAME SIZE as the sspaceList
function getSSpaceInto(resource,path,sspacename,targetspace)
resource:getSSpaceInto(targetspace,path)
if (resource:getRoot():NodePathExists(path)) then
local reqnode = resource:getRoot():NodeByPath(path)
targetspace:setName(reqnode:NodeValue())
end
end
| lgpl-3.0 |
zhaoxin54430/zhaoxin_test | src_luci/applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/olsrd.lua | 43 | 1470 | -- Copyright 2011 Manuel Munz <freifunk at somakoma dot de>
-- Licensed to the public under the Apache License 2.0.
m = Map("luci_statistics",
translate("OLSRd Plugin Configuration"),
translate("The OLSRd plugin reads information about meshed networks from the txtinfo plugin of OLSRd."))
s = m:section(NamedSection, "collectd_olsrd", "luci_statistics" )
enable = s:option(Flag, "enable", translate("Enable this plugin"))
enable.default = 0
host = s:option(Value, "Host", translate("Host"), translate("IP or hostname where to get the txtinfo output from"))
host.placeholder = "127.0.0.1"
host.datatype = "host"
host.rmempty = true
port = s:option(Value, "Port", translate("Port"))
port.placeholder = "2006"
port.datatype = "range(0,65535)"
port.rmempty = true
port.cast = "string"
cl = s:option(ListValue, "CollectLinks", translate("CollectLinks"),
translate("Specifies what information to collect about links."))
cl:value("No")
cl:value("Summary")
cl:value("Detail")
cl.default = "Detail"
cr = s:option(ListValue, "CollectRoutes", translate("CollectRoutes"),
translate("Specifies what information to collect about routes."))
cr:value("No")
cr:value("Summary")
cr:value("Detail")
cr.default = "Summary"
ct = s:option(ListValue, "CollectTopology", translate("CollectTopology"),
translate("Specifies what information to collect about the global topology."))
ct:value("No")
ct:value("Summary")
ct:value("Detail")
ct.default = "Summary"
return m
| gpl-2.0 |
sjznxd/lc-20130302 | applications/luci-openvpn/luasrc/model/cbi/openvpn.lua | 65 | 3316 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
local sys = require "luci.sys"
local uci = require "luci.model.uci".cursor()
local m = Map("openvpn", translate("OpenVPN"))
local s = m:section( TypedSection, "openvpn", translate("OpenVPN instances"), translate("Below is a list of configured OpenVPN instances and their current state") )
s.template = "cbi/tblsection"
s.template_addremove = "openvpn/cbi-select-input-add"
s.addremove = true
s.add_select_options = { }
s.extedit = luci.dispatcher.build_url(
"admin", "services", "openvpn", "basic", "%s"
)
uci:load("openvpn_recipes")
uci:foreach( "openvpn_recipes", "openvpn_recipe",
function(section)
s.add_select_options[section['.name']] =
section['_description'] or section['.name']
end
)
function s.parse(self, section)
local recipe = luci.http.formvalue(
luci.cbi.CREATE_PREFIX .. self.config .. "." ..
self.sectiontype .. ".select"
)
if recipe and not s.add_select_options[recipe] then
self.invalid_cts = true
else
TypedSection.parse( self, section )
end
end
function s.create(self, name)
local recipe = luci.http.formvalue(
luci.cbi.CREATE_PREFIX .. self.config .. "." ..
self.sectiontype .. ".select"
)
if name and not name:match("[^a-zA-Z0-9_]") then
uci:section(
"openvpn", "openvpn", name,
uci:get_all( "openvpn_recipes", recipe )
)
uci:delete("openvpn", name, "_role")
uci:delete("openvpn", name, "_description")
uci:save("openvpn")
luci.http.redirect( self.extedit:format(name) )
else
self.invalid_cts = true
end
end
s:option( Flag, "enabled", translate("Enabled") )
local active = s:option( DummyValue, "_active", translate("Started") )
function active.cfgvalue(self, section)
local pid = fs.readfile("/var/run/openvpn-%s.pid" % section)
if pid and #pid > 0 and tonumber(pid) ~= nil then
return (sys.process.signal(pid, 0))
and translatef("yes (%i)", pid)
or translate("no")
end
return translate("no")
end
local updown = s:option( Button, "_updown", translate("Start/Stop") )
updown._state = false
function updown.cbid(self, section)
local pid = fs.readfile("/var/run/openvpn-%s.pid" % section)
self._state = pid and #pid > 0 and sys.process.signal(pid, 0)
self.option = self._state and "stop" or "start"
return AbstractValue.cbid(self, section)
end
function updown.cfgvalue(self, section)
self.title = self._state and "stop" or "start"
self.inputstyle = self._state and "reset" or "reload"
end
function updown.write(self, section, value)
if self.option == "stop" then
luci.sys.call("/etc/init.d/openvpn down %s" % section)
else
luci.sys.call("/etc/init.d/openvpn up %s" % section)
end
end
local port = s:option( DummyValue, "port", translate("Port") )
function port.cfgvalue(self, section)
local val = AbstractValue.cfgvalue(self, section)
return val or "1194"
end
local proto = s:option( DummyValue, "proto", translate("Protocol") )
function proto.cfgvalue(self, section)
local val = AbstractValue.cfgvalue(self, section)
return val or "udp"
end
return m
| apache-2.0 |
anshkumar/yugioh-glaze | assets/script/c20457551.lua | 3 | 2494 | --鋼核収納
function c20457551.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:SetTarget(c20457551.target)
e1:SetOperation(c20457551.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(c20457551.eqlimit)
c:RegisterEffect(e2)
--atk down
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EVENT_DAMAGE_CALCULATING)
e3:SetRange(LOCATION_SZONE)
e3:SetOperation(c20457551.atkdown)
c:RegisterEffect(e3)
--destroy sub
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_EQUIP+EFFECT_TYPE_CONTINUOUS)
e4:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e4:SetCode(EFFECT_DESTROY_REPLACE)
e4:SetTarget(c20457551.desreptg)
c:RegisterEffect(e4)
end
function c20457551.eqlimit(e,c)
return c:IsSetCard(0x1d)
end
function c20457551.filter(c)
return c:IsFaceup() and c:IsSetCard(0x1d)
end
function c20457551.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c20457551.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c20457551.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c20457551.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c20457551.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 c20457551.atkdown(e,tp,eg,ep,ev,re,r,rp)
local eqc=e:GetHandler():GetEquipTarget()
if Duel.GetAttacker()~=eqc and Duel.GetAttackTarget()~=eqc then return end
local tc=eqc:GetBattleTarget()
if tc then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_PHASE+RESET_DAMAGE_CAL)
e1:SetValue(-eqc:GetLevel()*100)
tc:RegisterEffect(e1)
end
end
function c20457551.desreptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetCurrentPhase()==PHASE_END end
if Duel.SelectYesNo(tp,aux.Stringid(20457551,0)) then
Duel.SendtoGrave(e:GetHandler(),REASON_EFFECT)
return true
else return false end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c85310252.lua | 5 | 2159 | --ドドドドライバー
function c85310252.initial_effect(c)
--lv change
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(c85310252.spcon)
e1:SetOperation(c85310252.spop)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(85310252,0))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(2)
e2:SetCondition(c85310252.condition)
e2:SetTarget(c85310252.target)
e2:SetOperation(c85310252.operation)
c:RegisterEffect(e2)
end
function c85310252.spcon(e,tp,eg,ep,ev,re,r,rp)
return re and re:GetHandler():IsSetCard(0x82)
end
function c85310252.spop(e,tp,eg,ep,ev,re,r,rp)
e:GetHandler():RegisterFlagEffect(85310252,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
end
function c85310252.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetFlagEffect(85310252)>0
end
function c85310252.filter(c)
return c:IsFaceup() and c:IsSetCard(0x82) and c:IsLevelAbove(1)
end
function c85310252.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c85310252.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c85310252.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,c85310252.filter,tp,LOCATION_MZONE,0,1,1,nil)
local tc=g:GetFirst()
local op=0
if tc:GetLevel()==1 then op=Duel.SelectOption(tp,aux.Stringid(85310252,1))
else op=Duel.SelectOption(tp,aux.Stringid(85310252,1),aux.Stringid(85310252,2)) end
e:SetLabel(op)
end
function c85310252.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetReset(RESET_EVENT+0x1fe0000)
if e:GetLabel()==0 then
e1:SetValue(1)
else e1:SetValue(-1) end
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c19041767.lua | 3 | 1897 | --デュアル・サモナー
function c19041767.initial_effect(c)
--battle indes
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_INDESTRUCTABLE_COUNT)
e1:SetCountLimit(1)
e1:SetValue(c19041767.valcon)
c:RegisterEffect(e1)
--instant
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(19041767,0))
e2:SetCategory(CATEGORY_SUMMON)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetCountLimit(1)
e2:SetCondition(c19041767.condition)
e2:SetCost(c19041767.cost)
e2:SetTarget(c19041767.target)
e2:SetOperation(c19041767.operation)
c:RegisterEffect(e2)
end
function c19041767.valcon(e,re,r,rp)
return bit.band(r,REASON_BATTLE)~=0
end
function c19041767.filter(c)
return c:IsType(TYPE_DUAL) and (c:IsSummonable(true,nil) or c:IsMSetable(true,nil))
end
function c19041767.condition(e,tp,eg,ep,ev,re,r,rp)
return tp~=Duel.GetTurnPlayer()
end
function c19041767.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 c19041767.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c19041767.filter,tp,LOCATION_HAND+LOCATION_MZONE,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_SUMMON,nil,1,0,0)
end
function c19041767.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SUMMON)
local g=Duel.SelectMatchingCard(tp,c19041767.filter,tp,LOCATION_HAND+LOCATION_MZONE,0,1,1,nil)
local tc=g:GetFirst()
if tc then
local s1=tc:IsSummonable(true,nil)
local s2=tc:IsMSetable(true,nil)
if (s1 and s2 and Duel.SelectPosition(tp,tc,POS_FACEUP_ATTACK+POS_FACEDOWN_DEFENCE)==POS_FACEUP_ATTACK) or not s2 then
Duel.Summon(tp,tc,true,nil)
else
Duel.MSet(tp,tc,true,nil)
end
end
end
| gpl-2.0 |
Ardavans/DSR | mbwrap/games/MazeItem.lua | 2 | 2309 | -- Copyright (c) 2015-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
local MazeItem = torch.class('MazeItem')
-- An item can have attributes (optional except type) such as:
-- type: type of the item such as water, block
-- loc: absolute coordinate of the item
-- name: unique name for the item (optional)
-- All attributes are visible to the agents.
function MazeItem:__init(attr)
self.type = attr.type
self.name = attr.name
self.attr = attr
self.loc = self.attr.loc
if self.type == 'block' then
function self:is_reachable() return false end
elseif self.type == 'door' then
function self:is_reachable()
if self.attr.open == 'open' then
return true
end
return false
end
else
function self:is_reachable() return true end
end
end
-- Warning: basic clone only shallow copies
-- properties in the attr.
-- only numerical, string properties, and
-- the .loc table (if it exists) will be copied
-- override this (probably make a class)
-- if you want more complicated behavior
function MazeItem:clone()
local attr = {}
for i,j in pairs(self.attr) do
if type(j) == 'number' or type(j) == 'string' then
attr[i] = j
end
end
if self.attr.loc then
attr.loc = {}
attr.loc.x = self.attr.loc.x
attr.loc.y = self.attr.loc.y
end
local e = self.new(attr)
return e
end
-- use this to change item attributes
-- to match a new maze that the item
-- will belong to.
function MazeItem:change_owner(maze)
end
function MazeItem:to_sentence(dy, dx, disable_loc)
local s = {}
for k,v in pairs(self.attr) do
if k == 'loc' then
if not disable_loc then
local y = self.loc.y - dy
local x = self.loc.x - dx
table.insert(s, 'y' .. y .. 'x' .. x)
end
elseif type(k) == 'string' and k:sub(1,1) == '_' then
-- skip
else
table.insert(s, v)
end
end
return s
end
| mit |
anshkumar/yugioh-glaze | assets/script/c64990807.lua | 3 | 2361 | --氷結界の三方陣
function c64990807.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY+CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCost(c64990807.cost)
e1:SetTarget(c64990807.target)
e1:SetOperation(c64990807.activate)
c:RegisterEffect(e1)
end
function c64990807.cfilter(c)
return c:IsSetCard(0x2f) and c:IsType(TYPE_MONSTER) and not c:IsPublic()
end
function c64990807.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetMatchingGroup(c64990807.cfilter,tp,LOCATION_HAND,0,nil):GetClassCount(Card.GetCode)>=3 end
local g=Duel.GetMatchingGroup(c64990807.cfilter,tp,LOCATION_HAND,0,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONFIRM)
local tc1=g:Select(tp,1,1,nil):GetFirst()
g:Remove(Card.IsCode,nil,tc1:GetCode())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONFIRM)
local tc2=g:Select(tp,1,1,nil):GetFirst()
g:Remove(Card.IsCode,nil,tc2:GetCode())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONFIRM)
local tc3=g:Select(tp,1,1,nil):GetFirst()
local cg=Group.FromCards(tc1,tc2,tc3)
Duel.ConfirmCards(1-tp,cg)
Duel.ShuffleHand(tp)
end
function c64990807.spfilter(c,e,tp)
return c:IsSetCard(0x2f) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c64990807.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsOnField() and chkc:IsDestructable() end
if chk==0 then return Duel.IsExistingTarget(Card.IsDestructable,tp,0,LOCATION_ONFIELD,1,nil)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c64990807.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,Card.IsDestructable,tp,0,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c64990807.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.Destroy(tc,REASON_EFFECT)~=0 then
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c64990807.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c73136204.lua | 3 | 2820 | --森羅の渡し守 ロータス
function c73136204.initial_effect(c)
--deck
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(73136204,0))
e1:SetCategory(CATEGORY_TOGRAVE)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetTarget(c73136204.target)
e1:SetOperation(c73136204.operation)
c:RegisterEffect(e1)
--todeck
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(73136204,2))
e2:SetCategory(CATEGORY_TODECK)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetCondition(c73136204.tdcon)
e2:SetTarget(c73136204.tdtg)
e2:SetOperation(c73136204.tdop)
c:RegisterEffect(e2)
end
function c73136204.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local ac=Duel.GetFieldGroupCount(tp,0,LOCATION_ONFIELD)
return ac>0 and Duel.IsPlayerCanDiscardDeck(tp,ac)
end
end
function c73136204.operation(e,tp,eg,ep,ev,re,r,rp)
local ac=Duel.GetFieldGroupCount(tp,0,LOCATION_ONFIELD)
if ac==0 or not Duel.IsPlayerCanDiscardDeck(tp,ac) then return end
Duel.ConfirmDecktop(tp,ac)
local g=Duel.GetDecktopGroup(tp,ac)
local sg=g:Filter(Card.IsRace,nil,RACE_PLANT)
if sg:GetCount()>0 then
Duel.DisableShuffleCheck()
Duel.SendtoGrave(sg,REASON_EFFECT+REASON_REVEAL)
end
ac=ac-sg:GetCount()
if ac>0 then
Duel.SortDecktop(tp,tp,ac)
for i=1,ac do
local mg=Duel.GetDecktopGroup(tp,1)
Duel.MoveSequence(mg:GetFirst(),1)
end
end
end
function c73136204.tdcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_DECK) and
(c:IsReason(REASON_REVEAL) or c:GetPreviousPosition()==POS_FACEUP_DEFENCE or Duel.IsPlayerAffectedByEffect(tp,EFFECT_REVERSE_DECK))
end
function c73136204.filter(c)
return c:IsSetCard(0x90) and not c:IsCode(73136204) and c:IsAbleToDeck()
end
function c73136204.tdtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c73136204.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c73136204.filter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c73136204.filter,tp,LOCATION_GRAVE,0,1,5,nil)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,g:GetCount(),0,0)
end
function c73136204.tdop(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 sg:GetCount()>0 then
Duel.SendtoDeck(sg,nil,0,REASON_EFFECT)
local og=Duel.GetOperatedGroup()
local ct=og:FilterCount(Card.IsLocation,nil,LOCATION_DECK)
if ct==0 then return end
Duel.SortDecktop(tp,tp,ct)
for i=1,ct do
local mg=Duel.GetDecktopGroup(tp,1)
Duel.MoveSequence(mg:GetFirst(),1)
end
end
end
| gpl-2.0 |
paladiyom/paladerz | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
heroku/heroku-kong | spec/fixtures/blueprints.lua | 1 | 7702 | local ssl_fixtures = require "spec.fixtures.ssl"
local utils = require "kong.tools.utils"
local deep_merge = utils.deep_merge
local fmt = string.format
local Blueprint = {}
Blueprint.__index = Blueprint
function Blueprint:build(overrides)
overrides = overrides or {}
return deep_merge(self.build_function(overrides), overrides)
end
function Blueprint:insert(overrides, options)
local entity, err = self.dao:insert(self:build(overrides), options)
if err then
error(err, 2)
end
return entity
end
function Blueprint:remove(overrides, options)
local entity, err = self.dao:remove({ id = overrides.id }, options)
if err then
error(err, 2)
end
return entity
end
function Blueprint:insert_n(n, overrides, options)
local res = {}
for i=1,n do
res[i] = self:insert(overrides, options)
end
return res
end
local function new_blueprint(dao, build_function)
return setmetatable({
dao = dao,
build_function = build_function,
}, Blueprint)
end
local Sequence = {}
Sequence.__index = Sequence
function Sequence:next()
self.count = self.count + 1
return fmt(self.sequence_string, self.count)
end
local function new_sequence(sequence_string)
return setmetatable({
count = 0,
sequence_string = sequence_string,
}, Sequence)
end
local _M = {}
function _M.new(db)
local res = {}
local sni_seq = new_sequence("server-name-%d")
res.snis = new_blueprint(db.snis, function(overrides)
return {
name = sni_seq:next(),
certificate = overrides.certificate or res.certificates:insert(),
}
end)
res.certificates = new_blueprint(db.certificates, function()
return {
cert = ssl_fixtures.cert,
key = ssl_fixtures.key,
}
end)
local upstream_name_seq = new_sequence("upstream-%d")
res.upstreams = new_blueprint(db.upstreams, function(overrides)
local slots = overrides.slots or 100
return {
name = upstream_name_seq:next(),
slots = slots,
}
end)
local consumer_custom_id_seq = new_sequence("consumer-id-%d")
local consumer_username_seq = new_sequence("consumer-username-%d")
res.consumers = new_blueprint(db.consumers, function()
return {
custom_id = consumer_custom_id_seq:next(),
username = consumer_username_seq:next(),
}
end)
res.targets = new_blueprint(db.targets, function(overrides)
return {
weight = 10,
upstream = overrides.upstream or res.upstreams:insert(),
}
end)
res.plugins = new_blueprint(db.plugins, function()
return {}
end)
res.routes = new_blueprint(db.routes, function(overrides)
return {
service = overrides.service or res.services:insert(),
}
end)
res.services = new_blueprint(db.services, function()
return {
protocol = "http",
host = "127.0.0.1",
port = 15555,
}
end)
local named_service_name_seq = new_sequence("service-name-%d")
local named_service_host_seq = new_sequence("service-host-%d.test")
res.named_services = new_blueprint(db.services, function()
return {
protocol = "http",
name = named_service_name_seq:next(),
host = named_service_host_seq:next(),
port = 15555,
}
end)
local named_route_name_seq = new_sequence("route-name-%d")
local named_route_host_seq = new_sequence("route-host-%d.test")
res.named_routes = new_blueprint(db.routes, function(overrides)
return {
name = named_route_name_seq:next(),
hosts = { named_route_host_seq:next() },
service = overrides.service or res.services:insert(),
}
end)
res.acl_plugins = new_blueprint(db.plugins, function()
return {
name = "acl",
config = {},
}
end)
local acl_group_seq = new_sequence("acl-group-%d")
res.acls = new_blueprint(db.acls, function()
return {
group = acl_group_seq:next(),
}
end)
res.cors_plugins = new_blueprint(db.plugins, function()
return {
name = "cors",
config = {
origins = { "example.com" },
methods = { "GET" },
headers = { "origin", "type", "accepts"},
exposed_headers = { "x-auth-token" },
max_age = 23,
credentials = true,
}
}
end)
res.loggly_plugins = new_blueprint(db.plugins, function()
return {
name = "loggly",
config = {}, -- all fields have default values already
}
end)
res.tcp_log_plugins = new_blueprint(db.plugins, function()
return {
name = "tcp-log",
config = {
host = "127.0.0.1",
port = 35001,
},
}
end)
res.udp_log_plugins = new_blueprint(db.plugins, function()
return {
name = "udp-log",
config = {
host = "127.0.0.1",
port = 35001,
},
}
end)
res.jwt_plugins = new_blueprint(db.plugins, function()
return {
name = "jwt",
config = {},
}
end)
local jwt_key_seq = new_sequence("jwt-key-%d")
res.jwt_secrets = new_blueprint(db.jwt_secrets, function()
return {
key = jwt_key_seq:next(),
secret = "secret",
}
end)
res.oauth2_plugins = new_blueprint(db.plugins, function()
return {
name = "oauth2",
config = {
scopes = { "email", "profile" },
enable_authorization_code = true,
mandatory_scope = true,
provision_key = "provision123",
token_expiration = 5,
enable_implicit_grant = true,
}
}
end)
res.oauth2_credentials = new_blueprint(db.oauth2_credentials, function()
return {
name = "oauth2 credential",
client_secret = "secret",
}
end)
local oauth_code_seq = new_sequence("oauth-code-%d")
res.oauth2_authorization_codes = new_blueprint(db.oauth2_authorization_codes, function()
return {
code = oauth_code_seq:next(),
scope = "default",
}
end)
res.oauth2_tokens = new_blueprint(db.oauth2_tokens, function()
return {
token_type = "bearer",
expires_in = 1000000000,
scope = "default",
}
end)
res.key_auth_plugins = new_blueprint(db.plugins, function()
return {
name = "key-auth",
config = {},
}
end)
local keyauth_key_seq = new_sequence("keyauth-key-%d")
res.keyauth_credentials = new_blueprint(db.keyauth_credentials, function()
return {
key = keyauth_key_seq:next(),
}
end)
res.basicauth_credentials = new_blueprint(db.basicauth_credentials, function()
return {}
end)
res.hmac_auth_plugins = new_blueprint(db.plugins, function()
return {
name = "hmac-auth",
config = {},
}
end)
local hmac_username_seq = new_sequence("hmac-username-%d")
res.hmacauth_credentials = new_blueprint(db.hmacauth_credentials, function()
return {
username = hmac_username_seq:next(),
secret = "secret",
}
end)
res.rate_limiting_plugins = new_blueprint(db.plugins, function()
return {
name = "rate-limiting",
config = {},
}
end)
res.response_ratelimiting_plugins = new_blueprint(db.plugins, function()
return {
name = "response-ratelimiting",
config = {},
}
end)
res.datadog_plugins = new_blueprint(db.plugins, function()
return {
name = "datadog",
config = {},
}
end)
res.statsd_plugins = new_blueprint(db.plugins, function()
return {
name = "statsd",
config = {},
}
end)
res.rewriter_plugins = new_blueprint(db.plugins, function()
return {
name = "rewriter",
config = {},
}
end)
return res
end
return _M
| mit |
anshkumar/yugioh-glaze | assets/script/c36278828.lua | 3 | 1025 | --ヴェノム・サーペント
function c36278828.initial_effect(c)
--add counter
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(36278828,0))
e1:SetCategory(CATEGORY_COUNTER)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_MZONE)
e1:SetTarget(c36278828.target)
e1:SetOperation(c36278828.operation)
c:RegisterEffect(e1)
end
function c36278828.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsCanAddCounter(0x9,1) end
if chk==0 then return Duel.IsExistingTarget(Card.IsCanAddCounter,tp,0,LOCATION_MZONE,1,nil,0x9,1) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,Card.IsCanAddCounter,tp,0,LOCATION_MZONE,1,1,nil,0x9,1)
Duel.SetOperationInfo(0,CATEGORY_COUNTER,nil,1,0,0)
end
function c36278828.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsCanAddCounter(0x9,1) then
tc:AddCounter(0x9,1)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c1050186.lua | 9 | 1182 | --星因士 ウヌク
function c1050186.initial_effect(c)
--tograve
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(1050186,0))
e1:SetCategory(CATEGORY_TOGRAVE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e1:SetCountLimit(1,1050186)
e1:SetTarget(c1050186.target)
e1:SetOperation(c1050186.operation)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS)
c:RegisterEffect(e2)
local e3=e1:Clone()
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e3)
end
function c1050186.filter(c)
return c:IsSetCard(0x9c) and not c:IsCode(1050186) and c:IsAbleToGrave()
end
function c1050186.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c1050186.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK)
end
function c1050186.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c1050186.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoGrave(g,REASON_EFFECT)
end
end
| gpl-2.0 |
nhnb/stendhal | data/script/region/deniran/city/citizens.lua | 3 | 4705 | --[[
***************************************************************************
* Copyright © 2021 - Arianne *
***************************************************************************
***************************************************************************
* *
* 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. *
* *
***************************************************************************
]]
-- some non-interactive NPCs to wander around Deniran
local zones = {
["0_deniran_city"] = {
{ -- man walking house to house
sprite = "youngnpc",
path = {
nodes = {
{17,33}, {32,33}, {32,56}, {16,56}, {16,52}, {16,56},
{32,56}, {32,75}, {38,75}, {38,76}, {44,76}, {44,77},
{93,77}, {93,75}, {103,75}, {103,65}, {96,65}, {96,60},
},
retrace = true,
speed = 0.4,
on_collide = CollisionAction.STOP,
},
},
},
["0_deniran_city_e"] = {
{ -- woman sitting on bench
sprite = "womanonstoolnpc",
desc = "You see a woman sitting on a bench.",
pos = {x=53, y=55},
facedir = Direction.DOWN,
},
},
["0_deniran_city_e2"] = {
{ -- old man walking around trees
outfit = {
layers = "body=0,head=0,eyes=5,hair=39,dress=53,mask=1,hat=6",
},
path = {
nodes = {
{73,47}, {73,34}, {47,34}, {47,47},
},
},
},
},
["0_deniran_city_s"] = {
{ -- woman walking along main path
outfit = {
layers = "body=2,head=0,eyes=8,dress=55,hair=3",
colors = {hair=0x01e1ec, dress=0xffc000, eyes=0xee82ee},
},
path = {
nodes = {
{75,61}, {80,61}, {80,86}, {80,72}, {75,72},
},
},
},
{ -- man outside wall
sprite = "groundskeepernpc",
path = {
nodes = {
{77,100}, {29,100}, {29,85}, {4,85}, {4,100}, {87,100},
{87,96}, {126,96}, {126,111}, {87,111}, {87,100},
},
on_collide = CollisionAction.STOP,
},
},
},
["0_deniran_city_s_e2"] = {
{ -- man walking house to house
sprite = "holidaymakernpc",
path = {
nodes = {
{22,96}, {22,101}, {29,101}, {29,100}, {45,100}, {45,106},
{64,106},
},
retrace = true,
},
},
},
["0_deniran_city_se"] = {
{ -- woman walking around pond
outfit = {
layers = "body=2,head=0,eyes=8,dress=971,mask=8,hair=14",
colors = {eyes=Color.GREEN},
},
path = {
nodes = {
{65,29}, {45,29}, {45,36}, {42,36}, {42,44}, {46,44}, {46,48},
{53,48}, {53,55}, {62,55}, {62,49}, {76,49}, {76,41}, {70,41},
{70,36}, {65,36},
},
on_collide = CollisionAction.STOP,
},
},
},
["0_deniran_city_sw"] = {
{ -- boy running around
sprite = "childnpc",
desc = "You see a young Deniran boy.",
path = {
nodes = {
{47,15}, {47,34}, {46,34}, {46,59}, {125,59}, {125,9}, {69,9},
{69,15},
},
speed = 0.6,
},
},
},
["0_deniran_city_w"] = {
{ -- woman walking in orchard
sprite = "girlnpc",
path = {
nodes = {
{83,104}, {118,104}, {118,89}, {83,89},
},
},
},
},
}
for zone_name, entities_table in pairs(zones) do
if not game:setZone(zone_name) then
logger:error("could not set zone: " .. zone_name)
else
for _, data in ipairs(entities_table) do
local citizen = entities:createSilentNPC()
if data.desc == nil then
data.desc = "You see a citizen of Deniran City."
end
citizen:setDescription(data.desc)
if type(data.outfit) == "table" and data.outfit.layers ~= nil then
citizen:setOutfit(data.outfit.layers)
if type(data.outfit.colors) == "table" then
for k, v in pairs(data.outfit.colors) do
citizen:setOutfitColor(k, v)
end
end
elseif data.sprite ~= nil then
citizen:setEntityClass(data.sprite)
end
if type(data.path) == "table" and type(data.path.nodes) == "table" then
citizen:setPathAndPosition(data.path.nodes, true)
if data.path.retrace then
citizen:setRetracePath()
end
if data.path.speed ~= nil then
citizen:setBaseSpeed(data.path.speed)
end
citizen:setCollisionAction(data.path.on_collide or CollisionAction.REVERSE)
elseif type(data.pos) == "table" then
citizen:setPosition(data.pos.x, data.pos.y)
end
if data.facedir ~= nil then
citizen:setDirection(data.facedir)
end
game:add(citizen)
end
end
end
| gpl-2.0 |
andrejzverev/rspamd | src/plugins/lua/settings.lua | 1 | 12116 | --[[
Copyright (c) 2011-2015, Vsevolod Stakhov <vsevolod@highsecure.ru>
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.
]]--
-- This plugin implements user dynamic settings
-- Settings documentation can be found here:
-- https://rspamd.com/doc/configuration/settings.html
local set_section = rspamd_config:get_all_opt("settings")
local settings = {
[1] = {},
[2] = {},
[3] = {}
}
local settings_ids = {}
local settings_initialized = false
local max_pri = 0
local rspamd_logger = require "rspamd_logger"
local rspamd_ip = require "rspamd_ip"
local rspamd_regexp = require "rspamd_regexp"
local ucl = require "ucl"
require "fun" ()
-- Checks for overrided settings within query params and returns 'true' if
-- settings are overrided
local function check_query_settings(task)
-- Try 'settings' attribute
local query_set = task:get_request_header('settings')
if query_set then
local parser = ucl.parser()
local res,err = parser:parse_string(tostring(query_set))
if res then
task:set_settings(parser:get_object())
return true
end
end
local query_maxscore = task:get_request_header('maxscore')
if query_maxscore then
-- We have score limits redefined by request
local ms = tonumber(tostring(query_maxscore))
if ms then
local nset = {
default = {
actions = {
reject = ms
}
}
}
local query_softscore = task:get_request_header('softscore')
if query_softscore then
local ss = tonumber(tostring(query_softscore))
nset['default']['actions']['add header'] = ss
end
task:set_settings(nset)
return true
end
end
local settings_id = task:get_request_header('settings-id')
if settings_id and settings_initialized then
-- settings_id is rspamd text, so need to convert it to string for lua
local id_str = tostring(settings_id)
local elt = settings_ids[id_str]
if elt and elt['apply'] then
task:set_settings(elt['apply'])
rspamd_logger.infox(task, "applying settings id %s", id_str)
return true
end
end
return false
end
-- Check limit for a task
local function check_settings(task)
local function check_addr_setting(rule, addr)
local function check_specific_addr(elt)
if rule['name'] then
if elt['addr'] == rule['name'] then
return true
end
end
if rule['user'] then
if rule['user'] == elt['user'] then
return true
end
end
if rule['domain'] then
if rule['domain'] == elt['domain'] then
return true
end
end
if rule['regexp'] then
if rule['regexp']:match(elt['addr']) then
return true
end
end
return false
end
for _, e in ipairs(addr) do
if check_specific_addr(e) then
return true
end
end
return false
end
local function check_ip_setting(rule, ip)
if rule[2] ~= 0 then
local nip = ip:apply_mask(rule[2])
if nip and nip:to_string() == rule[1]:to_string() then
return true
end
elseif ip:to_string() == rule[1]:to_string() then
return true
end
return false
end
local function check_specific_setting(name, rule, ip, from, rcpt, user)
local res = false
if rule['ip'] then
if not ip then
return nil
end
for _, i in ipairs(rule['ip']) do
res = check_ip_setting(i, ip)
if res then
break
end
end
if not res then
return nil
end
end
if rule['from'] then
if not from then
return nil
end
for _, i in ipairs(rule['from']) do
res = check_addr_setting(i, from)
if res then
break
end
end
if not res then
return nil
end
end
if rule['rcpt'] then
if not rcpt then
return nil
end
for _, i in ipairs(rule['rcpt']) do
res = check_addr_setting(i, rcpt)
if res then
break
end
end
if not res then
return nil
end
end
if rule['user'] then
if not user then
return nil
end
for _, i in ipairs(rule['user']) do
res = check_addr_setting(i, user)
if res then
break
end
end
if not res then
return nil
end
end
if res then
if rule['whitelist'] then
rule['apply'] = {whitelist = true}
end
return rule
end
return nil
end
-- Check if we have override as query argument
if check_query_settings(task) then
return
end
-- Do not waste resources
if not settings_initialized then
return
end
rspamd_logger.infox(task, "check for settings")
local ip = task:get_from_ip()
local from = task:get_from()
local rcpt = task:get_recipients()
local uname = task:get_user()
local user = {}
if uname then
user[1] = {}
for localpart, domainpart in string.gmatch(uname, "(.+)@(.+)") do
user[1]["user"] = localpart
user[1]["domain"] = domainpart
user[1]["addr"] = uname
break
end
if not user[1]["addr"] then
user[1]["user"] = uname
user[1]["addr"] = uname
end
end
-- Match rules according their order
for pri = max_pri,1,-1 do
if settings[pri] then
for name, r in pairs(settings[pri]) do
local rule = check_specific_setting(name, r, ip, from, rcpt, user)
if rule then
rspamd_logger.infox(task, "<%1> apply settings according to rule %2",
task:get_message_id(), name)
if rule['apply'] then
task:set_settings(rule['apply'])
end
if rule['symbols'] then
-- Add symbols, specified in the settings
each(function(val)
task:insert_result(val, 1.0)
end, rule['symbols'])
end
end
end
end
end
end
-- Process settings based on their priority
local function process_settings_table(tbl)
local get_priority = function(elt)
local pri_tonum = function(p)
if p then
if type(p) == "number" then
return tonumber(p)
elseif type(p) == "string" then
if p == "high" then
return 3
elseif p == "medium" then
return 2
end
end
end
return 1
end
return pri_tonum(elt['priority'])
end
-- Check the setting element internal data
local process_setting_elt = function(name, elt)
-- Process IP address
local function process_ip(ip)
local out = {}
if type(ip) == "table" then
for i,v in ipairs(ip) do
table.insert(out, process_ip(v))
end
elseif type(ip) == "string" then
local slash = string.find(ip, '/')
if not slash then
-- Just a plain IP address
local res = rspamd_ip.from_string(ip)
if res:is_valid() then
out[1] = res
out[2] = 0
else
rspamd_logger.errx(rspamd_config, "bad IP address: " .. ip)
return nil
end
else
local res = rspamd_ip.from_string(string.sub(ip, 1, slash - 1))
local mask = tonumber(string.sub(ip, slash + 1))
if res:is_valid() then
out[1] = res
out[2] = mask
else
rspamd_logger.errx(rspamd_config, "bad IP address: " .. ip)
return nil
end
end
else
return nil
end
return out
end
local function process_addr(addr)
local out = {}
if type(addr) == "table" then
for i,v in ipairs(addr) do
table.insert(out, process_addr(v))
end
elseif type(addr) == "string" then
local start = string.sub(addr, 1, 1)
if start == '/' then
-- It is a regexp
local re = rspamd_regexp.create(addr)
if re then
out['regexp'] = re
else
rspamd_logger.errx(rspamd_config, "bad regexp: " .. addr)
return nil
end
elseif start == '@' then
-- It is a domain if form @domain
out['domain'] = string.sub(addr, 2)
else
-- Check user@domain parts
local at = string.find(addr, '@')
if at then
-- It is full address
out['name'] = addr
else
-- It is a user
out['user'] = addr
end
end
else
return nil
end
return out
end
local check_table = function(elt, out)
if type(elt) == 'string' then
return {out}
end
return out
end
local out = {}
if elt['ip'] then
local ip = process_ip(elt['ip'])
if ip then
out['ip'] = check_table(elt['ip'], ip)
end
end
if elt['from'] then
local from = process_addr(elt['from'])
if from then
out['from'] = check_table(elt['from'], from)
end
end
if elt['rcpt'] then
local rcpt = process_addr(elt['rcpt'])
if rcpt then
out['rcpt'] = check_table(elt['rcpt'], rcpt)
end
end
if elt['user'] then
local user = process_addr(elt['user'])
if user then
out['user'] = check_table(elt['user'], user)
end
end
-- Now we must process actions
if elt['symbols'] then out['symbols'] = elt['symbols'] end
if elt['id'] then
out['id'] = elt['id']
settings_ids[elt['id']] = out
end
if elt['apply'] then
-- Just insert all metric results to the action key
out['apply'] = elt['apply']
elseif elt['whitelist'] or elt['want_spam'] then
out['whitelist'] = true
else
rspamd_logger.errx(rspamd_config, "no actions in settings: " .. name)
return nil
end
return out
end
settings_initialized = false
-- filter trash in the input
local ft = filter(
function(_, elt)
if type(elt) == "table" then
return true
end
return false
end, tbl)
-- clear all settings
max_pri = 0
local nrules = 0
settings_ids = {}
for k,v in pairs(settings) do settings[k]={} end
-- fill new settings by priority
for_each(function(k, v)
local pri = get_priority(v)
if pri > max_pri then max_pri = pri end
if not settings[pri] then
settings[pri] = {}
end
local s = process_setting_elt(k, v)
if s then
settings[pri][k] = s
nrules = nrules + 1
end
end, ft)
settings_initialized = true
rspamd_logger.infox(rspamd_config, 'loaded %1 elements of settings', nrules)
return true
end
-- Parse settings map from the ucl line
local function process_settings_map(string)
local ucl = require "ucl"
local parser = ucl.parser()
local res,err = parser:parse_string(string)
if not res then
rspamd_logger.warnx(rspamd_config, 'cannot parse settings map: ' .. err)
else
local obj = parser:get_object()
if obj['settings'] then
process_settings_table(obj['settings'])
else
process_settings_table(obj)
end
end
return res
end
if set_section and set_section[1] and type(set_section[1]) == "string" then
-- Just a map of ucl
if not rspamd_config:add_map(set_section[1], "settings map", process_settings_map) then
rspamd_logger.errx(rspamd_config, 'cannot load settings from %1', set_section)
end
elseif set_section and type(set_section) == "table" then
process_settings_table(set_section)
end
rspamd_config:register_pre_filter(check_settings)
| apache-2.0 |
anshkumar/yugioh-glaze | assets/script/c93016201.lua | 3 | 4075 | --王宮の弾圧
function c93016201.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c93016201.cost1)
e1:SetTarget(c93016201.target1)
e1:SetOperation(c93016201.activate1)
c:RegisterEffect(e1)
--Activate(timing)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(93016201,0))
e2:SetType(EFFECT_TYPE_ACTIVATE)
e2:SetCode(EVENT_SPSUMMON)
e2:SetCondition(c93016201.condition2)
e2:SetCost(c93016201.cost2)
e2:SetTarget(c93016201.target2)
e2:SetOperation(c93016201.activate2)
c:RegisterEffect(e2)
--instant
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(93016201,0))
e3:SetType(EFFECT_TYPE_QUICK_O)
e3:SetRange(LOCATION_SZONE)
e3:SetProperty(EFFECT_FLAG_BOTH_SIDE)
e3:SetCode(EVENT_SPSUMMON)
e3:SetCondition(c93016201.condition2)
e3:SetCost(c93016201.cost2)
e3:SetTarget(c93016201.target2)
e3:SetOperation(c93016201.activate2)
c:RegisterEffect(e3)
--instant(chain)
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(93016201,0))
e4:SetType(EFFECT_TYPE_QUICK_O)
e4:SetRange(LOCATION_SZONE)
e4:SetProperty(EFFECT_FLAG_BOTH_SIDE)
e4:SetCode(EVENT_CHAINING)
e4:SetCondition(c93016201.condition3)
e4:SetCost(c93016201.cost3)
e4:SetTarget(c93016201.target3)
e4:SetOperation(c93016201.activate3)
c:RegisterEffect(e4)
end
function c93016201.cost1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
e:SetLabel(0)
if not Duel.CheckLPCost(tp,800) then return end
local ct=Duel.GetCurrentChain()
if ct==1 then return end
local pe=Duel.GetChainInfo(ct-1,CHAININFO_TRIGGERING_EFFECT)
if not pe:IsHasCategory(CATEGORY_SPECIAL_SUMMON) then return end
if not Duel.IsChainDisablable(ct-1) then return end
if Duel.SelectYesNo(tp,aux.Stringid(93016201,1)) then
Duel.PayLPCost(tp,800)
e:SetLabel(1)
end
end
function c93016201.target1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
if e:GetLabel()~=1 then return end
local ct=Duel.GetCurrentChain()
local te=Duel.GetChainInfo(ct-1,CHAININFO_TRIGGERING_EFFECT)
local tc=te:GetHandler()
Duel.SetOperationInfo(0,CATEGORY_DISABLE,tc,1,0,0)
if tc:IsDestructable() and tc:IsRelateToEffect(te) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,tc,1,0,0)
end
end
function c93016201.activate1(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if e:GetLabel()~=1 then return end
if not c:IsRelateToEffect(e) then return end
local ct=Duel.GetChainInfo(0,CHAININFO_CHAIN_COUNT)
local te=Duel.GetChainInfo(ct-1,CHAININFO_TRIGGERING_EFFECT)
local tc=te:GetHandler()
Duel.NegateEffect(ct-1)
if tc:IsRelateToEffect(te) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
function c93016201.condition2(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentChain()==0
end
function c93016201.cost2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,800) end
Duel.PayLPCost(tp,800)
end
function c93016201.target2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DISABLE_SUMMON,eg,eg:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,eg:GetCount(),0,0)
end
function c93016201.activate2(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
Duel.NegateSummon(eg)
Duel.Destroy(eg,REASON_EFFECT)
end
function c93016201.condition3(e,tp,eg,ep,ev,re,r,rp)
return re:IsHasCategory(CATEGORY_SPECIAL_SUMMON) and Duel.IsChainDisablable(ev)
end
function c93016201.cost3(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,800) end
Duel.PayLPCost(tp,800)
end
function c93016201.target3(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DISABLE,eg,1,0,0)
if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function c93016201.activate3(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
Duel.NegateEffect(ev)
if re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c71578874.lua | 3 | 2990 | --Emミラー・コンダクター
function c71578874.initial_effect(c)
--pendulum summon
aux.AddPendulumProcedure(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--atk/def
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_PZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1)
e2:SetTarget(c71578874.adtg)
e2:SetOperation(c71578874.adop)
c:RegisterEffect(e2)
--swap
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_DAMAGE)
e3:SetType(EFFECT_TYPE_QUICK_O)
e3:SetCode(EVENT_FREE_CHAIN)
e3:SetRange(LOCATION_MZONE)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e3:SetHintTiming(TIMING_DAMAGE_STEP)
e3:SetCountLimit(1)
e3:SetCondition(c71578874.swcon)
e3:SetTarget(c71578874.swtg)
e3:SetOperation(c71578874.swop)
c:RegisterEffect(e3)
end
function c71578874.filter(c)
return c:IsFaceup() and c:GetAttack()~=c:GetDefence()
and bit.band(c:GetSummonType(),SUMMON_TYPE_SPECIAL)==SUMMON_TYPE_SPECIAL
end
function c71578874.adtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c71578874.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c71578874.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c71578874.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
end
function c71578874.adop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
local val=math.min(tc:GetAttack(),tc:GetDefence())
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
e1:SetValue(val)
tc:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_SET_DEFENCE_FINAL)
tc:RegisterEffect(e2)
end
end
function c71578874.swcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated()
end
function c71578874.swtg(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)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,0,0,tp,500)
end
function c71578874.swop(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_SWAP_AD)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
Duel.BreakEffect()
Duel.Damage(tp,500,REASON_EFFECT)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c41307269.lua | 3 | 1542 | --超重武者カブ-10
function c41307269.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(41307269,0))
e1:SetCategory(CATEGORY_POSITION)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c41307269.condition)
e1:SetTarget(c41307269.target)
e1:SetOperation(c41307269.operation)
c:RegisterEffect(e1)
end
function c41307269.cfilter(c,tp)
return c:GetSummonPlayer()~=tp
end
function c41307269.condition(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c41307269.cfilter,1,nil,tp)
end
function c41307269.filter(c)
return c:IsPosition(POS_FACEUP_ATTACK) and c:IsSetCard(0x9a)
end
function c41307269.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c41307269.filter,tp,LOCATION_MZONE,0,1,nil) end
local g=Duel.GetMatchingGroup(c41307269.filter,tp,LOCATION_MZONE,0,nil)
Duel.SetOperationInfo(0,CATEGORY_POSITION,g,g:GetCount(),0,0)
end
function c41307269.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c41307269.filter,tp,LOCATION_MZONE,0,nil)
Duel.ChangePosition(g,POS_FACEUP_DEFENCE,POS_FACEDOWN_DEFENCE,0,0)
local og=Duel.GetOperatedGroup()
local tc=og:GetFirst()
while tc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_DEFENCE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(500)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
tc:RegisterEffect(e1)
tc=og:GetNext()
end
end
| gpl-2.0 |
adan830/UpAndAway | code/prefabs/cloud_coral.lua | 2 | 3053 | BindGlobal()
local CFG = TheMod:GetConfig()
local assets =
{
Asset("ANIM", "anim/cloud_coral.zip"),
}
local prefabs = CFG.CLOUD_CORAL.PREFABS
local function grow(inst, dt)
if inst.components.scaler.scale < 2 then
local new_scale = math.min(inst.components.scaler.scale + CFG.CLOUD_CORAL.GROW_RATE*dt, 2)
inst.components.scaler:SetScale(new_scale)
else
if inst.growtask then
inst.growtask:Cancel()
inst.growtask = nil
end
end
end
local function applyscale(inst, scale)
inst.components.workable:SetWorkLeft(scale*CFG.CLOUD_CORAL.WORK_TIME)
local function lootscaling()
local lootamount = scale*0.2
inst.components.lootdropper.numrandomloot = lootamount
end
end
local function onMined(inst, chopper)
inst.components.lootdropper:DropLoot()
inst:Remove()
end
local function OnWork(inst, worker, workleft)
local pt = Point(inst.Transform:GetWorldPosition())
if workleft < CFG.CLOUD_CORAL.WORK_TIME*(1/3) then
inst.AnimState:PlayAnimation("idle_low")
elseif workleft < CFG.CLOUD_CORAL.WORK_TIME*(2/3) then
inst.AnimState:PlayAnimation("idle_med")
else
inst.AnimState:PlayAnimation("idle_full")
end
end
local function onsave(inst, data)
if inst.components.scaler.scale then
data.scale = inst.components.scaler.scale
end
end
local function onload(inst, data)
if data and data.scale then
inst.components.scaler:SetScale(data.scale)
end
end
local function fn(Sim)
local inst = CreateEntity()
inst.entity:AddTransform()
inst.entity:AddAnimState()
inst.entity:AddSoundEmitter()
inst.AnimState:SetBank("cloud_coral")
inst.AnimState:SetBuild("cloud_coral")
inst.AnimState:PlayAnimation("idle_full")
MakeObstaclePhysics(inst, .6)
inst.Transform:SetScale(1,1,1)
inst.entity:AddMiniMapEntity()
inst.MiniMapEntity:SetIcon("cloud_coral.tex")
------------------------------------------------------------------------
SetupNetwork(inst)
------------------------------------------------------------------------
inst:AddComponent("inspectable")
inst:AddComponent("workable")
inst.components.workable:SetWorkAction(ACTIONS.MINE)
inst.components.workable:SetOnFinishCallback(onMined)
inst.components.workable:SetWorkLeft(CFG.CLOUD_CORAL.WORK_TIME)
inst.components.workable:SetOnWorkCallback(OnWork)
inst:AddComponent("scaler")
inst.components.scaler.OnApplyScale = applyscale
inst:AddComponent("lootdropper")
inst.components.lootdropper:AddRandomLoot("cloud_coral_fragment", CFG.CLOUD_CORAL.DROP_RATE)
local start_scale = CFG.CLOUD_CORAL.START_SCALE
inst.components.scaler:SetScale(start_scale)
local dt = CFG.CLOUD_CORAL.GROW_RATE
inst.growtask = inst:DoPeriodicTask(dt, grow, nil, dt)
inst.OnLongUpdate = grow
inst.OnLoad = onload
inst.OnSave = onsave
return inst
end
return Prefab ("common/inventory/cloud_coral", fn, assets, prefabs)
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c62543393.lua | 7 | 1456 | --レクンガ
function c62543393.initial_effect(c)
--token
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(62543393,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c62543393.cost)
e1:SetTarget(c62543393.target)
e1:SetOperation(c62543393.operation)
c:RegisterEffect(e1)
end
function c62543393.cfilter(c)
return c:IsAttribute(ATTRIBUTE_WATER) and c:IsAbleToRemoveAsCost()
end
function c62543393.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c62543393.cfilter,tp,LOCATION_GRAVE,0,2,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c62543393.cfilter,tp,LOCATION_GRAVE,0,2,2,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c62543393.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsPlayerCanSpecialSummonMonster(tp,62543394,0,0x4011,700,700,2,RACE_PLANT,ATTRIBUTE_WATER) end
Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,0)
end
function c62543393.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsPlayerCanSpecialSummonMonster(tp,62543394,0,0x4011,700,700,2,RACE_PLANT,ATTRIBUTE_WATER) then
local token=Duel.CreateToken(tp,62543394)
Duel.SpecialSummon(token,0,tp,tp,false,false,POS_FACEUP_ATTACK)
end
end
| gpl-2.0 |
andrejzverev/rspamd | src/plugins/lua/once_received.lua | 1 | 4785 | --[[
Copyright (c) 2011-2015, Vsevolod Stakhov <vsevolod@highsecure.ru>
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.
]]--
-- 0 or 1 received: = spam
local symbol = 'ONCE_RECEIVED'
local symbol_rdns = 'RDNS_NONE'
-- Symbol for strict checks
local symbol_strict = nil
local bad_hosts = {}
local good_hosts = {}
local whitelist = nil
local rspamd_logger = require "rspamd_logger"
local function check_quantity_received (task)
local recvh = task:get_received_headers()
local function recv_dns_cb(resolver, to_resolve, results, err)
task:inc_dns_req()
if not results then
if recvh and #recvh <= 1 then
task:insert_result(symbol, 1)
task:insert_result(symbol_strict, 1)
end
task:insert_result(symbol_rdns, 1)
else
rspamd_logger.infox(task, 'SMTP resolver failed to resolve: %1 is %2',
to_resolve, results[1])
if good_hosts then
for _,gh in ipairs(good_hosts) do
if string.find(results[1], gh) then
return
end
end
end
task:insert_result(symbol, 1)
for _,h in ipairs(bad_hosts) do
if string.find(results[1], h) then
task:insert_result(symbol_strict, 1, h)
return
end
end
end
end
if task:get_user() ~= nil then
return
end
if whitelist then
local addr = task:get_from_ip()
if addr and whitelist:get_key(addr) then
rspamd_logger.infox(task, 'whitelisted mail from %s',
addr:to_string())
return
end
end
local task_ip = task:get_ip()
local hn = task:get_hostname()
-- Here we don't care about received
if (not hn or hn == 'unknown') and task_ip and task_ip:is_valid() then
task:get_resolver():resolve_ptr({task = task,
name = task_ip:to_string(),
callback = recv_dns_cb,
forced = true
})
return
end
local recvh = task:get_received_headers()
if recvh and #recvh <= 1 then
local ret = true
local r = recvh[1]
if not r then
return
end
local hn = nil
if r['real_hostname'] then
hn = string.lower(r['real_hostname'])
-- Check for good hostname
if hn and good_hosts then
for _,gh in ipairs(good_hosts) do
if string.find(hn, gh) then
ret = false
break
end
end
end
end
if ret then
-- Strict checks
if symbol_strict then
-- Unresolved host
task:insert_result(symbol, 1)
if not hn then return end
for _,h in ipairs(bad_hosts) do
if string.find(hn, h) then
task:insert_result(symbol_strict, 1, h)
return
end
end
else
task:insert_result(symbol, 1)
end
end
end
end
-- Registration
if type(rspamd_config.get_api_version) ~= 'nil' then
if rspamd_config:get_api_version() >= 1 then
rspamd_config:register_module_option('once_received', 'symbol', 'string')
rspamd_config:register_module_option('once_received', 'symbol_strict', 'string')
rspamd_config:register_module_option('once_received', 'bad_host', 'string')
rspamd_config:register_module_option('once_received', 'good_host', 'string')
end
end
-- Configuration
local opts = rspamd_config:get_all_opt('once_received')
if opts then
if opts['symbol'] then
local symbol = opts['symbol']
local id = rspamd_config:register_symbol({
name = symbol,
callback = check_quantity_received,
})
for n,v in pairs(opts) do
if n == 'symbol_strict' then
symbol_strict = v
elseif n == 'symbol_rdns' then
symbol_rdns = v
elseif n == 'bad_host' then
if type(v) == 'string' then
bad_hosts[1] = v
else
bad_hosts = v
end
elseif n == 'good_host' then
if type(v) == 'string' then
good_hosts[1] = v
else
good_hosts = v
end
elseif n == 'whitelist' then
whitelist = rspamd_config:add_radix_map (v, 'once received whitelist')
end
end
rspamd_config:register_symbol({
name = symbol_rdns,
type = 'virtual',
parent = id
})
rspamd_config:register_symbol({
name = symbol_strict,
type = 'virtual',
parent = id
})
end
end
| apache-2.0 |
anshkumar/yugioh-glaze | assets/script/c32231618.lua | 3 | 1636 | --占術姫コインノーマ
function c32231618.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_FLIP+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetTarget(c32231618.sptg)
e1:SetOperation(c32231618.spop)
c:RegisterEffect(e1)
end
function c32231618.spfilter(c,e,tp)
return c:IsType(TYPE_FLIP) and c:IsLevelAbove(3) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEDOWN)
end
function c32231618.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c32231618.spfilter,tp,LOCATION_DECK+LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK+LOCATION_HAND)
end
function c32231618.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,c32231618.spfilter,tp,LOCATION_DECK+LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEDOWN_DEFENCE)
Duel.ConfirmCards(1-tp,g)
end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetValue(c32231618.actlimit)
e1:SetReset(RESET_PHASE+RESET_END)
Duel.RegisterEffect(e1,tp)
end
function c32231618.actlimit(e,re,rp)
local rc=re:GetHandler()
return re:IsActiveType(TYPE_MONSTER) and not rc:IsSetCard(0xcc) and not rc:IsImmuneToEffect(e)
end
| gpl-2.0 |
qq2588258/floweers | libs/scripting/lua/script/Deprecated.lua | 8 | 32784 | --tip
local function deprecatedTip(old_name,new_name)
print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********")
end
--functions of _G will be deprecated begin
local function ccpLineIntersect(a,b,c,d,s,t)
deprecatedTip("ccpLineIntersect","CCPoint:isLineIntersect")
return CCPoint:isLineIntersect(a,b,c,d,s,t)
end
rawset(_G,"ccpLineIntersect",ccpLineIntersect)
local function CCPointMake(x,y)
deprecatedTip("CCPointMake(x,y)","CCPoint(x,y)")
return CCPoint(x,y)
end
rawset(_G,"CCPointMake",CCPointMake)
local function ccp(x,y)
deprecatedTip("ccp(x,y)","CCPoint(x,y)")
return CCPoint(x,y)
end
rawset(_G,"ccp",ccp)
local function CCSizeMake(width,height)
deprecatedTip("CCSizeMake(width,height)","CCSize(width,height)")
return CCSize(width,height)
end
rawset(_G,"CCSizeMake",CCSizeMake)
local function CCRectMake(x,y,width,height)
deprecatedTip("CCRectMake(x,y,width,height)","CCRect(x,y,width,height)")
return CCRect(x,y,width,height)
end
rawset(_G,"CCRectMake",CCRectMake)
local function ccpNeg(pt)
deprecatedTip("ccpNeg","CCPoint.__sub")
return CCPoint.__sub(CCPoint:new_local(0,0),pt)
end
rawset(_G,"ccpNeg",ccpNeg)
local function ccpAdd(pt1,pt2)
deprecatedTip("ccpAdd","CCPoint.__add")
return CCPoint.__add(pt1,pt2)
end
rawset(_G,"ccpAdd",ccpAdd)
local function ccpSub(pt1,pt2)
deprecatedTip("ccpSub","CCPoint.__sub")
return CCPoint.__sub(pt1,pt2)
end
rawset(_G,"ccpSub",ccpSub)
local function ccpMult(pt,factor)
deprecatedTip("ccpMult","CCPoint.__mul")
return CCPoint.__mul(pt,factor)
end
rawset(_G,"ccpMult",ccpMult)
local function ccpMidpoint(pt1,pt2)
deprecatedTip("ccpMidpoint","CCPoint:getMidpoint")
return pt1:getMidpoint(pt2)
end
rawset(_G,"ccpMidpoint",ccpMidpoint)
local function ccpDot(pt1,pt2)
deprecatedTip("ccpDot","CCPoint:dot")
return pt1:dot(pt2)
end
rawset(_G,"ccpDot",ccpDot)
local function ccpCross(pt1,pt2)
deprecatedTip("ccpCross","CCPoint:cross")
return pt1:cross(pt2)
end
rawset(_G,"ccpCross",ccpCross)
local function ccpPerp(pt)
deprecatedTip("ccpPerp","CCPoint:getPerp")
return pt:getPerp()
end
rawset(_G,"ccpPerp",ccpPerp)
local function ccpRPerp(pt)
deprecatedTip("ccpRPerp","CCPoint:getRPerp")
return pt:getRPerp()
end
rawset(_G,"ccpRPerp",ccpRPerp)
local function ccpProject(pt1,pt2)
deprecatedTip("ccpProject","CCPoint:project")
return pt1:project(pt2)
end
rawset(_G,"ccpProject",ccpProject)
local function ccpRotate(pt1,pt2)
deprecatedTip("ccpRotate","CCPoint:rotate")
return pt1:rotate(pt2)
end
rawset(_G,"ccpRotate",ccpRotate)
local function ccpUnrotate(pt1,pt2)
deprecatedTip("ccpUnrotate","CCPoint:unrotate")
return pt1:unrotate(pt2)
end
rawset(_G,"ccpUnrotate",ccpUnrotate)
local function ccpLengthSQ(pt)
deprecatedTip("ccpLengthSQ","CCPoint:getLengthSq")
return pt:getLengthSq(pt)
end
rawset(_G,"ccpLengthSQ",ccpLengthSQ)
local function ccpDistanceSQ(pt1,pt2)
deprecatedTip("ccpDistanceSQ","CCPoint:__sub(pt1,pt2):getLengthSq")
return (CCPoint.__sub(pt1,pt2)):getLengthSq()
end
rawset(_G,"ccpDistanceSQ",ccpDistanceSQ)
local function ccpLength(pt)
deprecatedTip("ccpLength","CCPoint:getLength")
return pt:getLength()
end
rawset(_G,"ccpLength",ccpLength)
local function ccpDistance(pt1,pt2)
deprecatedTip("ccpDistance","CCPoint:getDistance")
return pt1:getDistance(pt2)
end
rawset(_G,"ccpDistance",ccpDistance)
local function ccpNormalize(pt)
deprecatedTip("ccpNormalize","CCPoint:normalize")
return pt:normalize()
end
rawset(_G,"ccpNormalize",ccpNormalize)
local function ccpForAngle(angle)
deprecatedTip("ccpForAngle","CCPoint:forAngle")
return CCPoint:forAngle(angle)
end
rawset(_G,"ccpForAngle",ccpForAngle)
local function ccpToAngle(pt)
deprecatedTip("ccpToAngle","CCPoint:getAngle")
return pt:getAngle()
end
rawset(_G,"ccpToAngle",ccpToAngle)
local function ccpClamp(pt1,pt2,pt3)
deprecatedTip("ccpClamp","CCPoint:getClampPoint")
return pt1:getClampPoint(pt2, pt3)
end
rawset(_G,"ccpClamp",ccpClamp)
local function ccpFromSize(sz)
deprecatedTip("ccpFromSize(sz)","CCPoint(sz)")
return CCPoint(sz)
end
rawset(_G,"ccpFromSize",ccpFromSize)
local function ccpLerp(pt1,pt2,alpha)
deprecatedTip("ccpLerp","CCPoint:lerp")
return pt1:lerp(pt2,alpha)
end
rawset(_G,"ccpLerp",ccpLerp)
local function ccpFuzzyEqual(pt1,pt2,variance)
deprecatedTip("ccpFuzzyEqual","CCPoint:fuzzyEquals")
return pt1:fuzzyEquals(pt2,variance)
end
rawset(_G,"ccpFuzzyEqual",ccpFuzzyEqual)
local function ccpCompMult(pt1,pt2)
deprecatedTip("ccpCompMult","CCPoint")
return CCPoint(pt1.x * pt2.x , pt1.y * pt2.y)
end
rawset(_G,"ccpCompMult",ccpCompMult)
local function ccpAngleSigned(pt1,pt2)
deprecatedTip("ccpAngleSigned","CCPoint:getAngle")
return pt1:getAngle(pt2)
end
rawset(_G,"ccpAngleSigned",ccpAngleSigned)
local function ccpAngle(pt1,pt2)
deprecatedTip("ccpAngle","CCPoint:getAngle")
return pt1:getAngle(pt2)
end
rawset(_G,"ccpAngle",ccpAngle)
local function ccpRotateByAngle(pt1,pt2,angle)
deprecatedTip("ccpRotateByAngle","CCPoint:rotateByAngle")
return pt1:rotateByAngle(pt2, angle)
end
rawset(_G,"ccpRotateByAngle",ccpRotateByAngle)
local function ccpSegmentIntersect(pt1,pt2,pt3,pt4)
deprecatedTip("ccpSegmentIntersect","CCPoint:isSegmentIntersect")
return CCPoint:isSegmentIntersect(pt1,pt2,pt3,pt4)
end
rawset(_G,"ccpSegmentIntersect",ccpSegmentIntersect)
local function ccpIntersectPoint(pt1,pt2,pt3,pt4)
deprecatedTip("ccpIntersectPoint","CCPoint:getIntersectPoint")
return CCPoint:getIntersectPoint(pt1,pt2,pt3,pt4)
end
rawset(_G,"ccpIntersectPoint",ccpIntersectPoint)
local function ccc3(r,g,b)
deprecatedTip("ccc3(r,g,b)","ccColor3B(r,g,b)")
return ccColor3B(r,g,b)
end
rawset(_G,"ccc3",ccc3)
local function ccc4(r,g,b,a)
deprecatedTip("ccc4(r,g,b,a)","Color4B(r,g,b,a)")
return Color4B(r,g,b,a)
end
rawset(_G,"ccc4",ccc4)
local function ccc4FFromccc3B(color3B)
deprecatedTip("ccc4FFromccc3B(color3B)","Color4F(color3B.r / 255.0,color3B.g / 255.0,color3B.b / 255.0,1.0)")
return Color4F(color3B.r/255.0, color3B.g/255.0, color3B.b/255.0, 1.0)
end
rawset(_G,"ccc4FFromccc3B",ccc4FFromccc3B)
local function ccc4f(r,g,b,a)
deprecatedTip("ccc4f(r,g,b,a)","Color4F(r,g,b,a)")
return Color4F(r,g,b,a)
end
rawset(_G,"ccc4f",ccc4f)
local function ccc4FFromccc4B(color4B)
deprecatedTip("ccc4FFromccc4B(color4B)","Color4F(color4B.r/255.0, color4B.g/255.0, color4B.b/255.0, color4B.a/255.0)")
return Color4F(color4B.r/255.0, color4B.g/255.0, color4B.b/255.0, color4B.a/255.0)
end
rawset(_G,"ccc4FFromccc4B",ccc4FFromccc4B)
local function ccc4FEqual(a,b)
deprecatedTip("ccc4FEqual(a,b)","a:equals(b)")
return a:equals(b)
end
rawset(_G,"ccc4FEqual",ccc4FEqual)
local function vertex2(x,y)
deprecatedTip("vertex2(x,y)","Vertex2F(x,y)")
return Vertex2F(x,y)
end
rawset(_G,"vertex2",vertex2)
local function vertex3(x,y,z)
deprecatedTip("vertex3(x,y,z)","Vertex3F(x,y,z)")
return Vertex3F(x,y,z)
end
rawset(_G,"vertex3",vertex3)
local function tex2(u,v)
deprecatedTip("tex2(u,v)","Tex2F(u,v)")
return Tex2F(u,v)
end
rawset(_G,"tex2",tex2)
local function ccc4BFromccc4F(color4F)
deprecatedTip("ccc4BFromccc4F(color4F)","Color4B(color4F.r * 255.0, color4F.g * 255.0, color4F.b * 255.0, color4B.a * 255.0)")
return Color4B(color4F.r * 255.0, color4F.g * 255.0, color4F.b * 255.0, color4B.a * 255.0)
end
rawset(_G,"ccc4BFromccc4F",ccc4BFromccc4F)
local function ccColor3BDeprecated()
deprecatedTip("ccColor3B","Color3B")
return Color3B
end
_G["ccColor3B"] = ccColor3BDeprecated()
local function ccColor4BDeprecated()
deprecatedTip("ccColor4B","Color4B")
return Color4B
end
_G["ccColor4B"] = ccColor4BDeprecated()
local function ccColor4FDeprecated()
deprecatedTip("ccColor4F","Color4F")
return Color4F
end
_G["ccColor4F"] = ccColor4FDeprecated()
local function ccVertex2FDeprecated()
deprecatedTip("ccVertex2F","Vertex2F")
return Vertex2F
end
_G["ccVertex2F"] = ccVertex2FDeprecated()
local function ccVertex3FDeprecated()
deprecatedTip("ccVertex3F","Vertex3F")
return Vertex3F
end
_G["ccVertex3F"] = ccVertex3FDeprecated()
local function ccTex2FDeprecated()
deprecatedTip("ccTex2F","Tex2F")
return Tex2F
end
_G["ccTex2F"] = ccTex2FDeprecated()
local function ccPointSpriteDeprecated()
deprecatedTip("ccPointSprite","PointSprite")
return PointSprite
end
_G["ccPointSprite"] = ccPointSpriteDeprecated()
local function ccQuad2Deprecated()
deprecatedTip("ccQuad2","Quad2")
return Quad2
end
_G["ccQuad2"] = ccQuad2Deprecated()
local function ccQuad3Deprecated()
deprecatedTip("ccQuad3","Quad3")
return Quad3
end
_G["ccQuad3"] = ccQuad3Deprecated()
local function ccV2FC4BT2FDeprecated()
deprecatedTip("ccV2F_C4B_T2F","V2F_C4B_T2F")
return V2F_C4B_T2F
end
_G["ccV2F_C4B_T2F"] = ccV2FC4BT2FDeprecated()
local function ccV2FC4FT2FDeprecated()
deprecatedTip("ccV2F_C4F_T2F","V2F_C4F_T2F")
return V2F_C4F_T2F
end
_G["ccV2F_C4F_T2F"] = ccV2FC4FT2FDeprecated()
local function ccV3FC4BT2FDeprecated()
deprecatedTip("ccV3F_C4B_T2F","V3F_C4B_T2F")
return V3F_C4B_T2F
end
_G["ccV3F_C4B_T2F"] = ccV3FC4BT2FDeprecated()
local function ccV2FC4BT2FQuadDeprecated()
deprecatedTip("ccV2F_C4B_T2F_Quad","V2F_C4B_T2F_Quad")
return V2F_C4B_T2F_Quad
end
_G["ccV2F_C4B_T2F_Quad"] = ccV2FC4BT2FQuadDeprecated()
local function ccV3FC4BT2FQuadDeprecated()
deprecatedTip("ccV3F_C4B_T2F_Quad","V3F_C4B_T2F_Quad")
return V3F_C4B_T2F_Quad
end
_G["ccV3F_C4B_T2F_Quad"] = ccV3FC4BT2FQuadDeprecated()
local function ccV2FC4FT2FQuadDeprecated()
deprecatedTip("ccV2F_C4F_T2F_Quad","V2F_C4F_T2F_Quad")
return V2F_C4F_T2F_Quad
end
_G["ccV2F_C4F_T2F_Quad"] = ccV2FC4FT2FQuadDeprecated()
local function ccBlendFuncDeprecated()
deprecatedTip("ccBlendFunc","BlendFunc")
return BlendFunc
end
_G["ccBlendFunc"] = ccBlendFuncDeprecated()
local function ccT2FQuadDeprecated()
deprecatedTip("ccT2F_Quad","T2F_Quad")
return T2F_Quad
end
_G["ccT2F_Quad"] = ccT2FQuadDeprecated()
local function ccAnimationFrameDataDeprecated()
deprecatedTip("ccAnimationFrameData","AnimationFrameData")
return AnimationFrameData
end
_G["ccAnimationFrameData"] = ccAnimationFrameDataDeprecated()
local function CCCallFuncNDeprecated( )
deprecatedTip("CCCallFuncN","CCCallFunc")
return CCCallFunc
end
_G["CCCallFuncN"] = CCCallFuncNDeprecated()
--functions of _G will be deprecated end
--functions of CCControl will be deprecated end
local CCControlDeprecated = { }
function CCControlDeprecated.addHandleOfControlEvent(self,func,controlEvent)
deprecatedTip("addHandleOfControlEvent","registerControlEventHandler")
print("come in addHandleOfControlEvent")
self:registerControlEventHandler(func,controlEvent)
end
rawset(CCControl,"addHandleOfControlEvent",CCControlDeprecated.addHandleOfControlEvent)
--functions of CCControl will be deprecated end
--functions of CCEGLView will be deprecated end
local CCEGLViewDeprecated = { }
function CCEGLViewDeprecated.sharedOpenGLView()
deprecatedTip("CCEGLView:sharedOpenGLView","CCEGLView:getInstance")
return CCEGLView:getInstance()
end
rawset(CCEGLView,"sharedOpenGLView",CCEGLViewDeprecated.sharedOpenGLView)
--functions of CCFileUtils will be deprecated end
--functions of CCFileUtils will be deprecated end
local CCFileUtilsDeprecated = { }
function CCFileUtilsDeprecated.sharedFileUtils()
deprecatedTip("CCFileUtils:sharedFileUtils","CCFileUtils:getInstance")
return CCFileUtils:getInstance()
end
rawset(CCFileUtils,"sharedFileUtils",CCFileUtilsDeprecated.sharedFileUtils)
function CCFileUtilsDeprecated.purgeFileUtils()
deprecatedTip("CCFileUtils:purgeFileUtils","CCFileUtils:destroyInstance")
return CCFileUtils:destroyInstance()
end
rawset(CCFileUtils,"purgeFileUtils",CCFileUtilsDeprecated.purgeFileUtils)
--functions of CCFileUtils will be deprecated end
--functions of CCApplication will be deprecated end
local CCApplicationDeprecated = { }
function CCApplicationDeprecated.sharedApplication()
deprecatedTip("CCApplication:sharedApplication","CCApplication:getInstance")
return CCApplication:getInstance()
end
rawset(CCApplication,"sharedApplication",CCApplicationDeprecated.sharedApplication)
--functions of CCApplication will be deprecated end
--functions of CCDirector will be deprecated end
local CCDirectorDeprecated = { }
function CCDirectorDeprecated.sharedDirector()
deprecatedTip("CCDirector:sharedDirector","CCDirector:getInstance")
return CCDirector:getInstance()
end
rawset(CCDirector,"sharedDirector",CCDirectorDeprecated.sharedDirector)
--functions of CCDirector will be deprecated end
--functions of CCUserDefault will be deprecated end
local CCUserDefaultDeprecated = { }
function CCUserDefaultDeprecated.sharedUserDefault()
deprecatedTip("CCUserDefault:sharedUserDefault","CCUserDefault:getInstance")
return CCUserDefault:getInstance()
end
rawset(CCUserDefault,"sharedUserDefault",CCUserDefaultDeprecated.sharedUserDefault)
function CCUserDefaultDeprecated.purgeSharedUserDefault()
deprecatedTip("CCUserDefault:purgeSharedUserDefault","CCUserDefault:destroyInstance")
return CCUserDefault:destroyInstance()
end
rawset(CCUserDefault,"purgeSharedUserDefault",CCUserDefaultDeprecated.purgeSharedUserDefault)
--functions of CCUserDefault will be deprecated end
--functions of CCNotificationCenter will be deprecated end
local CCNotificationCenterDeprecated = { }
function CCNotificationCenterDeprecated.sharedNotificationCenter()
deprecatedTip("CCNotificationCenter:sharedNotificationCenter","CCNotificationCenter:getInstance")
return CCNotificationCenter:getInstance()
end
rawset(CCNotificationCenter,"sharedNotificationCenter",CCNotificationCenterDeprecated.sharedNotificationCenter)
function CCNotificationCenterDeprecated.purgeNotificationCenter()
deprecatedTip("CCNotificationCenter:purgeNotificationCenter","CCNotificationCenter:destroyInstance")
return CCNotificationCenter:destroyInstance()
end
rawset(CCNotificationCenter,"purgeNotificationCenter",CCNotificationCenterDeprecated.purgeNotificationCenter)
--functions of CCNotificationCenter will be deprecated end
--functions of CCTextureCache will be deprecated begin
local CCTextureCacheDeprecated = { }
function CCTextureCacheDeprecated.sharedTextureCache()
deprecatedTip("CCTextureCache:sharedTextureCache","CCTextureCache:getInstance")
return CCTextureCache:getInstance()
end
rawset(CCTextureCache,"sharedTextureCache",CCTextureCacheDeprecated.sharedTextureCache)
function CCTextureCacheDeprecated.purgeSharedTextureCache()
deprecatedTip("CCTextureCache:purgeSharedTextureCache","CCTextureCache:destroyInstance")
return CCTextureCache:destroyInstance()
end
rawset(CCTextureCache,"purgeSharedTextureCache",CCTextureCacheDeprecated.purgeSharedTextureCache)
--functions of CCTextureCache will be deprecated end
--functions of CCGrid3DAction will be deprecated begin
local CCGrid3DActionDeprecated = { }
function CCGrid3DActionDeprecated.vertex(self,pt)
deprecatedTip("vertex","CCGrid3DAction:getVertex")
return self:getVertex(pt)
end
rawset(CCGrid3DAction,"vertex",CCGrid3DActionDeprecated.vertex)
function CCGrid3DActionDeprecated.originalVertex(self,pt)
deprecatedTip("originalVertex","CCGrid3DAction:getOriginalVertex")
return self:getOriginalVertex(pt)
end
rawset(CCGrid3DAction,"originalVertex",CCGrid3DActionDeprecated.originalVertex)
--functions of CCGrid3DAction will be deprecated end
--functions of CCTiledGrid3DAction will be deprecated begin
local CCTiledGrid3DActionDeprecated = { }
function CCTiledGrid3DActionDeprecated.tile(self,pt)
deprecatedTip("tile","CCTiledGrid3DAction:getTile")
return self:getTile(pt)
end
rawset(CCTiledGrid3DAction,"tile",CCTiledGrid3DActionDeprecated.tile)
function CCTiledGrid3DActionDeprecated.originalTile(self,pt)
deprecatedTip("originalTile","CCTiledGrid3DAction:getOriginalTile")
return self:getOriginalTile(pt)
end
rawset(CCTiledGrid3DAction,"originalTile",CCTiledGrid3DActionDeprecated.originalTile)
--functions of CCTiledGrid3DAction will be deprecated end
--functions of CCAnimationCache will be deprecated begin
local CCAnimationCacheDeprecated = { }
function CCAnimationCacheDeprecated.sharedAnimationCache()
deprecatedTip("CCAnimationCache:sharedAnimationCache","CCAnimationCache:getInstance")
return CCAnimationCache:getInstance()
end
rawset(CCAnimationCache,"sharedAnimationCache",CCAnimationCacheDeprecated.sharedAnimationCache)
function CCAnimationCacheDeprecated.purgeSharedAnimationCache()
deprecatedTip("CCAnimationCache:purgeSharedAnimationCache","CCAnimationCache:destroyInstance")
return CCAnimationCache:destroyInstance()
end
rawset(CCAnimationCache,"purgeSharedAnimationCache",CCAnimationCacheDeprecated.purgeSharedAnimationCache)
--functions of CCAnimationCache will be deprecated end
--functions of CCNode will be deprecated begin
local CCNodeDeprecated = { }
function CCNodeDeprecated.boundingBox(self)
deprecatedTip("CCNode:boundingBox","CCNode:getBoundingBox")
return self:getBoundingBox()
end
rawset(CCNode,"boundingBox",CCNodeDeprecated.boundingBox)
function CCNodeDeprecated.numberOfRunningActions(self)
deprecatedTip("CCNode:numberOfRunningActions","CCNode:getNumberOfRunningActions")
return self:getNumberOfRunningActions()
end
rawset(CCNode,"numberOfRunningActions",CCNodeDeprecated.numberOfRunningActions)
--functions of CCNode will be deprecated end
--functions of CCTexture2D will be deprecated begin
local CCTexture2DDeprecated = { }
function CCTexture2DDeprecated.stringForFormat(self)
deprecatedTip("Texture2D:stringForFormat","Texture2D:getStringForFormat")
return self:getStringForFormat()
end
rawset(CCTexture2D,"stringForFormat",CCTexture2DDeprecated.stringForFormat)
function CCTexture2DDeprecated.bitsPerPixelForFormat(self)
deprecatedTip("Texture2D:bitsPerPixelForFormat","Texture2D:getBitsPerPixelForFormat")
return self:getBitsPerPixelForFormat()
end
rawset(CCTexture2D,"bitsPerPixelForFormat",CCTexture2DDeprecated.bitsPerPixelForFormat)
function CCTexture2DDeprecated.bitsPerPixelForFormat(self,pixelFormat)
deprecatedTip("Texture2D:bitsPerPixelForFormat","Texture2D:getBitsPerPixelForFormat")
return self:getBitsPerPixelForFormat(pixelFormat)
end
rawset(CCTexture2D,"bitsPerPixelForFormat",CCTexture2DDeprecated.bitsPerPixelForFormat)
function CCTexture2DDeprecated.defaultAlphaPixelFormat(self)
deprecatedTip("Texture2D:defaultAlphaPixelFormat","Texture2D:getDefaultAlphaPixelFormat")
return self:getDefaultAlphaPixelFormat()
end
rawset(CCTexture2D,"defaultAlphaPixelFormat",CCTexture2DDeprecated.defaultAlphaPixelFormat)
--functions of CCTexture2D will be deprecated end
--functions of CCSpriteFrameCache will be deprecated begin
local CCSpriteFrameCacheDeprecated = { }
function CCSpriteFrameCacheDeprecated.spriteFrameByName(self,szName)
deprecatedTip("CCSpriteFrameCache:spriteFrameByName","CCSpriteFrameCache:getSpriteFrameByName")
return self:getSpriteFrameByName(szName)
end
rawset(CCSpriteFrameCache,"spriteFrameByName",CCSpriteFrameCacheDeprecated.spriteFrameByName)
function CCSpriteFrameCacheDeprecated.sharedSpriteFrameCache()
deprecatedTip("CCSpriteFrameCache:sharedSpriteFrameCache","CCSpriteFrameCache:getInstance")
return CCSpriteFrameCache:getInstance()
end
rawset(CCSpriteFrameCache,"sharedSpriteFrameCache",CCSpriteFrameCacheDeprecated.sharedSpriteFrameCache)
function CCSpriteFrameCacheDeprecated.purgeSharedSpriteFrameCache()
deprecatedTip("CCSpriteFrameCache:purgeSharedSpriteFrameCache","CCSpriteFrameCache:destroyInstance")
return CCSpriteFrameCache:destroyInstance()
end
rawset(CCSpriteFrameCache,"purgeSharedSpriteFrameCache",CCSpriteFrameCacheDeprecated.purgeSharedSpriteFrameCache)
--functions of CCSpriteFrameCache will be deprecated end
--functions of CCTimer will be deprecated begin
local CCTimerDeprecated = { }
function CCTimerDeprecated.timerWithScriptHandler(handler,seconds)
deprecatedTip("CCTimer:timerWithScriptHandler","CCTimer:createWithScriptHandler")
return CCTimer:createWithScriptHandler(handler,seconds)
end
rawset(CCTimer,"timerWithScriptHandler",CCTimerDeprecated.timerWithScriptHandler)
function CCTimerDeprecated.numberOfRunningActionsInTarget(self,target)
deprecatedTip("CCActionManager:numberOfRunningActionsInTarget","CCActionManager:getNumberOfRunningActionsInTarget")
return self:getNumberOfRunningActionsInTarget(target)
end
rawset(CCTimer,"numberOfRunningActionsInTarget",CCTimerDeprecated.numberOfRunningActionsInTarget)
--functions of CCTimer will be deprecated end
--functions of CCMenuItemFont will be deprecated begin
local CCMenuItemFontDeprecated = { }
function CCMenuItemFontDeprecated.fontSize()
deprecatedTip("CCMenuItemFont:fontSize","CCMenuItemFont:getFontSize")
return CCMenuItemFont:getFontSize()
end
rawset(CCMenuItemFont,"fontSize",CCMenuItemFontDeprecated.fontSize)
function CCMenuItemFontDeprecated.fontName()
deprecatedTip("CCMenuItemFont:fontName","CCMenuItemFont:getFontName")
return CCMenuItemFont:getFontName()
end
rawset(CCMenuItemFont,"fontName",CCMenuItemFontDeprecated.fontName)
function CCMenuItemFontDeprecated.fontSizeObj(self)
deprecatedTip("CCMenuItemFont:fontSizeObj","CCMenuItemFont:getFontSizeObj")
return self:getFontSizeObj()
end
rawset(CCMenuItemFont,"fontSizeObj",CCMenuItemFontDeprecated.fontSizeObj)
function CCMenuItemFontDeprecated.fontNameObj(self)
deprecatedTip("CCMenuItemFont:fontNameObj","CCMenuItemFont:getFontNameObj")
return self:getFontNameObj()
end
rawset(CCMenuItemFont,"fontNameObj",CCMenuItemFontDeprecated.fontNameObj)
--functions of CCMenuItemFont will be deprecated end
--functions of CCMenuItemToggle will be deprecated begin
local CCMenuItemToggleDeprecated = { }
function CCMenuItemToggleDeprecated.selectedItem(self)
deprecatedTip("CCMenuItemToggle:selectedItem","CCMenuItemToggle:getSelectedItem")
return self:getSelectedItem()
end
rawset(CCMenuItemToggle,"selectedItem",CCMenuItemToggleDeprecated.selectedItem)
--functions of CCMenuItemToggle will be deprecated end
--functions of CCTileMapAtlas will be deprecated begin
local CCTileMapAtlasDeprecated = { }
function CCTileMapAtlasDeprecated.tileAt(self,pos)
deprecatedTip("CCTileMapAtlas:tileAt","CCTileMapAtlas:getTileAt")
return self:getTileAt(pos)
end
rawset(CCTileMapAtlas,"tileAt",CCTileMapAtlasDeprecated.tileAt)
--functions of CCTileMapAtlas will be deprecated end
--functions of CCTMXLayer will be deprecated begin
local CCTMXLayerDeprecated = { }
function CCTMXLayerDeprecated.tileAt(self,tileCoordinate)
deprecatedTip("CCTMXLayer:tileAt","CCTMXLayer:getTileAt")
return self:getTileAt(tileCoordinate)
end
rawset(CCTMXLayer,"tileAt",CCTMXLayerDeprecated.tileAt)
function CCTMXLayerDeprecated.tileGIDAt(self,tileCoordinate)
deprecatedTip("CCTMXLayer:tileGIDAt","CCTMXLayer:getTileGIDAt")
return self:getTileGIDAt(tileCoordinate)
end
rawset(CCTMXLayer,"tileGIDAt",CCTMXLayerDeprecated.tileGIDAt)
function CCTMXLayerDeprecated.positionAt(self,tileCoordinate)
deprecatedTip("CCTMXLayer:positionAt","CCTMXLayer:getPositionAt")
return self:getPositionAt(tileCoordinate)
end
rawset(CCTMXLayer,"positionAt",CCTMXLayerDeprecated.positionAt)
function CCTMXLayerDeprecated.propertyNamed(self,propertyName)
deprecatedTip("CCTMXLayer:propertyNamed","CCTMXLayer:getProperty")
return self:getProperty(propertyName)
end
rawset(CCTMXLayer,"propertyNamed",CCTMXLayerDeprecated.propertyNamed)
--functions of CCTMXLayer will be deprecated end
--functions of SimpleAudioEngine will be deprecated begin
local SimpleAudioEngineDeprecated = { }
function SimpleAudioEngineDeprecated.sharedEngine()
deprecatedTip("SimpleAudioEngine:sharedEngine","SimpleAudioEngine:getInstance")
return SimpleAudioEngine:getInstance()
end
rawset(SimpleAudioEngine,"sharedEngine",SimpleAudioEngineDeprecated.sharedEngine)
--functions of SimpleAudioEngine will be deprecated end
--functions of CCTMXTiledMap will be deprecated begin
local CCTMXTiledMapDeprecated = { }
function CCTMXTiledMapDeprecated.layerNamed(self,layerName)
deprecatedTip("CCTMXTiledMap:layerNamed","CCTMXTiledMap:getLayer")
return self:getLayer(layerName)
end
rawset(CCTMXTiledMap,"layerNamed", CCTMXTiledMapDeprecated.layerNamed)
function CCTMXTiledMapDeprecated.propertyNamed(self,propertyName)
deprecatedTip("CCTMXTiledMap:propertyNamed","CCTMXTiledMap:getProperty")
return self:getProperty(propertyName)
end
rawset(CCTMXTiledMap,"propertyNamed", CCTMXTiledMapDeprecated.propertyNamed )
function CCTMXTiledMapDeprecated.propertiesForGID(self,GID)
deprecatedTip("CCTMXTiledMap:propertiesForGID","CCTMXTiledMap:getPropertiesForGID")
return self:getPropertiesForGID(GID)
end
rawset(CCTMXTiledMap,"propertiesForGID", CCTMXTiledMapDeprecated.propertiesForGID)
function CCTMXTiledMapDeprecated.objectGroupNamed(self,groupName)
deprecatedTip("CCTMXTiledMap:objectGroupNamed","CCTMXTiledMap:getObjectGroup")
return self:getObjectGroup(groupName)
end
rawset(CCTMXTiledMap,"objectGroupNamed", CCTMXTiledMapDeprecated.objectGroupNamed)
--functions of CCTMXTiledMap will be deprecated end
--functions of CCTMXMapInfo will be deprecated begin
local CCTMXMapInfoDeprecated = { }
function CCTMXMapInfoDeprecated.getStoringCharacters(self)
deprecatedTip("CCTMXMapInfo:getStoringCharacters","CCTMXMapInfo:isStoringCharacters")
return self:isStoringCharacters()
end
rawset(CCTMXMapInfo,"getStoringCharacters", CCTMXMapInfoDeprecated.getStoringCharacters)
function CCTMXMapInfoDeprecated.formatWithTMXFile(infoTable,tmxFile)
deprecatedTip("CCTMXMapInfo:formatWithTMXFile","CCTMXMapInfo:create")
return CCTMXMapInfo:create(tmxFile)
end
rawset(CCTMXMapInfo,"formatWithTMXFile", CCTMXMapInfoDeprecated.formatWithTMXFile)
function CCTMXMapInfoDeprecated.formatWithXML(infoTable,tmxString,resourcePath)
deprecatedTip("CCTMXMapInfo:formatWithXML","TMXMapInfo:createWithXML")
return CCTMXMapInfo:createWithXML(tmxString,resourcePath)
end
rawset(CCTMXMapInfo,"formatWithXML", CCTMXMapInfoDeprecated.formatWithXML)
--functions of CCTMXMapInfo will be deprecated end
--functions of CCTMXObject will be deprecated begin
local CCTMXObjectGroupDeprecated = { }
function CCTMXObjectGroupDeprecated.propertyNamed(self,propertyName)
deprecatedTip("CCTMXObjectGroup:propertyNamed","CCTMXObjectGroup:getProperty")
return self:getProperty(propertyName)
end
rawset(CCTMXObjectGroup,"propertyNamed", CCTMXObjectGroupDeprecated.propertyNamed)
function CCTMXObjectGroupDeprecated.objectNamed(self, objectName)
deprecatedTip("CCTMXObjectGroup:objectNamed","CCTMXObjectGroup:getObject")
return self:getObject(objectName)
end
rawset(CCTMXObjectGroup,"objectNamed", CCTMXObjectGroupDeprecated.objectNamed)
--functions of CCTMXObject will be deprecated end
--functions of WebSocket will be deprecated begin
local targetPlatform = CCApplication:getInstance():getTargetPlatform()
if (kTargetIphone == targetPlatform) or (kTargetIpad == targetPlatform) or (kTargetAndroid == targetPlatform) or (kTargetWindows == targetPlatform) then
local WebSocketDeprecated = { }
function WebSocketDeprecated.sendTextMsg(self, string)
deprecatedTip("WebSocket:sendTextMsg","WebSocket:sendString")
return self:sendString(string)
end
rawset(WebSocket,"sendTextMsg", WebSocketDeprecated.sendTextMsg)
function WebSocketDeprecated.sendBinaryMsg(self, table,tablesize)
deprecatedTip("WebSocket:sendBinaryMsg","WebSocket:sendString")
string.char(unpack(table))
return self:sendString(string.char(unpack(table)))
end
rawset(WebSocket,"sendBinaryMsg", WebSocketDeprecated.sendBinaryMsg)
end
--functions of WebSocket will be deprecated end
--functions of CCDrawPrimitives will be deprecated begin
local CCDrawPrimitivesDeprecated = { }
function CCDrawPrimitivesDeprecated.ccDrawPoint(pt)
deprecatedTip("ccDrawPoint","CCDrawPrimitives.ccDrawPoint")
return CCDrawPrimitives.ccDrawPoint(pt)
end
rawset(_G, "ccDrawPoint", CCDrawPrimitivesDeprecated.ccDrawPoint)
function CCDrawPrimitivesDeprecated.ccDrawLine(origin,destination)
deprecatedTip("ccDrawLine","CCDrawPrimitives.ccDrawLine")
return CCDrawPrimitives.ccDrawLine(origin,destination)
end
rawset(_G, "ccDrawLine", CCDrawPrimitivesDeprecated.ccDrawLine)
function CCDrawPrimitivesDeprecated.ccDrawRect(origin,destination)
deprecatedTip("ccDrawRect","CCDrawPrimitives.ccDrawRect")
return CCDrawPrimitives.ccDrawRect(origin,destination)
end
rawset(_G, "ccDrawRect", CCDrawPrimitivesDeprecated.ccDrawRect)
function CCDrawPrimitivesDeprecated.ccDrawSolidRect(origin,destination,color)
deprecatedTip("ccDrawSolidRect","CCDrawPrimitives.ccDrawSolidRect")
return CCDrawPrimitives.ccDrawSolidRect(origin,destination,color)
end
rawset(_G, "ccDrawSolidRect", CCDrawPrimitivesDeprecated.ccDrawSolidRect)
-- params:... may represent two param(xScale,yScale) or nil
function CCDrawPrimitivesDeprecated.ccDrawCircle(center,radius,angle,segments,drawLineToCenter,...)
deprecatedTip("ccDrawCircle","CCDrawPrimitives.ccDrawCircle")
return CCDrawPrimitives.ccDrawCircle(center,radius,angle,segments,drawLineToCenter,...)
end
rawset(_G, "ccDrawCircle", CCDrawPrimitivesDeprecated.ccDrawCircle)
-- params:... may represent two param(xScale,yScale) or nil
function CCDrawPrimitivesDeprecated.ccDrawSolidCircle(center,radius,angle,segments,...)
deprecatedTip("ccDrawSolidCircle","CCDrawPrimitives.ccDrawSolidCircle")
return CCDrawPrimitives.ccDrawSolidCircle(center,radius,angle,segments,...)
end
rawset(_G, "ccDrawSolidCircle", CCDrawPrimitivesDeprecated.ccDrawSolidCircle)
function CCDrawPrimitivesDeprecated.ccDrawQuadBezier(origin,control,destination,segments)
deprecatedTip("ccDrawQuadBezier","CCDrawPrimitives.ccDrawQuadBezier")
return CCDrawPrimitives.ccDrawQuadBezier(origin,control,destination,segments)
end
rawset(_G, "ccDrawQuadBezier", CCDrawPrimitivesDeprecated.ccDrawQuadBezier)
function CCDrawPrimitivesDeprecated.ccDrawCubicBezier(origin,control1,control2,destination,segments)
deprecatedTip("ccDrawCubicBezier","CCDrawPrimitives.ccDrawCubicBezier")
return CCDrawPrimitives.ccDrawCubicBezier(origin,control1,control2,destination,segments)
end
rawset(_G, "ccDrawCubicBezier", CCDrawPrimitivesDeprecated.ccDrawCubicBezier)
function CCDrawPrimitivesDeprecated.ccDrawCatmullRom(arrayOfControlPoints,segments)
deprecatedTip("ccDrawCatmullRom","CCDrawPrimitives.ccDrawCatmullRom")
return CCDrawPrimitives.ccDrawCatmullRom(arrayOfControlPoints,segments)
end
rawset(_G, "ccDrawCatmullRom", CCDrawPrimitivesDeprecated.ccDrawCatmullRom)
function CCDrawPrimitivesDeprecated.ccDrawCardinalSpline(config,tension,segments)
deprecatedTip("ccDrawCardinalSpline","CCDrawPrimitives.ccDrawCardinalSpline")
return CCDrawPrimitives.ccDrawCardinalSpline(config,tension,segments)
end
rawset(_G, "ccDrawCardinalSpline", CCDrawPrimitivesDeprecated.ccDrawCardinalSpline)
function CCDrawPrimitivesDeprecated.ccDrawColor4B(r,g,b,a)
deprecatedTip("ccDrawColor4B","CCDrawPrimitives.ccDrawColor4B")
return CCDrawPrimitives.ccDrawColor4B(r,g,b,a)
end
rawset(_G, "ccDrawColor4B", CCDrawPrimitivesDeprecated.ccDrawColor4B)
function CCDrawPrimitivesDeprecated.ccDrawColor4F(r,g,b,a)
deprecatedTip("ccDrawColor4F","CCDrawPrimitives.ccDrawColor4F")
return CCDrawPrimitives.ccDrawColor4F(r,g,b,a)
end
rawset(_G, "ccDrawColor4F", CCDrawPrimitivesDeprecated.ccDrawColor4F)
function CCDrawPrimitivesDeprecated.ccPointSize(pointSize)
deprecatedTip("ccPointSize","CCDrawPrimitives.ccPointSize")
return CCDrawPrimitives.ccPointSize(pointSize)
end
rawset(_G, "ccPointSize", CCDrawPrimitivesDeprecated.ccPointSize)
--functions of CCDrawPrimitives will be deprecated end
--enums of CCParticleSystem will be deprecated begin
_G["kParticleStartSizeEqualToEndSize"] = _G["kCCParticleStartSizeEqualToEndSize"]
_G["kParticleDurationInfinity"] = _G["kCCParticleDurationInfinity"]
--enums of CCParticleSystem will be deprecated end
--enums of CCRenderTexture will be deprecated begin
local CCRenderTextureDeprecated = { }
function CCRenderTextureDeprecated.newCCImage(self)
deprecatedTip("CCRenderTexture:newCCImage","CCRenderTexture:newImage")
return self:newImage()
end
rawset(CCRenderTexture, "newCCImage", CCRenderTextureDeprecated.newCCImage)
--enums of CCRenderTexture will be deprecated end
| mit |
sjznxd/lc-20130302 | applications/luci-statistics/luasrc/model/cbi/luci_statistics/ping.lua | 80 | 1397 | --[[
Luci configuration model for statistics - collectd ping plugin configuration
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("luci_statistics",
translate("Ping Plugin Configuration"),
translate(
"The ping plugin will send icmp echo replies to selected " ..
"hosts and measure the roundtrip time for each host."
))
-- collectd_ping config section
s = m:section( NamedSection, "collectd_ping", "luci_statistics" )
-- collectd_ping.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_ping.hosts (Host)
hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space."))
hosts.default = "127.0.0.1"
hosts:depends( "enable", 1 )
-- collectd_ping.ttl (TTL)
ttl = s:option( Value, "TTL", translate("TTL for ping packets") )
ttl.isinteger = true
ttl.default = 128
ttl:depends( "enable", 1 )
-- collectd_ping.interval (Interval)
interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") )
interval.isinteger = true
interval.default = 30
interval:depends( "enable", 1 )
return m
| apache-2.0 |
Tiger66639/premake-core | tests/api/test_containers.lua | 1 | 1895 | --
-- tests/api/test_containers.lua
-- Tests the API's solution() and project() container definitions.
-- Copyright (c) 2013-2014 Jason Perkins and the Premake project
--
local suite = test.declare("api_containers")
local api = premake.api
--
-- Setup and teardown
--
local wks
function suite.setup()
wks = workspace("MyWorkspace")
end
--
-- The first time a name is encountered, a new container should be created.
--
function suite.solution_createsOnFirstUse()
test.isnotnil(premake.global.getWorkspace("MyWorkspace"))
end
function suite.project_createsOnFirstUse()
project("MyProject")
test.isnotnil(premake.solution.getproject(wks, "MyProject"))
end
--
-- When a container is created, it should become the active scope.
--
function suite.solution_setsActiveScope()
test.issame(api.scope.solution, wks)
end
function suite.project_setsActiveScope()
local prj = project("MyProject")
test.issame(api.scope.project, prj)
end
--
-- When container function is called with no arguments, that should
-- become the current scope.
--
function suite.solution_setsActiveScope_onNoArgs()
project("MyProject")
group("MyGroup")
solution()
test.issame(wks, api.scope.solution)
test.isnil(api.scope.project)
test.isnil(api.scope.group)
end
function suite.project_setsActiveScope_onNoArgs()
local prj = project("MyProject")
group("MyGroup")
project()
test.issame(prj, api.scope.project)
end
--
-- The "*" name should activate the parent scope.
--
function suite.solution_onStar()
project("MyProject")
group("MyGroup")
filter("Debug")
solution "*"
test.isnil(api.scope.solution)
test.isnil(api.scope.project)
test.isnil(api.scope.group)
end
function suite.project_onStar()
project("MyProject")
group("MyGroup")
filter("Debug")
project "*"
test.issame(wks, api.scope.solution)
test.isnil(api.scope.project)
end
| bsd-3-clause |
anshkumar/yugioh-glaze | assets/script/c387282.lua | 3 | 2238 | --ガガガシスター
function c387282.initial_effect(c)
--search
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(387282,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(c387282.thtg)
e1:SetOperation(c387282.thop)
c:RegisterEffect(e1)
--level
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(387282,1))
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,387282)
e2:SetTarget(c387282.lvtg)
e2:SetOperation(c387282.lvop)
c:RegisterEffect(e2)
end
function c387282.thfilter(c)
return c:IsSetCard(0x54) and c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsAbleToHand()
end
function c387282.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c387282.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c387282.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c387282.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 c387282.filter(c)
return c:IsFaceup() and c:GetLevel()>0 and c:IsSetCard(0x54)
end
function c387282.lvtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c387282.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c387282.filter,tp,LOCATION_MZONE,0,1,e:GetHandler()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c387282.filter,tp,LOCATION_MZONE,0,1,1,e:GetHandler())
end
function c387282.lvop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and c:IsFaceup() and tc:IsRelateToEffect(e) and tc:IsFaceup() then
local lv=c:GetLevel()+tc:GetLevel()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetValue(lv)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
c:RegisterEffect(e1)
local e2=e1:Clone()
tc:RegisterEffect(e2)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c41925941.lua | 3 | 2263 | --冥王の咆哮
function c41925941.initial_effect(c)
--atkdown
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCondition(c41925941.condition)
e1:SetCost(c41925941.cost)
e1:SetTarget(c41925941.target)
e1:SetOperation(c41925941.operation)
c:RegisterEffect(e1)
end
function c41925941.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()
if a:IsControler(tp) then
e:SetLabelObject(d)
return a:IsFaceup() and a:IsRace(RACE_FIEND) and a:IsRelateToBattle() and d and d:IsFaceup() and d:IsRelateToBattle()
else
e:SetLabelObject(a)
return d:IsFaceup() and d:IsRace(RACE_FIEND) and d:IsRelateToBattle() and a and a:IsFaceup() and a:IsRelateToBattle()
end
end
function c41925941.cost(e,tp,eg,ep,ev,re,r,rp,chk)
local bc=e:GetLabelObject()
if chk==0 then return Duel.CheckLPCost(tp,100) and (bc:IsAttackAbove(100) or bc:IsDefenceAbove(100)) end
local maxc=Duel.GetLP(tp)
local maxpay=bc:GetAttack()
local def=bc:GetDefence()
if maxpay<def then maxpay=def end
if maxpay<maxc then maxc=maxpay end
if maxc>5000 then maxc=5000 end
maxc=math.floor(maxc/100)*100
local t={}
for i=1,maxc/100 do
t[i]=i*100
end
local cost=Duel.AnnounceNumber(tp,table.unpack(t))
Duel.PayLPCost(tp,cost)
e:SetLabel(cost)
end
function c41925941.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local tc=e:GetLabelObject()
if chkc then return chkc==tc end
if chk==0 then return tc:IsCanBeEffectTarget(e) end
Duel.SetTargetCard(tc)
end
function c41925941.operation(e,tp,eg,ep,ev,re,r,rp,chk)
local bc=Duel.GetFirstTarget()
local val=e:GetLabel()
if not bc or not bc:IsRelateToEffect(e) or not bc:IsControler(1-tp) then return end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(-val)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
bc:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_UPDATE_DEFENCE)
bc:RegisterEffect(e2)
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c11556339.lua | 3 | 1275 | --霊獣の連契
function c11556339.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,0x1c0)
e1:SetCondition(c11556339.condition)
e1:SetTarget(c11556339.target)
e1:SetOperation(c11556339.activate)
c:RegisterEffect(e1)
end
function c11556339.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0xb5)
end
function c11556339.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c11556339.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c11556339.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDestructable,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
local g=Duel.GetMatchingGroup(Card.IsDestructable,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c11556339.activate(e,tp,eg,ep,ev,re,r,rp)
local ct=Duel.GetMatchingGroupCount(c11556339.cfilter,tp,LOCATION_MZONE,0,nil)
if ct==0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectMatchingCard(tp,Card.IsDestructable,tp,LOCATION_MZONE,LOCATION_MZONE,1,ct,nil)
if g:GetCount()>0 then
Duel.HintSelection(g)
Duel.Destroy(g,REASON_EFFECT)
end
end
| gpl-2.0 |
rahulk90/vae_sparse | optvaedatasets/rcv2_miao/preprocess.lua | 2 | 4034 | --Sent via email by Yishu Miao (yishu.miao@cs.ox.ac.uk)
require 'torch'
dir ='./'--./data/RCV1-v2/raw/'
des ='./'--./data/RCV1-v2/'
raw_full = dir..'train.txt'
raw_train_file = dir..'train.txt'
vocab_raw = des..'vocabulary.txt'
vocab_file = des..'vocab.new'
train_feat = des..'train.feat'
test_feat = des..'test.feat'
--------------------------------------------
local split = function(s, p)
local rt= {}
string.gsub(s, '[^'..p..']+', function(w) table.insert(rt, w) end )
return rt
end
local randomSelect = function( total, n,m )
local num_set = {}
local map = {}
while #num_set < total do
local num = math.random(n,m)
if not map[num] then
map[num] = #num_set + 1
num_set[#num_set+1] = num
end
end
return num_set
end
local findElement = function( tab, element )
for _,e in pairs(tab) do
if e == element then
return true
end
end
return false
end
--------------------------------------------
-- 0. ID:freq
Id2Word = {}
Word2ID = {}
term_freq = {}
train_label_set = {}
-- build vocab
fin = io.open(raw_full)
for line in fin:lines() do
local words = split(line,' ')
if words[1] == '.I' then
train_label_set[#train_label_set+1] = tonumber(words[2])
else
if words[1] ~= '.W' then
for _,word in pairs(words) do
if not Word2ID[word] then
Id2Word[#Id2Word+1] = word
Word2ID[word] = #Id2Word
end
term_freq[Word2ID[word] ] = ( term_freq[Word2ID[word] ] or 0)+1
end
end
end
end
fin:close()
print ('Built vocabulary')
fout = io.open(vocab_raw,'w')
for i =1,#Id2Word do
fout:write(Id2Word[i]..'\n')
end
fout:close()
-- rank
term_set = {}
for k, v in pairs(term_freq) do
term_set[#term_set+1] = {key = k, val = v}
end
table.sort(term_set, function(x1,x2) return x1.val>x2.val end )
-- 1. Filter words
volume = 0
filt_map = {} -- orginal key (0~61188) to filter key(1~ ...)
filt_freq = {}
fout = io.open(vocab_file,'w')
for i = 1,10000 do
if term_set[i].val >2 then
volume = volume+1
filt_map[tonumber(term_set[i].key)] = volume -- make a map
filt_freq[#filt_freq+1] = term_set[i].val
fout:write(Id2Word[tonumber(term_set[i].key)]..' '..term_set[i].val..'\n')
end
end
fout:close()
--2. build set
local idx = 0
train_set = {}
local isTest = randomSelect(10000,1,804414)
fin = io.open(raw_train_file)
fout_train = io.open(train_feat,'w')
fout_test = io.open(test_feat,'w')
for line in fin:lines() do
words = split(line,' ')
if words[1] == '.I' then
idx = idx +1
train_set = {}
print(idx)
else
if words[1] ~= '.W' then
for _,word in pairs(words) do
if filt_map[Word2ID[word]] then
train_set[ Word2ID[word] ] = (train_set[ Word2ID[word] ] or 0 )+ 1
end
end
end
end
if #words == 0 then
if findElement(isTest,idx) then
label = tostring(train_label_set[idx])
line = ''
--print(test_label_set[idx])
for k,v in pairs(train_set) do
if filt_map[tonumber(k)] then
line = line ..' '..filt_map[tonumber(k)]..':'..v
end
end
if string.len(line) > 0 then
fout_test:write(label..line..'\n')
end
else
label = tostring(train_label_set[idx])
line = ''
--print(test_label_set[idx])
for k,v in pairs(train_set) do
if filt_map[tonumber(k)] then
line = line ..' '..filt_map[tonumber(k)]..':'..v
end
end
if string.len(line) > 0 then
fout_train:write(label..line..'\n')
end
end
end
end
fin:close()
fout_train:close()
fout_test:close()
| mit |
fmidev/himan | himan-scripts/emc.lua | 1 | 1471 | --- ensemble member count
local currentProducer = configuration:GetSourceProducer(0)
local currentProducerName = currentProducer.GetName(currentProducer)
msg = string.format("Calculating ensemble member count for for producer: %s", currentProducerName)
logger:Info(msg)
local params = {}
params["T-K"] = { current_level, 0, 0 }
local ensemble_size = 0
if configuration:Exists("ensemble_size") then
ensemble_size = tonumber(configuration:GetValue("ensemble_size"))
end
msg = string.format("Ensemble size: %d", ensemble_size)
logger:Info(msg)
for key, value in pairs(params) do
ens = nil
-- For MEPS we use lagged ensemble
if currentProducerName == "MEPS" then
ens = lagged_ensemble(param(key), "MEPS_LAGGED_ENSEMBLE", 250)
else
ens = ensemble(param(key), ensemble_size, 250)
end
ens:Fetch(configuration, current_time, value[1])
local sz = ens:Size()
local missing_members = ensemble_size - sz
params[key][3] = sz
if missing_members > 0 then
params[key][2] = value[2] + missing_members
end
end
for key, value in pairs(params) do
msg = string.format("Parameter '%s' missing %d members", key, value[2])
logger:Info(msg)
end
local values = {}
for i = 1, result:SizeLocations() do
values[i] = params["T-K"][3]
end
result:SetValues(values)
result:SetParam(param("ENSMEMB-N"))
result:SetForecastType(forecast_type(HPForecastType.kStatisticalProcessing))
logger:Info("Writing source data to file")
luatool:WriteToFile(result)
| mit |
MmxBoy/mmx-anti | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
johnparker007/mame | 3rdparty/genie/src/actions/vstudio/vs2017.lua | 26 | 1735 | --
-- vs2015.lua
-- Baseline support for Visual Studio 2017.
--
premake.vstudio.vc2017 = {}
local vc2017 = premake.vstudio.vc2017
local vstudio = premake.vstudio
---
-- Register a command-line action for Visual Studio 2017.
---
newaction
{
trigger = "vs2017",
shortname = "Visual Studio 2017",
description = "Generate Microsoft Visual Studio 2017 project files",
os = "windows",
valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Bundle" },
valid_languages = { "C", "C++", "C#" },
valid_tools = {
cc = { "msc" },
dotnet = { "msnet" },
},
onsolution = function(sln)
premake.generate(sln, "%%.sln", vstudio.sln2005.generate)
end,
onproject = function(prj)
if premake.isdotnetproject(prj) then
premake.generate(prj, "%%.csproj", vstudio.cs2005.generate)
premake.generate(prj, "%%.csproj.user", vstudio.cs2005.generate_user)
else
premake.vstudio.needAppxManifest = false
premake.generate(prj, "%%.vcxproj", premake.vs2010_vcxproj)
premake.generate(prj, "%%.vcxproj.user", premake.vs2010_vcxproj_user)
premake.generate(prj, "%%.vcxproj.filters", vstudio.vc2010.generate_filters)
if premake.vstudio.needAppxManifest then
premake.generate(prj, "%%/Package.appxmanifest", premake.vs2010_appxmanifest)
end
end
end,
oncleansolution = premake.vstudio.cleansolution,
oncleanproject = premake.vstudio.cleanproject,
oncleantarget = premake.vstudio.cleantarget,
vstudio = {
solutionVersion = "12",
targetFramework = "4.5.2",
toolsVersion = "15.0",
windowsTargetPlatformVersion = "8.1",
supports64bitEditContinue = true,
intDirAbsolute = false,
}
}
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c70479321.lua | 3 | 3128 | --EMドラミング・コング
function c70479321.initial_effect(c)
--pendulum summon
aux.AddPendulumProcedure(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--atk
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_ATKCHANGE)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_ATTACK_ANNOUNCE)
e2:SetRange(LOCATION_PZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1)
e2:SetCondition(c70479321.atkcon)
e2:SetTarget(c70479321.atktg)
e2:SetOperation(c70479321.atkop)
c:RegisterEffect(e2)
--summon with no tribute
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(70479321,0))
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e3:SetCode(EFFECT_SUMMON_PROC)
e3:SetCondition(c70479321.ntcon)
c:RegisterEffect(e3)
--change level
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_SUMMON_COST)
e4:SetOperation(c70479321.lvop)
c:RegisterEffect(e4)
--atk
local e5=e2:Clone()
e5:SetRange(LOCATION_MZONE)
e5:SetOperation(c70479321.atkop2)
c:RegisterEffect(e5)
end
function c70479321.atkcon(e,tp,eg,ep,ev,re,r,rp)
local a=Duel.GetAttacker()
local d=Duel.GetAttackTarget()
if d and a:GetControler()~=d:GetControler() then
if a:IsControler(tp) then e:SetLabelObject(a)
else e:SetLabelObject(d) end
return true
else return false end
end
function c70479321.atktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local tc=e:GetLabelObject()
if chkc then return chkc==tc end
if chk==0 then return tc:IsOnField() and tc:IsCanBeEffectTarget(e) end
Duel.SetTargetCard(tc)
end
function c70479321.atkop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(600)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_BATTLE)
tc:RegisterEffect(e1)
end
end
function c70479321.ntcon(e,c,minc)
if c==nil then return true end
return minc==0 and c:GetLevel()>4 and Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
and Duel.GetFieldGroupCount(c:GetControler(),LOCATION_MZONE,LOCATION_MZONE)==0
end
function c70479321.lvcon(e)
return e:GetHandler():GetMaterialCount()==0
end
function c70479321.lvop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c70479321.lvcon)
e1:SetValue(4)
e1:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e1)
end
function c70479321.atkop2(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(600)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_BATTLE)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c9402966.lua | 5 | 2326 | --超重武者タマ-C
function c9402966.initial_effect(c)
--synchro summon
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,9402966)
e1:SetCondition(c9402966.sccon)
e1:SetTarget(c9402966.sctg)
e1:SetOperation(c9402966.scop)
c:RegisterEffect(e1)
end
function c9402966.cfilter(c)
return c:IsFacedown() or not c:IsSetCard(0x9a)
end
function c9402966.sccon(e,tp,eg,ep,ev,re,r,rp)
return not Duel.IsExistingMatchingCard(c9402966.cfilter,tp,LOCATION_MZONE,0,1,nil)
and not Duel.IsExistingMatchingCard(Card.IsType,tp,LOCATION_GRAVE,0,1,nil,TYPE_SPELL+TYPE_TRAP)
end
function c9402966.filter(c,e,tp,lv)
return c:IsFaceup() and c:GetLevel()>0
and Duel.IsExistingMatchingCard(c9402966.scfilter,tp,LOCATION_EXTRA,0,1,nil,e,tp,lv+c:GetOriginalLevel())
end
function c9402966.scfilter(c,e,tp,lv)
return c:IsSetCard(0x9a) and c:GetLevel()==lv and c:IsType(TYPE_SYNCHRO)
and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_SYNCHRO,tp,false,false)
end
function c9402966.sctg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
local lv=e:GetHandler():GetOriginalLevel()
if chk==0 then return Duel.IsExistingTarget(c9402966.filter,tp,0,LOCATION_MZONE,1,nil,e,tp,lv) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectTarget(tp,c9402966.filter,tp,0,LOCATION_MZONE,1,1,nil,e,tp,lv)
g:AddCard(e:GetHandler())
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,g,2,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c9402966.scop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if not c:IsRelateToEffect(e) or not tc:IsRelateToEffect(e) then return end
local g=Group.FromCards(c,tc)
if Duel.SendtoGrave(g,REASON_EFFECT)==2 and c:GetLevel()>0 and c:IsLocation(LOCATION_GRAVE)
and tc:GetLevel()>0 and tc:IsLocation(LOCATION_GRAVE) then
local lv=c:GetLevel()+tc:GetLevel()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=Duel.SelectMatchingCard(tp,c9402966.scfilter,tp,LOCATION_EXTRA,0,1,1,nil,e,tp,lv)
local tc=sg:GetFirst()
if tc then
Duel.BreakEffect()
Duel.SpecialSummon(tc,SUMMON_TYPE_SYNCHRO,tp,tp,false,false,POS_FACEUP)
tc:CompleteProcedure()
end
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c83544697.lua | 3 | 1555 | --ガスタの交信
function c83544697.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TODECK+CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c83544697.target)
e1:SetOperation(c83544697.activate)
c:RegisterEffect(e1)
end
function c83544697.filter1(c)
return c:IsSetCard(0x10) and c:IsType(TYPE_MONSTER) and c:IsAbleToDeck()
end
function c83544697.filter2(c)
return c:IsDestructable()
end
function c83544697.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
if chk==0 then return Duel.IsExistingTarget(c83544697.filter1,tp,LOCATION_GRAVE,0,2,nil)
and Duel.IsExistingTarget(c83544697.filter2,tp,0,LOCATION_ONFIELD,1,e:GetHandler()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g1=Duel.SelectTarget(tp,c83544697.filter1,tp,LOCATION_GRAVE,0,2,2,nil)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g2=Duel.SelectTarget(tp,c83544697.filter2,tp,0,LOCATION_ONFIELD,1,1,e:GetHandler())
Duel.SetOperationInfo(0,CATEGORY_TODECK,g1,2,0,0)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g2,1,0,0)
end
function c83544697.activate(e,tp,eg,ep,ev,re,r,rp)
local ex,g1=Duel.GetOperationInfo(0,CATEGORY_TODECK)
local ex,g2=Duel.GetOperationInfo(0,CATEGORY_DESTROY)
if g1:GetFirst():IsRelateToEffect(e) and g1:GetNext():IsRelateToEffect(e) then
Duel.SendtoDeck(g1,nil,2,REASON_EFFECT)
if g2:GetFirst():IsRelateToEffect(e) then
Duel.BreakEffect()
Duel.Destroy(g2,REASON_EFFECT)
end
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c97403510.lua | 5 | 4131 | --No.92 偽骸神龍 Heart-eartH Dragon
function c97403510.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,9,3)
c:EnableReviveLimit()
--battle
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_REFLECT_BATTLE_DAMAGE)
e1:SetValue(1)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e2:SetValue(1)
c:RegisterEffect(e2)
--remove
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(97403510,0))
e3:SetCategory(CATEGORY_REMOVE)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_PHASE+PHASE_END)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1)
e3:SetCondition(c97403510.rmcon)
e3:SetCost(c97403510.rmcost)
e3:SetTarget(c97403510.rmtg)
e3:SetOperation(c97403510.rmop)
c:RegisterEffect(e3)
--spsummon
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(97403510,1))
e4:SetCategory(CATEGORY_SPECIAL_SUMMON)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetCondition(c97403510.spcon)
e4:SetTarget(c97403510.sptg)
e4:SetOperation(c97403510.spop)
c:RegisterEffect(e4)
--atkup
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(97403510,2))
e5:SetCategory(CATEGORY_ATKCHANGE)
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e5:SetCode(EVENT_SPSUMMON_SUCCESS)
e5:SetCondition(c97403510.atkcon)
e5:SetOperation(c97403510.atkop)
c:RegisterEffect(e5)
if not c97403510.global_check then
c97403510.global_check=true
local ge1=Effect.CreateEffect(c)
ge1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
ge1:SetCode(EVENT_SSET)
ge1:SetOperation(c97403510.checkop)
Duel.RegisterEffect(ge1,0)
end
end
c97403510.xyz_number=92
function c97403510.checkop(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
while tc do
tc:RegisterFlagEffect(97403510,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
tc=eg:GetNext()
end
end
function c97403510.rmcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()~=tp
end
function c97403510.rmcost(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 c97403510.filter(c,turn)
return (c:IsLocation(LOCATION_MZONE) or c:GetFlagEffect(97403510)~=0) and c:GetTurnID()==turn and c:IsAbleToRemove()
end
function c97403510.rmtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c97403510.filter,tp,0,LOCATION_ONFIELD,1,nil,Duel.GetTurnCount()) end
local g=Duel.GetMatchingGroup(c97403510.filter,tp,0,LOCATION_ONFIELD,nil,Duel.GetTurnCount())
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,g:GetCount(),0,0)
end
function c97403510.rmop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c97403510.filter,tp,0,LOCATION_ONFIELD,nil,Duel.GetTurnCount())
if g:GetCount()>0 then
Duel.Remove(g,POS_FACEUP,REASON_EFFECT)
end
end
function c97403510.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_DESTROY) and e:GetHandler():GetOverlayCount()>0
end
function c97403510.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 c97403510.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,1,tp,tp,false,false,POS_FACEUP)
end
end
function c97403510.atkcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SPECIAL+1
end
function c97403510.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local atk=Duel.GetFieldGroupCount(tp,LOCATION_REMOVED,LOCATION_REMOVED)*1000
if atk>0 and c:IsFaceup() and c:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(atk)
e1:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e1)
end
end
| gpl-2.0 |
MoZhonghua/skynet | 3rd/lpeg/re.lua | 160 | 6286 | -- $Id: re.lua,v 1.44 2013/03/26 20:11:40 roberto Exp $
-- imported functions and modules
local tonumber, type, print, error = tonumber, type, print, error
local setmetatable = setmetatable
local m = require"lpeg"
-- 'm' will be used to parse expressions, and 'mm' will be used to
-- create expressions; that is, 're' runs on 'm', creating patterns
-- on 'mm'
local mm = m
-- pattern's metatable
local mt = getmetatable(mm.P(0))
-- No more global accesses after this point
local version = _VERSION
if version == "Lua 5.2" then _ENV = nil end
local any = m.P(1)
-- Pre-defined names
local Predef = { nl = m.P"\n" }
local mem
local fmem
local gmem
local function updatelocale ()
mm.locale(Predef)
Predef.a = Predef.alpha
Predef.c = Predef.cntrl
Predef.d = Predef.digit
Predef.g = Predef.graph
Predef.l = Predef.lower
Predef.p = Predef.punct
Predef.s = Predef.space
Predef.u = Predef.upper
Predef.w = Predef.alnum
Predef.x = Predef.xdigit
Predef.A = any - Predef.a
Predef.C = any - Predef.c
Predef.D = any - Predef.d
Predef.G = any - Predef.g
Predef.L = any - Predef.l
Predef.P = any - Predef.p
Predef.S = any - Predef.s
Predef.U = any - Predef.u
Predef.W = any - Predef.w
Predef.X = any - Predef.x
mem = {} -- restart memoization
fmem = {}
gmem = {}
local mt = {__mode = "v"}
setmetatable(mem, mt)
setmetatable(fmem, mt)
setmetatable(gmem, mt)
end
updatelocale()
local I = m.P(function (s,i) print(i, s:sub(1, i-1)); return i end)
local function getdef (id, defs)
local c = defs and defs[id]
if not c then error("undefined name: " .. id) end
return c
end
local function patt_error (s, i)
local msg = (#s < i + 20) and s:sub(i)
or s:sub(i,i+20) .. "..."
msg = ("pattern error near '%s'"):format(msg)
error(msg, 2)
end
local function mult (p, n)
local np = mm.P(true)
while n >= 1 do
if n%2 >= 1 then np = np * p end
p = p * p
n = n/2
end
return np
end
local function equalcap (s, i, c)
if type(c) ~= "string" then return nil end
local e = #c + i
if s:sub(i, e - 1) == c then return e else return nil end
end
local S = (Predef.space + "--" * (any - Predef.nl)^0)^0
local name = m.R("AZ", "az", "__") * m.R("AZ", "az", "__", "09")^0
local arrow = S * "<-"
local seq_follow = m.P"/" + ")" + "}" + ":}" + "~}" + "|}" + (name * arrow) + -1
name = m.C(name)
-- a defined name only have meaning in a given environment
local Def = name * m.Carg(1)
local num = m.C(m.R"09"^1) * S / tonumber
local String = "'" * m.C((any - "'")^0) * "'" +
'"' * m.C((any - '"')^0) * '"'
local defined = "%" * Def / function (c,Defs)
local cat = Defs and Defs[c] or Predef[c]
if not cat then error ("name '" .. c .. "' undefined") end
return cat
end
local Range = m.Cs(any * (m.P"-"/"") * (any - "]")) / mm.R
local item = defined + Range + m.C(any)
local Class =
"["
* (m.C(m.P"^"^-1)) -- optional complement symbol
* m.Cf(item * (item - "]")^0, mt.__add) /
function (c, p) return c == "^" and any - p or p end
* "]"
local function adddef (t, k, exp)
if t[k] then
error("'"..k.."' already defined as a rule")
else
t[k] = exp
end
return t
end
local function firstdef (n, r) return adddef({n}, n, r) end
local function NT (n, b)
if not b then
error("rule '"..n.."' used outside a grammar")
else return mm.V(n)
end
end
local exp = m.P{ "Exp",
Exp = S * ( m.V"Grammar"
+ m.Cf(m.V"Seq" * ("/" * S * m.V"Seq")^0, mt.__add) );
Seq = m.Cf(m.Cc(m.P"") * m.V"Prefix"^0 , mt.__mul)
* (#seq_follow + patt_error);
Prefix = "&" * S * m.V"Prefix" / mt.__len
+ "!" * S * m.V"Prefix" / mt.__unm
+ m.V"Suffix";
Suffix = m.Cf(m.V"Primary" * S *
( ( m.P"+" * m.Cc(1, mt.__pow)
+ m.P"*" * m.Cc(0, mt.__pow)
+ m.P"?" * m.Cc(-1, mt.__pow)
+ "^" * ( m.Cg(num * m.Cc(mult))
+ m.Cg(m.C(m.S"+-" * m.R"09"^1) * m.Cc(mt.__pow))
)
+ "->" * S * ( m.Cg((String + num) * m.Cc(mt.__div))
+ m.P"{}" * m.Cc(nil, m.Ct)
+ m.Cg(Def / getdef * m.Cc(mt.__div))
)
+ "=>" * S * m.Cg(Def / getdef * m.Cc(m.Cmt))
) * S
)^0, function (a,b,f) return f(a,b) end );
Primary = "(" * m.V"Exp" * ")"
+ String / mm.P
+ Class
+ defined
+ "{:" * (name * ":" + m.Cc(nil)) * m.V"Exp" * ":}" /
function (n, p) return mm.Cg(p, n) end
+ "=" * name / function (n) return mm.Cmt(mm.Cb(n), equalcap) end
+ m.P"{}" / mm.Cp
+ "{~" * m.V"Exp" * "~}" / mm.Cs
+ "{|" * m.V"Exp" * "|}" / mm.Ct
+ "{" * m.V"Exp" * "}" / mm.C
+ m.P"." * m.Cc(any)
+ (name * -arrow + "<" * name * ">") * m.Cb("G") / NT;
Definition = name * arrow * m.V"Exp";
Grammar = m.Cg(m.Cc(true), "G") *
m.Cf(m.V"Definition" / firstdef * m.Cg(m.V"Definition")^0,
adddef) / mm.P
}
local pattern = S * m.Cg(m.Cc(false), "G") * exp / mm.P * (-any + patt_error)
local function compile (p, defs)
if mm.type(p) == "pattern" then return p end -- already compiled
local cp = pattern:match(p, 1, defs)
if not cp then error("incorrect pattern", 3) end
return cp
end
local function match (s, p, i)
local cp = mem[p]
if not cp then
cp = compile(p)
mem[p] = cp
end
return cp:match(s, i or 1)
end
local function find (s, p, i)
local cp = fmem[p]
if not cp then
cp = compile(p) / 0
cp = mm.P{ mm.Cp() * cp * mm.Cp() + 1 * mm.V(1) }
fmem[p] = cp
end
local i, e = cp:match(s, i or 1)
if i then return i, e - 1
else return i
end
end
local function gsub (s, p, rep)
local g = gmem[p] or {} -- ensure gmem[p] is not collected while here
gmem[p] = g
local cp = g[rep]
if not cp then
cp = compile(p)
cp = mm.Cs((cp / rep + 1)^0)
g[rep] = cp
end
return cp:match(s)
end
-- exported names
local re = {
compile = compile,
match = match,
find = find,
gsub = gsub,
updatelocale = updatelocale,
}
if version == "Lua 5.1" then _G.re = re end
return re
| mit |
mramir8274/danibot | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
ARGANBOT/ARSHAM | plugins/stats.lua | 1 | 4015 | do
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(receiver, chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false)
return --text
end
local function chat_stats2(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nGroups: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == 'teleseed' then -- Put everything you like :)
local about = _config.about_text
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ")
return about
end
if matches[1]:lower() == "statslist" then
if not is_momod(msg) then
return "For mods only !"
end
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats2(chat_id)
end
if matches[1]:lower() == "stats" then
if not matches[2] then
if not is_momod(msg) then
return "For mods only !"
end
if msg.to.type == 'chat' or msg.to.type == 'channel' then
local receiver = get_receiver(msg)
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats(receiver, chat_id)
else
return
end
end
if matches[2] == "teleseed" then -- Put everything you like :)
if not is_admin1(msg) then
return "For admins only !"
else
return bot_stats()
end
end
if matches[2] == "group" then
if not is_admin1(msg) then
return "For admins only !"
else
return chat_stats(matches[3])
end
end
end
end
return {
patterns = {
"^[#!/]([Ss]tats)$",
"^[#!/]([Ss]tatslist)$",
"^[#!/]([Ss]tats) (group) (%d+)",
"^[#!/]([Ss]tats) (teleseed)",
"^[#!/]([Tt]eleseed)"
},
run = run
}
end
| gpl-2.0 |
dinodeck/rpg_dialog_script | dialog_runner/code/discourse/DiscourseEventManager.lua | 1 | 1356 | DiscourseEventManager = {}
DiscourseEventManager.__index = DiscourseEventManager
function DiscourseEventManager:Create()
local this =
{
mEventList = {}
}
setmetatable(this, self)
return this
end
function DiscourseEventManager:Render(renderer, trackbar)
local value = trackbar:Value()
local left = trackbar:Left()
local right = trackbar:Right()
for k, v in ipairs(self.mEventList) do
trackbar:DrawEvent(renderer, v.position, v.position > value)
end
end
function DiscourseEventManager:AddEvent(v01)
-- Yes, this should be ordered really.
table.insert(self.mEventList, {position = v01})
end
function DiscourseEventManager:Jump01(prev01, now01)
-- print(prev01, now01)
-- print("V")
-- print(debug.traceback())
-- print("")
local eventsToRun = {}
-- same or previous does not fire any events
if prev01 >= now01 then
return eventsToRun
end
-- future events that have been jumped over do fire
for k, v in ipairs(self.mEventList) do
if v.position > prev01 and v.position <= now01 then
table.insert(eventsToRun, v)
end
end
if next(eventsToRun) then
print("Ran some events")
for k,v in ipairs(eventsToRun) do
print(k, v.position)
end
end
return eventsToRun
end | mit |
anshkumar/yugioh-glaze | assets/script/c33911264.lua | 3 | 1680 | --太陽風帆船
function c33911264.initial_effect(c)
c:SetUniqueOnField(1,1,33911264)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c33911264.spcon)
e1:SetOperation(c33911264.spop)
c:RegisterEffect(e1)
--level up
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(33911264,0))
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetCode(EVENT_PHASE+PHASE_STANDBY)
e2:SetCondition(c33911264.lvcon)
e2:SetOperation(c33911264.lvop)
c:RegisterEffect(e2)
end
function c33911264.spcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
return Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)==0
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
end
function c33911264.spop(e,tp,eg,ep,ev,re,r,rp,c)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_SET_BASE_ATTACK)
e1:SetValue(400)
e1:SetReset(RESET_EVENT+0xff0000)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_SET_BASE_DEFENCE)
e2:SetValue(1200)
c:RegisterEffect(e2)
end
function c33911264.lvcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c33911264.lvop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFacedown() or not c:IsRelateToEffect(e) then return end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e1)
end
| gpl-2.0 |
freifunk-gluon/luci | applications/luci-statistics/luasrc/model/cbi/luci_statistics/netlink.lua | 78 | 2765 | --[[
Luci configuration model for statistics - collectd netlink plugin configuration
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
local devices = luci.sys.net.devices()
m = Map("luci_statistics",
translate("Netlink Plugin Configuration"),
translate(
"The netlink plugin collects extended informations like " ..
"qdisc-, class- and filter-statistics for selected interfaces."
))
-- collectd_netlink config section
s = m:section( NamedSection, "collectd_netlink", "luci_statistics" )
-- collectd_netlink.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_netlink.interfaces (Interface)
interfaces = s:option( MultiValue, "Interfaces", translate("Basic monitoring") )
interfaces.widget = "select"
interfaces.optional = true
interfaces.size = #devices + 1
interfaces:depends( "enable", 1 )
interfaces:value("")
for i, v in ipairs(devices) do
interfaces:value(v)
end
-- collectd_netlink.verboseinterfaces (VerboseInterface)
verboseinterfaces = s:option( MultiValue, "VerboseInterfaces", translate("Verbose monitoring") )
verboseinterfaces.widget = "select"
verboseinterfaces.optional = true
verboseinterfaces.size = #devices + 1
verboseinterfaces:depends( "enable", 1 )
verboseinterfaces:value("")
for i, v in ipairs(devices) do
verboseinterfaces:value(v)
end
-- collectd_netlink.qdiscs (QDisc)
qdiscs = s:option( MultiValue, "QDiscs", translate("Qdisc monitoring") )
qdiscs.widget = "select"
qdiscs.optional = true
qdiscs.size = #devices + 1
qdiscs:depends( "enable", 1 )
qdiscs:value("")
for i, v in ipairs(devices) do
qdiscs:value(v)
end
-- collectd_netlink.classes (Class)
classes = s:option( MultiValue, "Classes", translate("Shaping class monitoring") )
classes.widget = "select"
classes.optional = true
classes.size = #devices + 1
classes:depends( "enable", 1 )
classes:value("")
for i, v in ipairs(devices) do
classes:value(v)
end
-- collectd_netlink.filters (Filter)
filters = s:option( MultiValue, "Filters", translate("Filter class monitoring") )
filters.widget = "select"
filters.optional = true
filters.size = #devices + 1
filters:depends( "enable", 1 )
filters:value("")
for i, v in ipairs(devices) do
filters:value(v)
end
-- collectd_netlink.ignoreselected (IgnoreSelected)
ignoreselected = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") )
ignoreselected.default = 0
ignoreselected:depends( "enable", 1 )
return m
| apache-2.0 |
kiarash14/br | plugins/weather.lua | 274 | 1531 | do
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
location = string.gsub(location," ","+")
local url = BASE_URL
url = url..'?q='..location
url = url..'&units=metric'
url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'The temperature in '..city
..' (' ..country..')'
..' is '..weather.main.temp..'°C'
local conditions = 'Current conditions are: '
.. weather.weather[1].description
if weather.weather[1].main == 'Clear' then
conditions = conditions .. ' ☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. ' ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. ' ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. ' ☔☔☔☔'
end
return temp .. '\n' .. conditions
end
local function run(msg, matches)
local city = 'Madrid,ES'
if matches[1] ~= '!weather' then
city = matches[1]
end
local text = get_weather(city)
if not text then
text = 'Can\'t get weather from that city.'
end
return text
end
return {
description = "weather in that city (Madrid is default)",
usage = "!weather (city)",
patterns = {
"^!weather$",
"^!weather (.*)$"
},
run = run
}
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c10691144.lua | 3 | 2046 | --氷結界の鏡
function c10691144.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetOperation(c10691144.activate)
c:RegisterEffect(e1)
end
function c10691144.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetFlagEffect(tp,10691144)~=0 then return end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetCode(EVENT_REMOVE)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetCondition(c10691144.rmcon)
e1:SetOperation(c10691144.rmop)
Duel.RegisterEffect(e1,tp)
Duel.RegisterFlagEffect(tp,10691144,RESET_PHASE+PHASE_END,0,1)
end
function c10691144.rmcon(e,tp,eg,ep,ev,re,r,rp)
if not (re:GetOwnerPlayer()==1-tp and re:IsActiveType(TYPE_MONSTER) and re:IsActivated()) then
return false
end
local flag=0
local tc=eg:GetFirst()
while tc do
local ploc=tc:GetPreviousLocation()
if tc:GetPreviousControler()==tp and bit.band(ploc,0x1e)~=0 then
flag=bit.bor(flag,ploc)
end
tc=eg:GetNext()
end
e:SetLabel(flag)
return flag~=0
end
function c10691144.rmop(e,tp,eg,ep,ev,re,r,rp)
local g=Group.CreateGroup()
local flag=e:GetLabel()
if bit.band(flag,LOCATION_HAND)~=0 then
local rg=Duel.GetMatchingGroup(Card.IsAbleToRemove,tp,0,LOCATION_HAND,nil)
if rg:GetCount()>0 then
local ct=1
if rg:GetCount()>1 then ct=Duel.SelectOption(tp,aux.Stringid(10691144,3),aux.Stringid(10691144,4))+1 end
g:Merge(rg:RandomSelect(tp,ct))
end
end
if bit.band(flag,LOCATION_ONFIELD)~=0 then
local rg=Duel.GetMatchingGroup(Card.IsAbleToRemove,tp,0,LOCATION_ONFIELD,nil)
if rg:GetCount()>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
g:Merge(rg:Select(tp,1,2,nil))
end
end
if bit.band(flag,LOCATION_GRAVE)~=0 then
local rg=Duel.GetMatchingGroup(Card.IsAbleToRemove,tp,0,LOCATION_GRAVE,nil)
if rg:GetCount()>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
g:Merge(rg:Select(tp,1,2,nil))
end
end
Duel.Remove(g,POS_FACEUP,REASON_EFFECT)
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c69058960.lua | 3 | 3454 | --No.13 ケインズ・デビル
function c69058960.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,1,2)
c:EnableReviveLimit()
--pos
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(69058960,0))
e1:SetCategory(CATEGORY_POSITION)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c69058960.cost)
e1:SetTarget(c69058960.target)
e1:SetOperation(c69058960.operation)
c: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_INDESTRUCTABLE_BATTLE)
e2:SetCondition(c69058960.indcon)
e2:SetValue(1)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
c:RegisterEffect(e3)
--reflect
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_REFLECT_BATTLE_DAMAGE)
e4:SetCondition(c69058960.refcon)
e4:SetValue(1)
c:RegisterEffect(e4)
end
c69058960.xyz_number=13
function c69058960.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 c69058960.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,0,LOCATION_MZONE)>0 end
end
function c69058960.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g=Duel.GetFieldGroup(tp,0,LOCATION_MZONE)
if g:GetCount()>0 then
Duel.ChangePosition(g,POS_FACEUP_ATTACK)
c:RegisterFlagEffect(69058960,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_MUST_ATTACK)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_CANNOT_EP)
e2:SetRange(LOCATION_MZONE)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetTargetRange(1,0)
e2:SetCondition(c69058960.becon)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetRange(LOCATION_MZONE)
e3:SetTargetRange(0,LOCATION_MZONE)
e3:SetProperty(EFFECT_FLAG_SET_AVAILABLE+EFFECT_FLAG_IGNORE_IMMUNE)
e3:SetCode(EFFECT_CANNOT_BE_BATTLE_TARGET)
e3:SetTarget(c69058960.bttg)
e3:SetValue(c69058960.vala)
e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e3)
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_CANNOT_DIRECT_ATTACK)
e4:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e4)
tc=g:GetNext()
end
end
end
function c69058960.filter(c)
return c:IsFaceup() and c:IsCode(95442074)
end
function c69058960.indcon(e)
return Duel.IsExistingMatchingCard(c69058960.filter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil)
and e:GetHandler():GetOverlayCount()~=0
end
function c69058960.refcon(e)
return Duel.IsExistingMatchingCard(c69058960.filter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil)
and Duel.GetAttackTarget()==e:GetHandler()
end
function c69058960.becon(e)
return e:GetHandler():IsAttackable()
end
function c69058960.bttg(e,c)
return c:GetFlagEffect(69058960)==0
end
function c69058960.vala(e,c)
return c==e:GetHandler()
end
| gpl-2.0 |
zhaoxin54430/zhaoxin_test | src_luci/applications/luci-app-statistics/luasrc/statistics/i18n.lua | 39 | 1879 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.i18n", package.seeall)
require("luci.util")
require("luci.i18n")
Instance = luci.util.class()
function Instance.__init__( self, graph )
self.i18n = luci.i18n
self.graph = graph
end
function Instance._subst( self, str, val )
str = str:gsub( "%%H", self.graph.opts.host or "" )
str = str:gsub( "%%pn", val.plugin or "" )
str = str:gsub( "%%pi", val.pinst or "" )
str = str:gsub( "%%dt", val.dtype or "" )
str = str:gsub( "%%di", val.dinst or "" )
str = str:gsub( "%%ds", val.dsrc or "" )
return str
end
function Instance.title( self, plugin, pinst, dtype, dinst, user_title )
local title = user_title or
"p=%s/pi=%s/dt=%s/di=%s" % {
plugin,
(pinst and #pinst > 0) and pinst or "(nil)",
(dtype and #dtype > 0) and dtype or "(nil)",
(dinst and #dinst > 0) and dinst or "(nil)"
}
return self:_subst( title, {
plugin = plugin,
pinst = pinst,
dtype = dtype,
dinst = dinst
} )
end
function Instance.label( self, plugin, pinst, dtype, dinst, user_label )
local label = user_label or
"dt=%s/di=%s" % {
(dtype and #dtype > 0) and dtype or "(nil)",
(dinst and #dinst > 0) and dinst or "(nil)"
}
return self:_subst( label, {
plugin = plugin,
pinst = pinst,
dtype = dtype,
dinst = dinst
} )
end
function Instance.ds( self, source )
local label = source.title or
"dt=%s/di=%s/ds=%s" % {
(source.type and #source.type > 0) and source.type or "(nil)",
(source.instance and #source.instance > 0) and source.instance or "(nil)",
(source.ds and #source.ds > 0) and source.ds or "(nil)"
}
return self:_subst( label, {
dtype = source.type,
dinst = source.instance,
dsrc = source.ds
} ):gsub(":", "\\:")
end
| gpl-2.0 |
mobinantispam/017 | plugins/ingroup.lua | 527 | 44020 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
mikeller/nodemcu-firmware | lua_examples/ucglib/GraphicsTest.lua | 8 | 3420 | -- setup SPI and connect display
function init_spi_display()
-- Hardware SPI CLK = GPIO14
-- Hardware SPI MOSI = GPIO13
-- Hardware SPI MISO = GPIO12 (not used)
-- Hardware SPI /CS = GPIO15 (not used)
-- CS, D/C, and RES can be assigned freely to available GPIOs
local cs = 8 -- GPIO15, pull-down 10k to GND
local dc = 4 -- GPIO2
local res = 0 -- GPIO16
spi.setup(1, spi.MASTER, spi.CPOL_LOW, spi.CPHA_LOW, 8, 8)
-- we won't be using the HSPI /CS line, so disable it again
gpio.mode(8, gpio.INPUT, gpio.PULLUP)
-- initialize the matching driver for your display
-- see app/include/ucg_config.h
--disp = ucg.ili9341_18x240x320_hw_spi(cs, dc, res)
disp = ucg.st7735_18x128x160_hw_spi(cs, dc, res)
end
-- switch statement http://lua-users.org/wiki/SwitchStatement
function switch(c)
local swtbl = {
casevar = c,
caseof = function (self, code)
local f
if (self.casevar) then
f = code[self.casevar] or code.default
else
f = code.missing or code.default
end
if f then
if type(f)=="function" then
return f(self.casevar,self)
else
error("case "..tostring(self.casevar).." not a function")
end
end
end
}
return swtbl
end
z = 127 -- start value
function lcg_rnd()
z = bit.band(65 * z + 17, 255)
return z
end
function millis()
local usec = tmr.now()
return usec/1000
end
function set_clip_range()
local x, y, w, h
w = bit.band(lcg_rnd(), 31)
h = bit.band(lcg_rnd(), 31)
w = w + 25
h = h + 25
x = bit.rshift(lcg_rnd() * (disp:getWidth() - w), 8)
y = bit.rshift(lcg_rnd() * (disp:getHeight() - h), 8)
disp:setClipRange(x, y, w, h)
end
function loop()
if (loop_idx == 0) then
switch(bit.band(r, 3)) : caseof {
[0] = function() disp:undoRotate() end,
[1] = function() disp:setRotate90() end,
[2] = function() disp:setRotate180() end,
default = function() disp:setRotate270() end
}
if ( r > 3 ) then
disp:clearScreen()
set_clip_range()
end
r = bit.band(r + 1, 255)
end
switch(loop_idx) : caseof {
[0] = function() end,
[1] = function() require("GT_graphics_test").run() end,
[2] = function() require("GT_cross").run() end,
[3] = function() require("GT_pixel_and_lines").run() end,
[4] = function() require("GT_color_test").run() end,
[5] = function() require("GT_triangle").run() end,
[6] = function() require("GT_fonts").run() end,
[7] = function() require("GT_text").run() end,
[8] = function() if r <= 3 then require("GT_clip").run() end end,
[9] = function() require("GT_box").run() end,
[10] = function() require("GT_gradient").run() end,
[11] = function() disp:setMaxClipRange() end,
default = function() loop_idx = -1 end
}
loop_idx = loop_idx + 1
print("Heap: " .. node.heap())
end
T = 1000
r = 0
loop_idx = 0
init_spi_display()
disp:begin(ucg.FONT_MODE_TRANSPARENT)
disp:setFont(ucg.font_ncenR14_hr)
disp:clearScreen()
tmr.register(0, 3000, tmr.ALARM_AUTO, function() loop() end)
tmr.start(0)
| mit |
anshkumar/yugioh-glaze | assets/script/c4549095.lua | 5 | 1491 | --BK カウンターブロー
function c4549095.initial_effect(c)
--atkup
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetDescription(aux.Stringid(4549095,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetRange(LOCATION_HAND+LOCATION_GRAVE)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCountLimit(1,4549095)
e1:SetCondition(c4549095.condition)
e1:SetCost(c4549095.cost)
e1:SetOperation(c4549095.operation)
c:RegisterEffect(e1)
end
function c4549095.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:GetControler()==tp and a:IsSetCard(0x84) and a:IsRelateToBattle())
or (d and d:GetControler()==tp and d:IsSetCard(0x84) and d:IsRelateToBattle())
end
function c4549095.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
function c4549095.operation(e,tp,eg,ep,ev,re,r,rp,chk)
local a=Duel.GetAttacker()
if Duel.GetTurnPlayer()~=tp then a=Duel.GetAttackTarget() end
if not a:IsRelateToBattle() 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(1000)
a:RegisterEffect(e1)
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c46404281.lua | 9 | 1220 | --ラヴァルのマグマ砲兵
function c46404281.initial_effect(c)
--damage
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(46404281,0))
e1:SetCategory(CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(2)
e1:SetCost(c46404281.damcost)
e1:SetTarget(c46404281.damtg)
e1:SetOperation(c46404281.damop)
c:RegisterEffect(e1)
end
function c46404281.cfilter(c)
return c:IsAttribute(ATTRIBUTE_FIRE) and c:IsAbleToGraveAsCost()
end
function c46404281.damcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c46404281.cfilter,tp,LOCATION_HAND,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c46404281.cfilter,tp,LOCATION_HAND,0,1,1,nil)
Duel.SendtoGrave(g,REASON_COST)
end
function c46404281.damtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(500)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,500)
end
function c46404281.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
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c24903843.lua | 3 | 2868 | --버제스토마 피카이아
function c24903843.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c24903843.target)
e1:SetOperation(c24903843.activate)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_CHAINING)
e2:SetRange(LOCATION_GRAVE)
e2:SetCondition(c24903843.spcon)
e2:SetTarget(c24903843.sptg)
e2:SetOperation(c24903843.spop)
c:RegisterEffect(e2)
end
function c24903843.filter(c)
return c:IsSetCard(0xd4) and c:IsDiscardable(REASON_EFFECT)
end
function c24903843.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,2)
and Duel.IsExistingMatchingCard(c24903843.filter,tp,LOCATION_HAND,0,1,e:GetHandler()) end
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,2)
end
function c24903843.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.DiscardHand(tp,c24903843.filter,1,1,REASON_EFFECT+REASON_DISCARD,nil)~=0 then
Duel.BreakEffect()
Duel.Draw(tp,2,REASON_EFFECT)
end
end
function c24903843.spcon(e,tp,eg,ep,ev,re,r,rp)
return re:IsActiveType(TYPE_TRAP) and re:IsHasType(EFFECT_TYPE_ACTIVATE)
end
function c24903843.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:GetFlagEffect(24903843)==0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsPlayerCanSpecialSummonMonster(tp,24903843,0xd4,0x11,1200,0,2,RACE_AQUA,ATTRIBUTE_WATER) end
c:RegisterFlagEffect(24903843,RESET_CHAIN,0,1)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0)
end
function c24903843.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local c=e:GetHandler()
if c:IsRelateToEffect(e)
and Duel.IsPlayerCanSpecialSummonMonster(tp,24903843,0xd4,0x11,1200,0,2,RACE_AQUA,ATTRIBUTE_WATER) then
c:SetStatus(STATUS_NO_LEVEL,false)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_TYPE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(TYPE_NORMAL+TYPE_MONSTER)
e1:SetReset(RESET_EVENT+0x47c0000)
c:RegisterEffect(e1,true)
Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_IMMUNE_EFFECT)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetValue(c24903843.efilter)
e2:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_LEAVE_FIELD_REDIRECT)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetReset(RESET_EVENT+0x47e0000)
e3:SetValue(LOCATION_REMOVED)
c:RegisterEffect(e3,true)
end
end
function c24903843.efilter(e,re)
return re:IsActiveType(TYPE_MONSTER)
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c61258740.lua | 5 | 1406 | --水神の護符
function c61258740.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c61258740.target)
c:RegisterEffect(e1)
--indes
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e2:SetRange(LOCATION_SZONE)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetTarget(aux.TargetBoolFunction(Card.IsAttribute,ATTRIBUTE_WATER))
e2:SetValue(c61258740.indval)
c:RegisterEffect(e2)
end
function c61258740.indval(e,re,tp)
return e:GetHandlerPlayer()==1-tp
end
function c61258740.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
e:GetHandler():SetTurnCounter(0)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_SZONE)
e1:SetCondition(c61258740.tgcon)
e1:SetOperation(c61258740.tgop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END+RESET_OPPO_TURN,3)
e:GetHandler():RegisterEffect(e1)
end
function c61258740.tgcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()~=tp
end
function c61258740.tgop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local ct=c:GetTurnCounter()
ct=ct+1
c:SetTurnCounter(ct)
if ct==3 then
Duel.SendtoGrave(c,REASON_RULE)
end
end
| gpl-2.0 |
shirat74/sile | packages/pagebuilder-bestfit.lua | 5 | 1481 | local MAX_PAGES = 5
SILE.typesetter.pageBuilder = function (self, independent)
-- Find last penalty
local q = self.state.outputQueue
local lastpenalty = -1
local cHeight = SILE.length.new()
for j = #q,1,-1 do
if q[j]:isPenalty() and lastpenalty == -1 then
lastpenalty = q[j].penalty
end
cHeight = cHeight + q[j].height
end
if not(cHeight > self.frame:height() * MAX_PAGES) and not(independent) and lastpenalty > -10000 then return false end
SU.debug("pagebuilder", "Finally running pagebuilder")
repeat
q = self.state.outputQueue
local breaks = SILE.linebreak:doBreak( q, self.frame:height(), true)
--Height is variable! therefore only the first break is believable
local point = breaks[1]
if point.position == 0 then return false end
local linestart = 1
local slice = {}
local newslice = {}
for j = linestart, #self.state.outputQueue do
if j <= point.position then slice[#slice+1] = q[j] else newslice[#newslice+1] = q[j] end
end
self:setVerticalGlue(slice, self.frame:height())
self:outputLinesToPage(slice)
self.state.outputQueue = newslice
if #(self.state.outputQueue) == 0 then return false end
self:initNextFrame() -- This causes a tail call if there is more stuff waiting
-- If not, we keep going if we are being asked to ship out a page now now now.
until lastpenalty > -10000
return false -- because we have already dealt with initializing the next frame
end
| mit |
anshkumar/yugioh-glaze | assets/script/c17955766.lua | 6 | 1408 | --N・アクア・ドルフィン
function c17955766.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(17955766,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCost(c17955766.cost)
e1:SetTarget(c17955766.target)
e1:SetOperation(c17955766.activate)
c:RegisterEffect(e1)
end
function c17955766.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,nil) end
Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD)
end
function c17955766.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,0,LOCATION_HAND)>0 end
end
function c17955766.filter(c,atk)
return c:IsFaceup() and c:IsAttackAbove(atk)
end
function c17955766.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetFieldGroup(tp,0,LOCATION_HAND)
if g:GetCount()>0 then
Duel.ConfirmCards(tp,g)
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(17955766,1))
local tg=g:FilterSelect(tp,Card.IsType,1,1,nil,TYPE_MONSTER)
local tc=tg:GetFirst()
if tc then
local atk=tc:GetAttack()
if atk>=0 and Duel.IsExistingMatchingCard(c17955766.filter,tp,LOCATION_MZONE,0,1,nil,atk) then
Duel.Destroy(tc,REASON_EFFECT)
Duel.Damage(1-tp,500,REASON_EFFECT)
else
Duel.Damage(tp,500,REASON_EFFECT)
end
end
Duel.ShuffleHand(1-tp)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c85775486.lua | 7 | 1497 | --再機動
function c85775486.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c85775486.cost)
e1:SetTarget(c85775486.target)
e1:SetOperation(c85775486.activate)
c:RegisterEffect(e1)
end
function c85775486.cfilter(c)
return c:IsSetCard(0x13) and c:IsType(TYPE_MONSTER) and c:IsAbleToDeckAsCost()
end
function c85775486.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c85775486.cfilter,tp,LOCATION_HAND,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,c85775486.cfilter,tp,LOCATION_HAND,0,1,1,nil)
Duel.SendtoDeck(g,nil,2,REASON_COST)
end
function c85775486.filter(c)
return c:IsSetCard(0x13) and c:IsAbleToHand()
end
function c85775486.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c85775486.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c85775486.filter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c85775486.filter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c85775486.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,tc)
end
end
| gpl-2.0 |
jakubjelinek/gregorio | tex/gregoriotex.lua | 1 | 8725 | --GregorioTeX Lua file.
--Copyright (C) 2008-2013 Elie Roux <elie.roux@telecom-bretagne.eu>
--
--This program is free software: you can redistribute it and/or modify
--it under the terms of the GNU General Public License as published by
--the Free Software Foundation, either version 3 of the License, or
--(at your option) any later version.
--
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
--GNU General Public License for more details.
--
--You should have received a copy of the GNU General Public License
--along with this program. If not, see <http://www.gnu.org/licenses/>.
-- this file contains lua functions used by GregorioTeX when called with LuaTeX.
local hpack, traverse_id, has_attribute, count, remove, insert_after, copy = node.hpack, node.traverse_id, node.has_attribute, node.count, node.remove, node.insert_after, node.copy
gregoriotex = gregoriotex or {}
local gregoriotex = gregoriotex
local internalversion = 20130616
local err, warn, info, log = luatexbase.provides_module({
name = "gregoriotex",
version = 2.4,
greinternalversion = internalversion,
date = "2013/12/29",
description = "GregorioTeX module.",
author = "Elie Roux",
copyright = "Elie Roux",
license = "GPLv3",
})
local hlist = node.id('hlist')
local vlist = node.id('vlist')
local glyph = node.id('glyph')
local hyphen = tex.defaulthyphenchar or 45
local gregorioattr = luatexbase.attributes['gregorioattr']
local potentialdashvalue = 1
local nopotentialdashvalue = 2
local ictus = 4
local gregoriocenterattr = luatexbase.attributes['gregoriocenterattr']
local startcenter = 1
local endcenter = 2
-- node factory
local tmpnode = node.new(glyph, 0)
tmpnode.font = 0
tmpnode.char = hyphen
local function gethyphennode()
return copy(tmpnode)
end
local function getdashnnode()
local hyphnode = gethyphennode()
local dashnode = hpack(hyphnode)
dashnode.shift = 0
return dashnode,hyphnode
end
local function center_translation(startnode, endnode, ratio, sign, order)
-- total width between beginning the two centering points
local total_width = node.dimensions(ratio, sign, order, startnode, endnode)
-- definition of translation with a beginning is:
-- \hbox to 0pt{
-- \kern 0pt
-- \vbox to 0pt{
-- \vss\hbox to 0pt{
-- translation\hss
-- }
-- }
-- \kern 0pt
-- }
--
-- hence translation width is:
local trans_width = node.dimensions(startnode.head.next.head.next.head)
-- now we must transform the kern 0pt into kern Xpt and kern -Xpt where X is:
local X = (total_width - trans_width) / 2
startnode.head.kern = X
startnode.head.next.next.kern = -X
end
-- in each function we check if we really are inside a score,
-- which we can see with the gregorioattr being set or not
local function process (h, groupcode, glyphes)
-- TODO: to be changed according to the font
local lastseennode = nil
local adddash = false
local currentfont = 0
local currentshift = 0
local centerstartnode = nil
-- we explore the lines
for line in traverse_id(hlist, h) do
if has_attribute(line, gregorioattr) then
-- the next two lines are to remove the dumb lines
if count(hlist, line.head) <= 2 then
h, line = remove(h, line)
else
centerstartnode = nil
for n in traverse_id(hlist, line.head) do
if has_attribute(n, gregoriocenterattr, startcenter) then
centerstartnode = n
elseif has_attribute(n, gregoriocenterattr, endcenter) then
if not centerstartnode then
warn("End of a translation centering area encountered on a\nline without translation centering beginning,\nskipping translation...")
else
center_translation(centerstartnode, n, line.glue_set, line.glue_sign, line.glue_order)
end
elseif has_attribute(n, gregorioattr, potentialdashvalue) then
adddash=true
lastseennode=n
currentfont = 0
-- we traverse the list, to detect the font to use,
-- and also not to add an hyphen if there is already one
for g in node.traverse_id(glyph, n.head) do
if currentfont == 0 then
currentfont = g.font
end
if g.char == hyphen or g.char == 45 then
adddash = false
end
end
if currentshift == 0 then
currentshift = n.shift
end
-- if we encounter a text that doesn't need a dash, we acknowledge it
elseif has_attribute(n, gregorioattr, nopotentialdashvalue) then
adddash=false
end
end
if adddash==true then
local dashnode, hyphnode = getdashnnode()
dashnode.shift = currentshift
hyphnode.font = currentfont
insert_after(line.head, lastseennode, dashnode)
addash=false
end
end
-- we reinitialize the shift value, because it may change according to the line
currentshift=0
end
end
-- due to special cases, we don't return h here (see comments in bug #20974)
return true
end
-- In gregoriotex, hyphenation is made by the process function, so TeX hyphenation
-- is just a waste of time. This function will be registered in the hyphenate
-- callback to skip this step and thus gain a little time.
local function disable_hyphenation()
return false
end
local function atScoreBeggining ()
luatexbase.add_to_callback('post_linebreak_filter', process, 'gregoriotex.callback', 1)
luatexbase.add_to_callback("hyphenate", disable_hyphenation, "gregoriotex.disable_hyphenation", 1)
-- we call the optimize_gabc functions here
if optimize_gabc_style then
optimize_gabc_style.add_callback()
end
end
local function atScoreEnd ()
luatexbase.remove_from_callback('post_linebreak_filter', 'gregoriotex.callback')
luatexbase.remove_from_callback("hyphenate", "gregoriotex.disable_hyphenation")
if optimize_gabc_style then
optimize_gabc_style.remove_callback()
end
end
local function compile_gabc(gabc_file, tex_file)
info("compiling the score %s...", gabc_file)
res = os.execute(string.format("gregorio -o %s %s", tex_file, gabc_file))
if res == nil then
err("\nSomething went wrong when executing\n 'gregorio -o %s %s'.\n"
.."shell-escape mode may not be activated. Try\n '%s --shell-escape %s.tex'\nSee the documentation of gregorio or your TeX\ndistribution to automatize it.", tex_file, gabc_file, tex.formatname, tex.jobname)
elseif res ~= 0 then
err("\nAn error occured when compiling the score file\n'%s' with gregorio.\nPlease check your score file.", gabc_file)
end
end
local function include_gabc_score(gabc_file)
if not lfs.isfile(gabc_file) then
err("the file %s does not exist.", gabc_file)
return
end
local gabc_timestamp = lfs.attributes(gabc_file).modification
local tex_file = gabc_file:gsub("%.gabc+$","-auto.tex")
if lfs.isfile(tex_file) then
local tex_timestamp = lfs.attributes(tex_file).modification
if tex_timestamp < gabc_timestamp then
gregoriotex.compile_gabc(gabc_file, tex_file)
else
log("using the file %s without recompiling, as %s hasn't changed since last compilation.", tex_file, gabc_file)
end
else
compile_gabc(gabc_file, tex_file)
end
tex.print(string.format("\\input %s", tex_file))
end
local function check_version(greinternalversion)
if greinternalversion ~= internalversion then
err("uncoherent file versions: gregoriotex.tex is version %i while gregoriotex.lua is version "..internalversion, greinternalversion)
end
end
gregoriotex.include_gabc_score = include_gabc_score
gregoriotex.compile_gabc = compile_gabc
gregoriotex.atScoreEnd = atScoreEnd
gregoriotex.atScoreBeggining = atScoreBeggining
gregoriotex.check_version = check_version
| gpl-3.0 |
anshkumar/yugioh-glaze | assets/script/c45462639.lua | 3 | 2588 | --闇紅の魔導師
function c45462639.initial_effect(c)
c:EnableCounterPermit(0x3001)
--summon success
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(45462639,0))
e1:SetCategory(CATEGORY_COUNTER)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(c45462639.addct)
e1:SetOperation(c45462639.addc)
c:RegisterEffect(e1)
--add counter
local e0=Effect.CreateEffect(c)
e0:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e0:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e0:SetCode(EVENT_CHAINING)
e0:SetRange(LOCATION_MZONE)
e0:SetOperation(aux.chainreg)
c:RegisterEffect(e0)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e2:SetCode(EVENT_CHAIN_SOLVED)
e2:SetRange(LOCATION_MZONE)
e2:SetOperation(c45462639.acop)
c:RegisterEffect(e2)
--attackup
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetValue(c45462639.attackup)
c:RegisterEffect(e3)
--destroy
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(45462639,1))
e4:SetCategory(CATEGORY_HANDES)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetRange(LOCATION_MZONE)
e4:SetCountLimit(1)
e4:SetCost(c45462639.descost)
e4:SetTarget(c45462639.destarg)
e4:SetOperation(c45462639.desop)
c:RegisterEffect(e4)
end
function c45462639.addct(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_COUNTER,nil,2,0,0x3001)
end
function c45462639.addc(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
e:GetHandler():AddCounter(0x3001,2)
end
end
function c45462639.acop(e,tp,eg,ep,ev,re,r,rp)
if re:IsHasType(EFFECT_TYPE_ACTIVATE) and re:IsActiveType(TYPE_SPELL) and e:GetHandler():GetFlagEffect(1)>0 then
e:GetHandler():AddCounter(0x3001,1)
end
end
function c45462639.attackup(e,c)
return c:GetCounter(0x3001)*300
end
function c45462639.descost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsCanRemoveCounter(tp,0x3001,2,REASON_COST) end
e:GetHandler():RemoveCounter(tp,0x3001,2,REASON_COST)
end
function c45462639.destarg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,0,LOCATION_HAND)>0 end
Duel.SetOperationInfo(0,CATEGORY_HANDES,0,0,1-tp,1)
end
function c45462639.desop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetFieldGroup(tp,0,LOCATION_HAND,nil)
if g:GetCount()==0 then return end
local sg=g:RandomSelect(1-tp,1)
Duel.SendtoGrave(sg,REASON_DISCARD+REASON_EFFECT)
end
| gpl-2.0 |
LuaDist2/dromozoa-ubench | dromozoa/ubench/linest.lua | 1 | 2027 | -- Copyright (C) 2015,2017 Tomoyuki Fujimori <moyu@dromozoa.com>
--
-- This file is part of dromozoa-ubench.
--
-- dromozoa-ubench is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- dromozoa-ubench 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 dromozoa-ubench. If not, see <http://www.gnu.org/licenses/>.
local empty = require "dromozoa.commons.empty"
local function linest1(Y, X)
local sum_x = 0
local sum_y = 0
local sum_xx = 0
local sum_xy = 0
local n = #Y
if X == nil or empty(X) then
for x = 1, n do
local y = Y[x]
sum_x = sum_x + x
sum_y = sum_y + y
sum_xx = sum_xx + x * x
sum_xy = sum_xy + x * y
end
else
for i = 1, n do
local x = X[i]
local y = Y[i]
sum_x = sum_x + x
sum_y = sum_y + y
sum_xx = sum_xx + x * x
sum_xy = sum_xy + x * y
end
end
local d = n * sum_xx - sum_x * sum_x
return (n * sum_xy - sum_x * sum_y) / d, (sum_y * sum_xx - sum_x * sum_xy) / d
end
local function linest1k(Y, X, b)
local sum_x = 0
local sum_xx = 0
local sum_xy = 0
if X == nil or empty(X) then
for x = 1, #Y do
local y = Y[x]
sum_x = sum_x + x
sum_xx = sum_xx + x * x
sum_xy = sum_xy + x * y
end
else
for i = 1, #Y do
local x = X[i]
local y = Y[i]
sum_x = sum_x + x
sum_xx = sum_xx + x * x
sum_xy = sum_xy + x * y
end
end
return (sum_xy - b * sum_x) / sum_xx, b
end
return function (Y, X, b)
if b == nil then
return linest1(Y, X)
else
return linest1k(Y, X, b)
end
end
| gpl-3.0 |
anshkumar/yugioh-glaze | assets/script/c12235475.lua | 3 | 1267 | --魔轟神アシェンヴェイル
function c12235475.initial_effect(c)
--attack up
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(12235475,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_QUICK_O+EFFECT_TYPE_FIELD)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE)
e1:SetCondition(c12235475.con)
e1:SetCost(c12235475.cost)
e1:SetOperation(c12235475.op)
c:RegisterEffect(e1)
end
function c12235475.con(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:GetFlagEffect(12235475)==0 and (Duel.GetAttacker()==c or Duel.GetAttackTarget()==c)
end
function c12235475.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,1,nil)
Duel.SendtoGrave(g,REASON_COST)
e:GetHandler():RegisterFlagEffect(12235475,RESET_PHASE+RESET_DAMAGE_CAL,0,1)
end
function c12235475.op(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_PHASE+RESET_DAMAGE_CAL)
e1:SetValue(600)
c:RegisterEffect(e1)
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c48343627.lua | 3 | 1141 | --グレイブ・スクワーマー
function c48343627.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(48343627,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCondition(c48343627.condition)
e1:SetTarget(c48343627.target)
e1:SetOperation(c48343627.operation)
c:RegisterEffect(e1)
end
function c48343627.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLocation(LOCATION_GRAVE) and e:GetHandler():IsReason(REASON_BATTLE)
end
function c48343627.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsDestructable() end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c48343627.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
cartman300/Polycode | Bindings/Contents/LUA/API/Polycode/EventDispatcher.lua | 11 | 2316 |
class "EventDispatcher"
function EventDispatcher:EventDispatcher()
self.listenerEntries = {}
end
function EventDispatcher:addEventListener(listener, callback, eventCode)
if self.listenerEntries == nil then
self.listenerEntries = {}
end
local newEntry = {}
if self.__ptr ~= nil then
newEntry.handler = Polycore.EventHandler(newEntry)
Polycore.EventDispatcher_addEventListener(self.__ptr, newEntry.handler, eventCode)
end
newEntry.listener = listener
newEntry.callback = callback
newEntry.eventCode = eventCode
self.listenerEntries[#self.listenerEntries+1] = newEntry
end
function EventDispatcher:removeAllHandlers()
if self.listenerEntries == nil then
self.listenerEntries = {}
end
if self.__ptr ~= nil then
Polycore.EventDispatcher_removeAllHandlers(self.__ptr)
end
self.listenerEntries = {}
end
function EventDispatcher:removeAllHandlersForListener(listener)
if self.listenerEntries == nil then
self.listenerEntries = {}
end
local i=1
while i <= #self.listenerEntries do
if self.listenerEntries[i].listener == listener then
if self.__ptr ~= nil and self.listenerEntries[i].handler ~= nil then
Polycore.EventDispatcher_removeAllHandlersForListener(self.__ptr, self.listenerEntries[i].handler)
Polycore.delete_EventHandler(self.listenerEntries[i].handler)
end
table.remove(self.listenerEntries, i)
else
i = i + 1
end
end
end
function EventDispatcher:removeEventListener(listener, eventCode)
if self.listenerEntries == nil then
self.listenerEntries = {}
end
local i=1
while i <= #self.listenerEntries do
if self.listenerEntries[i].listener == listener and self.listenerEntries[i].eventCode == eventCode then
if self.__ptr ~= nil and self.listenerEntries[i].handler ~= nil then
Polycore.EventDispatcher_removeAllHandlersForListener(self.__ptr, self.listenerEntries[i].handler)
Polycore.delete_EventHandler(self.listenerEntries[i].handler)
end
table.remove(self.listenerEntries, i)
else
i = i + 1
end
end
end
function EventDispatcher:dispatchEvent(event, eventCode)
if self.listenerEntries == nil then
self.listenerEntries = {}
end
for i=1,#self.listenerEntries do
if self.listenerEntries[i].eventCode == eventCode then
self.listenerEntries[i].callback(self.listenerEntries[i].listener, event)
end
end
end | mit |
anshkumar/yugioh-glaze | assets/script/c16051717.lua | 3 | 2386 | --A BF-驟雨のライキリ
function c16051717.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1)
c:EnableReviveLimit()
--add type
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(c16051717.tncon)
e1:SetOperation(c16051717.tnop)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_MATERIAL_CHECK)
e2:SetValue(c16051717.valcheck)
e2:SetLabelObject(e1)
c:RegisterEffect(e2)
--destroy
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetCategory(CATEGORY_DESTROY)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1)
e3:SetTarget(c16051717.destg)
e3:SetOperation(c16051717.desop)
c:RegisterEffect(e3)
end
function c16051717.valcheck(e,c)
local g=c:GetMaterial()
if g:IsExists(Card.IsSetCard,1,nil,0x33) then
e:GetLabelObject():SetLabel(1)
else
e:GetLabelObject():SetLabel(0)
end
end
function c16051717.tncon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SYNCHRO and e:GetLabel()==1
end
function c16051717.tnop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EFFECT_ADD_TYPE)
e1:SetValue(TYPE_TUNER)
e1:SetReset(RESET_EVENT+0x1fe0000)
c:RegisterEffect(e1)
end
function c16051717.filter(c)
return c:IsFaceup() and c:IsSetCard(0x33)
end
function c16051717.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) and chkc:IsDestructable() end
if chk==0 then return Duel.IsExistingMatchingCard(c16051717.filter,tp,LOCATION_MZONE,0,1,e:GetHandler())
and Duel.IsExistingTarget(Card.IsDestructable,tp,0,LOCATION_ONFIELD,1,nil) end
local ct=Duel.GetMatchingGroupCount(c16051717.filter,tp,LOCATION_MZONE,0,e:GetHandler())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,Card.IsDestructable,tp,0,LOCATION_ONFIELD,1,ct,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c16051717.desop(e,tp,eg,ep,ev,re,r,rp)
local tg=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local g=tg:Filter(Card.IsRelateToEffect,nil,e)
if g:GetCount()>0 then
Duel.Destroy(g,REASON_EFFECT)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c59281922.lua | 3 | 3158 | --サイバー・ドラゴン・ドライ
function c59281922.initial_effect(c)
--lv
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(59281922,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetCost(c59281922.lvcost)
e1:SetTarget(c59281922.lvtg)
e1:SetOperation(c59281922.lvop)
c:RegisterEffect(e1)
--indes
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(59281922,1))
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_REMOVE)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e2:SetTarget(c59281922.target)
e2:SetOperation(c59281922.operation)
c:RegisterEffect(e2)
--code
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetCode(EFFECT_CHANGE_CODE)
e3:SetRange(LOCATION_MZONE+LOCATION_GRAVE)
e3:SetValue(70095154)
c:RegisterEffect(e3)
Duel.AddCustomActivityCounter(59281922,ACTIVITY_SPSUMMON,c59281922.counterfilter)
end
function c59281922.counterfilter(c)
return c:IsRace(RACE_MACHINE)
end
function c59281922.lvcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetCustomActivityCount(59281922,tp,ACTIVITY_SPSUMMON)==0 end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetTargetRange(1,0)
e1:SetTarget(c59281922.splimit)
Duel.RegisterEffect(e1,tp)
end
function c59281922.splimit(e,c,sump,sumtype,sumpos,targetp,se)
return c:GetRace()~=RACE_MACHINE
end
function c59281922.filter(c)
return c:IsFaceup() and c:IsCode(70095154)
end
function c59281922.lvtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c59281922.filter,tp,LOCATION_MZONE,0,1,nil) end
end
function c59281922.lvop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c59281922.filter,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(5)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
end
function c59281922.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and c59281922.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c59281922.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c59281922.filter,tp,LOCATION_MZONE,0,1,1,nil)
end
function c59281922.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END)
tc:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
tc:RegisterEffect(e2)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c35803249.lua | 3 | 3268 | --人造人間-サイコ・ロード
function c35803249.initial_effect(c)
c:EnableReviveLimit()
--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)
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(c35803249.spcon)
e2:SetOperation(c35803249.spop)
c:RegisterEffect(e2)
--cannot trigger
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_CANNOT_TRIGGER)
e3:SetProperty(EFFECT_FLAG_SET_AVAILABLE)
e3:SetRange(LOCATION_MZONE)
e3:SetTargetRange(0xa,0xa)
e3:SetTarget(c35803249.distg)
c:RegisterEffect(e3)
--disable
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetCode(EFFECT_DISABLE)
e4:SetRange(LOCATION_MZONE)
e4:SetTargetRange(LOCATION_SZONE,LOCATION_SZONE)
e4:SetTarget(c35803249.distg)
c:RegisterEffect(e4)
--disable effect
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e5:SetCode(EVENT_CHAIN_SOLVING)
e5:SetRange(LOCATION_MZONE)
e5:SetOperation(c35803249.disop)
c:RegisterEffect(e5)
--disable trap monster
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_FIELD)
e6:SetCode(EFFECT_DISABLE_TRAPMONSTER)
e6:SetRange(LOCATION_MZONE)
e6:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e6:SetTarget(c35803249.distg)
c:RegisterEffect(e6)
--destroy
local e7=Effect.CreateEffect(c)
e7:SetDescription(aux.Stringid(35803249,0))
e7:SetCategory(CATEGORY_DESTROY+CATEGORY_DAMAGE)
e7:SetType(EFFECT_TYPE_IGNITION)
e7:SetRange(LOCATION_MZONE)
e7:SetCountLimit(1)
e7:SetTarget(c35803249.destg)
e7:SetOperation(c35803249.desop)
c:RegisterEffect(e7)
end
function c35803249.distg(e,c)
return c:IsType(TYPE_TRAP)
end
function c35803249.disop(e,tp,eg,ep,ev,re,r,rp)
local tl=Duel.GetChainInfo(ev,CHAININFO_TRIGGERING_LOCATION)
if tl==LOCATION_SZONE and re:IsActiveType(TYPE_TRAP) then
Duel.NegateEffect(ev)
end
end
function c35803249.spfilter(c)
return c:IsFaceup() and c:IsCode(77585513)
end
function c35803249.spcon(e,c)
if c==nil then return true end
return Duel.CheckReleaseGroup(c:GetControler(),c35803249.spfilter,1,nil)
end
function c35803249.spop(e,tp,eg,ep,ev,re,r,rp,c)
local g=Duel.SelectReleaseGroup(tp,c35803249.spfilter,1,1,nil)
Duel.Release(g,REASON_COST)
end
function c35803249.filter(c)
return c:IsFaceup() and c:IsType(TYPE_TRAP) and c:IsDestructable()
end
function c35803249.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c35803249.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end
local sg=Duel.GetMatchingGroup(c35803249.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,sg,sg:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,sg:GetCount()*300)
end
function c35803249.desop(e,tp,eg,ep,ev,re,r,rp)
local sg=Duel.GetMatchingGroup(c35803249.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,nil)
local ct=Duel.Destroy(sg,REASON_EFFECT)
Duel.Damage(1-tp,ct*300,REASON_EFFECT)
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c88095331.lua | 7 | 1393 | --エヴォルド・ナハシュ
function c88095331.initial_effect(c)
--search
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(88095331,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_SINGLE)
e1:SetCode(EVENT_RELEASE)
e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCondition(c88095331.condition)
e1:SetTarget(c88095331.target)
e1:SetOperation(c88095331.operation)
c:RegisterEffect(e1)
end
function c88095331.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c88095331.filter(c,e,tp)
return c:IsSetCard(0x604e) and c:IsCanBeSpecialSummoned(e,155,tp,false,false)
end
function c88095331.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c88095331.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c88095331.operation(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,c88095331.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,155,tp,tp,false,false,POS_FACEUP)
local rf=g:GetFirst().evolreg
if rf then rf(g:GetFirst()) end
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c40732515.lua | 3 | 3294 | --神聖魔導王エンディミオン
function c40732515.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND+LOCATION_GRAVE)
e1:SetCondition(c40732515.spcon)
e1:SetOperation(c40732515.spop)
e1:SetValue(1)
c:RegisterEffect(e1)
--to hand
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(40732515,0))
e2:SetCategory(CATEGORY_TOHAND)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetCondition(c40732515.condition)
e2:SetTarget(c40732515.target)
e2:SetOperation(c40732515.operation)
c:RegisterEffect(e2)
--destroy
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(40732515,1))
e3:SetCategory(CATEGORY_DESTROY)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetCost(c40732515.descost)
e3:SetTarget(c40732515.destg)
e3:SetOperation(c40732515.desop)
c:RegisterEffect(e3)
end
function c40732515.spcon(e,c)
if c==nil then return true end
local fd=Duel.GetFieldCard(c:GetControler(),LOCATION_SZONE,5)
return fd and fd:IsCode(39910367) and fd:IsCanRemoveCounter(c:GetControler(),0x3001,6,REASON_COST)
and Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
end
function c40732515.spop(e,tp,eg,ep,ev,re,r,rp,c)
local fd=Duel.GetFieldCard(tp,LOCATION_SZONE,5)
fd:RemoveCounter(tp,0x3001,6,REASON_RULE)
end
function c40732515.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SPECIAL+1
end
function c40732515.filter(c)
return c:IsType(TYPE_SPELL) and c:IsAbleToHand()
end
function c40732515.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c40732515.filter(chkc) end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c40732515.filter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,g:GetCount(),0,0)
end
function c40732515.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
Duel.ShuffleHand(tp)
end
end
function c40732515.cfilter(c)
return c:IsType(TYPE_SPELL) and c:IsDiscardable()
end
function c40732515.descost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c40732515.cfilter,tp,LOCATION_HAND,0,1,e:GetHandler()) end
Duel.DiscardHand(tp,c40732515.cfilter,1,1,REASON_COST+REASON_DISCARD)
end
function c40732515.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsDestructable() end
if chk==0 then return Duel.IsExistingTarget(Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,Card.IsDestructable,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c40732515.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
dafei2015/hugula | Client/Assets/Lua/game/brain/Doc.lua | 7 | 3418 | --===================================决策节点====================================================
-------------------------------------条件节点-----------------------------
ConditionNode(luafunction) ConditionNode(Condition)
--条件等待节点
ConditionWaitNode(luafunction) ConditionWaitNode(Condition)
--按一定时间执行的条件节点
DeltaConditionNode(float delta, Condition condition) DeltaConditionNode(float delta, Condition condition)
-------------------------------------行动节点-------------------------------------
ActionNode((System.Action<BTInput, BTOutput> action) --返回true
ActionNotNode((System.Action<BTInput, BTOutput> action) --返回false
--间隔时间执行的行动节点
DeltaActionNode(float delta,System.Action<BTInput, BTOutput> action)
-- 事件行动节点
ActionEventNode(System.Action<BTInput,BTOutput> action)
-------------------------------------等待节点-------------------------------------
WaitNode(float duration, float variation)--(等待指定时间后返回成功)
-------------------------------------装饰节点-------------------------------------
DecoratorNotNode() -- 反转结果
-------------------------------------选择节点------------------------------------- [从begin到end依次执行子节点]
SelectorNode() --(遇到true返回True)
-------------------------------------顺序节点------------------------------------- [从begin到end依次执行子节点]
SequenceNode() --(遇到false返回false)
SequenceTrueNode() --(遇到false返回true,否则循环完成后返回true)
-------------------------------------并行节点------------------------------------- [同时执行所有子节点]
ParallelNode() --平行执行它的所有Child Node,遇到False则返回False,全True才返回True。
ParallelNodeAny() --平行执行它的所有Child Node,遇到False则返回False,有True返回True
ParallelSelectorNode() --遇到True则返回True,全False才返回False
ParallelFallOnAllNode() --所有False才返回False,否则返回True
-------------------------------------事件节点-------------------------------------
EventNode(int eventType) --事件触发的时候执行,只能有一个子节点
TriggerNode(int eventType) --触发事件节点,运行到当前节点时候会触发eventType事件 返回成功
-------------------------------------循环节点-------------------------------------
LoopNode(int count) --The Loop node allows to execute one child a multiple number of times n (if n is not specified then it's considered to be infinite) or until the child FAILS its execution
LoopUntilSuccessNode() --The LoopUntilSuccess node allows to execute one child until it SUCCEEDS. A maximum number of attempts can be specified. If no maximum number of attempts is specified or if it's set to <= 0, then this node will try to run its child over and over again until the child succeeds.
-------------------------------------压制失败-------------------------------------
SuppressFailure() --只能有一个子节点,总是返回true
--===================================输入域输出===================================--
input.target RoleActor --输入目标角色
input.position Vector3 --输入目标位置
input.skill int --输入技能
input.stopDistance --移动停止距离
input.isDragging --是否拖动状态
output.leafNode --当前叶节点
output.eventData --传输数据
| mit |
RockySeven3161/UB | bot/utils.lua | 356 | 14963 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has superuser privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has admins privileges
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has moderator privileges
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
-- Berfungsi utk mengecek user jika plugin moderated = true
if plugin.moderated and not is_momod(msg) then --Cek apakah user adalah momod
if plugin.moderated and not is_admin(msg) then -- Cek apakah user adalah admin
if plugin.moderated and not is_sudo(msg) then -- Cek apakah user adalah sudoers
return false
end
end
end
-- Berfungsi mengecek user jika plugin privileged = true
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end | gpl-2.0 |
beko123/DEV_VIP | plugins/filterfa.lua | 1 | 2525 | local function addword(msg, name)
local hash = 'chat:'..msg.to.id..':badword'
redis:hset(hash, name, 'newword')
return "تمت إضافة كلمة جديدة إلى كلمات المرشحه\n>"..name
end
local function get_variables_hash(msg)
return 'chat:'..msg.to.id..':badword'
end
local function list_variablesbad(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'قائمة الكلمات السيئة :\n\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
else
return
end
end
function clear_commandbad(msg, var_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:del(hash, var_name)
return 'پاک شدند'
end
local function list_variables2(msg, value)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(value, names[i]) and not is_momod(msg) then
if msg.to.type == 'channel' then
delete_msg(msg.id,ok_cb,false)
else
kick_user(msg.from.id, msg.to.id)
end
return
end
--text = text..names[i]..'\n'
end
end
end
local function get_valuebad(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
function clear_commandsbad(msg, cmd_name)
--Save on redis
local hash = get_variables_hash(msg)
redis:hdel(hash, cmd_name)
return ''..cmd_name..' مسح'
end
local function run(msg, matches)
if matches[2] == 'فلتر' then
if not is_momod(msg) then
return 'only for moderators'
end
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[2] == 'filterlist' then
return list_variablesbad(msg)
elseif matches[2] == 'حذف' then
if not is_momod(msg) then return '_|_' end
local asd = '1'
return clear_commandbad(msg, asd)
elseif matches[2] == 'الفلتره' or matches[2] == 'الفلتره' then
if not is_momod(msg) then return '_|_' end
return clear_commandsbad(msg, matches[3])
else
local name = user_print_name(msg.from)
return list_variables2(msg, matches[1])
end
end
return {
patterns = {
"^([!/#])(فتلر) (.*)$",
"^([!/#])(فتلر) (.*)$",
"^([!/#])(الفتلر) (.*)$",
"^([!/#])(القائمة)$",
"^([!/#])(حذف) القائمة$",
"^(.+)$",
},
run = run
}
| agpl-3.0 |
freifunk-gluon/luci | modules/niu/luasrc/controller/niu/system.lua | 33 | 6889 | --[[
LuCI - Lua Development Framework
Copyright 2009 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local require, pairs, unpack, tonumber = require, pairs, unpack, tonumber
module "luci.controller.niu.system"
function index()
local toniu = {on_success_to={"niu"}}
local e = entry({"niu", "system"}, alias("niu"), "System", 40)
e.niu_dbtemplate = "niu/system"
e.niu_dbtasks = true
e.niu_dbicon = "icons32/preferences-system.png"
entry({"niu", "system", "general"},
cbi("niu/system/general", toniu), "Configure Device", 1)
entry({"niu", "system", "backup"}, call("backup"), "Backup or Restore Settings", 2)
entry({"niu", "system", "upgrade"}, call("upgrade"), "Upgrade Firmware", 30)
end
function backup()
local dsp = require "luci.dispatcher"
local os, io = require "os", require "io"
local uci = require "luci.model.uci".inst
local nixio, nutl = require "nixio", require "nixio.util"
local fs = require "nixio.fs"
local http = require "luci.http"
local tpl = require "luci.template"
local restore_fpi
http.setfilehandler(
function(meta, chunk, eof)
if not restore_fpi then
restore_fpi = io.popen("tar -xzC/ >/dev/null 2>&1", "w")
end
if chunk then
restore_fpi:write(chunk)
end
if eof then
restore_fpi:close()
end
end
)
local reset_avail = (fs.readfile("/proc/mtd") or ""):find('"rootfs_data"')
local upload = http.formvalue("archive")
local backup = http.formvalue("backup")
local reset = reset_avail and http.formvalue("reset")
local backup_cmd = "tar -cz %s 2>/dev/null"
if http.formvalue("cancel") then
return http.redirect(dsp.build_url("niu"))
end
if backup then
local call = {"/bin/tar", "-cz"}
for k, v in pairs(uci:get_all("luci", "flash_keep")) do
if k:byte() ~= 46 then -- k[1] ~= "."
nutl.consume(fs.glob(v), call)
end
end
http.header(
'Content-Disposition', 'attachment; filename="backup-%s-%s.tar.gz"' % {
nixio.uname().nodename, os.date("%Y-%m-%d")
}
)
http.prepare_content("application/x-targz")
local fdin, fdout = nixio.pipe()
local devnull = nixio.open("/dev/null", "r+")
local proc = nixio.fork()
if proc == 0 then
fdin:close()
nixio.dup(devnull, nixio.stdin)
nixio.dup(devnull, nixio.stderr)
nixio.dup(fdout, nixio.stdout)
nixio.exec(unpack(call))
os.exit(1)
end
fdout:close()
http.splice(fdin)
http.close()
elseif (upload and #upload > 0) or reset then
tpl.render("niu/system/reboot")
if nixio.fork() == 0 then
nixio.nanosleep(1)
if reset then
nixio.execp("mtd", "-r", "erase", "rootfs_data")
else
nixio.execp("reboot")
end
os.exit(1)
end
else
tpl.render("niu/system/backup", {reset_avail = reset_avail})
end
end
function upgrade()
local io, os, table = require "io", require "os", require "table"
local uci = require "luci.store".uci_state
local http = require "luci.http"
local util = require "luci.util"
local tpl = require "luci.template"
local nixio = require "nixio", require "nixio.util", require "nixio.fs"
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 (util.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
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(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 = 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
http.prepare_content("text/plain")
local call = {}
for k, v in pairs(uci:get_all("luci", "flash_keep")) do
if k:byte() ~= 46 then -- k[1] ~= "."
nixio.util.consume(nixio.fs.glob(v), call)
end
end
-- Now invoke sysupgrade
local keepcfg = keep_avail and http.formvalue("keepcfg") == "1"
local fd = io.popen("/sbin/luci-flash %s %q" %{
keepcfg and "-k %q" % table.concat(call, " ") or "", tmpfile
})
if fd then
while true do
local ln = fd:read("*l")
if not ln then break end
http.write(ln .. "\n")
end
fd:close()
end
-- Make sure the device is rebooted
if nixio.fork() == 0 then
nixio.nanosleep(1)
nixio.execp("reboot")
os.exit(1)
end
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
tpl.render("niu/system/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
tpl.render("niu/system/upgrade", {
step=2,
checksum=image_checksum(),
filesize=nixio.fs.stat(tmpfile).size,
flashsize=storage_size(),
keepconfig=(keep_avail and http.formvalue("keepcfg") == "1")
} )
-- Step 3: load iframe which calls the actual flash procedure
elseif step == 3 then
tpl.render("niu/system/upgrade", {
step=3,
keepconfig=(keep_avail and http.formvalue("keepcfg") == "1")
} )
end
end
| apache-2.0 |
P403n1x87/New-Life | lua/mem.lua | 1 | 7553 | --[[
This file is part of "New Life" which is released under GPL.
See file LICENCE or go to http://www.gnu.org/licenses/ for full license details.
New Life is a series of custom scripts for Conky, a system monitor, based on
torsmo.
Copyright (c) 2016 Gabriele N. Tornetta <phoenix1987@gmail.com>. All rights
reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
]]
require 'cairo'
require 'lua.common'
--------------------------------------------------------------------------------
-- CONFIGURATION Section -------------------------------------------------------
--------------------------------------------------------------------------------
--[[
Table of memory type and label pairs. Adjoust accordingly.
]]
mem = {
{"mem", "RAM"},
{"swap", "SWAP"}
}
--------------------------------------------------------------------------------
-- END of CONFIGURATION Section ------------------------------------------------
--------------------------------------------------------------------------------
--[[ Internal code
Do not change unless you know what you're doing ]]
-- Geometry
cx, cy = 180, 80
offset_angle = 1/10
r = 54 -- Main ring radius. This controls the overall size
t = 8 -- Main ring thickness
--------------------------------------------------------------------------------
-- Draw helpers ----------------------------------------------------------------
--------------------------------------------------------------------------------
function draw_dial(cr)
local R = r - t / 2
cairo_select_font_face(cr, "DJB Get Digital", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL)
cairo_set_font_size(cr, 18)
cairo_set_source_rgba(cr, 1, 1, 1, 1)
write_center_middle(cr, cx, cy - 16, "R:" .. conky_parse("$memmax}"))
write_center_middle(cr, cx, cy + 16, "S:" .. conky_parse("$swapmax}"))
pat = cairo_pattern_create_radial (cx - 20, cy - 20, 25.6,
102.4, 102.4, 128.0);
cairo_pattern_add_color_stop_rgba (pat, 0, 1, 1, 1, .2);
cairo_pattern_add_color_stop_rgba (pat, 1, 0, 0, 0, .2);
cairo_set_source (cr, pat);
cairo_arc (cr, cx, cy, R, 0, 2 * math.pi);
cairo_fill (cr);
cairo_pattern_destroy (pat);
end
--------------------------------------------------------------------------------
function draw_memory(cr)
local R = r + 14 -- Indicator arc radius
local l = 32 -- Radial line length
local L = 80 -- Horizontal line length
for entry = 1, #mem do
perc = conky_parse("${" .. mem[entry][1] .. "perc}")
cairo_set_source_rgba(cr, 1, 1, 1, 1)
-- File system ring
local angle = (entry - 1) / #mem + offset_angle
if tonumber(perc) > 95 then
cairo_set_source_rgba(cr, 1, 0.1, 0.1, 1)
elseif tonumber(perc) > 85 then
cairo_set_source_rgba(cr, 0.85, 0.4, 0.05, 1)
end
cairo_save(cr)
rotate(cr, angle)
cairo_set_source_rgba(cr, 1, 1, 1, 0.2)
draw_arc(cr, cx, cy, R, 4, -1 / #mem * 100 / 106, 0) -- 106 creates gap
cairo_set_source_rgba(cr, 1, 1, 1, 1)
draw_arc(cr, cx, cy, R, 4, -perc / #mem / 106, 0)
cairo_set_line_width(cr, 1.5)
draw_segment(cr, cx + r, cy, cx + r + l, cy)
cairo_restore(cr)
-- Horizontal line
if tonumber(perc) > 95 then
cairo_set_source_rgba(cr, 1, 0.1, 0.1, 1)
elseif tonumber(perc) > 85 then
cairo_set_source_rgba(cr, 0.85, 0.4, 0.05, 1)
end
cairo_set_line_width(cr, 1.5)
if math.cos(2 * math.pi * angle) < 0 then d = -1 else d = 1 end
local J = r + l
draw_segment(cr, cx + J * math.cos(-2 * math.pi * angle),
cy + J * math.sin(-2 * math.pi * angle),
cx + J * math.cos(-2 * math.pi * angle) + d * L,
cy + J * math.sin(-2 * math.pi * angle))
-- Memory label
cairo_select_font_face(cr, "Neuropol", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_BOLD)
cairo_set_source_rgba(cr, 1, 1, 1, 1)
if math.cos(2 * math.pi * angle) > 0 then -- Select RIGHT
if math.sin(2 * math.pi * angle) < 0 then -- Select BOTTOM
writer = write_bottom_right
writer_perc = write_top_right
writer_free = write_top_left
else -- Select TOP
writer = write_top_right
writer_perc = write_bottom_right
writer_free = write_bottom_left
end
else -- Select LEFT
if math.sin(2 * math.pi * angle) < 0 then -- Select BOTTOM
writer = write_bottom_left
writer_perc = write_top_left
writer_free = write_top_right
else -- Select TOP
writer = write_top_left
writer_perc = write_bottom_left
writer_free = write_bottom_right
end
end
if math.cos(2 * math.pi * angle) < 0 then d = -1 else d = 1 end
if math.sin(2 * math.pi * angle) < 0 then s = 4 else s = -4 end
cairo_set_font_size(cr, 10)
writer(cr, cx + J * math.cos(-2 * math.pi * angle) + d * L,
cy + J * math.sin(-2 * math.pi * angle) + s,
mem[entry][2])
-- Write the rest of the details
cairo_select_font_face(cr, "Neuropol", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL)
cairo_set_font_size(cr, 8)
if math.cos(2 * math.pi * angle) < 0 then d = -1 else d = 1 end
writer_perc(cr, cx + J * math.cos(-2 * math.pi * angle) + d * L,
cy + J * math.sin(-2 * math.pi * angle) - s,
perc .. "%")
writer_free(cr, cx + J * math.cos(-2 * math.pi * angle),
cy + J * math.sin(-2 * math.pi * angle) - s,
conky_parse("${" .. mem[entry][1] .. "free}"))
end
-- Main ring shadow
cairo_set_source_rgba(cr, 0.4, 0.4, 0.4, .1)
draw_arc(cr, cx, cy, r, 2 * t, 0, 1)
-- Main ring
cairo_set_source_rgba(cr, 1, 1, 1, 1)
draw_arc(cr, cx, cy, r, t, 0, 1)
end
--------------------------------------------------------------------------------
--[[
Main function down here
]]
function conky_draw_pre()
--Check that Conky has been running for at least 5s
if conky_window == nil then
return
end
local cs = cairo_xlib_surface_create(conky_window.display,
conky_window.drawable,
conky_window.visual,
conky_window.width,
conky_window.height)
local cr = cairo_create(cs)
-- The actual script goes here
draw_dial(cr)
draw_memory(cr)
-- Memory clean-up
cairo_destroy(cr)
cairo_surface_destroy(cs)
cr = nil
end
| gpl-3.0 |
anshkumar/yugioh-glaze | assets/script/c37195861.lua | 6 | 1316 | --E・HERO オーシャン
function c37195861.initial_effect(c)
--to hand
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(37195861,0))
e1:SetCategory(CATEGORY_TOHAND)
e1:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetCountLimit(1)
e1:SetCondition(c37195861.con)
e1:SetTarget(c37195861.tg)
e1:SetOperation(c37195861.op)
c:RegisterEffect(e1)
end
function c37195861.con(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c37195861.filter(c)
return c:IsSetCard(0x8) and c:IsAbleToHand() and (c:IsLocation(LOCATION_GRAVE) or c:IsFaceup())
end
function c37195861.tg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(0x14) and chkc:IsControler(tp) and c37195861.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c37195861.filter,tp,LOCATION_MZONE+LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g=Duel.SelectTarget(tp,c37195861.filter,tp,LOCATION_MZONE+LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,1,0,0)
end
function c37195861.op(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c53610653.lua | 5 | 2776 | --バウンド・ワンド
function c53610653.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:SetTarget(c53610653.target)
e1:SetOperation(c53610653.operation)
c:RegisterEffect(e1)
--Atk up
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(c53610653.atkval)
c:RegisterEffect(e2)
--Equip limit
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_EQUIP_LIMIT)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetValue(c53610653.eqlimit)
c:RegisterEffect(e3)
--spsummon
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(53610653,0))
e4:SetCategory(CATEGORY_SPECIAL_SUMMON)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetCondition(c53610653.spcon)
e4:SetTarget(c53610653.sptg)
e4:SetOperation(c53610653.spop)
c:RegisterEffect(e4)
end
function c53610653.eqlimit(e,c)
return c:IsRace(RACE_SPELLCASTER) and not c:IsType(TYPE_XYZ)
end
function c53610653.filter(c)
return c:IsFaceup() and c:IsRace(RACE_SPELLCASTER) and not c:IsType(TYPE_XYZ)
end
function c53610653.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c53610653.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c53610653.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c53610653.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c53610653.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if e:GetHandler():IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,e:GetHandler(),tc)
end
end
function c53610653.atkval(e,c)
return c:GetLevel()*100
end
function c53610653.spcon(e,tp,eg,ep,ev,re,r,rp)
local ec=e:GetHandler():GetPreviousEquipTarget()
return e:GetHandler():IsReason(REASON_LOST_TARGET) and ec and ec:IsReason(REASON_DESTROY)
and ec:IsLocation(LOCATION_GRAVE) and ec:GetReasonPlayer()==1-tp
end
function c53610653.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local ec=e:GetHandler():GetPreviousEquipTarget()
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and ec:IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetTargetCard(ec)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,ec,1,0,0)
end
function c53610653.spop(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 |
anshkumar/yugioh-glaze | assets/script/c51865604.lua | 3 | 2922 | --ZS-幻影賢者
function c51865604.initial_effect(c)
--draw
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(51865604,0))
e1:SetCategory(CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1,51865604)
e1:SetCondition(c51865604.condition)
e1:SetTarget(c51865604.target)
e1:SetOperation(c51865604.operation)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(51865604,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetRange(LOCATION_MZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_REMOVE)
e2:SetCountLimit(1,51865604)
e2:SetCondition(c51865604.spcon)
e2:SetCost(c51865604.spcost)
e2:SetTarget(c51865604.sptg)
e2:SetOperation(c51865604.spop)
c:RegisterEffect(e2)
end
function c51865604.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x7f)
end
function c51865604.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c51865604.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c51865604.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 c51865604.operation(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)
end
function c51865604.spfilter(c,e,tp)
return c:IsFaceup() and c:IsPreviousLocation(LOCATION_MZONE) and c:GetPreviousControler()==tp
and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and c:IsCanBeEffectTarget(e)
end
function c51865604.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()==PHASE_BATTLE and eg:IsExists(c51865604.spfilter,1,nil,e,tp)
end
function c51865604.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
function c51865604.rmfilter(c)
return c:IsAttackBelow(3000) and c:IsAbleToRemove()
end
function c51865604.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return eg:IsContains(chkc) and c51865604.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c51865604.rmfilter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=eg:FilterSelect(tp,c51865604.spfilter,1,1,nil,e,tp)
Duel.SetTargetCard(g)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c51865604.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)~=0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c51865604.rmfilter,tp,0,LOCATION_MZONE,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_EFFECT)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c84814897.lua | 3 | 4316 | --騎竜
function c84814897.initial_effect(c)
--equip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(84814897,0))
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetTarget(c84814897.eqtg)
e1:SetOperation(c84814897.eqop)
c:RegisterEffect(e1)
--unequip
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(84814897,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_SZONE)
e2:SetCondition(c84814897.uncon)
e2:SetTarget(c84814897.sptg)
e2:SetOperation(c84814897.spop)
c:RegisterEffect(e2)
--Atk up
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_EQUIP)
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetValue(900)
e3:SetCondition(c84814897.uncon)
c:RegisterEffect(e3)
--Def up
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_EQUIP)
e4:SetCode(EFFECT_UPDATE_DEFENCE)
e4:SetValue(900)
e4:SetCondition(c84814897.uncon)
c:RegisterEffect(e4)
--direct_attack
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(84814897,2))
e5:SetType(EFFECT_TYPE_IGNITION)
e5:SetRange(LOCATION_SZONE)
e5:SetCondition(c84814897.uncon)
e5:SetCost(c84814897.atkcost)
e5:SetOperation(c84814897.atkop)
c:RegisterEffect(e5)
--destroy sub
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_EQUIP)
e6:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e6:SetCode(EFFECT_DESTROY_SUBSTITUTE)
e6:SetCondition(c84814897.uncon)
e6:SetValue(c84814897.repval)
c:RegisterEffect(e6)
--eqlimit
local e7=Effect.CreateEffect(c)
e7:SetType(EFFECT_TYPE_SINGLE)
e7:SetCode(EFFECT_EQUIP_LIMIT)
e7:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e7:SetValue(c84814897.eqlimit)
c:RegisterEffect(e7)
end
function c84814897.uncon(e)
return e:GetHandler():IsStatus(STATUS_UNION)
end
function c84814897.repval(e,re,r,rp)
return bit.band(r,REASON_BATTLE)~=0
end
function c84814897.eqlimit(e,c)
return c:IsCode(11321183)
end
function c84814897.filter(c)
return c:IsFaceup() and c:IsCode(11321183) and c:GetUnionCount()==0
end
function c84814897.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c84814897.filter(chkc) end
if chk==0 then return e:GetHandler():GetFlagEffect(84814897)==0 and Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingTarget(c84814897.filter,tp,LOCATION_MZONE,0,1,e:GetHandler()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
local g=Duel.SelectTarget(tp,c84814897.filter,tp,LOCATION_MZONE,0,1,1,e:GetHandler())
Duel.SetOperationInfo(0,CATEGORY_EQUIP,g,1,0,0)
e:GetHandler():RegisterFlagEffect(84814897,RESET_EVENT+0x7e0000+RESET_PHASE+PHASE_END,0,1)
end
function c84814897.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 c84814897.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 c84814897.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():GetFlagEffect(84814897)==0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,true,false) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
e:GetHandler():RegisterFlagEffect(84814897,RESET_EVENT+0x7e0000+RESET_PHASE+PHASE_END,0,1)
end
function c84814897.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
function c84814897.atkcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.SetTargetCard(e:GetHandler():GetEquipTarget())
Duel.Release(e:GetHandler(),REASON_COST)
end
function c84814897.atkop(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_DIRECT_ATTACK)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
freifunk-gluon/luci | protocols/core/luasrc/model/cbi/admin_network/proto_static.lua | 10 | 2663 | --[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local ifc = net:get_interface()
local ipaddr, netmask, gateway, broadcast, dns, accept_ra, send_rs, ip6addr, ip6gw
local mtu, metric
ipaddr = section:taboption("general", Value, "ipaddr", translate("IPv4 address"))
ipaddr.datatype = "ip4addr"
netmask = section:taboption("general", Value, "netmask",
translate("IPv4 netmask"))
netmask.datatype = "ip4addr"
netmask:value("255.255.255.0")
netmask:value("255.255.0.0")
netmask:value("255.0.0.0")
gateway = section:taboption("general", Value, "gateway", translate("IPv4 gateway"))
gateway.datatype = "ip4addr"
broadcast = section:taboption("general", Value, "broadcast", translate("IPv4 broadcast"))
broadcast.datatype = "ip4addr"
dns = section:taboption("general", DynamicList, "dns",
translate("Use custom DNS servers"))
dns.datatype = "ipaddr"
dns.cast = "string"
if luci.model.network:has_ipv6() then
local ip6assign = section:taboption("general", Value, "ip6assign", translate("IPv6 assignment length"),
translate("Assign a part of given length of every public IPv6-prefix to this interface"))
ip6assign:value("", translate("disabled"))
ip6assign:value("64")
ip6assign.datatype = "max(64)"
local ip6hint = section:taboption("general", Value, "ip6hint", translate("IPv6 assignment hint"),
translate("Assign prefix parts using this hexadecimal subprefix ID for this interface."))
for i=33,64 do ip6hint:depends("ip6assign", i) end
ip6addr = section:taboption("general", Value, "ip6addr", translate("IPv6 address"))
ip6addr.datatype = "ip6addr"
ip6addr:depends("ip6assign", "")
ip6gw = section:taboption("general", Value, "ip6gw", translate("IPv6 gateway"))
ip6gw.datatype = "ip6addr"
ip6gw:depends("ip6assign", "")
local ip6prefix = s:taboption("general", Value, "ip6prefix", translate("IPv6 routed prefix"),
translate("Public prefix routed to this device for distribution to clients."))
ip6prefix.datatype = "ip6addr"
ip6prefix:depends("ip6assign", "")
end
luci.tools.proto.opt_macaddr(section, ifc, translate("Override MAC address"))
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(1500)"
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
| apache-2.0 |
wvierber/hammerspoon | extensions/layout/init.lua | 7 | 10183 | --- === hs.layout ===
---
--- Window layout manager
---
--- This extension allows you to trigger window placement/sizing to a number of windows at once
local layout = {}
local geometry = require("hs.geometry")
local fnutils = require("hs.fnutils")
local screen = require("hs.screen")
local window = require("hs.window")
local application = require("hs.application")
--- hs.layout.left25
--- Constant
--- A unit rect which will make a window occupy the left 25% of a screen
layout.left25 = geometry.rect(0, 0, 0.25, 1)
--- hs.layout.left30
--- Constant
--- A unit rect which will make a window occupy the left 30% of a screen
layout.left30 = geometry.rect(0, 0, 0.3, 1)
--- hs.layout.left50
--- Constant
--- A unit rect which will make a window occupy the left 50% of a screen
layout.left50 = geometry.rect(0, 0, 0.5, 1)
--- hs.layout.left70
--- Constant
--- A unit rect which will make a window occupy the left 70% of a screen
layout.left70 = geometry.rect(0, 0, 0.7, 1)
--- hs.layout.left75
--- Constant
--- A unit rect which will make a window occupy the left 75% of a screen
layout.left75 = geometry.rect(0, 0, 0.75, 1)
--- hs.layout.right25
--- Constant
--- A unit rect which will make a window occupy the right 25% of a screen
layout.right25 = geometry.rect(0.75, 0, 0.25, 1)
--- hs.layout.right30
--- Constant
--- A unit rect which will make a window occupy the right 30% of a screen
layout.right30 = geometry.rect(0.7, 0, 0.3, 1)
--- hs.layout.right50
--- Constant
--- A unit rect which will make a window occupy the right 50% of a screen
layout.right50 = geometry.rect(0.5, 0, 0.5, 1)
--- hs.layout.right70
--- Constant
--- A unit rect which will make a window occupy the right 70% of a screen
layout.right70 = geometry.rect(0.3, 0, 0.7, 1)
--- hs.layout.right75
--- Constant
--- A unit rect which will make a window occupy the right 75% of a screen
layout.right75 = geometry.rect(0.25, 0, 0.75, 1)
--- hs.layout.maximized
--- Constant
--- A unit rect which will make a window occupy all of a screen
layout.maximized = geometry.rect(0, 0, 1, 1)
--- hs.layout.apply(table[, windowTitleComparator])
--- Function
--- Applies a layout to applications/windows
---
--- Parameters:
--- * table - A table describing your desired layout. Each element in the table should be another table describing a set of windows to match, and their desired size/position. The fields in each of these tables are:
--- * A string containing an application name, or an `hs.application` object, or nil
--- * A string containing a window title or nil
--- * A string containing a screen name, or an `hs.screen` object, or a function that accepts no parameters and returns an `hs.screen` object, or nil to select the first available screen
--- * A Unit rect (see `hs.window.moveToUnit()`)
--- * A Frame rect (see `hs.screen:frame()`)
--- * A Full-frame rect (see `hs.screen:fullFrame()`)
--- * windowTitleComparator - (optional) Function to use for window title comparison. It is called with two string arguments (below) and its return value is evaluated as a boolean. If no comparator is provided, the '==' operator is used
--- * windowTitle: The `:title()` of the window object being examined
--- * layoutWindowTitle: The window title string (second field) specified in each element of the layout table
---
--- Returns:
--- * None
---
--- Notes:
--- * If the application name argument is nil, window titles will be matched regardless of which app they belong to
--- * If the window title argument is nil, all windows of the specified application will be matched
--- * You can specify both application name and window title if you want to match only one window of a particular application
--- * If you specify neither application name or window title, no windows will be matched :)
--- * Monitor name is a string, as found in `hs.screen:name()`. You can also pass an `hs.screen` object, or a function that returns an `hs.screen` object. If you pass nil, the first screen will be selected
--- * The final three arguments use `hs.geometry.rect()` objects to describe the desired position and size of matched windows:
--- * Unit rect will be passed to `hs.window.moveToUnit()`
--- * Frame rect will be passed to `hs.window.setFrame()` (including menubar and dock)
--- * Full-frame rect will be passed to `hs.window.setFrame()` (ignoring menubar and dock)
--- * If either the x or y components of frame/full-frame rect are negative, they will be applied as offsets against the opposite edge of the screen (e.g. If x is -100 then the left edge of the window will be 100 pixels from the right edge of the screen)
--- * Only one of the rect arguments will apply to any matched windows. If you specify more than one, the first will win
--- * An example usage:
---
--- ```layout1 = {
--- {"Mail", nil, "Color LCD", hs.layout.maximized, nil, nil},
--- {"Safari", nil, "Thunderbolt Display", hs.layout.maximized, nil, nil},
--- {"iTunes", "iTunes", "Color LCD", hs.layout.maximized, nil, nil},
--- {"iTunes", "MiniPlayer", "Color LCD", nil, nil, hs.geometry.rect(0, -48, 400, 48)},
--- }```
--- * An example of a function that works well as a `windowTitleComparator` is the Lua built-in `string.match`, which uses Lua Patterns to match strings
function layout.apply(layout, windowTitleComparator)
-- Layout parameter should be a table where each row takes the form of:
-- {"App name", "Window name","Display Name"/"hs.screen object", "unitrect", "framerect", "fullframerect"},
-- First three items in each row are strings (although the display name can also be an hs.screen object, or nil)
-- Second three items are rects that specify the position of the window. The first one that is
-- not nil, wins.
-- unitrect is a rect passed to window:moveToUnit()
-- framerect is a rect passed to window:setFrame()
-- If either the x or y components of framerect are negative, they will be applied as
-- offsets from the width or height of screen:frame(), respectively
-- fullframerect is a rect passed to window:setFrame()
-- If either the x or y components of fullframerect are negative, they will be applied
-- as offsets from the width or height of screen:fullFrame(), respectively
if not windowTitleComparator then
windowTitleComparator = function(windowTitle, layoutWindowTitle)
return windowTitle == layoutWindowTitle
end
end
for n,_row in pairs(layout) do
local app = nil
local wins = nil
local display = nil
local displaypoint = nil
local unit = _row[4]
local frame = _row[5]
local fullframe = _row[6]
local windows = nil
-- Find the application's object, if wanted
if _row[1] then
if type(_row[1]) == "userdata" then
app = _row[1]
else
app = application.get(_row[1])
if not app then
print("Unable to find app: " .. _row[1])
end
end
end
-- Find the destination display, if wanted
if _row[3] then
if type(_row[3]) == "string" then
local displays = fnutils.filter(screen.allScreens(), function(aScreen) return aScreen:name() == _row[3] end)
if displays then
-- TODO: This is bogus, multiple identical monitors will be impossible to lay out
display = displays[1]
end
elseif type(_row[3]) == "function" then
display = _row[3]()
elseif fnutils.contains(screen.allScreens(), _row[3]) then
display = _row[3]
else
-- Default to the main screen if the passed-in screen isn't found; useful for
-- layouts activated using the screen watcher, meaning that screens in layouts may
-- not be in the current screen configuration.
display = screen.primaryScreen()
end
else
display = screen.primaryScreen()
end
if not display then
print("Unable to find display: ", _row[3])
else
displaypoint = geometry.point(display:frame().x, display:frame().y)
end
-- Find the matching windows, if any
if _row[2] then
if app then
wins = fnutils.filter(app:allWindows(), function(win) return windowTitleComparator(win:title(), _row[2]) end)
else
wins = fnutils.filter(window:allWindows(), function(win) return windowTitleComparator(win:title(), _row[2]) end)
end
elseif app then
wins = app:allWindows()
end
-- Apply the display/frame positions requested, if any
if not wins then
print(_row[1],_row[2])
print("No windows matched, skipping.")
else
for m,_win in pairs(wins) do
local winframe = nil
local screenrect = nil
-- Move window to destination display, if wanted
if display and displaypoint then
_win:setTopLeft(displaypoint)
end
-- Apply supplied position, if any
if unit then
_win:moveToUnit(unit)
elseif frame then
winframe = frame
screenrect = _win:screen():frame()
elseif fullframe then
winframe = fullframe
screenrect = _win:screen():fullFrame()
end
if winframe then
if winframe.x < 0 or winframe.y < 0 then
if winframe.x < 0 then
winframe.x = screenrect.w + winframe.x
end
if winframe.y < 0 then
winframe.y = screenrect.h + winframe.y
end
end
_win:setFrame(winframe)
end
end
end
end
end
return layout
| mit |
anshkumar/yugioh-glaze | assets/script/c40343749.lua | 3 | 2195 | --ハウスダストン
function c40343749.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(40343749,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c40343749.condition)
e1:SetTarget(c40343749.target)
e1:SetOperation(c40343749.operation)
c:RegisterEffect(e1)
end
function c40343749.condition(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsReason(REASON_BATTLE) then
return c:GetReasonPlayer()~=tp and bit.band(c:GetBattlePosition(),POS_FACEUP)~=0
end
return rp~=tp and c:IsReason(REASON_DESTROY) and c:IsPreviousPosition(POS_FACEUP)
and c:IsPreviousLocation(LOCATION_ONFIELD) and c:GetPreviousControler()==tp
end
function c40343749.filter(c,e,tp)
return c:IsSetCard(0x80) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP,1-tp)
end
function c40343749.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.GetLocationCount(1-tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c40343749.filter,tp,LOCATION_DECK+LOCATION_HAND,0,2,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK+LOCATION_HAND)
end
function c40343749.operation(e,tp,eg,ep,ev,re,r,rp)
local ft1=Duel.GetLocationCount(tp,LOCATION_MZONE)
local ft2=Duel.GetLocationCount(1-tp,LOCATION_MZONE)
if ft1<=0 or ft2<=0 then return end
if ft1>ft2 then ft1=ft2 end
local g=Duel.GetMatchingGroup(c40343749.filter,tp,LOCATION_HAND+LOCATION_DECK,0,nil,e,tp)
local ct=math.floor(g:GetCount()/2)
if ct==0 then return end
if ct>ft1 then ct=ft1 end
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(40343749,1))
local sg1=g:Select(tp,1,ct,nil)
local tc=sg1:GetFirst()
g:Sub(sg1)
while tc do
Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP)
tc=sg1:GetNext()
end
local sg2=g:Select(tp,sg1:GetCount(),sg1:GetCount(),nil)
tc=sg2:GetFirst()
while tc do
Duel.SpecialSummonStep(tc,0,tp,1-tp,false,false,POS_FACEUP)
tc=sg2:GetNext()
end
Duel.SpecialSummonComplete()
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c93751476.lua | 3 | 2659 | --猛炎星-テンレイ
function c93751476.initial_effect(c)
--to grave
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetOperation(c93751476.regop)
c:RegisterEffect(e1)
--set
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(93751476,0))
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetCode(EVENT_BE_MATERIAL)
e2:SetCondition(c93751476.setcon)
e2:SetTarget(c93751476.settg)
e2:SetOperation(c93751476.setop)
c:RegisterEffect(e2)
end
function c93751476.regop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsReason(REASON_EFFECT) and c:IsReason(REASON_DESTROY) then
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(93751476,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_GRAVE)
e1:SetTarget(c93751476.sptg)
e1:SetOperation(c93751476.spop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
c:RegisterEffect(e1)
end
end
function c93751476.spfilter(c,e,tp)
return c:IsSetCard(0x79) and c:GetLevel()==4 and c:GetCode()~=93751476 and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c93751476.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c93751476.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c93751476.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,c93751476.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c93751476.setcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLocation(LOCATION_GRAVE) and r==REASON_SYNCHRO
and e:GetHandler():GetReasonCard():IsSetCard(0x79)
end
function c93751476.filter(c)
return c:IsSetCard(0x7c) and c:IsType(TYPE_SPELL) and c:IsSSetable()
end
function c93751476.settg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingMatchingCard(c93751476.filter,tp,LOCATION_DECK,0,1,nil) end
end
function c93751476.setop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET)
local g=Duel.SelectMatchingCard(tp,c93751476.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SSet(tp,g:GetFirst())
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
tetoali605/THETETOO_A6A | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
RockySeven3161/UB | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c47731128.lua | 3 | 1305 | --結界術師 メイコウ
function c47731128.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(47731128,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c47731128.cost)
e1:SetTarget(c47731128.target)
e1:SetOperation(c47731128.operation)
c:RegisterEffect(e1)
end
function c47731128.cost(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 c47731128.filter(c)
local tpe=c:GetType()
return c:IsFaceup() and (tpe==0x20002 or tpe==0x20004) and c:IsDestructable()
end
function c47731128.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and c47731128.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c47731128.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,e:GetHandler()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c47731128.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c47731128.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
felipedaragon/sailor | src/web_utils/utils.lua | 4 | 1048 | local os_tmpname, gsub = os.tmpname, string.gsub
local M = {
}
-- Default function for temporary names
-- @returns a temporay name using os.tmpname
function M.tmpname ()
local tempname = os_tmpname()
-- Lua os.tmpname returns a full path in Unix, but not in Windows
-- so we strip the eventual prefix
tempname = gsub(tempname, "(/tmp/)", "")
return tempname
end
-- deep copies a table
function M.deepcopy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[M.deepcopy(orig_key)] = M.deepcopy(orig_value)
end
setmetatable(copy, M.deepcopy(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
-- performs string split
function M.split(str,sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
str:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
return M
| mit |
zwhfly/openwrt-luci | modules/niu/luasrc/model/cbi/niu/traffic/qos1.lua | 49 | 3073 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sys = require "luci.sys"
local fs = require "nixio.fs"
m = Map("qos", translate("Manage Prioritization (QoS)"), translate([[Different
kinds of network traffic usually have different transmission requirements.
For example the important factor for a large HTTP-download is bandwith whereas
VoIP has a large focus on low packet latency. Prioritization takes these quality
of service factors into account and optimizes priorities to allow reasonable
performance for time critical services.]]))
s = m:section(NamedSection, "wan", "interface", translate("General Settings"),
translate([[For QoS to work correctly you need to provide the upload and
download speed of your internet connection. Values are in kilobits per second.
For comparison a standard consumer ADSL connection has between 1000 and 25000
kbps as donwload speed and between 128 and 1000 kbps upload speed.]]))
s.addremove = false
local en = s:option(ListValue, "enabled", translate("Prioritization"))
en:value("1", "Enable Quality of Service")
en:value("0", "Disable")
local dl = s:option(Value, "download", translate("Maximum Download Speed"), "kbps")
dl:depends("enabled", "1")
local ul = s:option(Value, "upload", translate("Maximum Upload Speed"), "kbps")
ul:depends("enabled", "1")
s = m:section(TypedSection, "classify", translate("Finetuning"), translate([[
The QoS application provides different useful default prioritization rules not
listed here that cover many common use-cases. You however can add custom rules
to finetune the prioritization process.]]))
s.template = "cbi/tblsection"
s.anonymous = true
s.addremove = true
n = s:option(Value, "_name", translate("Name"), translate("optional"))
srch = s:option(Value, "srchost", translate("Local IP-Address"))
srch.rmempty = true
srch:value("", translate("all"))
for i, dataset in ipairs(sys.net.arptable()) do
srch:value(dataset["IP address"])
end
p = s:option(ListValue, "proto", translate("Protocol"))
p:value("", translate("all"))
p:value("tcp", "TCP")
p:value("udp", "UDP")
p.rmempty = true
ports = s:option(Value, "ports", translate("Ports"))
ports.rmempty = true
ports:value("", translate("any"))
if fs.access("/etc/l7-protocols") then
l7 = s:option(ListValue, "layer7", translate("Service"))
l7.rmempty = true
l7:value("", translate("all"))
for f in fs.glob("/etc/l7-protocols/*.pat") do
l7:value(f:sub(19, #f-4))
end
end
s:option(Value, "connbytes", translate("Bytes sent"), translate("from[-to]"))
t = s:option(ListValue, "target", translate("Priority"))
t:value("Priority", translate("Highest"))
t:value("Express", translate("High"))
t:value("Normal", translate("Normal"))
t:value("Bulk", translate("Low"))
t.default = "Normal"
return m
| apache-2.0 |
freifunk-gluon/luci | modules/niu/luasrc/model/cbi/niu/traffic/qos1.lua | 49 | 3073 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sys = require "luci.sys"
local fs = require "nixio.fs"
m = Map("qos", translate("Manage Prioritization (QoS)"), translate([[Different
kinds of network traffic usually have different transmission requirements.
For example the important factor for a large HTTP-download is bandwith whereas
VoIP has a large focus on low packet latency. Prioritization takes these quality
of service factors into account and optimizes priorities to allow reasonable
performance for time critical services.]]))
s = m:section(NamedSection, "wan", "interface", translate("General Settings"),
translate([[For QoS to work correctly you need to provide the upload and
download speed of your internet connection. Values are in kilobits per second.
For comparison a standard consumer ADSL connection has between 1000 and 25000
kbps as donwload speed and between 128 and 1000 kbps upload speed.]]))
s.addremove = false
local en = s:option(ListValue, "enabled", translate("Prioritization"))
en:value("1", "Enable Quality of Service")
en:value("0", "Disable")
local dl = s:option(Value, "download", translate("Maximum Download Speed"), "kbps")
dl:depends("enabled", "1")
local ul = s:option(Value, "upload", translate("Maximum Upload Speed"), "kbps")
ul:depends("enabled", "1")
s = m:section(TypedSection, "classify", translate("Finetuning"), translate([[
The QoS application provides different useful default prioritization rules not
listed here that cover many common use-cases. You however can add custom rules
to finetune the prioritization process.]]))
s.template = "cbi/tblsection"
s.anonymous = true
s.addremove = true
n = s:option(Value, "_name", translate("Name"), translate("optional"))
srch = s:option(Value, "srchost", translate("Local IP-Address"))
srch.rmempty = true
srch:value("", translate("all"))
for i, dataset in ipairs(sys.net.arptable()) do
srch:value(dataset["IP address"])
end
p = s:option(ListValue, "proto", translate("Protocol"))
p:value("", translate("all"))
p:value("tcp", "TCP")
p:value("udp", "UDP")
p.rmempty = true
ports = s:option(Value, "ports", translate("Ports"))
ports.rmempty = true
ports:value("", translate("any"))
if fs.access("/etc/l7-protocols") then
l7 = s:option(ListValue, "layer7", translate("Service"))
l7.rmempty = true
l7:value("", translate("all"))
for f in fs.glob("/etc/l7-protocols/*.pat") do
l7:value(f:sub(19, #f-4))
end
end
s:option(Value, "connbytes", translate("Bytes sent"), translate("from[-to]"))
t = s:option(ListValue, "target", translate("Priority"))
t:value("Priority", translate("Highest"))
t:value("Express", translate("High"))
t:value("Normal", translate("Normal"))
t:value("Bulk", translate("Low"))
t.default = "Normal"
return m
| apache-2.0 |
anshkumar/yugioh-glaze | assets/script/c64107820.lua | 6 | 1221 | --フューチャー・グロウ
function c64107820.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c64107820.cost)
e1:SetOperation(c64107820.operation)
c:RegisterEffect(e1)
--atk up
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetRange(LOCATION_SZONE)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetTarget(aux.TargetBoolFunction(Card.IsRace,RACE_PSYCHO))
e2:SetValue(c64107820.val)
c:RegisterEffect(e2)
e1:SetLabelObject(e2)
end
function c64107820.cfilter(c)
return c:IsRace(RACE_PSYCHO) and c:IsAbleToRemoveAsCost()
end
function c64107820.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c64107820.cfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c64107820.cfilter,tp,LOCATION_GRAVE,0,1,1,nil)
e:SetLabel(g:GetFirst():GetLevel()*200)
e:GetLabelObject():SetLabel(0)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c64107820.operation(e,tp,eg,ep,ev,re,r,rp)
e:GetLabelObject():SetLabel(e:GetLabel())
end
function c64107820.val(e,c)
return e:GetLabel()
end
| gpl-2.0 |
freifunk-gluon/luci | libs/nixio/axTLS/samples/lua/axssl.lua | 176 | 19286 | #!/usr/local/bin/lua
--
-- Copyright (c) 2007, Cameron Rich
--
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the axTLS project nor the names of its
-- contributors may be used to endorse or promote products derived
-- from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
-- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
-- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
-- OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
-- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
-- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
--
-- Demonstrate the use of the axTLS library in Lua with a set of
-- command-line parameters similar to openssl. In fact, openssl clients
-- should be able to communicate with axTLS servers and visa-versa.
--
-- This code has various bits enabled depending on the configuration. To enable
-- the most interesting version, compile with the 'full mode' enabled.
--
-- To see what options you have, run the following:
-- > [lua] axssl s_server -?
-- > [lua] axssl s_client -?
--
-- The axtls/axtlsl shared libraries must be in the same directory or be found
-- by the OS.
--
--
require "bit"
require("axtlsl")
local socket = require("socket")
-- print version?
if #arg == 1 and arg[1] == "version" then
print("axssl.lua "..axtlsl.ssl_version())
os.exit(1)
end
--
-- We've had some sort of command-line error. Print out the basic options.
--
function print_options(option)
print("axssl: Error: '"..option.."' is an invalid command.")
print("usage: axssl [s_server|s_client|version] [args ...]")
os.exit(1)
end
--
-- We've had some sort of command-line error. Print out the server options.
--
function print_server_options(build_mode, option)
local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET)
local ca_cert_size = axtlsl.ssl_get_config(
axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET)
print("unknown option "..option)
print("usage: s_server [args ...]")
print(" -accept\t- port to accept on (default is 4433)")
print(" -quiet\t\t- No server output")
if build_mode >= axtlsl.SSL_BUILD_SERVER_ONLY then
print(" -cert arg\t- certificate file to add (in addition to "..
"default) to chain -")
print("\t\t Can repeat up to "..cert_size.." times")
print(" -key arg\t- Private key file to use - default DER format")
print(" -pass\t\t- private key file pass phrase source")
end
if build_mode >= axtlsl.SSL_BUILD_ENABLE_VERIFICATION then
print(" -verify\t- turn on peer certificate verification")
print(" -CAfile arg\t- Certificate authority - default DER format")
print("\t\t Can repeat up to "..ca_cert_size.." times")
end
if build_mode == axtlsl.SSL_BUILD_FULL_MODE then
print(" -debug\t\t- Print more output")
print(" -state\t\t- Show state messages")
print(" -show-rsa\t- Show RSA state")
end
os.exit(1)
end
--
-- We've had some sort of command-line error. Print out the client options.
--
function print_client_options(build_mode, option)
local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET)
local ca_cert_size = axtlsl.ssl_get_config(
axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET)
print("unknown option "..option)
if build_mode >= axtlsl.SSL_BUILD_ENABLE_CLIENT then
print("usage: s_client [args ...]")
print(" -connect host:port - who to connect to (default "..
"is localhost:4433)")
print(" -verify\t- turn on peer certificate verification")
print(" -cert arg\t- certificate file to use - default DER format")
print(" -key arg\t- Private key file to use - default DER format")
print("\t\t Can repeat up to "..cert_size.." times")
print(" -CAfile arg\t- Certificate authority - default DER format")
print("\t\t Can repeat up to "..ca_cert_size.."times")
print(" -quiet\t\t- No client output")
print(" -pass\t\t- private key file pass phrase source")
print(" -reconnect\t- Drop and re-make the connection "..
"with the same Session-ID")
if build_mode == axtlsl.SSL_BUILD_FULL_MODE then
print(" -debug\t\t- Print more output")
print(" -state\t\t- Show state messages")
print(" -show-rsa\t- Show RSA state")
end
else
print("Change configuration to allow this feature")
end
os.exit(1)
end
-- Implement the SSL server logic.
function do_server(build_mode)
local i = 2
local v
local port = 4433
local options = axtlsl.SSL_DISPLAY_CERTS
local quiet = false
local password = ""
local private_key_file = nil
local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET)
local ca_cert_size = axtlsl.
ssl_get_config(axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET)
local cert = {}
local ca_cert = {}
while i <= #arg do
if arg[i] == "-accept" then
if i >= #arg then
print_server_options(build_mode, arg[i])
end
i = i + 1
port = arg[i]
elseif arg[i] == "-quiet" then
quiet = true
options = bit.band(options, bit.bnot(axtlsl.SSL_DISPLAY_CERTS))
elseif build_mode >= axtlsl.SSL_BUILD_SERVER_ONLY then
if arg[i] == "-cert" then
if i >= #arg or #cert >= cert_size then
print_server_options(build_mode, arg[i])
end
i = i + 1
table.insert(cert, arg[i])
elseif arg[i] == "-key" then
if i >= #arg then
print_server_options(build_mode, arg[i])
end
i = i + 1
private_key_file = arg[i]
options = bit.bor(options, axtlsl.SSL_NO_DEFAULT_KEY)
elseif arg[i] == "-pass" then
if i >= #arg then
print_server_options(build_mode, arg[i])
end
i = i + 1
password = arg[i]
elseif build_mode >= axtlsl.SSL_BUILD_ENABLE_VERIFICATION then
if arg[i] == "-verify" then
options = bit.bor(options, axtlsl.SSL_CLIENT_AUTHENTICATION)
elseif arg[i] == "-CAfile" then
if i >= #arg or #ca_cert >= ca_cert_size then
print_server_options(build_mode, arg[i])
end
i = i + 1
table.insert(ca_cert, arg[i])
elseif build_mode == axtlsl.SSL_BUILD_FULL_MODE then
if arg[i] == "-debug" then
options = bit.bor(options, axtlsl.SSL_DISPLAY_BYTES)
elseif arg[i] == "-state" then
options = bit.bor(options, axtlsl.SSL_DISPLAY_STATES)
elseif arg[i] == "-show-rsa" then
options = bit.bor(options, axtlsl.SSL_DISPLAY_RSA)
else
print_server_options(build_mode, arg[i])
end
else
print_server_options(build_mode, arg[i])
end
else
print_server_options(build_mode, arg[i])
end
else
print_server_options(build_mode, arg[i])
end
i = i + 1
end
-- Create socket for incoming connections
local server_sock = socket.try(socket.bind("*", port))
---------------------------------------------------------------------------
-- This is where the interesting stuff happens. Up until now we've
-- just been setting up sockets etc. Now we do the SSL handshake.
---------------------------------------------------------------------------
local ssl_ctx = axtlsl.ssl_ctx_new(options, axtlsl.SSL_DEFAULT_SVR_SESS)
if ssl_ctx == nil then error("Error: Server context is invalid") end
if private_key_file ~= nil then
local obj_type = axtlsl.SSL_OBJ_RSA_KEY
if string.find(private_key_file, ".p8") then
obj_type = axtlsl.SSL_OBJ_PKCS8
end
if string.find(private_key_file, ".p12") then
obj_type = axtlsl.SSL_OBJ_PKCS12
end
if axtlsl.ssl_obj_load(ssl_ctx, obj_type, private_key_file,
password) ~= axtlsl.SSL_OK then
error("Private key '" .. private_key_file .. "' is undefined.")
end
end
for _, v in ipairs(cert) do
if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CERT, v, "") ~=
axtlsl.SSL_OK then
error("Certificate '"..v .. "' is undefined.")
end
end
for _, v in ipairs(ca_cert) do
if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CACERT, v, "") ~=
axtlsl.SSL_OK then
error("Certificate '"..v .."' is undefined.")
end
end
while true do
if not quiet then print("ACCEPT") end
local client_sock = server_sock:accept();
local ssl = axtlsl.ssl_server_new(ssl_ctx, client_sock:getfd())
-- do the actual SSL handshake
local connected = false
local res
local buf
while true do
socket.select({client_sock}, nil)
res, buf = axtlsl.ssl_read(ssl)
if res == axtlsl.SSL_OK then -- connection established and ok
if axtlsl.ssl_handshake_status(ssl) == axtlsl.SSL_OK then
if not quiet and not connected then
display_session_id(ssl)
display_cipher(ssl)
end
connected = true
end
end
if res > axtlsl.SSL_OK then
for _, v in ipairs(buf) do
io.write(string.format("%c", v))
end
elseif res < axtlsl.SSL_OK then
if not quiet then
axtlsl.ssl_display_error(res)
end
break
end
end
-- client was disconnected or the handshake failed.
print("CONNECTION CLOSED")
axtlsl.ssl_free(ssl)
client_sock:close()
end
axtlsl.ssl_ctx_free(ssl_ctx)
end
--
-- Implement the SSL client logic.
--
function do_client(build_mode)
local i = 2
local v
local port = 4433
local options =
bit.bor(axtlsl.SSL_SERVER_VERIFY_LATER, axtlsl.SSL_DISPLAY_CERTS)
local private_key_file = nil
local reconnect = 0
local quiet = false
local password = ""
local session_id = {}
local host = "127.0.0.1"
local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET)
local ca_cert_size = axtlsl.
ssl_get_config(axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET)
local cert = {}
local ca_cert = {}
while i <= #arg do
if arg[i] == "-connect" then
if i >= #arg then
print_client_options(build_mode, arg[i])
end
i = i + 1
local t = string.find(arg[i], ":")
host = string.sub(arg[i], 1, t-1)
port = string.sub(arg[i], t+1)
elseif arg[i] == "-cert" then
if i >= #arg or #cert >= cert_size then
print_client_options(build_mode, arg[i])
end
i = i + 1
table.insert(cert, arg[i])
elseif arg[i] == "-key" then
if i >= #arg then
print_client_options(build_mode, arg[i])
end
i = i + 1
private_key_file = arg[i]
options = bit.bor(options, axtlsl.SSL_NO_DEFAULT_KEY)
elseif arg[i] == "-CAfile" then
if i >= #arg or #ca_cert >= ca_cert_size then
print_client_options(build_mode, arg[i])
end
i = i + 1
table.insert(ca_cert, arg[i])
elseif arg[i] == "-verify" then
options = bit.band(options,
bit.bnot(axtlsl.SSL_SERVER_VERIFY_LATER))
elseif arg[i] == "-reconnect" then
reconnect = 4
elseif arg[i] == "-quiet" then
quiet = true
options = bit.band(options, bnot(axtlsl.SSL_DISPLAY_CERTS))
elseif arg[i] == "-pass" then
if i >= #arg then
print_server_options(build_mode, arg[i])
end
i = i + 1
password = arg[i]
elseif build_mode == axtlsl.SSL_BUILD_FULL_MODE then
if arg[i] == "-debug" then
options = bit.bor(options, axtlsl.SSL_DISPLAY_BYTES)
elseif arg[i] == "-state" then
options = bit.bor(axtlsl.SSL_DISPLAY_STATES)
elseif arg[i] == "-show-rsa" then
options = bit.bor(axtlsl.SSL_DISPLAY_RSA)
else -- don't know what this is
print_client_options(build_mode, arg[i])
end
else -- don't know what this is
print_client_options(build_mode, arg[i])
end
i = i + 1
end
local client_sock = socket.try(socket.connect(host, port))
local ssl
local res
if not quiet then print("CONNECTED") end
---------------------------------------------------------------------------
-- This is where the interesting stuff happens. Up until now we've
-- just been setting up sockets etc. Now we do the SSL handshake.
---------------------------------------------------------------------------
local ssl_ctx = axtlsl.ssl_ctx_new(options, axtlsl.SSL_DEFAULT_CLNT_SESS)
if ssl_ctx == nil then
error("Error: Client context is invalid")
end
if private_key_file ~= nil then
local obj_type = axtlsl.SSL_OBJ_RSA_KEY
if string.find(private_key_file, ".p8") then
obj_type = axtlsl.SSL_OBJ_PKCS8
end
if string.find(private_key_file, ".p12") then
obj_type = axtlsl.SSL_OBJ_PKCS12
end
if axtlsl.ssl_obj_load(ssl_ctx, obj_type, private_key_file,
password) ~= axtlsl.SSL_OK then
error("Private key '"..private_key_file.."' is undefined.")
end
end
for _, v in ipairs(cert) do
if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CERT, v, "") ~=
axtlsl.SSL_OK then
error("Certificate '"..v .. "' is undefined.")
end
end
for _, v in ipairs(ca_cert) do
if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CACERT, v, "") ~=
axtlsl.SSL_OK then
error("Certificate '"..v .."' is undefined.")
end
end
-- Try session resumption?
if reconnect ~= 0 then
local session_id = nil
local sess_id_size = 0
while reconnect > 0 do
reconnect = reconnect - 1
ssl = axtlsl.ssl_client_new(ssl_ctx,
client_sock:getfd(), session_id, sess_id_size)
res = axtlsl.ssl_handshake_status(ssl)
if res ~= axtlsl.SSL_OK then
if not quiet then axtlsl.ssl_display_error(res) end
axtlsl.ssl_free(ssl)
os.exit(1)
end
display_session_id(ssl)
session_id = axtlsl.ssl_get_session_id(ssl)
sess_id_size = axtlsl.ssl_get_session_id_size(ssl)
if reconnect > 0 then
axtlsl.ssl_free(ssl)
client_sock:close()
client_sock = socket.try(socket.connect(host, port))
end
end
else
ssl = axtlsl.ssl_client_new(ssl_ctx, client_sock:getfd(), nil, 0)
end
-- check the return status
res = axtlsl.ssl_handshake_status(ssl)
if res ~= axtlsl.SSL_OK then
if not quiet then axtlsl.ssl_display_error(res) end
os.exit(1)
end
if not quiet then
local common_name = axtlsl.ssl_get_cert_dn(ssl,
axtlsl.SSL_X509_CERT_COMMON_NAME)
if common_name ~= nil then
print("Common Name:\t\t\t"..common_name)
end
display_session_id(ssl)
display_cipher(ssl)
end
while true do
local line = io.read()
if line == nil then break end
local bytes = {}
for i = 1, #line do
bytes[i] = line.byte(line, i)
end
bytes[#line+1] = 10 -- add carriage return, null
bytes[#line+2] = 0
res = axtlsl.ssl_write(ssl, bytes, #bytes)
if res < axtlsl.SSL_OK then
if not quiet then axtlsl.ssl_display_error(res) end
break
end
end
axtlsl.ssl_ctx_free(ssl_ctx)
client_sock:close()
end
--
-- Display what cipher we are using
--
function display_cipher(ssl)
io.write("CIPHER is ")
local cipher_id = axtlsl.ssl_get_cipher_id(ssl)
if cipher_id == axtlsl.SSL_AES128_SHA then
print("AES128-SHA")
elseif cipher_id == axtlsl.SSL_AES256_SHA then
print("AES256-SHA")
elseif axtlsl.SSL_RC4_128_SHA then
print("RC4-SHA")
elseif axtlsl.SSL_RC4_128_MD5 then
print("RC4-MD5")
else
print("Unknown - "..cipher_id)
end
end
--
-- Display what session id we have.
--
function display_session_id(ssl)
local session_id = axtlsl.ssl_get_session_id(ssl)
local v
if #session_id > 0 then
print("-----BEGIN SSL SESSION PARAMETERS-----")
for _, v in ipairs(session_id) do
io.write(string.format("%02x", v))
end
print("\n-----END SSL SESSION PARAMETERS-----")
end
end
--
-- Main entry point. Doesn't do much except works out whether we are a client
-- or a server.
--
if #arg == 0 or (arg[1] ~= "s_server" and arg[1] ~= "s_client") then
print_options(#arg > 0 and arg[1] or "")
end
local build_mode = axtlsl.ssl_get_config(axtlsl.SSL_BUILD_MODE)
_ = arg[1] == "s_server" and do_server(build_mode) or do_client(build_mode)
os.exit(0)
| apache-2.0 |
ejurgensen/packages | net/prosody/files/prosody.cfg.lua | 65 | 9428 | -- Prosody Example Configuration File
--
-- Information on configuring Prosody can be found on our
-- website at https://prosody.im/doc/configure
--
-- Tip: You can check that the syntax of this file is correct
-- when you have finished by running this command:
-- prosodyctl check config
-- If there are any errors, it will let you know what and where
-- they are, otherwise it will keep quiet.
--
-- The only thing left to do is rename this file to remove the .dist ending, and fill in the
-- blanks. Good luck, and happy Jabbering!
---------- Server-wide settings ----------
-- Settings in this section apply to the whole server and are the default settings
-- for any virtual hosts
-- This is a (by default, empty) list of accounts that are admins
-- for the server. Note that you must create the accounts separately
-- (see https://prosody.im/doc/creating_accounts for info)
-- Example: admins = { "user1@example.com", "user2@example.net" }
admins = { }
-- Enable use of libevent for better performance under high load
-- For more information see: https://prosody.im/doc/libevent
--use_libevent = true
-- Prosody will always look in its source directory for modules, but
-- this option allows you to specify additional locations where Prosody
-- will look for modules first. For community modules, see https://modules.prosody.im/
--plugin_paths = {}
-- This is the list of modules Prosody will load on startup.
-- It looks for mod_modulename.lua in the plugins folder, so make sure that exists too.
-- Documentation on modules can be found at: http://prosody.im/doc/modules
modules_enabled = {
-- Generally required
"roster"; -- Allow users to have a roster. Recommended ;)
"saslauth"; -- Authentication for clients and servers. Recommended if you want to log in.
"tls"; -- Add support for secure TLS on c2s/s2s connections
"dialback"; -- s2s dialback support
"disco"; -- Service discovery
-- Not essential, but recommended
"carbons"; -- Keep multiple clients in sync
"pep"; -- Enables users to publish their avatar, mood, activity, playing music and more
"private"; -- Private XML storage (for room bookmarks, etc.)
"blocklist"; -- Allow users to block communications with other users
"vcard4"; -- User profiles (stored in PEP)
"vcard_legacy"; -- Conversion between legacy vCard and PEP Avatar, vcard
-- Nice to have
"version"; -- Replies to server version requests
"uptime"; -- Report how long server has been running
"time"; -- Let others know the time here on this server
"ping"; -- Replies to XMPP pings with pongs
"register"; -- Allow users to register on this server using a client and change passwords
--"mam"; -- Store messages in an archive and allow users to access it
--"csi_simple"; -- Simple Mobile optimizations
-- Admin interfaces
"admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands
--"admin_telnet"; -- Opens telnet console interface on localhost port 5582
-- HTTP modules
--"bosh"; -- Enable BOSH clients, aka "Jabber over HTTP"
--"websocket"; -- XMPP over WebSockets
--"http_files"; -- Serve static files from a directory over HTTP
-- Other specific functionality
--"limits"; -- Enable bandwidth limiting for XMPP connections
--"groups"; -- Shared roster support
--"server_contact_info"; -- Publish contact information for this service
--"announce"; -- Send announcement to all online users
--"welcome"; -- Welcome users who register accounts
--"watchregistrations"; -- Alert admins of registrations
--"motd"; -- Send a message to users when they log in
--"legacyauth"; -- Legacy authentication. Only used by some old clients and bots.
--"proxy65"; -- Enables a file transfer proxy service which clients behind NAT can use
}
-- These modules are auto-loaded, but should you want
-- to disable them then uncomment them here:
modules_disabled = {
-- "offline"; -- Store offline messages
-- "c2s"; -- Handle client connections
-- "s2s"; -- Handle server-to-server connections
-- "posix"; -- POSIX functionality, sends server to background, enables syslog, etc.
}
-- Disable account creation by default, for security
-- For more information see https://prosody.im/doc/creating_accounts
allow_registration = false
-- Force clients to use encrypted connections? This option will
-- prevent clients from authenticating unless they are using encryption.
c2s_require_encryption = true
-- Force servers to use encrypted connections? This option will
-- prevent servers from authenticating unless they are using encryption.
s2s_require_encryption = true
-- Force certificate authentication for server-to-server connections?
s2s_secure_auth = false
-- Some servers have invalid or self-signed certificates. You can list
-- remote domains here that will not be required to authenticate using
-- certificates. They will be authenticated using DNS instead, even
-- when s2s_secure_auth is enabled.
--s2s_insecure_domains = { "insecure.example" }
-- Even if you disable s2s_secure_auth, you can still require valid
-- certificates for some domains by specifying a list here.
--s2s_secure_domains = { "jabber.org" }
-- Select the authentication backend to use. The 'internal' providers
-- use Prosody's configured data storage to store the authentication data.
authentication = "internal_hashed"
-- Select the storage backend to use. By default Prosody uses flat files
-- in its configured data directory, but it also supports more backends
-- through modules. An "sql" backend is included by default, but requires
-- additional dependencies. See https://prosody.im/doc/storage for more info.
--storage = "sql" -- Default is "internal"
-- For the "sql" backend, you can uncomment *one* of the below to configure:
--sql = { driver = "SQLite3", database = "prosody.sqlite" } -- Default. 'database' is the filename.
--sql = { driver = "MySQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
--sql = { driver = "PostgreSQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
-- Archiving configuration
-- If mod_mam is enabled, Prosody will store a copy of every message. This
-- is used to synchronize conversations between multiple clients, even if
-- they are offline. This setting controls how long Prosody will keep
-- messages in the archive before removing them.
archive_expires_after = "1w" -- Remove archived messages after 1 week
-- You can also configure messages to be stored in-memory only. For more
-- archiving options, see https://prosody.im/doc/modules/mod_mam
-- Logging configuration
-- For advanced logging see http://prosody.im/doc/logging
log = {
info = "/var/log/prosody/prosody.log"; -- Change 'info' to 'debug' for verbose logging
error = "/var/log/prosody/prosody.err";
-- "*syslog"; -- Uncomment this for logging to syslog; needs mod_posix
-- "*console"; -- Log to the console, useful for debugging with daemonize=false
}
-- Uncomment to enable statistics
-- For more info see https://prosody.im/doc/statistics
-- statistics = "internal"
-- Pidfile, used by prosodyctl and the init.d script
pidfile = "/var/run/prosody/prosody.pid"
-- User and group, used for daemon
prosody_user = "prosody"
prosody_group = "prosody"
-- Certificates
-- Every virtual host and component needs a certificate so that clients and
-- servers can securely verify its identity. Prosody will automatically load
-- certificates/keys from the directory specified here.
-- For more information, including how to use 'prosodyctl' to auto-import certificates
-- (from e.g. Let's Encrypt) see https://prosody.im/doc/certificates
-- Location of directory to find certificates in (relative to main config file):
--certificates = "certs"
-- HTTPS currently only supports a single certificate, specify it here:
--https_certificate = "certs/localhost.crt"
----------- Virtual hosts -----------
-- You need to add a VirtualHost entry for each domain you wish Prosody to serve.
-- Settings under each VirtualHost entry apply *only* to that host.
VirtualHost "localhost"
VirtualHost "example.com"
enabled = false -- Remove this line to enable this host
-- Assign this host a certificate for TLS, otherwise it would use the one
-- set in the global section (if any).
-- Note that old-style SSL on port 5223 only supports one certificate, and will always
-- use the global one.
ssl = {
key = "/etc/prosody/certs/example.com.key";
certificate = "/etc/prosody/certs/example.com.crt";
}
------ Components ------
-- You can specify components to add hosts that provide special services,
-- like multi-user conferences, and transports.
-- For more information on components, see http://prosody.im/doc/components
---Set up a MUC (multi-user chat) room server on conference.example.com:
--Component "conference.example.com" "muc"
-- Set up a SOCKS5 bytestream proxy for server-proxied file transfers:
--Component "proxy.example.com" "proxy65"
--- Store MUC messages in an archive and allow users to access it
--modules_enabled = { "muc_mam" }
---Set up an external component (default component port is 5347)
--
-- External components allow adding various services, such as gateways/
-- transports to other networks like ICQ, MSN and Yahoo. For more info
-- see: http://prosody.im/doc/components#adding_an_external_component
--
--Component "gateway.example.com"
-- component_secret = "password"
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c76419637.lua | 9 | 2239 | --CX 激烈華戦艦タオヤメ
function c76419637.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,4,4)
c:EnableReviveLimit()
--discard
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(76419637,0))
e1:SetCategory(CATEGORY_HANDES)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCondition(c76419637.dccon)
e1:SetTarget(c76419637.dctg)
e1:SetOperation(c76419637.dcop)
c:RegisterEffect(e1)
--damage
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(76419637,1))
e2:SetCategory(CATEGORY_DAMAGE)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1,76419637)
e2:SetCondition(c76419637.damcon)
e2:SetCost(c76419637.damcost)
e2:SetTarget(c76419637.damtg)
e2:SetOperation(c76419637.damop)
c:RegisterEffect(e2)
end
function c76419637.dccon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()~=tp and Duel.GetFieldGroupCount(tp,0,LOCATION_HAND)>Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)
end
function c76419637.dctg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_HANDES,nil,0,1-tp,1)
end
function c76419637.dcop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.DiscardHand(1-tp,nil,1,1,REASON_EFFECT+REASON_DISCARD)
end
function c76419637.damcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,40424929)
end
function c76419637.damcost(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 c76419637.damtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local ct=Duel.GetFieldGroupCount(tp,LOCATION_ONFIELD,LOCATION_ONFIELD)
Duel.SetTargetPlayer(1-tp)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,ct*300)
end
function c76419637.damop(e,tp,eg,ep,ev,re,r,rp)
local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER)
local ct=Duel.GetFieldGroupCount(p,LOCATION_ONFIELD,LOCATION_ONFIELD)
Duel.Damage(p,ct*300,REASON_EFFECT)
end
| gpl-2.0 |
SquidDev-CC/Howl | external/bsrocks/init.lua | 1 | 1394 | --- The main BSRocks extension bootstrapper
-- @module howl.external.bsrocks
local root = ...
local fs = require "howl.platform".fs
local BSRocksPackage = require(root .. ".BSRocksPackage")
local BustedTask = require(root .. ".BustedTask")
local LDocTask = require(root .. ".LDocTask")
local Manager = require "howl.packages.Manager"
local Runner = require "howl.tasks.Runner"
local function getRequire(context)
local module = context:getModuleData("blue-shiny-rocks")
if module.require then
return module.require
end
local path = context.packageManager
:addPackage("gist", { id = "6ced21eb437a776444aacef4d597c0f7" })
:require({"bsrocks.lua"})
["bsrocks.lua"]
local bsrocks, err = loadfile(path, _ENV._NATIVE)
if not bsrocks then
context.logger:error("Cannot load bsrocks:" .. err)
return
end
return bsrocks({}).require
end
return {
name = "blue-shiny-rocks",
description = "Basic interaction with Blue-Shiny-Rocks.",
apply = function()
Manager:addProvider(BSRocksPackage, "bs-rock")
Runner:include {
busted = function(self, name, taskDepends)
return self:injectTask(BustedTask(self.env, name, taskDepends))
end,
ldoc = function(self, name, taskDepends)
return self:injectTask(LDocTask(self.env, name, taskDepends))
end,
}
end,
setup = function(context, data)
data.getRequire = function() return getRequire(context) end
end,
}
| mit |
anshkumar/yugioh-glaze | assets/script/c16114248.lua | 3 | 1239 | --ペア・サイクロイド
function c16114248.initial_effect(c)
c:EnableReviveLimit()
--fusion material
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetCondition(c16114248.fscondition)
e1:SetOperation(c16114248.fsoperation)
c:RegisterEffect(e1)
--direct attack
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DIRECT_ATTACK)
c:RegisterEffect(e2)
end
function c16114248.spfilter(c,mg)
return c:IsRace(RACE_MACHINE) and mg:IsExists(c16114248.spfilter2,1,c,c:GetCode())
end
function c16114248.spfilter2(c,code)
return c:IsRace(RACE_MACHINE) and c:IsCode(code)
end
function c16114248.fscondition(e,mg,gc)
if mg==nil then return true end
if gc then return false end
return mg:IsExists(c16114248.spfilter,1,nil,mg)
end
function c16114248.fsoperation(e,tp,eg,ep,ev,re,r,rp,gc)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FMATERIAL)
local g1=eg:FilterSelect(tp,c16114248.spfilter,1,1,nil,eg)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FMATERIAL)
local g2=eg:FilterSelect(tp,c16114248.spfilter2,1,1,g1:GetFirst(),g1:GetFirst():GetCode())
g1:Merge(g2)
Duel.SetFusionMaterial(g1)
end | gpl-2.0 |
rickyHong/nn_lib_torch | Criterion.lua | 3 | 1263 | local Criterion = torch.class('nn.Criterion')
function Criterion:__init()
self.gradInput = torch.Tensor()
self.output = 0
end
function Criterion:updateOutput(input, target)
end
function Criterion:forward(input, target)
return self:updateOutput(input, target)
end
function Criterion:backward(input, target)
return self:updateGradInput(input, target)
end
function Criterion:updateGradInput(input, target)
end
function Criterion:clone()
local f = torch.MemoryFile("rw"):binary()
f:writeObject(self)
f:seek(1)
local clone = f:readObject()
f:close()
return clone
end
function Criterion:type(type)
-- find all tensors and convert them
for key,param in pairs(self) do
if torch.typename(param) and torch.typename(param):find('torch%..+Tensor') then
self[key] = param:type(type)
end
end
return self
end
function Criterion:float()
return self:type('torch.FloatTensor')
end
function Criterion:double()
return self:type('torch.DoubleTensor')
end
function Criterion:cuda()
return self:type('torch.CudaTensor')
end
function Criterion:__call__(input, target)
self.output = self:forward(input, target)
self.gradInput = self:backward(input, target)
return self.output, self.gradInput
end
| bsd-3-clause |
anshkumar/yugioh-glaze | assets/script/c9831539.lua | 5 | 1638 | --タンホイザーゲート
function c9831539.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c9831539.target)
e1:SetOperation(c9831539.activate)
c:RegisterEffect(e1)
end
function c9831539.filter1(c,tp)
return c:IsLevelAbove(1) and c:IsAttackBelow(1000)
and Duel.IsExistingTarget(c9831539.filter2,tp,LOCATION_MZONE,0,1,c,c:GetRace())
end
function c9831539.filter2(c,rac)
return c:IsLevelAbove(1) and c:IsAttackBelow(1000) and c:IsRace(rac)
end
function c9831539.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(c9831539.filter1,tp,LOCATION_MZONE,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g1=Duel.SelectTarget(tp,c9831539.filter1,tp,LOCATION_MZONE,0,1,1,nil,tp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c9831539.filter2,tp,LOCATION_MZONE,0,1,1,g1:GetFirst(),g1:GetFirst():GetRace())
end
function c9831539.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS)
local tc1=g:GetFirst()
local tc2=g:GetNext()
if tc1:IsRelateToEffect(e) and tc1:IsFaceup() and tc2:IsRelateToEffect(e) and tc2:IsFaceup() then
local lv=tc1:GetLevel()+tc2:GetLevel()
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL_FINAL)
e1:SetValue(lv)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc1:RegisterEffect(e1)
local e2=e1:Clone()
tc2:RegisterEffect(e2)
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c12817939.lua | 5 | 2513 | --漆黒の魔王 LV6
function c12817939.initial_effect(c)
--disable
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_BATTLED)
e1:SetRange(LOCATION_MZONE)
e1:SetOperation(c12817939.disop)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(12817939,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EVENT_PHASE+PHASE_STANDBY)
e2:SetCondition(c12817939.spcon)
e2:SetCost(c12817939.spcost)
e2:SetTarget(c12817939.sptg)
e2:SetOperation(c12817939.spop)
c:RegisterEffect(e2)
end
c12817939.lvupcount=2
c12817939.lvup={85313220,58206034}
c12817939.lvdncount=1
c12817939.lvdn={85313220}
function c12817939.disop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local d=Duel.GetAttackTarget()
if d==c then d=Duel.GetAttacker() end
if d and d:IsStatus(STATUS_BATTLE_DESTROYED) and d:IsType(TYPE_EFFECT)
and c:GetFlagEffect(85313220)~=0 and not c:IsStatus(STATUS_BATTLE_DESTROYED) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x17a0000)
d:RegisterEffect(e1)
c:RegisterFlagEffect(12817939,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END+RESET_SELF_TURN,0,2)
end
end
function c12817939.spcon(e,tp,eg,ep,ev,re,r,rp)
return tp==Duel.GetTurnPlayer() and e:GetHandler():GetFlagEffect(12817939)~=0
end
function c12817939.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 c12817939.spfilter(c,e,tp)
return c:IsCode(58206034) and c:IsCanBeSpecialSummoned(e,0,tp,true,true)
end
function c12817939.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and Duel.IsExistingMatchingCard(c12817939.spfilter,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 c12817939.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,c12817939.spfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil,e,tp)
local tc=g:GetFirst()
if tc then
Duel.SpecialSummon(tc,0,tp,tp,true,true,POS_FACEUP)
tc:RegisterFlagEffect(12817939,RESET_EVENT+0x16e0000,0,0)
tc:CompleteProcedure()
end
end
| gpl-2.0 |
anshkumar/yugioh-glaze | assets/script/c45215453.lua | 3 | 1388 | --ヴァイロン・デルタ
function c45215453.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(Card.IsAttribute,ATTRIBUTE_LIGHT),1)
c:EnableReviveLimit()
--search
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(45215453,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCountLimit(1)
e1:SetCondition(c45215453.thcon)
e1:SetTarget(c45215453.thtg)
e1:SetOperation(c45215453.thop)
c:RegisterEffect(e1)
end
function c45215453.thcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp and e:GetHandler():IsDefencePos()
end
function c45215453.filter(c)
return c:IsType(TYPE_EQUIP) and c:IsAbleToHand()
end
function c45215453.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c45215453.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c45215453.thop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFacedown() or c:IsAttackPos() or not c:IsRelateToEffect(e) then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c45215453.filter,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 |
anshkumar/yugioh-glaze | assets/script/c81866673.lua | 3 | 2923 | --D-HERO ダッシュガイ
function c81866673.initial_effect(c)
--atkup
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(81866673,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCost(c81866673.atkcost)
e1:SetOperation(c81866673.atkop)
c:RegisterEffect(e1)
--pos
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_PHASE+PHASE_BATTLE)
e2:SetRange(LOCATION_MZONE)
e2:SetCountLimit(1)
e2:SetCondition(c81866673.poscon)
e2:SetOperation(c81866673.posop)
c:RegisterEffect(e2)
--spsummon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(81866673,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_NO_TURN_RESET)
e3:SetRange(LOCATION_GRAVE)
e3:SetCountLimit(1)
e3:SetCode(EVENT_DRAW)
e3:SetCondition(c81866673.spcon)
e3:SetTarget(c81866673.sptg)
e3:SetOperation(c81866673.spop)
c:RegisterEffect(e3)
end
function c81866673.atkcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,nil,1,e:GetHandler()) end
local g=Duel.SelectReleaseGroup(tp,nil,1,1,e:GetHandler())
Duel.Release(g,REASON_COST)
end
function c81866673.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFacedown() or not c:IsRelateToEffect(e) then return end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(1000)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
c:RegisterEffect(e1)
end
function c81866673.poscon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetAttackedCount()>0
end
function c81866673.posop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsAttackPos() then
Duel.ChangePosition(c,POS_FACEUP_DEFENCE)
end
end
function c81866673.spcon(e,tp,eg,ep,ev,re,r,rp)
return ep==tp and Duel.GetCurrentPhase()==PHASE_DRAW
end
function c81866673.spfilter(c,e,tp)
return c:IsLocation(LOCATION_HAND) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c81866673.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and eg:IsExists(c81866673.spfilter,1,nil,e,tp) end
if eg:GetCount()==1 then
Duel.ConfirmCards(1-tp,eg)
Duel.ShuffleHand(tp)
Duel.SetTargetCard(eg)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,eg,1,0,0)
else
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=eg:FilterSelect(tp,c81866673.spfilter,1,1,nil,e,tp)
Duel.ConfirmCards(1-tp,g)
Duel.ShuffleHand(tp)
Duel.SetTargetCard(g)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
end
function c81866673.spop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) 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 |
anshkumar/yugioh-glaze | assets/script/c59023523.lua | 5 | 1405 | --サイバネティック・マジシャン
function c59023523.initial_effect(c)
--atk change
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(59023523,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c59023523.cost)
e1:SetTarget(c59023523.target)
e1:SetOperation(c59023523.operation)
c:RegisterEffect(e1)
end
function c59023523.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 c59023523.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsFaceup() and chkc:IsLocation(LOCATION_MZONE) 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 c59023523.operation(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_SET_ATTACK_FINAL)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
e1:SetValue(2000)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
nanopack/flip | lib/store/failover.lua | 2 | 3480 | -- -*- mode: lua; tab-width: 2; indent-tabs-mode: 1; st-rulers: [70] -*-
-- vim: ts=4 sw=4 ft=lua noet
---------------------------------------------------------------------
-- @author Daniel Barney <daniel@pagodabox.com>
-- @copyright 2014, Pagoda Box, Inc.
-- @doc
--
-- @end
-- Created : 4 Feb 2015 by Daniel Barney <daniel@pagodabox.com>
---------------------------------------------------------------------
local logger = require('../logger')
local Packet = require('../packet')
local JSON = require('json')
local http = require('http')
local net = require('net')
local timer = require('timer')
local table = require('table')
local lmmdb = require("../lmmdb")
Env = lmmdb.Env
DB = lmmdb.DB
Txn = lmmdb.Txn
Cursor = lmmdb.Cursor
return function(Store)
local Init = require("./rep_client")
function Store:start_replication_connection()
net.createServer(function (client)
logger:info("client connected")
local state_machine = coroutine.create(Init.push)
client:on('data',function(data)
local worked,err = coroutine.resume(state_machine,data)
if coroutine.status(state_machine) == "dead" then
if not worked then
logger:error(err)
end
client:destroy()
end
end)
client:on('end',function()
coroutine.resume(state_machine,false)
end)
coroutine.resume(state_machine,self.push_connections,client,self.id,self.env)
end):listen(self.port,self.ip)
logger:info("tcp replication socket is open")
end
function Store:cancel_sync(ip,port)
local sync = self.connections[ip .. ":" .. port]
if sync then
if sync.timer then
timer.clearTimer(sync.timer)
end
if sync.connection then
-- this isn't quite right
sync.connection:close()
end
self.connections[ip .. ":" .. port] = nil
end
end
function Store:begin_sync(ip,port,cb)
local key = ip .. ":" .. port
if self.connections[key] and self.connections[key].connection then
logger:info("already syncing with remote",ip,port)
if cb then
cb()
end
else
if self.connections[key] and self.connections[key].timer then
timer.clearTimer(self.connections[key].timer)
end
-- create a connection
local client
client = net.createConnection(port, ip, function (err)
if err then
self.connections[key].timer = timer.setTimeout(5000,function() self:begin_sync(ip,port,cb) end)
self.connections[key].connection = nil
return
end
logger:info("connected to remote",ip,port)
local state_machine = coroutine.create(Init.pull)
client:on('data',function(data)
local worked,err = coroutine.resume(state_machine,data)
if coroutine.status(state_machine) == "dead" then
if not worked then
logger:error(err)
end
client:destroy()
end
end)
client:once('end',function()
coroutine.resume(state_machine,false)
self.connections[key].timer = timer.setTimeout(5000,function() self:begin_sync(ip,port,cb) end)
self.connections[key].connection = nil
end)
client:once('error',function(err)
coroutine.resume(state_machine,false)
end)
coroutine.resume(state_machine,self.env,self.id,self.ip,self.port,client,cb)
end)
client:once('error',function(err)
logger:info("we errored out",err)
self.connections[key].timer = timer.setTimeout(5000,function() self:begin_sync(ip,port,cb) end)
self.connections[key].connection = nil
end)
self.connections[key] = {connection = client}
end
end
end | mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.