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
kaustubhcs/torch-toolbox
BN-absorber/BN-absorber.lua
2
2074
require('nn') local function absorb_bn(w, b, mean, std, affine, gamma, beta) w:cmul(std:view(w:size(1),1):repeatTensor(1,w:size(2))) b:add(-mean):cmul(std) if affine then w:cmul(gamma:view(w:size(1),1):repeatTensor(1,w:size(2))) b:cmul(gamma):add(beta) end end local function BN_absorber(x) local i = 1 while (i <= #x.modules) do if x.modules[i].__typename == 'nn.Sequential' then BN_absorber(x.modules[i]) elseif x.modules[i].__typename == 'nn.Parallel' then BN_absorber(x.modules[i]) elseif x.modules[i].__typename == 'nn.Concat' then BN_absorber(x.modules[i]) elseif x.modules[i].__typename == 'nn.DataParallel' then BN_absorber(x.modules[i]) elseif x.modules[i].__typename == 'nn.ModelParallel' then BN_absorber(x.modules[i]) else -- check BN if x.modules[i].__typename == 'nn.SpatialBatchNormalization' or x.modules[i].__typename == 'nn.BatchNormalization' then if x.modules[i-1] and (x.modules[i-1].__typename == 'nn.Linear' or x.modules[i-1].__typename == 'nn.SpatialConvolution' or x.modules[i-1].__typename == 'nn.SpatialConvolutionMM') then -- force weight to be in 2-dim local weight = x.modules[i-1].weight weight = weight:view(weight:size(1), weight:nElement()/weight:size(1)) -- remove BN absorb_bn(weight, x.modules[i-1].bias, x.modules[i].running_mean, x.modules[i].running_std, x.modules[i].affine, x.modules[i].weight, x.modules[i].bias) x:remove(i) i = i - 1 else assert(false, 'Convolution module must exist right before batch normalization layer') end end end i = i + 1 end collectgarbage() return x end return BN_absorber
bsd-3-clause
shangjiyu/luci-with-extra
applications/luci-app-firewall/luasrc/model/cbi/firewall/rules.lua
66
6975
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2010-2012 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local ds = require "luci.dispatcher" local ft = require "luci.tools.firewall" m = Map("firewall", translate("Firewall - Traffic Rules"), translate("Traffic rules define policies for packets traveling between \ different zones, for example to reject traffic between certain hosts \ or to open WAN ports on the router.")) -- -- Rules -- s = m:section(TypedSection, "rule", translate("Traffic Rules")) s.addremove = true s.anonymous = true s.sortable = true s.template = "cbi/tblsection" s.extedit = ds.build_url("admin/network/firewall/rules/%s") s.defaults.target = "ACCEPT" s.template_addremove = "firewall/cbi_addrule" function s.create(self, section) created = TypedSection.create(self, section) end function s.parse(self, ...) TypedSection.parse(self, ...) local i_n = m:formvalue("_newopen.name") local i_p = m:formvalue("_newopen.proto") local i_e = m:formvalue("_newopen.extport") local i_x = m:formvalue("_newopen.submit") local f_n = m:formvalue("_newfwd.name") local f_s = m:formvalue("_newfwd.src") local f_d = m:formvalue("_newfwd.dest") local f_x = m:formvalue("_newfwd.submit") if i_x then created = TypedSection.create(self, section) self.map:set(created, "target", "ACCEPT") self.map:set(created, "src", "wan") self.map:set(created, "proto", (i_p ~= "other") and i_p or "all") self.map:set(created, "dest_port", i_e) self.map:set(created, "name", i_n) if i_p ~= "other" and i_e and #i_e > 0 then created = nil end elseif f_x then created = TypedSection.create(self, section) self.map:set(created, "target", "ACCEPT") self.map:set(created, "src", f_s) self.map:set(created, "dest", f_d) self.map:set(created, "name", f_n) end if created then m.uci:save("firewall") luci.http.redirect(ds.build_url( "admin/network/firewall/rules", created )) end end ft.opt_name(s, DummyValue, translate("Name")) local function rule_proto_txt(self, s) local f = self.map:get(s, "family") local p = ft.fmt_proto(self.map:get(s, "proto"), self.map:get(s, "icmp_type")) or translate("traffic") if f and f:match("4") then return "%s-%s" %{ translate("IPv4"), p } elseif f and f:match("6") then return "%s-%s" %{ translate("IPv6"), p } else return "%s %s" %{ translate("Any"), p } end end local function rule_src_txt(self, s) local z = ft.fmt_zone(self.map:get(s, "src"), translate("any zone")) local a = ft.fmt_ip(self.map:get(s, "src_ip"), translate("any host")) local p = ft.fmt_port(self.map:get(s, "src_port")) local m = ft.fmt_mac(self.map:get(s, "src_mac")) if p and m then return translatef("From %s in %s with source %s and %s", a, z, p, m) elseif p or m then return translatef("From %s in %s with source %s", a, z, p or m) else return translatef("From %s in %s", a, z) end end local function rule_dest_txt(self, s) local z = ft.fmt_zone(self.map:get(s, "dest")) local p = ft.fmt_port(self.map:get(s, "dest_port")) -- Forward if z then local a = ft.fmt_ip(self.map:get(s, "dest_ip"), translate("any host")) if p then return translatef("To %s, %s in %s", a, p, z) else return translatef("To %s in %s", a, z) end -- Input else local a = ft.fmt_ip(self.map:get(s, "dest_ip"), translate("any router IP")) if p then return translatef("To %s at %s on <var>this device</var>", a, p) else return translatef("To %s on <var>this device</var>", a) end end end local function snat_dest_txt(self, s) local z = ft.fmt_zone(self.map:get(s, "dest"), translate("any zone")) local a = ft.fmt_ip(self.map:get(s, "dest_ip"), translate("any host")) local p = ft.fmt_port(self.map:get(s, "dest_port")) or ft.fmt_port(self.map:get(s, "src_dport")) if p then return translatef("To %s, %s in %s", a, p, z) else return translatef("To %s in %s", a, z) end end match = s:option(DummyValue, "match", translate("Match")) match.rawhtml = true match.width = "70%" function match.cfgvalue(self, s) return "<small>%s<br />%s<br />%s</small>" % { rule_proto_txt(self, s), rule_src_txt(self, s), rule_dest_txt(self, s) } end target = s:option(DummyValue, "target", translate("Action")) target.rawhtml = true target.width = "20%" function target.cfgvalue(self, s) local t = ft.fmt_target(self.map:get(s, "target"), self.map:get(s, "dest")) local l = ft.fmt_limit(self.map:get(s, "limit"), self.map:get(s, "limit_burst")) if l then return translatef("<var>%s</var> and limit to %s", t, l) else return "<var>%s</var>" % t end end ft.opt_enabled(s, Flag, translate("Enable")).width = "1%" -- -- SNAT -- s = m:section(TypedSection, "redirect", translate("Source NAT"), translate("Source NAT is a specific form of masquerading which allows \ fine grained control over the source IP used for outgoing traffic, \ for example to map multiple WAN addresses to internal subnets.")) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true s.sortable = true s.extedit = ds.build_url("admin/network/firewall/rules/%s") s.template_addremove = "firewall/cbi_addsnat" function s.create(self, section) created = TypedSection.create(self, section) end function s.parse(self, ...) TypedSection.parse(self, ...) local n = m:formvalue("_newsnat.name") local s = m:formvalue("_newsnat.src") local d = m:formvalue("_newsnat.dest") local a = m:formvalue("_newsnat.dip") local p = m:formvalue("_newsnat.dport") local x = m:formvalue("_newsnat.submit") if x and a and #a > 0 then created = TypedSection.create(self, section) self.map:set(created, "target", "SNAT") self.map:set(created, "src", s) self.map:set(created, "dest", d) self.map:set(created, "proto", "all") self.map:set(created, "src_dip", a) self.map:set(created, "src_dport", p) self.map:set(created, "name", n) end if created then m.uci:save("firewall") luci.http.redirect(ds.build_url( "admin/network/firewall/rules", created )) end end function s.filter(self, sid) return (self.map:get(sid, "target") == "SNAT") end ft.opt_name(s, DummyValue, translate("Name")) match = s:option(DummyValue, "match", translate("Match")) match.rawhtml = true match.width = "70%" function match.cfgvalue(self, s) return "<small>%s<br />%s<br />%s</small>" % { rule_proto_txt(self, s), rule_src_txt(self, s), snat_dest_txt(self, s) } end snat = s:option(DummyValue, "via", translate("Action")) snat.rawhtml = true snat.width = "20%" function snat.cfgvalue(self, s) local a = ft.fmt_ip(self.map:get(s, "src_dip")) local p = ft.fmt_port(self.map:get(s, "src_dport")) if a and p then return translatef("Rewrite to source %s, %s", a, p) else return translatef("Rewrite to source %s", a or p) end end ft.opt_enabled(s, Flag, translate("Enable")).width = "1%" return m
apache-2.0
thesabbir/luci
protocols/luci-proto-openconnect/luasrc/model/cbi/admin_network/proto_openconnect.lua
40
2661
-- Copyright 2014 Nikos Mavrogiannopoulos <nmav@gnutls.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local server, username, password, cert, ca local oc_cert_file, oc_key_file, oc_ca_file local ifc = net:get_interface():name() oc_cert_file = "/etc/openconnect/user-cert-" .. ifc .. ".pem" oc_key_file = "/etc/openconnect/user-key-" .. ifc .. ".pem" oc_ca_file = "/etc/openconnect/ca-" .. ifc .. ".pem" server = section:taboption("general", Value, "server", translate("VPN Server")) server.datatype = "host" port = section:taboption("general", Value, "port", translate("VPN Server port")) port.placeholder = "443" port.datatype = "port" ifname = section:taboption("general", Value, "interface", translate("Output Interface")) ifname.template = "cbi/network_netlist" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) section:taboption("general", Value, "serverhash", translate("VPN Server's certificate SHA1 hash")) section:taboption("general", Value, "authgroup", translate("AuthGroup")) username = section:taboption("general", Value, "username", translate("Username")) password = section:taboption("general", Value, "password", translate("Password")) password.password = true cert = section:taboption("advanced", Value, "usercert", translate("User certificate (PEM encoded)")) cert.template = "cbi/tvalue" cert.rows = 10 function cert.cfgvalue(self, section) return nixio.fs.readfile(oc_cert_file) end function cert.write(self, section, value) value = value:gsub("\r\n?", "\n") nixio.fs.writefile(oc_cert_file, value) end cert = section:taboption("advanced", Value, "userkey", translate("User key (PEM encoded)")) cert.template = "cbi/tvalue" cert.rows = 10 function cert.cfgvalue(self, section) return nixio.fs.readfile(oc_key_file) end function cert.write(self, section, value) value = value:gsub("\r\n?", "\n") nixio.fs.writefile(oc_key_file, value) end ca = section:taboption("advanced", Value, "ca", translate("CA certificate; if empty it will be saved after the first connection.")) ca.template = "cbi/tvalue" ca.rows = 10 function ca.cfgvalue(self, section) return nixio.fs.readfile(oc_ca_file) end function ca.write(self, section, value) value = value:gsub("\r\n?", "\n") nixio.fs.writefile(oc_ca_file, value) end
apache-2.0
haka-security/haka
lib/haka/lua/lua/state.lua
5
6241
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. local class = require('class') local dg = require('grammar_dg') local check = require('check') local module = {} local log = haka.log_section("states") -- -- Actions collection -- module.ActionCollection = class.class('ActionCollection') function module.ActionCollection.method:__init(const) self._const = const or false self._actions = { timeouts = {} } end function module.ActionCollection.method:on(action) check.assert(not action.when or type(action.when) == 'function', "when must be a function") check.assert(not action.execute or type(action.execute) == 'function', "execute must be a function") check.assert(not action.jump or class.isa(action.jump, module.State), "can only jump on defined state") check.assert(action.execute or action.jump, "action must have either an execute or a jump") action.events = action.events or { action.event } check.assert(type(action.events) == 'table', "events must be a table of event") for _, event in ipairs(action.events) do check.assert(event, "action must have an event") check.assert(event.name, "action must be a table") check.assert(not self._const or self._actions[event.name], string.format("unknown event '%s'", event.name)) -- build another representation of the action local a = { when = action.when, execute = action.execute, } if action.jump then a.jump = action.jump._name end -- register action if event.name == 'timeouts' then self._actions.timeouts[event.timeout] = a else if not self._actions[event.name] then self._actions[event.name] = {} end table.insert(self._actions[event.name], a) end end end function module.ActionCollection.method:_register_events(events) if not events then return end for _, event in pairs(events) do if self._actions[event] then log.warning("cannot redefine event: %s", event) else self._actions[event] = {} end end end -- -- State -- module.State = class.class('State', module.ActionCollection) module.State._events = { 'fail', 'enter', 'leave', 'init', 'finish' } function module.State.method:__init(name) class.super(module.State).__init(self, true) self._name = name or '<unnamed>' local c = class.classof(self) while c do if c == module.ActionCollection then return end self:_register_events(c._events) c = c.super end end function module.State.method:setdefaults(defaults) check.assert(class.classof(defaults) == module.ActionCollection, "can only set default with a raw ActionCollection") for name, a in pairs(defaults._actions) do -- Don't add action to state that doesn't support it if self._actions[name] then table.append(self._actions[name], a) end end end function module.State.method:update(state_machine, event) error("unimplemented update function") end function module.State.method:_dump_graph(file) local dest = {} for name, actions in pairs(self._actions) do for _, a in ipairs(actions) do if a.jump then dest[a.jump] = true end end end for jump, _ in pairs(dest) do file:write(string.format('%s -> %s;\n', self._name, jump)) end end module.BidirectionalState = class.class('BidirectionalState', module.State) module.BidirectionalState._events = { 'up', 'down', 'parse_error', 'missing_grammar' } function module.BidirectionalState.method:__init(gup, gdown) check.assert(not gup or class.isa(gup, dg.Entity), "bidirectionnal state expect an exported element of a grammar", 1) check.assert(not gdown or class.isa(gdown, dg.Entity), "bidirectionnal state expect an exported element of a grammar", 1) class.super(module.BidirectionalState).__init(self) self._grammar = { up = gup, down = gdown, } end function module.BidirectionalState.method:update(state_machine, payload, direction, ...) if not self._grammar[direction] then state_machine:trigger("missing_grammar", direction, payload, ...) else local res, err = self._grammar[direction]:parse(payload, state_machine.owner) if err then state_machine:trigger("parse_error", err, ...) else state_machine:trigger(direction, res, ...) end end end -- -- CompiledState -- module.CompiledState = class.class('CompiledState') local function transitions_wrapper(state_table, actions, ...) for _, a in ipairs(actions) do if not a.when or a.when(...) then if a.execute then a.execute(...) end if a.jump then newstate = state_table[a.jump] check.assert(newstate, string.format("unknown state '%s'", a.jump)) return newstate._compiled_state end -- return anyway since we have done this action return end end end local function build_transitions_wrapper(state_table, actions) return function (...) return transitions_wrapper(state_table, actions, ...) end end function module.CompiledState.method:__init(state_machine, state, name) self._compiled_state = state_machine._state_machine:create_state(name) self._name = name self._state = state for n, a in pairs(state._actions) do local transitions_wrapper = build_transitions_wrapper(state_machine._state_table, a) if n == 'timeouts' then for timeout, action in pairs(a) do self._compiled_state:transition_timeout(timeout, build_transitions_wrapper(state_machine._state_table, { action })) end elseif n == 'fail' then self._compiled_state:transition_fail(transitions_wrapper) elseif n == 'enter' then self._compiled_state:transition_enter(transitions_wrapper) elseif n == 'leave' then self._compiled_state:transition_leave(transitions_wrapper) elseif n == 'init' then self._compiled_state:transition_init(transitions_wrapper) elseif n == 'finish' then self._compiled_state:transition_finish(transitions_wrapper) else self[n] = transitions_wrapper end end end module.new = function(state) state.name = state.name or "AnonymousState" state.parent = state.parent or module.State local State = class.class(state.name, state.parent) State._events = state.events if state.update then State.method.update = state.update end return State end return module
mpl-2.0
nasomi/darkstar
scripts/zones/The_Boyahda_Tree/Zone.lua
9
1831
----------------------------------- -- -- Zone: The_Boyahda_Tree (153) -- ----------------------------------- package.loaded["scripts/zones/The_Boyahda_Tree/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/zones/The_Boyahda_Tree/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local tomes = {17404406,17404407,17404408,17404409}; SetGroundsTome(tomes); UpdateTreasureSpawnPoint(17404390); end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-140.008,3.787,202.715,64); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/North_Gustaberg/npcs/Cavernous_Maw.lua
29
1494
----------------------------------- -- Area: North Gustaberg -- NPC: Cavernous Maw -- @pos 466 0 479 106 -- Teleports Players to North Gustaberg [S] ----------------------------------- package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/campaign"); require("scripts/zones/North_Gustaberg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) and hasMawActivated(player,7)) then player:startEvent(0x0387); else player:messageSpecial(NOTHING_HAPPENS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID:",csid); -- printf("RESULT:",option); if (csid == 0x0387 and option == 1) then toMaw(player,11); end end;
gpl-3.0
nasomi/darkstar
scripts/globals/mobskills/Glacial_Breath.lua
13
1287
--------------------------------------------- -- Glacial Breath -- -- Description: Deals Ice damage to enemies within a fan-shaped area. -- Type: Breath -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown cone -- Notes: Used only by Jormungand and Isgebind --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/utils"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON)) then return 1; elseif (target:isBehind(mob, 48) == true) then return 1; elseif (mob:AnimationSub() == 1) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local dmgmod = MobBreathMove(mob, target, 0.2, 1.25, ELE_ICE, 1400); local angle = mob:getAngle(target); angle = mob:getRotPos() - angle; dmgmod = dmgmod * ((128-math.abs(angle))/128); utils.clamp(dmgmod, 50, 1600); local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,MOBSKILL_BREATH,MOBPARAM_ICE,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
nasomi/darkstar
scripts/zones/Temenos/mobs/Thrym.lua
16
1190
----------------------------------- -- Area: Temenos N T -- NPC: Thrym ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) GetMobByID(16928781):updateEnmity(target); GetMobByID(16928783):updateEnmity(target); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if (IsMobDead(16928781)==true and IsMobDead(16928782)==true and IsMobDead(16928783)==true ) then GetNPCByID(16928768+19):setPos(200,-82,495); GetNPCByID(16928768+19):setStatus(STATUS_NORMAL); GetNPCByID(16928768+153):setPos(206,-82,495); GetNPCByID(16928768+153):setStatus(STATUS_NORMAL); GetNPCByID(16928768+210):setPos(196,-82,495); GetNPCByID(16928768+210):setStatus(STATUS_NORMAL); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Riverne-Site_A01/mobs/Heliodromos.lua
31
1721
----------------------------------- -- Area: Riverne Site A01 -- MOB: Heliodromos ----------------------------------- ----------------------------------- function onMobRoam(mob) local Heliodromos_Table = { 16900110, 16900111, 16900112 }; local Heliodromos_PH_Table = { 16900107, 16900108, 16900109 }; local Heliodromos_Despawn = GetServerVariable("Heliodromos_Despawn"); if (Heliodromos_Despawn > 0 and Heliodromos_Despawn <= os.time()) then for i=1, table.getn(Heliodromos_Table), 1 do if (Heliodromos_PH_Table[i] ~= nil) then if (GetMobAction(Heliodromos_PH_Table[i]) == 0) then DeterMob(Heliodromos_Table[i], true); DeterMob(Heliodromos_PH_Table[i], false); DespawnMob(Heliodromos_Table[i]); SpawnMob(Heliodromos_PH_Table[i], "", GetMobRespawnTime(Heliodromos_PH_Table[i])); end end end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) local Heliodromos = mob:getID(); local Heliodromos_Table = { 16900110, 16900111, 16900112 }; local Heliodromos_PH_Table = { 16900107, 16900108, 16900109 }; for i = 1, table.getn(Heliodromos_Table), 1 do if (Heliodromos_Table[i] ~= nil) then if (Heliodromos == Heliodromos_Table[i]) then SetServerVariable("Heliodromos_ToD", (os.time() + math.random((43200), (54000)))); DeterMob(Heliodromos_PH_Table[i], false); DeterMob(Heliodromos_Table[i], true); SpawnMob(Heliodromos_PH_Table[i], "", GetMobRespawnTime(Heliodromos_PH_Table[i])); end end end if (GetServerVariable("Heliodromos_Despawn") == 0) then SetServerVariable("Heliodromos_Despawn", os.time() + 600); end end;
gpl-3.0
dani-sj/soheyl
plugins/banhammer.lua
37
11688
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 2 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 2 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -2) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs banall_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process } --Copyright; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
j-san/awsome-conf
status_popup.lua
1
6251
local capi = { timer = timer, screen = screen, mouse = mouse, client = client } local wibox = require("wibox") local awful = require("awful") local beautiful = require("beautiful") local object = require("gears.object") local surface = require("gears.surface") local naughty = require("naughty") local cairo = require("lgi").cairo local setmetatable = setmetatable local tonumber = tonumber local string = string local ipairs = ipairs local pairs = pairs local pcall = pcall local print = print local table = table local type = type local math = math local vicious = require("vicious") local status_popup = { mt = {} } local table_update = function (t, set) for k, v in pairs(set) do t[k] = v end return t end local function set_coords(_status_popup) local s_geometry = capi.screen[1].workarea local screen_w = s_geometry.x + s_geometry.width local screen_h = s_geometry.y + s_geometry.height _status_popup.x = screen_w - 10 - _status_popup.width _status_popup.y = 30 _status_popup.wibox.x = _status_popup.x _status_popup.wibox.y = _status_popup.y end local function set_size(_status_popup) _status_popup.wibox.height = _status_popup.height _status_popup.wibox.width = _status_popup.width _status_popup.width = _status_popup.wibox.width _status_popup.height = _status_popup.wibox.height return true end --- Show a status_popup. function status_popup:show() set_size(self) set_coords(self) for k, widget in pairs(self.widgets) do vicious.activate(widget) end self.wibox.visible = true end --- Hide a status_popup popup. function status_popup:hide() for k, widget in pairs(self.widgets) do vicious.unregister(widget, true) end self.wibox.visible = false end --- Toggle status_popup visibility. function status_popup:toggle() if self.wibox.visible then self:hide() else self:show() end end function status_popup:add_vicious_widget(widget, wtype, format, timer, wargs) vicious.register(widget, wtype, format, timer, wargs) vicious.unregister(widget, true) table.insert(self.widgets, widget) self.layout:add(widget) end function status_popup:text(wtype, format, timer, wargs) local text = wibox.widget.textbox() if format == nil then text:set_text(wtype) self.layout:add(text) return text end self:add_vicious_widget(text, wtype, format, timer, wargs) return text end function status_popup:link(text, command) local link = wibox.widget.textbox(text) link:buttons(awful.button({ }, 1, function () awful.util.spawn(command) end)) return link end function status_popup:progress(wtype, format, timer, wargs) local progress = awful.widget.progressbar() progress:set_height(8) progress:set_vertical(false) progress:set_background_color(self.theme.bg_minimize) progress:set_border_color(self.theme.border_focus) progress:set_color(self.theme.bg_urgent) self:add_vicious_widget(progress, wtype, format, timer, wargs) return progress end function status_popup.init(_status_popup) _status_popup.layout = wibox.layout.fixed.vertical() date_long = _status_popup:text(vicious.widgets.date, "%d-%m-%y %T", 1) date_long:set_font('sans mono 12 bold') _status_popup:text(vicious.widgets.pkg, "$1 packages available for update", 600, "Arch") _status_popup:text(vicious.widgets.fs, "Root: ${/ avail_gb}GB free of ${/ size_gb}GB", 37) _status_popup:progress(vicious.widgets.fs, "${/ used_p}", 37) _status_popup:text(vicious.widgets.fs, "Home: ${/home avail_gb}GB free of ${/home size_gb}GB", 37) _status_popup:progress(vicious.widgets.fs, "${/home used_p}", 37) _status_popup:text(vicious.widgets.mem, "Memory: $2Mb used of $3Mb", 3) _status_popup:progress(vicious.widgets.mem, "$1", 3) _status_popup:text(vicious.widgets.cpu, "CPU: $1%", 1) _status_popup:progress(vicious.widgets.cpu, "$1", 1) _status_popup:text("CPUs:") _status_popup:progress(vicious.widgets.cpu, "$2", 0.5) _status_popup:progress(vicious.widgets.cpu, "$3", 0.5) _status_popup:progress(vicious.widgets.cpu, "$4", 0.5) _status_popup:progress(vicious.widgets.cpu, "$5", 0.5) local links_layout = wibox.layout.fixed.horizontal() links_layout:add(_status_popup:link("top cpu", terminal .. " -e 'top -o %CPU'")) links_layout:add(wibox.widget.textbox(" | ")) links_layout:add(_status_popup:link("top mem", terminal .. " -e 'top -o %MEM'")) links_layout:add(wibox.widget.textbox(" | ")) links_layout:add(_status_popup:link("syslog", terminal .. " -e 'top -o %MEM'")) _status_popup.layout:add(links_layout) margin = wibox.layout.margin(_status_popup.layout, 8, 8, 4, 4) _status_popup.wibox:set_widget(margin) end function status_popup.new(args, parent) args = args or {} local _status_popup = table_update(object(), { height = 200, width = 300, toggle = status_popup.toggle, hide = status_popup.hide, show = status_popup.show, text = status_popup.text, link = status_popup.link, add_vicious_widget = status_popup.add_vicious_widget, progress = status_popup.progress, widgets = {} }) _status_popup.theme = beautiful.get() if parent then _status_popup.auto_expand = parent.auto_expand elseif args.auto_expand ~= nil then _status_popup.auto_expand = args.auto_expand else _status_popup.auto_expand = true end _status_popup.wibox = wibox({ ontop = true, fg = _status_popup.theme.fg_focus, bg = _status_popup.theme.bg_normal, border_color = _status_popup.theme.border_focus, border_width = _status_popup.theme.border_width, type = "popup_status_popup" }) status_popup.init(_status_popup) _status_popup.wibox.visible = false set_size(_status_popup) _status_popup.x = _status_popup.wibox.x _status_popup.y = _status_popup.wibox.y return _status_popup end function status_popup.mt:__call(...) return status_popup.new(...) end return setmetatable(status_popup, status_popup.mt)
mit
rosejn/torch-datasets
dataset/cifar10.lua
2
3989
require 'torch' require 'nn' require 'image' require 'paths' require 'util/file' require 'logroll' require 'dataset' cifar10 = {} cifar10_md = { name = 'cifar10', dimensions = {3, 32, 32}, n_dimensions = 3 * 32 * 32, size = function() return 50000 end, classes = {'airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck'}, url = 'http://data.neuflow.org/data/cifar-10-torch.tar.gz', files = {'cifar-10-batches-t7/data_batch_1.t7', 'cifar-10-batches-t7/data_batch_2.t7', 'cifar-10-batches-t7/data_batch_3.t7', 'cifar-10-batches-t7/data_batch_4.t7', 'cifar-10-batches-t7/data_batch_5.t7'}, batch_size = 10000 } cifar10_test_md = util.merge(util.copy(cifar10_md), { size = function() return 10000 end, files = {'cifar-10-batches-t7/test_batch.t7'} }) local function load_data_files(md) local data = torch.Tensor(md.size(), md.n_dimensions) local labels = torch.Tensor(md.size()) for i, file in ipairs(md.files) do local path = dataset.data_path(md.name, md.url, file) local subset = torch.load(path, 'ascii') data[ {{(i - 1) * md.batch_size + 1, i * md.batch_size}}] = subset.data:t():double() labels[{{(i - 1) * md.batch_size + 1, i * md.batch_size}}] = subset.labels end labels = labels + 1 return data, labels end local function local_normalization(data) normalization = nn.SpatialContrastiveNormalization(1, image.gaussian1D(7)) for i = 1, cifar10_md.size() do -- rgb -> yuv local yuv = image.rgb2yuv(data[i]) -- normalize y locally: yuv[1] = normalization(yuv[{{1}}]) data[i] = yuv end return data end local function global_normalization(data) -- normalize u globally: mean_u = data[{ {},2,{},{} }]:mean() std_u = data[{ {},2,{},{} }]:std() data[{ {},2,{},{} }]:add(-mean_u) data[{ {},2,{},{} }]:div(-std_u) -- normalize v globally: mean_v = data[{ {},3,{},{} }]:mean() std_v = data[{ {},3,{},{} }]:std() data[{ {},3,{},{} }]:add(-mean_v) data[{ {},3,{},{} }]:div(-std_v) return data end local function present_dataset(dataset) local labelvector = torch.zeros(10) util.set_index_fn(dataset, function(self, index) local input = dataset.data[index] local label = dataset.labels[index] local target = labelvector:zero() target[label] = 1 local display = function() image.display{image=input, zoom=4, legend='cifar10[' .. index .. ']'} end return {input=input, target=target, label=label, display=display} end) util.set_size_fn(dataset, function(self) return self.size() end) return dataset end local function prepare_dataset(md) local data, labels = load_data_files(md) data = data:reshape(md.size(), 3, 32, 32) data = local_normalization(data) data = global_normalization(data) local dataset = util.merge(util.copy(md), { data = data, labels = labels, }) return present_dataset(dataset) end function cifar10.dataset() return prepare_dataset(cifar10_md) end function cifar10.raw_dataset() local data, labels = load_data_files(cifar10_md) data = data:reshape(cifar10_md.size(), 3, 32, 32) local dataset = util.merge(util.copy(cifar10_md), { data = data, labels = labels, }) return present_dataset(dataset) end function cifar10.test_dataset() return prepare_dataset(cifar10_test_md) end function cifar10.raw_test_dataset() local data, labels = load_data_files(cifar10_test_md) data = data:reshape(cifar10_test_md.size(), 3, 32, 32) local dataset = util.merge(util.copy(cifar10_test_md), { data = data, labels = labels, }) return present_dataset(dataset) end
bsd-3-clause
nasomi/darkstar
scripts/zones/Temenos/mobs/Telchines_Bard.lua
16
1135
----------------------------------- -- Area: Temenos N T -- NPC: Telchines_Bard ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if (IsMobDead(16928788)==true and IsMobDead(16928789)==true and IsMobDead(16928792)==true and IsMobDead(16928793)==true ) then GetNPCByID(16928768+26):setPos(19,80,430); GetNPCByID(16928768+26):setStatus(STATUS_NORMAL); GetNPCByID(16928768+160):setPos(16,80,430); GetNPCByID(16928768+160):setStatus(STATUS_NORMAL); GetNPCByID(16928768+211):setPos(22,80,430); GetNPCByID(16928768+211):setStatus(STATUS_NORMAL); end end;
gpl-3.0
coolflyreg/gs
3rd/skynet-mingw/service/cdummy.lua
94
1797
local skynet = require "skynet" require "skynet.manager" -- import skynet.launch, ... local globalname = {} local queryname = {} local harbor = {} local harbor_service skynet.register_protocol { name = "harbor", id = skynet.PTYPE_HARBOR, pack = function(...) return ... end, unpack = skynet.tostring, } skynet.register_protocol { name = "text", id = skynet.PTYPE_TEXT, pack = function(...) return ... end, unpack = skynet.tostring, } local function response_name(name) local address = globalname[name] if queryname[name] then local tmp = queryname[name] queryname[name] = nil for _,resp in ipairs(tmp) do resp(true, address) end end end function harbor.REGISTER(name, handle) assert(globalname[name] == nil) globalname[name] = handle response_name(name) skynet.redirect(harbor_service, handle, "harbor", 0, "N " .. name) end function harbor.QUERYNAME(name) if name:byte() == 46 then -- "." , local name skynet.ret(skynet.pack(skynet.localname(name))) return end local result = globalname[name] if result then skynet.ret(skynet.pack(result)) return end local queue = queryname[name] if queue == nil then queue = { skynet.response() } queryname[name] = queue else table.insert(queue, skynet.response()) end end function harbor.LINK(id) skynet.ret() end function harbor.CONNECT(id) skynet.error("Can't connect to other harbor in single node mode") end skynet.start(function() local harbor_id = tonumber(skynet.getenv "harbor") assert(harbor_id == 0) skynet.dispatch("lua", function (session,source,command,...) local f = assert(harbor[command]) f(...) end) skynet.dispatch("text", function(session,source,command) -- ignore all the command end) harbor_service = assert(skynet.launch("harbor", harbor_id, skynet.self())) end)
gpl-2.0
sjthespian/dotfiles
hammerspoon/hs/_asm/undocumented/spaces/init.lua
3
22657
--- === hs._asm.undocumented.spaces === --- --- These functions utilize private API's within the OS X internals, and are known to have unpredictable behavior under Mavericks and Yosemite when "Displays have separate Spaces" is checked under the Mission Control system preferences. --- local USERDATA_TAG = "hs._asm.undocumented.spaces" -- some of the commands can really get you in a bit of a fix, so this file will be mostly wrappers and -- predefined, common actions. local internal = require(USERDATA_TAG..".internal") local module = {} local basePath = package.searchpath(USERDATA_TAG, package.path) if basePath then basePath = basePath:match("^(.+)/init.lua$") if require"hs.fs".attributes(basePath .. "/docs.json") then require"hs.doc".registerJSONFile(basePath .. "/docs.json") end end -- local log = require("hs.logger").new(USERDATA_TAG, require"hs.settings".get(USERDATA_TAG .. ".logLevel") or "warning") local screen = require("hs.screen") local window = require("hs.window") local settings = require("hs.settings") local inspect = require("hs.inspect") local application = require("hs.application") -- private variables and methods ----------------------------------------- -- flag is checked to see if certain functions are called from module or from module.raw to prevent doing -- dangerous/unexpected/unknown things unless explicitly enabled local _BE_DANGEROUS_FLAG_ = false local _kMetaTable = {} _kMetaTable._k = {} _kMetaTable.__index = function(obj, key) if _kMetaTable._k[obj] then if _kMetaTable._k[obj][key] then return _kMetaTable._k[obj][key] else for k,v in pairs(_kMetaTable._k[obj]) do if v == key then return k end end end end return nil end _kMetaTable.__newindex = function(obj, key, value) error("attempt to modify a table of constants",2) return nil end _kMetaTable.__pairs = function(obj) return pairs(_kMetaTable._k[obj]) end _kMetaTable.__tostring = function(obj) local result = "" if _kMetaTable._k[obj] then local width = 0 for k,v in pairs(_kMetaTable._k[obj]) do width = width < #k and #k or width end for k,v in pairs(_kMetaTable._k[obj]) do result = result..string.format("%-"..tostring(width).."s %s\n", k, tostring(v)) end else result = "constants table missing" end return result end _kMetaTable.__metatable = _kMetaTable -- go ahead and look, but don't unset this local _makeConstantsTable = function(theTable) local results = setmetatable({}, _kMetaTable) _kMetaTable._k[results] = theTable return results end local reverseWithoutSystemSpaces = function(list) local results = {} for i,v in ipairs(list) do if internal.spaceType(v) ~= internal.types.system then table.insert(results, 1, v) end end return results end local isSpaceSafe = function(spaceID, func) func = func or "undocumented.spaces" if not _BE_DANGEROUS_FLAG_ then local t = internal.spaceType(spaceID) if t ~= internal.types.fullscreen and t ~= internal.types.tiled and t ~= internal.types.user then _BE_DANGEROUS_FLAG_ = false error(func..":must be user-created or fullscreen application space", 3) end end _BE_DANGEROUS_FLAG_ = false return spaceID end local screenMT = hs.getObjectMetatable("hs.screen") local windowMT = hs.getObjectMetatable("hs.window") -- Public interface ------------------------------------------------------ module.types = _makeConstantsTable(internal.types) module.masks = _makeConstantsTable(internal.masks) -- replicate legacy functions --- hs._asm.undocumented.spaces.count() -> number --- Function --- LEGACY: The number of spaces you currently have. --- --- Notes: --- * this function may go away in a future update --- --- * this functions is included for backwards compatibility. It is not recommended because it worked by indexing the spaces ignoring that fullscreen applications are included in the list twice, and only worked with one monitor. Use `hs._asm.undocumented.spaces.query` or `hs._asm.undocumented.spaces.spacesByScreenUUID`. module.count = function() return #reverseWithoutSystemSpaces(module.query(internal.masks.allSpaces)) end --- hs._asm.undocumented.spaces.currentSpace() -> number --- Function --- LEGACY: The index of the space you're currently on, 1-indexed (as usual). --- --- Notes: --- * this function may go away in a future update --- --- * this functions is included for backwards compatibility. It is not recommended because it worked by indexing the spaces, which can be rearranged by the operating system anyways. Use `hs._asm.undocumented.spaces.query` or `hs._asm.undocumented.spaces.spacesByScreenUUID`. module.currentSpace = function() local theSpaces = reverseWithoutSystemSpaces(module.query(internal.masks.allSpaces)) local currentID = internal.query(internal.masks.currentSpaces)[1] for i,v in ipairs(theSpaces) do if v == currentID then return i end end return nil end --- hs._asm.undocumented.spaces.moveToSpace(number) --- Function --- LEGACY: Switches to the space at the given index, 1-indexed (as usual). --- --- Notes: --- * this function may go away in a future update --- --- * this functions is included for backwards compatibility. It is not recommended because it was never really reliable and worked by indexing the spaces, which can be rearranged by the operating system anyways. Use `hs._asm.undocumented.spaces.changeToSpace`. module.moveToSpace = function(whichIndex) local theID = internal.query(internal.masks.allSpaces)[whichIndex] if theID then internal._changeToSpace(theID, false) return true else return false end end --- hs._asm.undocumented.spaces.isAnimating([screen]) -> bool --- Function --- Returns the state of space changing animation for the specified monitor, or for any monitor if no parameter is specified. --- --- Parameters: --- * screen - an optional hs.screen object specifying the specific monitor to check the animation status for. --- --- Returns: --- * a boolean value indicating whether or not a space changing animation is currently active. --- --- Notes: --- * This function can be used in `hs.eventtap` based space changing functions to determine when to release the mouse and key events. --- --- * This function is also added to the `hs.screen` object metatable so that you can check a specific screen's animation status with `hs.screen:spacesAnimating()`. module.isAnimating = function(...) local args = table.pack(...) if args.n == 0 then local isAnimating = false for i,v in ipairs(screen.allScreens()) do isAnimating = isAnimating or internal.screenUUIDisAnimating(internal.UUIDforScreen(v)) end return isAnimating elseif args.n == 1 then return internal.screenUUIDisAnimating(internal.UUIDforScreen(args[1])) else error("isAnimating:invalid argument, none or hs.screen object expected", 2) end end module.spacesByScreenUUID = function(...) local args = table.pack(...) if args.n == 0 or args.n == 1 then local masks = args[1] or internal.masks.allSpaces local theSpaces = module.query(masks) local holding = {} for i,v in ipairs(theSpaces) do local myScreen = internal.spaceScreenUUID(v) or "screenUndefined" if not holding[myScreen] then holding[myScreen] = {} end table.insert(holding[myScreen], v) end return holding else error("spacesByScreenUUID:invalid argument, none or integer expected", 2) end end -- need to make sure its a user accessible space module.changeToSpace = function(...) local args = table.pack(...) if args.n == 1 or args.n == 2 then local spaceID = isSpaceSafe(args[1], "changeToSpace") if type(args[2]) == "boolean" then resetDock = args[2] else resetDock = true end local fromID, uuid = 0, internal.spaceScreenUUID(spaceID) for i, v in ipairs(module.query(internal.masks.currentSpaces)) do if uuid == internal.spaceScreenUUID(v) then fromID = v break end end if fromID == 0 then error("changeToSpace:unable to identify screen for space id "..spaceID, 2) end -- this is where you could do some sort of animation with the transform functions -- may add that in the future internal.disableUpdates() for i,v in ipairs(module.query(internal.masks.currentOSSpaces)) do if internal.spaceScreenUUID(v) == targetUUID then internal.spaceLevel(v, internal.spaceLevel(v) + 1) end end internal.spaceLevel(spaceID, internal.spaceLevel(spaceID) + 1) -- doesn't seem to be necessary, _changeToSpace does it for us, though you would need -- it if you did any animation for the switch -- internal.showSpaces(spaceID) internal._changeToSpace(spaceID) internal.hideSpaces(fromID) internal.spaceLevel(spaceID, internal.spaceLevel(spaceID) - 1) for i,v in ipairs(module.query(internal.masks.currentOSSpaces)) do if internal.spaceScreenUUID(v) == targetUUID then internal.spaceLevel(v, internal.spaceLevel(v) - 1) end end internal.enableUpdates() if resetDock then hs.execute("killall Dock") end else error("changeToSpace:invalid argument, spaceID and optional boolean expected", 2) end return internal.query(internal.masks.currentSpaces) end module.mainScreenUUID = function(...) local UUID = internal.mainScreenUUID(...) if #UUID ~= 36 then -- on one screen machines, it returns "Main" which doesn't work for spaceCreate UUID = internal.spaceScreenUUID(internal.activeSpace()) end return UUID end -- -need a way to determine/specify which screen module.createSpace = function(...) local args = table.pack(...) if args.n <= 2 then local uuid, resetDock if type(args[1]) == "string" then uuid = args[1] else uuid = module.mainScreenUUID() end if type(args[#args]) == "boolean" then resetDock = args[#args] else resetDock = true end local newID = internal.createSpace(uuid) if resetDock then hs.execute("killall Dock") end return newID else error("createSpace:invalid argument, screenUUID and optional boolean expected", 2) end end -- -need to make sure no windows are only there -- -need to make sure its a user window -- ?check for how to do tiled/fullscreen? module.removeSpace = function(...) local args = table.pack(...) if args.n == 1 or args.n == 2 then local _Are_We_Being_Dangerous_ = _BE_DANGEROUS_FLAG_ local spaceID = isSpaceSafe(args[1], "removeSpace") local resetDock if type(args[2]) == "boolean" then resetDock = args[2] else resetDock = true end if internal.spaceType(spaceID) ~= internal.types.user then error("removeSpace:you can only remove user created spaces", 2) end for i,v in ipairs(module.query(internal.masks.currentSpaces)) do if spaceID == v then error("removeSpace:you can't remove one of the currently active spaces", 2) end end local targetUUID = internal.spaceScreenUUID(spaceID) local sameScreenSpaces = module.spacesByScreenUUID()[targetUUID] local userSpacesCount = 0 for i,v in ipairs(sameScreenSpaces) do if internal.spaceType(v) == internal.types.user then userSpacesCount = userSpacesCount + 1 end end if userSpacesCount < 2 then error("removeSpace:there must be at least one user space on each screen", 2) end -- Probably not necessary, with above checks, but if I figure out how to safely -- "remove" fullscreen/tiled spaces, I may remove them for experimenting _BE_DANGEROUS_FLAG_ = _Are_We_Being_Dangerous_ -- check for windows which need to be moved local theWindows = {} for i, v in ipairs(module.allWindowsForSpace(spaceID)) do if v:id() then table.insert(theWindows, v:id()) end end -- get id of screen to move them to local baseID = 0 for i,v in ipairs(module.query(internal.masks.currentSpaces)) do if internal.spaceScreenUUID(v) == targetUUID then baseID = v break end end for i,v in ipairs(theWindows) do -- only add windows that exist in only one place if #internal.windowsOnSpaces(v) == 1 then internal.windowsAddTo(v, baseID) end end internal.windowsRemoveFrom(theWindows, spaceID) internal._removeSpace(spaceID) if resetDock then hs.execute("killall Dock") end else error("removeSpace:invalid argument, spaceID and optional boolean expected", 2) end end module.allWindowsForSpace = function(...) local args = table.pack(...) if args.n == 1 then local ok, spaceID = pcall(isSpaceSafe, args[1], "allWindowsForSpace") if not ok then if internal.spaceName(args[1]) == "dashboard" then spaceID = args[1] else error(spaceID, 2) end end local isCurrent, windowIDs = false, {} for i,v in ipairs(module.query(internal.masks.currentSpaces)) do if v == spaceID then isCurrent = true break end end if isCurrent then windowIDs = window.allWindows() else local targetUUID = internal.spaceScreenUUID(spaceID) local baseID = 0 for i,v in ipairs(module.query(internal.masks.currentSpaces)) do if internal.spaceScreenUUID(v) == targetUUID then baseID = v break end end internal.disableUpdates() for i,v in ipairs(module.query(internal.masks.currentOSSpaces)) do if internal.spaceScreenUUID(v) == targetUUID then internal.spaceLevel(v, internal.spaceLevel(v) + 1) end end internal.spaceLevel(baseID, internal.spaceLevel(baseID) + 1) internal._changeToSpace(spaceID) windowIDs = window.allWindows() internal.hideSpaces(spaceID) internal._changeToSpace(baseID) internal.spaceLevel(baseID, internal.spaceLevel(baseID) - 1) for i,v in ipairs(module.query(internal.masks.currentOSSpaces)) do if internal.spaceScreenUUID(v) == targetUUID then internal.spaceLevel(v, internal.spaceLevel(v) - 1) end end internal.enableUpdates() end local realWindowIDs = {} for i,v in ipairs(windowIDs) do if v:id() then for j,k in ipairs(internal.windowsOnSpaces(v:id())) do if k == spaceID then table.insert(realWindowIDs, v) end end end end windowIDs = realWindowIDs return windowIDs else error("allWindowsForSpace:invalid argument, spaceID expected", 2) end end module.windowOnSpaces = function(...) local args = table.pack(...) if args.n == 1 then windowIDs = internal.windowsOnSpaces(args[1]) return windowIDs else error("windowOnSpaces:invalid argument, windowID expected", 2) end end module.moveWindowToSpace = function(...) local args = table.pack(...) if args.n == 2 then local windowID = args[1] local spaceID = isSpaceSafe(args[2], "moveWindowToSpace") local currentSpaces = internal.windowsOnSpaces(windowID) if #currentSpaces == 0 then error("moveWindowToSpace:no spaceID found for window", 2) elseif #currentSpaces > 1 then error("moveWindowToSpace:window on multiple spaces", 2) end if currentSpaces[1] ~= spaceID then internal.windowsAddTo(windowID, spaceID) internal.windowsRemoveFrom(windowID, currentSpaces[1]) end return internal.windowsOnSpaces(windowID)[1] else error("moveWindowToSpace:invalid argument, windowID and spaceID expected", 2) end end module.layout = function() local results = {} for i,v in ipairs(internal.details()) do local screenID = v["Display Identifier"] if screenID == "Main" then screenID = module.mainScreenUUID() end results[screenID] = {} for j,k in ipairs(v.Spaces) do table.insert(results[screenID], k.ManagedSpaceID) end end return results end module.query = function(...) local args = table.pack(...) if args.n <= 2 then local mask, flatten = internal.masks.allSpaces, true if type(args[1]) == "number" then mask = args[1] end if type(args[#args]) == "boolean" then flatten = args[#args] end local results = internal.query(mask) if not flatten then return results else local userWants, seen = {}, {} for i, v in ipairs(results) do if not seen[v] then seen[v] = true table.insert(userWants, v) end end return userWants end else error("query:invalid argument, mask and optional boolean expected", 2) end end -- map the basic functions to the main module spaceID module.screensHaveSeparateSpaces = internal.screensHaveSeparateSpaces module.activeSpace = internal.activeSpace module.spaceType = internal.spaceType module.spaceName = internal.spaceName module.spaceOwners = internal.spaceOwners module.spaceScreenUUID = internal.spaceScreenUUID -- generate debugging information module.debug = {} module.debug.layout = function(...) return inspect(internal.details(...)) end module.debug.report = function(...) local mask = 7 -- user accessible spaces local _ = table.pack(...)[1] if type(_) == "boolean" and _ then mask = 31 -- I think this gets user and "system" spaces like expose, etc. elseif type(_) == "boolean" then mask = 917519 -- I think this gets *everything*, but it may change as I dig elseif type(_) == "number" then mask = _ -- user specified mask elseif table.pack(...).n ~= 0 then error("debugReport:bad mask type provided, expected number", 2) end local list, report = module.query(mask), "" report = "Screens have separate spaces: "..tostring(internal.screensHaveSeparateSpaces()).."\n".. "Spaces for mask "..string.format("0x%08x", mask)..": "..(inspect(internal.query(mask)):gsub("%s+"," ")).. "\n\n" for i,v in ipairs(list) do report = report..module.debug.spaceInfo(v).."\n" end -- see if mask included any of the users accessible spaces flag if (mask & (1 << 2) ~= 0) then report = report.."\nLayout: "..inspect(internal.details()).."\n" end return report end module.debug.spaceInfo = function(v) local results = "Space: "..v.." ("..inspect(internal.spaceName(v))..")\n".. " Type: "..(module.types[internal.spaceType(v)] and module.types[internal.spaceType(v)] or "-- unknown --") .." ("..internal.spaceType(v)..")\n".. " Level: ".. internal.spaceLevel(v).."\n".. " CompatID: ".. internal.spaceCompatID(v).."\n".. " Screen: ".. inspect(internal.spaceScreenUUID(v)).."\n".. " Shape: "..(inspect(internal.spaceShape(v)):gsub("%s+"," ")).."\n".. " MShape: "..(inspect(internal.spaceManagedShape(v)):gsub("%s+"," ")).."\n".. " Transform: "..(inspect(internal.spaceTransform(v)):gsub("%s+"," ")).."\n".. " Values: "..(inspect(internal.spaceValues(v)):gsub("%s+"," ")).."\n".. " Owners: "..(inspect(internal.spaceOwners(v)):gsub("%s+"," ")).."\n" if #internal.spaceOwners(v) > 0 then local apps = {} for i,v in ipairs(internal.spaceOwners(v)) do table.insert(apps, (application.applicationForPID(v) and application.applicationForPID(v):title() or "n/a")) end results = results.." : "..(inspect(apps):gsub("%s+"," ")).."\n" end return results end -- extend built in modules screenMT.__index.spaces = function(obj) return module.spacesByScreenUUID()[internal.UUIDforScreen(obj)] end screenMT.__index.spacesUUID = internal.UUIDforScreen screenMT.__index.spacesAnimating = function(obj) return internal.screenUUIDisAnimating(internal.UUIDforScreen(obj)) end windowMT.__index.spaces = function(obj) return obj:id() and internal.windowsOnSpaces(obj:id()) or nil end windowMT.__index.spacesMoveTo = function(obj, ...) if obj:id() then module.moveWindowToSpace(obj:id(), ...) return obj end return nil end -- add raw subtable if the user has enabled it if settings.get("_ASMundocumentedSpacesRaw") then module.raw = internal module.raw.changeToSpace = function(...) _BE_DANGEROUS_FLAG_ = true local result = module.changeToSpace(...) _BE_DANGEROUS_FLAG_ = false -- should be already, but just in case return result end module.raw.removeSpace = function(...) _BE_DANGEROUS_FLAG_ = true local result = module.changeToSpace(...) _BE_DANGEROUS_FLAG_ = false -- should be already, but just in case return result end module.raw.allWindowsForSpace = function(...) _BE_DANGEROUS_FLAG_ = true local result = module.allWindowsForSpace(...) _BE_DANGEROUS_FLAG_ = false -- should be already, but just in case return result end end -- Return Module Object -------------------------------------------------- return module
mit
shangjiyu/luci-with-extra
applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/dns.lua
68
1085
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. require("luci.sys") m = Map("luci_statistics", translate("DNS Plugin Configuration"), translate( "The dns plugin collects detailled statistics about dns " .. "related traffic on selected interfaces." )) -- collectd_dns config section s = m:section( NamedSection, "collectd_dns", "luci_statistics" ) -- collectd_dns.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_dns.interfaces (Interface) interfaces = s:option( MultiValue, "Interfaces", translate("Monitor interfaces") ) interfaces.widget = "select" interfaces.size = 5 interfaces:depends( "enable", 1 ) interfaces:value("any") for k, v in pairs(luci.sys.net.devices()) do interfaces:value(v) end -- collectd_dns.ignoresources (IgnoreSource) ignoresources = s:option( Value, "IgnoreSources", translate("Ignore source addresses") ) ignoresources.default = "127.0.0.1" ignoresources:depends( "enable", 1 ) return m
apache-2.0
nasomi/darkstar
scripts/zones/Kuftal_Tunnel/npcs/_4u0.lua
61
1080
----------------------------------- -- Area: Kuftal Tunnel -- NPC: ----------------------------------- require("scripts/globals/status"); ----------------------------------- ----------------------------------- -- onSpawn ----------------------------------- function onSpawn(npc) local elevator = { id = ELEVATOR_KUFTAL_TUNNEL_DSPPRNG_RCK, -- id is usually 0, but 1 for this cause it's special lowerDoor = 0, -- lowerDoor's npcid upperDoor = 0, -- upperDoor usually has a smaller id than lowerDoor elevator = npc:getID(), -- actual elevator npc's id is usually the smallest started = 1, -- is the elevator already running regime = 1, -- } npc:setElevator(elevator.id, elevator.lowerDoor, elevator.upperDoor, elevator.elevator, elevator.started, elevator.regime); end;
gpl-3.0
thesabbir/luci
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/iface_add.lua
31
2881
-- Copyright 2009-2010 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. 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
nasomi/darkstar
scripts/zones/Sauromugue_Champaign/npcs/qm7.lua
19
2301
----------------------------------- -- Area: Sauromugue Champaign -- NPC: qm7 (???) (Tower 7) -- Involved in Quest: THF AF "As Thick As Thieves" -- @pos -193.869 15.400 276.837 120 ----------------------------------- package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Sauromugue_Champaign/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local thickAsThievesGrapplingCS = player:getVar("thickAsThievesGrapplingCS"); if (thickAsThievesGrapplingCS >= 2 and thickAsThievesGrapplingCS <= 7) then if (trade:hasItemQty(17474,1) and trade:getItemCount() == 1) then -- Trade grapel player:messageSpecial(THF_AF_WALL_OFFSET+3,0,17474); -- You cannot get a decent grip on the wall using the [Grapnel]. end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local thickAsThieves = player:getQuestStatus(WINDURST,AS_THICK_AS_THIEVES); local thickAsThievesGrapplingCS = player:getVar("thickAsThievesGrapplingCS"); if (thickAsThieves == QUEST_ACCEPTED) then if (thickAsThievesGrapplingCS == 7) then player:messageSpecial(THF_AF_MOB); SpawnMob(17269107,120):updateClaim(player); -- Climbpix Highrise setMobPos(17269107,194,15,269,0); elseif (thickAsThievesGrapplingCS == 0 or thickAsThievesGrapplingCS == 1 or thickAsThievesGrapplingCS == 2 or thickAsThievesGrapplingCS == 3 or thickAsThievesGrapplingCS == 4 or thickAsThievesGrapplingCS == 5 or thickAsThievesGrapplingCS == 6) then player:messageSpecial(THF_AF_WALL_OFFSET); end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Cloister_of_Tremors/bcnms/trial_by_earth.lua
19
1779
----------------------------------- -- Area: Cloister of Tremors -- BCNM: Trial by Earth -- @pos -539 1 -493 209 ----------------------------------- package.loaded["scripts/zones/Cloister_of_Tremors/TextIDs"] = nil; ------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Cloister_of_Tremors/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasCompleteQuest(BASTOK,TRIAL_BY_EARTH)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then player:delKeyItem(TUNING_FORK_OF_EARTH); player:addKeyItem(WHISPER_OF_TREMORS); player:messageSpecial(KEYITEM_OBTAINED,WHISPER_OF_TREMORS); end end;
gpl-3.0
nasomi/darkstar
scripts/globals/spells/bluemagic/battery_charge.lua
18
1499
----------------------------------------- -- Spell: Battery Charge -- Gradually restores MP -- Spell cost: 50 MP -- Monster Type: Arcana -- Spell Type: Magical (Light) -- Blue Magic Points: 3 -- Stat Bonus: MP+10, MND+1 -- Level: 79 -- Casting Time: 5 seconds -- Recast Time: 75 seconds -- Spell Duration: 100 ticks, 300 Seconds (5 Minutes) -- -- Combos: None ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_REFRESH; local power = 3; local duration = 300; if (caster:hasStatusEffect(EFFECT_DIFFUSION)) then local diffMerit = caster:getMerit(MERIT_DIFFUSION); if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit; end; caster:delStatusEffect(EFFECT_DIFFUSION); end; if (target:hasStatusEffect(EFFECT_REFRESH)) then target:delStatusEffect(EFFECT_REFRESH); end if (target:addStatusEffect(typeEffect,power,3,duration) == false) then spell:setMsg(75); end; return typeEffect; end;
gpl-3.0
aqasaeed/zeus
bot/seedbot.lua
1
12516
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '1.0' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "calculator", "chat", "robot", "auto_leave", "plugins", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban", "antilink", "admin" }, sudo_users = {146340607},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[SPARTACUS Robot Ver 3.7 AntispamBot : @tele_sparta Our Channel : @sparta_antispam Admins @blackhacker666 [Developer] http://uupload.ir/files/mxct_tele_spartacus.jpg ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group !createrealm [Name] Create a realm !setname [Name] Set realm name !setabout [GroupID] [Text] Set a group's about text !setrules [GroupID] [Text] Set a group's rules !lock [GroupID] [setting] Lock a group's setting !unlock [GroupID] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [GroupID] Kick all memebers and delete group !kill realm [RealmID] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Grt a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups Only sudo users can run this command !br [group_id] [text] !br 123456789 Hello ! This command will send text to [group_id] **U can use both "/" and "!" *Only admins and sudo can add bots in group *Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only admins and sudo can use res, setowner, commands ]], help_text = [[ لیست دستورات : __________________________ kick [آیدی،کد،ریپلای] شخص مورد نظر از گروه اخراج ميشود. —------------------- ban [آیدی،کد،ریپلای] شخص مورد نظر از گروه تحریم میشود —------------------- unban[کد] شخص مورد نظر از تحریم خارج ميشود —------------------- banlist لیست افرادی که از گروه تحریم شده اند —------------------- kickme : ترک گروه —------------------------------— filter set [کلمه] فیلتر کردن کلمه مورد نظر —---------------------- filter warn [کلمه] اخطار گرفتن برای کلمه مورد نظر —------------------------------— filter set [کلمه] فیلتر کردن کلمه مورد نظر —---------------------- filterlist : لیست کلمه های فیلتر شده —---------------------- owner : نمایش آیدی مدیر گروه —------------------- modlist : لیست کمک مدیرها —------------------- promote [ریپلای،یوزرنیم] اضافه کردن کمک مدیر —------------------- demote [ریپلای،یوزرنیم] حذف کردن کمک مدیر —------------------- lock [member|name|bots|flood] قفل کردن :اعضا،نام،رباتها،اسپم —---------------------- unlock [member|name|photo|bots] آزاد کردن :اعضا،نام،عکس،ربات —------------------------------— setphoto : اضافه کردن وقفل عکس گروه —---------------------- setname [نام] عوض کردن نام گروه —------------------------------— about : درباره گروه —---------------------- rules : قوانین گروه —---------------------- set rules <متن> متن قوانین گروه —---------------------- set about <متن> متن درباره گروه —------------------------------— settings : تنظیمات گروه —------------------------------— newlink : تعویض لینک و ارسال درگروه —---------------------- newlinkpv :تعویض لینک و ارسال در چت خصوصی —------------------------------— link : لینک گروه —------------------------------— linkpv : ارسال لینک در چت خصوصی —------------------------------— setflood [تعداد] محدودیت تعداد اسپم —------------------------------— set [کلمه] <text> ذخیره کلمه و جمله برگشت —---------------------- get [کلمه] باز گردانی جمله ای که برای کلمه ذخیره کردید —------------------------------— clean [modlist|rules|about] پاکسازی مدیرها/قوانین/موضوع —------------------------------— info [ریپلای] بازگرداندن اطلاعات شخص —---------------------- id [یوزرنیم] بازگرداندن کد آیدی —---------------------- id : بازگرداندن کد گروه یا افراد —------------------------------— log : اطلاعات گروه —---------------------- stats : آمار در پیام ساده —---------------------- who : لیست اعضا —------------------------------— tex <متن> تبدیل متن به تصویر —------------------------------— meme list : لیست انیمیشن های موجود —---------------------- ساخت انیمیشن: meme [title] [text_up] [text_down] [موضوع] [متن بالا] [متن پایین] —------------------------------— echo <متن> : تکرار متن —------------------------------— plugins enable 'plugin' chat فعال کردن ابزار در گروه —---------------------- plugins disable 'plugin' chat غیر فغال کردن ابزار در گروه —------------------------------— tagall : صدا کردن افراد گروه —---------------------— نیاز نیست از '!' و '/' استفاده کنید* ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
nasomi/darkstar
scripts/zones/Apollyon/mobs/Adamantshell.lua
16
1266
----------------------------------- -- Area: Apollyon SE -- NPC: Adamantshell ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if (mobID ==16933008) then -- GetNPCByID(16932864+232):setPos(108,-1,-518); GetNPCByID(16932864+232):setStatus(STATUS_NORMAL); elseif (mobID ==16933013) then -- GetNPCByID(16932864+233):setPos(109,-1,-521); GetNPCByID(16932864+233):setStatus(STATUS_NORMAL); elseif (mobID ==16933007) then -- GetNPCByID(16932864+234):setPos(112,-1,-523); GetNPCByID(16932864+234):setStatus(STATUS_NORMAL); end end;
gpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/baka47_shot_5.meta.lua
12
2773
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 150, light_colors = { "255 128 0 255", "244 213 156 255", "72 71 71 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = -17, y = 7 }, rotation = 0 }, shell_spawn = { pos = { x = 3, y = -2 }, rotation = -75.963760375976562 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = -33, y = 1 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/baka47_shot_1.meta.lua
12
2773
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 150, light_colors = { "255 128 0 255", "244 213 156 255", "72 71 71 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = -17, y = 7 }, rotation = 0 }, shell_spawn = { pos = { x = 3, y = -2 }, rotation = -75.963760375976562 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = -33, y = 1 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
akornatskyy/lucid
src/http/middleware/authorize.lua
1
1533
return function(following, options) assert(options.ticket, 'options.ticket') local name, path, domain, same_site, secure local cookie_dump, deleted_cookie local ticket = options.ticket local principal_parse do local cookie = require 'http.cookie' local c = options.auth_cookie or {} cookie_dump = cookie.dump name = c.name or '_a' path = c.path or options.root_path or '/' domain = c.domain same_site = c.same_site secure = c.secure local principal = options.principal or require 'security.principal' principal_parse = assert(principal.parse) deleted_cookie = cookie.delete {name = name, path = path} end return function(w, req) local cookies = req.cookies or req:parse_cookie() local c = cookies[name] if not c then return w:set_status_code(401) end local p, time_left = ticket:decode(c) if not p then w:add_header('Set-Cookie', deleted_cookie) return w:set_status_code(401) end if time_left < ticket.max_age / 2 then w:add_header('Set-Cookie', cookie_dump { name=name, value=ticket:encode(p), path=path, domain=domain, same_site=same_site, secure=secure, http_only=true }) end req.principal = principal_parse(p) return following(w, req) end end
mit
shakfu/start-vm
config/base/awesome/vicious/widgets/net.lua
15
2702
--------------------------------------------------- -- Licensed under the GNU General Public License v2 -- * (c) 2010, Adrian C. <anrxc@sysphere.org> -- * (c) 2009, Lucas de Vries <lucas@glacicle.com> --------------------------------------------------- -- {{{ Grab environment local tonumber = tonumber local os = { time = os.time } local io = { lines = io.lines } local setmetatable = setmetatable local string = { match = string.match } local helpers = require("vicious.helpers") -- }}} -- Net: provides state and usage statistics of all network interfaces -- vicious.widgets.net local net = {} -- Initialize function tables local nets = {} -- Variable definitions local unit = { ["b"] = 1, ["kb"] = 1024, ["mb"] = 1024^2, ["gb"] = 1024^3 } -- {{{ Net widget type local function worker(format) local args = {} -- Get NET stats for line in io.lines("/proc/net/dev") do -- Match wmaster0 as well as rt0 (multiple leading spaces) local name = string.match(line, "^[%s]?[%s]?[%s]?[%s]?([%w]+):") if name ~= nil then -- Received bytes, first value after the name local recv = tonumber(string.match(line, ":[%s]*([%d]+)")) -- Transmited bytes, 7 fields from end of the line local send = tonumber(string.match(line, "([%d]+)%s+%d+%s+%d+%s+%d+%s+%d+%s+%d+%s+%d+%s+%d$")) helpers.uformat(args, name .. " rx", recv, unit) helpers.uformat(args, name .. " tx", send, unit) -- Operational state and carrier detection local sysnet = helpers.pathtotable("/sys/class/net/" .. name) args["{"..name.." carrier}"] = tonumber(sysnet.carrier) or 0 local now = os.time() if nets[name] == nil then -- Default values on the first run nets[name] = {} helpers.uformat(args, name .. " down", 0, unit) helpers.uformat(args, name .. " up", 0, unit) else -- Net stats are absolute, substract our last reading local interval = now - nets[name].time if interval <= 0 then interval = 1 end local down = (recv - nets[name][1]) / interval local up = (send - nets[name][2]) / interval helpers.uformat(args, name .. " down", down, unit) helpers.uformat(args, name .. " up", up, unit) end nets[name].time = now -- Store totals nets[name][1] = recv nets[name][2] = send end end return args end -- }}} return setmetatable(net, { __call = function(_, ...) return worker(...) end })
mit
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/applications/luci-ushare/luasrc/model/cbi/ushare.lua
68
1275
--[[ LuCI uShare (c) 2008 Yanira <forum-2008@email.de> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("ushare", translate("uShare"), luci.util.pcdata(translate("uShare is a UPnP (TM) A/V & DLNA Media Server. It implements the server component that provides UPnP media devices with information on available multimedia files."))) s = m:section(TypedSection, "ushare", translate("Settings")) s.addremove = false s.anonymous = true s:option(Flag, "enabled", translate("Enable")) s:option(Value, "username", translate("Username")) s:option(Value, "servername", translate("Servername")) dif = s:option( Value, "interface", translate("Interface")) for _, nif in ipairs(luci.sys.net.devices()) do if nif ~= "lo" then dif:value(nif) end end s:option(DynamicList, "content_directories", translate("Content directories")) s:option(Flag, "disable_webif", translate("Disable webinterface")) s:option(Flag, "disable_telnet", translate("Disable telnet console")) s:option(Value, "options", translate("Options")) return m
gpl-2.0
vrld/Panoptes
states/gameover.lua
1
2101
local st = {} local canvas function st:init() canvas = love.graphics.newCanvas() self.name = {text = ""} end local names = { 'barmpot', 'berk', 'slowpoke', 'muppet', 'dimwit', 'halfwit', 'blockhead', 'dunce', 'cretin', 'dullard', 'dum-dum', 'noodle' } local switching = false function st:enter(pre) canvas:clear() canvas:renderTo(function() pre:draw() end) switching = false end function st:draw() draw_blurred(canvas, 7) love.graphics.setColor(20,16,10,190) love.graphics.rectangle('fill', 0,0, WIDTH, HEIGHT) gui.core.draw() end local hot function st:update(dt) love.graphics.setFont(Font[90]) gui.group.push{grow = 'down', pos = {20,120}, size={WIDTH-40,50}} gui.Label{text = "GAME OVER", align = "center"} love.graphics.setFont(Font[40]) gui.Label{text = "Final Score: " .. State.game.points, align = "center", pos = {nil,70}} gui.Label{text = "", size = {nil,20}} love.graphics.setFont(Font[30]) gui.group.push{grow = 'right', pos = {160}, size={WIDTH/2-180}} gui.Label{text = "Your name: ", align = "left"} gui.Input{info = self.name} gui.group.pop{} if gui.Button{text = "OK", pos = {(WIDTH-40-250)/2,100}, size = {250}} and not switching then switching = true if self.name.text == "" then local n, i = names[love.math.random(#names)], 0 Timer.addPeriodic(.2, function() i = i + 1 self.name.text = n:sub(1,i) self.name.cursor = i if i == #n then Timer.add(1, function() GS.transition(State.menu) add_highscore(State.game.points, self.name.text) if sync_highscores then sync_highscores_threaded() end end) return false end end) return end add_highscore(State.game.points, self.name.text) if sync_highscores then sync_highscores_threaded() end GS.transition(State.menu) end gui.group.pop{} local h = gui.mouse.getHot() if h ~= hot and h ~= nil then Sound.static.btn:play() end hot = h end function st:leave() end function st:textinput(text) gui.keyboard.textinput(text) end function st:keypressed(key) gui.keyboard.pressed(key) end return st
gpl-3.0
nasomi/darkstar
scripts/zones/King_Ranperres_Tomb/npcs/Tombstone.lua
15
2930
----------------------------------- -- Area: King Ranperre's Tomb -- NPC: Tombstone -- Involved in Quest: Grave Concerns -- @pos 1 0.1 -101 190 ----------------------------------- package.loaded["scripts/zones/King_Ranperres_Tomb/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/King_Ranperres_Tomb/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,GRAVE_CONCERNS) == QUEST_ACCEPTED) then if (trade:hasItemQty(567,1) and trade:getItemCount() == 1) then -- Trade Well Water player:startEvent(0x0003); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentMission = player:getCurrentMission(SANDORIA); local MissionStatus = player:getVar("MissionStatus"); local BatHuntCompleted = player:hasCompletedMission(SANDORIA,BAT_HUNT); -- quest repeatable and clicking tombstone should not produce cutscene on repeat local X = npc:getXPos(); local Z = npc:getZPos(); if (X >= -1 and X <= 1 and Z >= -106 and Z <= -102) then if (currentMission == BAT_HUNT and MissionStatus <= 1) then player:startEvent(0x0004); else player:startEvent(0x0002); end elseif (currentMission == RANPERRE_S_FINAL_REST and MissionStatus == 2) then player:startEvent(0x0008); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0004) then player:setVar("MissionStatus",2); elseif (csid == 0x0002) then local graveConcerns = player:getQuestStatus(SANDORIA,GRAVE_CONCERNS); if (graveConcerns == QUEST_ACCEPTED and player:hasItem(547) == false and player:hasItem(567) == false) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,547); -- Tomb Waterskin else player:addItem(547); player:messageSpecial(ITEM_OBTAINED,547); -- Tomb Waterskin end end elseif (csid == 0x0003) then player:tradeComplete(); player:setVar("OfferingWaterOK",1); player:addItem(547); player:messageSpecial(ITEM_OBTAINED,547); -- Tomb Waterskin elseif (csid == 0x0008) then player:setVar("MissionStatus",3); player:addKeyItem(ANCIENT_SANDORIAN_BOOK); player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_SANDORIAN_BOOK); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Windurst_Waters/npcs/Furan-Furin.lua
59
1052
----------------------------------- -- Area: Windurst Waters -- NPC: Furan-Furin -- Type: Weather Reporter ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x82712,0,0,0,0,0,0,0,VanadielTime()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Windurst_Waters/npcs/Lumomo.lua
19
2836
----------------------------------- -- Area: Windurst Waters -- NPC: Lumomo -- Type: Standard NPC -- @zone: 238 -- @pos -55.770 -5.499 18.914 -- 0x027e 0x0332 0x0334 0x0336 0x0337 -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ecoWarWindurst = player:getQuestStatus(WINDURST,ECO_WARRIOR_WIN); local ecoWarActiveNation = player:getVar("ECO_WARRIOR_ACTIVE"); if (player:hasKeyItem(INDIGESTED_MEAT) and ecoWarActiveNation == 238) then player:startEvent(0x0336); -- quest done elseif (ecoWarActiveNation < 1 and player:getFameLevel(WINDURST) >= 1 and player:getVar("ECO-WAR_ConquestWeek") ~= getConquestTally()) then player:startEvent(0x0332); -- Start CS elseif (ecoWarActiveNation ~= 238 and ecoWarActiveNation > 1) then player:startEvent(0x0337); elseif (ecoWarWindurst ~= QUEST_AVAILABLE and ecoWarActiveNation == 238 and player:getVar("ECO-WAR_ConquestWeek") ~= getConquestTally()) then player:startEvent(0x0334); -- reminder else player:startEvent(0x0335); -- Default chit-chat end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); printf("RESULT: %u",option); if (csid == 0x0332 and option == 1) then if (player:getQuestStatus(WINDURST,ECO_WARRIOR_WIN) == QUEST_AVAILABLE) then player:addQuest(WINDURST,ECO_WARRIOR_WIN); end player:setVar("ECO_WARRIOR_ACTIVE",player:getZoneID()); player:setVar("ECO-WAR_ConquestWeek",0); elseif (csid == 0x0336) then if (player:getFreeSlotsCount() >= 1) then player:completeQuest(WINDURST,ECO_WARRIOR_WIN); player:delKeyItem(INDIGESTED_MEAT); player:addGil(GIL_RATE * 5000); player:messageSpecial(GIL_OBTAINED,GIL_RATE * 5000); player:addItem(4198); player:messageSpecial(ITEM_OBTAINED,4198); player:addTitle(EMERALD_EXTERMINATOR); player:addFame(WINDURST,WIN_FAME * 80); player:setVar("ECO-WAR_ConquestWeek",getConquestTally()) player:setVar("ECO_WARRIOR_ACTIVE",0); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4198); end end end;
gpl-3.0
mrfoxirani/mehran
plugins/xkcd.lua
628
1374
do function get_last_id() local res,code = https.request("http://xkcd.com/info.0.json") if code ~= 200 then return "HTTP ERROR" end local data = json:decode(res) return data.num end function get_xkcd(id) local res,code = http.request("http://xkcd.com/"..id.."/info.0.json") if code ~= 200 then return "HTTP ERROR" end local data = json:decode(res) local link_image = data.img if link_image:sub(0,2) == '//' then link_image = msg.text:sub(3,-1) end return link_image, data.title, data.alt end function get_xkcd_random() local last = get_last_id() local i = math.random(1, last) return get_xkcd(i) end function send_title(cb_extra, success, result) if success then local message = cb_extra[2] .. "\n" .. cb_extra[3] send_msg(cb_extra[1], message, ok_cb, false) end end function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!xkcd" then url, title, alt = get_xkcd_random() else url, title, alt = get_xkcd(matches[1]) end file_path = download_to_file(url) send_photo(receiver, file_path, send_title, {receiver, title, alt}) return false end return { description = "Send comic images from xkcd", usage = {"!xkcd (id): Send an xkcd image and title. If not id, send a random one"}, patterns = { "^!xkcd$", "^!xkcd (%d+)", "xkcd.com/(%d+)" }, run = run } end
gpl-2.0
nasomi/darkstar
scripts/globals/items/cougar_baghnakhs.lua
41
1068
----------------------------------------- -- ID: 16702 -- Item: Cougar Baghnakhs -- Additional Effect: Ice Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(3,10); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_ICE, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_ICE,0); dmg = adjustForTarget(target,dmg,ELE_ICE); dmg = finalMagicNonSpellAdjustments(player,target,ELE_ICE,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_ICE_DAMAGE,message,dmg; end end;
gpl-3.0
shangjiyu/luci-with-extra
applications/luci-app-udpxy/luasrc/model/cbi/udpxy.lua
77
2104
-- Copyright 2014 Álvaro Fernández Rojas <noltari@gmail.com> -- Licensed to the public under the Apache License 2.0. m = Map("udpxy", "udpxy", translate("udpxy is a UDP-to-HTTP multicast traffic relay daemon, here you can configure the settings.")) s = m:section(TypedSection, "udpxy", "") s.addremove = true s.anonymous = false enable=s:option(Flag, "disabled", translate("Enabled")) enable.enabled="0" enable.disabled="1" enable.default = "1" enable.rmempty = false respawn=s:option(Flag, "respawn", translate("Respawn")) respawn.default = false verbose=s:option(Flag, "verbose", translate("Verbose")) verbose.default = false status=s:option(Flag, "status", translate("Status")) bind=s:option(Value, "bind", translate("Bind IP/Interface")) bind.rmempty = true bind.datatype = "or(ipaddr, network)" port=s:option(Value, "port", translate("Port")) port.rmempty = true port.datatype = "port" source=s:option(Value, "source", translate("Source IP/Interface")) source.rmempty = true source.datatype = "or(ipaddr, network)" max_clients=s:option(Value, "max_clients", translate("Max clients")) max_clients.rmempty = true max_clients.datatype = "range(1, 5000)" log_file=s:option(Value, "log_file", translate("Log file")) log_file.rmempty = true --log_file.datatype = "file" buffer_size=s:option(Value, "buffer_size", translate("Buffer size")) buffer_size.rmempty = true buffer_size.datatype = "range(4096,2097152)" buffer_messages=s:option(Value, "buffer_messages", translate("Buffer messages")) buffer_messages.rmempty = true buffer_messages.datatype = "or(-1, and(min(1), uinteger))" buffer_time=s:option(Value, "buffer_time", translate("Buffer time")) buffer_time.rmempty = true buffer_time.datatype = "or(-1, and(min(1), uinteger))" nice_increment=s:option(Value, "nice_increment", translate("Nice increment")) nice_increment.rmempty = true nice_increment.datatype = "or(and(max(-1), integer),and(min(1), integer))" mcsub_renew=s:option(Value, "mcsub_renew", translate("Multicast subscription renew")) mcsub_renew.rmempty = true mcsub_renew.datatype = "or(0, range(30, 64000))" return m
apache-2.0
dageq/Dage-Aliraqi
plugins/en-Dage_Aliraqi4.lua
1
1683
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY Dage Aliraqi ▀▄ ▄▀ ▀▄ ▄▀ BY Dage Aliraqi (@dageq) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY Dage Aliraqi ▀▄ ▄▀ ▀▄ ▄▀ help dev : اوامر المطور ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do local function run(msg, matches) if is_sudo(msg) and matches[1]== "help dev" then return [[ ✔️All orders to operate without setting / او ! ا🔸➖🔹➖🔸➖🔹➖🔸 ❣ sosuper : Upgrade Super Group ❣ add : To activate Group ❣ rem : To disable Group ❣ setowner : Raising Director of the total ❣ broadcast : Spread the word in all groups bot ❣ bot on : To run the bot to a certain group ❣ bot off : To extinguish the boot to a certain group ❣ addsudo : Add developer ❣ kickbot : To get out the bot of the group ❣ get file : Fetch the file from the server ❣ isup : Server with a link to improve the bot stop ❣ isup cron : Link with the server to improve server ا🔸➖🔹➖🔸➖🔹➖🔸 🃏🔺For inquiries:- Contact Developer :- ☢⚜ ✋🏿👇🏿 #Dev : @dageq ]] end if not is_sudo(msg) then return "Developers Only 😎🖕🏿" end end return { description = "Help list", usage = "Help list", patterns = { "(help dev)" }, run = run } end
gpl-2.0
nasomi/darkstar
scripts/zones/Heavens_Tower/npcs/Rhy_Epocan.lua
19
1628
----------------------------------- -- Area: Heavens Tower -- NPC: Rhy Epocan -- Involved in Mission 3-1 -- @pos 2 -48 14 242 ----------------------------------- package.loaded["scripts/zones/Heavens_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Heavens_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentMission = player:getCurrentMission(WINDURST); local MissionStatus = player:getVar("MissionStatus"); if (currentMission == TO_EACH_HIS_OWN_RIGHT and MissionStatus == 1) then player:startEvent(0x006B); elseif (currentMission == TO_EACH_HIS_OWN_RIGHT and MissionStatus == 2) then player:startEvent(0x006C); elseif (currentMission == TO_EACH_HIS_OWN_RIGHT and MissionStatus == 4) then player:startEvent(0x0072); else player:startEvent(0x005d); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); printf("RESULT: %u",option); if (csid == 0x006B) then player:setVar("MissionStatus",2); elseif (csid == 0x0072) then finishMissionTimeline(player,2,csid,option); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Ilrusi_Atoll/mobs/Cursed_Chest.lua
16
1381
----------------------------------- -- Area: Illrusi atoll -- NPC: Cursed Chest ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) local PX=target:getXPos(); local PY=target:getYPos(); local PZ=target:getZPos(); local MX=mob:getXPos(); local MY=mob:getYPos(); local MZ=mob:getZPos(); local distanceMin = 4; local distanceMax = 20; if (CheckForDrawnIn(MX,MY,MZ,PX,PY,PZ,distanceMin,distanceMax)==true) then target:setPos(mob:getXPos(),mob:getYPos(),mob:getZPos()); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) end; function CheckForDrawnIn(centerX,centerY,centerZ,playerX,playerY,playerZ,Rayon,maxRayon) local difX = playerX-centerX; local difY = playerY-centerY; local difZ = playerZ-centerZ; local Distance = math.sqrt( math.pow(difX,2) + math.pow(difY,2) + math.pow(difZ,2) ); --print(Distance); if (Distance > Rayon and Distance < maxRayon ) then return true; else return false; end end;
gpl-3.0
actboy168/YDWE
Development/Component/plugin/w3x2lni/script/backend/cli/unpack.lua
2
5912
local get_report = require 'share.report' local command = require 'backend.command' local messager = require 'share.messager' local lang = require 'share.lang' local builder = require 'map-builder' local core = require 'backend.sandbox_core' local w2l = core() local root = require 'backend.w2l_path' local base = require 'backend.base_path' local report = {} local messager_report = messager.report function messager.report(type, level, content, tip) messager_report(type, level, content, tip) local name = level .. type if not report[name] then report[name] = {} end table.insert(report[name], {content, tip}) end local function default_output(input) return input:parent_path() / (input:stem():string()) end local function exit(report) local err = 0 local warn = 0 for k, t in pairs(report) do if k:sub(1, 1) == '1' then err = #t elseif k:sub(1, 1) == '2' then warn = #t end end if err > 0 then messager.exit('error', lang.script.ERROR_COUNT:format(err, warn)) elseif warn > 0 then messager.exit('warning', lang.script.ERROR_COUNT:format(err, warn)) else messager.exit('success', lang.script.ERROR_COUNT:format(err, warn)) end return err, warn end local function absolute_path(path) if not path then return end path = fs.path(path) if not path:is_absolute() then return fs.absolute(path, base) end return fs.absolute(path) end local function loadListFile(buf) if not buf then return nil end local list = {} local start = 1 while true do local pos = buf:find('\r\n', start) if not pos then list[#list+1] = buf:sub(start) break end list[#list+1] = buf:sub(start, pos-1) start = pos + 2 end return list end local function mergeLists(...) local result = {} local mark = {} local lists = table.pack(...) for i = 1, lists.n do local list = lists[i] if list then for _, name in ipairs(list) do local lname = name:lower() if not mark[lname] then mark[lname] = true result[#result+1] = name end end end end return result end local function loadStaticfile() local list = {} local function search_tbl(tbl) for _, v in pairs(tbl) do if type(v) == 'table' then search_tbl(v) elseif type(v) == 'string' then list[#list+1] = v end end end search_tbl(w2l.info) return list end local function load_file(input_ar, output_ar) local extraPath = absolute_path(command['listfile']) local extraList if extraPath then extraList = loadListFile(io.load(extraPath)) end local mapList = loadListFile(input_ar:get('(listfile)')) local staticList = loadStaticfile() local list = mergeLists(mapList, extraList, staticList) local total = #list local clock = os.clock() for i, name in ipairs(list) do local buf = input_ar:get(name) if buf then output_ar:set(name, buf) end if os.clock() - clock > 0.1 then clock = os.clock() w2l.messager.text(lang.script.LOAD_MAP_FILE:format(i, total)) w2l.progress(i / total) end end local count = 0 for _ in pairs(output_ar) do count = count + 1 end if count ~= input_ar:number_of_files() then return false, lang.script.NEED_LIST_FILE end return true end local function remove(path) if fs.is_directory(path) then for c in path:list_directory() do remove(c) end end fs.remove(path) end local function createDir(path) if fs.exists(path) then remove(path) end fs.create_directories(path) end return function() w2l:set_messager(messager) messager.title 'Obj' messager.text(lang.script.INIT) messager.progress(0) w2l.log_path = root / 'log' fs.remove(w2l.log_path / 'report.log') local input = absolute_path(command[2]) local output = absolute_path(command[3]) if not input then w2l:failed(lang.script.OPEN_FAILED_NO_EXISTS) end messager.text(lang.script.OPEN_MAP) local input_ar, err = builder.load(input) if not input_ar then w2l:failed(err) end local output = output or default_output(input) createDir(output) local output_ar, err = builder.load(output, 'w') if not output_ar then w2l:failed(err) end w2l.input_ar = input_ar w2l.output_ar = output_ar local wts = w2l:frontend_wts(input_ar:get 'war3map.wts') local w3i = w2l:frontend_w3i(input_ar:get 'war3map.w3i', wts) local w3f = w2l:frontend_w3f(input_ar:get 'war3campaign.w3f', wts) messager.text(lang.script.LOAD_FILE) w2l.progress:start(0.6) local suc, err = load_file(input_ar, output_ar) if not suc then w2l:failed(err) end w2l.progress:finish() local plugin_loader = require 'backend.plugin' plugin_loader(w2l, function (source, plugin) w2l:add_plugin(source, plugin) end) messager.text(lang.script.CHECK_PLUGIN) w2l:call_plugin('on_unpack', output_ar) messager.text(lang.script.SAVE_FILE) w2l.progress:start(1.0) builder.save(w2l, w3i, w3f, input_ar, output_ar) w2l.progress:finish() local clock = os.clock() messager.text(lang.script.FINISH:format(clock)) local err, warn = exit(report) local setting = { input = input, output = output, mode = 'pack', } fs.create_directories(w2l.log_path) io.save(w2l.log_path / 'report.log', get_report(w2l, report, setting, clock, err, warn)) end
gpl-3.0
Hello23-Ygopro/ygopro-ds
expansions/script/c27002059.lua
1
1151
--BT2-053 Tiny Heroes Haru and Maki local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,SPECIAL_TRAIT_EARTHLING) ds.AddPlayProcedure(c,COLOR_BLUE,1,0) --power up ds.AddSingleAutoPlay(c,0,nil,scard.powtg,scard.powop,DS_EFFECT_FLAG_CARD_CHOOSE) end scard.dragon_ball_super_card=true scard.combo_cost=0 function scard.powtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) local c=e:GetHandler() if chkc then return chkc:IsLocation(DS_LOCATION_BATTLE) and chkc:IsControler(tp) and ds.BattleAreaFilter()(chkc) and chkc~=c end if chk==0 then return true end Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_POWERUP) Duel.SelectTarget(tp,ds.BattleAreaFilter(),tp,DS_LOCATION_BATTLE,0,1,1,c) end function scard.powop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if not tc or not tc:IsRelateToSkill(e) then return end ds.GainSkillUpdatePower(e:GetHandler(),tc,1,scard.powval) end function scard.powval(e,c) return Duel.GetMatchingGroupCount(ds.EnergyAreaFilter(),c:GetControler(),DS_LOCATION_ENERGY,0,nil)*1000 end
gpl-3.0
nasomi/darkstar
scripts/zones/Alzadaal_Undersea_Ruins/Zone.lua
21
6100
----------------------------------- -- -- Zone: Alzadaal_Undersea_Ruins (72) -- ----------------------------------- package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) zone:registerRegion(1, -329, -2, 483,-323, 0, 489); -- map 1 SE porter zone:registerRegion(2, -477, -2, 631,-471, 0, 636); -- map 1 NW porter zone:registerRegion(3, 110, -2,-556, 116, 0,-551); -- map 2 west porter (white) zone:registerRegion(4, 30, -2, 750, 36, 0, 757); -- map 3 west porter (blue) zone:registerRegion(5, 83, -2, 750, 90, 0, 757); -- map 3 east porter (white) zone:registerRegion(6, -329, -2, 150,-323, 0, 156); -- map 4 porter (white) zone:registerRegion(7, -208, -2,-556,-202, 0,-551); -- map 5 porter (white) zone:registerRegion(8, 323, -2, 591, 329, 0, 598); -- map 6 east porter (white) zone:registerRegion(9, 270, -2, 591, 276, 0, 598); -- map 6 west porter (blue) zone:registerRegion(10, 442, -2,-557, 450, 0,-550); -- map 7 porter (white) zone:registerRegion(11, -63,-10, 56, -57,-8, 62); -- map 8 NW/Arrapago porter zone:registerRegion(12, 17, -6, 56, 23,-4, 62); -- map 8 NE/Silver Sea/Khim porter zone:registerRegion(13, -63,-10, -23, -57,-8, -16); -- map 8 SW/Zhayolm/bird camp porter zone:registerRegion(14, 17, -6, -23, 23,-4, -16); -- map 8 SE/Bhaflau Porter zone:registerRegion(15,-556, -2, -77,-550, 0, -71); -- map 9 east porter (white) zone:registerRegion(16,-609, -2, -77,-603, 0, -71); -- map 9 west porter (blue) zone:registerRegion(17, 643, -2,-289, 649, 0,-283); -- map 10 east porter (blue) zone:registerRegion(18, 590, -2,-289, 597, 0,-283); -- map 10 west porter (white) zone:registerRegion(19, 603, -2, 522, 610, 0, 529); -- map 11 east porter (blue) zone:registerRegion(20, 550, -2, 522, 557, 0, 529); -- map 11 west porter (white) zone:registerRegion(21,-556, -2,-489,-550, 0,-483); -- map 12 east porter (white) zone:registerRegion(22,-610, -2,-489,-603, 0,-483); -- map 12 west porter (blue) zone:registerRegion(23,382, -1,-582,399, 1,-572); --mission 9 TOAU end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(222.798, -0.5, 19.872, 0); end return cs; end; ----------------------------------- -- afterZoneIn ----------------------------------- function afterZoneIn(player) player:entityVisualPacket("1pa1"); player:entityVisualPacket("1pb1"); player:entityVisualPacket("2pb1"); end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) player:startEvent(0x00CC); end, [2] = function (x) player:startEvent(0x00CD); end, [3] = function (x) player:startEvent(0x00C9); end, [4] = function (x) player:startEvent(0x00CB); end, [5] = function (x) player:startEvent(0x00CA); end, [6] = function (x) player:startEvent(0x00CE); end, [7] = function (x) player:startEvent(0x00D3); end, [8] = function (x) player:startEvent(0x00C8); end, [9] = function (x) player:startEvent(0x00C9); end, [10] = function (x) player:startEvent(0x00D5); end, [11] = function (x) player:startEvent(0x00DA); end, [12] = function (x) player:startEvent(0x00DD); end, [13] = function (x) player:startEvent(0x00DB); end, [14] = function (x) player:startEvent(0x00DC); end, [15] = function (x) player:startEvent(0x00CF); end, [16] = function (x) player:startEvent(0x00D0); end, [17] = function (x) player:startEvent(0x00D6); end, [18] = function (x) player:startEvent(0x00CF); end, [19] = function (x) player:startEvent(0x00CA); end, [20] = function (x) player:startEvent(0x00CF); end, [21] = function (x) player:startEvent(0x00CF); end, [22] = function (x) player:startEvent(0x00D2); end, [23] = function (x) if (player:getCurrentMission(TOAU) == UNDERSEA_SCOUTING and player:getVar("TOAUM9") ==0) then player:startEvent(0x0001); end end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) printf("CSID: %u",csid); printf("RESULT: %u",option); if (csid == 0x0001 and option == 10) then player:updateEvent(1,0,0,0,0,0,0); elseif (csid == 0x0001 and option == 2) then player:updateEvent(3,0,0,0,0,0,0); elseif (csid == 0x0001 and option == 3) then player:updateEvent(7,0,0,0,0,0,0); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) printf("CSID: %u",csid); printf("RESULT: %u",option); if (csid ==0x0001) then player:addKeyItem(ASTRAL_COMPASS); player:messageSpecial(KEYITEM_OBTAINED,ASTRAL_COMPASS); player:setVar("TOAUM9",0); player:completeMission(TOAU,UNDERSEA_SCOUTING); player:addMission(TOAU,ASTRAL_WAVES); end end;
gpl-3.0
nasomi/darkstar
scripts/globals/spells/foe_requiem_iv.lua
18
1625
----------------------------------------- -- Spell: Foe Requiem IV ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_REQUIEM; local duration = 111; local power = 4; local pCHR = caster:getStat(MOD_CHR); local mCHR = target:getStat(MOD_CHR); local dCHR = (pCHR - mCHR); local resm = applyResistance(caster,spell,target,dCHR,SINGING_SKILL,0); if (resm < 0.5) then spell:setMsg(85);--resist message return 1; end local iBoost = caster:getMod(MOD_REQUIEM_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end -- Try to overwrite weaker slow / haste if (canOverwrite(target, effect, power)) then -- overwrite them target:delStatusEffect(effect); target:addStatusEffect(effect,power,3,duration); spell:setMsg(237); else spell:setMsg(75); -- no effect end return effect; end;
gpl-3.0
nasomi/darkstar
scripts/zones/Sauromugue_Champaign/TextIDs.lua
9
1425
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6393; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6398; -- Obtained: <item>. GIL_OBTAINED = 6399; -- Obtained <number> gil. KEYITEM_OBTAINED = 6401; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7224; -- You can't fish here. -- Quest Dialogs MANY_TIGER_BONES = 7216; -- There are many tiger bones here... OLD_SABERTOOTH_DIALOG_I = 7222; -- You hear the distant roar of a tiger. It sounds as if the beast is approaching slowly... OLD_SABERTOOTH_DIALOG_II = 7223; -- The sound of the tiger's footsteps is growing louder. THF_AF_MOB = 7396; -- Something has come down from the tower! THF_AF_WALL_OFFSET = 7415; -- It is impossible to climb this wall with your bare hands. -- Other Dialog NOTHING_HAPPENS = 133; -- Nothing happens... NOTHING_OUT_OF_ORDINARY = 6412; -- There is nothing out of the ordinary here. -- conquest Base CONQUEST_BASE = 7057; -- Tallying conquest results... -- chocobo digging DIG_THROW_AWAY = 7237; -- You dig up ?Possible Special Code: 01??Possible Special Code: 01??Possible Special Code: 01? ?Possible Special Code: 01??Possible Special Code: 05?$?BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?, but your inventory is full. FIND_NOTHING = 7239; -- You dig and you dig, but find nothing.
gpl-3.0
nasomi/darkstar
scripts/zones/Valkurm_Dunes/npcs/Cavernous_Maw.lua
58
1887
----------------------------------- -- Area: Valkurm Dunes -- NPC: Cavernous Maw -- @pos 368.980, -0.443, -119.874 103 -- Teleports Players to Abyssea Misareaux ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/abyssea"); require("scripts/zones/Valkurm_Dunes/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_ABYSSEA == 1 and player:getMainLvl() >= 30) then local HasStone = getTravStonesTotal(player); if (HasStone >= 1 and player:getQuestStatus(ABYSSEA, DAWN_OF_DEATH) == QUEST_ACCEPTED and player:getQuestStatus(ABYSSEA, A_DELECTABLE_DEMON) == QUEST_AVAILABLE) then player:startEvent(56); else player:startEvent(55,0,1); -- No param = no entry. end else player:messageSpecial(NOTHING_HAPPENS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 56) then player:addQuest(ABYSSEA, A_DELECTABLE_DEMON); elseif (csid == 57) then -- Killed Cirein-croin elseif (csid == 55 and option == 1) then player:setPos(670,-15,318,119,216); end end;
gpl-3.0
coolflyreg/gs
3rd/skynet-mingw/service/datacenterd.lua
100
1928
local skynet = require "skynet" local command = {} local database = {} local wait_queue = {} local mode = {} local function query(db, key, ...) if key == nil then return db else return query(db[key], ...) end end function command.QUERY(key, ...) local d = database[key] if d then return query(d, ...) end end local function update(db, key, value, ...) if select("#",...) == 0 then local ret = db[key] db[key] = value return ret, value else if db[key] == nil then db[key] = {} end return update(db[key], value, ...) end end local function wakeup(db, key1, ...) if key1 == nil then return end local q = db[key1] if q == nil then return end if q[mode] == "queue" then db[key1] = nil if select("#", ...) ~= 1 then -- throw error because can't wake up a branch for _,response in ipairs(q) do response(false) end else return q end else -- it's branch return wakeup(q , ...) end end function command.UPDATE(...) local ret, value = update(database, ...) if ret or value == nil then return ret end local q = wakeup(wait_queue, ...) if q then for _, response in ipairs(q) do response(true,value) end end end local function waitfor(db, key1, key2, ...) if key2 == nil then -- push queue local q = db[key1] if q == nil then q = { [mode] = "queue" } db[key1] = q else assert(q[mode] == "queue") end table.insert(q, skynet.response()) else local q = db[key1] if q == nil then q = { [mode] = "branch" } db[key1] = q else assert(q[mode] == "branch") end return waitfor(q, key2, ...) end end skynet.start(function() skynet.dispatch("lua", function (_, _, cmd, ...) if cmd == "WAIT" then local ret = command.QUERY(...) if ret then skynet.ret(skynet.pack(ret)) else waitfor(wait_queue, ...) end else local f = assert(command[cmd]) skynet.ret(skynet.pack(f(...))) end end) end)
gpl-2.0
nasomi/darkstar
scripts/zones/Port_Jeuno/npcs/Zuah_Lepahnyu.lua
19
3977
----------------------------------- -- Area: Port Jeuno -- NPC: ZuahLepahnyu -- Title Change NPC -- @pos 0 0 8 246 ----------------------------------- require("scripts/globals/titles"); local title2 = { VISITOR_TO_ABYSSEA , FRIEND_OF_ABYSSEA , WARRIOR_OF_ABYSSEA , STORMER_OF_ABYSSEA , DEVASTATOR_OF_ABYSSEA , HERO_OF_ABYSSEA , CHAMPION_OF_ABYSSEA , CONQUEROR_OF_ABYSSEA , SAVIOR_OF_ABYSSEA , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { GOLDWING_SQUASHER , SILAGILITH_DETONATOR , SURTR_SMOTHERER , DREYRUK_PREDOMINATOR , SAMURSK_VITIATOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { YAANEI_CRASHER , KUTHAREI_UNHORSER , SIPPOY_CAPTURER , RANI_DECROWNER , ORTHRUS_DECAPITATOR , DRAGUA_SLAYER , BENNU_DEPLUMER , HEDJEDJET_DESTINGER , CUIJATENDER_DESICCATOR , BRULO_EXTINGUISHER , PANTOKRATOR_DISPROVER , APADEMAK_ANNIHILATOR , ISGEBIND_DEFROSTER , RESHEPH_ERADICATOR , EMPOUSA_EXPURGATOR , INDRIK_IMMOLATOR , OGOPOGO_OVERTURNER , RAJA_REGICIDE , ALFARD_DETOXIFIER , AZDAJA_ABOLISHER , AMPHITRITE_SHUCKER , FUATH_PURIFIER , KILLAKRIQ_EXCORIATOR , MAERE_BESTIRRER , WYRM_GOD_DEFIER , 0 , 0 , 0 } local title5 = { TITLACAUAN_DISMEMBERER , SMOK_DEFOGGER , AMHULUK_INUNDATER , PULVERIZER_DISMANTLER , DURINN_DECEIVER , KARKADANN_EXOCULATOR , 0 , 0 , 0 , 0 , 0 , TEMENOS_EMANCIPATOR , APOLLYON_RAZER , UMAGRHK_MANEMANGLER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { KARKINOS_CLAWCRUSHER , CARABOSSE_QUASHER , OVNI_OBLITERATOR , RUMINATOR_CONFOUNDER , FISTULE_DRAINER , TURUL_GROUNDER , BLOODEYE_BANISHER , SATIATOR_DEPRIVER , CHLORIS_UPROOTER , MYRMECOLEON_TAMER , GLAVOID_STAMPEDER , USURPER_DEPOSER , ULHUADSHI_DESICCATOR , ITZPAPALOTL_DECLAWER , SOBEK_MUMMIFIER , CIREINCROIN_HARPOONER , BUKHIS_TETHERER , SEDNA_TUSKBREAKER , CLEAVER_DISMANTLER , EXECUTIONER_DISMANTLER , SEVERER_DISMANTLER , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title7 = { HADHAYOSH_HALTERER , BRIAREUS_FELLER , ECCENTRICITY_EXPUNGER , KUKULKAN_DEFANGER , IRATHAM_CAPTURER , LACOVIE_CAPSIZER , LUSCA_DEBUNKER , TRISTITIA_DELIVERER , KETEA_BEACHER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x014A,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid==0x014A) then if (option > 0 and option <29) then if (player:delGil(200)) then player:setTitle( title2[option] ) end elseif (option > 256 and option <285) then if (player:delGil(300)) then player:setTitle( title3[option - 256] ) end elseif (option > 512 and option < 541) then if (player:delGil(400)) then player:setTitle( title4[option - 512] ) end elseif (option > 768 and option <797) then if (player:delGil(500)) then player:setTitle( title5[option - 768] ) end elseif (option > 1024 and option < 1053) then if (player:delGil(600)) then player:setTitle( title6[option - 1024] ) end elseif (option > 1280 and option < 1309) then if (player:delGil(700)) then player:setTitle( title7[option - 1280] ) end end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Norg/npcs/_700.lua
17
2923
----------------------------------- -- Area: Norg -- NPC: Oaken door (Gilgamesh's room) -- @pos 97 -7 -12 252 ----------------------------------- require("scripts/globals/missions"); require("scripts/globals/settings") ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ZilartMission = player:getCurrentMission(ZILART); local currentMission = player:getCurrentMission(BASTOK); local ZilartStatus = player:getVar("ZilartStatus"); -- Checked here to be fair to new players local DMEarrings = 0; for i=14739, 14743 do if (player:hasItem(i)) then DMEarrings = DMEarrings + 1; end end if (ZilartMission == WELCOME_TNORG) then player:startEvent(0x0002); -- Zilart Missions 2 elseif (ZilartMission == ROMAEVE and player:getVar("ZilartStatus") <= 1) then player:startEvent(0x0003); -- Zilart Missions 9 elseif (ZilartMission == THE_HALL_OF_THE_GODS) then player:startEvent(0x00a9); -- Zilart Missions 11 elseif (currentMission == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 1) then player:startEvent(0x0062); -- Bastok Mission 6-2 elseif (ZilartMission == THE_SEALED_SHRINE and ZilartStatus == 0 and DMEarrings <= NUMBER_OF_DM_EARRINGS) then player:startEvent(0x00ac); else player:startEvent(0x0005); end return 1; end; -- 0x00af 0x0005 0x0002 0x0003 0x00a9 0x00ac 0x00ce 0x00eb -- 0x00af 0x0000 0x0002 0x0003 0x0004 0x0007 0x0008 0x0009 0x000a 0x0062 0x0063 0x001d 0x000c 0x000d -- 0x0092 0x009e 0x00a4 0x00a9 0x00aa 0x00ab 0x00ac 0x00ad 0x00b0 0x00b1 0x00e8 0x00e9 0x00ea ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) printf("CSID: %u",csid); printf("RESULT: %u",option); if (csid == 0x0002 and option == 0) then player:completeMission(ZILART,WELCOME_TNORG); player:addMission(ZILART,KAZAMS_CHIEFTAINESS); elseif (csid == 0x0003 and option == 0) then player:setVar("ZilartStatus",0); player:completeMission(ZILART,ROMAEVE); player:addMission(ZILART,THE_TEMPLE_OF_DESOLATION); elseif (csid == 0x00a9 and option == 0) then player:completeMission(ZILART,THE_HALL_OF_THE_GODS); player:addMission(ZILART,THE_MITHRA_AND_THE_CRYSTAL); elseif (csid == 0x0062) then player:setVar("MissionStatus",2); elseif (csid == 0x00ac and bit.band(option, 0x40000000) == 0) then player:setVar("ZilartStatus",1); end end;
gpl-3.0
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/modules/base/luasrc/model/cbi/admin_network/proto_static.lua
60
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(9200)" metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger"
gpl-2.0
nasomi/darkstar
scripts/zones/Castle_Zvahl_Keep/npcs/Treasure_Chest.lua
19
3200
----------------------------------- -- Area: Castle Zvahl Keep -- NPC: Treasure Chest -- @zone 162 ----------------------------------- package.loaded["scripts/zones/Castle_Zvahl_Keep/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Castle_Zvahl_Keep/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1048,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1048,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); -- IMPORTANT ITEM: keyitem ----------- if (player:getQuestStatus(BASTOK,A_TEST_OF_TRUE_LOVE) == QUEST_ACCEPTED and player:hasKeyItem(UN_MOMENT) == false) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- 0 or 1 -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:setVar("ATestOfTrueLoveProgress",player:getVar("ATestOfTrueLoveProgress")+1); player:addKeyItem(UN_MOMENT); player:messageSpecial(KEYITEM_OBTAINED,UN_MOMENT); -- Un moment for A Test Of True Love quest else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1048); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Castle_Oztroja/npcs/Kaa_Toru_the_Just.lua
19
1581
----------------------------------- -- Area: Castle Oztroja -- NPC: Kaa Toru the Just -- Type: Mission NPC [ Windurst Mission 6-2 NPC ]~ -- @pos -100.188 -62.125 145.422 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(WINDURST) == SAINTLY_INVITATION and player:getVar("MissionStatus") == 2) then player:startEvent(0x002d,0,200); else player:startEvent(0x002e); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x002d) then player:delKeyItem(HOLY_ONES_INVITATION); player:addKeyItem(HOLY_ONES_OATH); player:messageSpecial(KEYITEM_OBTAINED,HOLY_ONES_OATH); player:addItem(13134); -- Ashura Necklace player:messageSpecial(ITEM_OBTAINED,13134); player:setVar("MissionStatus",3); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Selbina/npcs/Gibol.lua
17
1187
----------------------------------- -- Area: Selbina -- NPC: Gibol -- Guild Merchant NPC: Clothcrafting Guild -- @pos 13.591 -7.287 8.569 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Selbina/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(516,6,21,0)) then player:showText(npc,CLOTHCRAFT_SHOP_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/RuAun_Gardens/npcs/Treasure_Coffer.lua
17
3325
----------------------------------- -- Area: Ru'Aun Gardens -- NPC: Treasure Coffer -- @zone 130 -- @pos ----------------------------------- package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/RuAun_Gardens/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1058,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1058,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then -- IMPORTANT ITEM: AF Keyitems, AF Items, & Map ----------- local zone = player:getZoneID(); if (player:hasKeyItem(MAP_OF_THE_RUAUN_GARDENS) == false) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:addKeyItem(MAP_OF_THE_RUAUN_GARDENS); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_RUAUN_GARDENS); -- Map of the Ru'Aun Gardens (KI) else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]); player:messageSpecial(GIL_OBTAINED,loot[2]); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1058); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Port_Jeuno/npcs/Imasuke.lua
17
3152
----------------------------------- -- Area: Port Jeuno -- NPC: Imasuke -- Starts and Finishes Quest: The Antique Collector -- @zone 246 -- @pos -165 11 94 ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,THE_ANTIQUE_COLLECTOR) == QUEST_ACCEPTED and trade:hasItemQty(16631,1) == true and trade:getItemCount() == 1) then player:startEvent(0x000f); -- End quest end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) TheAntiqueCollector = player:getQuestStatus(JEUNO,THE_ANTIQUE_COLLECTOR); local circleOfTime = player:getQuestStatus(JEUNO,THE_CIRCLE_OF_TIME); if (circleOfTime == QUEST_ACCEPTED) then if (player:getVar("circleTime") == 1) then player:startEvent(0x1E); elseif (player:getVar("circleTime") == 2) then player:startEvent(0x1D); elseif (player:getVar("circleTime") == 3) then player:startEvent(0x20); elseif (player:getVar("circleTime") == 4) then player:startEvent(0x21); elseif (player:getVar("circleTime") == 5) then player:startEvent(0x1F); end elseif (player:getFameLevel(JEUNO) >= 3 and TheAntiqueCollector == QUEST_AVAILABLE) then player:startEvent(0x000d); -- Start quest elseif (TheAntiqueCollector == QUEST_ACCEPTED) then player:startEvent(0x000e); -- Mid CS else player:startEvent(0x000c); -- Standard dialog end --end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x000d and option == 1) then player:addQuest(JEUNO,THE_ANTIQUE_COLLECTOR); elseif (csid == 0x000f) then player:addTitle(TRADER_OF_ANTIQUITIES); if (player:hasKeyItem(MAP_OF_DELKFUTTS_TOWER) == false) then player:addKeyItem(MAP_OF_DELKFUTTS_TOWER); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_DELKFUTTS_TOWER); end player:addFame(JEUNO, JEUNO_FAME*30); player:tradeComplete(trade); player:completeQuest(JEUNO,THE_ANTIQUE_COLLECTOR); elseif (csid == 0x1D and option == 1) then player:setVar("circleTime",3); elseif (csid == 0x1E and option == 1) then player:setVar("circleTime",3); elseif (csid == 0x1E and option == 0) then player:setVar("circleTime",2); elseif (csid == 0x21) then player:setVar("circleTime",5); end end;
gpl-3.0
MatthewDwyer/botman
mudlet/profiles/newbot/scripts/lua_tables.lua
1
22061
function table.val_to_str ( v ) if "string" == type( v ) then v = string.gsub( v, "\n", "\\n" ) if string.match( string.gsub(v,"[^'\"]",""), '^"+$' ) then return "'" .. v .. "'" end return '"' .. string.gsub(v,'"', '\\"' ) .. '"' else return "table" == type( v ) and table.tostring( v ) or tostring( v ) end end function table.key_to_str ( k ) if "string" == type( k ) and string.match( k, "^[_%a][_%a%d]*$" ) then return k else return "[" .. table.val_to_str( k ) .. "]" end end function dumpTable( tbl ) local k, v, result, file local done = {} for k, v in ipairs( tbl ) do table.insert( result, table.val_to_str( v ) ) done[ k ] = true end for k, v in pairs( tbl ) do if not done[ k ] then table.insert( result, table.key_to_str( k ) .. "=" .. table.val_to_str( v ) ) end end file = io.open(homedir .. "/" .. "table_dump.txt", "a") file:write("{" .. table.concat( result, "," ) .. "}" .. "\n") file:close() end function loadBotMaintenance() botMaintenance = {} if isFile(homedir .. "/botMaintenance.lua") then table.load(homedir .. "/botMaintenance.lua", botMaintenance) end end function saveBotMaintenance() table.save(homedir .. "/botMaintenance.lua", botMaintenance) end function saveLuaTables(date, name) if date ~= nil then date = date .. "_" else date = "" end if name ~= nil then name = name .. "_" if name == "_" then name = "" end else name = "" end if date ~= "" or name ~= "" then -- save with a date or name table.save(homedir .. "/data_backup/" .. date .. name .. "badItems.lua", badItems) table.save(homedir .. "/data_backup/" .. date .. name .. "bases.lua", bases) table.save(homedir .. "/data_backup/" .. date .. name .. "customMessages.lua", customMessages) table.save(homedir .. "/data_backup/" .. date .. name .. "donors.lua", donors) table.save(homedir .. "/data_backup/" .. date .. name .. "friends.lua", friends) table.save(homedir .. "/data_backup/" .. date .. name .. "hotspots.lua", hotspots) table.save(homedir .. "/data_backup/" .. date .. name .. "locationCategories.lua", locationCategories) table.save(homedir .. "/data_backup/" .. date .. name .. "locations.lua", locations) table.save(homedir .. "/data_backup/" .. date .. name .. "modBotman.lua", modBotman) table.save(homedir .. "/data_backup/" .. date .. name .. "modVersions.lua", modVersions) table.save(homedir .. "/data_backup/" .. date .. name .. "players.lua", players) table.save(homedir .. "/data_backup/" .. date .. name .. "playersArchived.lua", playersArchived) table.save(homedir .. "/data_backup/" .. date .. name .. "resetRegions.lua", resetRegions) table.save(homedir .. "/data_backup/" .. date .. name .. "restrictedItems.lua", restrictedItems) table.save(homedir .. "/data_backup/" .. date .. name .. "server.lua", server) table.save(homedir .. "/data_backup/" .. date .. name .. "shop.lua", shop) table.save(homedir .. "/data_backup/" .. date .. name .. "shopCategories.lua", shopCategories) table.save(homedir .. "/data_backup/" .. date .. name .. "teleports.lua", teleports) table.save(homedir .. "/data_backup/" .. date .. name .. "villagers.lua", villagers) table.save(homedir .. "/data_backup/" .. date .. name .. "waypoints.lua", waypoints) else -- save without a date or name table.save(homedir .. "/data_backup/badItems.lua", badItems) table.save(homedir .. "/data_backup/bases.lua", bases) table.save(homedir .. "/data_backup/customMessages.lua", customMessages) table.save(homedir .. "/data_backup/donors.lua", donors) table.save(homedir .. "/data_backup/friends.lua", friends) table.save(homedir .. "/data_backup/hotspots.lua", hotspots) table.save(homedir .. "/data_backup/locationCategories.lua", locationCategories) table.save(homedir .. "/data_backup/locations.lua", locations) table.save(homedir .. "/data_backup/modBotman.lua", modBotman) table.save(homedir .. "/data_backup/modVersions.lua", modVersions) table.save(homedir .. "/data_backup/players.lua", players) table.save(homedir .. "/data_backup/playersArchived.lua", playersArchived) table.save(homedir .. "/data_backup/resetRegions.lua", resetRegions) table.save(homedir .. "/data_backup/restrictedItems.lua", restrictedItems) table.save(homedir .. "/data_backup/server.lua", server) table.save(homedir .. "/data_backup/shop.lua", shop) table.save(homedir .. "/data_backup/shopCategories.lua", shopCategories) table.save(homedir .. "/data_backup/teleports.lua", teleports) table.save(homedir .. "/data_backup/villagers.lua", villagers) table.save(homedir .. "/data_backup/waypoints.lua", waypoints) end table.save(homedir .. "/data_backup/igplayers.lua", igplayers) end function importServer() if debug then dbug("Importing Server") end conn:execute("DELETE FROM server)") conn:execute("INSERT INTO server (ircMain, ircAlerts, ircWatch, rules, shopCountdown, gimmePeace, allowGimme, mapSize, baseCooldown, MOTD, allowShop, chatColour, botName, lottery, allowWaypoints, prisonSize, baseSize) VALUES ('" .. escape(server.ircMain) .. "','" .. escape(server.ircAlerts) .. "','" .. escape(server.ircWatch) .. "','" .. escape(server.rules) .. "',0," .. dbBool(server.gimmePeace) .. "," .. dbBool(server.allowGimme) .. "," .. server.mapSize .. "," .. server.baseCooldown .. ",'" .. escape(server.MOTD) .. "'," .. dbBool(server.allowShop) .. ",'" .. server.chatColour .. "','" .. escape(server.botName) .. "'," .. server.lottery .. "," .. dbBool(server.allowWaypoints) .. "," .. server.prisonSize .. "," .. server.baseSize .. ")") -- reload from db to grab defaults for any missing data loadServer() openUserWindow(server.windowGMSG) openUserWindow(server.windowDebug) openUserWindow(server.windowLists) end function importShop() local k, v if debug then dbug("Importing Shop") end for k,v in pairs(shop) do if v.prizeLimit == nil then -- fixes an oops that caused bad shop data to be saved conn:execute("INSERT INTO shop (item, category, price, stock, idx, maxStock, variation, special, validated, units, quality) VALUES ('" .. escape(k) .. "','" .. escape(v.category) .. "'," .. v.price .. "," .. v.stock .. "," .. v.idx .. "," .. v.maxStock .. "," .. v.variation .. "," .. v.special .. ",1," .. v.units .. "," .. v.quality .. ")") end end if debug then dbug("Shop Shop Imported") end end function importShopCategories() local k, v if debug then dbug("Importing Shop Categories") end for k,v in pairs(shopCategories) do conn:execute("INSERT INTO shopCategories (category, idx, code) VALUES ('" .. escape(k) .. "'," .. v.idx .. ",'" .. v.code .. "')") end if debug then dbug("Shop Categories Imported") end end function importPlayers() local k, v if debug then dbug("Importing Players") end for k,v in pairs(players) do if debug then dbug("Importing " .. k .. " " .. v.id .. " " .. v.name) end conn:execute("INSERT INTO players (steam, id, name) VALUES (" .. k .. "," .. v.id .. ",'" .. escape(v.name) .. "')") conn:execute("INSERT INTO persistentQueue (steam, command) VALUES (" .. k .. ",'update player')") end for k,v in pairs(playersArchived) do if debug then dbug("Importing archived " .. k .. " " .. v.id .. " " .. v.name) end conn:execute("INSERT INTO playersArchived (steam, id, name) VALUES (" .. k .. "," .. v.id .. ",'" .. escape(v.name) .. "')") conn:execute("INSERT INTO persistentQueue (steam, command) VALUES (" .. k .. ",'update archived player')") end if debug then dbug("Players Imported") end end function importTeleports() local k, v if debug then dbug("Importing Teleports") end for k,v in pairs(teleports) do conn:execute("INSERT INTO teleports (name, active, public, oneway, friends, x, y, z, dx, dy, dz, owner) VALUES ('" .. escape(v.name) .. "'," .. dbBool(v.active) .. "," .. dbBool(v.public) .. "," .. dbBool(v.oneway) .. "," .. dbBool(v.friends) .. "," .. v.x .. "," .. v.y .. "," .. v.z .. "," .. v.dx .. "," .. v.dy .. "," .. v.owner .. ")") end end function importLocationCategories() local k, v if debug then dbug("Importing locationCategories") end for k,v in pairs(locationCategories) do conn:execute("INSERT INTO locationCategories (categoryName, minAccessLevel, maxAccessLevel) VALUES (" .. escape(k) .. "," .. v.minAccessLevel .. "," .. v.maxAccessLevel .. ")") end if debug then dbug("locationCategories Imported") end end function importLocations() local sql, fields, values, k, v if debug then dbug("Importing Locations") end for k,v in pairs(locations) do fields = "name, x, y, z, public, active" values = "'" .. escape(v.name) .. "'," .. v.x .. "," .. v.y .. "," .. v.z .. "," .. dbBool(v.public) .. "," .. dbBool(v.active) if v.protect ~= nil then fields = fields .. ", protected" values = values .. "," .. dbBool(v.protect) end if v.village ~= nil then fields = fields .. ", village" values = values .. "," .. dbBool(v.village) end if v.pvp ~= nil then fields = fields .. ", pvp" values = values .. "," .. dbBool(v.pvp) end if v.allowBase ~= nil then fields = fields .. ", allowBase" values = values .. "," .. dbBool(v.allowBase) end if v.accessLevel ~= nil then fields = fields .. ", accessLevel" values = values .. "," .. dbBool(v.accessLevel) end if v.owner ~= nil then fields = fields .. ", owner" values = values .. "," .. v.owner end if v.mayor ~= nil then fields = fields .. ", mayor" values = values .. "," .. v.mayor end if v.protectSize ~= nil then fields = fields .. ", protectSize" values = values .. "," .. v.protectSize end if v.killZombies ~= nil then fields = fields .. ", killZombies" values = values .. "," .. dbBool(v.killZombies) end sql = "INSERT INTO locations (" .. fields .. ") VALUES (" .. values .. ")" conn:execute(sql) end if debug then dbug("Locations Imported") end end function importFriends() local friendlist, i, max, k, v if debug then dbug("Importing Friends") end for k,v in pairs(friends) do if debug then dbug("Importing friends of " .. k) end if v.friends then friendlist = string.split(v.friends, ",") max = table.maxn(friendlist) for i=1,max,1 do if friendlist[i] ~= "" then conn:execute("INSERT INTO friends (steam, friend) VALUES (" .. k .. "," .. friendlist[i] .. ")") end end end end if debug then dbug("Friends Imported") end end function importVillagers() local k, v if debug then dbug("Importing Villagers") end for k,v in pairs(villagers) do conn:execute("INSERT INTO villagers (steam, village) VALUES (" .. k .. ",'" .. escape(v.village) .. "')") end if debug then dbug("Villagers Imported") end end function importHotspots() local k, v if debug then dbug("Importing Hotspots") end for k,v in pairs(hotspots) do if v.radius then conn:execute("INSERT INTO hotspots (hotspot, x, y, z, owner, size) VALUES ('" .. escape(v.message) .. "'," .. v.x .. "," .. v.y .. "," .. v.z .. "," .. v.owner .. "," .. v.radius .. ")") else conn:execute("INSERT INTO hotspots (hotspot, x, y, z, owner) VALUES ('" .. escape(v.message) .. "'," .. v.x .. "," .. v.y .. "," .. v.z .. "," .. v.owner .. ")") end end if debug then dbug("Hotspots Imported") end end function importResets() local k, v, temp if debug then dbug("Importing Reset Zones") end for k,v in pairs(resetRegions) do temp = string.split(k, "%.") conn:execute("INSERT INTO resetZones (region, x, z) VALUES ('" .. escape(k) .. "'," .. temp[2] .. "," .. temp[3] .. ")") end if debug then dbug("Resets Imported") end end function importBaditems() local k, v if debug then dbug("Importing Bad Items") end for k,v in pairs(badItems) do conn:execute("INSERT INTO badItems (item, action) VALUES ('" .. escape(k) .. "','" .. escape(v.action) .. "')") end if debug then dbug("Bad Items Imported") end end function importDonors() local k, v if debug then dbug("Importing Donors") end for k,v in pairs(donors) do conn:execute("INSERT INTO donors (steam, level, expiry) VALUES (" .. k .. "," .. v.level .. "," .. v.expiry .. ")") end if debug then dbug("Donors Imported") end end function importRestricteditems() local k, v if debug then dbug("Importing Restricted Items") end for k,v in pairs(restrictedItems) do conn:execute("INSERT INTO restrictedItems (item, qty, accessLevel, action) VALUES ('" .. escape(k) .. "'," .. v.qty .. "," .. v.accessLevel .. ",'" .. escape(v.action) .. "')") end if debug then dbug("Bad Items Imported") end end function importWaypoints() local k, v if debug then dbug("Importing Waypoints") end for k,v in pairs(waypoints) do conn:execute("INSERT INTO waypoints (steam, name, x, y, z, linked, shared) VALUES (" .. v.steam .. ",'" .. escape(v.name) .. "'," .. v.x .. "," .. v.y .. "," .. v.z .. "," .. v.linked .. "," .. dbBool(v.shared) .. ")") end if debug then dbug("Waypoints Imported") end end function importModVersions() local k, v if isFile(homedir .. "/data_backup/modVersions.lua") then modVersions = {} table.load(homedir .. "/data_backup/modVersions.lua", modVersions) server.coppi = false server.csmm = false server.SDXDetected = false server.ServerToolsDetected = false server.djkrose = false if not botMaintenance.modsInstalled then server.stompy = false server.allocs = false end for k,v in pairs(modVersions) do matchAll(k) end end end function importLuaData(pathPrefix, onlyImportThis, path) local k, v, id, temp, pos, importedAPlayer if debug then dbug("Importing Lua Tables") end importedAPlayer = false if not botman.silentDataImport then if pathPrefix then if onlyImportThis ~= "" then irc_chat(server.ircMain, "Restoring requested bot data from backup " .. pathPrefix) alertAdmins("Restoring requested bot data from backup " .. pathPrefix) else irc_chat(server.ircMain, "Restoring backup " .. pathPrefix) alertAdmins("Restoring backup " .. pathPrefix) end else if onlyImportThis ~= "" then irc_chat(server.ircMain, "Restoring requested bot data from last backup.") alertAdmins("Restoring requested bot data from last backup.") else irc_chat(server.ircMain, "Restoring last backup.") alertAdmins("Restoring last backup.") end end end if not path then path = homedir .. "/data_backup/" end if not pathPrefix then pathPrefix = "" end if not onlyImportThis then onlyImportThis = "" end if onlyImportThis == "" then if debug then dbug("Loading bad items") end badItems = {} table.load(path .. pathPrefix .. "badItems.lua", badItems) if debug then dbug("Loading friends") end friends = {} table.load(path .. pathPrefix .. "friends.lua", friends) if debug then dbug("Loading hotspots") end hotspots = {} table.load(path .. pathPrefix .. "hotspots.lua", hotspots) if debug then dbug("Loading locationCategories") end locationCategories = {} table.load(path .. pathPrefix .. "locationCategories.lua", locationCategories) if debug then dbug("Loading locations") end locations = {} table.load(path .. pathPrefix .. "locations.lua", locations) if debug then dbug("Loading players") end players = {} table.load(path .. pathPrefix .. "players.lua", players) if debug then dbug("Loading reset zones") end resetRegions = {} table.load(path .. pathPrefix .. "resetRegions.lua", resetRegions) if debug then dbug("Loading server") end table.load(path .. pathPrefix .. "server.lua", server) if debug then dbug("Loading shop categories") end shopCategories = {} table.load(path .. pathPrefix .. "shopCategories.lua", shopCategories) if debug then dbug("Loading shop") end shop = {} table.load(path .. pathPrefix .. "shop.lua", shop) if debug then dbug("Loading teleports") end teleports = {} table.load(path .. pathPrefix .. "teleports.lua", teleports) if debug then dbug("Loading villagers") end villagers = {} table.load(path .. pathPrefix .. "villagers.lua", villagers) if debug then dbug("Loading waypoints") end waypoints = {} table.load(path .. pathPrefix .. "waypoints.lua", waypoints) conn:execute("TRUNCATE badItems") conn:execute("TRUNCATE donors") conn:execute("TRUNCATE friends") conn:execute("TRUNCATE hotspots") conn:execute("TRUNCATE locations") conn:execute("TRUNCATE locationCategories") conn:execute("TRUNCATE players") conn:execute("TRUNCATE resetZones") conn:execute("TRUNCATE restrictedItems") conn:execute("TRUNCATE shopCategories") conn:execute("TRUNCATE shop") conn:execute("TRUNCATE teleports") conn:execute("TRUNCATE villagers") conn:execute("TRUNCATE waypoints") importBaditems() importDonors() importRestricteditems() importHotspots() importLocationCategories() importLocations() importResets() importTeleports() importVillagers() importFriends() importShopCategories() importShop() importWaypoints() importPlayers() else -- restore bases and cash for the players table playersTemp = {} table.load(path .. pathPrefix .. "players.lua", playersTemp) if string.find(onlyImportThis, " player ", nil, true) then pos = string.find(onlyImportThis, " player ") + 8 temp = string.sub(onlyImportThis, pos) temp = string.trim(temp) id = LookupPlayer(temp) end for k,v in pairs(playersTemp) do if string.find(onlyImportThis, "bases") then if players[k] then if players[k].homeX == 0 and players[k].homeZ == 0 then players[k].homeX = v.homeX players[k].homeY = v.homeY players[k].homeZ = v.homeZ players[k].protect = v.protect players[k].protectSize = v.protectSize end if players[k].home2X == 0 and players[k].home2Z == 0 then players[k].home2X = v.home2X players[k].home2Y = v.home2Y players[k].home2Z = v.home2Z players[k].protect2 = v.protect2 players[k].protect2Size = v.protect2Size end end end if string.find(onlyImportThis, "cash") then if players[k] then players[k].cash = players[k].cash + v.cash end end if string.find(onlyImportThis, "donors") then if players[k] then players[k].donor = v.donor players[k].donorLevel = v.donorLevel players[k].donorExpiry = v.donorExpiry end end if string.find(onlyImportThis, "colours") then if players[k] then players[k].chatColour = v.chatColour end end if string.find(onlyImportThis, " player ", nil, true) then if k == id then players[k] = {} players[k] = playersTemp[k] conn:execute("INSERT INTO players (steam) VALUES (" .. k .. ")") conn:execute("INSERT INTO persistentQueue (steam, command) VALUES (" .. k .. ",'update player')") importedAPlayer = true end end end playersTemp = nil end if string.find(onlyImportThis, "friends") then if debug then dbug("Loading friends") end friends = {} table.load(path .. pathPrefix .. "friends.lua", friends) conn:execute("TRUNCATE friends") importFriends() end if string.find(onlyImportThis, "hotspots") then if debug then dbug("Loading hotspots") end hotspots = {} table.load(path .. pathPrefix .. "hotspots.lua", hotspots) conn:execute("TRUNCATE hotspots") importHotspots() end if string.find(onlyImportThis, "locations") then if debug then dbug("Loading locationCategories") end locationCategories = {} table.load(path .. pathPrefix .. "locationCategories.lua", locationCategories) if debug then dbug("Loading locations") end locations = {} table.load(path .. pathPrefix .. "locations.lua", locations) conn:execute("TRUNCATE locations") conn:execute("TRUNCATE locationCategories") importLocationCategories() importLocations() end if string.find(onlyImportThis, "players") then if debug then dbug("Loading players") end players = {} table.load(path .. pathPrefix .. "players.lua", players) conn:execute("TRUNCATE players") importPlayers() end if string.find(onlyImportThis, "resets") then if debug then dbug("Loading reset zones") end resetRegions = {} table.load(path .. pathPrefix .. "resetRegions.lua", resetRegions) conn:execute("TRUNCATE resetZones") importResets() end if string.find(onlyImportThis, "shop") then if debug then dbug("Loading shop") end shop = {} table.load(path .. pathPrefix .. "shop.lua", shop) conn:execute("TRUNCATE shop") importShop() end if string.find(onlyImportThis, "teleports") then if debug then dbug("Loading teleports") end teleports = {} table.load(path .. pathPrefix .. "teleports.lua", teleports) conn:execute("TRUNCATE teleports") importTeleports() end if string.find(onlyImportThis, "villagers") then if debug then dbug("Loading villagers") end villagers = {} table.load(path .. pathPrefix .. "villagers.lua", villagers) conn:execute("TRUNCATE villagers") importVillagers() end if string.find(onlyImportThis, "waypoints") then if debug then dbug("Loading waypoints") end waypoints = {} table.load(path .. pathPrefix .. "waypoints.lua", waypoints) conn:execute("TRUNCATE waypoints") importWaypoints() end if debug then dbug("Import of Lua tables Complete") end if not botman.silentDataImport then if importedAPlayer then irc_chat(server.ircMain, "Player " .. id .. " " .. players[id].name .. " has been restored from backup.") alertAdmins("Player " .. id .. " " .. players[id].name .. " has been restored from backup.") else if string.find(onlyImportThis, " player ", nil, true) then irc_chat(server.ircMain, "Nothing restored. That player wasn't found. Either the name is wrong or the player is archived.") alertAdmins("Nothing restored. That player wasn't found. Either the name is wrong or the player is archived.") else irc_chat(server.ircMain, "Bot restore complete. It is now safe to turn off your modem. xD") alertAdmins("Bot restore complete. It is now safe to turn off your modem. xD") end end end end
gpl-3.0
nasomi/darkstar
scripts/globals/spells/aisha_ichi.lua
18
1599
----------------------------------------- -- Spell: Aisha: Ichi ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_ATTACK_DOWN; -- Base Stats local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Duration Calculation local resist = applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0); --Base power is 15 and is not affected by resistaces. local power = 15; --Calculates Resist Chance if (resist >= 0.125) then local duration = 120 * resist; if (duration >= 50) then -- Erases a weaker attack down and applies the stronger one local attackdown = target:getStatusEffect(effect); if (attackdown ~= nil) then if (attackdown:getPower() < power) then target:delStatusEffect(effect); target:addStatusEffect(effect,power,0,duration); spell:setMsg(237); else -- no effect spell:setMsg(75); end else target:addStatusEffect(effect,power,0,duration); spell:setMsg(237); end else spell:setMsg(85); end else spell:setMsg(284); end return effect; end;
gpl-3.0
nasomi/darkstar
scripts/zones/Port_San_dOria/npcs/Croumangue.lua
36
1884
----------------------------------- -- Area: Port San d'Oria -- NPC: Croumangue -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CROUMANGUE_SHOP_DIALOG); stock = {0x1159,837,1, --Grape Juice 0x1143,6300,1, --Mushroom Soup 0x1134,540,1, --Roast Trout 0x1147,270,2, --Apple Juice 0x11b9,468,2, --Roast Carp 0x11d0,1355,2, --Vegetable Soup 0x1104,180,2, --White Bread 0x110c,108,3, --Black Bread 0x11b7,360,3, --Boiled Crayfish 0x119d,10,3, --Distilled Water 0x1167,180,3} --Pebble Soup showNationShop(player, SANDORIA, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Upper_Jeuno/npcs/Luto_Mewrilah.lua
34
1856
----------------------------------- -- Area: Upper Jeuno -- NPC: Luto Mewrilah -- @zone 244 -- @pos -53 0 45 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,7) == false) then player:startEvent(10085); else player:startEvent(0x2732); -- Standard dialog end end; -- 0x272f 0x2730 0x2731 0x2732 0x2737 0x2739 0x273c 0x273a 0x2740 0x273d 0x273f 0x2757 0x2745 0x2741 -- 0x2742 0x2743 0x2754 0x2755 0x2756 0x275c 0x275d 0x2744 0x273b 0x273e 0x2747 0x2748 0x2749 0x274a -- 0x274c 0x274b 0x274d 0x274e 0x274f 0x2750 0x2753 0x2751 0x2752 0x2758 0x2759 0x275a 0x275b 0x275e -- 0x275f 0x2760 0x2761 0x2762 0x2765 0x27be 0x27bf ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 10085) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",7,true); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Norg/npcs/Washu.lua
17
3574
----------------------------------- -- Area: Norg -- NPC: Washu -- Involved in Quest: Yomi Okuri -- Starts and finishes Quest: Stop Your Whining -- @pos 49 -6 15 252 ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/zones/Norg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(OUTLANDS,YOMI_OKURI) == QUEST_ACCEPTED and player:getVar("yomiOkuriCS") == 2) then -- Trade Giant Sheep Meat, Frost Turnip, Bastore Sardine, Hecteyes Eye if (trade:hasItemQty(4372,1) and trade:hasItemQty(4382,1) and (trade:hasItemQty(4360,1) or trade:hasItemQty(5792,1)) and trade:hasItemQty(939,1) and trade:getItemCount() == 4) then player:startEvent(0x0096); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Whining = player:getQuestStatus(OUTLANDS,STOP_YOUR_WHINING); mLvl = player:getMainLvl(); if (player:getQuestStatus(OUTLANDS,YOMI_OKURI) == QUEST_ACCEPTED) then if (player:getVar("yomiOkuriCS") == 1) then player:startEvent(0x0094); elseif (player:getVar("yomiOkuriCS") == 2) then player:startEvent(0x0095); elseif (player:getVar("yomiOkuriCS") >= 3) then player:startEvent(0x0097); end elseif (Whining == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 4 and mLvl >= 10) then player:startEvent(0x0015); --Start Quest elseif (Whining == QUEST_ACCEPTED and player:hasKeyItem(EMPTY_BARREL) == true) then player:startEvent(0x0016); --Reminder Dialogue elseif (Whining == QUEST_ACCEPTED and player:hasKeyItem(BARREL_OF_OPOOPO_BREW) == true) then player:startEvent(0x0017); --Finish Quest elseif (Whining == QUEST_COMPLETED) then player:startEvent(0x0018); else player:startEvent(0x0050); end end; -- 0x0050 0x0015 0x0016 0x0017 0x0018 0x0094 0x0095 0x0096 0x0097 0x00d1 0x00d2 0x00dd 0x00de 0x00df ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0094) then player:setVar("yomiOkuriCS",2); elseif (csid == 0x0096) then player:tradeComplete(); player:addKeyItem(WASHUS_TASTY_WURST); player:messageSpecial(KEYITEM_OBTAINED,WASHUS_TASTY_WURST); player:setVar("yomiOkuriCS",3); elseif (csid == 0x0015 and option == 1) then player:addKeyItem(EMPTY_BARREL); --Empty Barrel player:addQuest(OUTLANDS,STOP_YOUR_WHINING); player:messageSpecial(KEYITEM_OBTAINED,EMPTY_BARREL); elseif (csid == 0x0017) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4952); else player:delKeyItem(BARREL_OF_OPOOPO_BREW); --Filled Barrel player:addItem(4952); -- Scroll of Hojo: Ichi player:messageSpecial(ITEM_OBTAINED,4952); -- Scroll of Hojo: Ichi player:addFame(OUTLANDS,NORG_FAME*75); player:addTitle(APPRENTICE_SOMMELIER); player:completeQuest(OUTLANDS,STOP_YOUR_WHINING); end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Lower_Jeuno/npcs/Tuh_Almobankha.lua
17
3832
----------------------------------- -- Area: Lower Jeuno -- NPC: Tuh Almobankha -- Title Change NPC -- @pos -14 0 -61 245 ----------------------------------- require("scripts/globals/titles"); local title2 = { BROWN_MAGE_GUINEA_PIG , BROWN_MAGIC_BYPRODUCT , RESEARCHER_OF_CLASSICS , TORCHBEARER , FORTUNETELLER_IN_TRAINING , CHOCOBO_TRAINER , CLOCK_TOWER_PRESERVATIONIST , LIFE_SAVER , CARD_COLLECTOR , TWOS_COMPANY , TRADER_OF_ANTIQUITIES , GOBLINS_EXCLUSIVE_FASHION_MANNEQUIN , TENSHODO_MEMBER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { ACTIVIST_FOR_KINDNESS , ENVOY_TO_THE_NORTH , EXORCIST_IN_TRAINING , FOOLS_ERRAND_RUNNER , STREET_SWEEPER , MERCY_ERRAND_RUNNER , BELIEVER_OF_ALTANA , TRADER_OF_MYSTERIES , WANDERING_MINSTREL , ANIMAL_TRAINER , HAVE_WINGS_WILL_FLY , ROD_RETRIEVER , DESTINED_FELLOW , TROUPE_BRILIOTH_DANCER , PROMISING_DANCER , STARDUST_DANCER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { TIMEKEEPER , BRINGER_OF_BLISS , PROFESSIONAL_LOAFER , TRADER_OF_RENOWN , HORIZON_BREAKER , SUMMIT_BREAKER , BROWN_BELT , DUCAL_DUPE , CHOCOBO_LOVE_GURU , PICKUP_ARTIST , WORTHY_OF_TRUST , A_FRIEND_INDEED , CHOCOROOKIE , CRYSTAL_STAKES_CUPHOLDER , WINNING_OWNER , VICTORIOUS_OWNER , TRIUMPHANT_OWNER , HIGH_ROLLER , FORTUNES_FAVORITE , CHOCOCHAMPION , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { PARAGON_OF_BEASTMASTER_EXCELLENCE , PARAGON_OF_BARD_EXCELLENCE , SKY_BREAKER , BLACK_BELT , GREEDALOX , CLOUD_BREAKER , STAR_BREAKER , ULTIMATE_CHAMPION_OF_THE_WORLD , DYNAMISJEUNO_INTERLOPER , DYNAMISBEAUCEDINE_INTERLOPER , DYNAMISXARCABARD_INTERLOPER , DYNAMISQUFIM_INTERLOPER , CONQUEROR_OF_FATE , SUPERHERO , SUPERHEROINE , ELEGANT_DANCER , DAZZLING_DANCE_DIVA , GRIMOIRE_BEARER , FELLOW_FORTIFIER , BUSHIN_ASPIRANT , BUSHIN_RYU_INHERITOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { GRAND_GREEDALOX , SILENCER_OF_THE_ECHO , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title7 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x271E,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid==0x271E) then if (option > 0 and option <29) then if (player:delGil(400)) then player:setTitle( title2[option] ) end elseif (option > 256 and option <285) then if (player:delGil(500)) then player:setTitle( title3[option - 256] ) end elseif (option > 512 and option < 541) then if (player:delGil(600)) then player:setTitle( title4[option - 512] ) end elseif (option > 768 and option <797) then if (player:delGil(700)) then player:setTitle( title5[option - 768] ) end elseif (option > 1024 and option < 1053) then if (player:delGil(800)) then player:setTitle( title6[option - 1024] ) end end end end;
gpl-3.0
Ingenious-Gaming/Starfall
lua/starfall/database.lua
4
1455
SF.DB = {} SF.DB.query = sql.Query SF.DB.querySingleValue = sql.QueryValue function SF.DB.querySingleRow ( query ) return sql.QueryRow( query, 0 ) end function SF.DB.escape ( str ) return sql.SQLStr( str ):sub( 2, -2 ) end local function queryMultiple ( statements ) local ret for _, v in pairs( statements ) do ret = sql.Query( v ) if ret == false then break end end return ret end -- check whether the tables exist and, if not, import the schema if sql.TableExists( "starfall_meta" ) then local version = sql.QueryValue( "SELECT value FROM starfall_meta WHERE key='schema_version'" ) if not version then error( "starfall tables exists but couldn't get schema version" ) elseif "0.1" ~= version then error( "starfall DB schema exists but is wrong version" ) end else sql.Begin() local result = queryMultiple( { [==[ -- bits of meta-information about Starfall CREATE TABLE starfall_meta ( key TEXT NOT NULL PRIMARY KEY, value TEXT NOT NULL )]==], [==[ INSERT INTO starfall_meta VALUES ("schema_version", "0.1")]==], [==[ -- grants permissions to roles CREATE TABLE starfall_perms_grants ( role INTEGER NOT NULL, -- 0 = user, 1 = admin, 2 = superadmin key TEXT NOT NULL, grant INTEGER CHECK (grant IN (0, 1, 2)), -- 0 = NEUTRAL, 1 = ALLOW, 2 = DENY PRIMARY KEY (role, key) )]==] } ) sql.Commit() if result == false then error( "error importing Starfall schema " .. sql.LastError() ) end end
bsd-3-clause
Ingenious-Gaming/Starfall
lua/starfall/editor.lua
1
51674
------------------------------------------------------------------------------- -- SF Editor -- Originally created by Jazzelhawk -- -- To do: -- Find new icons ------------------------------------------------------------------------------- SF.Editor = {} local addon_path = nil do local tbl = debug.getinfo( 1 ) local file = tbl.short_src addon_path = string.TrimRight( string.match( file, ".-/.-/" ), "/" ) end local function addToTable( addTo, addFrom ) for name, val in pairs( addFrom ) do addTo[ addVal and val or name ] = true end end local function createCodeMap () local map = {} map.Environment = {} map.Libraries = {} map.Types = {} for typ, tbl in pairs( SF.Types ) do if typ == "Environment" then addToTable( map.Environment, tbl.__methods ) elseif typ:find( "Library: " ) and type( tbl.__methods ) == "table" then typ = typ:Replace( "Library: ", "" ) map.Libraries[ typ ] = {} addToTable( map.Libraries[ typ ], tbl.__methods ) elseif typ ~= "Callback" and type( tbl.__methods ) == "table" then map.Types[ typ ] = {} addToTable( map.Types[ typ ], tbl.__methods ) end end if map.Libraries[ "globaltables" ] then map.Libraries[ "globaltables" ][ "player" ] = true end for k, v in pairs( map.Libraries ) do map.Environment[ k ] = nil end return map end if CLIENT then include( "sfderma.lua" ) -- Colors SF.Editor.colors = {} SF.Editor.colors.dark = Color( 36, 41, 53 ) SF.Editor.colors.meddark = Color( 48, 57, 92 ) SF.Editor.colors.med = Color( 78, 122, 199 ) SF.Editor.colors.medlight = Color( 127, 178, 240 ) SF.Editor.colors.light = Color( 173, 213, 247 ) -- Icons SF.Editor.icons = {} SF.Editor.icons.arrowr = Material( "radon/arrow_right.png", "noclamp smooth" ) SF.Editor.icons.arrowl = Material( "radon/arrow_left.png", "noclamp smooth" ) local defaultCode = [[--@name --@author --[[ Starfall Scripting Environment More info: http://inpstarfall.github.io/Starfall Github: http://github.com/INPStarfall/Starfall Reference Page: http://sf.inp.io Development Thread: http://www.wiremod.com/forum/developers-showcase/22739-starfall-processor.html Default Keyboard shortcuts: https://github.com/ajaxorg/ace/wiki/Default-Keyboard-Shortcuts ]].."]]" local invalid_filename_chars = { ["*"] = "", ["?"] = "", [">"] = "", ["<"] = "", ["|"] = "", ["\\"] = "", ['"'] = "", } CreateClientConVar( "sf_editor_width", 1100, true, false ) CreateClientConVar( "sf_editor_height", 760, true, false ) CreateClientConVar( "sf_editor_posx", ScrW() / 2 - 1100 / 2, true, false ) CreateClientConVar( "sf_editor_posy", ScrH() / 2 - 760 / 2, true, false ) CreateClientConVar( "sf_fileviewer_width", 263, true, false ) CreateClientConVar( "sf_fileviewer_height", 760, true, false ) CreateClientConVar( "sf_fileviewer_posx", ScrW() / 2 - 1100 / 2 - 263, true, false ) CreateClientConVar( "sf_fileviewer_posy", ScrH() / 2 - 760 / 2, true, false ) CreateClientConVar( "sf_fileviewer_locked", 1, true, false ) CreateClientConVar( "sf_modelviewer_width", 930, true, false ) CreateClientConVar( "sf_modelviewer_height", 615, true, false ) CreateClientConVar( "sf_modelviewer_posx", ScrW() / 2 - 930 / 2, true, false ) CreateClientConVar( "sf_modelviewer_posy", ScrH() / 2 - 615 / 2, true, false ) CreateClientConVar( "sf_editor_wordwrap", 1, true, false ) CreateClientConVar( "sf_editor_widgets", 1, true, false ) CreateClientConVar( "sf_editor_linenumbers", 1, true, false ) CreateClientConVar( "sf_editor_gutter", 1, true, false ) CreateClientConVar( "sf_editor_invisiblecharacters", 0, true, false ) CreateClientConVar( "sf_editor_indentguides", 1, true, false ) CreateClientConVar( "sf_editor_activeline", 1, true, false ) CreateClientConVar( "sf_editor_autocompletion", 1, true, false ) CreateClientConVar( "sf_editor_fixkeys", system.IsLinux() and 1 or 0, true, false ) --maybe osx too? need someone to check CreateClientConVar( "sf_editor_fixconsolebug", 0, true, false ) CreateClientConVar( "sf_editor_disablequitkeybind", 0, true, false ) CreateClientConVar( "sf_editor_disablelinefolding", 0, true, false ) CreateClientConVar( "sf_editor_fontsize", 13, true, false ) local aceFiles = {} local htmlEditorCode = nil function SF.Editor.init () if not SF.Editor.safeToInit then SF.AddNotify( LocalPlayer(), "Starfall is downloading editor files, please wait.", NOTIFY_GENERIC, 5, NOTIFYSOUND_DRIP3 ) return false end if SF.Editor.initialized or #aceFiles == 0 or htmlEditorCode == nil then SF.AddNotify( LocalPlayer(), "Failed to initialize Starfall editor.", NOTIFY_GENERIC, 5, NOTIFYSOUND_DRIP3 ) return false end if not file.Exists( "starfall", "DATA" ) then file.CreateDir( "starfall" ) end SF.Editor.editor = SF.Editor.createEditor() SF.Editor.fileViewer = SF.Editor.createFileViewer() SF.Editor.settingsWindow = SF.Editor.createSettingsWindow() SF.Editor.modelViewer = SF.Editor.createModelViewer() SF.Editor.runJS = function ( ... ) SF.Editor.editor.components.htmlPanel:QueueJavascript( ... ) end SF.Editor.updateSettings() local tabs = util.JSONToTable( file.Read( "sf_tabs.txt" ) or "" ) if tabs ~= nil and #tabs ~= 0 then for k, v in pairs( tabs ) do if type( v ) ~= "number" then SF.Editor.addTab( v.filename, v.code ) end end SF.Editor.selectTab( tabs.selectedTab or 1 ) else SF.Editor.addTab() end SF.Editor.editor:close() SF.Editor.initialized = true return true end function SF.Editor.open () if not SF.Editor.initialized then if not SF.Editor.init() then return end end SF.Editor.editor:open() if CanRunConsoleCommand() then RunConsoleCommand( "starfall_event", "editor_open" ) end end function SF.Editor.close () SF.Editor.editor:close() if CanRunConsoleCommand() then RunConsoleCommand( "starfall_event", "editor_close" ) end end function SF.Editor.updateCode () -- Incase anyone needs to force update the code SF.Editor.runJS( "console.log(\"RUNLUA:SF.Editor.getActiveTab().code = \\\"\" + addslashes(editor.getValue()) + \"\\\"\")" ) end function SF.Editor.getCode () return SF.Editor.getActiveTab().code end function SF.Editor.getOpenFile () return SF.Editor.getActiveTab().filename end function SF.Editor.getTabHolder () return SF.Editor.editor.components[ "tabHolder" ] end function SF.Editor.getActiveTab () return SF.Editor.getTabHolder():getActiveTab() end function SF.Editor.selectTab ( tab ) local tabHolder = SF.Editor.getTabHolder() if type( tab ) == "number" then tab = math.min( tab, #tabHolder.tabs ) tab = tabHolder.tabs[ tab ] end if tab == nil then SF.Editor.selectTab( 1 ) return end tabHolder:selectTab( tab ) SF.Editor.runJS( "selectEditSession("..tabHolder:getTabIndex( tab )..")" ) end function SF.Editor.addTab ( filename, code ) local name = filename or "generic" if code then local ppdata = {} SF.Preprocessor.ParseDirectives( "file", code, {}, ppdata ) if ppdata.scriptnames and ppdata.scriptnames.file ~= "" then name = ppdata.scriptnames.file end end code = code or defaultCode -- Settings to pass to editor when creating a new session local settings = util.TableToJSON({ wrap = GetConVarNumber( "sf_editor_wordwrap" ) }):JavascriptSafe() SF.Editor.runJS( "newEditSession(\"" .. string.JavascriptSafe( code or defaultCode ) .. "\", JSON.parse(\"" .. settings .. "\"))" ) local tab = SF.Editor.getTabHolder():addTab( name ) tab.code = code tab.name = name tab.filename = filename function tab:DoClick () SF.Editor.selectTab( self ) end SF.Editor.selectTab( tab ) end function SF.Editor.removeTab ( tab ) local tabHolder = SF.Editor.getTabHolder() if type( tab ) == "number" then tab = tabHolder.tabs[ tab ] end if tab == nil then return end tabHolder:removeTab( tab ) end function SF.Editor.saveTab ( tab ) if not tab.filename then SF.Editor.saveTabAs( tab ) return end local saveFile = "starfall/" .. tab.filename file.Write( saveFile, tab.code ) SF.Editor.updateTabName( tab ) SF.AddNotify( LocalPlayer(), "Starfall code saved as " .. saveFile .. ".", NOTIFY_GENERIC, 5, NOTIFYSOUND_DRIP3 ) end function SF.Editor.saveTabAs ( tab ) SF.Editor.updateTabName( tab ) local saveName = "" if tab.filename then saveName = string.StripExtension( tab.filename ) else saveName = tab.name or "generic" end Derma_StringRequestNoBlur( "Save File", "", saveName, function ( text ) if text == "" then return end text = string.gsub( text, ".", invalid_filename_chars ) local saveFile = "starfall/" .. text .. ".txt" file.Write( saveFile, tab.code ) SF.AddNotify( LocalPlayer(), "Starfall code saved as " .. saveFile .. ".", NOTIFY_GENERIC, 5, NOTIFYSOUND_DRIP3 ) SF.Editor.fileViewer.components[ "browser" ].tree:reloadTree() tab.filename = text .. ".txt" SF.Editor.updateTabName( tab ) end ) end function SF.Editor.doValidation ( forceShow ) local function valid () local code = SF.Editor.getActiveTab().code if code and code == "" then SF.Editor.runJS( "editor.session.clearAnnotations(); clearErrorLines()" ) return end local err = CompileString( code, "Validation", false ) if type( err ) ~= "string" then if forceShow then SF.AddNotify( LocalPlayer(), "Validation successful", NOTIFY_GENERIC, 3, NOTIFYSOUND_DRIP3 ) end SF.Editor.runJS( "editor.session.clearAnnotations(); clearErrorLines()" ) return end local row = tonumber( err:match( "%d+" ) ) - 1 local message = err:match( ": .+$" ):sub( 3 ) SF.Editor.runJS( string.format( "editor.session.setAnnotations([{row: %d, text: \"%s\", type: \"error\"}])", row, message:JavascriptSafe() ) ) SF.Editor.runJS( [[ clearErrorLines(); var Range = ace.require("ace/range").Range; var range = new Range(]] .. row .. [[, 1, ]] .. row .. [[, Infinity); editor.session.addMarker(range, "ace_error", "screenLine"); ]] ) if not forceShow then return end SF.Editor.runJS( "editor.session.unfold({row: " .. row .. ", column: 0})" ) SF.Editor.runJS( "editor.scrollToLine( " .. row .. ", true )" ) end if forceShow then valid() return end if not timer.Exists( "validationTimer" ) or ( timer.Exists( "validationTimer") and not timer.Adjust( "validationTimer", 0.5, 1, valid ) ) then timer.Remove( "validationTimer" ) timer.Create( "validationTimer", 0.5, 1, valid ) end end function SF.Editor.refreshTab ( tab ) local tabHolder = SF.Editor.getTabHolder() if type( tab ) == "number" then tab = tabHolder.tabs[ tab ] end if tab == nil then return end SF.Editor.updateTabName( tab ) local fileName = tab.filename local tabIndex = tabHolder:getTabIndex( tab ) if not fileName or not file.Exists( "starfall/" .. fileName, "DATA" ) then SF.AddNotify( LocalPlayer(), "Unable to refresh tab as file doesn't exist", NOTIFY_GENERIC, 5, NOTIFYSOUND_DRIP3 ) return end local fileData = file.Read( "starfall/" .. fileName, "DATA" ) SF.Editor.runJS( "editSessions[ " .. tabIndex .. " - 1 ].setValue( \"" .. fileData:JavascriptSafe() .. "\" )" ) SF.Editor.updateTabName( tab ) SF.AddNotify( LocalPlayer(), "Refreshed tab: " .. fileName, NOTIFY_GENERIC, 5, NOTIFYSOUND_DRIP3 ) end function SF.Editor.updateTabName ( tab ) local ppdata = {} SF.Preprocessor.ParseDirectives( "tab", tab.code, {}, ppdata ) if ppdata.scriptnames and ppdata.scriptnames.tab ~= "" then tab.name = ppdata.scriptnames.tab else tab.name = tab.filename or "generic" end tab:SetText( tab.name ) end function SF.Editor.createEditor () local editor = vgui.Create( "StarfallFrame" ) editor:DockPadding( 0, 0, 0, 0 ) editor:SetTitle( "Starfall Code Editor" ) editor:Center() function editor:OnKeyCodePressed ( keyCode ) if keyCode == KEY_S and ( input.IsKeyDown( KEY_LCONTROL ) or input.IsKeyDown( KEY_RCONTROL ) ) then SF.Editor.saveTab( SF.Editor.getActiveTab() ) elseif keyCode == KEY_Q and ( input.IsKeyDown( KEY_LCONTROL ) or input.IsKeyDown( KEY_RCONTROL ) ) and GetConVarNumber( "sf_editor_disablequitkeybind" ) == 0 then SF.Editor.close() end end local buttonHolder = editor.components[ "buttonHolder" ] buttonHolder:getButton( "Close" ).DoClick = function ( self ) SF.Editor.close() end buttonHolder:removeButton( "Lock" ) local buttonSaveExit = vgui.Create( "StarfallButton", buttonHolder ) buttonSaveExit:SetText( "Save and Exit" ) function buttonSaveExit:DoClick () SF.Editor.saveTab( SF.Editor.getActiveTab() ) SF.Editor.close() end buttonHolder:addButton( "SaveExit", buttonSaveExit ) local buttonSettings = vgui.Create( "StarfallButton", buttonHolder ) buttonSettings:SetText( "Settings" ) function buttonSettings:DoClick () if SF.Editor.settingsWindow:IsVisible() then SF.Editor.settingsWindow:close() else SF.Editor.settingsWindow:open() end end buttonHolder:addButton( "Settings", buttonSettings ) local buttonHelper = vgui.Create( "StarfallButton", buttonHolder ) buttonHelper:SetText( "SF Helper" ) function buttonHelper:DoClick () if SF.Helper.Frame and SF.Helper.Frame:IsVisible() then SF.Helper.Frame:close() else SF.Helper.show() end end buttonHolder:addButton( "Helper", buttonHelper ) local buttonModels = vgui.Create( "StarfallButton", buttonHolder ) buttonModels:SetText( "Model Viewer" ) function buttonModels:DoClick () if SF.Editor.modelViewer:IsVisible() then SF.Editor.modelViewer:close() else SF.Editor.modelViewer:open() end end buttonHolder:addButton( "Model Viewer", buttonModels ) local buttonFiles = vgui.Create( "StarfallButton", buttonHolder ) buttonFiles:SetText( "Files" ) function buttonFiles:DoClick () if SF.Editor.fileViewer:IsVisible() then SF.Editor.fileViewer:close() else SF.Editor.fileViewer:open() end end buttonHolder:addButton( "Files", buttonFiles ) local buttonSaveAs = vgui.Create( "StarfallButton", buttonHolder ) buttonSaveAs:SetText( "Save As" ) function buttonSaveAs:DoClick () SF.Editor.saveTabAs( SF.Editor.getActiveTab() ) end buttonHolder:addButton( "SaveAs", buttonSaveAs ) local buttonSave = vgui.Create( "StarfallButton", buttonHolder ) buttonSave:SetText( "Save" ) function buttonSave:DoClick () SF.Editor.saveTab( SF.Editor.getActiveTab() ) end buttonHolder:addButton( "Save", buttonSave ) local buttonNewFile = vgui.Create( "StarfallButton", buttonHolder ) buttonNewFile:SetText( "New tab" ) function buttonNewFile:DoClick () SF.Editor.addTab() end buttonHolder:addButton( "NewFile", buttonNewFile ) local buttonCloseTab = vgui.Create( "StarfallButton", buttonHolder ) buttonCloseTab:SetText( "Close tab" ) function buttonCloseTab:DoClick () SF.Editor.removeTab( SF.Editor.getActiveTab() ) end buttonHolder:addButton( "CloseTab", buttonCloseTab ) local html = vgui.Create( "DHTML", editor ) html:Dock( FILL ) html:DockMargin( 5, 59, 5, 5 ) html:SetKeyboardInputEnabled( true ) html:SetMouseInputEnabled( true ) htmlEditorCode = htmlEditorCode:Replace( "<script>//replace//</script>", table.concat( aceFiles ) ) html:SetHTML( htmlEditorCode ) html:SetAllowLua( true ) html:QueueJavascript( "codeMap = JSON.parse(\"" .. util.TableToJSON( SF.Editor.codeMap ):JavascriptSafe() .. "\")" ) local libs = table.GetKeys( SF.Editor.codeMap.Libraries ) local functions = table.GetKeys( SF.Editor.codeMap.Environment ) for k, v in pairs( SF.Editor.codeMap.Libraries ) do functions = table.Add( functions, table.GetKeys( v ) ) end for k, v in pairs( SF.Editor.codeMap.Types ) do functions = table.Add( functions, table.GetKeys( v ) ) end html:QueueJavascript( "createStarfallMode(\"" .. table.concat( libs, "|" ) .. "\", \"" .. table.concat( table.Add( table.Copy( functions ), libs ), "|" ) .. "\")" ) function html:OnKeyCodePressed ( key, notfirst ) local function repeatKey () timer.Create( "repeatKey"..key, not notfirst and 0.5 or 0.02, 1, function () self:OnKeyCodePressed( key, true ) end ) end if GetConVarNumber( "sf_editor_fixkeys" ) == 0 then return end if ( input.IsKeyDown( KEY_LSHIFT ) or input.IsKeyDown( KEY_RSHIFT ) ) and ( input.IsKeyDown( KEY_LCONTROL ) or input.IsKeyDown( KEY_RCONTROL ) ) then if key == KEY_UP and input.IsKeyDown( key ) then self:QueueJavascript( "editor.modifyNumber(1)" ) repeatKey() elseif key == KEY_DOWN and input.IsKeyDown( key ) then self:QueueJavascript( "editor.modifyNumber(-1)" ) repeatKey() elseif key == KEY_LEFT and input.IsKeyDown( key ) then self:QueueJavascript( "editor.selection.selectWordLeft()" ) repeatKey() elseif key == KEY_RIGHT and input.IsKeyDown( key ) then self:QueueJavascript( "editor.selection.selectWordRight()" ) repeatKey() end elseif input.IsKeyDown( KEY_LSHIFT ) or input.IsKeyDown( KEY_RSHIFT ) then if key == KEY_LEFT and input.IsKeyDown( key ) then self:QueueJavascript( "editor.selection.selectLeft()" ) repeatKey() elseif key == KEY_RIGHT and input.IsKeyDown( key ) then self:QueueJavascript( "editor.selection.selectRight()" ) repeatKey() elseif key == KEY_UP and input.IsKeyDown( key ) then self:QueueJavascript( "editor.selection.selectUp()" ) repeatKey() elseif key == KEY_DOWN and input.IsKeyDown( key ) then self:QueueJavascript( "editor.selection.selectDown()" ) repeatKey() elseif key == KEY_HOME and input.IsKeyDown( key ) then self:QueueJavascript( "editor.selection.selectLineStart()" ) repeatKey() elseif key == KEY_END and input.IsKeyDown( key ) then self:QueueJavascript( "editor.selection.selectLineEnd()" ) repeatKey() end elseif input.IsKeyDown( KEY_LCONTROL ) or input.IsKeyDown( KEY_RCONTROL ) then if key == KEY_LEFT and input.IsKeyDown( key ) then self:QueueJavascript( "editor.navigateWordLeft()" ) repeatKey() elseif key == KEY_RIGHT and input.IsKeyDown( key ) then self:QueueJavascript( "editor.navigateWordRight()" ) repeatKey() elseif key == KEY_BACKSPACE and input.IsKeyDown( key ) then self:QueueJavascript( "editor.removeWordLeft()" ) repeatKey() elseif key == KEY_DELETE and input.IsKeyDown( key ) then self:QueueJavascript( "editor.removeWordRight()" ) repeatKey() elseif key == KEY_SPACE and input.IsKeyDown( key ) then SF.Editor.doValidation( true ) elseif key == KEY_C and input.IsKeyDown( key ) then self:QueueJavascript( "console.log(\"RUNLUA:SetClipboardText(\\\"\"+ addslashes(editor.getSelectedText()) +\"\\\")\")" ) end elseif input.IsKeyDown( KEY_LALT ) or input.IsKeyDown( KEY_RALT ) then if key == KEY_UP and input.IsKeyDown( key ) then self:QueueJavascript( "editor.moveLinesUp()" ) repeatKey() elseif key == KEY_DOWN and input.IsKeyDown( key ) then self:QueueJavascript( "editor.moveLinesDown()" ) repeatKey() end else if key == KEY_LEFT and input.IsKeyDown( key ) then self:QueueJavascript( "editor.navigateLeft(1)" ) repeatKey() elseif key == KEY_RIGHT and input.IsKeyDown( key ) then self:QueueJavascript( "editor.navigateRight(1)" ) repeatKey() elseif key == KEY_UP and input.IsKeyDown( key ) then self:QueueJavascript( "editor.navigateUp(1)" ) repeatKey() elseif key == KEY_DOWN and input.IsKeyDown( key ) then self:QueueJavascript( "editor.navigateDown(1)" ) repeatKey() elseif key == KEY_HOME and input.IsKeyDown( key ) then self:QueueJavascript( "editor.navigateLineStart()" ) repeatKey() elseif key == KEY_END and input.IsKeyDown( key ) then self:QueueJavascript( "editor.navigateLineEnd()" ) repeatKey() elseif key == KEY_PAGEUP and input.IsKeyDown( key ) then self:QueueJavascript( "editor.navigateFileStart()" ) repeatKey() elseif key == KEY_PAGEDOWN and input.IsKeyDown( key ) then self:QueueJavascript( "editor.navigateFileEnd()" ) repeatKey() elseif key == KEY_BACKSPACE and input.IsKeyDown( key ) then self:QueueJavascript( "editor.remove('left')" ) repeatKey() elseif key == KEY_DELETE and input.IsKeyDown( key ) then self:QueueJavascript( "editor.remove('right')" ) repeatKey() elseif key == KEY_ENTER and input.IsKeyDown( key ) then self:QueueJavascript( "editor.splitLine(); editor.navigateDown(1); editor.navigateLineStart()" ) repeatKey() elseif key == KEY_INSERT and input.IsKeyDown( key ) then self:QueueJavascript( "editor.toggleOverwrite()" ) repeatKey() elseif key == KEY_TAB and input.IsKeyDown( key ) then self:QueueJavascript( "editor.indent()" ) repeatKey() end end end editor:AddComponent( "htmlPanel", html ) function editor:OnOpen () html:Call( "editor.focus()" ) html:RequestFocus() end local tabHolder = vgui.Create( "StarfallTabHolder", editor ) tabHolder:SetPos( 5, 30 ) tabHolder.menuoptions[ #tabHolder.menuoptions + 1 ] = { "", "SPACER" } tabHolder.menuoptions[ #tabHolder.menuoptions + 1 ] = { "Save", function () if not tabHolder.targetTab then return end SF.Editor.saveTab( tabHolder.targetTab ) tabHolder.targetTab = nil end } tabHolder.menuoptions[ #tabHolder.menuoptions + 1 ] = { "Save As", function () if not tabHolder.targetTab then return end SF.Editor.saveTabAs( tabHolder.targetTab ) tabHolder.targetTab = nil end } tabHolder.menuoptions[ #tabHolder.menuoptions + 1 ] = { "", "SPACER" } tabHolder.menuoptions[ #tabHolder.menuoptions + 1 ] = { "Refresh", function () if not tabHolder.targetTab then return end SF.Editor.refreshTab( tabHolder.targetTab ) tabHolder.targetTab = nil end } function tabHolder:OnRemoveTab ( tabIndex ) SF.Editor.runJS( "removeEditSession("..tabIndex..")" ) if #self.tabs == 0 then SF.Editor.addTab() end SF.Editor.selectTab( tabIndex ) end editor:AddComponent( "tabHolder", tabHolder ) function editor:OnClose () local tabs = {} for k, v in pairs( tabHolder.tabs ) do tabs[ k ] = {} tabs[ k ].filename = v.filename tabs[ k ].code = v.code end tabs.selectedTab = SF.Editor.getTabHolder():getTabIndex( SF.Editor.getActiveTab() ) file.Write( "sf_tabs.txt", util.TableToJSON( tabs ) ) SF.Editor.saveSettings() local activeWep = LocalPlayer():GetActiveWeapon() if IsValid( activeWep ) and activeWep:GetClass() == "gmod_tool" and activeWep.Mode == "starfall_processor" then local model = nil local ppdata = {} SF.Preprocessor.ParseDirectives( "file", SF.Editor.getCode(), {}, ppdata ) if ppdata.models and ppdata.models.file ~= "" then model = ppdata.models.file end local tool = activeWep:GetToolObject( "starfall_processor" ) tool.ClientConVar[ "HologramModel" ] = model end end return editor end function SF.Editor.createFileViewer () local fileViewer = vgui.Create( "StarfallFrame" ) fileViewer:SetSize( 200, 600 ) fileViewer:SetTitle( "Starfall File Viewer" ) fileViewer:Center() local browser = vgui.Create( "StarfallFileBrowser", fileViewer ) local searchBox, tree = browser:getComponents() tree:setup( "starfall" ) function tree:OnNodeSelected ( node ) if not node:GetFileName() or string.GetExtensionFromFilename( node:GetFileName() ) ~= "txt" then return end local fileName = string.gsub( node:GetFileName(), "starfall/", "", 1 ) local code = file.Read( node:GetFileName(), "DATA" ) for k, v in pairs( SF.Editor.getTabHolder().tabs ) do if v.filename == fileName and v.code == code then SF.Editor.selectTab( v ) return end end SF.Editor.addTab( fileName, code ) end fileViewer:AddComponent( "browser", browser ) local buttonHolder = fileViewer.components[ "buttonHolder" ] local buttonLock = buttonHolder:getButton( "Lock" ) buttonLock._DoClick = buttonLock.DoClick buttonLock.DoClick = function ( self ) self:_DoClick() SF.Editor.saveSettings() end local buttonRefresh = vgui.Create( "StarfallButton", buttonHolder ) buttonRefresh:SetText( "Refresh" ) buttonRefresh:SetHoverColor( Color( 7, 70, 0 ) ) buttonRefresh:SetColor( Color( 26, 104, 17 ) ) buttonRefresh:SetLabelColor( Color( 103, 155, 153 ) ) function buttonRefresh:DoClick () tree:reloadTree() searchBox:SetValue( "Search..." ) end buttonHolder:addButton( "Refresh", buttonRefresh ) function fileViewer:OnOpen () SF.Editor.editor.components[ "buttonHolder" ]:getButton( "Files" ).active = true end function fileViewer:OnClose () SF.Editor.editor.components[ "buttonHolder" ]:getButton( "Files" ).active = false SF.Editor.saveSettings() end return fileViewer end function SF.Editor.createSettingsWindow () local frame = vgui.Create( "StarfallFrame" ) frame:SetSize( 200, 400 ) frame:SetTitle( "Starfall Settings" ) frame:Center() local panel = vgui.Create( "StarfallPanel", frame ) panel:Dock( FILL ) panel:DockMargin( 0, 5, 0, 0 ) frame:AddComponent( "panel", panel ) local scrollPanel = vgui.Create( "DScrollPanel", panel ) scrollPanel:Dock( FILL ) scrollPanel:SetPaintBackgroundEnabled( false ) local form = vgui.Create( "DForm", scrollPanel ) form:Dock( FILL ) form:DockPadding( 0, 10, 0, 10 ) form.Header:SetVisible( false ) form.Paint = function () end local function setDoClick ( panel ) function panel:OnChange () SF.Editor.saveSettings() timer.Simple( 0.1, function () SF.Editor.updateSettings() end ) end return panel end local function setWang( wang, label ) function wang:OnValueChanged() SF.Editor.saveSettings() timer.Simple( 0.1, function () SF.Editor.updateSettings() end ) end wang:GetParent():DockPadding( 10, 1, 10, 1 ) wang:Dock( RIGHT ) return wang, label end setWang( form:NumberWang( "Font size", "sf_editor_fontsize", 5, 40 ) ) setDoClick( form:CheckBox( "Enable word wrap", "sf_editor_wordwrap" ) ) setDoClick( form:CheckBox( "Show fold widgets", "sf_editor_widgets" ) ) setDoClick( form:CheckBox( "Show line numbers", "sf_editor_linenumbers" ) ) setDoClick( form:CheckBox( "Show gutter", "sf_editor_gutter" ) ) setDoClick( form:CheckBox( "Show invisible characters", "sf_editor_invisiblecharacters" ) ) setDoClick( form:CheckBox( "Show indenting guides", "sf_editor_indentguides" ) ) setDoClick( form:CheckBox( "Highlight active line", "sf_editor_activeline" ) ) setDoClick( form:CheckBox( "Auto completion", "sf_editor_autocompletion" ) ) setDoClick( form:CheckBox( "Fix keys not working on Linux", "sf_editor_fixkeys" ) ):SetTooltip( "Some keys don't work with the editor on Linux\nEg. Enter, Tab, Backspace, Arrow keys etc..." ) setDoClick( form:CheckBox( "Fix console bug", "sf_editor_fixconsolebug" ) ):SetTooltip( "Fix console opening when pressing ' or @ (UK Keyboad layout)" ) setDoClick( form:CheckBox( "Disable quit keybind", "sf_editor_disablequitkeybind" ) ):SetTooltip( "Ctrl-Q" ) setDoClick( form:CheckBox( "Disable line folding keybinds", "sf_editor_disablelinefolding" ) ) function frame:OnOpen () SF.Editor.editor.components[ "buttonHolder" ]:getButton( "Settings" ).active = true end function frame:OnClose () SF.Editor.editor.components[ "buttonHolder" ]:getButton( "Settings" ).active = false end return frame end function SF.Editor.createModelViewer () local frame = vgui.Create( "StarfallFrame" ) frame:SetTitle( "Model Viewer - Click an icon to insert model filename into editor" ) frame:SetVisible( false ) frame:Center() function frame:OnOpen () SF.Editor.editor.components[ "buttonHolder" ]:getButton( "Model Viewer" ).active = true end function frame:OnClose () SF.Editor.editor.components[ "buttonHolder" ]:getButton( "Model Viewer" ).active = false SF.Editor.saveSettings() end local sidebarPanel = vgui.Create( "StarfallPanel", frame ) sidebarPanel:Dock( LEFT ) sidebarPanel:SetSize( 190, 10 ) sidebarPanel:DockMargin( 0, 0, 4, 0 ) sidebarPanel.Paint = function () end frame.ContentNavBar = vgui.Create( "ContentSidebar", sidebarPanel ) frame.ContentNavBar:Dock( FILL ) frame.ContentNavBar:DockMargin( 0, 0, 0, 0 ) frame.ContentNavBar.Tree:SetBackgroundColor( Color( 240, 240, 240 ) ) frame.ContentNavBar.Tree.OnNodeSelected = function ( self, node ) if not IsValid( node.propPanel ) then return end if IsValid( frame.PropPanel.selected ) then frame.PropPanel.selected:SetVisible( false ) frame.PropPanel.selected = nil end frame.PropPanel.selected = node.propPanel frame.PropPanel.selected:Dock( FILL ) frame.PropPanel.selected:SetVisible( true ) frame.PropPanel:InvalidateParent() frame.HorizontalDivider:SetRight( frame.PropPanel.selected ) end frame.PropPanel = vgui.Create( "StarfallPanel", frame ) frame.PropPanel:Dock( FILL ) function frame.PropPanel:Paint ( w, h ) draw.RoundedBox( 0, 0, 0, w, h, Color( 240, 240, 240 ) ) end frame.HorizontalDivider = vgui.Create( "DHorizontalDivider", frame ) frame.HorizontalDivider:Dock( FILL ) frame.HorizontalDivider:SetLeftWidth( 175 ) frame.HorizontalDivider:SetLeftMin( 175 ) frame.HorizontalDivider:SetRightMin( 450 ) frame.HorizontalDivider:SetLeft( sidebarPanel ) frame.HorizontalDivider:SetRight( frame.PropPanel ) local root = frame.ContentNavBar.Tree:AddNode( "Your Spawnlists" ) root:SetExpanded( true ) root.info = {} root.info.id = 0 local function hasGame ( name ) for k, v in pairs( engine.GetGames() ) do if v.folder == name and v.mounted then return true end end return false end local function addModel ( container, obj ) local icon = vgui.Create( "SpawnIcon", container ) if ( obj.body ) then obj.body = string.Trim( tostring(obj.body), "B" ) end if ( obj.wide ) then icon:SetWide( obj.wide ) end if ( obj.tall ) then icon:SetTall( obj.tall ) end icon:InvalidateLayout( true ) icon:SetModel( obj.model, obj.skin or 0, obj.body ) icon:SetTooltip( string.Replace( string.GetFileFromFilename( obj.model ), ".mdl", "" ) ) icon.DoClick = function ( icon ) SF.Editor.runJS( "editor.insert(\"" .. string.gsub( obj.model, "\\", "/" ):JavascriptSafe() .. "\")" ) SF.AddNotify( LocalPlayer(), "\"" .. string.gsub( obj.model, "\\", "/" ) .. "\" inserted into editor.", NOTIFY_GENERIC, 5, NOTIFYSOUND_DRIP1 ) frame:close() end icon.OpenMenu = function ( icon ) local menu = DermaMenu() local submenu = menu:AddSubMenu( "Re-Render", function () icon:RebuildSpawnIcon() end ) submenu:AddOption( "This Icon", function () icon:RebuildSpawnIcon() end ) submenu:AddOption( "All Icons", function () container:RebuildAll() end ) local ChangeIconSize = function ( w, h ) icon:SetSize( w, h ) icon:InvalidateLayout( true ) container:OnModified() container:Layout() icon:SetModel( obj.model, obj.skin or 0, obj.body ) end local submenu = menu:AddSubMenu( "Resize", function () end ) submenu:AddOption( "64 x 64 (default)", function () ChangeIconSize( 64, 64 ) end ) submenu:AddOption( "64 x 128", function () ChangeIconSize( 64, 128 ) end ) submenu:AddOption( "64 x 256", function () ChangeIconSize( 64, 256 ) end ) submenu:AddOption( "64 x 512", function () ChangeIconSize( 64, 512 ) end ) submenu:AddSpacer() submenu:AddOption( "128 x 64", function () ChangeIconSize( 128, 64 ) end ) submenu:AddOption( "128 x 128", function () ChangeIconSize( 128, 128 ) end ) submenu:AddOption( "128 x 256", function () ChangeIconSize( 128, 256 ) end ) submenu:AddOption( "128 x 512", function () ChangeIconSize( 128, 512 ) end ) submenu:AddSpacer() submenu:AddOption( "256 x 64", function () ChangeIconSize( 256, 64 ) end ) submenu:AddOption( "256 x 128", function () ChangeIconSize( 256, 128 ) end ) submenu:AddOption( "256 x 256", function () ChangeIconSize( 256, 256 ) end ) submenu:AddOption( "256 x 512", function () ChangeIconSize( 256, 512 ) end ) submenu:AddSpacer() submenu:AddOption( "512 x 64", function () ChangeIconSize( 512, 64 ) end ) submenu:AddOption( "512 x 128", function () ChangeIconSize( 512, 128 ) end ) submenu:AddOption( "512 x 256", function () ChangeIconSize( 512, 256 ) end ) submenu:AddOption( "512 x 512", function () ChangeIconSize( 512, 512 ) end ) menu:AddSpacer() menu:AddOption( "Delete", function () icon:Remove() end ) menu:Open() end icon:InvalidateLayout( true ) if ( IsValid( container ) ) then container:Add( icon ) end return icon end local function addBrowseContent ( viewPanel, node, name, icon, path, pathid ) local models = node:AddFolder( name, path .. "models", pathid, false ) models:SetIcon( icon ) models.OnNodeSelected = function ( self, node ) if viewPanel and viewPanel.currentNode and viewPanel.currentNode == node then return end viewPanel:Clear( true ) viewPanel.currentNode = node local path = node:GetFolder() local searchString = path .. "/*.mdl" local Models = file.Find( searchString, node:GetPathID() ) for k, v in pairs( Models ) do if not IsUselessModel( v ) then addModel( viewPanel, { model = path .. "/" .. v } ) end end node.propPanel = viewPanel frame.ContentNavBar.Tree:OnNodeSelected( node ) viewPanel.currentNode = node end end local function addAddonContent ( panel, folder, path ) local files, folders = file.Find( folder .. "*", path ) for k, v in pairs( files ) do if string.EndsWith( v, ".mdl" ) then addModel( panel, { model = folder .. v } ) end end for k, v in pairs( folders ) do addAddonContent( panel, folder .. v .. "/", path ) end end local function fillNavBar ( propTable, parentNode ) for k, v in SortedPairs( propTable ) do if v.parentid == parentNode.info.id and ( v.needsapp ~= "" and hasGame( v.needsapp ) or v.needsapp == "" ) then local node = parentNode:AddNode( v.name, v.icon ) node:SetExpanded( true ) node.info = v node.propPanel = vgui.Create( "ContentContainer", frame.PropPanel ) node.propPanel:DockMargin( 5, 0, 0, 0 ) node.propPanel:SetVisible( false ) for i, object in SortedPairs( node.info.contents ) do if object.type == "model" then addModel( node.propPanel, object ) elseif object.type == "header" then if not object.text or type( object.text ) ~= "string" then return end local label = vgui.Create( "ContentHeader", node.propPanel ) label:SetText( object.text ) node.propPanel:Add( label ) end end fillNavBar( propTable, node ) end end end if table.Count( spawnmenu.GetPropTable() ) == 0 then hook.Call( "PopulatePropMenu", GAMEMODE ) end fillNavBar( spawnmenu.GetPropTable(), root ) frame.OldSpawnlists = frame.ContentNavBar.Tree:AddNode( "#spawnmenu.category.browse", "icon16/cog.png" ) frame.OldSpawnlists:SetExpanded( true ) -- Games local gamesNode = frame.OldSpawnlists:AddNode( "#spawnmenu.category.games", "icon16/folder_database.png" ) local viewPanel = vgui.Create( "ContentContainer", frame.PropPanel ) viewPanel:DockMargin( 5, 0, 0, 0 ) viewPanel:SetVisible( false ) local games = engine.GetGames() table.insert( games, { title = "All", folder = "GAME", icon = "all", mounted = true } ) table.insert( games, { title = "Garry's Mod", folder = "garrysmod", mounted = true } ) for _, game in SortedPairsByMemberValue( games, "title" ) do if game.mounted then addBrowseContent( viewPanel, gamesNode, game.title, "games/16/" .. ( game.icon or game.folder ) .. ".png", "", game.folder ) end end -- Addons local addonsNode = frame.OldSpawnlists:AddNode( "#spawnmenu.category.addons", "icon16/folder_database.png" ) local viewPanel = vgui.Create( "ContentContainer", frame.PropPanel ) viewPanel:DockMargin( 5, 0, 0, 0 ) viewPanel:SetVisible( false ) function addonsNode:OnNodeSelected ( node ) if node == addonsNode then return end viewPanel:Clear( true ) addAddonContent( viewPanel, "models/", node.addon.title ) node.propPanel = viewPanel frame.ContentNavBar.Tree:OnNodeSelected( node ) end for _, addon in SortedPairsByMemberValue( engine.GetAddons(), "title" ) do if addon.downloaded and addon.mounted and addon.models > 0 then local node = addonsNode:AddNode( addon.title .. " ("..addon.models..")", "icon16/bricks.png" ) node.addon = addon end end -- Search box local viewPanel = vgui.Create( "ContentContainer", frame.PropPanel ) viewPanel:DockMargin( 5, 0, 0, 0 ) viewPanel:SetVisible( false ) frame.searchBox = vgui.Create( "DTextEntry", sidebarPanel ) frame.searchBox:Dock( TOP ) frame.searchBox:SetValue( "Search..." ) frame.searchBox:SetTooltip( "Press enter to search" ) frame.searchBox.propPanel = viewPanel frame.searchBox._OnGetFocus = frame.searchBox.OnGetFocus function frame.searchBox:OnGetFocus () if self:GetValue() == "Search..." then self:SetValue( "" ) end frame.searchBox:_OnGetFocus() end frame.searchBox._OnLoseFocus = frame.searchBox.OnLoseFocus function frame.searchBox:OnLoseFocus () if self:GetValue() == "" then self:SetText( "Search..." ) end frame.searchBox:_OnLoseFocus() end function frame.searchBox:updateHeader () self.header:SetText( frame.searchBox.results .. " Results for \"" .. self.search .. "\"" ) end local searchTime = nil function frame.searchBox:getAllModels ( time, folder, extension, path ) if searchTime and time ~= searchTime then return end if self.results and self.results >= 256 then return end self.load = self.load + 1 local files, folders = file.Find( folder .. "/*", path ) for k, v in pairs( files ) do local file = folder .. v if v:EndsWith( extension ) and file:find( self.search:PatternSafe() ) and not IsUselessModel( file ) then addModel( self.propPanel, { model = file } ) self.results = self.results + 1 self:updateHeader() end if self.results >= 256 then break end end for k, v in pairs( folders ) do timer.Simple( k * 0.02, function() if searchTime and time ~= searchTime then return end if self.results >= 256 then return end self:getAllModels( time, folder .. v .. "/", extension, path ) end ) end timer.Simple( 1, function () if searchTime and time ~= searchTime then return end self.load = self.load - 1 end ) end function frame.searchBox:OnEnter () if self:GetValue() == "" then return end self.propPanel:Clear() self.results = 0 self.load = 1 self.search = self:GetText() self.header = vgui.Create( "ContentHeader", self.propPanel ) self.loading = vgui.Create( "ContentHeader", self.propPanel ) self:updateHeader() self.propPanel:Add( self.header ) self.propPanel:Add( self.loading ) searchTime = CurTime() self:getAllModels( searchTime, "models/", ".mdl", "GAME" ) self.load = self.load - 1 frame.ContentNavBar.Tree:OnNodeSelected( self ) end hook.Add( "Think", "sf_header_update", function () if frame.searchBox.loading and frame.searchBox.propPanel:IsVisible() then frame.searchBox.loading:SetText( "Loading" .. string.rep( ".", math.floor( CurTime() ) % 4 ) ) end if frame.searchBox.load and frame.searchBox.load <= 0 then frame.searchBox.loading:Remove() frame.searchBox.loading = nil frame.searchBox.load = nil end end ) return frame end function SF.Editor.saveSettings () local frame = SF.Editor.editor RunConsoleCommand( "sf_editor_width", frame:GetWide() ) RunConsoleCommand( "sf_editor_height", frame:GetTall() ) local x, y = frame:GetPos() RunConsoleCommand( "sf_editor_posx", x ) RunConsoleCommand( "sf_editor_posy", y ) local frame = SF.Editor.fileViewer RunConsoleCommand( "sf_fileviewer_width", frame:GetWide() ) RunConsoleCommand( "sf_fileviewer_height", frame:GetTall() ) local x, y = frame:GetPos() RunConsoleCommand( "sf_fileviewer_posx", x ) RunConsoleCommand( "sf_fileviewer_posy", y ) RunConsoleCommand( "sf_fileviewer_locked", frame.locked and 1 or 0 ) local frame = SF.Editor.modelViewer RunConsoleCommand( "sf_modelviewer_width", frame:GetWide() ) RunConsoleCommand( "sf_modelviewer_height", frame:GetTall() ) local x, y = frame:GetPos() RunConsoleCommand( "sf_modelviewer_posx", x ) RunConsoleCommand( "sf_modelviewer_posy", y ) end function SF.Editor.updateSettings () local frame = SF.Editor.editor frame:SetWide( GetConVarNumber( "sf_editor_width" ) ) frame:SetTall( GetConVarNumber( "sf_editor_height" ) ) frame:SetPos( GetConVarNumber( "sf_editor_posx" ), GetConVarNumber( "sf_editor_posy" ) ) local frame = SF.Editor.fileViewer frame:SetWide( GetConVarNumber( "sf_fileviewer_width" ) ) frame:SetTall( GetConVarNumber( "sf_fileviewer_height" ) ) frame:SetPos( GetConVarNumber( "sf_fileviewer_posx" ), GetConVarNumber( "sf_fileviewer_posy" ) ) frame:lock( SF.Editor.editor ) frame.locked = tobool(GetConVarNumber( "sf_fileviewer_locked" )) local buttonLock = frame.components[ "buttonHolder" ]:getButton( "Lock" ) buttonLock.active = frame.locked buttonLock:SetText( frame.locked and "Locked" or "Unlocked" ) local frame = SF.Editor.modelViewer frame:SetWide( GetConVarNumber( "sf_modelviewer_width" ) ) frame:SetTall( GetConVarNumber( "sf_modelviewer_height" ) ) frame:SetPos( GetConVarNumber( "sf_modelviewer_posx" ), GetConVarNumber( "sf_modelviewer_posy" ) ) local js = SF.Editor.runJS js( [[ editSessions.forEach( function( session ) { session.setUseWrapMode( ]] .. GetConVarNumber( "sf_editor_wordwrap" ) .. [[ ) } ) ]] ) js( "editor.setOption(\"showFoldWidgets\", " .. GetConVarNumber( "sf_editor_widgets" ) .. ")" ) js( "editor.setOption(\"showLineNumbers\", " .. GetConVarNumber( "sf_editor_linenumbers" ) .. ")" ) js( "editor.setOption(\"showGutter\", " .. GetConVarNumber( "sf_editor_gutter" ) .. ")" ) js( "editor.setOption(\"showInvisibles\", " .. GetConVarNumber( "sf_editor_invisiblecharacters" ) .. ")" ) js( "editor.setOption(\"displayIndentGuides\", " .. GetConVarNumber( "sf_editor_indentguides" ) .. ")" ) js( "editor.setOption(\"highlightActiveLine\", " .. GetConVarNumber( "sf_editor_activeline" ) .. ")" ) js( "editor.setOption(\"highlightGutterLine\", " .. GetConVarNumber( "sf_editor_activeline" ) .. ")" ) js( "editor.setOption(\"enableLiveAutocompletion\", " .. GetConVarNumber( "sf_editor_autocompletion" ) .. ")" ) js( "setFoldKeybinds( " .. GetConVarNumber( "sf_editor_disablelinefolding" ) .. ")" ) js( "editor.setFontSize(" .. GetConVarNumber( "sf_editor_fontsize" ) .. ")" ) end --- (Client) Builds a table for the compiler to use -- @param maincode The source code for the main chunk -- @param codename The name of the main chunk -- @return True if ok, false if a file was missing -- @return A table with mainfile = codename and files = a table of filenames and their contents, or the missing file path. function SF.Editor.BuildIncludesTable ( maincode, codename ) if not SF.Editor.initialized then if not SF.Editor.init() then return end end local tbl = {} maincode = maincode or SF.Editor.getCode() codename = codename or SF.Editor.getOpenFile() or "main" tbl.mainfile = codename tbl.files = {} tbl.filecount = 0 tbl.includes = {} local loaded = {} local ppdata = {} local function recursiveLoad ( path ) if loaded[ path ] then return end loaded[ path ] = true local code if path == codename and maincode then code = maincode else code = file.Read( "starfall/"..path, "DATA" ) or error( { fatal = false, err = "Bad include: " .. path }, 0 ) end tbl.files[ path ] = code local ok, err = SF.Preprocessor.ParseDirectives( path, code, {}, ppdata, nil, { "include" } ) if not ok and err then error( { fatal = false, err = err }, 0 ) end if ppdata.includes and ppdata.includes[ path ] then local inc = ppdata.includes[ path ] if not tbl.includes[ path ] then tbl.includes[ path ] = inc tbl.filecount = tbl.filecount + 1 else assert( tbl.includes[ path ] == inc ) end for i = 1, #inc do recursiveLoad( inc[i] ) end end end local ok, msg = pcall( recursiveLoad, codename ) local function findCycle ( file, visited, recStack ) if not visited[ file ] then --Mark the current file as visited and part of recursion stack visited[ file ] = true recStack[ file ] = true --Recurse for all the files included in this file for k, v in pairs( ppdata.includes[ file ] or {} ) do if recStack[ v ] then return true, file elseif not visited[ v ] then local cyclic, cyclicFile = findCycle( v, visited, recStack ) if cyclic then return true, cyclicFile end end end end --Remove this file from the recursion stack recStack[ file ] = false return false, nil end local isCyclic = false local cyclicFile = nil for k, v in pairs( ppdata.includes or {} ) do local cyclic, file = findCycle( k, {}, {} ) if cyclic then isCyclic = true cyclicFile = file break end end if isCyclic then return false, "Loop in includes from: " .. cyclicFile end if ok then return true, tbl elseif type( msg ) == "table" and not msg.fatal then return false, msg.err else error( msg, 0 ) end end net.Receive( "starfall_editor_getacefiles", function ( len ) local index = net.ReadInt( 8 ) aceFiles[ index ] = net.ReadString() if not tobool( net.ReadBit() ) then net.Start( "starfall_editor_getacefiles" ) net.SendToServer() else SF.Editor.safeToInit = true SF.Editor.init() end end ) net.Receive( "starfall_editor_geteditorcode", function ( len ) htmlEditorCode = net.ReadString() SF.Editor.codeMap = net.ReadTable() table.Merge( SF.Editor.codeMap, createCodeMap() ) end ) -- CLIENT ANIMATION local busy_players = { } hook.Add( "EntityRemoved", "starfall_busy_animation", function ( ply ) busy_players[ ply ] = nil end ) local emitter = ParticleEmitter( vector_origin ) net.Receive( "starfall_editor_status", function ( len ) local ply = net.ReadEntity() local status = net.ReadBit() ~= 0 -- net.ReadBit returns 0 or 1, despite net.WriteBit taking a boolean if not ply:IsValid() or ply == LocalPlayer() then return end busy_players[ ply ] = status or nil end ) local rolldelta = math.rad( 80 ) timer.Create( "starfall_editor_status", 1 / 3, 0, function () rolldelta = -rolldelta for ply, _ in pairs( busy_players ) do local BoneIndx = ply:LookupBone( "ValveBiped.Bip01_Head1" ) or ply:LookupBone( "ValveBiped.HC_Head_Bone" ) or 0 local BonePos, BoneAng = ply:GetBonePosition( BoneIndx ) local particle = emitter:Add( "radon/starfall2", BonePos + Vector( math.random( -10, 10 ), math.random( -10, 10 ), 60 + math.random( 0, 10 ) ) ) if particle then particle:SetColor( math.random( 30, 50 ), math.random( 40, 150 ), math.random( 180, 220 ) ) particle:SetVelocity( Vector( 0, 0, -40 ) ) particle:SetDieTime( 1.5 ) particle:SetLifeTime( 0 ) particle:SetStartSize( 10 ) particle:SetEndSize( 5 ) particle:SetStartAlpha( 255 ) particle:SetEndAlpha( 0 ) particle:SetRollDelta( rolldelta ) end end end ) elseif SERVER then util.AddNetworkString( "starfall_editor_status" ) util.AddNetworkString( "starfall_editor_getacefiles" ) util.AddNetworkString( "starfall_editor_geteditorcode" ) local function getFiles ( dir, dir2 ) local files = {} local dir2 = dir2 or "" local f, directories = file.Find( dir .. "/" .. dir2 .. "/*", "GAME" ) for k, v in pairs( f ) do files[ #files + 1 ] = dir2 .. "/" .. v end for k, v in pairs( directories ) do table.Add( files, getFiles( dir, dir2 .. "/" .. v ) ) end return files end local acefiles = {} do local netSize = 64000 local files = file.Find( addon_path .. "/html/starfall/ace/*", "GAME" ) local out = "" for k, v in pairs( files ) do out = out .. "<script>\n" .. file.Read( addon_path .. "/html/starfall/ace/" .. v, "GAME" ) .. "</script>\n" end for i = 1, math.ceil( out:len() / netSize ) do acefiles[i] = out:sub( (i - 1)*netSize + 1, i*netSize ) end end local plyIndex = {} local function sendAceFile ( len, ply ) local index = plyIndex[ ply ] net.Start( "starfall_editor_getacefiles" ) net.WriteInt( index, 8 ) net.WriteString( acefiles[ index ] ) net.WriteBit( index == #acefiles ) net.Send( ply ) plyIndex[ ply ] = index + 1 end hook.Add( "PlayerInitialSpawn", "starfall_file_init", function ( ply ) net.Start( "starfall_editor_geteditorcode" ) net.WriteString( file.Read( addon_path .. "/html/starfall/editor.html", "GAME" ) ) net.WriteTable( createCodeMap() ) net.Send( ply ) plyIndex[ ply ] = 1 sendAceFile( nil, ply ) end ) net.Receive( "starfall_editor_getacefiles", sendAceFile ) for k, v in pairs( getFiles( addon_path, "materials/radon" ) ) do resource.AddFile( v ) end local starfall_event = {} concommand.Add( "starfall_event", function ( ply, command, args ) local handler = starfall_event[ args[ 1 ] ] if not handler then return end return handler( ply, args ) end ) function starfall_event.editor_open ( ply, args ) net.Start( "starfall_editor_status" ) net.WriteEntity( ply ) net.WriteBit( true ) net.Broadcast() end function starfall_event.editor_close ( ply, args ) net.Start( "starfall_editor_status" ) net.WriteEntity( ply ) net.WriteBit( false ) net.Broadcast() end end
bsd-3-clause
nasomi/darkstar
scripts/globals/spells/slow_ii.lua
18
1665
----------------------------------------- -- Spell: Slow II -- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and MND. -- caster:getMerit() returns a value which is equal to the number of merit points TIMES the value of each point -- Slow II value per point is '1' This is a constant set in the table 'merits' ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local dMND = (caster:getStat(MOD_MND) - target:getStat(MOD_MND)); local potency = 230 + math.floor(dMND * 1.6); -- ([230] + [y * 10] + [floor(dMND * 1.6)])/1024 if (potency > 350) then potency = 350; end if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then potency = potency * 2; end local merits = caster:getMerit(MERIT_SLOW_II); --Power. local power = (potency + (merits * 10)); --Duration, including resistance. local duration = 180 * applyResistanceEffect(caster,spell,target,dMND,35,merits*2,EFFECT_SLOW); if (duration >= 60) then --Do it! if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then duration = duration * 2; end caster:delStatusEffect(EFFECT_SABOTEUR); if (target:addStatusEffect(EFFECT_SLOW,power,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end return EFFECT_SLOW; end;
gpl-3.0
cristiandonosoc/unexperiments
dotaoh/lib/hardon_collider/gjk.lua
23
5593
--[[ Copyright (c) 2012 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local _PACKAGE = (...):match("^(.+)%.[^%.]+") local vector = require(_PACKAGE .. '.vector-light') local huge, abs = math.huge, math.abs local function support(shape_a, shape_b, dx, dy) local x,y = shape_a:support(dx,dy) return vector.sub(x,y, shape_b:support(-dx, -dy)) end -- returns closest edge to the origin local function closest_edge(simplex) local e = {dist = huge} local i = #simplex-1 for k = 1,#simplex-1,2 do local ax,ay = simplex[i], simplex[i+1] local bx,by = simplex[k], simplex[k+1] i = k local ex,ey = vector.perpendicular(bx-ax, by-ay) local nx,ny = vector.normalize(ex,ey) local d = vector.dot(ax,ay, nx,ny) if d < e.dist then e.dist = d e.nx, e.ny = nx, ny e.i = k end end return e end local function EPA(shape_a, shape_b, simplex) -- make sure simplex is oriented counter clockwise local cx,cy, bx,by, ax,ay = unpack(simplex) if vector.dot(ax-bx,ay-by, cx-bx,cy-by) < 0 then simplex[1],simplex[2] = ax,ay simplex[5],simplex[6] = cx,cy end -- the expanding polytype algorithm local is_either_circle = shape_a._center or shape_b._center local last_diff_dist = huge while true do local e = closest_edge(simplex) local px,py = support(shape_a, shape_b, e.nx, e.ny) local d = vector.dot(px,py, e.nx, e.ny) local diff_dist = d - e.dist if diff_dist < 1e-6 or (is_either_circle and abs(last_diff_dist - diff_dist) < 1e-10) then return -d*e.nx, -d*e.ny end last_diff_dist = diff_dist -- simplex = {..., simplex[e.i-1], px, py, simplex[e.i] table.insert(simplex, e.i, py) table.insert(simplex, e.i, px) end end -- : : origin must be in plane between A and B -- B o------o A since A is the furthest point on the MD -- : : in direction of the origin. local function do_line(simplex) local bx,by, ax,ay = unpack(simplex) local abx,aby = bx-ax, by-ay local dx,dy = vector.perpendicular(abx,aby) if vector.dot(dx,dy, -ax,-ay) < 0 then dx,dy = -dx,-dy end return simplex, dx,dy end -- B .' -- o-._ 1 -- | `-. .' The origin can only be in regions 1, 3 or 4: -- | 4 o A 2 A lies on the edge of the MD and we came -- | _.-' '. from left of BC. -- o-' 3 -- C '. local function do_triangle(simplex) local cx,cy, bx,by, ax,ay = unpack(simplex) local aox,aoy = -ax,-ay local abx,aby = bx-ax, by-ay local acx,acy = cx-ax, cy-ay -- test region 1 local dx,dy = vector.perpendicular(abx,aby) if vector.dot(dx,dy, acx,acy) > 0 then dx,dy = -dx,-dy end if vector.dot(dx,dy, aox,aoy) > 0 then -- simplex = {bx,by, ax,ay} simplex[1], simplex[2] = bx,by simplex[3], simplex[4] = ax,ay simplex[5], simplex[6] = nil, nil return simplex, dx,dy end -- test region 3 dx,dy = vector.perpendicular(acx,acy) if vector.dot(dx,dy, abx,aby) > 0 then dx,dy = -dx,-dy end if vector.dot(dx,dy, aox, aoy) > 0 then -- simplex = {cx,cy, ax,ay} simplex[3], simplex[4] = ax,ay simplex[5], simplex[6] = nil, nil return simplex, dx,dy end -- must be in region 4 return simplex end local function GJK(shape_a, shape_b) local ax,ay = support(shape_a, shape_b, 1,0) if ax == 0 and ay == 0 then -- only true if shape_a and shape_b are touching in a vertex, e.g. -- .--- .---. -- | A | .-. | B | support(A, 1,0) = x -- '---x---. or : A :x---' support(B, -1,0) = x -- | B | `-' => support(A,B,1,0) = x - x = 0 -- '---' -- Since CircleShape:support(dx,dy) normalizes dx,dy we have to opt -- out or the algorithm blows up. In accordance to the cases below -- choose to judge this situation as not colliding. return false end local simplex = {ax,ay} local n = 2 local dx,dy = -ax,-ay -- first iteration: line case ax,ay = support(shape_a, shape_b, dx,dy) if vector.dot(ax,ay, dx,dy) <= 0 then return false end simplex[n+1], simplex[n+2] = ax,ay simplex, dx, dy = do_line(simplex, dx, dy) n = 4 -- all other iterations must be the triangle case while true do ax,ay = support(shape_a, shape_b, dx,dy) if vector.dot(ax,ay, dx,dy) <= 0 then return false end simplex[n+1], simplex[n+2] = ax,ay simplex, dx, dy = do_triangle(simplex, dx,dy) n = #simplex if n == 6 then return true, EPA(shape_a, shape_b, simplex) end end end return GJK
mit
sjthespian/dotfiles
hammerspoon/utils/file.lua
4
5429
-- File and directory related utilities local lib = {} -- Return true if the file exists, else false function lib.exists(name) local f = io.open(name,'r') if f ~= nil then io.close(f) return true else return false end end -- Takes a list of path parts, returns a string with the parts delimited by '/' function lib.toPath(...) return table.concat({...}, '/') end -- Splits a string by '/', returning the parent dir, filename (with extension), -- and the extension alone. function lib.splitPath(file) local parent = file:match('(.+)/[^/]+$') if parent == nil then parent = '.' end local filename = file:match('/([^/]+)$') if filename == nil then filename = file end local ext = filename:match('%.([^.]+)$') return parent, filename, ext end -- Make a parent dir for a file. Does not error if it exists already. function lib.makeParentDir(path) local parent, _, _ = lib.splitPath(path) local ok, err = hs.fs.mkdir(parent) if ok == nil then if err == 'File exists' then ok = true end end return ok, err end -- Create a file (making parent directories if necessary). function lib.create(path) if lib.makeParentDir(path) then io.open(path, 'w'):close() end end -- Append a line of text to a file. function lib.append(file, text) if text == '' then return end local f = io.open(file, 'a') f:write(tostring(text) .. '\n') f:close() end -- Move a file. This calls task (so runs asynchronously), so calls onSuccess -- and onFailure callback functions depending on the result. Set force to true -- to overwrite. function lib.move(from, to, force, onSuccess, onFailure) force = force and '-f' or '-n' local function callback(exitCode, stdOut, stdErr) if exitCode == 0 then onSuccess(stdOut) else onFailure(stdErr) end end if lib.exists(from) then hs.task.new('/bin/mv', callback, {force, from, to}):start() end end -- If the given file is older than the given time (in epoch seconds), return -- true. This checks the inode change time, not the original file creation -- time. function lib.isOlderThan(file, seconds) local age = os.time() - hs.fs.attributes(file, 'change') if age > seconds then return true end return false end -- Return the last modified time of a file in epoch seconds. function lib.lastModified(file) local when = os.time() if lib.exists(file) then when = hs.fs.attributes(file, 'modification') end return when end -- If any files are found in the given path, make a list of them and call the -- given callback function with that list. function lib.runOnFiles(path, callback) local iter, data = hs.fs.dir(path) local files = {} repeat local item = iter(data) if item ~= nil then table.insert(files, lib.toPath(path, item)) end until item == nil if #files > 0 then callback(files) end end -- Unhide the extension on the given file, if it matches the extension given, -- and that extension does not exist in the given hiddenExtensions table. function lib.unhideExtension(file, ext, hiddenExtensions) if ext == nil or hiddenExtensions == nil or hiddenExtensions[ext] == nil then local function unhide(exitCode, stdOut, stdErr) if exitCode == 0 and tonumber(stdOut) == 1 then hs.task.new('/usr/bin/SetFile', nil, {'-a', 'e', file}):start() end end hs.task.new('/usr/bin/GetFileInfo', unhide, {'-aE', file}):start() end end -- Returns true if the file has any default OS X color tag enabled. function lib.isColorTagged(file) local colors = { Red = true, Orange = true, Yellow = true, Green = true, Blue = true, Purple = true, Gray = true, } local tags = hs.fs.tagsGet(file) if tags ~= nil then for _,tag in ipairs(tags) do if colors[tag] then return true end end end return false end -- Simply set a single tag on a file function lib.setTag(file, tag) hs.fs.tagsAdd(file, {tag}) end -- Return a string that ensures the given file ends with the given extension. function lib.withExtension(filePath, ext) local path = filePath local extMatch = '%.'..ext..'$' if not string.find(path, extMatch) then path = path..'.'..ext end return path end -- load a json file into a lua table and return it function lib.loadJSON(file) local data = nil local f = io.open(file, 'r') if f then local content = f:read('*all') f:close() if content then ok, data = pcall(function() return hs.json.decode(content) end) if not ok then hsm.log.e('loadJSON:', data) data = nil end end end return data end -- Find the most recent path in a directory -- attr should be one of: access, change, modification, creation function lib.mostRecent(parent, attr) if not lib.exists(parent) then return nil end -- make sure attr is valid and default to modification local attrs = {access=true, change=true, modification=true, creation=true} if not attrs[attr] then attr = 'modification' end local max = 0 local mostRecent = nil local iterFn, dirObj = hs.fs.dir(parent) local child = iterFn(dirObj) while child do -- ignore dotfiles if string.find(child, '^[^%.]') then local path = lib.toPath(parent, child) local last = hs.fs.attributes(path, attr) if last > max then mostRecent = path max = last end end child = iterFn(dirObj) end return mostRecent end return lib
mit
mrfoxirani/mehran
plugins/anti-bot.lua
369
3064
local function isBotAllowed (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId local banned = redis:get(hash) return banned end local function allowBot (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId redis:set(hash, true) end local function disallowBot (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId redis:del(hash) end -- Is anti-bot enabled on chat local function isAntiBotEnabled (chatId) local hash = 'anti-bot:enabled:'..chatId local enabled = redis:get(hash) return enabled end local function enableAntiBot (chatId) local hash = 'anti-bot:enabled:'..chatId redis:set(hash, true) end local function disableAntiBot (chatId) local hash = 'anti-bot:enabled:'..chatId redis:del(hash) end local function isABot (user) -- Flag its a bot 0001000000000000 local binFlagIsBot = 4096 local result = bit32.band(user.flags, binFlagIsBot) return result == binFlagIsBot end local function kickUser(userId, chatId) local chat = 'chat#id'..chatId local user = 'user#id'..userId chat_del_user(chat, user, function (data, success, result) if success ~= 1 then print('I can\'t kick '..data.user..' but should be kicked') end end, {chat=chat, user=user}) end local function run (msg, matches) -- We wont return text if is a service msg if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' end end local chatId = msg.to.id if matches[1] == 'enable' then enableAntiBot(chatId) return 'Anti-bot enabled on this chat' end if matches[1] == 'disable' then disableAntiBot(chatId) return 'Anti-bot disabled on this chat' end if matches[1] == 'allow' then local userId = matches[2] allowBot(userId, chatId) return 'Bot '..userId..' allowed' end if matches[1] == 'disallow' then local userId = matches[2] disallowBot(userId, chatId) return 'Bot '..userId..' disallowed' end if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then local user = msg.action.user or msg.from if isABot(user) then print('It\'s a bot!') if isAntiBotEnabled(chatId) then print('Anti bot is enabled') local userId = user.id if not isBotAllowed(userId, chatId) then kickUser(userId, chatId) else print('This bot is allowed') end end end end end return { description = 'When bot enters group kick it.', usage = { '!antibot enable: Enable Anti-bot on current chat', '!antibot disable: Disable Anti-bot on current chat', '!antibot allow <botId>: Allow <botId> on this chat', '!antibot disallow <botId>: Disallow <botId> on this chat' }, patterns = { '^!antibot (allow) (%d+)$', '^!antibot (disallow) (%d+)$', '^!antibot (enable)$', '^!antibot (disable)$', '^!!tgservice (chat_add_user)$', '^!!tgservice (chat_add_user_link)$' }, run = run }
gpl-2.0
nasomi/darkstar
scripts/zones/Sealions_Den/npcs/Sueleen.lua
17
1989
----------------------------------- -- Area: Sealion's Den -- NPC: Sueleen -- @pos 612 132 774 32 ----------------------------------- package.loaded["scripts/zones/Sealions_Den/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Sealions_Den/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --player:startEvent(0x000c); if (player:getCurrentMission(COP) == FLAMES_IN_THE_DARKNESS and player:getVar("PromathiaStatus") == 1) then player:startEvent(0x0010); elseif (player:getCurrentMission(COP) == CALM_BEFORE_THE_STORM and player:hasKeyItem(LETTERS_FROM_ULMIA_AND_PRISHE)== true ) then player:startEvent(0x0011); else player:startEvent(0x0014); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (csid == 0x000c and option == 1) then toPalaceEntrance(player); elseif (csid == 0x0010) then player:setVar("PromathiaStatus",2); elseif (csid == 0x0011) then player:completeMission(COP,CALM_BEFORE_THE_STORM); player:addMission(COP,THE_WARRIOR_S_PATH); player:setVar("PromathiaStatus",0); player:setVar("COP_Dalham_KILL",0); player:setVar("COP_Boggelmann_KILL",0); player:setVar("Cryptonberry_Executor_KILL",0); end end;
gpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/small_bubble_rt_3.meta.lua
146
1898
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 5, light_colors = { "255 255 255 255" }, radius = { x = 80, y = 80 }, standard_deviation = 5 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/medium_bubble_11.meta.lua
146
1898
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 5, light_colors = { "255 255 255 255" }, radius = { x = 80, y = 80 }, standard_deviation = 5 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/small_bubble_rb_3.meta.lua
146
1898
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 5, light_colors = { "255 255 255 255" }, radius = { x = 80, y = 80 }, standard_deviation = 5 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/small_bubble_rt_6.meta.lua
146
1898
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 5, light_colors = { "255 255 255 255" }, radius = { x = 80, y = 80 }, standard_deviation = 5 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/big_bubble_1.meta.lua
146
1898
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 5, light_colors = { "255 255 255 255" }, radius = { x = 80, y = 80 }, standard_deviation = 5 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/big_bubble_14.meta.lua
146
1898
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 5, light_colors = { "255 255 255 255" }, radius = { x = 80, y = 80 }, standard_deviation = 5 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
raburton/nodemcu-firmware
lua_examples/u8glib/u8g_bitmaps.lua
19
2968
-- *************************************************************************** -- Bitmaps Test -- -- This script executes the bitmap features of u8glib to test their Lua -- integration. -- -- Note: It is prepared for SSD1306-based displays. Select your connectivity -- type by calling either init_i2c_display() or init_spi_display() at -- the bottom of this file. -- -- *************************************************************************** -- setup I2c and connect display function init_i2c_display() -- SDA and SCL can be assigned freely to available GPIOs local sda = 5 -- GPIO14 local scl = 6 -- GPIO12 local sla = 0x3c i2c.setup(0, sda, scl, i2c.SLOW) disp = u8g.ssd1306_128x64_i2c(sla) end -- 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) disp = u8g.ssd1306_128x64_hw_spi(cs, dc, res) end function xbm_picture() disp:setFont(u8g.font_6x10) disp:drawStr( 0, 10, "XBM picture") disp:drawXBM( 0, 20, 38, 24, xbm_data ) end function bitmap_picture(state) disp:setFont(u8g.font_6x10) disp:drawStr( 0, 10, "Bitmap picture") disp:drawBitmap( 0 + (state * 10), 20 + (state * 4), 1, 8, bm_data ) end -- the draw() routine function draw(draw_state) local component = bit.rshift(draw_state, 3) if (component == 0) then xbm_picture(bit.band(draw_state, 7)) elseif (component == 1) then bitmap_picture(bit.band(draw_state, 7)) end end function draw_loop() -- Draws one page and schedules the next page, if there is one local function draw_pages() draw(draw_state) if disp:nextPage() then node.task.post(draw_pages) else node.task.post(bitmap_test) end end -- Restart the draw loop and start drawing pages disp:firstPage() node.task.post(draw_pages) end function bitmap_test() if (draw_state <= 7 + 1*8) then draw_state = draw_state + 1 else print("--- Restarting Bitmap Test ---") draw_state = 1 end print("Heap: " .. node.heap()) -- retrigger draw_loop node.task.post(draw_loop) end draw_state = 1 init_i2c_display() --init_spi_display() -- read XBM picture file.open("u8glib_logo.xbm", "r") xbm_data = file.read() file.close() -- read Bitmap picture file.open("u8g_rook.bm", "r") bm_data = file.read() file.close() print("--- Starting Bitmap Test ---") node.task.post(draw_loop)
mit
Etehadmarg/margbot
plugins/yoda.lua
642
1199
local ltn12 = require "ltn12" local https = require "ssl.https" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(text) local api = "https://yoda.p.mashape.com/yoda?" text = string.gsub(text, " ", "+") local parameters = "sentence="..(text or "") local url = api..parameters local api_key = mashape.api_key if api_key:isempty() then return 'Configure your Mashape API Key' end local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "text/plain" } local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return code end local body = table.concat(respbody) return body end local function run(msg, matches) return request(matches[1]) end return { description = "Listen to Yoda and learn from his words!", usage = "!yoda You will learn how to speak like me someday.", patterns = { "^![y|Y]oda (.*)$" }, run = run }
gpl-2.0
nasomi/darkstar
scripts/zones/Northern_San_dOria/npcs/Kuu_Mohzolhi.lua
37
3233
----------------------------------- -- Area: Northern San d'Oria -- NPC: Kuu Mohzolhi -- Starts and Finishes Quest: Growing Flowers -- @zone 231 -- @pos -123 0 80 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) count = trade:getItemCount(); gil = trade:getGil(); itemQuality = 0; if (trade:getItemCount() == 1 and trade:getGil() == 0) then if (trade:hasItemQty(958,1)) then -- Marguerite itemQuality = 2; elseif (trade:hasItemQty(957,1) or -- Amaryllis trade:hasItemQty(2554,1) or -- Asphodel trade:hasItemQty(948,1) or -- Carnation trade:hasItemQty(1120,1) or -- Casablanca trade:hasItemQty(1413,1) or -- Cattleya trade:hasItemQty(636,1) or -- Chamomile trade:hasItemQty(959,1) or -- Dahlia trade:hasItemQty(835,1) or -- Flax Flower trade:hasItemQty(956,1) or -- Lilac trade:hasItemQty(2507,1) or -- Lycopodium Flower trade:hasItemQty(1412,1) or -- Olive Flower trade:hasItemQty(938,1) or -- Papaka Grass trade:hasItemQty(1411,1) or -- Phalaenopsis trade:hasItemQty(949,1) or -- Rain Lily trade:hasItemQty(941,1) or -- Red Rose trade:hasItemQty(1725,1) or -- Snow Lily trade:hasItemQty(1410,1) or -- Sweet William trade:hasItemQty(950,1) or -- Tahrongi Cactus trade:hasItemQty(2960,1) or -- Water Lily trade:hasItemQty(951,1)) then -- Wijnruit itemQuality = 1; end end GrowingFlowers = player:getQuestStatus(SANDORIA,GROWING_FLOWERS); if (itemQuality == 2) then if (GrowingFlowers == QUEST_COMPLETED) then player:startEvent(0x025d, 0, 231, 4); else player:startEvent(0x025d, 0, 231, 2); end elseif (itemQuality == 1) then if (GrowingFlowers == QUEST_ACCEPTED) then player:startEvent(0x025d, 0, 231, 3); else player:startEvent(0x025d, 0, 231, 1); end else player:startEvent(0x025d, 0, 231, 0); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x025d, 0, 231, 10); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x025d and option == 1002) then player:tradeComplete(); player:completeQuest(SANDORIA,GROWING_FLOWERS); player:addFame(SANDORIA,SAN_FAME*120); player:moghouseFlag(1); player:messageSpecial(MOGHOUSE_EXIT); elseif (csid == 0x025d and option == 1) then player:tradeComplete(); player:addQuest(SANDORIA,GROWING_FLOWERS); end end;
gpl-3.0
OrenjiAkira/lua-html
lib/lux/class.lua
1
5360
--[[ -- -- Copyright (c) 2013-2016 Wilson Kazuo Mizutani -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely, subject to the following restrictions: -- -- 1. The origin of this software must not be misrepresented; you must not -- claim that you wrote the original software. If you use this software -- in a product, an acknowledgment in the product documentation would be -- appreciated but is not required. -- -- 2. Altered source versions must be plainly marked as such, and must not be -- misrepresented as being the original software. -- -- 3. This notice may not be removed or altered from any source -- distribution. -- --]] --- A class-based implementation object oriented programming. -- Ironically, this is actually a prototype, which means it inherits from -- @{lux.prototype}, but otherwise provides its own mechanism for OOP. -- Be sure to check @{instance}, @{inherit} and @{super} usages. -- -- ***This module requires macro takeover in order to work properly*** -- -- @usage -- local MyClass = require 'lux.class' :new{} -- @prototype lux.class local class = require 'lux.prototype' :new {} --- Defines how an instance of the class should be constructed. -- This function is supposed to only be overriden, not called from the user's -- side. By populating the `_ENV` parameter provided in this factory-like -- strategy method is what creates class instances in this OOP feature. -- This is actually done automatically: every "global" variable or function -- you define inside this function is instead stored as a corresponding object -- field. -- -- @tparam object _ENV -- The to-be-constructed object. Its name must be exactly `_ENV` -- -- @param ... -- Arguments required by the construction of objects from the current class -- -- @see some.lua -- -- @usage -- local MyClass = require 'lux.class' :new{} -- local print = print -- must explicitly enclosure dependencies -- function MyClass:instance (_ENV, x) -- -- public field -- y = 1337 -- -- private field -- local a_number = 42 -- -- public method -- function show () -- print(a_number + x) -- end -- end -- -- myobj = MyClass(8001) -- -- call without colons! -- myobj.show() function class:instance (_ENV, ...) -- Does nothing end --- Makes this class inherit from another. -- This guarantess that instances from the former are also instances from the -- latter. The semantics differs from that of inheritance through prototyping! -- Also, it is necessary to call @{super} inside the current class' -- @{instance} definition method since there is no way of guessing how the -- parent class' constructor should be called. -- -- @tparam class another_class -- The class being inherited from -- -- @see class:super -- -- @usage -- local class = require 'lux.class' -- local ParentClass = class:new{} -- local ChildClass = class:new{} -- ChildClass:inherit(ParentClass) function class:inherit (another_class) assert(not self.__parent, "Multiple inheritance not allowed!") assert(another_class:__super() == class, "Must inherit a class!") self.__parent = another_class end local function makeInstance (ofclass, obj, ...) #if port.minVersion(5,2) then ofclass:instance(obj, ...) #else setfenv(ofclass.instance, obj) ofclass:instance(obj, ...) setfenv(ofclass.instance, getfenv()) #end end local operator_meta = {} function operator_meta:__newindex (key, value) rawset(self, "__"..key, value) end --- The class constructor. -- This is how someone actually instantiates objects from this class system. -- After having created a new class and defined its @{instance} method, calling -- the class itself behaves as expected by calling the constructor that will -- use the @{instance} method to create the object. -- -- @param ... -- The constructor parameters as specified in the @{instance} -- -- @treturn object -- A new instance from the current class. function class:__call (...) local obj = { __class = self, __extended = not self.__parent, __operator = setmetatable({}, operator_meta) } makeInstance(self, obj, ...) assert(obj.__extended, "Missing call to parent constructor!") return setmetatable(obj, obj.__operator) end class.__init = { __call = class.__call } --- Calls the parent class' constructor. -- Should only be called inside this class' @{instance} definition method when -- it inherits from another class. -- -- @tparam object obj -- The object being constructed by the child class, that is, the `_ENV` -- parameter passed to @{instance} -- -- @param ... -- The parent class' constructor parameters -- -- @see class:inherit -- -- @usage -- -- After ChildClass inherited ParentClass -- function ChildClass:instance (_ENV, x, y) -- self:super(_ENV, x + y) -- parent's constructor parameters -- -- Finish instancing -- end function class:super (obj, ...) assert(not obj.__extended, "Already called parent constructor!") makeInstance(self.__parent, obj, ...) obj.__extended = true end return class
mit
nasomi/darkstar
scripts/globals/abilities/curing_waltz_iv.lua
18
2182
----------------------------------- -- Ability: Curing Waltz IV -- Heals HP to target player. -- Obtained: Dancer Level 70 -- TP Required: 65% -- Recast Time: 00:17 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (target:getHP() == 0) then return MSGBASIC_CANNOT_ON_THAT_TARG,0; elseif (player:hasStatusEffect(EFFECT_SABER_DANCE)) then return MSGBASIC_UNABLE_TO_USE_JA2, 0; elseif (player:hasStatusEffect(EFFECT_TRANCE)) then return 0,0; elseif (player:getTP() < 65) then return MSGBASIC_NOT_ENOUGH_TP,0; else -- apply waltz recast modifiers if (player:getMod(MOD_WALTZ_RECAST)~=0) then local recastMod = -170 * (player:getMod(MOD_WALTZ_RECAST)); -- 850 ms per 5% (per merit) if (recastMod <0) then --TODO end end return 0,0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(EFFECT_TRANCE) then player:delTP(65); end; --Grabbing variables. local vit = target:getStat(MOD_VIT); local chr = player:getStat(MOD_CHR); local mjob = player:getMainJob(); --19 for DNC main. local cure = 0; --Performing mj check. if (mjob == 19) then cure = (vit+chr)+450; end -- apply waltz modifiers cure = math.floor(cure * (1.0 + (player:getMod(MOD_WALTZ_POTENTCY)/100))); --Reducing TP. --Applying server mods.... cure = cure * CURE_POWER; --Cap the final amount to max HP. if ((target:getMaxHP() - target:getHP()) < cure) then cure = (target:getMaxHP() - target:getHP()); end --Do it target:restoreHP(cure); target:wakeUp(); player:updateEnmityFromCure(target,cure); return cure; end;
gpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/covert_magazine.meta.lua
2
2853
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 60, light_colors = { "255 0 255 255", "0 181 255 255", "0 255 255 255" }, radius = { x = 80, y = 80 }, standard_deviation = 9 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, rail = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
actboy168/YDWE
Development/Component/script/war3/window/main.lua
2
2136
log = require 'log' local fs = require 'bee.filesystem' local ydwe = fs.dll_path():parent_path():parent_path() log.init(ydwe / "logs", "lock_mouse") local ffi = require 'ffi' ffi.cdef[[ void __stdcall Sleep(unsigned long dwMilliseconds); struct RECT { long left; long top; long right; long bottom; }; struct POINT { long x; long y; }; int __stdcall GetParent(int hWnd); int __stdcall GetForegroundWindow(); int __stdcall GetCursorPos(struct POINT* lpPoint); int __stdcall GetClientRect(int hWnd, struct RECT* lpRect); int __stdcall ClientToScreen(int hWnd, struct POINT* lpPoint); int __stdcall ClipCursor(const struct RECT* lpRect); ]] local thread = require 'bee.thread' local channel = thread.channel 'window' local war3window = channel:bpop(window) local enable = false local function IsForegroundWindow() local window = ffi.C.GetParent(war3window) if window == 0 then return ffi.C.GetForegroundWindow() == war3window else return ffi.C.GetForegroundWindow() == window end end local function PtInRect(rect, pt) return (pt.x >= rect.left) and (pt.x < rect.right) and (pt.y >= rect.top) and (pt.y < rect.bottom) end local function lock_mouse() if IsForegroundWindow() then local rect = ffi.new('struct RECT') local pt = ffi.new('struct POINT') ffi.C.GetClientRect(war3window, rect) pt.x = rect.left pt.y = rect.top ffi.C.ClientToScreen(war3window, pt) rect.left = pt.x rect.top = pt.y pt.x = rect.right pt.y = rect.bottom ffi.C.ClientToScreen(war3window, pt) rect.right = pt.x rect.bottom = pt.y ffi.C.GetCursorPos(pt) if PtInRect(rect, pt) then ffi.C.ClipCursor(rect) enable = true end elseif enable then ffi.C.ClipCursor(nil) enable = false end end while true do local ok, msg = channel:pop() if ok and msg == 'exit' then return end lock_mouse() thread.sleep(0.01) end
gpl-3.0
dageq/Dage-Aliraqi
plugins/inrealm.lua
30
36636
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.peer_id, result.peer_id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.peer_id, result.peer_id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then if msg.to.type == 'chat' and not is_realm(msg) then data[tostring(msg.to.id)]['group_type'] = 'Group' save_data(_config.moderation.data, data) elseif msg.to.type == 'channel' then data[tostring(msg.to.id)]['group_type'] = 'SuperGroup' save_data(_config.moderation.data, data) end end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid local channel = 'channel#id'..extra.chatid send_large_msg(chat, user..'\n'..name) send_large_msg(channel, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin1(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_arabic(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic/Persian is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic/Persian has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL char. in names is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL char. in names has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL char. in names is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL char. in names has been unlocked' end end local function lock_group_links(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Link posting is already locked' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Link posting has been locked' end end local function unlock_group_links(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Link posting is not locked' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Link posting has been unlocked' end end local function lock_group_spam(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return 'SuperGroup spam is already locked' else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'SuperGroup spam has been locked' end end local function unlock_group_spam(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return 'SuperGroup spam is not locked' else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup spam has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL char. in names is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL char. in names has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL char. in names is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL char. in names has been unlocked' end end local function lock_group_sticker(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker posting is already locked' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker posting has been locked' end end local function unlock_group_sticker(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker posting is already unlocked' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker posting has been unlocked' end end local function set_public_membermod(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_public_lock = data[tostring(target)]['settings']['public'] if group_public_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup is now: public' end local function unset_public_membermod(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_public_lock = data[tostring(target)]['settings']['public'] if group_public_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup is now: not public' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin1(msg) then return "For admins only!" end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "Group settings for "..target..":\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nPublic: "..settings.public end -- show SuperGroup settings local function show_super_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin1(msg) then return "For admins only!" end if data[tostring(msg.to.id)]['settings'] then if not data[tostring(msg.to.id)]['settings']['public'] then data[tostring(msg.to.id)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict return text end local function returnids(cb_extra, success, result) local i = 1 local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' (ID: '..result.peer_id..'):\n\n' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text ..i..' - '.. string.gsub(v.print_name,"_"," ") .. " [" .. v.peer_id .. "] \n\n" i = i + 1 end end local file = io.open("./groups/lists/"..result.peer_id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function cb_user_info(cb_extra, success, result) local receiver = cb_extra.receiver if result.first_name then first_name = result.first_name:gsub("_", " ") else first_name = "None" end if result.last_name then last_name = result.last_name:gsub("_", " ") else last_name = "None" end if result.username then username = "@"..result.username else username = "@[none]" end text = "User Info:\n\nID: "..result.peer_id.."\nFirst: "..first_name.."\nLast: "..last_name.."\nUsername: "..username send_large_msg(receiver, text) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_id..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List of global admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do if data[tostring(v)] then if data[tostring(v)]['settings'] then local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end end end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, '@'..member_username..' is already an admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then send_large_msg(receiver, "@"..member_username..' is not an admin.') return end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, 'Admin @'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.peer_id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function res_user_support(cb_extra, success, result) local receiver = cb_extra.receiver local get_cmd = cb_extra.get_cmd local support_id = result.peer_id if get_cmd == 'addsupport' then support_add(support_id) send_large_msg(receiver, "User ["..support_id.."] has been added to the support team") elseif get_cmd == 'removesupport' then support_remove(support_id) send_large_msg(receiver, "User ["..support_id.."] has been removed from the support team") end end local function set_log_group(target, data) if not is_admin1(msg) then return end local log_group = data[tostring(target)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(target)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin1(msg) then return end local log_group = data[tostring(target)]['log_group'] if log_group == 'no' then return 'Log group is not set' else data[tostring(target)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then local receiver = get_receiver(msg) savelog(msg.to.id, "log file created by owner/support/admin") send_document(receiver,"./groups/logs/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and msg.to.type == 'chat' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) local file = io.open("./groups/lists/"..msg.to.id.."memberlist.txt", "r") text = file:read("*a") send_large_msg(receiver,text) file:close() end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) send_document("chat#id"..msg.to.id,"./groups/lists/"..msg.to.id.."memberlist.txt", ok_cb, false) end if matches[1] == 'whois' and is_momod(msg) then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] user_info(user_id, cb_user_info, {receiver = receiver}) end if not is_sudo(msg) and not is_realm(msg) and is_admin1(msg) then return end if matches[1] == 'اصنع مجموعه' and matches[2] then if not is_momod(msg) then return end if not is_sudo(msg) or is_admin1(msg) and is_realm(msg) then return "You cant create groups!" end group_name = matches[2] group_type = 'group' return create_group(msg) end --[[ Experimental if matches[1] == 'createsuper' and matches[2] then if not is_sudo(msg) or is_admin1(msg) and is_realm(msg) then return "You cant create groups!" end group_name = matches[2] group_type = 'super_group' return create_group(msg) end]] if matches[1] == 'createrealm' and matches[2] then if not is_sudo(msg) or not is_admin1(msg) and is_realm(msg) then return "You cant create groups!" end group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[1] == 'setabout' and matches[2] == 'group' and is_realm(msg) then local target = matches[3] local about = matches[4] return set_description(msg, data, target, about) end if matches[1] == 'setabout' and matches[2] == 'sgroup'and is_realm(msg) then local channel = 'channel#id'..matches[3] local about_text = matches[4] local data_cat = 'description' local target = matches[3] channel_set_about(channel, about_text, ok_cb, false) data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) return "Description has been set for ["..matches[2]..']' end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end if matches[2] == 'arabic' then return lock_group_arabic(msg, data, target) end if matches[3] == 'links' then return lock_group_links(msg, data, target) end if matches[3] == 'spam' then return lock_group_spam(msg, data, target) end if matches[3] == 'rtl' then return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' then return lock_group_sticker(msg, data, target) end end if matches[1] == 'unlock' then local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end if matches[3] == 'arabic' then return unlock_group_arabic(msg, data, target) end if matches[3] == 'links' then return unlock_group_links(msg, data, target) end if matches[3] == 'spam' then return unlock_group_spam(msg, data, target) end if matches[3] == 'rtl' then return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' then return unlock_group_sticker(msg, data, target) end end if matches[1] == 'settings' and matches[2] == 'group' and data[tostring(matches[3])]['settings'] then local target = matches[3] text = show_group_settingsmod(msg, target) return text.."\nID: "..target.."\n" end if matches[1] == 'settings' and matches[2] == 'sgroup' and data[tostring(matches[3])]['settings'] then local target = matches[3] text = show_supergroup_settingsmod(msg, target) return text.."\nID: "..target.."\n" end if matches[1] == 'setname' and is_realm(msg) then local settings = data[tostring(matches[2])]['settings'] local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin1(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local chat_to_rename = 'chat#id'..matches[2] local channel_to_rename = 'channel#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) rename_channel(channel_to_rename, group_name_set, ok_cb, false) savelog(matches[3], "Group { "..group_name_set.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end --[[if matches[1] == 'set' then if matches[2] == 'loggroup' and is_sudo(msg) then local target = msg.to.peer_id savelog(msg.to.peer_id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(target, data) end end if matches[1] == 'rem' then if matches[2] == 'loggroup' and is_sudo(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return unset_log_group(target, data) end end]] if matches[1] == 'kill' and matches[2] == 'chat' and matches[3] then if not is_admin1(msg) then return end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' and matches[3] then if not is_admin1(msg) then return end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'rem' and matches[2] then -- Group configuration removal data[tostring(matches[2])] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(matches[2])] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, 'Chat '..matches[2]..' removed') end if matches[1] == 'chat_add_user' then if not msg.service then return end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin1(msg) and is_realm(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if not is_sudo(msg) then-- Sudo only return end if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if not is_sudo(msg) then-- Sudo only return end if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'support' and matches[2] then if string.match(matches[2], '^%d+$') then local support_id = matches[2] print("User "..support_id.." has been added to the support team") support_add(support_id) return "User ["..support_id.."] has been added to the support team" else local member = string.gsub(matches[2], "@", "") local receiver = get_receiver(msg) local get_cmd = "addsupport" resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver}) end end if matches[1] == '-support' then if string.match(matches[2], '^%d+$') then local support_id = matches[2] print("User "..support_id.." has been removed from the support team") support_remove(support_id) return "User ["..support_id.."] has been removed from the support team" else local member = string.gsub(matches[2], "@", "") local receiver = get_receiver(msg) local get_cmd = "removesupport" resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' then if matches[2] == 'admins' then return admin_list(msg) end -- if matches[2] == 'support' and not matches[2] then -- return support_list() -- end end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' or msg.to.type == 'channel' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) send_document("channel#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' or msg.to.type == 'channel' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) send_document("channel#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return resolve_username(username, callbackres, cbres_extra) end end return { patterns = { "^[#!/](اصنع مجموعه) (.*)$", "^[#!/](createsuper) (.*)$", "^[#!/](createrealm) (.*)$", "^[#!/](setabout) (%d+) (.*)$", "^[#!/](setrules) (%d+) (.*)$", "^[#!/](setname) (.*)$", "^[#!/](setgpname) (%d+) (.*)$", "^[#!/](setname) (%d+) (.*)$", "^[#!/](lock) (%d+) (.*)$", "^[#!/](unlock) (%d+) (.*)$", "^[#!/](mute) (%d+)$", "^[#!/](unmute) (%d+)$", "^[#!/](settings) (.*) (%d+)$", "^[#!/](wholist)$", "^[#!/](who)$", "^[#!/]([Ww]hois) (.*)", "^[#!/](type)$", "^[#!/](kill) (chat) (%d+)$", "^[#!/](kill) (realm) (%d+)$", "^[#!/](rem) (%d+)$", "^[#!/](addadmin) (.*)$", -- sudoers only "^[#!/](removeadmin) (.*)$", -- sudoers only "[#!/ ](support)$", "^[#!/](support) (.*)$", "^[#!/](-support) (.*)$", "^[#!/](list) (.*)$", "^[#!/](log)$", "^[#!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/metropolis_torso_heavy_gtm_5.meta.lua
2
2835
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.43000000715255737, amplification = 140, light_colors = { "89 31 168 255", "48 42 88 255", "61 16 123 0" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = -6, y = -10 }, rotation = 45 }, head = { pos = { x = 2, y = -1 }, rotation = 17.198541641235352 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 10, y = 28 }, rotation = -33.690067291259766 }, secondary_hand = { pos = { x = 39, y = 7 }, rotation = 82.234832763671875 }, secondary_shoulder = { pos = { x = -1, y = 18 }, rotation = -166 }, shoulder = { pos = { x = 20, y = -11 }, rotation = -122 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
nasomi/darkstar
scripts/zones/Abyssea-Grauberg/npcs/Conflux_Surveyor.lua
49
3758
----------------------------------- -- Area: Abyssea - Grauberg -- NPC: Conflux Surveyor -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Grauberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/abyssea"); require("scripts/zones/Abyssea-Grauberg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local visitant = 0; local prevtime = player:getVar("Abyssea_Time"); local STONES = getTravStonesTotal(player); local SOJOURN = getAbyssiteTotal(player,"SOJOURN"); if (player:hasStatusEffect(EFFECT_VISITANT)) then visitant = 60; end player:startEvent(2002,0,visitant,prevtime,STONES,SOJOURN,0,0,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local SOJOURN = getAbyssiteTotal(player,"SOJOURN"); local duration = 0; local prevtime = player:getVar("Abyssea_Time"); -- Gets reduced by Visitants "on tic". if (prevtime > 7200) then prevtime = 7200; duration = prevtime; else duration = prevtime; end duration = duration+(SOJOURN *180); if (csid == 2002) then if (VISITANT_SYSTEM == false and (option == 65538 or option == 131074 or option == 196610 or option == 262146)) then player:addStatusEffect(EFFECT_VISITANT,0,0,0,0,0); -- using 0 should cause an infinate duration. elseif (option == 2) then -- Use no stones, use previous remaining time player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0); player:setVar("Abyssea_Time",duration); elseif (option == 65538) then -- Use 1 stone duration = ((duration + 1800) * VISITANT_BONUS); player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0); player:setVar("Abyssea_Time",duration); spendTravStones(player,1); elseif (option == 65539) then -- Use 1 stone player:PrintToPlayer( "Not implemented yet, sorry!" ); -- Todo: extend time elseif (option == 131074) then -- Use 2 stone duration = ((duration + 3600) * VISITANT_BONUS); player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0); player:setVar("Abyssea_Time",duration); spendTravStones(player,2); elseif (option == 131075) then -- Use 2 stone player:PrintToPlayer( "Not implemented yet, sorry!" ); -- Todo: extend time elseif (option == 196610) then -- Use 3 stone duration = ((duration + 5400) * VISITANT_BONUS); player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0); player:setVar("Abyssea_Time",duration); spendTravStones(player,3); elseif (option == 196611) then -- Use 3 stone player:PrintToPlayer( "Not implemented yet, sorry!" ); -- Todo: extend time elseif (option == 262146) then -- Use 4 stone duration = ((duration + 7200) * VISITANT_BONUS); player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0); player:setVar("Abyssea_Time",duration); spendTravStones(player,4); end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5fn.lua
34
2569
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: North Plate -- @pos 180 -34 71 195 ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local state0 = 8; local state1 = 9; local DoorOffset = npc:getID() - 22; -- _5f1 if (npc:getAnimation() == 8) then state0 = 9; state1 = 8; end -- Gates -- Shiva's Gate GetNPCByID(DoorOffset):setAnimation(state0); GetNPCByID(DoorOffset+1):setAnimation(state0); GetNPCByID(DoorOffset+2):setAnimation(state0); GetNPCByID(DoorOffset+3):setAnimation(state0); GetNPCByID(DoorOffset+4):setAnimation(state0); -- Odin's Gate GetNPCByID(DoorOffset+5):setAnimation(state1); GetNPCByID(DoorOffset+6):setAnimation(state1); GetNPCByID(DoorOffset+7):setAnimation(state1); GetNPCByID(DoorOffset+8):setAnimation(state1); GetNPCByID(DoorOffset+9):setAnimation(state1); -- Leviathan's Gate GetNPCByID(DoorOffset+10):setAnimation(state0); GetNPCByID(DoorOffset+11):setAnimation(state0); GetNPCByID(DoorOffset+12):setAnimation(state0); GetNPCByID(DoorOffset+13):setAnimation(state0); GetNPCByID(DoorOffset+14):setAnimation(state0); -- Titan's Gate GetNPCByID(DoorOffset+15):setAnimation(state1); GetNPCByID(DoorOffset+16):setAnimation(state1); GetNPCByID(DoorOffset+17):setAnimation(state1); GetNPCByID(DoorOffset+18):setAnimation(state1); GetNPCByID(DoorOffset+19):setAnimation(state1); -- Plates -- East Plate GetNPCByID(DoorOffset+20):setAnimation(state0); GetNPCByID(DoorOffset+21):setAnimation(state0); -- North Plate GetNPCByID(DoorOffset+22):setAnimation(state0); GetNPCByID(DoorOffset+23):setAnimation(state0); -- West Plate GetNPCByID(DoorOffset+24):setAnimation(state0); GetNPCByID(DoorOffset+25):setAnimation(state0); -- South Plate GetNPCByID(DoorOffset+26):setAnimation(state0); GetNPCByID(DoorOffset+27):setAnimation(state0); return 0; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/interference_grenade_released.meta.lua
4
1897
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 60, light_colors = { "255 165 0 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
Gamerbude/Wasteland
mods/coffin/init.lua
2
2420
minetest.register_node("coffin:gravestone", { description = "Gravestone", tiles = {"default_stone.png"}, paramtype = "light", paramtype2 = "facedir", groups = {dig_immediate = 1, cracky = 3}, sounds = default.node_sound_stone_defaults(), drop = "default:cobble", drawtype = "nodebox", node_box = {type = "fixed", fixed = { {-0.5,-0.5,-0.1,0.5,-0.3,0.5}, {-0.3,-0.3,0.1,0.3,0.7,0.3}, } } }) minetest.register_node("coffin:coffin", { description = "Coffin", tiles = { "coffin_top.png", "coffin_top.png", "coffin_side.png", "coffin_side.png", "coffin_side.png", "coffin_side.png", }, paramtype2 = "facedir", groups = {choppy = default.dig.old_chest}, sounds = default.node_sound_wood_defaults({ dug = {name = "ruins_chest_break", gain = 0.6}, }), drop = "default:stick 2", after_dig_node = default.drop_node_inventory(), }) minetest.register_alias("bones:bones", "coffin:coffin") minetest.register_alias("bones:gravestone", "coffin:gravestone") minetest.register_on_dieplayer(function(player) minetest.after(0.5, function() if minetest.setting_getbool("creative_mode") then return end local pos = player:getpos() pos.x = math.floor(pos.x+0.5) pos.y = math.floor(pos.y-0.5) pos.z = math.floor(pos.z+0.5) local param2 = minetest.dir_to_facedir(player:get_look_dir()) local nn = minetest.get_node(pos).name if minetest.registered_nodes[nn].can_dig and not minetest.registered_nodes[nn].can_dig(pos, player) then local player_inv = player:get_inventory() for i=1,player_inv:get_size("main") do player_inv:set_stack("main", i, nil) end for i=1,player_inv:get_size("craft") do player_inv:set_stack("craft", i, nil) end return end minetest.dig_node(pos) minetest.add_node(pos, {name="coffin:coffin", param2=param2}) pos.y = pos.y+1 minetest.set_node(pos, {name="coffin:gravestone", param2=param2}) local meta = minetest.get_meta(pos) meta:set_string("infotext", "RIP "..player:get_player_name()) pos.y = pos.y-1 meta = minetest.get_meta(pos) local inv = meta:get_inventory() local player_inv = player:get_inventory() inv:set_size("main", 8*4) local empty_list = inv:get_list("main") inv:set_list("main", player_inv:get_list("main")) player_inv:set_list("main", empty_list) for i=1,player_inv:get_size("craft") do inv:add_item("main", player_inv:get_stack("craft", i)) player_inv:set_stack("craft", i, nil) end end) end)
gpl-3.0
ngeiswei/ardour
share/scripts/_midi_rewrite.lua
4
1914
ardour { ["type"] = "session", name = "Rewrite Midi", license = "MIT", author = "Ardour Team", description = [[An example session script preprocesses midi buffers.]] } function factory () -- this function is called in every process cycle, before processing return function (n_samples) _, t = Session:engine ():get_ports (ARDOUR.DataType.midi (), ARDOUR.PortList ()) for p in t[2]:iter () do if not p:receives_input () then goto next end -- search-filter port if not p:name () == "MIDITrackName/midi_in 1" then goto next -- skip end -- ensure that the port is-a https://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:MidiPort assert (not p:to_midiport ():isnil ()) -- https://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:MidiBuffer local mb = p:to_midiport ():get_midi_buffer (n_samples) -- When an I/O port is connected (source -> sink), the -- buffer is shared. The MidiBuffer is in fact the buffer -- from the backend. Changing events in this buffer affects -- all destinations that use this buffer as source. local events = mb:table() -- *copy* event list to a Lua table mb:silence (n_samples, 0) -- clear existing buffer -- now iterate over events that were in the buffer for _,e in pairs (events) do -- e is-a http://manual.ardour.org/lua-scripting/class_reference/#Evoral:Event if e:size () == 3 then -- found a 3 byte event local buffer = e:buffer():array() local ev_type = buffer[1] >> 4 -- get MIDI event type (upper 4 bits) if ev_type == 8 or ev_type == 9 then -- note on or note off event buffer[1] = (buffer[1] & 0xf0) + 2 -- change the MIDI channel to "2" buffer[3] = buffer[3] >> 1 -- reduce the velocity by half end end -- finally place the event back into the Port's MIDI buffers mb:push_event (e) end ::next:: end end end
gpl-2.0
DevTeam-Co/maximus
bot/utils.lua
8
15523
--Begin Utils.lua By #BeyondTeam :) 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 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 = "data/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 run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end 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 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 function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end 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 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 function gp_type(chat_id) local gp_type = "pv" local id = tostring(chat_id) if id:match("^-100") then gp_type = "channel" elseif id:match("-") then gp_type = "chat" end return gp_type end function is_reply(msg) local var = false if msg.reply_to_message_id_ ~= 0 then -- reply message id is not 0 var = true end return var end function is_supergroup(msg) chat_id = tostring(msg.to.id) if chat_id:match('^-100') then --supergroups and channels start with -100 if not msg.is_post_ then return true end else return false end end function is_channel(msg) chat_id = tostring(msg.to.id) if chat_id:match('^-100') then -- Start with -100 (like channels and supergroups) if msg.is_post_ then -- message is a channel post return true else return false end end end function is_group(msg) chat_id = tostring(msg.to.id) if chat_id:match('^-100') then --not start with -100 (normal groups does not have -100 in first) return false elseif chat_id:match('^-') then return true else return false end end function is_private(msg) chat_id = tostring(msg.to.id) if chat_id:match('^-') then --private chat does not start with - return false else return true end end function check_markdown(text) --markdown escape ( when you need to escape markdown , use it like : check_markdown('your text') str = text if str:match('_') then output = str:gsub('_','\\_') elseif str:match('*') then output = str:gsub('*','\\*') elseif str:match('`') then output = str:gsub('`','\\`') else output = str end return output end 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 function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['owners'] then if data[tostring(msg.to.id)]['owners'][tostring(msg.from.id)] then var = true end end end for v,user in pairs(_config.admins) do if user[1] == msg.from.id then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin(msg) local var = false local user = msg.from.id for v,user in pairs(_config.admins) do if user[1] == msg.from.id 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 --Check if user is the mod of that group or not function is_mod(msg) local var = false local data = load_data(_config.moderation.data) local usert = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['mods'] then if data[tostring(msg.to.id)]['mods'][tostring(msg.from.id)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['owners'] then if data[tostring(msg.to.id)]['owners'][tostring(msg.from.id)] then var = true end end end for v,user in pairs(_config.admins) do if user[1] == msg.from.id then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_sudo1(user_id) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end function is_owner1(chat_id, user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id if data[tostring(chat_id)] then if data[tostring(chat_id)]['owners'] then if data[tostring(chat_id)]['owners'][tostring(user)] then var = true end end end for v,user in pairs(_config.admins) do if user[1] == user_id then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end function is_admin1(user_id) local var = false local user = user_id for v,user in pairs(_config.admins) do if user[1] == user_id then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_mod1(chat_id, user_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(chat_id)] then if data[tostring(chat_id)]['mods'] then if data[tostring(chat_id)]['mods'][tostring(usert)] then var = true end end end if data[tostring(chat_id)] then if data[tostring(chat_id)]['owners'] then if data[tostring(chat_id)]['owners'][tostring(usert)] then var = true end end end for v,user in pairs(_config.admins) do if user[1] == user_id then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end function is_banned(user_id, chat_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(chat_id)] then if data[tostring(chat_id)]['banned'] then if data[tostring(chat_id)]['banned'][tostring(user_id)] then var = true end end end return var end function is_silent_user(user_id, chat_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(chat_id)] then if data[tostring(chat_id)]['is_silent_users'] then if data[tostring(chat_id)]['is_silent_users'][tostring(user_id)] then var = true end end end return var end function is_gbanned(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local gban_users = 'gban_users' if data[tostring(gban_users)] then if data[tostring(gban_users)][tostring(user)] then var = true end end return var end function is_filter(msg, text) local var = false local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)]['filterlist'] then for k,v in pairs(data[tostring(msg.to.id)]['filterlist']) do if string.find(string.lower(text), string.lower(k)) then var = true end end end return var end function kick_user(user_id, chat_id) if not tonumber(user_id) then return false end tdcli.changeChatMemberStatus(chat_id, user_id, 'Kicked', dl_cb, nil) end function del_msg(chat_id, message_ids) local msgid = {[0] = message_ids} tdcli.deleteMessages(chat_id, msgid, dl_cb, nil) end function banned_list(chat_id) local hash = "gp_lang:"..chat_id local lang = redis:get(hash) local data = load_data(_config.moderation.data) local i = 1 if not data[tostring(msg.chat_id_)] then if not lang then return '_Group is not added_' else return 'گروه به لیست گروه های مدیریتی ربات اضافه نشده است' end end -- determine if table is empty if next(data[tostring(chat_id)]['banned']) == nil then --fix way if not lang then return "_No_ *banned* _users in this group_" else return "*هیچ کاربری از این گروه محروم نشده*" end end if not lang then message = '*List of banned users :*\n' else message = '_لیست کاربران محروم شده از گروه :_\n' end for k,v in pairs(data[tostring(chat_id)]['banned']) do message = message ..i.. '- '..v..' [' ..k.. '] \n' i = i + 1 end return message end function silent_users_list(chat_id) local hash = "gp_lang:"..chat_id local lang = redis:get(hash) local data = load_data(_config.moderation.data) local i = 1 if not data[tostring(msg.chat_id_)] then if not lang then return '_Group is not added_' else return 'گروه به لیست گروه های مدیریتی ربات اضافه نشده است' end end -- determine if table is empty if next(data[tostring(chat_id)]['is_silent_users']) == nil then --fix way if not lang then return "_No_ *silent* _users in this group_" else return "*لیست کاربران سایلنت شده خالی است*" end end if not lang then message = '*List of silent users :*\n' else message = '_لیست کاربران سایلنت شده :_\n' end for k,v in pairs(data[tostring(chat_id)]['is_silent_users']) do message = message ..i.. '- '..v..' [' ..k.. '] \n' i = i + 1 end return message end function gbanned_list(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local data = load_data(_config.moderation.data) local i = 1 if not data['gban_users'] then data['gban_users'] = {} save_data(_config.moderation.data, data) end if next(data['gban_users']) == nil then --fix way if not lang then return "_No_ *globally banned* _users available_" else return "*هیچ کاربری از گروه های ربات محروم نشده*" end end if not lang then message = '*List of globally banned users :*\n' else message = '_لیست کاربران محروم شده از گروه های ربات :_\n' end for k,v in pairs(data['gban_users']) do message = message ..i.. '- '..v..' [' ..k.. '] \n' i = i + 1 end return message end function filter_list(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local data = load_data(_config.moderation.data) if not data[tostring(msg.chat_id_)]['filterlist'] then data[tostring(msg.chat_id_)]['filterlist'] = {} save_data(_config.moderation.data, data) end if not data[tostring(msg.chat_id_)] then if not lang then return '_Group is not added_' else return 'گروه به لیست گروه های مدیریتی ربات اضافه نشده است' end end -- determine if table is empty if next(data[tostring(msg.chat_id_)]['filterlist']) == nil then --fix way if not lang then return "*Filtered words list* _is empty_" else return "_لیست کلمات فیلتر شده خالی است_" end end if not data[tostring(msg.chat_id_)]['filterlist'] then data[tostring(msg.chat_id_)]['filterlist'] = {} save_data(_config.moderation.data, data) end if not lang then filterlist = '*List of filtered words :*\n' else filterlist = '_لیست کلمات فیلتر شده :_\n' end local i = 1 for k,v in pairs(data[tostring(msg.chat_id_)]['filterlist']) do filterlist = filterlist..'*'..i..'* - _'..k..'_\n' i = i + 1 end return filterlist end
gpl-3.0
nasomi/darkstar
scripts/globals/items/seafood_stewpot.lua
36
1391
----------------------------------------- -- ID: 5238 -- Item: Seafood Stewpot -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10% Cap 50 -- MP +10 -- Accuracy 5 -- Evasion 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5238); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 50); target:addMod(MOD_MP, 10); target:addMod(MOD_ACC, 5); target:addMod(MOD_EVA, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 50); target:delMod(MOD_MP, 10); target:delMod(MOD_ACC, 5); target:delMod(MOD_EVA, 5); end;
gpl-3.0
DevTeam-Co/maximus
plugins/fullhlp.lua
1
4158
local function run(msg, matches) if matches[1] == "help" then if matches[2] == "sudo" and is_sudo(msg) then return "<b>You know it all Babe :|</b>" end if macthes[1] == "help" and is_owner(msg) then local text = [[<b>Owner help List</b>\n\n<b>[!#/]Lock [link|flood|tag|edit|arabic|webpage|spam|bots|markdown|mention]</b>\n\n<b>[!#/]Unlock [link|flood|tag|edit|arabic|webpage|spam|bots|markdown|mention]</b>\n\n<b>[!#/]modset [username|id|reply]</b>\n<i>promotes user to group admin</i>\n\n<b>[!#/]moddem [username|id|reply]</b>\n<i>demotes user from admin list</i>\n\n<b>[!#/]floodmax [1-200]</b>\n<i>set flooding number</i>\n\n<b>[!#/]silent [username|id|reply]</b>\n<i>silents user</i>\n\n<b>[!#/]unsilent [username|id|reply]</b>\n<i>unsilents user</i>\n\n<b>[!#/]kick [username|id|reply]</b>\n<i>kickes user from group</i>\n\n<b>[!#/]ban [username|id|reply]</b>\n<i>ban user from group</i>\n\n<b>[!#/]unban [username|id|reply]</b>\n<i>unbans user from group</i>\n\n<b>[!#/]res [username]</b>\n<i>show user id</i>\n\n<b>[!#/]userid [reply]</b>\n<i>show user id</i>\n\n<b>[!#/]whois [id]</b>\n<i>show user's username and name</i>\n\n<b>[!#/]mute [gifs|photo|document|sticker|video|text|forward|location|audio|voice|contact|all]</b>\n\n<b>[!#/]unlock [gifs|photo|document|sticker|video|text|forward|location|audio|voice|contact|all]</b>\n\n<b>[!#/]set [rules|name|photo|link|about|welcome]</b>\n\n<b>[!#/]delete [bans|mods|bots|rules|about|silentlist|filterlist|welcome]</b>\n\n<b>[!#/]filter [word]</b>\n\n<b>[!#/]unfilter [word]</b>\n\n<b>[!#/]pin [reply]</b>\n\n<b>[!#/]unpin</b>\n\n<b>[!#/]settings</b>\n\n<b>[!#/]mutelist</b>\n\n<b>[!#/]silentlist</b>\n\n<b>[!#/]filterlist</b>\n\n<b>[!#/]banlist</b>\n\n<b>[!#/]ownerlist</b>\n\n<b>[!#/]managers</b>\n\n<b>[!#/]rules</b>\n\n<b>[!#/]about</b>\n\n<b>[!#/]userid</b>\n<i>shows your id and chat id</i>\n\n<b>[!#/]gpinfo</b>\n\n<b>[!#/]link</b>\n\n<b>[!#/]setwelcome [text]</b>\n\n<b>help is going to be completed soon :)</b> ]] return text end if matches[1] == "help" and is_mod(msg) then local text [[<b>Owner help List</b>\n\n<b>[!#/]Lock [link|flood|tag|edit|arabic|webpage|spam|bots|markdown|mention]</b>\n\n<b>[!#/]Unlock [link|flood|tag|edit|arabic|webpage|spam|bots|markdown|mention]</b>\n\n<n<b>[!#/]floodmax [1-200]</b>\n<i>set flooding number</i>\n\n<b>[!#/]silent [username|id|reply]</b>\n<i>silents user</i>\n\n<b>[!#/]unsilent [username|id|reply]</b>\n<i>unsilents user</i>\n\n<b>[!#/]kick [username|id|reply]</b>\n<i>kickes user from group</i>\n\n<b>[!#/]ban [username|id|reply]</b>\n<i>ban user from group</i>\n\n<b>[!#/]unban [username|id|reply]</b>\n<i>unbans user from group</i>\n\n<b>[!#/]res [username]</b>\n<i>show user id</i>\n\n<b>[!#/]userid [reply]</b>\n<i>show user id</i>\n\n<b>[!#/]whois [id]</b>\n<i>show user's username and name</i>\n\n<b>[!#/]mute [gifs|photo|document|sticker|video|text|forward|location|audio|voice|contact|all]</b>\n\n<b>[!#/]unlock [gifs|photo|document|sticker|video|text|forward|location|audio|voice|contact|all]</b>\n\n<b>[!#/]set [rules|name|photo|link|about|welcome]</b>\n\n<b>[!#/]delete [bans|mods|bots|rules|about|silentlist|filterlist|welcome]</b>\n\n<b>[!#/]filter [word]</b>\n\n<b>[!#/]unfilter [word]</b>\n\n<b>[!#/]pin [reply]</b>\n\n<b>[!#/]unpin</b>\n\n<b>[!#/]settings</b>\n\n<b>[!#/]mutelist</b>\n\n<b>[!#/]silentlist</b>\n\n<b>[!#/]filterlist</b>\n\n<b>[!#/]banlist</b>\n\n<b>[!#/]ownerlist</b>\n\n<b>[!#/]managers</b>\n\n<b>[!#/]rules</b>\n\n<b>[!#/]about</b>\n\n<b>[!#/]userid</b>\n<i>shows your id and chat id</i>\n\n<b>[!#/]gpinfo</b>\n\n<b>[!#/]link</b>\n\n<b>[!#/]setwelcome [text]</b>\n\n<b>help is going to be completed soon :)</b> ]] return text end else if matches[1]"help" then local text [[<b>well...</b>\n<b>You can only suck my cock :|</b> ]] return text end return{ patterns = { "^[#!/](help)$" }, run=run } end --By @pedaret --Channel @nasakh
gpl-3.0
coolflyreg/gs
3rd/skynet-mingw/lualib/skynet/remotedebug.lua
54
5502
local skynet = require "skynet" local debugchannel = require "debugchannel" local socket = require "socket" local injectrun = require "skynet.injectcode" local table = table local debug = debug local coroutine = coroutine local sethook = debugchannel.sethook local M = {} local HOOK_FUNC = "raw_dispatch_message" local raw_dispatcher local print = _G.print local skynet_suspend local prompt local newline local function change_prompt(s) newline = true prompt = s end local function replace_upvalue(func, uvname, value) local i = 1 while true do local name, uv = debug.getupvalue(func, i) if name == nil then break end if name == uvname then if value then debug.setupvalue(func, i, value) end return uv end i = i + 1 end end local function remove_hook(dispatcher) assert(raw_dispatcher, "Not in debug mode") replace_upvalue(dispatcher, HOOK_FUNC, raw_dispatcher) raw_dispatcher = nil print = _G.print skynet.error "Leave debug mode" end local function gen_print(fd) -- redirect print to socket fd return function(...) local tmp = table.pack(...) for i=1,tmp.n do tmp[i] = tostring(tmp[i]) end table.insert(tmp, "\n") socket.write(fd, table.concat(tmp, "\t")) end end local function run_exp(ok, ...) if ok then print(...) end return ok end local function run_cmd(cmd, env, co, level) if not run_exp(injectrun("return "..cmd, co, level, env)) then print(select(2, injectrun(cmd,co, level,env))) end end local ctx_skynet = debug.getinfo(skynet.start,"S").short_src -- skip when enter this source file local ctx_term = debug.getinfo(run_cmd, "S").short_src -- term when get here local ctx_active = {} local linehook local function skip_hook(mode) local co = coroutine.running() local ctx = ctx_active[co] if mode == "return" then ctx.level = ctx.level - 1 if ctx.level == 0 then ctx.needupdate = true sethook(linehook, "crl") end else ctx.level = ctx.level + 1 end end function linehook(mode, line) local co = coroutine.running() local ctx = ctx_active[co] if mode ~= "line" then ctx.needupdate = true if mode ~= "return" then if ctx.next_mode or debug.getinfo(2,"S").short_src == ctx_skynet then ctx.level = 1 sethook(skip_hook, "cr") end end else if ctx.needupdate then ctx.needupdate = false ctx.filename = debug.getinfo(2, "S").short_src if ctx.filename == ctx_term then ctx_active[co] = nil sethook() change_prompt(string.format(":%08x>", skynet.self())) return end end change_prompt(string.format("%s(%d)>",ctx.filename, line)) return true -- yield end end local function add_watch_hook() local co = coroutine.running() local ctx = {} ctx_active[co] = ctx local level = 1 sethook(function(mode) if mode == "return" then level = level - 1 else level = level + 1 if level == 0 then ctx.needupdate = true sethook(linehook, "crl") end end end, "cr") end local function watch_proto(protoname, cond) local proto = assert(replace_upvalue(skynet.register_protocol, "proto"), "Can't find proto table") local p = proto[protoname] local dispatch = p.dispatch_origin or p.dispatch if p == nil or dispatch == nil then return "No " .. protoname end p.dispatch_origin = dispatch p.dispatch = function(...) if not cond or cond(...) then p.dispatch = dispatch -- restore origin dispatch function add_watch_hook() end dispatch(...) end end local function remove_watch() for co in pairs(ctx_active) do sethook(co) end ctx_active = {} end local dbgcmd = {} function dbgcmd.s(co) local ctx = ctx_active[co] ctx.next_mode = false skynet_suspend(co, coroutine.resume(co)) end function dbgcmd.n(co) local ctx = ctx_active[co] ctx.next_mode = true skynet_suspend(co, coroutine.resume(co)) end function dbgcmd.c(co) sethook(co) ctx_active[co] = nil change_prompt(string.format(":%08x>", skynet.self())) skynet_suspend(co, coroutine.resume(co)) end local function hook_dispatch(dispatcher, resp, fd, channel) change_prompt(string.format(":%08x>", skynet.self())) print = gen_print(fd) local env = { print = print, watch = watch_proto } local watch_env = { print = print } local function watch_cmd(cmd) local co = next(ctx_active) watch_env._CO = co if dbgcmd[cmd] then dbgcmd[cmd](co) else run_cmd(cmd, watch_env, co, 0) end end local function debug_hook() while true do if newline then socket.write(fd, prompt) newline = false end local cmd = channel:read() if cmd then if cmd == "cont" then -- leave debug mode break end if cmd ~= "" then if next(ctx_active) then watch_cmd(cmd) else run_cmd(cmd, env, coroutine.running(),2) end end newline = true else -- no input return end end -- exit debug mode remove_watch() remove_hook(dispatcher) resp(true) end local func local function hook(...) debug_hook() return func(...) end func = replace_upvalue(dispatcher, HOOK_FUNC, hook) if func then local function idle() skynet.timeout(10,idle) -- idle every 0.1s end skynet.timeout(0, idle) end return func end function M.start(import, fd, handle) local dispatcher = import.dispatch skynet_suspend = import.suspend assert(raw_dispatcher == nil, "Already in debug mode") skynet.error "Enter debug mode" local channel = debugchannel.connect(handle) raw_dispatcher = hook_dispatch(dispatcher, skynet.response(), fd, channel) end return M
gpl-2.0
nasomi/darkstar
scripts/globals/weaponskills/leg_sweep.lua
18
1532
----------------------------------- -- Leg Sweep -- Polearm weapon skill -- Skill Level: 100 -- Stuns enemy. Chance of stunning varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Thunder Gorget. -- Aligned with the Thunder Belt. -- Element: None -- Modifiers: STR:30% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 1.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); local chance = player:getTP()-100 > math.random()*150; if (damage > 0 and chance) then if (target:hasStatusEffect(EFFECT_STUN) == false) then target:addStatusEffect(EFFECT_STUN, 1, 0, 4); end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
renyaoxiang/QSanguosha-For-Hegemony
extension-doc/6-Applications.lua
8
9477
--技能讲解5:基本技能类型的组合和复杂技能的实现(一) --[[ 在游戏中,对于有些技能来说,我们不可能仅仅通过写一个技能来实现这些效果。 因此,基本技能的组合对于国战(也包括身份)来说是非常重要的。 在这个文档中,我们会介绍两种技能组合的形式。 第一种是并列式,也就是两个技能是并列存在的。 先来看这样一个技能: ]] --[[ 奇心:锁定技,你的手牌上限增加X,X为你当前的体力;你的攻击范围增加X,X为你损失的体力。 ]] --[[ 分析:通过技能描述,我们可以看出这个技能是由两个基本技能组成: 1.手牌上限 2.攻击范围 因此,我们需要写两个技能就能完成任务。 代码如下: ]] devQixin = sgs.CreateMaxCardsSkill{ name = "devQixin", extra_func = function(self, target) if target:hasSkill(self:objectName()) and (target:hasShownSkill(self) or target:askForSkillInvoke(self:objectName())) then --别忘了,手牌上限技在国战里面可是在服务器执行的,所以可以询问发动技能。 return target:getHp() end end } devQixinAttackRange = sgs.CreateAttackRangeSkill{ name = "#devQixin_attack", --技能名以#开头的技能会隐藏起来(没有按钮),但是仍然有效果 extra_func = function(self, target) if target:hasSkill(self:objectName()) and target:hasShownSkill(self) then return target:getLostHp() end end } sgs.insertRelatedSkills(extension,"devQixin","#devQixin_attack") --最后一句是把两个小技能组合起来,其中extension参数是扩展包,第二个参数是主技能(即不隐藏的技能),后面的是附加技能。 --附加技能可以有很多,如果有很多,可以这样写: sgs.insertRelatedSkills(extension,"main","#related1","#related2","#related3") --这里的字符串也可以换成技能对象,比如说: sgs.insertRelatedSkills(extension,devQixin,devQixinAttackRange) --[[ 看完上面的技能,你是否对技能组合有了一定的初步认识? 这些在身份局的相关教程也被介绍过。 我们再来看另外一种组合方式:嵌入式 对于嵌入式技能来说,一般是一个视为技+一个触发技的组合,二者用触发技的view_as_skill成员连接。 有些情况下,还需要技能卡的参与。 来看这样一个技能: ]] --[[ 奸雄:出牌阶段限一次,你可以将一张牌当作本出牌阶段上次使用的牌使用。(杀需要考虑限制) 其实就是英雄杀的曹操的技能。 ]] --[[ 我们可以把这个技能分成两个小部分: 1.在使用完基本牌后,记录一下基本牌的id 2.在视为技中获取id,然后制造出这样一张牌。 ]] devJiaoxiongVS = sgs.CreateViewAsSkill{ --这里可以换成OneCardViewAsSkill name = "devJiaoxiong", --这里的name要和下面触发技的保持一致。 n = 1, enabled_at_play = function(self, player) if player:getMark(self:objectName()) >= 0 then return not player:hasFlag("hasUsed"..self:objectName()) end end, view_filter = function(self, selected, to_select) return not to_select:isEquipped() end, view_as = function(self, cards) if #cards == 1 then local acard = sgs.Sanguosha:cloneCard(sgs.Sanguosha:getCard(sgs.Self:getMark(self:objectName())):objectName()) --sgs.Self也可以获取Mark,前提是使用Room的setPlayerMark设置。 assert(acard) --assert函数将会在后面的章节介绍 acard:addSubcard(cards[1]:getId()) acard:setSkillName(self:objectName()) acard:setShowSkill(self:objectName()) return acard end end, } devJiaoxiong = sgs.CreateTriggerSkill{ name = "devJiaoxiong", view_as_skill = devJiaoxiongVS, events = {sgs.CardFinished,sgs.EventPhaseStart}, can_trigger = function(self, event, room, player, data) if player and player:isAlive() and player:hasSkill(self:objectName()) then if player:getPhase() ~= sgs.Player_Play then return "" end if event == sgs.CardFinished then local use = data:toCardUse() local card = use.card if card:getSkillName() ~= self:objectName() and (not card:isKindOf("EquipCard")) then room:setPlayerMark(player,self:objectName(),card:getId()) --这里通过Mark来传递ID elseif card:getSkillName() == self:objectName() then room:setPlayerFlag(player,"hasUsed"..self:objectName()) room:setPlayerMark(player,self:objectName(),-1) --貌似有Id为0的Card,所以使用-1 end else room:setPlayerMark(player,self:objectName(),-1) end end return "" end } --[[ 这个技能由一个触发技和一个视为技组成,之间用view_as_skill连接起来。 其实这种方式和并列式差不多,当然这种方式比并列式更简洁,尤其是在处理提示使用(askForUseCard)的时候相当有效。 再来看一个相对复杂的技能: ]] --[[ 箭矢:每当你的黑色牌因弃置而失去时,你可将这些牌置于你的武将牌上称为“箭”。回合外你可将两张“箭”当成【无懈可击】使用。 ]] --[[ 分析:通过技能描述,我们可以看出这个技能是由两个基本技能组成的,一个是将被弃置的黑色牌置于牌堆上,另一种则是视为无懈可击。 这个技能有新旧两种形式,为了便于教学,我们这里使用旧式的技能作为范例。(新式的技能将会在后面用到) 代码如下: ]] devJianshiCard = sgs.CreateSkillCard{ name = "devJianshiCard", target_fixed = true, will_throw = false, skill_name = "devJianshi", on_validate = function(self, carduse) --这两个函数到下面再解释。 local source = cardUse.from local room = source:getRoom() local ncard = sgs.Sanguosha:cloneCard("nullification") ncard:setSkillName("devJianshi") local ids = source:getPile("devJianshi") for i = 0, 1, 1 do room:fillAG(ids, source) local id = room:askForAG(source, ids, false, "devJianshi") ncard:addSubcard(id) ids:removeOne(id) room:clearAG(source) end return ncard end, on_validate_in_response = function(self, source) --同理 local room = source:getRoom() local ncard = sgs.Sanguosha:cloneCard("nullification") ncard:setSkillName("devJianshi") local ids = source:getPile("devJianshi") for i = 0,1,1 do room:fillAG(ids, source) local id = room:askForAG(source, ids, false, "devJianshi") ncard:addSubcard(id) ids:removeOne(id) room:clearAG(source) end return ncard end, } devJianshiVS = sgs.CreateZeroCardViewAsSkill{ --详细定义可以参考lua\sgs_ex.lua name = "devJianshi", view_as = function(self) local ac = devJianshiCard:clone() ac:setSkillName("devJianshi") ac:setShowSkill("devJianshi") return ac end, enabled_at_play = function(self, player) return false end, enabled_at_response = function(self, player, pattern) return pattern == "nullification" and player:getPile("devJianshi"):length() > 1 end, enabled_at_nullification = function(self, player) return player:getPile("devJianshi"):length() > 1 end } devJianshi = sgs.CreateTriggerSkill{ name = "devJianshi", view_as_skill = devJianshiVS, events = {sgs.BeforeCardsMove}, can_trigger = function(self, event, room, player, data) if player and player:isAlive() and player:hasSkill(self:objectName()) then local move = data:toMoveOneTime() if move.from and move.from:objectName() ~= player:objectName() then return "" end if bit32.band(move.reason.m_reason, sgs.CardMoveReason_S_MASK_BASIC_REASON) == sgs.CardMoveReason_S_REASON_DISCARD then for i = 0, move.card_ids:length()-1, 1 do local id = move.card_ids:at(i) card = sgs.Sanguosha:getCard(id) if move.from_places:at(i) == sgs.Player_PlaceHand or move.from_places:at(i) == sgs.Player_PlaceEquip then if card:isBlack() then return self:objectName() end end end end return "" end end, on_cost = function(self, event, room, player, data) if player:askForSkillInvoke(self:objectName(), data) then return true end return false end , on_effect = function(self, event, room, player, data) local move = data:toMoveOneTime() local card local dummy = sgs.Sanguosha:cloneCard("jink") for i = 0, move.card_ids:length()-1, 1 do local id = move.card_ids:at(i) card = sgs.Sanguosha:getCard(id) if move.from_places:at(i) == sgs.Player_PlaceHand or move.from_places:at(i) == sgs.Player_PlaceEquip then if card:isBlack() then dummy:addSubcard(id) end end end for _,id in sgs.qlist(dummy:getSubcards()) do move.card_ids:removeOne(id) end data:setValue(move) --如果对data做过更变一定不要忘记setValue player:addToPile("devJianshi", dummy:getSubcards()) dummy:deleteLater() --记住,DummyCard不用一定要删除,否则会造成内存泄漏。 end, } --[[ 仔细研究一下这个技能,也有很多值得学习的地方,这里我们就不深入研究了。 通过以上几个例子发现,当一个技能在我们面前的时候,我们可以按照这样的步骤去完成技能代码: 1.分析技能,如果技能用一个基本技能就可以解决,就用一个技能解决;否则的话考虑使用两个或多个技能 2.分清职责,什么技能处理什么效果一定要明白。必要时可以使用注视。 3.撰写代码,这一步没有什么说的 4.组合,千万别忘记sgs.insertRelatedSkills或者view_as_skill ]]
gpl-3.0
nasomi/darkstar
scripts/zones/Mhaura/npcs/Standing_Bear.lua
34
1052
----------------------------------- -- Area: Mhaura -- NPC: Standing Bear ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0e); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Abyssea-Grauberg/npcs/Atma_Infusionist.lua
65
1058
----------------------------------- -- Area: Abyssea - Grauberg -- NPC: Atma Infusionist -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Grauberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/abyssea"); require("scripts/zones/Abyssea-Grauberg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(2003); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Al_Zahbi/npcs/Bornahn.lua
19
1147
----------------------------------- -- Area: Al Zahbi -- NPC: Bornahn -- Guild Merchant NPC: Goldsmithing Guild -- @pos 46.011 0.000 -42.713 48 ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Al_Zahbi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(60429,8,23,4)) then player:showText(npc,BORNAHN_SHOP_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
MatthewDwyer/botman
mudlet/profiles/newbot/scripts/reset_bot.lua
1
6443
--[[ Botman - A collection of scripts for managing 7 Days to Die servers Copyright (C) 2020 Matthew Dwyer This copyright applies to the Lua source code in this Mudlet profile. Email smegzor@gmail.com URL http://botman.nz Source https://bitbucket.org/mhdwyer/botman --]] function quickBotReset() -- reset stuff but don't touch players or locations or reset zones. teleports = {} invTemp = {} hotspots = {} lastHotspots = {} villagers = {} server.lottery = 0 server.mapSize = 10000 conn:execute("TRUNCATE TABLE alerts") conn:execute("TRUNCATE TABLE bookmarks") conn:execute("TRUNCATE TABLE commandQueue") conn:execute("TRUNCATE TABLE connectQueue") conn:execute("TRUNCATE TABLE events") conn:execute("TRUNCATE TABLE gimmeQueue") conn:execute("TRUNCATE TABLE hotspots") conn:execute("TRUNCATE TABLE ircQueue") conn:execute("TRUNCATE TABLE keystones") conn:execute("TRUNCATE TABLE list") conn:execute("TRUNCATE TABLE lottery") conn:execute("TRUNCATE TABLE mail") conn:execute("TRUNCATE TABLE memLottery") conn:execute("TRUNCATE TABLE memTracker") conn:execute("TRUNCATE TABLE messageQueue") conn:execute("TRUNCATE TABLE miscQueue") conn:execute("TRUNCATE TABLE performance") conn:execute("TRUNCATE TABLE playerQueue") conn:execute("TRUNCATE TABLE polls") conn:execute("TRUNCATE TABLE pollVotes") conn:execute("TRUNCATE TABLE teleports") conn:execute("TRUNCATE TABLE tracker") conn:execute("TRUNCATE TABLE searchResults") conn:execute("TRUNCATE TABLE inventoryChanges") conn:execute("TRUNCATE TABLE inventoryTracker") conn:execute("TRUNCATE TABLE waypoints") -- remove a flag so that the bot will re-test for installed mods. botMaintenance.modsInstalled = false saveBotMaintenance() end function resetBases() local sql conn:execute("TRUNCATE TABLE bases") -- reset bases in the players table sql = "UPDATE players SET homeX=0, home2X=0, homeY=0, home2Y=0, homeZ=0, home2Z=0, exitX=0, exit2X=0, exitY=0, exit2Y=0, exitZ=0, exit2Z=0, baseCooldown=0, protect=0, protect2=0, protectSize=" .. server.LandClaimSize .. ", protect2Size=" .. server.LandClaimSize conn:execute(sql) loadPlayers() end function ResetBot(keepTheMoney, backupName) if backupName then saveLuaTables(os.date("%Y%m%d_%H%M%S"), backupName) else saveLuaTables(os.date("%Y%m%d_%H%M%S")) end -- save some additional tables from mysql dumpTable("events") dumpTable("announcements") dumpTable("locationSpawns") dumpTable("alerts") -- clean up other tables teleports = {} invTemp = {} hotspots = {} resetRegions = {} lastHotspots = {} stackLimits = {} villagers = {} locations = {} waypoints = {} server.lottery = 0 server.warnBotReset = false server.playersCanFly = true conn:execute("TRUNCATE TABLE alerts") conn:execute("TRUNCATE TABLE bases") conn:execute("TRUNCATE TABLE bookmarks") conn:execute("TRUNCATE TABLE commandQueue") conn:execute("TRUNCATE TABLE connectQueue") conn:execute("TRUNCATE TABLE events") conn:execute("TRUNCATE TABLE gimmeQueue") conn:execute("TRUNCATE TABLE hotspots") conn:execute("TRUNCATE TABLE ircQueue") conn:execute("TRUNCATE TABLE keystones") conn:execute("TRUNCATE TABLE list") conn:execute("TRUNCATE TABLE locations") conn:execute("TRUNCATE TABLE locationSpawns") conn:execute("TRUNCATE TABLE lottery") conn:execute("TRUNCATE TABLE mail") conn:execute("TRUNCATE TABLE memLottery") conn:execute("TRUNCATE TABLE memTracker") conn:execute("TRUNCATE TABLE messageQueue") conn:execute("TRUNCATE TABLE miscQueue") conn:execute("TRUNCATE TABLE performance") conn:execute("TRUNCATE TABLE playerQueue") conn:execute("TRUNCATE TABLE polls") conn:execute("TRUNCATE TABLE pollVotes") conn:execute("TRUNCATE TABLE prefabCopies") conn:execute("TRUNCATE TABLE reservedSlots") conn:execute("TRUNCATE TABLE resetZones") conn:execute("TRUNCATE TABLE teleports") conn:execute("TRUNCATE TABLE tracker") conn:execute("TRUNCATE TABLE searchResults") conn:execute("TRUNCATE TABLE villagers") conn:execute("TRUNCATE TABLE inventoryChanges") conn:execute("TRUNCATE TABLE inventoryTracker") conn:execute("TRUNCATE TABLE waypoints") -- reset some data in the players table sql = "UPDATE players SET bail=0, bed='', bedX=0, bedY=0, bedZ=0, deaths=0, xPos=0, xPosOld=0, yPos=0, yPosOld=0, zPos=0, zPosOld=0, homeX=0, home2X=0, homeY=0, home2Y=0, homeZ=0, home2Z=0, exitX=0, exit2X=0, exitY=0, exit2Y=0, exitZ=0, exit2Z=0, exiled=0, keystones=0, location='lobby', canTeleport=1, botTimeout=0, allowBadInventory=0, baseCooldown=0, overstackTimeout=0, playerKills=0, prisoner=0, prisonReason='', prisonReleaseTime=0, prisonxPosOld=0, prisonyPosOld=0, prisonzPosOld=0, protect=0, protect2=0, protectSize=" .. server.LandClaimSize .. ", protect2Size=" .. server.LandClaimSize .. ", pvpBounty=0, pvpCount=0, pvpVictim=0, score=0, sessionCount=0, silentBob=0, walkies=0, zombies=0, timeout=0" if keepTheMoney == nil then sql = sql .. ", cash=0" end conn:execute(sql) loadPlayers() getServerData(true) -- remove a flag so that the bot will re-test for installed mods. botMaintenance.modsInstalled = false saveBotMaintenance() if botman.resetServer then botman.resetServer = nil restartBot() end end function ResetServer() -- This will wipe everything from the bot about the server and its players and it will ask the server for players and other info. -- For anything else, default values will be set until you change them. saveLuaTables(os.date("%Y%m%d_%H%M%S"), "undo_reset_server") botman.resetServer = true botman.serverTime = "" botman.feralWarning = false homedir = getMudletHomeDir() lfs.mkdir(homedir .. "/daily") lfs.mkdir(homedir .. "/dns") lfs.mkdir(homedir .. "/temp") lfs.mkdir(homedir .. "/chatlogs") lfs.mkdir(homedir .. "/data_backup") friends = {} gimmeQueuedCommands = {} hotspots = {} igplayers = {} invTemp = {} lastHotspots = {} locations = {} resetRegions = {} shopCategories = {} stackLimits = {} teleports = {} villagers = {} waypoints = {} if (botman.ExceptionCount == nil) then botman.ExceptionCount = 0 end botman.announceBot = true botman.botStarted = os.time() botman.faultyGimme = false botman.faultyChat = false botman.gimmeHell = 0 botman.scheduledRestartPaused = false botman.scheduledRestart = false botman.ExceptionRebooted = false if server.lottery == nil then server.lottery = 0 end forgetPlayers() ResetBot() end
gpl-3.0
nasomi/darkstar
scripts/zones/Windurst_Walls/npcs/Four_of_Diamonds.lua
38
1047
----------------------------------- -- Area: Windurst Walls -- NPC: Four of Diamonds -- Type: Standard NPC -- @zone: 239 -- @pos -187.184 -3.545 151.092 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x010b); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/West_Ronfaure/npcs/Doladepaiton_RK.lua
28
3142
----------------------------------- -- Area: West Ronfaure -- NPC: Doladepaiton, R.K. -- Type: Outpost Conquest Guards -- @pos -448 -19 -214 100 ------------------------------------- package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil; -------------------------------------- require("scripts/globals/conquest"); require("scripts/zones/West_Ronfaure/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = RONFAURE; local csid = 0x7ffb; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/rice_ball.lua
21
1402
----------------------------------------- -- ID: 4405 -- Item: Rice Ball -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 10, -- Vit +2 -- Dex -1 -- hHP +1 -- Effect with enhancing equipment (Note: these are latents on gear with the effect) -- Def +50 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4405); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_VIT, 2); target:addMod(MOD_DEX, -1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_VIT, 2); target:delMod(MOD_DEX, -1); end;
gpl-3.0
dageq/Dage-Aliraqi
plugins/en-banhammer.lua
11
12600
local function pre_process(msg) local data = load_data(_config.moderation.data) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned and not is_momod2(msg.from.id, msg.to.id) or is_gbanned(user_id) and not is_admin2(msg.from.id) then -- Check it with redis print('User is banned!') local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) >= 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) >= 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' or msg.to.type == 'channel' then local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) local chat_id = extra.chat_id local chat_type = extra.chat_type if chat_type == "chat" then receiver = 'chat#id'..chat_id else receiver = 'channel#id'..chat_id end if success == 0 then return send_large_msg(receiver, "Cannot find user by that username!") end local member_id = result.peer_id local user_id = member_id local member = result.username local from_id = extra.from_id local get_cmd = extra.get_cmd if get_cmd == "kick" then if member_id == from_id then send_large_msg(receiver, "You can't kick yourself") return end if is_momod2(member_id, chat_id) and not is_admin2(sender) then send_large_msg(receiver, "You can't kick mods/owner/admins") return end kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then send_large_msg(receiver, "You can't ban mods/owner/admins") return end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') banall_user(member_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally unbanned') unbanall_user(member_id) end end local function run(msg, matches) local support_id = msg.from.id if matches[1]:lower() == 'id' and msg.to.type == "chat" or msg.to.type == "user" then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' and msg.to.type == "chat" then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin1(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin1(msg) then msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id elseif string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") local receiver = get_receiver(msg) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(matches[2], msg.to.id) send_large_msg(receiver, 'User ['..matches[2]..'] banned') else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin1(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end elseif string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id print("sexy") local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if not is_admin1(msg) and not is_support(support_id) then return end if matches[1]:lower() == 'banall' and is_admin1(msg) then -- Global ban if type(msg.reply_id) ~="nil" and is_admin1(msg) then banall = get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] globally unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[#!/]([Bb]anall) (.*)$", "^[#!/]([Bb]anall)$", "^[#!/]([Bb]anlist) (.*)$", "^[#!/]([Bb]anlist)$", "^[#!/]([Gg]banlist)$", "^[#!/]([Kk]ickme)", "^[#!/]([Kk]ick)$", "^[#!/]([Bb]an)$", "^[#!/]([Bb]an) (.*)$", "^[#!/]([Uu]nban) (.*)$", "^[#!/]([Uu]nbanall) (.*)$", "^[#!/]([Uu]nbanall)$", "^[#!/]([Kk]ick) (.*)$", "^[#!/]([Uu]nban)$", "^[#!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0