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 |
|---|---|---|---|---|---|
jiang42/Algorithm-Implementations | Caesar_Cipher/Lua/Yonaba/caesar_cipher_test.lua | 26 | 1202 | -- Tests for caesar_cipher.lua
local caesar = require 'caesar_cipher'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
run('Ciphering test', function()
assert(caesar.cipher('abcd',1) == 'bcde')
assert(caesar.cipher('WXYZ',2) == 'YZAB')
assert(caesar.cipher('abcdefghijklmnopqrstuvwxyz',3) == 'defghijklmnopqrstuvwxyzabc')
assert(caesar.cipher('ABCDEFGHIJKLMNOPQRSTUVWXYZ',4) == 'EFGHIJKLMNOPQRSTUVWXYZABCD')
end)
run('Deciphering test', function()
assert(caesar.decipher('bcde',1) == 'abcd')
assert(caesar.decipher('YZAB',2) == 'WXYZ')
assert(caesar.decipher('defghijklmnopqrstuvwxyzabc',3) == 'abcdefghijklmnopqrstuvwxyz')
assert(caesar.decipher('EFGHIJKLMNOPQRSTUVWXYZABCD',4) == 'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
Fatalerror66/ffxi-a | scripts/globals/abilities/thunder_shot.lua | 2 | 2211 | -----------------------------------
-- Ability: Thunder Shot
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- OnUseAbility
-----------------------------------
function OnAbilityCheck(player,target,ability)
--ranged weapon/ammo: You do not have an appropriate ranged weapon equipped.
--no card: <name> cannot perform that action.
if (player:getWeaponSkillType(SLOT_RANGED) ~= SKILL_MRK or player:getWeaponSkillType(SLOT_AMMO) ~= SKILL_MRK) then
return 216,0;
end
if (player:hasItem(2180, 0) or player:hasItem(2974, 0)) then
return 0,0;
else
return 71, 0;
end
end;
function OnUseAbility(player, target, ability)
local dmg = 2 * player:getRangedDmg() + player:getAmmoDmg() + player:getMod(MOD_QUICK_DRAW_DMG);
dmg = addBonusesAbility(player, ELE_LIGHTNING, target, dmg);
dmg = dmg * applyResistanceAbility(player,target,ELE_LIGHTNING,SKILL_MRK);
dmg = adjustForTarget(target,dmg);
dmg = utils.stoneskin(target, dmg);
target:delHP(dmg);
target:updateEnmityFromDamage(player,dmg);
local effects = {};
local counter = 1;
local shock = target:getStatusEffect(EFFECT_SHOCK);
if (shock ~= nil) then
effects[counter] = shock;
counter = counter + 1;
end
local threnody = target:getStatusEffect(EFFECT_THRENODY);
if (threnody ~= nil and threnody:getSubPower() == MOD_WATERRES) then
effects[counter] = threnody;
counter = counter + 1;
end
if counter > 1 then
local effect = effects[math.random(1, counter-1)];
local duration = effect:getDuration();
local startTime = effect:getStartTime();
local tick = effect:getTick();
local power = effect:getPower();
local subpower = effect:getSubPower();
local tier = effect:getTier();
local effectId = effect:getType();
local subId = effect:getSubType();
power = power * 1.2;
target:delStatusEffectSilent(effectId);
target:addStatusEffect(effectId, power, tick, duration, subId, subpower, tier);
local newEffect = target:getStatusEffect(effectId);
newEffect:setStartTime(startTime);
end
return dmg;
end; | gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Mhaura/npcs/Yabby_Tanmikey.lua | 2 | 1140 | -----------------------------------
-- Area: Mhaura
-- NPC: Yabby Tanmikey
-- Guild Merchant NPC: Goldsmithing Guild
-- @pos -36.459 -16.000 76.840 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:sendGuild(528,8,23,4)) then
player:showText(npc,GOLDSMITHING_GUILD);
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 |
soumith/cuda-convnet2.torch | examples/load_imagenet.lua | 3 | 3737 | -- Copyright (c) 2014 by
-- Sergey Zagoruyko <sergey.zagoruyko@imagine.enpc.fr>
-- Francisco Massa <fvsmassa@gmail.com>
-- Universite Paris-Est Marne-la-Vallee/ENPC, LIGM, IMAGINE group
require 'cunn'
require 'ccn2'
require 'mattorch'
function load_imagenet(matfilename)
local fSize = {3, 96, 256, 384, 384, 256, 256*6*6, 4096, 4096, 1000}
local model = nn.Sequential()
model:add(nn.Transpose({1,4}, {1,3}, {1,2}))
model:add(ccn2.SpatialConvolution(fSize[1], fSize[2], 11, 4)) -- conv1
model:add(nn.ReLU()) -- relu1
model:add(ccn2.SpatialMaxPooling(3,2)) -- pool1
model:add(ccn2.SpatialCrossResponseNormalization(5)) -- norm1
model:add(ccn2.SpatialConvolution(fSize[2], fSize[3], 5, 1, 2, 2)) -- conv2
model:add(nn.ReLU()) -- relu2
model:add(ccn2.SpatialMaxPooling(3,2)) -- pool2
model:add(ccn2.SpatialCrossResponseNormalization(5)) -- norm2
model:add(ccn2.SpatialConvolution(fSize[3], fSize[4], 3, 1, 1)) -- conv3
model:add(nn.ReLU()) -- relu3
model:add(ccn2.SpatialConvolution(fSize[4], fSize[5], 3, 1, 1, 2)) -- conv4
model:add(nn.ReLU()) -- relu4
model:add(ccn2.SpatialConvolution(fSize[5], fSize[6], 3, 1, 1, 2)) -- conv5
model:add(nn.ReLU()) -- relu5
model:add(ccn2.SpatialMaxPooling(3,2)) -- pool5
model:add(nn.Transpose({4,1},{4,2},{4,3}))
model:add(nn.Reshape(fSize[7]))
model:add(nn.Linear(fSize[7], fSize[8])) -- fc6
model:add(nn.ReLU()) -- relu6
model:add(nn.Dropout(0.5)) -- drop6
model:add(nn.Linear(fSize[8], fSize[9])) -- fc7
model:add(nn.ReLU()) -- relu7
model:add(nn.Dropout(0.5)) -- drop7
model:add(nn.Linear(fSize[9], fSize[10])) -- fc8
model:cuda()
-- run to check consistency
local input = torch.randn(32, 3, 227, 227):cuda()
local output = model:forward(input)
print(output:size())
local mat = mattorch.load(matfilename)
local i = 2
model:get(i).weight = mat['conv1_w']:transpose(1,4):transpose(1,3):transpose(1,2):reshape(fSize[1]*11*11, fSize[2]):contiguous():cuda()
model:get(i).bias = mat['conv1_b']:squeeze():cuda()
i = 6
model:get(i).weight = mat['conv2_w']:transpose(1,4):transpose(1,3):transpose(1,2):reshape(fSize[2]*5*5/2, fSize[3]):contiguous():cuda()
model:get(i).bias = mat['conv2_b']:squeeze():cuda()
i = 10
model:get(i).weight = mat['conv3_w']:transpose(1,4):transpose(1,3):transpose(1,2):reshape(fSize[3]*3*3, fSize[4]):contiguous():cuda()
model:get(i).bias = mat['conv3_b']:squeeze():cuda()
i = 12
model:get(i).weight = mat['conv4_w']:transpose(1,4):transpose(1,3):transpose(1,2):reshape(fSize[4]*3*3/2, fSize[5]):contiguous():cuda()
model:get(i).bias = mat['conv4_b']:squeeze():cuda()
i = 14
model:get(i).weight = mat['conv5_w']:transpose(1,4):transpose(1,3):transpose(1,2):reshape(fSize[5]*3*3/2, fSize[6]):contiguous():cuda()
model:get(i).bias = mat['conv5_b']:squeeze():cuda()
i = 19
model:get(i).weight = mat['fc6_w']:cuda()
model:get(i).bias = mat['fc6_b']:squeeze():cuda()
i = 22
model:get(i).weight = mat['fc7_w']:cuda()
model:get(i).bias = mat['fc7_b']:squeeze():cuda()
i = 25
model:get(i).weight = mat['fc8_w']:cuda()
model:get(i).bias = mat['fc8_b']:squeeze():cuda()
-- run again to check consistency
output = model:forward(input)
print(output:size())
print(model)
return model
end
function preprocess(im, meanfilename)
-- rescale the image
local im3 = image.scale(im,227,227,'bilinear')*255
-- RGB2BGR
local im4 = im3:clone()
im4[{1,{},{}}] = im3[{3,{},{}}]
im4[{3,{},{}}] = im3[{1,{},{}}]
-- subtract imagenet mean
local img_mean = mattorch.load(meanfilename)['img_mean']:transpose(3,1)
return im4 - image.scale(img_mean, 227, 227,'bilinear')
end
| apache-2.0 |
Fatalerror66/ffxi-a | scripts/globals/abilities/wizards_roll.lua | 6 | 1407 | -----------------------------------
-- Ability: Choral Roll
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- OnUseAbility
-----------------------------------
function OnAbilityCheck(player,target,ability)
local effectID = getCorsairRollEffect(ability:getID());
if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then
return MSGBASIC_ROLL_ALREADY_ACTIVE,0;
else
return 0,0;
end
end;
function OnUseAbilityRoll(caster, target, ability, total)
local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK)
local effectpowers = {2, 3, 4, 4, 10, 5, 6, 7, 1, 7, 12, 4};
local effectpower = effectpowers[total]
if (total < 12 and caster:hasPartyJob(JOB_BLM) ) then
effectpower = effectpower + 3;
end
if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl());
elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl());
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_WIZARDS_ROLL, effectpower, 0, duration, target:getID(), total, MOD_MATT) == false) then
ability:setMsg(423);
end
end; | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Tavnazian_Safehold/npcs/Home_Point.lua | 10 | 1208 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Home Point
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (HOMEPOINT_HEAL == 1) then
player:addHP(player:getMaxHP());
player:addMP(player:getMaxMP());
end
player:startEvent(0x00fa);
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 (option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
end
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/globals/items/baked_popoto.lua | 2 | 1222 | -----------------------------------------
-- ID: 4436
-- Item: Baked Popoto
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health 20
-- Dexterity -1
-- Vitality 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4436);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_DEX, -1);
target:addMod(MOD_VIT, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_DEX, -1);
target:delMod(MOD_VIT, 2);
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Windurst_Waters_[S]/npcs/Koton-Llaton.lua | 4 | 1053 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Koton-Llaton
-- Type: Standard NPC
-- @zone: 94
-- @pos: 78.220 -3.75 -173.631
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0192);
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 |
Wedge009/wesnoth | data/ai/micro_ais/cas/ca_herding_sheep_runs_enemy.lua | 15 | 1688 | local AH = wesnoth.require "ai/lua/ai_helper.lua"
local M = wesnoth.map
local function get_next_sheep_enemies(cfg)
local sheep = AH.get_units_with_moves {
side = wesnoth.current.side,
{ "and", wml.get_child(cfg, "filter_second") }
}
if (not sheep[1]) then return end
local enemies = AH.get_attackable_enemies()
if (not enemies[1]) then return end
local attention_distance = cfg.attention_distance or 8
-- Simply return the first sheep, order does not matter
for _,single_sheep in ipairs(sheep) do
local close_enemies = {}
for _,enemy in ipairs(enemies) do
if (M.distance_between(single_sheep.x, single_sheep.y, enemy.x, enemy.y) <= attention_distance) then
table.insert(close_enemies, enemy)
end
end
if close_enemies[1] then
return single_sheep, enemies
end
end
end
local ca_herding_sheep_runs_enemy = {}
function ca_herding_sheep_runs_enemy:evaluation(cfg)
-- Sheep runs from any enemy within attention_distance hexes (after the dogs have moved in)
if get_next_sheep_enemies(cfg) then return cfg.ca_score end
return 0
end
function ca_herding_sheep_runs_enemy:execution(cfg)
local sheep, close_enemies = get_next_sheep_enemies(cfg)
-- Maximize distance between sheep and enemies
local best_hex = AH.find_best_move(sheep, function(x, y)
local rating = 0
for _,enemy in ipairs(close_enemies) do
rating = rating + M.distance_between(x, y, enemy.x, enemy.y)
end
return rating
end)
AH.movefull_stopunit(ai, sheep, best_hex)
end
return ca_herding_sheep_runs_enemy
| gpl-2.0 |
kidaa/FFXIOrgins | scripts/zones/Temenos/mobs/Abyssdweller_Jhabdebb.lua | 2 | 1552 | -----------------------------------
-- Area: Temenos
-- NPC:
-----------------------------------
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)
if (IsMobDead(16929010)==true and IsMobDead(16929011)==true and IsMobDead(16929012)==true and
IsMobDead(16929013)==true and IsMobDead(16929014)==true and IsMobDead(16929015)==true
)then
mob:setMod(MOD_SLASHRES,1400);
mob:setMod(MOD_PIERCERES,1400);
mob:setMod(MOD_IMPACTRES,1400);
mob:setMod(MOD_HTHRES,1400);
else
mob:setMod(MOD_SLASHRES,300);
mob:setMod(MOD_PIERCERES,300);
mob:setMod(MOD_IMPACTRES,300);
mob:setMod(MOD_HTHRES,300);
end
GetMobByID(16929006):updateEnmity(target);
GetMobByID(16929007):updateEnmity(target);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
if(IsMobDead(16929005)==true and IsMobDead(16929006)==true and IsMobDead(16929007)==true)then
GetNPCByID(16928768+78):setPos(-280,-161,-440);
GetNPCByID(16928768+78):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+473):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
KevinGuarnati/controllore | plugins/boobs.lua | 3 | 1719 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. 🔞",
"!butts: Get a butts NSFW image. 🔞"
},
patterns = {
"^!boobs$",
"^!butts$"
},
nsfw = true,
run = run
}
end
| mit |
MikePetullo/grilo-plugins | tests/lua-factory/data/test-source-lua-errors.lua | 4 | 4293 | --[[
* Copyright (C) 2016 Victor Toso.
*
* Contact: Victor Toso <me@victortoso.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
--]]
---------------------------
-- Source initialization --
---------------------------
source = {
id = "test-source-lua-errors",
name = "Fake Source",
description = "a source to test GrlMedia",
supported_keys = { "title" },
supported_media = "all",
resolve_keys = {
["type"] = "all",
required = { "url" } ,
},
tags = { 'test', 'net:plaintext' },
}
TEST_NOT_CALLBACK_SIMPLE = "test-not-calback-simple"
TEST_NOT_CALLBACK_ASYNC = "test-not-callback-on-async"
TEST_CALLBACK_ON_FINISHED_OP = "test-callback-after-finished"
TEST_MULTIPLE_FETCH = "multiple-fetch-with-callback"
---------------------------------
-- Handlers of Grilo functions --
---------------------------------
function grl_source_resolve()
local media = grl.get_media_keys()
local operation_id = grl.get_options("operation-id" )
if not media or not media.id or not media.url then
grl.warning ("test failed due lack of information")
grl.callback()
return
end
grl.debug ("source-resolve-test: " .. media.id)
if media.id == TEST_NOT_CALLBACK_SIMPLE then
test_not_callback_simple (media, operation_id)
elseif media.id == TEST_NOT_CALLBACK_ASYNC then
test_not_callback_async (media, operation_id)
elseif media.id == TEST_CALLBACK_ON_FINISHED_OP then
test_callback_on_finished_op (media, operation_id)
else
grl.warning ("test unknow: " .. media.id)
grl.callback()
end
end
function grl_source_search(test_id)
local url = "http://xml.parser.test/lua-factory/simple.xml"
local operation_id = grl.get_options("operation-id" )
grl.debug ("source-search-test: " .. test_id)
if test_id == TEST_MULTIPLE_FETCH then
test_multiple_fetch (url, operation_id)
else
grl.warning ("test unknow: " .. test_id)
grl.callback()
end
end
---------------------------------
-- Handlers of Tests functions --
---------------------------------
function test_multiple_fetch(url, operation_id)
grl.debug ("calling multiple grl.fetch and only grl.callback() "
.. "in the last one | operation-id: " .. operation_id)
grl.debug (url)
local test_t = { num_op = 4, received = 0 }
for i = 1, test_t.num_op do
grl.debug ("operation: " .. i)
grl.fetch(url, fetch_multiple_url_cb, test_t)
end
end
function test_not_callback_simple (media, operation_id)
grl.debug ("not calling grl.callback, operation-id: " .. operation_id)
end
function test_callback_on_finished_op (media, operation_id)
grl.debug ("calling grl.callback after operation is over, "
.. "operation-id: " .. operation_id)
grl.callback ({title = "grilo-1" }, 0)
grl.callback ({title = "grilo-2" }, 0)
end
function test_not_callback_async (media, operation_id)
grl.debug ("calling grl.fetch but not grl.callback, "
.. "operation-id: " .. operation_id)
grl.fetch(media.url, fetch_url_cb)
end
---------------------------------
-- Callbacks --------------------
---------------------------------
function fetch_multiple_url_cb(feeds, data)
if not data then
grl.warning ("Fail to get userdata")
return
end
data.received = data.received + 1
grl.debug (string.format("fetch_multiple_url_cb: received %d/%d",
data.received, data.num_op))
local media = { title = "title: " .. data.received }
local count = data.num_op - data.received
grl.callback (media, count)
end
function fetch_url_cb(feeds)
grl.debug ("fetch_url_cb: not calling grl.callback()" )
end
| lgpl-2.1 |
actionless/awesome | tests/examples/wibox/nwidget/default.lua | 4 | 3116 | --DOC_GEN_IMAGE --DOC_HIDE_ALL
local parent = ...
local naughty = require("naughty")
local wibox = require("wibox")
local beautiful = require("beautiful")
local def = require("naughty.widget._default")
local acommon = require("awful.widget.common")
local aplace = require("awful.placement")
local gears = require("gears")
beautiful.notification_bg = beautiful.bg_normal
local notif = naughty.notification {
title = "A notification",
message = "This notification has actions!",
icon = beautiful.awesome_icon,
actions = {
naughty.action {
name = "Accept",
icon = beautiful.awesome_icon,
},
naughty.action {
name = "Refuse",
icon = beautiful.awesome_icon,
},
naughty.action {
name = "Ignore",
icon = beautiful.awesome_icon,
},
}
}
local default = wibox.widget(def)
acommon._set_common_property(default, "notification", notif)
local w, h = default:fit({dpi=96}, 9999, 9999)
default.forced_width = w + 25
default.forced_height = h
local canvas = wibox.layout.manual()
canvas.forced_width = w + 150
canvas.forced_height = h + 100
canvas:add_at(default, aplace.centered)
local function create_info(text, x, y, width, height)
canvas:add_at(wibox.widget {
{
{
text = text,
align = "center",
ellipsize = "none",
wrap = "word",
widget = wibox.widget.textbox
},
top = 2,
bottom = 2,
left = 10,
right = 10,
widget = wibox.container.margin
},
forced_width = width,
forced_height = height,
shape = gears.shape.rectangle,
shape_border_width = 1,
shape_border_color = beautiful.border_color,
bg = "#ffff0055",
widget = wibox.container.background
}, {x = x, y = y})
end
local function create_line(x1, y1, x2, y2)
return canvas:add_at(wibox.widget {
fit = function()
return x2-x1+6, y2-y1+6
end,
draw = function(_, _, cr)
cr:set_source_rgb(0,0,0)
cr:set_line_width(1)
cr:arc(1.5, 1.5, 1.5, 0, math.pi*2)
cr:arc(x2-x1+1.5, y2-y1+1.5, 1.5, 0, math.pi*2)
cr:fill()
cr:move_to(1.5,1.5)
cr:line_to(x2-x1+1.5, y2-y1+1.5)
cr:stroke()
end,
layout = wibox.widget.base.make_widget,
}, {x=x1, y=y1})
end
create_info("naughty.widget.background", 10, canvas.forced_height - 30, nil, nil)
create_line(80, canvas.forced_height-55, 80, canvas.forced_height - 30)
create_info("naughty.list.actions", 170, canvas.forced_height - 30, nil, nil)
create_line(200, canvas.forced_height-105, 200, canvas.forced_height - 30)
create_info("naughty.widget.icon", 20, 25, nil, nil)
create_line(80, 40, 80, 60)
create_info("naughty.widget.title", 90, 4, nil, nil)
create_line(140, 20, 140, 60)
create_info("naughty.widget.message", 150, 25, nil, nil)
create_line(210, 40, 210, 75)
parent:add(canvas)
| gpl-2.0 |
flyzjhz/openwrt-bb | feeds/luci/applications/luci-vnstat/luasrc/model/cbi/vnstat.lua | 90 | 2019 | --[[
LuCI - Lua Configuration Interface
Copyright 2010-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 utl = require "luci.util"
local sys = require "luci.sys"
local fs = require "nixio.fs"
local nw = require "luci.model.network"
local dbdir, line
for line in io.lines("/etc/vnstat.conf") do
dbdir = line:match("^%s*DatabaseDir%s+[\"'](%S-)[\"']")
if dbdir then break end
end
dbdir = dbdir or "/var/lib/vnstat"
m = Map("vnstat", translate("VnStat"),
translate("VnStat is a network traffic monitor for Linux that keeps a log of network traffic for the selected interface(s)."))
m.submit = translate("Restart VnStat")
m.reset = false
nw.init(luci.model.uci.cursor_state())
local ifaces = { }
local enabled = { }
local iface
if fs.access(dbdir) then
for iface in fs.dir(dbdir) do
if iface:sub(1,1) ~= '.' then
ifaces[iface] = iface
enabled[iface] = iface
end
end
end
for _, iface in ipairs(sys.net.devices()) do
ifaces[iface] = iface
end
local s = m:section(TypedSection, "vnstat")
s.anonymous = true
s.addremove = false
mon_ifaces = s:option(Value, "interface", translate("Monitor selected interfaces"))
mon_ifaces.template = "cbi/network_ifacelist"
mon_ifaces.widget = "checkbox"
mon_ifaces.cast = "table"
mon_ifaces.noinactive = true
mon_ifaces.nocreate = true
function mon_ifaces.write(self, section, val)
local i
local s = { }
if val then
for _, i in ipairs(type(val) == "table" and val or { val }) do
s[i] = true
end
end
for i, _ in pairs(ifaces) do
if not s[i] then
fs.unlink(dbdir .. "/" .. i)
fs.unlink(dbdir .. "/." .. i)
end
end
if next(s) then
m.uci:set_list("vnstat", section, "interface", utl.keys(s))
else
m.uci:delete("vnstat", section, "interface")
end
end
mon_ifaces.remove = mon_ifaces.write
return m
| gpl-2.0 |
woesdo/XY | plugins/plugins.lua | 88 | 6304 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '❌'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '✔'
end
nact = nact+1
end
if not only_enabled or status == '✔' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
Fatalerror66/ffxi-a | scripts/zones/Upper_Jeuno/TextIDs.lua | 2 | 1594 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6617; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6537; -- Obtained: <item>
GIL_OBTAINED = 6538; -- Obtained <number> gil
KEYITEM_OBTAINED = 6540; -- Obtained key item: <keyitem>
NOT_HAVE_ENOUGH_GIL = 6542; -- You do not have enough gil.
HOMEPOINT_SET = 6610; -- Home point set!
GUIDE_STONE = 6867; -- Up: Ru'Lude Gardens, Down: Lower Jeuno
-- Other Texts
ITEM_DELIVERY_DIALOG = 7961; -- Delivering goods to residences everywhere!
-- Conquest system
CONQUEST = 7628; -- You've earned conquest points!
-- NPC Texts
KIRISOMANRISO_DIALOG = 7961; -- Delivering goods to residences everywhere!
YOU_CAN_NOW_BECOME_A_BEASTMASTER = 7072; -- You can now become a beastmaster.
-- Shop Texts
GLYKE_SHOP_DIALOG = 6862; -- Can I help you?
MEJUONE_SHOP_DIALOG = 6863; -- Welcome to the Chocobo Shop.
COUMUNA_SHOP_DIALOG = 6864; -- Welcome to Viette's Finest Weapons.
ANTONIA_SHOP_DIALOG = 6864; -- Welcome to Viette's Finest Weapons.
DEADLYMINNOW_SHOP_DIALOG = 6865; -- Welcome to Durable Shields.
KHECHALAHKO_SHOP_DIALOG = 6865; -- Welcome to Durable Shields.
AREEBAH_SHOP_DIALOG = 6866; -- Welcome to M & P's Market.
CHAMPALPIEU_SHOP_DIALOG = 6866; -- Welcome to M & P's Market.
LEILLAINE_SHOP_DIALOG = 6892; -- Hello. Are you feeling all right?
-- Lakeside Minuet - DNC flag quest text
UNLOCK_DANCER = 11715; -- You can now become a dancer!
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/items/tortilla_bueno.lua | 1 | 1145 | -----------------------------------------
-- ID: 5181
-- Item: tortilla_bueno
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 8
-- Vitality 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5181);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 8);
target:addMod(MOD_VIT, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 8);
target:delMod(MOD_VIT, 4);
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/globals/items/bowl_of_riverfin_soup.lua | 3 | 1761 | -----------------------------------------
-- ID: 6069
-- Item: Bowl of Riverfin Soup
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- Accuracy % 14 Cap 90
-- Ranged Accuracy % 14 Cap 90
-- Attack % 18 Cap 80
-- Ranged Attack % 18 Cap 80
-- Amorph Killer 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,6069);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_ACCP, 14);
target:addMod(MOD_FOOD_ACC_CAP, 90);
target:addMod(MOD_FOOD_RACCP, 14);
target:addMod(MOD_FOOD_RACC_CAP, 90);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 80);
target:addMod(MOD_FOOD_RATTP, 18);
target:addMod(MOD_FOOD_RATT_CAP, 80);
target:addMod(MOD_AMORPH_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_ACCP, 14);
target:delMod(MOD_FOOD_ACC_CAP, 90);
target:delMod(MOD_FOOD_RACCP, 14);
target:delMod(MOD_FOOD_RACC_CAP, 90);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 80);
target:delMod(MOD_FOOD_RATTP, 18);
target:delMod(MOD_FOOD_RATT_CAP, 80);
target:delMod(MOD_AMORPH_KILLER, 5);
end;
| gpl-3.0 |
tltneon/nsplugins | plugins/playx/sv_plugin.lua | 2 | 1608 | local PLUGIN = PLUGIN
function PLUGIN:LoadData()
if not PlayX then return end
local screen = ents.Create("gmod_playx")
screen:SetModel("models/dav0r/camera.mdl")
screen:SetPos(self.screenPos)
screen:SetAngles(self.screenAng)
screen:SetRenderMode(RENDERMODE_TRANSALPHA)
screen:SetColor(Color(255, 255, 255, 1))
screen:Spawn()
screen:Activate()
local phys = screen:GetPhysicsObject()
if IsValid(phys) then
phys:EnableMotion(false)
phys:Sleep()
end
end
function PLUGIN:KeyPress( ply, key )
if not PlayX then return end
if key == IN_USE then
local data = {}
data.start = ply:GetShootPos()
data.endpos = data.start + ply:GetAimVector() * 84
data.filter = ply
local entity = util.TraceLine(data).Entity
local isController = false
if IsValid(entity) then
for _, v in pairs(self.controllers) do
if entity:MapCreationID() == v then
isController = true
end
end
end
if isController then
if not ply:HasFlag("m") then
PlayX.SendError(ply, "You do not have permission to use the player")
return
end
ply.nextMusicUse = ply.nextMusicUse or 0
if CurTime() > ply.nextMusicUse then
netstream.Start(ply, "nut_RequestPlayxURL")
ply.nextMusicUse = CurTime() + 1.5
end
end
end
end
netstream.Hook("nut_MediaRequest", function( ply, url )
if not PlayX then return end
if not ply:hasFlag("m") and not ply:IsAdmin() then
PlayX.SendError(ply, "You do not have permission to use the player")
return
end
local result, err = PlayX.OpenMedia("", url, 0, false, true, false)
if not result then
PlayX.SendError(ply, err)
end
end) | gpl-2.0 |
Fatalerror66/ffxi-a | scripts/zones/Lower_Jeuno/npcs/_l10.lua | 36 | 1556 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Streetlamp
-- Involved in Quests: Community Service
-- @zone 245
-- @pos -19 0 -4.625
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
if (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then
if (player:getVar("cService") == 1) then
player:setVar("cService",2);
end
elseif (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then
if (player:getVar("cService") == 14) then
player:setVar("cService",15);
end
end
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);
end; | gpl-3.0 |
flyzjhz/openwrt-bb | feeds/luci/modules/freifunk/luasrc/model/cbi/freifunk/basics.lua | 74 | 3518 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2011 Manuel Munz <freifunk at somakoma de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]
local fs = require "luci.fs"
local util = require "luci.util"
local uci = require "luci.model.uci".cursor()
local profiles = "/etc/config/profile_"
m = Map("freifunk", translate ("Community"))
c = m:section(NamedSection, "community", "public", nil, translate("These are the basic settings for your local wireless community. These settings define the default values for the wizard and DO NOT affect the actual configuration of the router."))
community = c:option(ListValue, "name", translate ("Community"))
community.rmempty = false
local list = { }
local list = fs.glob(profiles .. "*")
for k,v in ipairs(list) do
local name = uci:get_first(v, "community", "name") or "?"
local n = string.gsub(v, profiles, "")
community:value(n, name)
end
n = Map("system", translate("Basic system settings"))
function n.on_after_commit(self)
luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "basics"))
end
b = n:section(TypedSection, "system")
b.anonymous = true
hn = b:option(Value, "hostname", translate("Hostname"))
hn.rmempty = false
hn.datatype = "hostname"
loc = b:option(Value, "location", translate("Location"))
loc.rmempty = false
loc.datatype = "minlength(1)"
lat = b:option(Value, "latitude", translate("Latitude"), translate("e.g.") .. " 48.12345")
lat.datatype = "float"
lat.rmempty = false
lon = b:option(Value, "longitude", translate("Longitude"), translate("e.g.") .. " 10.12345")
lon.datatype = "float"
lon.rmempty = false
--[[
Opens an OpenStreetMap iframe or popup
Makes use of resources/OSMLatLon.htm and htdocs/resources/osm.js
]]--
local class = util.class
local ff = uci:get("freifunk", "community", "name") or ""
local co = "profile_" .. ff
local deflat = uci:get_first("system", "system", "latitude") or uci:get_first(co, "community", "latitude") or 52
local deflon = uci:get_first("system", "system", "longitude") or uci:get_first(co, "community", "longitude") or 10
local zoom = 12
if ( deflat == 52 and deflon == 10 ) then
zoom = 4
end
OpenStreetMapLonLat = luci.util.class(AbstractValue)
function OpenStreetMapLonLat.__init__(self, ...)
AbstractValue.__init__(self, ...)
self.template = "cbi/osmll_value"
self.latfield = nil
self.lonfield = nil
self.centerlat = ""
self.centerlon = ""
self.zoom = "0"
self.width = "100%" --popups will ignore the %-symbol, "100%" is interpreted as "100"
self.height = "600"
self.popup = false
self.displaytext="OpenStreetMap" --text on button, that loads and displays the OSMap
self.hidetext="X" -- text on button, that hides OSMap
end
osm = b:option(OpenStreetMapLonLat, "latlon", translate("Find your coordinates with OpenStreetMap"), translate("Select your location with a mouse click on the map. The map will only show up if you are connected to the Internet."))
osm.latfield = "latitude"
osm.lonfield = "longitude"
osm.centerlat = uci:get_first("system", "system", "latitude") or deflat
osm.centerlon = uci:get_first("system", "system", "longitude") or deflon
osm.zoom = zoom
osm.width = "100%"
osm.height = "600"
osm.popup = false
osm.displaytext=translate("Show OpenStreetMap")
osm.hidetext=translate("Hide OpenStreetMap")
return m, n
| gpl-2.0 |
pavouk/lgi | samples/gstvideo.lua | 6 | 3219 | #! /usr/bin/env lua
--
-- Sample GStreamer application, based on public Vala GStreamer Video
-- Example (http://live.gnome.org/Vala/GStreamerSample)
--
local lgi = require 'lgi'
local GLib = lgi.GLib
local Gtk = lgi.Gtk
local GdkX11 = lgi.GdkX11
local Gst = lgi.Gst
if tonumber(Gst._version) >= 1.0 then
local GstVideo = lgi.GstVideo
end
local app = Gtk.Application { application_id = 'org.lgi.samples.gstvideo' }
local window = Gtk.Window {
title = "LGI Based Video Player",
Gtk.Box {
orientation = 'VERTICAL',
Gtk.DrawingArea {
id = 'video',
expand = true,
width = 300,
height = 150,
},
Gtk.ButtonBox {
orientation = 'HORIZONTAL',
Gtk.Button {
id = 'play',
use_stock = true,
label = Gtk.STOCK_MEDIA_PLAY,
},
Gtk.Button {
id = 'stop',
use_stock = true,
sensitive = false,
label = Gtk.STOCK_MEDIA_STOP,
},
Gtk.Button {
id = 'quit',
use_stock = true,
label = Gtk.STOCK_QUIT,
},
},
}
}
function window.child.quit:on_clicked()
window:destroy()
end
local pipeline = Gst.Pipeline.new('mypipeline')
local src = Gst.ElementFactory.make('autovideosrc', 'videosrc')
local colorspace = Gst.ElementFactory.make('videoconvert', 'colorspace')
or Gst.ElementFactory.make('ffmpegcolorspace', 'colorspace')
local scale = Gst.ElementFactory.make('videoscale', 'scale')
local rate = Gst.ElementFactory.make('videorate', 'rate')
local sink = Gst.ElementFactory.make('xvimagesink', 'sink')
pipeline:add_many(src, colorspace, scale, rate, sink)
src:link_many(colorspace, scale, rate, sink)
function window.child.play:on_clicked()
pipeline.state = 'PLAYING'
end
function window.child.stop:on_clicked()
pipeline.state = 'PAUSED'
end
local function bus_callback(bus, message)
if message.type.ERROR then
print('Error:', message:parse_error().message)
Gtk.main_quit()
end
if message.type.EOS then
print 'end of stream'
end
if message.type.STATE_CHANGED then
local old, new, pending = message:parse_state_changed()
print(string.format('state changed: %s->%s:%s', old, new, pending))
-- Set up sensitive state on buttons according to current state.
-- Note that this is forwarded to mainloop, because bus callback
-- can be called in some side thread and Gtk might not like to
-- be controlled from other than main thread on some platforms.
GLib.idle_add(GLib.PRIORITY_DEFAULT, function()
window.child.play.sensitive = (new ~= 'PLAYING')
window.child.stop.sensitive = (new == 'PLAYING')
return GLib.SOURCE_REMOVE
end)
end
if message.type.TAG then
message:parse_tag():foreach(
function(list, tag)
print(('tag: %s = %s'):format(tag, tostring(list:get(tag))))
end)
end
return true
end
function window.child.video:on_realize()
-- Retarget video output to the drawingarea.
sink:set_window_handle(self.window:get_xid())
end
function app:on_activate()
window.application = app
pipeline.bus:add_watch(GLib.PRIORITY_DEFAULT, bus_callback)
window:show_all()
end
app:run { arg[0], ... }
-- Must always set the pipeline to NULL before disposing it
pipeline.state = 'NULL'
| mit |
kidaa/FFXIOrgins | scripts/zones/Riverne-Site_B01/npcs/_0t2.lua | 4 | 1283 | -----------------------------------
-- Area: Riverne Site #B01
-- NPC: Unstable Displacement
-----------------------------------
package.loaded["scripts/zones/Riverne-Site_B01/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Riverne-Site_B01/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale
player:tradeComplete();
npc:openDoor(RIVERNE_PORTERS);
player:messageSpecial(SD_HAS_GROWN);
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
if(npc:getAnimation() == 8) then
player:startEvent(0x16);
else
player:messageSpecial(SD_VERY_SMALL);
end;
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
actionless/awesome | spec/wibox/container/margin_spec.lua | 2 | 1966 | ---------------------------------------------------------------------------
-- @author Uli Schlachter
-- @copyright 2017 Uli Schlachter
---------------------------------------------------------------------------
local base = require('wibox.widget.base')
local margin = require("wibox.container.margin")
local imagebox = require("wibox.widget.imagebox")
local utils = require("wibox.test_utils")
describe("wibox.container.margin", function()
it("common interfaces", function()
utils.test_container(margin())
end)
describe("composite widgets", function()
it("can be wrapped with child", function()
local widget_name = "test_widget"
local new = function()
local ret = base.make_widget_declarative {
{
id = "img",
widget = imagebox,
},
widget = margin,
}
ret.widget_name = widget_name
return ret
end
local widget = base.make_widget_declarative {
widget = new,
}
assert.is.equal(
widget_name,
widget.widget_name,
"Widget name doesn't match"
)
local children = widget:get_children()
assert.is_not.Nil(children, "Widget doesn't have children")
assert.is.equal(
1,
#children,
"Widget should have exactly one child"
)
assert.is.True(
children[1].is_widget,
"Child widget should be a valid widget"
)
assert.is.equal(
widget.img,
children[1],
"Child widget should match the id accessor"
)
end)
end)
end)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
Inorizushi/DDR-EXTREME-JP-SM5 | BGAnimations/ScreenTitleJoin background/default.lua | 1 | 1439 | function memcardActor(player)
return LoadActor(THEME:GetPathG("MemoryCard", "Icons"))..{
InitCommand=cmd(vertalign,bottom;xy,THEME:GetMetric("ScreenSystemLayer","Credits"..pname(player).."X"),SCREEN_BOTTOM;zoom,2;animate,false;);
OnCommand=cmd(visible,ToEnumShortString(MEMCARDMAN:GetCardState(player)) == 'ready');
StorageDevicesChangedMessageCommand=function(self)
local memCardState = ToEnumShortString(MEMCARDMAN:GetCardState(player))
self:visible(true)
if memCardState == 'checking' then
self:setstate(2);
elseif memCardState == "ready" then
self:setstate(1);
elseif memCardState == "none" then
self:visible(false)
else
self:setstate(4)
end;
end;
};
end
return Def.ActorFrame{
Def.Sprite{
Texture=THEME:GetPathB("ScreenLogo","background/bg.png");
InitCommand=cmd(Center);
};
--[[LoadActor("a")..{
InitCommand=cmd(Center);
};]]
LoadActor("start")..{
InitCommand=cmd(xy,SCREEN_CENTER_X,SCREEN_BOTTOM-70;diffuseblink;linear,0.5;effectcolor1,color(".5,.5,.5,1"));
};
-- Memory cards
memcardActor(PLAYER_1);
memcardActor(PLAYER_2);
--[[LoadActor(THEME:GetPathG("", "USB icon"))..{
InitCommand=cmd(horizalign,right;vertalign,bottom;xy,SCREEN_RIGHT-5,SCREEN_BOTTOM;zoom,.2);
--OnCommand=cmd(visible,true);
OnCommand=cmd(visible,ToEnumShortString(MEMCARDMAN:GetCardState(PLAYER_2)) == 'ready');
StorageDevicesChangedMessageCommand=cmd(playcommand,"On");
};]]
} | mit |
shahryar1989/ShahryarAntiSpam | plugins/ingroup.lua | 371 | 44212 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
local user_info = redis:hgetall('user:'..group_owner)
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
if user_info.username then
return "Group onwer is @"..user_info.username.." ["..group_owner.."]"
else
return "Group owner is ["..group_owner..']'
end
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
hjsrzvpqma/test2 | plugins/ingroup.lua | 371 | 44212 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
local user_info = redis:hgetall('user:'..group_owner)
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
if user_info.username then
return "Group onwer is @"..user_info.username.." ["..group_owner.."]"
else
return "Group owner is ["..group_owner..']'
end
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
meshr-net/meshr_win32 | usr/lib/lua/luci/model/cbi/asterisk-mod-cdr.lua | 11 | 1931 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: asterisk-mod-cdr.lua 3618 2008-10-23 02:25:26Z jow $
]]--
cbimap = Map("asterisk", "asterisk", "")
module = cbimap:section(TypedSection, "module", "Modules", "")
module.anonymous = true
cdr_csv = module:option(ListValue, "cdr_csv", "Comma Separated Values CDR Backend", "")
cdr_csv:value("yes", "Load")
cdr_csv:value("no", "Do Not Load")
cdr_csv:value("auto", "Load as Required")
cdr_csv.rmempty = true
cdr_custom = module:option(ListValue, "cdr_custom", "Customizable Comma Separated Values CDR Backend", "")
cdr_custom:value("yes", "Load")
cdr_custom:value("no", "Do Not Load")
cdr_custom:value("auto", "Load as Required")
cdr_custom.rmempty = true
cdr_manager = module:option(ListValue, "cdr_manager", "Asterisk Call Manager CDR Backend", "")
cdr_manager:value("yes", "Load")
cdr_manager:value("no", "Do Not Load")
cdr_manager:value("auto", "Load as Required")
cdr_manager.rmempty = true
cdr_mysql = module:option(ListValue, "cdr_mysql", "MySQL CDR Backend", "")
cdr_mysql:value("yes", "Load")
cdr_mysql:value("no", "Do Not Load")
cdr_mysql:value("auto", "Load as Required")
cdr_mysql.rmempty = true
cdr_pgsql = module:option(ListValue, "cdr_pgsql", "PostgreSQL CDR Backend", "")
cdr_pgsql:value("yes", "Load")
cdr_pgsql:value("no", "Do Not Load")
cdr_pgsql:value("auto", "Load as Required")
cdr_pgsql.rmempty = true
cdr_sqlite = module:option(ListValue, "cdr_sqlite", "SQLite CDR Backend", "")
cdr_sqlite:value("yes", "Load")
cdr_sqlite:value("no", "Do Not Load")
cdr_sqlite:value("auto", "Load as Required")
cdr_sqlite.rmempty = true
return cbimap
| apache-2.0 |
Fatalerror66/ffxi-a | scripts/globals/spells/dia_iii.lua | 2 | 1947 | -----------------------------------------
-- Spell: Dia III
-- Lowers an enemy's defense and gradually deals light elemental damage.
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function OnMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
--calculate raw damage
local basedmg = caster:getSkillLevel(ENFEEBLING_MAGIC_SKILL) / 4;
local dmg = calculateMagicDamage(basedmg,5,caster,spell,target,ENFEEBLING_MAGIC_SKILL,MOD_INT,false);
-- Softcaps at 32, should always do at least 1
dmg = utils.clamp(dmg, 1, 32);
--get resist multiplier (1x if no resist)
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ENFEEBLING_MAGIC_SKILL,1.0);
--get the resisted damage
dmg = dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg);
--add in target adjustment
dmg = adjustForTarget(target,dmg);
--add in final adjustments including the actual damage dealt
local final = finalMagicAdjustments(caster,target,spell,dmg);
-- Calculate duration.
local merits = caster:getMerit(MERIT_DIA_III);
local duration = 30 * merits;
-- Check for Bio.
local bio = target:getStatusEffect(EFFECT_BIO);
-- Do it!
if(bio == nil or (DIA_OVERWRITE == 0 and bio:getPower() <= 3) or (DIA_OVERWRITE == 1 and bio:getPower() < 3)) then
target:addStatusEffect(EFFECT_DIA,3,3,duration, 0, 15);
spell:setMsg(2);
else
spell:setMsg(75);
end
-- Try to kill same tier Bio
if(BIO_OVERWRITE == 1 and bio ~= nil) then
if(bio:getPower() <= 3) then
target:delStatusEffect(EFFECT_BIO);
end
end
return final;
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Lower_Delkfutts_Tower/npcs/_544.lua | 2 | 1599 | -----------------------------------
-- Area: Lower Delkfutt's Tower
-- NPC: Cermet Door
-- Notes: Door opens when you trade Delkfutt Key to it
-- @pos 345 0.1 20 184
-----------------------------------
package.loaded["scripts/zones/Lower_Delkfutts_Tower/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Lower_Delkfutts_Tower/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(549,1) and trade:getItemCount() == 1) then -- Trade Delkfutt Key
player:startEvent(0x0010);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:hasKeyItem(DELKFUTT_KEY)) then
player:startEvent(0x0010);
else
player:startEvent(0x000a); -- door is firmly shut
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
--print("CSID:",csid);
--print("RESULT:",option);
if(csid == 0x0010 and option == 1) then
if(player:hasKeyItem(DELKFUTT_KEY) == false) then
player:tradeComplete();
player:messageSpecial(KEYITEM_OBTAINED,DELKFUTT_KEY);
player:addKeyItem(DELKFUTT_KEY);
end
end
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/North_Gustaberg_[S]/npcs/Roderich.lua | 2 | 1418 | -----------------------------------
-- Area: North Gusta(S)
-- NPC: -400.039, 39.991, -90.445,
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Markets_[S]/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets_[S]/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getVar("discontent") == 2)then
player:startEvent(0x0068);
elseif(player:getVar("discontent") == 3)then
player:startEvent(0x0069);
elseif(player:getVar("discontent") == 4)then
player:startEvent(0x006B);
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 == 0x0068)then
player:setVar("discontent",3);
end
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Bastok_Mines/npcs/_6i8.lua | 4 | 1235 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Door
-- Involved in Quest: A Thief in Norg!?
-- @pos 70 7 2 234
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getQuestStatus(OUTLANDS,A_THIEF_IN_NORG) == QUEST_ACCEPTED and player:getVar("aThiefinNorgCS") == 3) then
player:startEvent(0x00ba);
return -1;
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 == 0x00ba) then
player:setVar("aThiefinNorgCS",4);
end
end; | gpl-3.0 |
simon-wh/PAYDAY-2-BeardLib-Editor | mods/BeardLib-Editor/Classes/Map/Elements/corelogicchance.lua | 2 | 2099 | EditorLogicChance = EditorLogicChance or class(MissionScriptEditor)
function EditorLogicChance:create_element()
self.super.create_element(self)
self._element.class = "ElementLogicChance"
self._element.values.chance = 100
end
function EditorLogicChance:_build_panel()
self:_create_panel()
self:NumberCtrl("chance", {
floats = 0,
min = 0,
max = 100,
help = "Specifies chance that this element will call its on executed elements (in percent)"
})
end
EditorLogicChanceOperator = EditorLogicChanceOperator or class(MissionScriptEditor)
function EditorLogicChanceOperator:create_element()
self.super.create_element(self)
self._element.class = "ElementLogicChanceOperator"
self._element.module = "CoreElementLogicChance"
self._element.values.operation = "none"
self._element.values.chance = 0
self._element.values.elements = {}
end
function EditorLogicChanceOperator:_build_panel()
self:_create_panel()
self:BuildElementsManage("elements", nil, {"ElementLogicChance"})
self:ComboCtrl("operation", {
"none",
"add_chance",
"subtract_chance",
"reset",
"set_chance"
}, {help = "Select an operation for the selected elements"})
self:NumberCtrl("chance", {
floats = 0,
min = 0,
max = 100,
help = "Amount of chance to add, subtract or set to the logic chance elements."
})
self:Text("This element can modify logic chance elements. Select logic chance elements to modify using insert and clicking on the elements.")
end
EditorLogicChanceTrigger = EditorLogicChanceTrigger or class(MissionScriptEditor)
function EditorLogicChanceTrigger:create_element()
self.super.create_element(self)
self._element.class = "ElementLogicChanceTrigger"
self._element.module = "CoreElementLogicChance"
self._element.values.outcome = "fail"
self._element.values.elements = {}
end
function EditorLogicChanceTrigger:_build_panel()
self:_create_panel()
self:BuildElementsManage("elements", nil, {"ElementLogicChance"})
self:ComboCtrl("outcome", {"fail", "success"}, {help = "Select an outcome to trigger on"})
self:Text("This element is a trigger to logic chance elements.")
end | mit |
Fatalerror66/ffxi-a | scripts/zones/Port_San_dOria/npcs/Habitox.lua | 2 | 16216 | -----------------------------------
-- Area: Port Sandoria
-- NPC: Habitox
-- Type: Goblin Mystery Box
-- @zone 232
-- @pos 10.000, -8.000, -130.000
--
-- Menu
-- startEvent(0x031E, Item1, (Item2 or Dial #), Item3, 0, MysteryBoxTally)
--
-- Tally Increase Amount 0: Smidge 1: Someamawhats 2: Gobby-fold 3: Ginormagantic
-- startEvent(0x0199, 0, 0, 0, 0, 0, tallyIncrease)
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local count = trade:getItemCount();
local tallyIncrease = 1;
if(player:getVar("MysteryBoxTally") == 10000) then
player:startEvent(0x0323); -- tally points total full
elseif(player:getVar("MysteryTradeTally") == 10) then
player:startEvent(0x0322); -- tally points for trades full for day
elseif(count == 1) then
player:startEvent(0x0320, 0, 0, 0, 0, 0, tallyIncrease); -- take item add tally points
else
player:startEvent(0x0321); -- don't take item
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
foodItems =
{
5680, -- Agaricus
4511, -- Ambrosia
4513, -- Bottle of Amrita
4300, -- Apple Au Lait
4413, -- Apple Pie
4542, -- Brain Stew
5196, -- Buffalo Jerky
4548, -- Coeurl Sautee
4411, -- Dhalmel Pie
4433, -- Dhalmel Stew
4350, -- Dragon Steak
4398, -- Fish Mithkabob
4276, -- Flint Caviar
4458, -- Goblin Bread
4495, -- Goblin Chocolate
4539, -- Goblin Pie
5143, -- Goblin Stir-fry
5146, -- Hedgehog Pie
4325, -- Hobgoblin Pie
4424, -- Melon Juice
4421, -- Melon Pie
5676, -- Mushroom Sautee
4361, -- Nebimonite
4422, -- Orange Juice
4302, -- Pamama Au Lait
5752, -- Pot-au-feu
4446, -- Pumpkin Pie
5685, -- Rabbit Pie
4410, -- Roast Mushroom
4414, -- Rolanberry Pie
5737, -- Salted Hare
4279, -- Tavnazian Salad
4425, -- Tomato Juice
4512, -- Vampire Juice
5562, -- White Honey
4387, -- Wild Onion
4558, -- Yagudo Drink
5579 -- Yayla Corbasi
}
medicineItems =
{
4153, -- Antacid
4148, -- Antidote
4150, -- Eye Drops
5411, -- Dawn Mulsum
4132, -- Hi-Ether
4134, -- Hi-Ether +2
5255, -- Hyper Ether
4173, -- Hi-Reraiser
4154, -- Holy Water
4149, -- Panacea
4112, -- Potion
4114, -- Potion +2
4140, -- Pro-Ether
4155, -- Remedy
4136, -- Super Ether
4138, -- Super Ether +2
5570, -- Super Reraiser
4174, -- Vile Elixir
4120, -- X-Potion
4122, -- X-Potion +2
4123, -- X-Potion +3
5355, -- Elixir Vitae
4145 -- Elixir
}
scrollItems =
{
4874, -- Absorb-STR
4990, -- Army's Paeon V
4820, -- Burst
4715, -- Erase
4755, -- Fire IV
4812, -- Flare
4814, -- Freeze
4247, -- Miratete's Memories
4714, -- Phalanx
4818, -- Quake
4748, -- Raise III
4717, -- Refresh
4770, -- Stone IV
4816, -- Tornado
4947 -- Utsusemi: Ni
}
synthesisItems =
{
646, -- Adaman Ore
2417, -- Aht Urgan Brass
894, -- Beetle Jaw
880, -- Bone Chip
694, -- Chestnut Log
898, -- Chicken Bone
818, -- Cotton Thread
645, -- Darksteel Ore
857, -- Dhalmel Hide
727, -- Dogwood Log
1133, -- Dragon Blood
756, -- Durium Ore
690, -- Elm Log
893, -- Giant Femur
925, -- Giant Stringer
2542, -- Goblin Mess Tin
2543, -- Goblin Weel
748, -- Gold Beastcoin
817, -- Grass Thread
732, -- Kapor Log
878, -- Karakul Skin
685, -- Khroma Ore
819, -- Linen Thread
2155, -- Lesser Chigoe
749, -- Mythril Beastcoin
739, -- Orichalcum Ore
740, -- Phrygian Ore
1828, -- Red Grass Thread
897, -- Scorpion Claw
505, -- Sheepskin
750, -- Silver Beastcoin
637, -- Slime Oil
861, -- Tiger Hide
915, -- Toad Oil
2304, -- Wamoura Silk
642, -- Zinc Ore
2563, -- Karugo Clay
884, -- Black Tiger Fang
2754, -- Ruszor Fang
700, -- Mahogany Log
699, -- Oak Log
2151 -- Marid Hide
}
popItems =
{
3341, -- Beastly Shank
1873, -- Brigand's Chart
3343, -- Blue Pondweed
3344, -- Red Pondweed
2583, -- Buffalo Corpse
1847, -- Fifth Virtue
1848, -- Fourth Virtue
1418, -- Gem of the East
1424, -- Gem of the North
1420, -- Gem of the South
1422, -- Gem of the West
2566, -- Gnaty Pellets
2565, -- Gnole Pellets
3339, -- Honey Wine
3340, -- Sweet Tea
2573, -- Monkey Wine
2385, -- Moldy Buckler
2572, -- Pandemonium Key
2564, -- Peiste Pellets
1874, -- Pirate's Chart
3342, -- Savory Shank
1849, -- Sixth Virtue
2384, -- Smoky Flask
1419, -- Springstone
1421, -- Summerstone
1425, -- Winterstone
1423 -- Autumstone
}
otherItems =
{
2322, -- Attuner
2324, -- Drum Magazine
2351, -- Dynamo
2325, -- Equalizer
2382, -- Eraser
2327, -- Mana Channeler
14809, -- Novia Earring
14808, -- Novio Earring
2353, -- Optic Fiber
2347, -- Reactive Shield
2329, -- Smoke Screen
2323, -- Tactical Processor
2326, -- Target Marker
1238, -- Tree Saplings
}
peek1 = 0;
peek2 = 0;
peek3 = 0;
var4 = 0;
var5 = player:getVar("MysteryBoxTally");
var6 = 0;
var7 = 0;
var8 = 0;
-- Randomize peek items
if(math.random(2) == 1) then
peek1 = foodItems[math.random(38)];
else
peek1 = medicineItems[math.random(23)];
end
if(math.random(2) == 1) then
peek2 = scrollItems[math.random(15)];
else
peek2 = synthesisItems[math.random(42)];
end
if(math.random(2) == 1) then
peek3 = popItems[math.random(27)];
else
peek3 = otherItems[math.random(14)];
end
if(player:getVar("GoblinMysteryBox") == 0) then -- Initial CS tracking
player:startEvent(0x031D); -- first diagloge explanation
else
if(player:getVar("MysteryBox_Day") < tonumber(os.date("%j"))) then
player:setVar("MysteryBoxTally",(player:getVar("MysteryBoxTally") + ((tonumber(os.date("%j")) - player:getVar("MysteryBox_Day")) * 10))); -- add 10 points per day
player:setVar("MysteryBox_Day",tonumber(os.date("%j"))); -- reset day timer
end
player:startEvent(0x031E,peek1,peek2,peek3,var4,var5,var6,var7,var8); -- menu
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
local dial1Items =
{
4413, -- Apple Pie
5196, -- Buffalo Jerky
4411, -- Dhalmel Pie
4495, -- Goblin Chocolate
4424, -- Melon Juice
4421, -- Melon Pie
4422, -- Orange Juice
4446, -- Pumpkin Pie
5685, -- Rabbit Pie
4410, -- Roast Mushroom
5737, -- Salted Hare
4425, -- Tomato Juice
5562, -- White Honey
4387, -- Wild Onion
4153, -- Antacid
4148, -- Antidote
4150, -- Eye Drops
4112, -- Potion
884, -- Black Tiger Fang
818, -- Cotton Thread
880, -- Bone Chip
898, -- Chicken Bone
857, -- Dhalmel Hide
817, -- Grass Thread
878, -- Karakul Skin
819, -- Linen Thread
749, -- Mythril Beastcoin
897, -- Scorpion Claw
505, -- Sheepskin
861, -- Tiger Hide
642, -- Zinc Ore
1238 -- Tree Saplings
}
local dial2Items =
{
4300, -- Apple Au Lait
4542, -- Brain Stew
4548, -- Coeurl Sautee
4433, -- Dhalmel Stew
4276, -- Flint Caviar
4458, -- Goblin Bread
5146, -- Hedgehog Pie
4325, -- Hobgoblin Pie
4539, -- Goblin Pie
5680, -- Agaricus
4398, -- Fish Mithkabob
4361, -- Nebimonite
4302, -- Pamama Au Lait
5752, -- Pot-au-feu
5579, -- Yayla Corbasi
4132, -- Hi-Ether
4154, -- Holy Water
4114, -- Potion +2
4155, -- Remedy
4120, -- X-Potion
4122, -- X-Potion +2
4145, -- Elixir
646, -- Adaman Ore
894, -- Beetle Jaw
694, -- Chestnut Log
727, -- Dogwood Log
756, -- Durium Ore
690, -- Elm Log
925, -- Giant Stringer
2543, -- Goblin Weel
748, -- Gold Beastcoin
1828, -- Red Grass Thread
750, -- Silver Beastcoin
2563, -- Karugo Clay
4874, -- Absorb-STR
700 -- Mahogany Log
}
local dial3Items =
{
5143, -- Goblin Stir-fry
5676, -- Mushroom Sautee
4414, -- Rolanberry Pie
4279, -- Tavnazian Salad
5411, -- Dawn Mulsum
4134, -- Hi-Ether +2
5255, -- Hyper Ether
4173, -- Hi-Reraiser
4136, -- Super Ether
4138, -- Super Ether +2
5570, -- Super Reraiser
2417, -- Aht Urgan Brass
645, -- Darksteel Ore
1133, -- Dragon Blood
893, -- Giant Femur
2542, -- Goblin Mess Tin
732, -- Kapor Log
685, -- Khroma Ore
2155, -- Lesser Chigoe
637, -- Slime Oil
915, -- Toad Oil
2754, -- Ruszor Fang
699, -- Oak Log
2151, -- Marid Hide
4820, -- Burst
4715, -- Erase
4812, -- Flare
4818, -- Quake
4717, -- Refresh
4816, -- Tornado
740 -- Phrygian Ore
}
local dial4Items =
{
4513, -- Bottle of Amrita
4350, -- Dragon Steak
4512, -- Vampire Juice
4558, -- Yagudo Drink
4149, -- Panacea
4140, -- Pro-Ether
4174, -- Vile Elixir
4123, -- X-Potion +3
5355, -- Elixir Vitae
4755, -- Fire IV
4814, -- Freeze
4748, -- Raise III
4770, -- Stone IV
739, -- Orichalcum Ore
2304, -- Wamoura Silk
14809, -- Novia Earring
14808, -- Novio Earring
2353, -- Optic Fiber
2347, -- Reactive Shield
2329, -- Smoke Screen
2323, -- Tactical Processor
2385, -- Moldy Buckler
1418, -- Gem of the East
1424, -- Gem of the North
1420, -- Gem of the South
1422 -- Gem of the West
}
local dial5Items =
{
4511, -- Ambrosia
4990, -- Army's Paeon V
4247, -- Miratete's Memories
4714, -- Phalanx
4947, -- Utsusemi: Ni
3341, -- Beastly Shank
1873, -- Brigand's Chart
3343, -- Blue Pondweed
3344, -- Red Pondweed
2583, -- Buffalo Corpse
1847, -- Fifth Virtue
1848, -- Fourth Virtue
2566, -- Gnaty Pellets
2565, -- Gnole Pellets
3339, -- Honey Wine
3340, -- Sweet Tea
2573, -- Monkey Wine
2572, -- Pandemonium Key
2564, -- Peiste Pellets
1874, -- Pirate's Chart
3342, -- Savory Shank
1849, -- Sixth Virtue
2384, -- Smoky Flask
1419, -- Springstone
1421, -- Summerstone
1425, -- Winterstone
1423, -- Autumstone
2322, -- Attuner
2324, -- Drum Magazine
2351, -- Dynamo
2325, -- Equalizer
2382, -- Eraser
2327, -- Mana Channeler
2326 -- Target Marker
}
local prize1 = dial1Items[math.random(32)];
local prize2 = 0;
local prize3 = 0;
local prize4 = 0;
local prize5 = 0;
if(math.random(2) == 1) then
prize2 = dial1Items[math.random(32)];
else
prize2 = dial2Items[math.random(36)];
end
local rand1 = math.random(3);
if(rand1 == 1) then
prize3 = dial1Items[math.random(32)];
elseif(rand1 == 2) then
prize3 = dial2Items[math.random(36)];
else
prize3 = dial3Items[math.random(31)];
end
local rand2 = math.random(8);
if(rand2 <= 3) then
prize4 = dial1Items[math.random(32)];
elseif(rand2 == 4 or rand2 == 5) then
prize4 = dial2Items[math.random(36)];
elseif(rand2 == 6 or rand2 == 7) then
prize4 = dial3Items[math.random(31)];
else
prize4 = dial4Items[math.random(26)];
end
local rand3 = math.random(10);
if(rand3 <= 3) then
prize5 = dial1Items[math.random(32)];
elseif(rand3 == 4 or rand3 == 5) then
prize5 = dial2Items[math.random(36)];
elseif(rand3 == 6 or rand3 == 7) then
prize5 = dial3Items[math.random(31)];
elseif(rand3 == 8 or rand3 == 9) then
prize5 = dial4Items[math.random(26)];
else
prize5 = dial5Items[math.random(34)];
end
if(csid == 0x031E) then
var5 = player:getVar("MysteryBoxTally"); -- refresh point tally
-- Re-Randomize peek items
if(option == 4) then
if(math.random(2) == 1) then
peek1 = foodItems[math.random(38)];
else
peek1 = medicineItems[math.random(23)];
end
if(math.random(2) == 1) then
peek2 = scrollItems[math.random(15)];
else
peek2 = synthesisItems[math.random(42)];
end
if(math.random(2) == 1) then
peek3 = popItems[math.random(27)];
else
peek3 = otherItems[math.random(14)];
end
player:updateEvent(peek1,peek2,peek3,0,var5); -- Update peek at items
elseif(option == 9) then
player:updateEvent(0,1,0,0,var5); -- Update 1st param to Dial 1
if(var5 < 10) then
player:updateEvent(0,1,1,0,var5); -- Update 2st param say you don't have the points
end
elseif(option == 10) then
player:addItem(prize1);
player:messageSpecial(ITEM_OBTAINED,prize1);
player:setVar("MysteryBoxTally",(player:getVar("MysteryBoxTally") - 10));
player:updateEvent(0,0,0,0,var5); -- Update so you wanna go again prompt
elseif(option == 17) then
player:updateEvent(0,2,0,0,var5); -- Update 1st param to Dial 2
if(var5 < 20) then
player:updateEvent(0,2,1,0,var5); -- Update 2st param say you don't have the points
end
elseif(option == 18) then
player:addItem(prize2);
player:messageSpecial(ITEM_OBTAINED,prize2);
player:setVar("MysteryBoxTally",(player:getVar("MysteryBoxTally") - 20));
player:updateEvent(0,0,0,0,var5); -- Update so you wanna go again prompt
elseif(option == 25) then
player:updateEvent(0,3,0,0,var5); -- Update 1st param to Dial 3
if(var5 < 30) then
player:updateEvent(0,3,1,var5); -- Update 2st param say you don't have the points
end
elseif(option == 26) then
player:addItem(prize3);
player:messageSpecial(ITEM_OBTAINED,prize3);
player:setVar("MysteryBoxTally",(player:getVar("MysteryBoxTally") - 30));
player:updateEvent(0,0,0,0,var5); -- Update so you wanna go again prompt
elseif(option == 33) then
player:updateEvent(0,4,0,0,var5); -- Update 1st param to Dial 4
if(var5 < 40) then
player:updateEvent(0,4,1,0,var5); -- Update 2st param say you don't have the points
end
elseif(option == 34) then
player:addItem(prize4);
player:messageSpecial(ITEM_OBTAINED,prize4);
player:setVar("MysteryBoxTally",(player:getVar("MysteryBoxTally") - 40));
player:updateEvent(0,0,0,0,var5); -- Update so you wanna go again prompt
elseif(option == 41) then
player:updateEvent(0,5,0,0,var5); -- Update 1st param to Dial 5
if(var5 < 50) then
player:updateEvent(0,5,1,0,var5); -- Update 2st param say you don't have the points
end
elseif(option == 42) then
player:addItem(prize5);
player:messageSpecial(ITEM_OBTAINED,prize5);
player:setVar("MysteryBoxTally",(player:getVar("MysteryBoxTally") - 50));
player:updateEvent(0,0,0,0,var5); -- Update so you wanna go again prompt
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x031D) then -- shown explanation give initial tally points
player:setVar("GoblinMysteryBox",1); -- set initial CS viewed
player:setVar("MysteryBoxTally",50); -- set initial points
player:setVar("MysteryBox_Day",tonumber(os.date("%j"))); -- Day tracker for tally points
elseif(csid == 0x031E) then
var5 = player:getVar("MysteryBoxTally"); -- refresh point tally
-- Replay menu or cutscene will hang ??
if(option == 10) then
player:startEvent(0x031E,peek1,peek2,peek3,var4,var5,var6,var7,var8); -- menu
elseif(option == 18) then
player:startEvent(0x031E,peek1,peek2,peek3,var4,var5,var6,var7,var8); -- menu
elseif(option == 26) then
player:startEvent(0x031E,peek1,peek2,peek3,var4,var5,var6,var7,var8); -- menu
elseif(option == 34) then
player:startEvent(0x031E,peek1,peek2,peek3,var4,var5,var6,var7,var8); -- menu
elseif(option == 42) then
player:startEvent(0x031E,peek1,peek2,peek3,var4,var5,var6,var7,var8); -- menu
end
end
end;
-- player:startEvent(0x0324); -- transform to blue treasure chest
| gpl-3.0 |
flyzjhz/openwrt-bb | feeds/luci/applications/luci-coovachilli/luasrc/model/cbi/coovachilli_network.lua | 79 | 1639 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
require("luci.ip")
m = Map("coovachilli")
-- tun
s1 = m:section(TypedSection, "tun")
s1.anonymous = true
s1:option( Flag, "usetap" )
s1:option( Value, "tundev" ).optional = true
s1:option( Value, "txqlen" ).optional = true
net = s1:option( Value, "net" )
for _, route in ipairs(luci.sys.net.routes()) do
if route.device ~= "lo" and route.dest:prefix() < 32 then
net:value( route.dest:string() )
end
end
s1:option( Value, "dynip" ).optional = true
s1:option( Value, "statip" ).optional = true
s1:option( Value, "dns1" ).optional = true
s1:option( Value, "dns2" ).optional = true
s1:option( Value, "domain" ).optional = true
s1:option( Value, "ipup" ).optional = true
s1:option( Value, "ipdown" ).optional = true
s1:option( Value, "conup" ).optional = true
s1:option( Value, "condown" ).optional = true
-- dhcp config
s2 = m:section(TypedSection, "dhcp")
s2.anonymous = true
dif = s2:option( Value, "dhcpif" )
for _, nif in ipairs(luci.sys.net.devices()) do
if nif ~= "lo" then dif:value(nif) end
end
s2:option( Value, "dhcpmac" ).optional = true
s2:option( Value, "lease" ).optional = true
s2:option( Value, "dhcpstart" ).optional = true
s2:option( Value, "dhcpend" ).optional = true
s2:option( Flag, "eapolenable" )
return m
| gpl-2.0 |
flyzjhz/openwrt-bb | feeds/luci/applications/luci-commands/luasrc/controller/commands.lua | 76 | 5959 | --[[
LuCI - Lua Configuration Interface
Copyright 2012 Jo-Philipp Wich <jow@openwrt.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
]]--
module("luci.controller.commands", package.seeall)
function index()
entry({"admin", "system", "commands"}, firstchild(), _("Custom Commands"), 80)
entry({"admin", "system", "commands", "dashboard"}, template("commands"), _("Dashboard"), 1)
entry({"admin", "system", "commands", "config"}, cbi("commands"), _("Configure"), 2)
entry({"admin", "system", "commands", "run"}, call("action_run"), nil, 3).leaf = true
entry({"admin", "system", "commands", "download"}, call("action_download"), nil, 3).leaf = true
entry({"command"}, call("action_public"), nil, 1).leaf = true
end
--- Decode a given string into arguments following shell quoting rules
--- [[abc \def "foo\"bar" abc'def']] -> [[abc def]] [[foo"bar]] [[abcdef]]
local function parse_args(str)
local args = { }
local function isspace(c)
if c == 9 or c == 10 or c == 11 or c == 12 or c == 13 or c == 32 then
return c
end
end
local function isquote(c)
if c == 34 or c == 39 or c == 96 then
return c
end
end
local function isescape(c)
if c == 92 then
return c
end
end
local function ismeta(c)
if c == 36 or c == 92 or c == 96 then
return c
end
end
--- Convert given table of byte values into a Lua string and append it to
--- the "args" table. Segment byte value sequence into chunks of 256 values
--- to not trip over the parameter limit for string.char()
local function putstr(bytes)
local chunks = { }
local csz = 256
local upk = unpack
local chr = string.char
local min = math.min
local len = #bytes
local off
for off = 1, len, csz do
chunks[#chunks+1] = chr(upk(bytes, off, min(off + csz - 1, len)))
end
args[#args+1] = table.concat(chunks)
end
--- Scan substring defined by the indexes [s, e] of the string "str",
--- perform unquoting and de-escaping on the fly and store the result in
--- a table of byte values which is passed to putstr()
local function unquote(s, e)
local off, esc, quote
local res = { }
for off = s, e do
local byte = str:byte(off)
local q = isquote(byte)
local e = isescape(byte)
local m = ismeta(byte)
if e then
esc = true
elseif esc then
if m then res[#res+1] = 92 end
res[#res+1] = byte
esc = false
elseif q and quote and q == quote then
quote = nil
elseif q and not quote then
quote = q
else
if m then res[#res+1] = 92 end
res[#res+1] = byte
end
end
putstr(res)
end
--- Find substring boundaries in "str". Ignore escaped or quoted
--- whitespace, pass found start- and end-index for each substring
--- to unquote()
local off, esc, start, quote
for off = 1, #str + 1 do
local byte = str:byte(off)
local q = isquote(byte)
local s = isspace(byte) or (off > #str)
local e = isescape(byte)
if esc then
esc = false
elseif e then
esc = true
elseif q and quote and q == quote then
quote = nil
elseif q and not quote then
start = start or off
quote = q
elseif s and not quote then
if start then
unquote(start, off - 1)
start = nil
end
else
start = start or off
end
end
--- If the "quote" is still set we encountered an unfinished string
if quote then
unquote(start, #str)
end
return args
end
local function parse_cmdline(cmdid, args)
local uci = require "luci.model.uci".cursor()
if uci:get("luci", cmdid) == "command" then
local cmd = uci:get_all("luci", cmdid)
local argv = parse_args(cmd.command)
local i, v
if cmd.param == "1" and args then
for i, v in ipairs(parse_args(luci.http.urldecode(args))) do
argv[#argv+1] = v
end
end
for i, v in ipairs(argv) do
if v:match("[^%w%.%-i/]") then
argv[i] = '"%s"' % v:gsub('"', '\\"')
end
end
return argv
end
end
function action_run(...)
local fs = require "nixio.fs"
local argv = parse_cmdline(...)
if argv then
local outfile = os.tmpname()
local errfile = os.tmpname()
local rv = os.execute(table.concat(argv, " ") .. " >%s 2>%s" %{ outfile, errfile })
local stdout = fs.readfile(outfile, 1024 * 512) or ""
local stderr = fs.readfile(errfile, 1024 * 512) or ""
fs.unlink(outfile)
fs.unlink(errfile)
local binary = not not (stdout:match("[%z\1-\8\14-\31]"))
luci.http.prepare_content("application/json")
luci.http.write_json({
command = table.concat(argv, " "),
stdout = not binary and stdout,
stderr = stderr,
exitcode = rv,
binary = binary
})
else
luci.http.status(404, "No such command")
end
end
function action_download(...)
local fs = require "nixio.fs"
local argv = parse_cmdline(...)
if argv then
local fd = io.popen(table.concat(argv, " ") .. " 2>/dev/null")
if fd then
local chunk = fd:read(4096) or ""
local name
if chunk:match("[%z\1-\8\14-\31]") then
luci.http.header("Content-Disposition", "attachment; filename=%s"
% fs.basename(argv[1]):gsub("%W+", ".") .. ".bin")
luci.http.prepare_content("application/octet-stream")
else
luci.http.header("Content-Disposition", "attachment; filename=%s"
% fs.basename(argv[1]):gsub("%W+", ".") .. ".txt")
luci.http.prepare_content("text/plain")
end
while chunk do
luci.http.write(chunk)
chunk = fd:read(4096)
end
fd:close()
else
luci.http.status(500, "Failed to execute command")
end
else
luci.http.status(404, "No such command")
end
end
function action_public(cmdid, args)
local uci = require "luci.model.uci".cursor()
if cmdid and
uci:get("luci", cmdid) == "command" and
uci:get("luci", cmdid, "public") == "1"
then
action_download(cmdid, args)
else
luci.http.status(403, "Access to command denied")
end
end
| gpl-2.0 |
Clavus/LD32 | engine/lib/loveframes/objects/multichoice.lua | 13 | 11033 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------
-- get the current require path
local path = string.sub(..., 1, string.len(...) - string.len(".objects.multichoice"))
local loveframes = require(path .. ".libraries.common")
-- multichoice object
local newobject = loveframes.NewObject("multichoice", "loveframes_object_multichoice", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize()
self.type = "multichoice"
self.choice = ""
self.text = "Select an option"
self.width = 200
self.height = 25
self.listpadding = 0
self.listspacing = 0
self.buttonscrollamount = 200
self.mousewheelscrollamount = 1500
self.sortfunc = function(a, b) return a < b end
self.haslist = false
self.dtscrolling = true
self.enabled = true
self.internal = false
self.choices = {}
self.listheight = nil
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
local parent = self.parent
local base = loveframes.base
local update = self.Update
self:CheckHover()
-- move to parent if there is a parent
if parent ~= base then
self.x = self.parent.x + self.staticx
self.y = self.parent.y + self.staticy
end
if update then
update(self, dt)
end
end
--[[---------------------------------------------------------
- func: draw()
- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local skins = loveframes.skins.available
local skinindex = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = skins[selfskin] or skins[skinindex]
local drawfunc = skin.DrawMultiChoice or skins[defaultskin].DrawMultiChoice
local draw = self.Draw
local drawcount = loveframes.drawcount
-- set the object's draw order
self:SetDrawOrder()
if draw then
draw(self)
else
drawfunc(self)
end
end
--[[---------------------------------------------------------
- func: mousepressed(x, y, button)
- desc: called when the player presses a mouse button
--]]---------------------------------------------------------
function newobject:mousepressed(x, y, button)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local hover = self.hover
local haslist = self.haslist
local enabled = self.enabled
if hover and not haslist and enabled and button == "l" then
local baseparent = self:GetBaseParent()
if baseparent and baseparent.type == "frame" then
baseparent:MakeTop()
end
self.haslist = true
self.list = loveframes.objects["multichoicelist"]:new(self)
self.list:SetState(self.state)
loveframes.downobject = self
end
end
--[[---------------------------------------------------------
- func: mousereleased(x, y, button)
- desc: called when the player releases a mouse button
--]]---------------------------------------------------------
function newobject:mousereleased(x, y, button)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
end
--[[---------------------------------------------------------
- func: AddChoice(choice)
- desc: adds a choice to the current list of choices
--]]---------------------------------------------------------
function newobject:AddChoice(choice)
local choices = self.choices
table.insert(choices, choice)
return self
end
--[[---------------------------------------------------------
- func: RemoveChoice(choice)
- desc: removes the specified choice from the object's
list of choices
--]]---------------------------------------------------------
function newobject:RemoveChoice(choice)
local choices = self.choices
for k, v in ipairs(choices) do
if v == choice then
table.remove(choices, k)
break
end
end
return self
end
--[[---------------------------------------------------------
- func: SetChoice(choice)
- desc: sets the current choice
--]]---------------------------------------------------------
function newobject:SetChoice(choice)
self.choice = choice
return self
end
--[[---------------------------------------------------------
- func: SelectChoice(choice)
- desc: selects a choice
--]]---------------------------------------------------------
function newobject:SelectChoice(choice)
local onchoiceselected = self.OnChoiceSelected
self.choice = choice
if self.list then
self.list:Close()
end
if onchoiceselected then
onchoiceselected(self, choice)
end
return self
end
--[[---------------------------------------------------------
- func: SetListHeight(height)
- desc: sets the height of the list of choices
--]]---------------------------------------------------------
function newobject:SetListHeight(height)
self.listheight = height
return self
end
--[[---------------------------------------------------------
- func: SetPadding(padding)
- desc: sets the padding of the list of choices
--]]---------------------------------------------------------
function newobject:SetPadding(padding)
self.listpadding = padding
return self
end
--[[---------------------------------------------------------
- func: SetSpacing(spacing)
- desc: sets the spacing of the list of choices
--]]---------------------------------------------------------
function newobject:SetSpacing(spacing)
self.listspacing = spacing
return self
end
--[[---------------------------------------------------------
- func: GetValue()
- desc: gets the value (choice) of the object
--]]---------------------------------------------------------
function newobject:GetValue()
return self.choice
end
--[[---------------------------------------------------------
- func: GetChoice()
- desc: gets the current choice (same as get value)
--]]---------------------------------------------------------
function newobject:GetChoice()
return self.choice
end
--[[---------------------------------------------------------
- func: SetText(text)
- desc: sets the object's text
--]]---------------------------------------------------------
function newobject:SetText(text)
self.text = text
return self
end
--[[---------------------------------------------------------
- func: GetText()
- desc: gets the object's text
--]]---------------------------------------------------------
function newobject:GetText()
return self.text
end
--[[---------------------------------------------------------
- func: SetButtonScrollAmount(speed)
- desc: sets the scroll amount of the object's scrollbar
buttons
--]]---------------------------------------------------------
function newobject:SetButtonScrollAmount(amount)
self.buttonscrollamount = amount
return self
end
--[[---------------------------------------------------------
- func: GetButtonScrollAmount()
- desc: gets the scroll amount of the object's scrollbar
buttons
--]]---------------------------------------------------------
function newobject:GetButtonScrollAmount()
return self.buttonscrollamount
end
--[[---------------------------------------------------------
- func: SetMouseWheelScrollAmount(amount)
- desc: sets the scroll amount of the mouse wheel
--]]---------------------------------------------------------
function newobject:SetMouseWheelScrollAmount(amount)
self.mousewheelscrollamount = amount
return self
end
--[[---------------------------------------------------------
- func: GetMouseWheelScrollAmount()
- desc: gets the scroll amount of the mouse wheel
--]]---------------------------------------------------------
function newobject:GetButtonScrollAmount()
return self.mousewheelscrollamount
end
--[[---------------------------------------------------------
- func: SetDTScrolling(bool)
- desc: sets whether or not the object should use delta
time when scrolling
--]]---------------------------------------------------------
function newobject:SetDTScrolling(bool)
self.dtscrolling = bool
return self
end
--[[---------------------------------------------------------
- func: GetDTScrolling()
- desc: gets whether or not the object should use delta
time when scrolling
--]]---------------------------------------------------------
function newobject:GetDTScrolling()
return self.dtscrolling
end
--[[---------------------------------------------------------
- func: Sort(func)
- desc: sorts the object's choices
--]]---------------------------------------------------------
function newobject:Sort(func)
local default = self.sortfunc
if func then
table.sort(self.choices, func)
else
table.sort(self.choices, default)
end
return self
end
--[[---------------------------------------------------------
- func: SetSortFunction(func)
- desc: sets the object's default sort function
--]]---------------------------------------------------------
function newobject:SetSortFunction(func)
self.sortfunc = func
return self
end
--[[---------------------------------------------------------
- func: GetSortFunction(func)
- desc: gets the object's default sort function
--]]---------------------------------------------------------
function newobject:GetSortFunction()
return self.sortfunc
end
--[[---------------------------------------------------------
- func: Clear()
- desc: removes all choices from the object's list
of choices
--]]---------------------------------------------------------
function newobject:Clear()
self.choices = {}
self.choice = ""
self.text = "Select an option"
return self
end
--[[---------------------------------------------------------
- func: SetClickable(bool)
- desc: sets whether or not the object is enabled
--]]---------------------------------------------------------
function newobject:SetEnabled(bool)
self.enabled = bool
return self
end
--[[---------------------------------------------------------
- func: GetEnabled()
- desc: gets whether or not the object is enabled
--]]---------------------------------------------------------
function newobject:GetEnabled()
return self.enabled
end
| mit |
BTAxis/naev | dat/missions/empire/shipping/es01.lua | 2 | 6549 | --[[
Empire Shipping Dangerous Cargo Delivery
Author: bobbens
minor edits by Infiltrator
]]--
include "dat/scripts/numstring.lua"
-- Mission details
bar_desc = _("You see Commander Soldner who is expecting you.")
misn_title = _("Empire Shipping Delivery")
misn_reward = _("%s credits")
misn_desc = {}
misn_desc[1] = _("Pick up a package at %s in the %s system.")
misn_desc[2] = _("Deliver the package to %s in the %s system.")
misn_desc[3] = _("Return to %s in the %s system.")
-- Fancy text messages
title = {}
title[1] = _("Commander Soldner")
title[2] = _("Loading Cargo")
title[3] = _("Cargo Delivery")
title[4] = _("Mission Success")
text = {}
text[1] = _([[You approach Commander Soldner, who seems to be waiting for you.
"Hello, ready for your next mission?"]])
text[2] = _([[Commander Soldner begins, "We have an important package that we must take from %s in the %s system to %s in the %s system. We have reason to believe that it is also wanted by external forces."
"The plan is to send an advance convoy with guards to make the run in an attempt to confuse possible enemies. You will then go in and do the actual delivery by yourself. This way we shouldn't arouse suspicion. You are to report here when you finish delivery and you'll be paid %d credits."]])
text[3] = _([["Avoid hostility at all costs. The package must arrive at its destination. Since you are undercover, Empire ships won't assist you if you come under fire, so stay sharp. Good luck."]])
text[4] = _([[The packages labelled "Food" are loaded discreetly onto your ship. Now to deliver them to %s in the %s system.]])
text[5] = _([[Workers quickly unload the package as mysteriously as it was loaded. You notice that one of them gives you a note. Looks like you'll have to go to %s in the %s system to report to Commander Soldner.]])
text[6] = _([[You arrive at %s and report to Commander Soldner. He greets you and starts talking. "I heard you encountered resistance. At least you managed to deliver the package. Great work there. I've managed to get you cleared for the Heavy Weapon License. You'll still have to pay the fee for getting it, though.
"If you're interested in more work, meet me in the bar in a bit. I've got some paperwork I need to finish first."]])
-- Errors
errtitle = {}
errtitle[1] = _("Need More Space")
err = {}
err[1] = _("You do not have enough space to load the packages. You need to make room for %d more tons.")
function create ()
-- Note: this mission does not make any system claims.
-- Planet targets
pickup,pickupsys = planet.getLandable( "Selphod" )
dest,destsys = planet.getLandable( "Cerberus" )
ret,retsys = planet.getLandable( "Halir" )
if pickup==nil or dest==nil or ret==nil then
misn.finish(false)
end
-- Bar NPC
misn.setNPC( _("Soldner"), "empire/unique/soldner" )
misn.setDesc( bar_desc )
end
function accept ()
-- See if accept mission
if not tk.yesno( title[1], text[1] ) then
misn.finish()
end
misn.accept()
-- target destination
misn_marker = misn.markerAdd( pickupsys, "low" )
-- Mission details
misn_stage = 0
reward = 500000
misn.setTitle(misn_title)
misn.setReward( string.format(misn_reward, numstring(reward)) )
misn.setDesc( string.format(misn_desc[1], pickup:name(), pickupsys:name()))
-- Flavour text and mini-briefing
tk.msg( title[1], string.format( text[2], pickup:name(), pickupsys:name(),
dest:name(), destsys:name(), reward ))
misn.osdCreate(misn_title, {misn_desc[1]:format(pickup:name(),pickupsys:name())})
-- Set up the goal
tk.msg( title[1], text[3] )
-- Set hooks
hook.land("land")
hook.enter("enter")
end
function land ()
landed = planet.cur()
if landed == pickup and misn_stage == 0 then
-- Make sure player has room.
if player.pilot():cargoFree() < 3 then
tk.msg( errtitle[1], string.format( err[1], 3 - player.pilot():cargoFree() ) )
return
end
-- Update mission
package = misn.cargoAdd("Packages", 3)
misn_stage = 1
jumped = 0
misn.setDesc( string.format(misn_desc[2], dest:name(), destsys:name()))
misn.markerMove( misn_marker, destsys )
misn.osdCreate(misn_title, {misn_desc[2]:format(dest:name(),destsys:name())})
-- Load message
tk.msg( title[2], string.format( text[4], dest:name(), destsys:name()) )
elseif landed == dest and misn_stage == 1 then
if misn.cargoRm(package) then
-- Update mission
misn_stage = 2
misn.setDesc( string.format(misn_desc[3], ret:name(), retsys:name()))
misn.markerMove( misn_marker, retsys )
misn.osdCreate(misn_title, {misn_desc[3]:format(ret:name(),retsys:name())})
-- Some text
tk.msg( title[3], string.format(text[5], ret:name(), retsys:name()) )
end
elseif landed == ret and misn_stage == 2 then
-- Rewards
player.pay(reward)
faction.modPlayerSingle("Empire",5);
-- Flavour text
tk.msg(title[4], string.format(text[6], ret:name()) )
-- The goods
diff.apply("heavy_weapons_license")
misn.finish(true)
end
end
function enter ()
sys = system.cur()
if misn_stage == 1 then
-- Mercenaries appear after a couple of jumps
jumped = jumped + 1
if jumped <= 3 then
return
end
-- Get player position
enter_vect = player.pos()
-- Calculate where the enemies will be
r = rnd.rnd(0,4)
-- Next to player (always if landed)
if enter_vect:dist() < 1000 or r < 2 then
a = rnd.rnd() * 2 * math.pi
d = rnd.rnd( 400, 1000 )
enter_vect:add( math.cos(a) * d, math.sin(a) * d )
enemies()
-- Enter after player
else
t = hook.timer(rnd.int( 2000, 5000 ) , "enemies")
end
end
end
function enemies ()
-- Choose mercenaries
merc = {}
if rnd.rnd() < 0.3 then table.insert( merc, "Mercenary Pacifier" ) end
if rnd.rnd() < 0.7 then table.insert( merc, "Mercenary Ancestor" ) end
if rnd.rnd() < 0.9 then table.insert( merc, "Mercenary Vendetta" ) end
-- Add mercenaries
for k,v in ipairs(merc) do
-- Move position a bit
a = rnd.rnd() * 2 * math.pi
d = rnd.rnd( 50, 75 )
enter_vect:add( math.cos(a) * d, math.sin(a) * d )
-- Add pilots
p = pilot.add( v, "mercenary", enter_vect )
-- Set hostile
for k,v in ipairs(p) do
v:setHostile()
end
end
end
| gpl-3.0 |
flyzjhz/openwrt-bb | feeds/luci/applications/luci-asterisk/luasrc/model/cbi/asterisk/trunk_sip.lua | 80 | 2561 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local ast = require("luci.asterisk")
--
-- SIP trunk info
--
if arg[2] == "info" then
form = SimpleForm("asterisk", "SIP Trunk Information")
form.reset = false
form.submit = "Back to overview"
local info, keys = ast.sip.peer(arg[1])
local data = { }
for _, key in ipairs(keys) do
data[#data+1] = {
key = key,
val = type(info[key]) == "boolean"
and ( info[key] and "yes" or "no" )
or ( info[key] == nil or #info[key] == 0 )
and "(none)"
or tostring(info[key])
}
end
itbl = form:section(Table, data, "SIP Trunk %q" % arg[1])
itbl:option(DummyValue, "key", "Key")
itbl:option(DummyValue, "val", "Value")
function itbl.parse(...)
luci.http.redirect(
luci.dispatcher.build_url("admin", "asterisk", "trunks")
)
end
return form
--
-- SIP trunk config
--
elseif arg[1] then
cbimap = Map("asterisk", "Edit SIP Trunk")
peer = cbimap:section(NamedSection, arg[1])
peer.hidden = {
type = "peer",
qualify = "yes",
}
back = peer:option(DummyValue, "_overview", "Back to trunk overview")
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "asterisk", "trunks")
sipdomain = peer:option(Value, "host", "SIP Domain")
sipport = peer:option(Value, "port", "SIP Port")
function sipport.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "5060"
end
username = peer:option(Value, "username", "Authorization ID")
password = peer:option(Value, "secret", "Authorization Password")
password.password = true
outboundproxy = peer:option(Value, "outboundproxy", "Outbound Proxy")
outboundport = peer:option(Value, "outboundproxyport", "Outbound Proxy Port")
register = peer:option(Flag, "register", "Register with peer")
register.enabled = "yes"
register.disabled = "no"
regext = peer:option(Value, "registerextension", "Extension to register (optional)")
regext:depends({register="1"})
didval = peer:option(ListValue, "_did", "Number of assigned DID numbers")
didval:value("", "(none)")
for i=1,24 do didval:value(i) end
dialplan = peer:option(ListValue, "context", "Dialplan Context")
dialplan:value(arg[1] .. "_inbound", "(default)")
cbimap.uci:foreach("asterisk", "dialplan",
function(s) dialplan:value(s['.name']) end)
return cbimap
end
| gpl-2.0 |
emoses/hammerspoon | extensions/location/init.lua | 13 | 7506 | --- === hs.location ===
---
--- Determine the machine's location and useful information about that location
local location = require("hs.location.internal")
local internal = {}
internal.__callbacks = {}
--- hs.location.register(tag, fn[, distance])
--- Function
--- Registers a callback function to be called when the system location is updated
---
--- Parameters:
--- * tag - A string containing a unique tag, used to identify the callback later
--- * fn - A function to be called when the system location is updated. The function should accept a single argument, which will be a table containing the same data as is returned by `hs.location.get()`
--- * distance - An optional number containing the minimum distance in meters that the system should have moved, before calling the callback. Defaults to 0
---
--- Returns:
--- * None
location.register = function(tag, fn, distance)
if internal.__callbacks[tag] then
error("Callback tag '"..tag.."' already registered for hs.location.", 2)
else
internal.__callbacks[tag] = {
fn = fn,
distance = distance,
last = {
latitude = 0,
longitude = 0,
timestamp = 0,
}
}
end
end
--- hs.location.unregister(tag)
--- Function
--- Unregisters a callback
---
--- Parameters:
--- * tag - A string containing the unique tag a callback was registered with
---
--- Returns:
--- * None
location.unregister = function(tag)
internal.__callbacks[tag] = nil
end
-- Set up callback dispatcher
internal.__dispatch = function()
local locationNow = location.get()
for tag, callback in pairs(internal.__callbacks) do
if not(callback.distance and location.distance(locationNow, callback.last) < callback.distance) then
callback.last = {
latitude = locationNow.latitude,
longitude = locationNow.longitude,
timestamp = locationNow.timestamp
}
callback.fn(locationNow)
end
end
-- print("Proof of concept: ",hs.inspect(location.get()))
end
-- -------- Functions related to sunrise/sunset times -----------------
local rad = math.rad
local deg = math.deg
local floor = math.floor
local frac = function(n) return n - floor(n) end
local cos = function(d) return math.cos(rad(d)) end
local acos = function(d) return deg(math.acos(d)) end
local sin = function(d) return math.sin(rad(d)) end
local asin = function(d) return deg(math.asin(d)) end
local tan = function(d) return math.tan(rad(d)) end
local atan = function(d) return deg(math.atan(d)) end
local function fit_into_range(val, min, max)
local range = max - min
local count
if val < min then
count = floor((min - val) / range) + 1
return val + count * range
elseif val >= max then
count = floor((val - max) / range) + 1
return val - count * range
else
return val
end
end
local function day_of_year(date)
local n1 = floor(275 * date.month / 9)
local n2 = floor((date.month + 9) / 12)
local n3 = (1 + floor((date.year - 4 * floor(date.year / 4) + 2) / 3))
return n1 - (n2 * n3) + date.day - 30
end
local function sunturn_time(date, rising, latitude, longitude, zenith, local_offset)
local n = day_of_year(date)
-- Convert the longitude to hour value and calculate an approximate time
local lng_hour = longitude / 15
local t
if rising then -- Rising time is desired
t = n + ((6 - lng_hour) / 24)
else -- Setting time is desired
t = n + ((18 - lng_hour) / 24)
end
-- Calculate the Sun's mean anomaly
local M = (0.9856 * t) - 3.289
-- Calculate the Sun's true longitude
local L = fit_into_range(M + (1.916 * sin(M)) + (0.020 * sin(2 * M)) + 282.634, 0, 360)
-- Calculate the Sun's right ascension
local RA = fit_into_range(atan(0.91764 * tan(L)), 0, 360)
-- Right ascension value needs to be in the same quadrant as L
local Lquadrant = floor(L / 90) * 90
local RAquadrant = floor(RA / 90) * 90
RA = RA + Lquadrant - RAquadrant
-- Right ascension value needs to be converted into hours
RA = RA / 15
-- Calculate the Sun's declination
local sinDec = 0.39782 * sin(L)
local cosDec = cos(asin(sinDec))
-- Calculate the Sun's local hour angle
local cosH = (cos(zenith) - (sinDec * sin(latitude))) / (cosDec * cos(latitude))
if rising and cosH > 1 then
return "N/R" -- The sun never rises on this location on the specified date
elseif cosH < -1 then
return "N/S" -- The sun never sets on this location on the specified date
end
-- Finish calculating H and convert into hours
local H
if rising then
H = 360 - acos(cosH)
else
H = acos(cosH)
end
H = H / 15
-- Calculate local mean time of rising/setting
local T = H + RA - (0.06571 * t) - 6.622
-- Adjust back to UTC
local UT = fit_into_range(T - lng_hour, 0, 24)
-- Convert UT value to local time zone of latitude/longitude
local LT = UT + local_offset
return os.time({ day = date.day, month = date.month, year = date.year,
hour = floor(LT), min = frac(LT) * 60})
end
--- hs.location.sunrise(latitude, longitude, offset[, date]) -> number or string
--- Function
--- Returns the time of official sunrise for the supplied location
---
--- Parameters:
--- * latitude - A number containing a latitude
--- * longitude - A number containing a longitude
--- * offset - A number containing the offset from UTC (in hours) for the given latitude/longitude
--- * date - An optional table containing date information (equivalent to the output of ```os.date("*t")```). Defaults to the current date
---
--- Returns:
--- * A number containing the time of sunrise (represented as seconds since the epoch) for the given date. If no date is given, the current date is used. If the sun doesn't rise on the given day, the string "N/R" is returned.
---
--- Notes:
--- * You can turn the return value into a more useful structure, with ```os.date("*t", returnvalue)```
location.sunrise = function (lat, lon, offset, date)
local zenith = 90.83
if not date then
date = os.date("*t")
end
return sunturn_time(date, true, lat, lon, zenith, offset)
end
--- hs.location.sunset(latitude, longitude, offset[, date]) -> number or string
--- Function
--- Returns the time of official sunset for the supplied location
---
--- Parameters:
--- * latitude - A number containing a latitude
--- * longitude - A number containing a longitude
--- * offset - A number containing the offset from UTC (in hours) for the given latitude/longitude
--- * date - An optional table containing date information (equivalent to the output of ```os.date("*t")```). Defaults to the current date
---
--- Returns:
--- * A number containing the time of sunset (represented as seconds since the epoch) for the given date. If no date is given, the current date is used. If the sun doesn't set on the given day, the string "N/S" is returned.
---
--- Notes:
--- * You can turn the return value into a more useful structure, with ```os.date("*t", returnvalue)```
location.sunset = function (lat, lon, offset, date)
local zenith = 90.83
if not date then
date = os.date("*t")
end
return sunturn_time(date, false, lat, lon, zenith, offset)
end
local meta = getmetatable(location)
meta.__index = function(_, key) return internal[key] end
setmetatable(location, meta)
return location
| mit |
redbill/torch7 | torchcwrap.lua | 54 | 15111 | local wrap = require 'cwrap'
local types = wrap.types
types.Tensor = {
helpname = function(arg)
if arg.dim then
return string.format("Tensor~%dD", arg.dim)
else
return "Tensor"
end
end,
declare = function(arg)
local txt = {}
table.insert(txt, string.format("THTensor *arg%d = NULL;", arg.i))
if arg.returned then
table.insert(txt, string.format("int arg%d_idx = 0;", arg.i));
end
return table.concat(txt, '\n')
end,
check = function(arg, idx)
if arg.dim then
return string.format("(arg%d = luaT_toudata(L, %d, torch_Tensor)) && (arg%d->nDimension == %d)", arg.i, idx, arg.i, arg.dim)
else
return string.format("(arg%d = luaT_toudata(L, %d, torch_Tensor))", arg.i, idx)
end
end,
read = function(arg, idx)
if arg.returned then
return string.format("arg%d_idx = %d;", arg.i, idx)
end
end,
init = function(arg)
if type(arg.default) == 'boolean' then
return string.format('arg%d = THTensor_(new)();', arg.i)
elseif type(arg.default) == 'number' then
return string.format('arg%d = %s;', arg.i, arg.args[arg.default]:carg())
else
error('unknown default tensor type value')
end
end,
carg = function(arg)
return string.format('arg%d', arg.i)
end,
creturn = function(arg)
return string.format('arg%d', arg.i)
end,
precall = function(arg)
local txt = {}
if arg.default and arg.returned then
table.insert(txt, string.format('if(arg%d_idx)', arg.i)) -- means it was passed as arg
table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i))
table.insert(txt, string.format('else'))
if type(arg.default) == 'boolean' then -- boolean: we did a new()
table.insert(txt, string.format('luaT_pushudata(L, arg%d, torch_Tensor);', arg.i))
else -- otherwise: point on default tensor --> retain
table.insert(txt, string.format('{'))
table.insert(txt, string.format('THTensor_(retain)(arg%d);', arg.i)) -- so we need a retain
table.insert(txt, string.format('luaT_pushudata(L, arg%d, torch_Tensor);', arg.i))
table.insert(txt, string.format('}'))
end
elseif arg.default then
-- we would have to deallocate the beast later if we did a new
-- unlikely anyways, so i do not support it for now
if type(arg.default) == 'boolean' then
error('a tensor cannot be optional if not returned')
end
elseif arg.returned then
table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i))
end
return table.concat(txt, '\n')
end,
postcall = function(arg)
local txt = {}
if arg.creturned then
-- this next line is actually debatable
table.insert(txt, string.format('THTensor_(retain)(arg%d);', arg.i))
table.insert(txt, string.format('luaT_pushudata(L, arg%d, torch_Tensor);', arg.i))
end
return table.concat(txt, '\n')
end
}
types.Generator = {
helpname = function(arg)
return "Generator"
end,
declare = function(arg)
return string.format("THGenerator *arg%d = NULL;", arg.i)
end,
check = function(arg, idx)
return string.format("(arg%d = luaT_toudata(L, %d, torch_Generator))", arg.i, idx)
end,
read = function(arg, idx)
end,
init = function(arg)
local text = {}
-- If no generator is supplied, pull the default out of the torch namespace.
table.insert(text, 'lua_getglobal(L,"torch");')
table.insert(text, string.format('arg%d = luaT_getfieldcheckudata(L, -1, "_gen", torch_Generator);', arg.i))
table.insert(text, 'lua_pop(L, 2);')
return table.concat(text, '\n')
end,
carg = function(arg)
return string.format('arg%d', arg.i)
end,
creturn = function(arg)
return string.format('arg%d', arg.i)
end,
precall = function(arg)
end,
postcall = function(arg)
end
}
types.IndexTensor = {
helpname = function(arg)
return "LongTensor"
end,
declare = function(arg)
local txt = {}
table.insert(txt, string.format("THLongTensor *arg%d = NULL;", arg.i))
if arg.returned then
table.insert(txt, string.format("int arg%d_idx = 0;", arg.i));
end
return table.concat(txt, '\n')
end,
check = function(arg, idx)
return string.format('(arg%d = luaT_toudata(L, %d, "torch.LongTensor"))', arg.i, idx)
end,
read = function(arg, idx)
local txt = {}
if not arg.noreadadd then
table.insert(txt, string.format("THLongTensor_add(arg%d, arg%d, -1);", arg.i, arg.i));
end
if arg.returned then
table.insert(txt, string.format("arg%d_idx = %d;", arg.i, idx))
end
return table.concat(txt, '\n')
end,
init = function(arg)
return string.format('arg%d = THLongTensor_new();', arg.i)
end,
carg = function(arg)
return string.format('arg%d', arg.i)
end,
creturn = function(arg)
return string.format('arg%d', arg.i)
end,
precall = function(arg)
local txt = {}
if arg.default and arg.returned then
table.insert(txt, string.format('if(arg%d_idx)', arg.i)) -- means it was passed as arg
table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i))
table.insert(txt, string.format('else')) -- means we did a new()
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongTensor");', arg.i))
elseif arg.default then
error('a tensor cannot be optional if not returned')
elseif arg.returned then
table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i))
end
return table.concat(txt, '\n')
end,
postcall = function(arg)
local txt = {}
if arg.creturned or arg.returned then
table.insert(txt, string.format("THLongTensor_add(arg%d, arg%d, 1);", arg.i, arg.i));
end
if arg.creturned then
-- this next line is actually debatable
table.insert(txt, string.format('THLongTensor_retain(arg%d);', arg.i))
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongTensor");', arg.i))
end
return table.concat(txt, '\n')
end
}
for _,typename in ipairs({"ByteTensor", "CharTensor", "ShortTensor", "IntTensor", "LongTensor",
"FloatTensor", "DoubleTensor"}) do
types[typename] = {
helpname = function(arg)
if arg.dim then
return string.format('%s~%dD', typename, arg.dim)
else
return typename
end
end,
declare = function(arg)
local txt = {}
table.insert(txt, string.format("TH%s *arg%d = NULL;", typename, arg.i))
if arg.returned then
table.insert(txt, string.format("int arg%d_idx = 0;", arg.i));
end
return table.concat(txt, '\n')
end,
check = function(arg, idx)
if arg.dim then
return string.format('(arg%d = luaT_toudata(L, %d, "torch.%s")) && (arg%d->nDimension == %d)', arg.i, idx, typename, arg.i, arg.dim)
else
return string.format('(arg%d = luaT_toudata(L, %d, "torch.%s"))', arg.i, idx, typename)
end
end,
read = function(arg, idx)
if arg.returned then
return string.format("arg%d_idx = %d;", arg.i, idx)
end
end,
init = function(arg)
if type(arg.default) == 'boolean' then
return string.format('arg%d = TH%s_new();', arg.i, typename)
elseif type(arg.default) == 'number' then
return string.format('arg%d = %s;', arg.i, arg.args[arg.default]:carg())
else
error('unknown default tensor type value')
end
end,
carg = function(arg)
return string.format('arg%d', arg.i)
end,
creturn = function(arg)
return string.format('arg%d', arg.i)
end,
precall = function(arg)
local txt = {}
if arg.default and arg.returned then
table.insert(txt, string.format('if(arg%d_idx)', arg.i)) -- means it was passed as arg
table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i))
table.insert(txt, string.format('else'))
if type(arg.default) == 'boolean' then -- boolean: we did a new()
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.%s");', arg.i, typename))
else -- otherwise: point on default tensor --> retain
table.insert(txt, string.format('{'))
table.insert(txt, string.format('TH%s_retain(arg%d);', typename, arg.i)) -- so we need a retain
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.%s");', arg.i, typename))
table.insert(txt, string.format('}'))
end
elseif arg.default then
-- we would have to deallocate the beast later if we did a new
-- unlikely anyways, so i do not support it for now
if type(arg.default) == 'boolean' then
error('a tensor cannot be optional if not returned')
end
elseif arg.returned then
table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i))
end
return table.concat(txt, '\n')
end,
postcall = function(arg)
local txt = {}
if arg.creturned then
-- this next line is actually debatable
table.insert(txt, string.format('TH%s_retain(arg%d);', typename, arg.i))
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.%s");', arg.i, typename))
end
return table.concat(txt, '\n')
end
}
end
types.LongArg = {
vararg = true,
helpname = function(arg)
return "(LongStorage | dim1 [dim2...])"
end,
declare = function(arg)
return string.format("THLongStorage *arg%d = NULL;", arg.i)
end,
init = function(arg)
if arg.default then
error('LongArg cannot have a default value')
end
end,
check = function(arg, idx)
return string.format("torch_islongargs(L, %d)", idx)
end,
read = function(arg, idx)
return string.format("arg%d = torch_checklongargs(L, %d);", arg.i, idx)
end,
carg = function(arg, idx)
return string.format('arg%d', arg.i)
end,
creturn = function(arg, idx)
return string.format('arg%d', arg.i)
end,
precall = function(arg)
local txt = {}
if arg.returned then
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongStorage");', arg.i))
end
return table.concat(txt, '\n')
end,
postcall = function(arg)
local txt = {}
if arg.creturned then
-- this next line is actually debatable
table.insert(txt, string.format('THLongStorage_retain(arg%d);', arg.i))
table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongStorage");', arg.i))
end
if not arg.returned and not arg.creturned then
table.insert(txt, string.format('THLongStorage_free(arg%d);', arg.i))
end
return table.concat(txt, '\n')
end
}
types.charoption = {
helpname = function(arg)
if arg.values then
return "(" .. table.concat(arg.values, '|') .. ")"
end
end,
declare = function(arg)
local txt = {}
table.insert(txt, string.format("const char *arg%d = NULL;", arg.i))
if arg.default then
table.insert(txt, string.format("char arg%d_default = '%s';", arg.i, arg.default))
end
return table.concat(txt, '\n')
end,
init = function(arg)
return string.format("arg%d = &arg%d_default;", arg.i, arg.i)
end,
check = function(arg, idx)
local txt = {}
local txtv = {}
table.insert(txt, string.format('(arg%d = lua_tostring(L, %d)) && (', arg.i, idx))
for _,value in ipairs(arg.values) do
table.insert(txtv, string.format("*arg%d == '%s'", arg.i, value))
end
table.insert(txt, table.concat(txtv, ' || '))
table.insert(txt, ')')
return table.concat(txt, '')
end,
read = function(arg, idx)
end,
carg = function(arg, idx)
return string.format('arg%d', arg.i)
end,
creturn = function(arg, idx)
end,
precall = function(arg)
end,
postcall = function(arg)
end
}
| bsd-3-clause |
kidaa/FFXIOrgins | scripts/zones/Windurst_Woods/TextIDs.lua | 3 | 5431 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6537; -- Come back after sorting your inventory.
ITEM_OBTAINED = 6540; -- Obtained: <<<Unknown Parameter (Type: 80) 1>>><<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>
GIL_OBTAINED = 6541; -- Obtained <<<Numeric Parameter 0>>> gil.
KEYITEM_OBTAINED = 6543; -- Obtained key item: <<<Unknown Parameter (Type: 80) 1>>>
KEYITEM_LOST = 6544; -- Lost key item: <<<Unknown Parameter (Type: 80) 1>>>
NOT_HAVE_ENOUGH_GIL = 6545; -- You do not have enough gil.
HOMEPOINT_SET = 6613; -- Home point set!
FISHING_MESSAGE_OFFSET = 7016; -- You can't fish here.
IMAGE_SUPPORT = 7115; -- Your ?Multiple Choice (Parameter 1)?[fishing/woodworking/smithing/goldsmithing/clothcraft/leatherworking/bonecraft/alchemy/cooking] skills went up ...
-- Conquest System
CONQUEST = 8835; -- You've earned conquest points!
-- Other Texts
ITEM_DELIVERY_DIALOG = 6789; -- We can deliver goods to your residence or to the residences of your friends.
CHOCOBO_DIALOG = 10310; -- Kweh!
-- Mission Dialogs
YOU_ACCEPT_THE_MISSION = 6698; -- You have accepted the mission.
-- Shop Texts
JU_KAMJA_DIALOG = 6789; -- We can deliver goods to your residence or to the residences of your friends.
PEW_SAHBARAEF_DIALOG = 6789; -- We can deliver goods to your residence or to the residences of your friends.
VALERIANO_SHOP_DIALOG = 7458; -- Halfling philosophers and heroine beauties, welcome to the Troupe Valeriano show! And how gorgeous and green this fair town is!
RETTO_MARUTTO_DIALOG = 7871; -- Allo-allo! If you're after boneworking materials, then make sure you buy them herey in Windurst! We're the cheapest in the whole wide worldy!
SHIH_TAYUUN_DIALOG = 7873; -- Oh, that Retto-Marutto... If he keeps carrying on while speaking to the customers, he'll get in trouble with the guildmaster again!
KUZAH_HPIROHPON_DIALOG = 7882; -- want to get your paws on the top-quality materials as used in the Weaverrrs' Guild?
MERIRI_DIALOG = 7884; -- If you're interested in buying some works of art from our Weavers' Guild, then you've come to the right placey-wacey.
QUESSE_SHOP_DIALOG = 8424; -- Welcome to the Windurst Chocobo Stables.
MONONCHAA_SHOP_DIALOG = 8425; -- , then hurry up and decide, then get the heck out of herrre!
MANYNY_SHOP_DIALOG = 8426; -- Are you in urgent needy-weedy of anything? I have a variety of thingy-wingies you may be interested in.
WIJETIREN_SHOP_DIALOG = 8431; -- From humble Mithran cold medicines to the legendary Windurstian ambrrrosia of immortality, we have it all...
NHOBI_ZALKIA_OPEN_DIALOG = 8434; -- Psst... Interested in some rrreal hot property? From lucky chocobo digs to bargain goods that fell off the back of an airship...all my stuff is a rrreal steal!
NHOBI_ZALKIA_CLOSED_DIALOG = 8435; -- You're interested in some cheap shopping, rrright? I'm real sorry. I'm not doing business rrright now.
NYALABICCIO_OPEN_DIALOG = 8436; -- Ladies and gentlemen, kittens and cubs! Do we have the sale that you've been waiting forrr!
NYALABICCIO_CLOSED_DIALOG = 8437; -- Sorry, but our shop is closed rrright now. Why don't you go to Gustaberg and help the situation out therrre?
BIN_STEJIHNA_OPEN_DIALOG = 8438; -- Why don't you buy something from me? You won't regrrret it! I've got all sorts of goods from the Zulkheim region!
BIN_STEJIHNA_CLOSED_DIALOG = 8439; -- I'm taking a brrreak from the saleswoman gig to give dirrrections. So...through this arrrch is the residential area.
TARAIHIPERUNHI_OPEN_DIALOG = 8440; -- Ooh...do I have some great merchandise for you! Man...these are once-in-a-lifetime offers, so get them while you can.
TARAIHIPERUNHI_CLOSED_DIALOG = 8441; -- I am but a poor merchant. Mate, but you just wait! Strife...one day I'll live the high life. Hey, that's my dream, anyway...
MILLEROVIEUNET_OPEN_DIALOG = 9885; -- Please have a look at these wonderful products from Qufim Island! You won't regret it!
MILLEROVIEUNET_CLOSED_DIALOG = 9886; -- Now that I've finally learned the language here, I'd like to start my own business. If I could only find a supplier...
--Test
RAKOHBUUMA_OPEN_DIALOG = 7555; -- To expel those who would subvert the law and order of Windurst Woods...
-- Quest Dialog
PERIH_VASHAI_DIALOG = 8170; -- You can now become a ranger!
CATALIA_DIALOG = 8472; -- While we cannot break our promise to the Windurstians, to ensure justice is served, we would secretly like you to take two shields off of the Yagudo who you meet en route.
FORINE_DIALOG = 8473; -- Act according to our convictions while fulfilling our promise with the Tarutaru. This is indeed a fitting course for us, the people of glorious San d'Oria.
APURURU_DIALOG = 9398; -- There's no way Semih Lafihna will just hand it over for no good reason. Maybe if you try talking with Kupipi...
-- Harvest Festival
TRICK_OR_TREAT = 9643; -- Trick or treat...
THANK_YOU_TREAT = 9644; -- And now for your treat...
HERE_TAKE_THIS = 9645; -- Here, take this...
IF_YOU_WEAR_THIS = 9646; -- If you put this on and walk around, something...unexpected might happen...
THANK_YOU = 9644; -- Thank you...
-- conquest Base
CONQUEST_BASE = 0;
| gpl-3.0 |
Eric-Dang/CocosLua | src/game/guanqia.lua | 1 | 5447 | ---------------------------------------------------------------------------------------------------
-- ¹Ø¿¨ÐÅÏ¢
---------------------------------------------------------------------------------------------------
local d_chunk = require "game.chunk"
---------------------------------------------------------------------------------------------------
local chuck_color = {
pink = 1, -- ·ÛÉ«
red = 2, -- ºìÉ«
yellow = 3, -- »ÆÉ«
blue = 4, -- À¶É«
green = 5, -- ÂÌÉ«
purple = 6, -- ×ÏÉ«
}
-- ¸÷ÖÖÑÕÉ«¸÷ÖÖ״̬¶ÔÓ¦µÄÌùͼÐÅÏ¢
local chunk_file_names = {
[chuck_color.pink] = {
normal = "yuansu_fen.PNG",
normalTNT = "fanweifen.png", normalRowMissile = "hengzadanfen.png", normalColumnMissile = "suzadanfen.png", normalSpecter = "zadanfen.png",
specialTNT = "fanwei.png", specialRowMissile = "henzadan.png", specialColumnMissile = "suzadan.png", specialSpecter = "yuansu_ranse.png"
},
[chuck_color.red] = {
normal = "yuansu_hong.PNG",
normalTNT = "fanweihong.png", normalRowMissile = "hengzadanhong.png", normalColumnMissile = "suzadanhong.png", normalSpecter = "zadanhong.png",
specialTNT = "fanwei.png", specialRowMissile = "henzadan.png", specialColumnMissile = "suzadan.png", specialSpecter = "yuansu_ranse.png"
},
[chuck_color.yellow] = {
normal = "yuansu_huang.PNG",
normalTNT = "fanweihuang.png", normalRowMissile = "hengzadanhuang.png", normalColumnMissile = "suzadanhuang.png", normalSpecter = "zadanhuang.png",
specialTNT = "fanwei.png", specialRowMissile = "henzadan.png", specialColumnMissile = "suzadan.png", specialSpecter = "yuansu_ranse.png"
},
[chuck_color.blue] = {
normal = "yuansu_lan.PNG",
normalTNT = "fanweilan.png", normalRowMissile = "hengzadanlan.png", normalColumnMissile = "suzadanlan.png", normalSpecter = "zadanlan.png",
specialTNT = "fanwei.png", specialRowMissile = "henzadan.png", specialColumnMissile = "suzadan.png", specialSpecter = "yuansu_ranse.png"
},
[chuck_color.green] = {
normal = "yuansu_lv.PNG",
normalTNT = "fanweilv.png", normalRowMissile = "hengzadanlv.png", normalColumnMissile = "suzadanlv.png", normalSpecter = "zadanlv.png",
specialTNT = "fanwei.png", specialRowMissile = "henzadan.png", specialColumnMissile = "suzadan.png", specialSpecter = "yuansu_ranse.png"
},
[chuck_color.purple] = {
normal = "yuansu_zhi.PNG",
normalTNT = "fanweizhi.png", normalRowMissile = "hengzadanzhi.png", normalColumnMissile = "suzadanzhi.png", normalSpecter = "zadanzhi.png",
specialTNT = "fanwei.png", specialRowMissile = "henzadan.png", specialColumnMissile = "suzadan.png", specialSpecter = "yuansu_ranse.png"
},
}
---------------------------------------------------------------------------------------------------
local Guanqia = class("Guanqia")
---------------------------------------------------------------------------------------------------
-- ¸ù¾ÝtouchµÄλÖÃÈ·¶¨µã»÷µÄÊÇÄĸö¿é
-- ·µ»ØÖµÎªm_guanqia_infoÖеÄË÷Òý
-- index˳ÐòºÍm_guanqia_info´æ´¢·½Ê½Ïàͬ
local function GetIndexByTouchPos(x, y)
return 1, 1
end
function Guanqia:ctor(tContainer, winSize)
-- Íæ¼ÒÑ¡Ôñ¹Ø¿¨µÄÌî³äÊý¾Ý i26¶ÔÓ¦µÄÊý¾ÝÐÅϢΪself.m_guanqia_info[2][6]
-- ÓÅÏÈÐд洢
-- ÁÐ\ÐÐ 1 2 3 4 5
-- 1 i11 i12 i13 i14 i15
-- 2 i26
-- 3
-- 4
-- 5 i55
self.m_guanqia_info = {} -- ¹Ø¿¨ÐÅÏ¢
self.m_Container = tContainer -- µãÏû¿éÈÝÆ÷
self.m_winSize = winSize -- ³ß´ç
self.m_chunkLength = 40 -- µãÏû¿é´óС
self.m_chunkWidth = 40 -- µãÏû¿é´óС
self.m_chunkRowCount = 9 -- ÈÝÆ÷¿ÉÒÔÈÝÄɵãÏû¿éµÄ×ݺáÊýÁ¿
self.m_chunkColumnCount = 9 -- ÈÝÆ÷¿ÉÒÔÈÝÄɵãÏû¿éµÄ×ݺáÊýÁ¿
self.GuanqiaRect = {} -- ÈÝÆ÷´æ·ÅµãÏû¿éµÄRect
self:CalcGuanqiaRect()
end
function Guanqia:CalcGuanqiaRect()
-- for k, v in pairs(self.m_winSize) do print(k, v) end
local centerX = math.floor(self.m_winSize.width/2)
local centerY = math.floor(self.m_winSize.height/2)
local chunkRowLen = self.m_chunkRowCount * self.m_chunkLength
local chunkColumnLen = self.m_chunkColumnCount * self.m_chunkWidth
local allChunkCenterX = math.floor(chunkRowLen/2)
local allChunkCenterY = math.floor(chunkColumnLen/2)
-- ĬÈϵÄêµãÊÇ(0.5, 0.5)
self.GuanqiaRect.left = centerX - allChunkCenterX + math.floor(self.m_chunkLength/2)
self.GuanqiaRect.right = centerX + allChunkCenterX
self.GuanqiaRect.top = centerY + allChunkCenterY
self.GuanqiaRect.bottom = centerY - allChunkCenterY + math.floor(self.m_chunkWidth/2)
end
function Guanqia:GetDropChunk(row, column)
return math.random(1, 6)
end
function Guanqia:GetLevelConfig(level)
for i = 1, 9 do
self.m_guanqia_info[i] = {}
for j = 1, 9 do
self.m_guanqia_info[i][j] = math.random(1, 6)
end
end
return self.m_guanqia_info
end
function Guanqia:InitAllChunk()
local level_config = self:GetLevelConfig(1)
for row, row_info in pairs(level_config) do
for column, chunkType in pairs(row_info) do
local chunk_inof = {
row = row,
column = column,
type = chunkType,
chartlet = chunk_file_names[chunkType],
container = self.m_Container,
}
local chunk = d_chunk.Chunk:create(chunk_inof)
local chunkPos = {
x = self.GuanqiaRect.left + self.m_chunkLength * (row - 1),
y = self.GuanqiaRect.bottom + self.m_chunkWidth * (column - 1)
}
chunk:Init(chunkPos)
self.m_guanqia_info[row][column] = chunk
end
end
end
function Guanqia:Clear()
end
function Guanqia:ClickChunk(row, column)
print("Guanqia:ClickChunk", row, column)
end
return Guanqia
| mit |
capr/fbclient-alien | lua/fbclient/status_vector.lua | 2 | 4528 | --[[
STATUS_VECTOR structure: encapsulate error reporting for all firebird functions
new() -> sv
status(sv) -> true|nil,errcode
full_status(fbapi, sv) -> true|nil,full_error_message
errors(fbapi, sv) -> {err_msg1,...}
sqlcode(fbapi, sv) -> n; deprecated in favor of sqlstate() in firebird 2.5+
sqlstate(fbapi, sv) -> s; SQL-2003 compliant SQLSTATE code; fbclient 2.5+ firebird 2.5+
sqlerror(fbapi, sqlcode) -> sql_error_message
pcall(fbapi, sv, fname, ...) -> true,status|false,full_error_message
try(fbapi, sv, fname, ...) -> status; breaks on errors with full_error_message
USAGE:
use new() to get you a new status_vector, then you can use any Firebird API function
with it (arg#1). then check out status() to see if the function failed, and if so, call errors(), etc.
to grab the errors. alternatively, use pcall() with any firebird function, which follows
the lua protocol for failing, or use try() to make them break directly.
on success, the status code returned by the function is returned (rarely used).
TODO:
- error_codes(b, sv) -> {errtype=errcode|errmsg,...}
]]
module(...,require 'fbclient.module')
local binding = require 'fbclient.binding'
--to be used by error_codes()
local codes = {
isc_arg_end = 0, -- end of argument list
isc_arg_gds = 1, -- generic DSRI (means Interbase) status value
isc_arg_string = 2, -- string argument
isc_arg_cstring = 3, -- count & string argument
isc_arg_number = 4, -- numeric argument (long)
isc_arg_interpreted = 5, -- interpreted status code (string)
isc_arg_vms = 6, -- VAX/VMS status code (long)
isc_arg_unix = 7, -- UNIX error code
isc_arg_domain = 8, -- Apollo/Domain error code
isc_arg_dos = 9, -- MSDOS/OS2 error code
isc_arg_mpexl = 10, -- HP MPE/XL error code
isc_arg_mpexl_ipc = 11, -- HP MPE/XL IPC error code
isc_arg_next_mach = 15, -- NeXT/Mach error code
isc_arg_netware = 16, -- NetWare error code
isc_arg_win32 = 17, -- Win32 error code
isc_arg_warning = 18, -- warning argument
}
function new()
return alien.buffer(struct.size('i')*20)
end
-- this function is made so you can do assert(status(sv)) after each firebird call.
function status(sv)
--checktype(sv,'alien buffer',1)
s0, s1 = struct.unpack('ii', sv, struct.size('ii'))
return not (s0 == 1 and s1 ~= 0), s1
end
-- use this only if status() returns false.
function errors(fbapi, sv)
checktype(fbapi,'alien library',1)
--checktype(sv,'alien buffer',2)
local errlist = {}
local msg = alien.buffer(2048)
local psv = alien.buffer(POINTER_SIZE)
psv:set(1, sv:topointer(), 'pointer')
while fbapi.fb_interpret(msg, 2048, psv) ~= 0 do
errlist[#errlist+1] = msg:tostring()
end
return errlist
end
-- use this if status() returns false.
function sqlcode(fbapi, sv)
return fbapi.isc_sqlcode(sv)
end
-- use this if status() returns false.
function sqlstate(fbapi, sv)
checktype(fbapi,'alien library',1)
--checktype(sv,'alien buffer',2)
local sqlstate_buf = alien.buffer(6)
fbapi.fb_sqlstate(sqlstate_buf, sv)
return sqlstate_buf:tostring(5)
end
-- use this if status() returns false.
function sqlerror(fbapi, sqlcode)
checktype(fbapi,'alien library',1)
local msg = alien.buffer(2048)
fbapi.isc_sql_interprete(sqlcode, msg, 2048)
return msg:tostring()
end
function full_status(fbapi, sv)
checktype(fbapi,'alien library',1)
--checktype(sv,'alien buffer',2)
local ok,err = status(sv)
if not ok then
local errcodes = package.loaded['fbclient.error_codes']
if errcodes then
local err_name = errcodes[err]
if err_name then
err = err_name..' ['..err..']'
end
end
local errlist = errors(fbapi, sv)
local sqlcod = sqlcode(fbapi, sv)
--TODO: include sqlstate() only if supported in the client library: local sqlstat = sqlstate(fbapi, sv)
local sqlerr = sqlerror(fbapi, sqlcod)
err = 'error '..err..': '..table.concat(errlist,'\n')..
'\nSQLCODE = '..(sqlcod or '<none>')..(sqlerr and ', '..sqlerr or '')
end
return ok,err
end
-- calls fname (which is the name of a firebird API function) in "protected mode",
-- following the return protocol of lua's pcall
function pcall(fbapi, sv, fname,...)
checktype(fbapi,'alien library',1)
--checktype(sv,'alien buffer',2)
checktype(fname,'string',3)
local status = fbapi[fname](sv,...)
ok,err = full_status(fbapi, sv)
if ok then
return true,status
else
return false,fname..'() '..err
end
end
function try(fbapi, sv, fname,...)
local ok,result = pcall(fbapi, sv, fname,...)
if ok then
return result
else
error(result, 3)
end
end
| mit |
nonconforme/U3DTerrainEditor | Bin/OldFilters/dirtgrass.lua | 2 | 1152 | return
{
name="Perlin Fractal Terrain Types",
description="Create a mottled dirt/grass terrain.",
options=
{
{name="Frequency", type="value", value=8},
{name="Num Octaves", type="value", value=6},
{name="Gain", type="value", value=0.8},
{name="Seed", type="value", value=12345},
{name="Use Mask?", type="flag", value=false},
{name="Invert Mask?", type="flag", value=false},
},
execute=function(self)
local frequency=self.options[1].value
local octaves=self.options[2].value
local gn=self.options[3].value
local seed=self.options[4].value
local usemask=self.options[5].value
local invertmask=self.options[6].value
local k=CKernel()
local point5=k:constant(0.5)
local fbm=k:simplefBm(3, 3, octaves, frequency, seed, true)
local scale=k:multiply(fbm,point5)
local offset=k:add(scale,point5)
local gainval=k:constant(gn)
local gain=k:gain(gainval,offset)
local buffer=RasterBuffer(blend1:GetWidth(), blend1:GetHeight())
RenderANLKernelToBuffer(buffer,k,0,1)
BlendColorWithRasterizedBuffer(blend1, buffer, Color(0,1,0,0), mask, usemask, invertmask)
blendtex1:SetData(blend1,false)
end,
} | mit |
Fatalerror66/ffxi-a | scripts/globals/mobskills/Everyones_Grudge.lua | 6 | 1545 | ---------------------------------------------
-- Everyones Grudge
--
-- Notes: Invokes collective hatred to spite a single target.
-- Damage done is 5x the amount of tonberries you have killed! For NM's using this it is 50 x damage.
---------------------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/status");
require("/scripts/globals/monstertpmoves");
---------------------------------------------
function OnMobSkillCheck(target,mob,skill)
if(mob:isMobType(MOBTYPE_NOTORIOUS)) then
return 1;
end
return 0;
end;
function OnMobWeaponSkill(target, mob, skill)
local realDmg = 0;
local mobID = mob:getID();
local power = 5;
if(target:getID() > 100000) then
realDmg = power * math.random(30,100);
else
realDmg = power * target:getVar("EVERYONES_GRUDGE_KILLS"); -- Damage is 5 times the amount you have killed
if(mobID == 17428677 or mobID == 17433008 or mobID == 17433006 or mobID == 17433009 or mobID == 17432994 or mobID == 17433007 or mobID == 17428813 or mobID == 17432659 or mobID == 17432846 or mobID == 17428809) then
realDmg = realDmg * 10; -- Sets the Multiplyer to 50 for NM's
elseif(mobID == 17432799 or mobID == 17428611 or MobID == 17428554 or mobID == 17428751 or mobID == 17432609 or mobID == 16814432 or mobID == 17432624 or mobID == 17285526 or mobID == 17285460) then
realDmg = realDmg * 10; -- Sets the Multiplyer to 50 for NM's , staggered list
end
end
target:delHP(realDmg);
return realDmg;
end; | gpl-3.0 |
mrbangi/deviilbot | plugins/plugins.lua | 7 | 6145 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ? enabled, ? disabled
local status = '?'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '?'
end
nact = nact+1
end
if not only_enabled or status == '?' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'. '..v..' '..status..'\n'
end
end
local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled'
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ? enabled, ? disabled
local status = '?'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '?'
end
nact = nact+1
end
if not only_enabled or status == '?' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..v..' '..status..'\n'
end
end
local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return 'Plugin '..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return 'Plugin '..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return 'Plugin '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return 'Plugin '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return 'Plugin '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return 'Plugin '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == 'enable' and matches[3] == 'chat' then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
-- Enable a plugin
if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
-- Disable a plugin on a chat
if matches[1] == 'disable' and matches[3] == 'chat' then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
-- Disable a plugin
if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plugins disable [plugin] chat : disable plugin only this chat.",
"!plugins enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plugins : list all plugins.",
"!plugins enable [plugin] : enable plugin.",
"!plugins disable [plugin] : disable plugin.",
"!plugins reload : reloads all plugins." },
},
patterns = {
"^!plugins$",
"^!plugins? (enable) ([%w_%.%-]+)$",
"^!plugins? (disable) ([%w_%.%-]+)$",
"^!plugins? (enable) ([%w_%.%-]+) (chat)",
"^!plugins? (disable) ([%w_%.%-]+) (chat)",
"^!plugins? (reload)$" },
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end
| gpl-2.0 |
kidaa/FFXIOrgins | scripts/zones/Zeruhn_Mines/Zone.lua | 1 | 2378 | -----------------------------------
--
-- Zone: Zeruhn_Mines (172)
--
-----------------------------------
package.loaded["scripts/zones/Zeruhn_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Zeruhn_Mines/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (prevZone == 143) then
cs = 0x0096;
if (player:getQuestStatus(BASTOK, BLADE_OF_DARKNESS) == QUEST_ACCEPTED) then
if (player:getVar("ZeruhnMines_Zeid_CS") == 0) then
cs = 0x0082;
elseif (player:hasItem(16607) == false) then
cs = 0x0083;
end
elseif (player:getQuestStatus(BASTOK,BLADE_OF_DEATH) == QUEST_ACCEPTED) then
if (player:hasItem(16607) == false) then
cs = 0x0083;
end
end
elseif ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-270.707,14.159,-20.268,0);
end
return cs;
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;
-----------------------------------
-- 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);
if (csid == 0x0082 or csid == 0x0083) then
if (player:getFreeSlotsCount() > 0) then
player:addItem(16607);
player:setVar("ChaosbringerKills", 0);
player:messageSpecial(ITEM_OBTAINED,16607);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16607);
end
player:setVar("ZeruhnMines_Zeid_CS", 1);
end
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Southern_San_dOria/npcs/Kipopo.lua | 11 | 1778 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Kipopo
-- Type: Leathercraft Synthesis Image Support
-- @pos -191.050 -2.15 12.285 230
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/status");
require("scripts/globals/crafting");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,7);
local SkillCap = getCraftSkillCap(player,128);
local SkillLevel = player:getSkillLevel(128);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_LEATHERCRAFT_IMAGERY) == false) then
player:startEvent(0x028B,SkillCap,SkillLevel,1,239,player:getGil(),0,0,0);
else
player:startEvent(0x028B,SkillCap,SkillLevel,1,239,player:getGil(),7128,0,0);
end
else
player:startEvent(0x028B); -- Standard Dialogue
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 == 0x028B and option == 1) then
player:messageSpecial(LEATHER_SUPPORT,0,5,1);
player:addStatusEffect(EFFECT_LEATHERCRAFT_IMAGERY,1,0,120);
end
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Mhaura/npcs/Pikini-Mikini.lua | 36 | 1448 | -----------------------------------
-- Area: Mhaura
-- NPC: Pikini-Mikini
-- Standard Merchant NPC
-- @pos -48 -4 30 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,PIKINIMIKINI_SHOP_DIALOG);
stock = {0x1036,2335, --Eye Drops
0x1034,284, --Antidote
0x1037,720, --Echo Drops
0x1010,819, --Potion
0x119d,10, --Distilled Water
0x395,1821, --Parchment
0x43f3,9, --Lugworm
0x3fd,450, --Hatchet
0x1118,108, --Meat Jerky
0x14b3,133, --Salsa
0x0b33,9000} --Mhaura Waystone
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/La_Theine_Plateau/npcs/qm2.lua | 2 | 1829 | -----------------------------------
-- Area: La Theine Plateau
-- NPC: ???
-- Involved in Quest: HITTING_THE_MARQUISATE THF af3
-----------------------------------
package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/globals/settings");
require("scripts/zones/La_Theine_Plateau/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
hittingTheMarquisateNanaaCS = player:getVar("hittingTheMarquisateNanaaCS");
if(trade:hasItemQty(605,1) and trade:getItemCount() == 1) then -- Trade pickaxe
if (hittingTheMarquisateNanaaCS == 1) then
player:startEvent(0x0077);
end
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
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 == 0x0077) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14094);
else
player:addItem(14094);
player:messageSpecial(ITEM_OBTAINED,14094);
player:tradeComplete();
player:completeQuest(WINDURST, HITTING_THE_MARQUISATE);
player:addTitle(PARAGON_OF_THIEF_EXCELLENCE);
player:setVar("hittingTheMarquisateNanaaCS",0);
player:delKeyItem(CAT_BURGLARS_NOTE);
end
end
end; | gpl-3.0 |
miotatsu/milton | tundra/scripts/tundra/tools/msvc-winsdk.lua | 28 | 4318 | -- msvc-winsdk.lua - Use Microsoft Windows SDK 7.1 or later to build.
module(..., package.seeall)
local native = require "tundra.native"
local os = require "os"
if native.host_platform ~= "windows" then
error("the msvc toolset only works on windows hosts")
end
local function get_host_arch()
local snative = native.getenv("PROCESSOR_ARCHITECTURE")
local swow = native.getenv("PROCESSOR_ARCHITEW6432", "")
if snative == "AMD64" or swow == "AMD64" then
return "x64"
elseif snative == "IA64" or swow == "IA64" then
return "itanium";
else
return "x86"
end
end
local compiler_dirs = {
["x86"] = {
["x86"] = "bin\\",
["x64"] = "bin\\x86_amd64\\",
["itanium"] = "bin\\x86_ia64\\",
},
["x64"] = {
["x86"] = "bin\\",
["x64"] = {
["11.0"] = "bin\\x86_amd64\\",
"bin\\amd64\\"
},
["itanium"] = "bin\\x86_ia64\\",
},
["itanium"] = {
["x86"] = "bin\\x86_ia64\\",
["itanium"] = "bin\\ia64\\",
},
}
local function setup(env, options)
options = options or {}
local target_arch = options.TargetArch or "x86"
local host_arch = options.HostArch or get_host_arch()
local vcversion = options.VcVersion or "10.0"
local binDir =
compiler_dirs[host_arch][target_arch][vcversion]
or compiler_dirs[host_arch][target_arch][1]
or compiler_dirs[host_arch][target_arch]
if not binDir then
errorf("can't build target arch %s on host arch %s", target_arch, host_arch)
end
local sdkDir;
local sdkDirIncludes;
local sdkLibDir;
local vcLibDir;
if vcversion == "11.0" then
local sdk_key = "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows\\v8.0"
sdkDir = assert(native.reg_query("HKLM", sdk_key, "InstallationFolder"))
sdkDirIncludes = { sdkDir .. "\\INCLUDE\\UM", sdkDir .. "\\INCLUDE\\SHARED" }
sdkLibDir = "LIB\\win8\\um\\"
vcLibDir = "LIB"
if "x86" == target_arch then
sdkLibDir = sdkLibDir .. "x86"
elseif "x64" == target_arch then
sdkLibDir = sdkLibDir .. "x64"
vcLibDir = "LIB\\amd64"
elseif "arm" == target_arch then
sdkLibDir = sdkLibDir .. "arm"
end
else
local sdk_key = "SOFTWARE\\Microsoft\\Microsoft SDKs\\Windows"
sdkDir = assert(native.reg_query("HKLM", sdk_key, "CurrentInstallFolder"))
sdkDirIncludes = { sdkDir .. "\\INCLUDE" };
sdkLibDir = "LIB"
vcLibDir = "LIB"
if "x64" == target_arch then
sdkLibDir = "LIB\\x64"
vcLibDir = "LIB\\amd64"
elseif "itanium" == target_arch then
sdkLibDir = "LIB\\IA64"
vcLibDir = "LIB\\IA64"
end
end
local vc_key = "SOFTWARE\\Microsoft\\VisualStudio\\SxS\\VC7"
local vc_dir = assert(native.reg_query("HKLM", vc_key, vcversion))
if vc_dir:sub(-1) ~= '\\' then
vc_dir = vc_dir .. '\\'
end
local cl_exe = '"' .. vc_dir .. binDir .. "cl.exe" ..'"'
local lib_exe = '"' .. vc_dir .. binDir .. "lib.exe" ..'"'
local link_exe = '"' .. vc_dir .. binDir .. "link.exe" ..'"'
env:set('CC', cl_exe)
env:set('CXX', cl_exe)
env:set('LIB', lib_exe)
env:set('LD', link_exe)
-- Set up the MS SDK associated with visual studio
env:set_external_env_var("WindowsSdkDir", sdkDir)
env:set_external_env_var("INCLUDE", table.concat(sdkDirIncludes, ";") .. ";" .. vc_dir .. "\\INCLUDE")
local rc_exe
print("vcversion", vcversion)
if vcversion == "11.0" then
rc_exe = '"' .. sdkDir .. "\\bin\\x86\\rc.exe" ..'"'
else
rc_exe = '"' .. sdkDir .. "\\bin\\rc.exe" ..'"'
end
env:set('RC', rc_exe)
local libString = sdkDir .. "\\" .. sdkLibDir .. ";" .. vc_dir .. "\\" .. vcLibDir
env:set_external_env_var("LIB", libString)
env:set_external_env_var("LIBPATH", libString)
local path = { }
local vc_root = vc_dir:sub(1, -4)
if binDir ~= "\\bin\\" then
path[#path + 1] = vc_dir .. "\\bin"
end
path[#path + 1] = vc_root .. "Common7\\Tools" -- drop vc\ at end
path[#path + 1] = vc_root .. "Common7\\IDE" -- drop vc\ at end
path[#path + 1] = sdkDir
path[#path + 1] = vc_dir .. binDir
path[#path + 1] = env:get_external_env_var('PATH')
env:set_external_env_var("PATH", table.concat(path, ';'))
end
function apply(env, options)
-- Load basic MSVC environment setup first. We're going to replace the paths to
-- some tools.
tundra.unitgen.load_toolset('msvc', env)
setup(env, options)
end
| mit |
lua-stdlib/lua-stdlib | lib/std/debug.lua | 1 | 3921 | --[[
General Lua Libraries for Lua 5.1, 5.2 & 5.3
Copyright (C) 2002-2018 stdlib authors
]]
--[[--
Additions to the core debug module.
The module table returned by `std.debug` also contains all of the entries
from the core debug table. An hygienic way to import this module, then, is
simply to override the core `debug` locally:
local debug = require 'std.debug'
@corelibrary std.debug
]]
local _ENV = require 'std.normalize' {
'debug',
_debug = require 'std._debug',
concat = 'table.concat',
huge = 'math.huge',
max = 'math.max',
merge = 'table.merge',
stderr = 'io.stderr',
}
--[[ =============== ]]--
--[[ Implementation. ]]--
--[[ =============== ]]--
local function say(n, ...)
local level, argt = n, {...}
if type(n) ~= 'number' then
level, argt = 1, {n, ...}
end
if _debug.level ~= huge and
((type(_debug.level) == 'number' and _debug.level >= level) or level <= 1)
then
local t = {}
for k, v in pairs(argt) do
t[k] = str(v)
end
stderr:write(concat(t, '\t') .. '\n')
end
end
local level = 0
local function trace(event)
local t = debug.getinfo(3)
local s = ' >>> '
for i = 1, level do
s = s .. ' '
end
if t ~= nil and t.currentline >= 0 then
s = s .. t.short_src .. ':' .. t.currentline .. ' '
end
t = debug.getinfo(2)
if event == 'call' then
level = level + 1
else
level = max(level - 1, 0)
end
if t.what == 'main' then
if event == 'call' then
s = s .. 'begin ' .. t.short_src
else
s = s .. 'end ' .. t.short_src
end
elseif t.what == 'Lua' then
s = s .. event .. ' ' ..(t.name or '(Lua)') .. ' <' ..
t.linedefined .. ':' .. t.short_src .. '>'
else
s = s .. event .. ' ' ..(t.name or '(C)') .. ' [' .. t.what .. ']'
end
stderr:write(s .. '\n')
end
-- Set hooks according to _debug
if _debug.call then
debug.sethook(trace, 'cr')
end
local M = {
--- Function Environments
-- @section environments
--- Extend `debug.getfenv` to unwrap functables correctly.
-- @function getfenv
-- @tparam int|function|functable fn target function, or stack level
-- @treturn table environment of *fn*
getfenv = getfenv,
--- Extend `debug.setfenv` to unwrap functables correctly.
-- @function setfenv
-- @tparam function|functable fn target function
-- @tparam table env new function environment
-- @treturn function *fn*
setfenv = setfenv,
--- Functions
-- @section functions
--- Print a debugging message to `io.stderr`.
-- Display arguments passed through `std.tostring` and separated by tab
-- characters when `std._debug` hinting is `true` and *n* is 1 or less;
-- or `std._debug.level` is a number greater than or equal to *n*. If
-- `std._debug` hinting is false or nil, nothing is written.
-- @function say
-- @int[opt=1] n debugging level, smaller is higher priority
-- @param ... objects to print(as for print)
-- @usage
-- local _debug = require 'std._debug'
-- _debug.level = 3
-- say(2, '_debug status level:', _debug.level)
say = say,
--- Trace function calls.
-- Use as debug.sethook(trace, 'cr'), which is done automatically
-- when `std._debug.call` is set.
-- Based on test/trace-calls.lua from the Lua distribution.
-- @function trace
-- @string event event causing the call
-- @usage
-- local _debug = require 'std._debug'
-- _debug.call = true
-- local debug = require 'std.debug'
trace = trace,
}
--- Metamethods
-- @section metamethods
--- Equivalent to calling `debug.say(1, ...)`
-- @function __call
-- @see say
-- @usage
-- local debug = require 'std.debug'
-- debug 'oh noes!'
local metatable = {
__call = function(self, ...)
M.say(1, ...)
end,
}
return setmetatable(merge(debug, M), metatable)
| mit |
Fatalerror66/ffxi-a | scripts/zones/Monastic_Cavern/TextIDs.lua | 4 | 1042 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6375; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6378; -- Obtained: <item>
GIL_OBTAINED = 6379; -- Obtained <number> gil
KEYITEM_OBTAINED = 6381; -- Obtained key item: <keyitem>
-- Other dialog
NOTHING_OUT_OF_ORDINARY = 7256; -- There is nothing out of the ordinary here.
THE_MAGICITE_GLOWS_OMINOUSLY = 7222; -- The magicite glows ominously.
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7240; -- You unlock the chest!
CHEST_FAIL = 7241; -- Fails to open the chest.
CHEST_TRAP = 7242; -- The chest was trapped!
CHEST_WEAK = 7243; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7244; -- The chest was a mimic!
CHEST_MOOGLE = 7245; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7246; -- The chest was but an illusion...
CHEST_LOCKED = 7247; -- The chest appears to be locked.
| gpl-3.0 |
teddemunnik/tundra | scripts/tundra/tools/vbcc.lua | 25 | 1563 | module(..., package.seeall)
local native = require "tundra.native"
function apply(env, options)
-- load the generic C toolset first
tundra.unitgen.load_toolset("generic-cpp", env)
-- Also add assembly support.
tundra.unitgen.load_toolset("generic-asm", env)
local vbcc_root = assert(native.getenv("VBCC"), "VBCC environment variable must be set")
env:set_many {
["NATIVE_SUFFIXES"] = { ".c", ".cpp", ".cc", ".cxx", ".s", ".asm", ".a", ".o" },
["OBJECTSUFFIX"] = ".o",
["LIBPREFIX"] = "",
["LIBSUFFIX"] = ".a",
["VBCC_ROOT"] = vbcc_root,
["CC"] = vbcc_root .. "$(SEP)bin$(SEP)vc$(HOSTPROGSUFFIX)",
["LIB"] = vbcc_root .. "$(SEP)bin$(SEP)vlink$(HOSTPROGSUFFIX)",
["LD"] = vbcc_root .. "$(SEP)bin$(SEP)vc$(HOSTPROGSUFFIX)",
["ASM"] = vbcc_root .. "$(SEP)bin$(SEP)vasmm68k_mot$(HOSTPROGSUFFIX)",
["VBCC_SDK_INC"] = vbcc_root .. "$(SEP)include$(SEP)sdk",
["_OS_CCOPTS"] = "",
["_OS_CXXOPTS"] = "",
["CCCOM"] = "$(CC) $(_OS_CCOPTS) -c $(CPPDEFS:p-D) $(CPPPATH:f:p-I) $(CCOPTS) $(CCOPTS_$(CURRENT_VARIANT:u)) -o $(@) $(<)",
["ASMCOM"] = "$(ASM) -quiet -Fhunk -phxass $(ASMOPTS) $(ASMOPTS_$(CURRENT_VARIANT:u)) $(ASMDEFS:p-D) $(ASMINCPATH:f:p-I) -I$(VBCC_SDK_INC) -o $(@) $(<)",
["PROGOPTS"] = "",
["PROGCOM"] = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) $(LIBS:p-l) -o $(@) $(<)",
["PROGPREFIX"] = "",
["LIBOPTS"] = "",
["LIBCOM"] = "$(LIB) -r $(LIBOPTS) -o $(@) $(<)",
["ASMINC_KEYWORDS"] = { "INCLUDE", "include" },
["ASMINC_BINARY_KEYWORDS"] = { "INCBIN", "incbin" },
}
end
| gpl-3.0 |
miotatsu/milton | tundra/scripts/tundra/tools/vbcc.lua | 25 | 1563 | module(..., package.seeall)
local native = require "tundra.native"
function apply(env, options)
-- load the generic C toolset first
tundra.unitgen.load_toolset("generic-cpp", env)
-- Also add assembly support.
tundra.unitgen.load_toolset("generic-asm", env)
local vbcc_root = assert(native.getenv("VBCC"), "VBCC environment variable must be set")
env:set_many {
["NATIVE_SUFFIXES"] = { ".c", ".cpp", ".cc", ".cxx", ".s", ".asm", ".a", ".o" },
["OBJECTSUFFIX"] = ".o",
["LIBPREFIX"] = "",
["LIBSUFFIX"] = ".a",
["VBCC_ROOT"] = vbcc_root,
["CC"] = vbcc_root .. "$(SEP)bin$(SEP)vc$(HOSTPROGSUFFIX)",
["LIB"] = vbcc_root .. "$(SEP)bin$(SEP)vlink$(HOSTPROGSUFFIX)",
["LD"] = vbcc_root .. "$(SEP)bin$(SEP)vc$(HOSTPROGSUFFIX)",
["ASM"] = vbcc_root .. "$(SEP)bin$(SEP)vasmm68k_mot$(HOSTPROGSUFFIX)",
["VBCC_SDK_INC"] = vbcc_root .. "$(SEP)include$(SEP)sdk",
["_OS_CCOPTS"] = "",
["_OS_CXXOPTS"] = "",
["CCCOM"] = "$(CC) $(_OS_CCOPTS) -c $(CPPDEFS:p-D) $(CPPPATH:f:p-I) $(CCOPTS) $(CCOPTS_$(CURRENT_VARIANT:u)) -o $(@) $(<)",
["ASMCOM"] = "$(ASM) -quiet -Fhunk -phxass $(ASMOPTS) $(ASMOPTS_$(CURRENT_VARIANT:u)) $(ASMDEFS:p-D) $(ASMINCPATH:f:p-I) -I$(VBCC_SDK_INC) -o $(@) $(<)",
["PROGOPTS"] = "",
["PROGCOM"] = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) $(LIBS:p-l) -o $(@) $(<)",
["PROGPREFIX"] = "",
["LIBOPTS"] = "",
["LIBCOM"] = "$(LIB) -r $(LIBOPTS) -o $(@) $(<)",
["ASMINC_KEYWORDS"] = { "INCLUDE", "include" },
["ASMINC_BINARY_KEYWORDS"] = { "INCBIN", "incbin" },
}
end
| mit |
Segs/Segs | Data/scripts/City_02_02/Spawndefs/Trolls_Skyway.spawndef.lua | 3 | 6869 | --This is a rank table
--There could be multiple tables to generate spawns from
local Trolls_Ranks_01 = {
["Underlings"] = {
--NA
},
["Minions"] = {
"Thug_Troll_01","Thug_Troll_02","Thug_Troll_03",
"Thug_Troll_04","Thug_Troll_05","Thug_Troll_06",
},
["Boss"] = {
},
["Sniper"] = {
--NA
},
["Boss"] = {
"Thug_Troll_Boss_01", "Thug_Troll_Boss_02", "Thug_Troll_Boss_03"
},
["Elite Boss"] = {
},
["Victims"] = {
"FemaleNPC_51", "FemaleNPC_56", "FemaleNPC_52",
"FemaleNPC_53", "FemaleNPC_54", "FemaleNPC_55",
"MaleNPC_50", "MaleNPC_51", "MaleNPC_52",
"MaleNPC_53", "MaleNPC_54", "MaleNPC_55",
"MaleNPC_56", "MaleNPC_57", "MaleNPC_58",
"MaleNPC_59",
},
["Specials"] = {
},
}
-- ShadyDeals --
ShadyDeal_Trolls_L11_13_V0 = {
["Markers"] = {
["Encounter_S_30"] = Trolls_Ranks_01.Minions,
["Encounter_S_32"] = Trolls_Ranks_01.Minions,
["Encounter_E_01"] = Trolls_Ranks_01.Minions,
},
}
ShadyDeal_Trolls_L11_13_V1 = {
["Markers"] = {
["Encounter_S_30"] = Trolls_Ranks_01.Boss,
["Encounter_S_32"] = Trolls_Ranks_01.Boss,
["Encounter_E_01"] = Trolls_Ranks_01.Minions,
["Encounter_E_04"] = Trolls_Ranks_01.Minions,
},
}
ShadyDeal_Trolls_L11_13_V2 = {
["Markers"] = {
["Encounter_S_30"] = Trolls_Ranks_01.Boss,
["Encounter_S_32"] = Trolls_Ranks_01.Boss,
["Encounter_E_01"] = Trolls_Ranks_01.Minions,
["Encounter_E_04"] = Trolls_Ranks_01.Minions,
["Encounter_E_05"] = Trolls_Ranks_01.Minions,
["Encounter_E_08"] = Trolls_Ranks_01.Minions,
},
}
ShadyDeal_Trolls_L11_13_V3 = {
["Markers"] = {
["Encounter_S_30"] = Trolls_Ranks_01.Boss,
["Encounter_S_32"] = Trolls_Ranks_01.Boss,
["Encounter_E_02"] = Trolls_Ranks_01.Minions,
["Encounter_E_03"] = Trolls_Ranks_01.Minions,
["Encounter_E_05"] = Trolls_Ranks_01.Minions,
["Encounter_E_06"] = Trolls_Ranks_01.Minions,
["Encounter_E_08"] = Trolls_Ranks_01.Minions,
},
}
ShadyDeal_Trolls_L14_17_V0 = ShadyDeal_Trolls_L11_13_V0
ShadyDeal_Trolls_L14_17_V1 = ShadyDeal_Trolls_L11_13_V1
ShadyDeal_Trolls_L14_17_V2 = ShadyDeal_Trolls_L11_13_V2
ShadyDeal_Trolls_L14_17_V3 = ShadyDeal_Trolls_L11_13_V3
ShadyDeal_Trolls_L18_20_V0 = ShadyDeal_Trolls_L11_13_V0
ShadyDeal_Trolls_L18_20_V1 = ShadyDeal_Trolls_L11_13_V1
ShadyDeal_Trolls_L18_20_V2 = ShadyDeal_Trolls_L11_13_V2
ShadyDeal_Trolls_L18_20_V3 = ShadyDeal_Trolls_L11_13_V3
-- Fight Club --
FightClub_Trolls_L12_15_V0 = {
["Markers"] = {
["Encounter_S_32"] = Trolls_Ranks_01.Boss,
["Encounter_S_30"] = Trolls_Ranks_01.Boss,
["Encounter_E_03"] = Trolls_Ranks_01.Minions,
["Encounter_E_07"] = Trolls_Ranks_01.Minions,
},
}
FightClub_Trolls_L12_15_V1 = {
["Markers"] = {
["Encounter_S_30"] = Trolls_Ranks_01.Minions,
["Encounter_S_32"] = Trolls_Ranks_01.Minions,
["Encounter_E_01"] = Trolls_Ranks_01.Boss,
["Encounter_E_04"] = Trolls_Ranks_01.Boss,
},
}
FightClub_Trolls_L12_15_V2 = {
["Markers"] = {
["Encounter_S_30"] = Trolls_Ranks_01.Minions,
["Encounter_S_32"] = Trolls_Ranks_01.Minions,
["Encounter_E_05"] = Trolls_Ranks_01.Boss,
["Encounter_E_06"] = Trolls_Ranks_01.Boss,
["Encounter_E_07"] = Trolls_Ranks_01.Minions,
["Encounter_E_08"] = Trolls_Ranks_01.Minions,
},
}
FightClub_Trolls_L12_15_V3 = {
["Markers"] = {
["Encounter_S_30"] = Trolls_Ranks_01.Minions,
["Encounter_S_32"] = Trolls_Ranks_01.Minions,
["Encounter_E_01"] = Trolls_Ranks_01.Boss,
["Encounter_E_02"] = Trolls_Ranks_01.Minions,
["Encounter_E_03"] = Trolls_Ranks_01.Boss,
["Encounter_E_04"] = Trolls_Ranks_01.Minions,
["Encounter_E_05"] = Trolls_Ranks_01.Minions,
["Encounter_E_08"] = Trolls_Ranks_01.Boss,
},
}
FightClub_Trolls_L16_19_V0 = FightClub_Trolls_L12_15_V0
FightClub_Trolls_L16_19_V1 = FightClub_Trolls_L12_15_V1
FightClub_Trolls_L16_19_V2 = FightClub_Trolls_L12_15_V2
FightClub_Trolls_L16_19_V3 = FightClub_Trolls_L12_15_V3
-- Vandalism --
Vandalism_Trolls_L11_13_V0 = {
["Markers"] = {
["Encounter_S_30"] = Trolls_Ranks_01.Minions,
["Encounter_E_02"] = Trolls_Ranks_01.Minions,
["Encounter_E_05"] = Trolls_Ranks_01.Minions,
["Encounter_E_06"] = Trolls_Ranks_01.Minions,
},
}
Vandalism_Trolls_L11_13_V1 = Vandalism_Trolls_L11_13_V0
Vandalism_Trolls_L11_13_V2 = Vandalism_Trolls_L11_13_V0
Vandalism_Trolls_L11_13_V3 = Vandalism_Trolls_L11_13_V0
Vandalism_Trolls_L14_17_V0 = Vandalism_Trolls_L11_13_V0
Vandalism_Trolls_L14_17_V1 = Vandalism_Trolls_L11_13_V0
Vandalism_Trolls_L14_17_V2 = Vandalism_Trolls_L11_13_V0
Vandalism_Trolls_L14_17_V3 = Vandalism_Trolls_L11_13_V0
Vandalism_Trolls_L18_20_V0 = Vandalism_Trolls_L11_13_V0
Vandalism_Trolls_L18_20_V1 = Vandalism_Trolls_L11_13_V0
Vandalism_Trolls_L18_20_V2 = Vandalism_Trolls_L11_13_V0
Vandalism_Trolls_L18_20_V3 = Vandalism_Trolls_L11_13_V0
-- Breaking in --
BreakingIn_Trolls_L11_13_V0 = {
["Markers"] = {
["Encounter_S_31"] = Trolls_Ranks_01.Minions,
["Encounter_E_05"] = Trolls_Ranks_01.Minions,
["Encounter_E_06"] = Trolls_Ranks_01.Minions,
},
}
BreakingIn_Trolls_L11_13_V1 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L11_13_V2 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L11_13_V3 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L11_13_V4 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L14_17_V0 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L14_17_V1 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L14_17_V2 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L14_17_V3 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L14_17_V4 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L18_20_V0 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L18_20_V1 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L18_20_V2 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L18_20_V3 = BreakingIn_Trolls_L11_13_V0
BreakingIn_Trolls_L18_20_V4 = BreakingIn_Trolls_L11_13_V0
-- Peddle / Mugging / Snatch --
Peddle_Trolls_L12_15_V0 = {
["Markers"] = {
["Encounter_V_40"] = Trolls_Ranks_01.Victims,
["Encounter_S_30"] = Trolls_Ranks_01.Minions,
["Encounter_E_05"] = Trolls_Ranks_01.Minions,
["Encounter_S_31"] = Trolls_Ranks_01.Minions,
},
}
Peddle_Trolls_L12_15_V1 = Peddle_Trolls_L12_15_V0
Peddle_Trolls_L12_15_V2 = Peddle_Trolls_L12_15_V0
Peddle_Trolls_L16_19_V0 = Peddle_Trolls_L12_15_V0
Peddle_Trolls_L16_19_V1 = Peddle_Trolls_L12_15_V0
Peddle_Trolls_L16_19_V2 = Peddle_Trolls_L12_15_V0
| bsd-3-clause |
kidaa/FFXIOrgins | scripts/globals/mobskills/Optic_Induration.lua | 2 | 1222 | ---------------------------------------------
-- Optic Induration
--
-- Description: Charges up a powerful, calcifying beam directed at targets in a fan-shaped area of effect. Additional effect: Petrification & enmity reset
-- Type: Magical
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: Unknown cone
-- Notes: Charges up (three times) before actually being used (except Jailer of Temperance, who doesn't need to charge it up). The petrification lasts a very long time.
---------------------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/status");
require("/scripts/globals/monstertpmoves");
---------------------------------------------
function OnMobSkillCheck(target,mob,skill)
return 0;
end;
function OnMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_PETRIFICATION;
MobStatusEffectMove(mob, target, typeEffect, 1, 0, 60);
local dmgmod = 1;
local accmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_DARK,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
mob:resetEnmity(target);
return dmg;
end;
| gpl-3.0 |
BTAxis/naev | dat/missions/empire/emp_cargo00.lua | 2 | 3677 | --[[
Simple cargo mission that opens up the Empire cargo missions.
Author: bobbens
minor edits by Infiltrator
]]--
include "dat/scripts/numstring.lua"
include "dat/scripts/jumpdist.lua"
bar_desc = _("You see an Empire Lieutenant who seems to be looking at you.")
misn_title = _("Empire Recruitment")
misn_reward = _("%s credits")
misn_desc = _("Deliver some parcels for the Empire to %s in %s.")
title = {}
title[1] = _("Spaceport Bar")
title[2] = _("Empire Recruitment")
title[3] = _("Mission Accomplished")
text = {}
text[1] = _([[You approach the Empire Lieutenant.
"Hello, I'm Lieutenant Czesc from the Empire Armada Shipping Division. We're having another recruitment operation and would be interested in having another pilot among us. Would you be interested in working for the Empire?"]])
text[2] = _([["Welcome aboard," says Czesc before giving you a firm handshake. "At first you'll just be tested with cargo missions while we gather data on your flying skills. Later on, you could get called upon for more important missions. Who knows? You could be the next Yao Pternov, greatest pilot we ever had in the armada."
He hits a couple buttons on his wrist computer, which springs into action. "It looks like we already have a simple task for you. Deliver these parcels to %s. The best pilots started delivering papers and ended up flying into combat against gigantic warships with the Interception Division."]])
text[3] = _([[You deliver the parcels to the Empire Shipping station at the %s spaceport. Afterwards, they make you do some paperwork to formalise your participation with the Empire. They tell you to keep an eye out for missions labeled ES, which stands for Empire Shipping, in the mission computer, to which you now have access.
You aren't too sure of what to make of your encounter with the Empire. Only time will tell...]])
function create ()
-- Note: this mission does not make any system claims.
local landed, landed_sys = planet.cur()
-- target destination
local planets = {}
getsysatdistance( system.cur(), 1, 6,
function(s)
for i, v in ipairs(s:planets()) do
if v:faction() == faction.get("Empire") and v:canLand() then
planets[#planets + 1] = {v, s}
end
end
return false
end )
if #planets == 0 then abort() end -- Sanity in case no suitable planets are in range.
local index = rnd.rnd(1, #planets)
dest = planets[index][1]
sys = planets[index][2]
misn.setNPC( _("Lieutenant"), "empire/unique/czesc" )
misn.setDesc( bar_desc )
end
function accept ()
misn.markerAdd( sys, "low" )
-- Intro text
if not tk.yesno( title[1], text[1] ) then
misn.finish()
end
-- Accept the mission
misn.accept()
-- Mission details
reward = 30000
misn.setTitle(misn_title)
misn.setReward( string.format(misn_reward, numstring(reward)) )
misn.setDesc( string.format(misn_desc,dest:name(),sys:name()))
-- Flavour text and mini-briefing
tk.msg( title[2], string.format( text[2], dest:name() ))
misn.osdCreate(title[2], {misn_desc:format(dest:name(),sys:name())})
-- Set up the goal
parcels = misn.cargoAdd("Parcels", 0)
hook.land("land")
end
function land()
local landed = planet.cur()
if landed == dest then
if misn.cargoRm(parcels) then
player.pay(reward)
-- More flavour text
tk.msg(title[3], string.format( text[3], dest:name() ))
var.push("es_cargo", true)
faction.modPlayerSingle("Empire",3);
misn.finish(true)
end
end
end
function abort()
misn.finish(false)
end
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Dynamis-Windurst/npcs/qm1.lua | 2 | 1258 | -----------------------------------
-- Area: Dynamis Windurst
-- NPC: qm1 (???)
-- Notes: Spawns when Megaboss is defeated
-----------------------------------
package.loaded["scripts/zones/Dynamis-Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Dynamis-Windurst/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
if(player:hasKeyItem(HYDRA_CORPS_LANTERN) == false)then
player:setVar("DynaWindurst_Win",1);
player:addKeyItem(HYDRA_CORPS_LANTERN);
player:messageSpecial(KEYITEM_OBTAINED,HYDRA_CORPS_LANTERN);
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 |
kidaa/FFXIOrgins | scripts/zones/Ordelles_Caves/npcs/Stalagmite.lua | 2 | 2371 | -----------------------------------
-- Area: Ordelles Caves
-- NPC: Stalagmite
-- Involved In Quest: Sharpening the Sword
-- @pos -51 0.1 3 193
-----------------------------------
package.loaded["scripts/zones/Ordelles_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Ordelles_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getVar("sharpeningTheSwordCS") == 3) then
local NMDespawned = GetMobAction(17568134) == 0;
local spawnTime = player:getVar("Polevik_Spawned");
local canSpawn = (os.time() - spawnTime) > 30;
local PolevikKilled = player:getVar("PolevikKilled");
if(PolevikKilled == 1) then
if((os.time() - player:getVar("Polevik_Timer") < 30) or (NMDespawned and (os.time() - spawnTime) < 30)) then
player:addKeyItem(ORDELLE_WHETSTONE);
player:messageSpecial(KEYITEM_OBTAINED,ORDELLE_WHETSTONE);
player:setVar("PolevikKilled",0);
player:setVar("Polevik_Spawned",0);
player:setVar("Polevik_Timer",0);
player:setVar("sharpeningTheSwordCS",4)
elseif(NMDespawned) then
SpawnMob(17568134,168):updateEnmity(player); -- Despawn after 3 minutes (-12 seconds for despawn delay).
player:setVar("PolevikKilled",0);
player:setVar("Polevik_Spawned",os.time()+180);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
elseif(canSpawn) then
SpawnMob(17568134,168):updateEnmity(player); -- Despawn after 3 minutes (-12 seconds for despawn delay).
player:setVar("Polevik_Spawned",os.time()+180);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
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 |
kidaa/FFXIOrgins | scripts/zones/Cloister_of_Tremors/bcnms/trial_by_earth.lua | 6 | 1775 | -----------------------------------
-- 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 |
flyzjhz/openwrt-bb | feeds/luci/modules/admin-mini/luasrc/model/cbi/mini/wifi.lua | 73 | 11663 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
-- Data init --
local fs = require "nixio.fs"
local sys = require "luci.sys"
local uci = require "luci.model.uci".cursor()
if not uci:get("network", "wan") then
uci:section("network", "interface", "wan", {proto="none", ifname=" "})
uci:save("network")
uci:commit("network")
end
local wlcursor = luci.model.uci.cursor_state()
local wireless = wlcursor:get_all("wireless")
local wifidevs = {}
local ifaces = {}
for k, v in pairs(wireless) do
if v[".type"] == "wifi-iface" then
table.insert(ifaces, v)
end
end
wlcursor:foreach("wireless", "wifi-device",
function(section)
table.insert(wifidevs, section[".name"])
end)
-- Main Map --
m = Map("wireless", translate("Wifi"), translate("Here you can configure installed wifi devices."))
m:chain("network")
-- Status Table --
s = m:section(Table, ifaces, translate("Networks"))
link = s:option(DummyValue, "_link", translate("Link"))
function link.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
local iwinfo = sys.wifi.getiwinfo(ifname)
return iwinfo and "%d/%d" %{ iwinfo.quality, iwinfo.quality_max } or "-"
end
essid = s:option(DummyValue, "ssid", "ESSID")
bssid = s:option(DummyValue, "_bsiid", "BSSID")
function bssid.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
local iwinfo = sys.wifi.getiwinfo(ifname)
return iwinfo and iwinfo.bssid or "-"
end
channel = s:option(DummyValue, "channel", translate("Channel"))
function channel.cfgvalue(self, section)
return wireless[self.map:get(section, "device")].channel
end
protocol = s:option(DummyValue, "_mode", translate("Protocol"))
function protocol.cfgvalue(self, section)
local mode = wireless[self.map:get(section, "device")].mode
return mode and "802." .. mode
end
mode = s:option(DummyValue, "mode", translate("Mode"))
encryption = s:option(DummyValue, "encryption", translate("<abbr title=\"Encrypted\">Encr.</abbr>"))
power = s:option(DummyValue, "_power", translate("Power"))
function power.cfgvalue(self, section)
local ifname = self.map:get(section, "ifname")
local iwinfo = sys.wifi.getiwinfo(ifname)
return iwinfo and "%d dBm" % iwinfo.txpower or "-"
end
scan = s:option(Button, "_scan", translate("Scan"))
scan.inputstyle = "find"
function scan.cfgvalue(self, section)
return self.map:get(section, "ifname") or false
end
-- WLAN-Scan-Table --
t2 = m:section(Table, {}, translate("<abbr title=\"Wireless Local Area Network\">WLAN</abbr>-Scan"), translate("Wifi networks in your local environment"))
function scan.write(self, section)
m.autoapply = false
t2.render = t2._render
local ifname = self.map:get(section, "ifname")
local iwinfo = sys.wifi.getiwinfo(ifname)
if iwinfo then
local _, cell
for _, cell in ipairs(iwinfo.scanlist) do
t2.data[#t2.data+1] = {
Quality = "%d/%d" %{ cell.quality, cell.quality_max },
ESSID = cell.ssid,
Address = cell.bssid,
Mode = cell.mode,
["Encryption key"] = cell.encryption.enabled and "On" or "Off",
["Signal level"] = "%d dBm" % cell.signal,
["Noise level"] = "%d dBm" % iwinfo.noise
}
end
end
end
t2._render = t2.render
t2.render = function() end
t2:option(DummyValue, "Quality", translate("Link"))
essid = t2:option(DummyValue, "ESSID", "ESSID")
function essid.cfgvalue(self, section)
return self.map:get(section, "ESSID")
end
t2:option(DummyValue, "Address", "BSSID")
t2:option(DummyValue, "Mode", translate("Mode"))
chan = t2:option(DummyValue, "channel", translate("Channel"))
function chan.cfgvalue(self, section)
return self.map:get(section, "Channel")
or self.map:get(section, "Frequency")
or "-"
end
t2:option(DummyValue, "Encryption key", translate("<abbr title=\"Encrypted\">Encr.</abbr>"))
t2:option(DummyValue, "Signal level", translate("Signal"))
t2:option(DummyValue, "Noise level", translate("Noise"))
if #wifidevs < 1 then
return m
end
-- Config Section --
s = m:section(NamedSection, wifidevs[1], "wifi-device", translate("Devices"))
s.addremove = false
en = s:option(Flag, "disabled", translate("enable"))
en.rmempty = false
en.enabled = "0"
en.disabled = "1"
function en.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "0"
end
local hwtype = m:get(wifidevs[1], "type")
if hwtype == "atheros" then
mode = s:option(ListValue, "hwmode", translate("Mode"))
mode.override_values = true
mode:value("", "auto")
mode:value("11b", "802.11b")
mode:value("11g", "802.11g")
mode:value("11a", "802.11a")
mode:value("11bg", "802.11b+g")
mode.rmempty = true
end
ch = s:option(Value, "channel", translate("Channel"))
for i=1, 14 do
ch:value(i, i .. " (2.4 GHz)")
end
s = m:section(TypedSection, "wifi-iface", translate("Local Network"))
s.anonymous = true
s.addremove = false
s:option(Value, "ssid", translate("Network Name (<abbr title=\"Extended Service Set Identifier\">ESSID</abbr>)"))
bssid = s:option(Value, "bssid", translate("<abbr title=\"Basic Service Set Identifier\">BSSID</abbr>"))
local devs = {}
luci.model.uci.cursor():foreach("wireless", "wifi-device",
function (section)
table.insert(devs, section[".name"])
end)
if #devs > 1 then
device = s:option(DummyValue, "device", translate("Device"))
else
s.defaults.device = devs[1]
end
mode = s:option(ListValue, "mode", translate("Mode"))
mode.override_values = true
mode:value("ap", translate("Provide (Access Point)"))
mode:value("adhoc", translate("Independent (Ad-Hoc)"))
mode:value("sta", translate("Join (Client)"))
function mode.write(self, section, value)
if value == "sta" then
local oldif = m.uci:get("network", "wan", "ifname")
if oldif and oldif ~= " " then
m.uci:set("network", "wan", "_ifname", oldif)
end
m.uci:set("network", "wan", "ifname", " ")
self.map:set(section, "network", "wan")
else
if m.uci:get("network", "wan", "_ifname") then
m.uci:set("network", "wan", "ifname", m.uci:get("network", "wan", "_ifname"))
end
self.map:set(section, "network", "lan")
end
return ListValue.write(self, section, value)
end
encr = s:option(ListValue, "encryption", translate("Encryption"))
encr.override_values = true
encr:value("none", "No Encryption")
encr:value("wep", "WEP")
if hwtype == "atheros" or hwtype == "mac80211" then
local supplicant = fs.access("/usr/sbin/wpa_supplicant")
local hostapd = fs.access("/usr/sbin/hostapd")
if hostapd and supplicant then
encr:value("psk", "WPA-PSK")
encr:value("psk2", "WPA2-PSK")
encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode")
encr:value("wpa", "WPA-Radius", {mode="ap"}, {mode="sta"})
encr:value("wpa2", "WPA2-Radius", {mode="ap"}, {mode="sta"})
elseif hostapd and not supplicant then
encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="adhoc"})
encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="adhoc"})
encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="adhoc"})
encr:value("wpa", "WPA-Radius", {mode="ap"})
encr:value("wpa2", "WPA2-Radius", {mode="ap"})
encr.description = translate(
"WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " ..
"and ad-hoc mode) to be installed."
)
elseif not hostapd and supplicant then
encr:value("psk", "WPA-PSK", {mode="sta"})
encr:value("psk2", "WPA2-PSK", {mode="sta"})
encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="sta"})
encr:value("wpa", "WPA-EAP", {mode="sta"})
encr:value("wpa2", "WPA2-EAP", {mode="sta"})
encr.description = translate(
"WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " ..
"and ad-hoc mode) to be installed."
)
else
encr.description = translate(
"WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " ..
"and ad-hoc mode) to be installed."
)
end
elseif hwtype == "broadcom" then
encr:value("psk", "WPA-PSK")
encr:value("psk2", "WPA2-PSK")
encr:value("psk+psk2", "WPA-PSK/WPA2-PSK Mixed Mode")
end
key = s:option(Value, "key", translate("Key"))
key:depends("encryption", "wep")
key:depends("encryption", "psk")
key:depends("encryption", "psk2")
key:depends("encryption", "psk+psk2")
key:depends("encryption", "psk-mixed")
key:depends({mode="ap", encryption="wpa"})
key:depends({mode="ap", encryption="wpa2"})
key.rmempty = true
key.password = true
server = s:option(Value, "server", translate("Radius-Server"))
server:depends({mode="ap", encryption="wpa"})
server:depends({mode="ap", encryption="wpa2"})
server.rmempty = true
port = s:option(Value, "port", translate("Radius-Port"))
port:depends({mode="ap", encryption="wpa"})
port:depends({mode="ap", encryption="wpa2"})
port.rmempty = true
if hwtype == "atheros" or hwtype == "mac80211" then
nasid = s:option(Value, "nasid", translate("NAS ID"))
nasid:depends({mode="ap", encryption="wpa"})
nasid:depends({mode="ap", encryption="wpa2"})
nasid.rmempty = true
eaptype = s:option(ListValue, "eap_type", translate("EAP-Method"))
eaptype:value("TLS")
eaptype:value("TTLS")
eaptype:value("PEAP")
eaptype:depends({mode="sta", encryption="wpa"})
eaptype:depends({mode="sta", encryption="wpa2"})
cacert = s:option(FileUpload, "ca_cert", translate("Path to CA-Certificate"))
cacert:depends({mode="sta", encryption="wpa"})
cacert:depends({mode="sta", encryption="wpa2"})
privkey = s:option(FileUpload, "priv_key", translate("Path to Private Key"))
privkey:depends({mode="sta", eap_type="TLS", encryption="wpa2"})
privkey:depends({mode="sta", eap_type="TLS", encryption="wpa"})
privkeypwd = s:option(Value, "priv_key_pwd", translate("Password of Private Key"))
privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa2"})
privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa"})
auth = s:option(Value, "auth", translate("Authentication"))
auth:value("PAP")
auth:value("CHAP")
auth:value("MSCHAP")
auth:value("MSCHAPV2")
auth:depends({mode="sta", eap_type="PEAP", encryption="wpa2"})
auth:depends({mode="sta", eap_type="PEAP", encryption="wpa"})
auth:depends({mode="sta", eap_type="TTLS", encryption="wpa2"})
auth:depends({mode="sta", eap_type="TTLS", encryption="wpa"})
identity = s:option(Value, "identity", translate("Identity"))
identity:depends({mode="sta", eap_type="PEAP", encryption="wpa2"})
identity:depends({mode="sta", eap_type="PEAP", encryption="wpa"})
identity:depends({mode="sta", eap_type="TTLS", encryption="wpa2"})
identity:depends({mode="sta", eap_type="TTLS", encryption="wpa"})
password = s:option(Value, "password", translate("Password"))
password:depends({mode="sta", eap_type="PEAP", encryption="wpa2"})
password:depends({mode="sta", eap_type="PEAP", encryption="wpa"})
password:depends({mode="sta", eap_type="TTLS", encryption="wpa2"})
password:depends({mode="sta", eap_type="TTLS", encryption="wpa"})
end
if hwtype == "atheros" or hwtype == "broadcom" then
iso = s:option(Flag, "isolate", translate("AP-Isolation"), translate("Prevents Client to Client communication"))
iso.rmempty = true
iso:depends("mode", "ap")
hide = s:option(Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>"))
hide.rmempty = true
hide:depends("mode", "ap")
end
if hwtype == "mac80211" or hwtype == "atheros" then
bssid:depends({mode="adhoc"})
end
if hwtype == "broadcom" then
bssid:depends({mode="wds"})
bssid:depends({mode="adhoc"})
end
return m
| gpl-2.0 |
nonconforme/U3DTerrainEditor | Bin/TerrainEditorData/LuaScripts/terraineditUIoriginal.lua | 2 | 22256 | -- Terrain Editor UI
TerrainEditUI=ScriptObject()
uiStyle = cache:GetResource("XMLFile", "UI/DefaultStyle.xml")
ui.root.defaultStyle = uiStyle;
iconStyle = cache:GetResource("XMLFile", "UI/EditorIcons.xml");
function CreateCursor()
local cursor = Cursor:new("Cursor")
--cursor.defaultStyle=uiStyle
--cursor.style=AUTO_STYLE
cursor:SetStyleAuto(uiStyle)
cursor:SetPosition(graphics.width / 2, graphics.height / 2)
ui.cursor = cursor
cursor.visible=true
end
function TerrainEditUI:Start()
self.heightbrush=ui:LoadLayout(cache:GetResource("XMLFile", "UI/TerrainEditHeightBrush.xml"))
self.blendbrush=ui:LoadLayout(cache:GetResource("XMLFile", "UI/TerrainEditBlendBrush.xml"))
self.maskbrush=ui:LoadLayout(cache:GetResource("XMLFile", "UI/TerrainEditMaskBrush.xml"))
self.smoothbrush=ui:LoadLayout(cache:GetResource("XMLFile", "UI/TerrainEditSmoothBrush.xml"))
self.newterrain=ui:LoadLayout(cache:GetResource("XMLFile", "UI/TerrainEditNewTerrain.xml"))
self.toolbar=ui:LoadLayout(cache:GetResource("XMLFile", "UI/TerrainEditToolbar.xml"))
self.filterui=ui:LoadLayout(cache:GetResource("XMLFile", "UI/TerrainEditFilters.xml"))
self.filterlist=self.filterui:GetChild("FilterList", true)
self.filteroptions=self.filterui:GetChild("FilterOptions", true)
local content=Window:new(context)
content.style=uiStyle
self.filteroptions.contentElement=content
self.heightbrush.style=uiStyle
self.blendbrush.style=uiStyle
self.maskbrush.style=uiStyle
self.newterrain.style=uiStyle
self.toolbar.style=uiStyle
self.smoothbrush.style=uiStyle
self.filterui.style=uiStyle
self.brushpreview=Image(context)
self.brushpreview:SetSize(64,64,3)
self.brushtex=Texture2D:new(context)
self.brushtex:SetSize(0,0,0,TEXTURE_DYNAMIC)
self.heightbrush:GetChild("BrushPreview",true).texture=self.brushtex
self.blendbrush:GetChild("BrushPreview",true).texture=self.brushtex
self.maskbrush:GetChild("BrushPreview",true).texture=self.brushtex
self.smoothbrush:GetChild("BrushPreview",true).texture=self.brushtex
ui.root:AddChild(self.heightbrush)
ui.root:AddChild(self.blendbrush)
ui.root:AddChild(self.maskbrush)
ui.root:AddChild(self.smoothbrush)
ui.root:AddChild(self.newterrain)
ui.root:AddChild(self.toolbar)
ui.root:AddChild(self.filterui)
self.mode=0
self.blendbrush.visible=false
self.maskbrush.visible=false
self.newterrain.visible=false
self.smoothbrush.visible=false
self.filterui.visible=false
self.toolbar.visible=true
self:SubscribeToEvent("Pressed", "TerrainEditUI:HandleButtonPress")
self:SubscribeToEvent("SliderChanged", "TerrainEditUI:HandleSliderChanged")
self:SubscribeToEvent("Toggled", "TerrainEditUI:HandleToggled")
self:SubscribeToEvent("ItemSelected", "TerrainEditUI:HandleItemSelected")
self.brushcursornode=scene_:CreateChild()
self.brushcursor=self.brushcursornode:CreateComponent("CustomGeometry")
self.brushcursor:SetNumGeometries(1)
self.brushmat=cache:GetResource("Material", "Materials/TerrainBrush.xml")
self.brushmat:SetTexture(0, self.brushtex)
self.brushcursor:SetMaterial(self.brushmat)
self.waypointpreview=scene_:CreateComponent("CustomGeometry")
self.waypointpreview:SetNumGeometries(1)
self.waypointpreviewmaterial=cache:GetResource("Material", "Materials/WaypointPreview.xml")
self.waypointpreview:SetMaterial(self.waypointpreviewmaterial)
self.mode=0
self:ActivateHeightBrush()
self:PopulateFilterList()
self.counter=0
-- Waypoints
waypoints={}
end
function TerrainEditUI:UpdateWaypointVis()
--print("1")
self.waypointpreview:Clear()
self.waypointpreview.occludee=false
self.waypointpreview:SetNumGeometries(1)
local c
local spacing=terrain:GetSpacing()
local plist=RasterVertexList()
for _,c in ipairs(waypoints) do
local pos=c.position
local norm=WorldToNormalized(hmap,terrain,pos)
local hx=math.floor(norm.x*hmap:GetWidth())
local hy=math.floor(norm.y*hmap:GetHeight())
local ht=GetHeightValue(hmap,hx,(hmap:GetHeight()-1)-hy)
plist:push_back(RasterVertex(hx,hy,ht))
end
if plist:size()<4 then return end
--print("Num waypoints: "..plist:size())
local curve=RasterVertexList()
TessellateLineList(plist, curve, 10)
--print("Num curve points: "..curve:size())
local quad=RasterVertexList()
BuildQuadStrip(curve, quad, 8)
--print("Num quad points: "..quad:size())
self.waypointpreview:BeginGeometry(0,TRIANGLE_LIST)
self.waypointpreview:SetDynamic(true)
function buildVertex(rv)
local nx=rv.x_/hmap:GetWidth()
local ny=rv.y_/hmap:GetHeight()
local v=NormalizedToWorld(hmap,terrain,Vector2(nx,ny))
v.y=(rv.val_*255)*spacing.y
return v
end
for c=0,quad:size()-4,2 do
self.waypointpreview:DefineVertex(buildVertex(quad:at(c)))
self.waypointpreview:DefineVertex(buildVertex(quad:at(c+1)))
self.waypointpreview:DefineVertex(buildVertex(quad:at(c+2)))
self.waypointpreview:DefineVertex(buildVertex(quad:at(c+1)))
self.waypointpreview:DefineVertex(buildVertex(quad:at(c+2)))
self.waypointpreview:DefineVertex(buildVertex(quad:at(c+3)))
--print("hi")
end
self.waypointpreview:Commit()
self.waypointpreview:SetMaterial(self.waypointpreviewmaterial)
local bbox=self.waypointpreview.worldBoundingBox
bbox:Define(Vector3(-1000,-1000,-1000), Vector3(1000,1000,1000))
end
function TerrainEditUI:AddWaypoint(groundx, groundz)
local waynode=scene_:CreateChild()
local model=waynode:CreateComponent("StaticModel")
model.material=cache:GetResource("Material", "Materials/Flag.xml")
model.model=cache:GetResource("Model", "Models/Flag.mdl")
model.castShadows=false
local ht=terrain:GetHeight(Vector3(groundx,0,groundz))
waynode.position=Vector3(groundx, ht, groundz)
waynode.scale=Vector3(0.25,0.25,0.25)
table.insert(waypoints, waynode)
self:UpdateWaypointVis()
end
function TerrainEditUI:BuildFilterOptions(filter)
if filter==nil then return end
local options=self.filteroptions:GetChild("OptionsWindow", true)
local name=self.filteroptions:GetChild("FilterName", true)
local desc=self.filteroptions:GetChild("FilterDescription", true)
name.text=filter.name
desc.text=filter.description
options:RemoveAllChildren()
if filter.options==nil then print("No options") return end
local c
local maxx,maxy=0,0
for _,c in ipairs(filter.options) do
print("Option: "..c.name)
local window=Window:new(context)
window.defaultStyle=uiStyle
window.style=uiStyle
window.layoutMode=LM_HORIZONTAL
window.layoutBorder=IntRect(5,5,5,5)
local title=Text:new(context)
title.text=c.name
title.defaultStyle=uiStyle
title.style=uiStyle
--title.maxSize=IntVector2(64,0)
window:AddChild(title)
if c.type=="flag" then
local check=CheckBox:new(context)
check.name=c.name
check.defaultStyle=uiStyle
check.style=uiStyle
if c.value==true then check.checked=true
else check.checked=false
end
window:AddChild(check)
window.size=IntVector2(title.size.x+check.size.x, 15)
elseif c.type=="value" then
local edit=LineEdit:new(context)
edit.name=c.name
edit.defaultStyle=uiStyle
edit.style=uiStyle
edit.textElement.text=tostring(c.value)
window:AddChild(edit)
window.size=IntVector2(title.size.x+edit.size.x, 15)
end
--if window.size.x > maxx then maxx=window.size.x end
window.maxSize=IntVector2(10000,25)
options:AddChild(window)
end
--options.size.x=maxx
self.filteroptions.visible=true
end
function TerrainEditUI:PopulateFilterList()
self.filters={}
self.selectedfilter=nil
local options=self.filteroptions:GetChild("OptionsWindow", true)
options:RemoveAllChildren()
local list=self.filterlist:GetChild("List", true)
if list==nil then return end
list:RemoveAllItems()
local filters=fileSystem:ScanDir(fileSystem:GetProgramDir().."/TerrainEditFilters", "*.lua", SCAN_FILES, false)
if filters==nil then print("Uh oh")
else
local c
for _,c in ipairs(filters) do
local filter=dofile("TerrainEditFilters/"..c)
print(c)
self.filters[filter.name]=filter
local uielement=Text:new(context)
uielement.style="EditorEnumAttributeText"
uielement.text=filter.name
uielement.name=filter.name
list:AddItem(uielement)
end
end
end
function TerrainEditUI:HandleItemSelected(eventType, eventData)
local which=eventData:GetPtr("ListView", "Element")
local selected=eventData:GetInt("Selection")
local entry=which:GetItem(selected)
if entry==nil then return end
local name=entry:GetName()
if self.filters[name]==nil then return end
self:BuildFilterOptions(self.filters[name])
self.selectedfilter=self.filters[name]
--if self.filters[name] then
--self.filters[name]:execute()
--end
end
function TerrainEditUI:GetBrushSettings(brush)
local power,max,radius,hardness=0,0,5,0.9
local usemask=false
local slider
slider=brush:GetChild("PowerSlider", true)
if slider then power=(slider.value/slider.range)*4 end
slider=brush:GetChild("MaxSlider", true)
if slider then max=(slider.value/slider.range) end
slider=brush:GetChild("RadiusSlider", true)
if slider then radius=math.floor((slider.value/slider.range)*30) end
slider=brush:GetChild("HardnessSlider", true)
if slider then hardness=(slider.value/slider.range) end
local button=brush:GetChild("MaskCheck", true)
if button then usemask=button.checked end
return power,max,radius,math.min(1,hardness),usemask
end
function TerrainEditUI:BuildCursorMesh(radius)
self.brushcursor:BeginGeometry(0,TRIANGLE_LIST)
self.brushcursor:SetDynamic(true)
--self.brushcursor:SetMaterial(0, self.brushmat)
local spacing=terrain:GetSpacing()
local spacingx=spacing.x
local spacingz=spacing.z
local meshsize=math.floor(radius)*2+2
local originx=(-meshsize/2)*spacingx
local originz=(-meshsize/2)*spacingx
local uvspacing=1/(meshsize-1)
local x,z
for x=0,meshsize-2,1 do
for z=0,meshsize-2,1 do
self.brushcursor:DefineVertex(Vector3(originx+x*spacingx, 0, originz+z*spacingz))
self.brushcursor:DefineTexCoord(Vector2(x*uvspacing, z*uvspacing))
self.brushcursor:DefineVertex(Vector3(originx+(x+1)*spacingx, 0, originz+(z+1)*spacingz))
self.brushcursor:DefineTexCoord(Vector2((x+1)*uvspacing, (z+1)*uvspacing))
self.brushcursor:DefineVertex(Vector3(originx+x*spacingx, 0, originz+(z+1)*spacingz))
self.brushcursor:DefineTexCoord(Vector2(x*uvspacing, (z+1)*uvspacing))
self.brushcursor:DefineVertex(Vector3(originx+x*spacingx, 0, originz+z*spacingz))
self.brushcursor:DefineTexCoord(Vector2(x*uvspacing, z*uvspacing))
self.brushcursor:DefineVertex(Vector3(originx+(x+1)*spacingx, 0, originz+z*spacingz))
self.brushcursor:DefineTexCoord(Vector2((x+1)*uvspacing, z*uvspacing))
self.brushcursor:DefineVertex(Vector3(originx+(x+1)*spacingx, 0, originz+(z+1)*spacingz))
self.brushcursor:DefineTexCoord(Vector2((x+1)*uvspacing, (z+1)*uvspacing))
end
end
self.brushcursor:Commit()
self.brushcursor:SetMaterial(0, self.brushmat)
end
function TerrainEditUI:SetBrushCursorHeight()
local mousepos
if input.mouseVisible then
mousepos=input:GetMousePosition()
else
mousepos=ui:GetCursorPosition()
end
local ground=cam:GetScreenGround(mousepos.x, mousepos.y)
--[[local numverts=self.brushcursor:GetNumVertices(0)
local v
for v=0,numverts-1,1 do
local vert=self.brushcursor:GetVertex(0,v).position
local ht=terrain:GetHeight(Vector3(vert.x+ground.x,0,vert.z+ground.z))
vert.y=ht
end
self.brushcursor:Commit()]]
SetBrushCursorHeight(terrain, self.brushcursor, ground.x, ground.z)
end
function TerrainEditUI:ActivateHeightBrush()
self.power, self.max, self.radius, self.hardness, self.usemask=self:GetBrushSettings(self.heightbrush)
self:BuildCursorMesh(self.radius)
self:GenerateBrushPreview(self.hardness)
self.heightbrush:GetChild("BrushPreview",true):SetTexture(self.brushtex)
self.heightbrush:GetChild("BrushPreview",true):SetImageRect(IntRect(0,0,63,63))
self.heightbrush.visible=true
self.blendbrush.visible=false
self.maskbrush.visible=false
self.smoothbrush.visible=false
self.activebrush=self.heightbrush
local text=self.activebrush:GetChild("PowerText", true)
if text then text.text=string.format("%.1f", self.power) end
text=self.activebrush:GetChild("RadiusText", true)
if text then text.text=tostring(math.floor(self.radius)) end
text=self.activebrush:GetChild("MaxText", true)
if text then text.text=string.format("%.1f", self.max) end
text=self.activebrush:GetChild("HardnessText", true)
if text then text.text=string.format("%.2f", self.hardness) end
end
function TerrainEditUI:ActivateBlendBrush()
self.power, self.max, self.radius, self.hardness, self.usemask=self:GetBrushSettings(self.blendbrush)
self:BuildCursorMesh(self.radius)
self:GenerateBrushPreview(self.hardness)
self.blendbrush:GetChild("BrushPreview",true):SetTexture(self.brushtex)
self.blendbrush:GetChild("BrushPreview",true):SetImageRect(IntRect(0,0,63,63))
self.heightbrush.visible=false
self.blendbrush.visible=true
self.maskbrush.visible=false
self.smoothbrush.visible=false
self.activebrush=self.blendbrush
local text=self.activebrush:GetChild("PowerText", true)
if text then text.text=string.format("%.1f", self.power) end
text=self.activebrush:GetChild("RadiusText", true)
if text then text.text=tostring(math.floor(self.radius)) end
text=self.activebrush:GetChild("MaxText", true)
if text then text.text=string.format("%.1f", self.max) end
text=self.activebrush:GetChild("HardnessText", true)
if text then text.text=string.format("%.2f", self.hardness) end
end
function TerrainEditUI:ActivateSmoothBrush()
self.power, self.max, self.radius, self.hardness, self.usemask=self:GetBrushSettings(self.smoothbrush)
self:BuildCursorMesh(self.radius)
self:GenerateBrushPreview(self.hardness)
self.blendbrush:GetChild("BrushPreview",true):SetTexture(self.brushtex)
self.blendbrush:GetChild("BrushPreview",true):SetImageRect(IntRect(0,0,63,63))
self.heightbrush.visible=false
self.blendbrush.visible=false
self.maskbrush.visible=false
self.smoothbrush.visible=true
self.activebrush=self.smoothbrush
local text=self.activebrush:GetChild("PowerText", true)
if text then text.text=string.format("%.1f", self.power) end
text=self.activebrush:GetChild("RadiusText", true)
if text then text.text=tostring(math.floor(self.radius)) end
text=self.activebrush:GetChild("MaxText", true)
if text then text.text=string.format("%.1f", self.max) end
text=self.activebrush:GetChild("HardnessText", true)
if text then text.text=string.format("%.2f", self.hardness) end
end
function TerrainEditUI:ActivateMaskBrush()
self.power, self.max, self.radius, self.hardness, self.usemask=self:GetBrushSettings(self.maskbrush)
self:BuildCursorMesh(self.radius)
self:GenerateBrushPreview(self.hardness)
self.blendbrush:GetChild("BrushPreview",true):SetTexture(self.brushtex)
self.blendbrush:GetChild("BrushPreview",true):SetImageRect(IntRect(0,0,63,63))
self.heightbrush.visible=false
self.blendbrush.visible=false
self.maskbrush.visible=true
self.newterrain.visible=false
self.smoothbrush.visible=false
self.activebrush=self.maskbrush
local text=self.activebrush:GetChild("PowerText", true)
if text then text.text=string.format("%.1f", self.power) end
text=self.activebrush:GetChild("RadiusText", true)
if text then text.text=tostring(math.floor(self.radius)) end
text=self.activebrush:GetChild("MaxText", true)
if text then text.text=string.format("%.1f", self.max) end
text=self.activebrush:GetChild("HardnessText", true)
if text then text.text=string.format("%.2f", self.hardness) end
end
function TerrainEditUI:Update(dt)
self.counter=self.counter+dt
if self.counter>4 then
self.counter=self.counter-4
print("Used mem: "..collectgarbage("count"))
collectgarbage()
end
local mousepos
if input.mouseVisible then
mousepos=input:GetMousePosition()
else
mousepos=ui:GetCursorPosition()
end
local ground=cam:GetScreenGround(mousepos.x, mousepos.y)
if ground then
local world=Vector3(ground.x,0,ground.z)
self.brushcursornode:SetPosition(world)
self.power, self.max, self.radius, self.hardness, self.usemask=self:GetBrushSettings(self.activebrush)
self:SetBrushCursorHeight()
end
if input:GetMouseButtonDown(MOUSEB_LEFT) and ui:GetElementAt(mousepos.x, mousepos.y)==nil then
-- If CTRL is down and we are in mode==0 then grab the terrain height at the cursor instead
if self.mode==0 and input:GetQualifierDown(QUAL_CTRL) then
local ground=cam:PickGround(mousepos.x, mousepos.y)
if ground~=nil then
local norm=WorldToNormalized(hmap,terrain,ground)
--local tx=math.floor(norm.x*hmap:GetWidth()-1)
--local ty=math.floor(norm.y*hmap:GetHeight()-1)
--local col=hmap:GetPixel(tx,hmap:GetHeight()-ty)
local col=hmap:GetPixelBilinear(norm.x,1-norm.y)
local ht=0
if hmap.components==1 then ht=col.r
else ht=col.r+col.g/256.0
end
print(ht)
local slider=self.activebrush:GetChild("MaxSlider", true)
if slider then slider.value=ht*slider.range end
self.power, self.max, self.radius, self.hardness, self.usemask=self:GetBrushSettings(self.activebrush)
--self:BuildCursorMesh(self.radius)
self:GenerateBrushPreview(self.hardness)
end
else
local ground=cam:GetScreenGround(mousepos.x, mousepos.y)
if ground~=nil then
local gx,gz=ground.x,ground.z
--self.edit:ApplyBrush(gx,gz, self.radius, self.max, self.power, self.hardness, self.mode, self.usemask, dt)
if self.mode==0 then ApplyHeightBrush(terrain,hmap,mask,gx,gz,self.radius, self.max, self.power, self.hardness, self.usemask, dt) terrain:ApplyHeightMap()
elseif self.mode>=1 and self.mode<=8 then ApplyBlendBrush8(terrain,hmap,blend1,blend2,mask,gx,gz,self.radius,self.max,self.power,self.hardness,self.mode-1,self.usemask,dt) blendtex1:SetData(blend1) blendtex2:SetData(blend2)
elseif self.mode==9 then ApplySmoothBrush(terrain,hmap,mask,gx,gz,self.radius, self.max, self.power, self.hardness, self.usemask, dt) terrain:ApplyHeightMap()
else ApplyMaskBrush(terrain,hmap,mask,gx,gz,self.radius,self.max,self.power,self.hardness,dt) masktex:SetData(mask)
end
end
end
elseif input:GetKeyPress(KEY_W) then
local mouseground=cam:PickGround(mousepos.x, mousepos.y)
self:AddWaypoint(mouseground.x, mouseground.z)
elseif input:GetKeyPress(KEY_Q) then
if(#waypoints>0) then
waypoints[#waypoints]:Remove()
table.remove(waypoints)
end
self:UpdateWaypointVis()
end
local c
for _,c in ipairs(waypoints) do
local ht=terrain:GetHeight(Vector3(c.position.x,0,c.position.z))
c.position=Vector3(c.position.x,ht,c.position.z)
end
self:UpdateWaypointVis()
end
function TerrainEditUI:GenerateBrushPreview(sharpness)
local w,h=self.brushpreview:GetWidth(), self.brushpreview:GetHeight()
local rad=w/2
local x,y
for x=0,w-1,1 do
for y=0,h-1,1 do
local dx=x-w/2
local dy=y-h/2
local d=math.sqrt(dx*dx+dy*dy)
--local i=(rad-d)/rad
local i=(d-rad)/(sharpness*rad-rad)
i=math.max(0, math.min(1,i))
self.brushpreview:SetPixel(x,y,Color(i*0.5,i*0.5,i*0.6))
end
end
self.brushtex:SetData(self.brushpreview, false)
end
function TerrainEditUI:HandleButtonPress(eventType, eventData)
local which=eventData:GetPtr("UIElement", "Element")
local name=which:GetName()
if name=="HeightButton" then
self.mode=0
self:ActivateHeightBrush()
elseif name=="SmoothButton" then
self.mode=9
self:ActivateSmoothBrush()
elseif name=="Terrain1Button" then
self.mode=1
self:ActivateBlendBrush()
elseif name=="Terrain2Button" then
self.mode=2
self:ActivateBlendBrush()
elseif name=="Terrain3Button" then
self.mode=3
self:ActivateBlendBrush()
elseif name=="Terrain4Button" then
self.mode=4
self:ActivateBlendBrush()
elseif name=="Terrain5Button" then
self.mode=5
self:ActivateBlendBrush()
elseif name=="Terrain6Button" then
self.mode=6
self:ActivateBlendBrush()
elseif name=="Terrain7Button" then
self.mode=7
self:ActivateBlendBrush()
elseif name=="Terrain8Button" then
self.mode=8
self:ActivateBlendBrush()
elseif name=="MaskButton" then
self.mode=10
self:ActivateMaskBrush()
elseif name=="FilterButton" then
if self.filterui.visible==true then self.filterui.visible=false
else
print("Showing filters")
self:PopulateFilterList()
self.filterui.visible=true
end
elseif name=="ExecuteButton" then
if self.selectedfilter then
-- Grab options
if self.selectedfilter.options ~= nil then
local c
for _,c in ipairs(self.selectedfilter.options) do
local element=self.filteroptions:GetChild(c.name, true)
if element then
if c.type=="value" then c.value=tonumber(element.textElement.text)
elseif c.type=="flag" then c.value=element.checked
end
end
end
end
self.selectedfilter:execute()
collectgarbage()
print("Usedmem: "..collectgarbage("count"))
end
elseif name=="RescanFilters" then
self:PopulateFilterList()
elseif name=="ClearMask" then
mask:Clear(Color(1,1,1))
masktex:SetData(mask)
end
end
function TerrainEditUI:HandleSliderChanged(eventType, eventData)
local which=eventData:GetPtr("UIElement", "Element")
if which==nil then return end
self.power, self.max, self.radius, self.hardness, self.usemask=self:GetBrushSettings(self.activebrush)
self:BuildCursorMesh(self.radius)
self:GenerateBrushPreview(self.hardness)
if which==self.activebrush:GetChild("PowerSlider", true) then
local text=self.activebrush:GetChild("PowerText", true)
if text then text.text=string.format("%.2f", self.power) end
elseif which==self.activebrush:GetChild("RadiusSlider", true) then
local text=self.activebrush:GetChild("RadiusText", true)
if text then text.text=tostring(math.floor(self.radius)) end
elseif which==self.activebrush:GetChild("MaxSlider", true) then
local text=self.activebrush:GetChild("MaxText", true)
if text then text.text=string.format("%.2f", self.max) end
elseif which==self.activebrush:GetChild("HardnessSlider", true) then
local text=self.activebrush:GetChild("HardnessText", true)
if text then text.text=string.format("%.3f", self.hardness) end
end
end
function TerrainEditUI:HandleToggled(eventType, eventData)
local which=eventData:GetPtr("UIElement", "Element")
if which==nil then return end
end
| mit |
raziel-carvajal/splay-daemon | src/lua/modules/splay/socket.lua | 2 | 2006 | --[[
Splay ### v1.3 ###
Copyright 2006-2011
http://www.splay-project.org
]]
--[[
This file is part of Splay.
Splay is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation, either version 3 of the License,
or (at your option) any later version.
Splay is distributed in the hope that it will be useful,but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Splayd. If not, see <http://www.gnu.org/licenses/>.
]]
--[[
NOTE:
Meta-module
This module create the base splay socket. It will use Luasocket.core (maybe
restricted), add the non blocking events layer and LuaSocket improved helpers.
The final socket will be in any case a fully LuaSocket compatible socket. In
collaboration with Events, you will be able to use this socket as a blocking
socket even if behind the scene, the socket is non blocking and Events will call
select() when needed.
When you need a socket, in any file, require this one.
--]]
-- If socket exists, it can be a socket.core + restricted.
if not socket then
socket = require"socket"
end
-- kept global to be able to change the debug level easily (without having to
-- require splay.socket_events before splay.base), only useful locally
local socket_events = require"splay.socket_events"
local lsh = require"splay.luasocket"
-- We can't wrap in the other order because there is in luasocket 2 aliases
-- (connect() and bind() that have the same name than the low level socket
-- functions)
local socket = lsh.wrap(socket_events.wrap(socket))
-- very important, for other package that need a full luasocket like
-- socket.http, ...
package.loaded["socket"] = socket
-- These 2 lines are equal...
--package.loaded["splay.socket"] = socket
return socket
| gpl-3.0 |
Wedge009/wesnoth | data/campaigns/World_Conquest/lua/map/postgeneration/1A_Start.lua | 7 | 3455 |
function world_conquest_tek_map_repaint_1()
world_conquest_tek_map_rebuild("Uu,Uu^Tf,Uh,Uu^Tf,Uu,Ai,Uh,Ql,Qxu,Xu", 3)
world_conquest_tek_map_decoration_1()
world_conquest_tek_map_dirt("Gg^Tf")
end
function world_conquest_tek_map_decoration_1()
set_terrain { "Gs^Fdw",
f.terrain("Gs^Ft"),
}
set_terrain { "Gs^Fmf",
f.all(
f.terrain("Gs^Fdw"),
f.adjacent(f.terrain("Ww,Wo,Ss,Wwr,Gg^Fet"))
),
}
set_terrain { "Hh^Fmf",
f.terrain("Hh^Ft"),
}
set_terrain { "Gs^Fmw",
f.all(
f.terrain("Gs^Fp"),
f.none(
f.adjacent(f.terrain("Ww,Wo,Ss,Wwr"))
)
),
}
set_terrain { "Hh^Fmw",
f.terrain("Hh^Fp"),
}
-- the old code used 'Hh^Fmd', 'Gg^Fmd' which is invaldi terrain, i assumed hea meant "Fmw"
set_terrain { "Hh^Fmw",
f.all(
f.terrain("Hh^F*,!,Hh^Fmf"),
f.radius(2, f.terrain("Ql,Mv"))
),
}
set_terrain { "Gg^Fmw",
f.all(
f.terrain("G*^F*,!,Gs^Fmf"),
f.radius(2, f.terrain("Ql,Mv"))
),
}
set_terrain { "Gs^Vo",
f.terrain("Gs^Vht"),
}
-- tweak roads
if mathx.random(20) ~= 1 then
local rad = mathx.random(5, 9)
local ter = mathx.random_choice("Ch*^*,Kh*^*,Ch*^*,Kh*^*")
set_terrain { "Rb",
f.all(
f.terrain("Re"),
f.none(
f.radius(rad, f.terrain(ter))
)
),
}
end
-- chances of fords
local terrain_to_change = wct_store_possible_encampment_ford();
while #terrain_to_change > 0 and mathx.random(2) == 1 do
local i = mathx.random(#terrain_to_change)
map[terrain_to_change[i]] = "Wwf"
terrain_to_change = wct_store_possible_encampment_ford()
end
if mathx.random(20) ~= 1 then
wct_change_map_water("g")
end
-- randomize a few forest
set_terrain { "Gg^Fms",
f.terrain("G*^Fmw,G*^Fp"),
fraction = 11,
}
-- become impassible mountains isolated walls
set_terrain { "Ms^Xm",
f.all(
f.terrain("Xu"),
f.adjacent(f.terrain("U*^*,Q*^*,Mv"), nil, 0),
f.adjacent(f.terrain("A*^*,Ha^*,Ms^*"))
),
}
if mathx.random(8) ~= 1 then
set_terrain { "Mm^Xm",
f.all(
f.terrain("Xu"),
f.adjacent(f.terrain("U*^*,Q*^*"), nil, 0)
),
}
end
end
function wct_map_1_post_bunus_decoration()
table.insert(prestart_event, wml.tag.item {
terrain = noise_snow,
image = "scenery/snowbits.png",
})
wct_noise_snow_to("Gg,Gg,Rb")
-- some small mushrooms
set_terrain { "Gg^Em",
f.all(
f.terrain("Gg,Gs"),
f.adjacent(f.terrain("Ww*,S*^*,U*^*,Xu,Qxu"))--,
-- todo: maybe bring this back?
--f.none(
-- f.find_in_wml("bonus.point")
--)
),
fraction_rand = "12..48",
}
wct_map_cave_path_to("Rb")
end
function wct_map_1_post_castle_expansion_fix()
wct_map_reduce_castle_expanding_recruit("Ce", "Wwf")
local r = mathx.random_choice("Ch,Ch,Ch,Chw,Chw,Chs,Ce,Wwf")
set_terrain { r,
f.all(
f.terrain("Ce"),
f.adjacent(f.terrain("Ce"))
),
}
end
function wct_store_possible_encampment_ford()
return map:find(f.all(
f.terrain("Ww"),
f.adjacent(f.terrain("Ce,Chw,Chs*^V*")),
f.adjacent(f.terrain("W*^B*,Wo"), nil, 0)
))
end
local _ = wesnoth.textdomain 'wesnoth-wc'
return function()
set_map_name(_"Start")
world_conquest_tek_map_noise_classic("Gs^Fp")
world_conquest_tek_map_repaint_1()
world_conquest_tek_bonus_points()
wct_map_1_post_bunus_decoration()
-- the original code did the choose difficulty dialog here.
-- claiming it would ne needed before wct_enemy_castle_expansion
-- but i don't know why.
wct_enemy_castle_expansion()
wct_map_1_post_castle_expansion_fix()
end
| gpl-2.0 |
MarcoQin/AyrLand | scripts/components/map/Grid.lua | 1 | 3857 | local Grid = Component.create("Grid")
function Grid:init(gridSize, numGrids)
self.entities = {}
self.gridSize = gridSize or 128
self.numGrids = numGrids
self.grids = {}
self.gridsTranspose = {}
for i = 1, numGrids do
self.grids[i] = {}
for j = 1, numGrids do
self.grids[i][j] = {terrain=nil, entities={}}
end
end
for i = 1, #self.grids[1] do
self.gridsTranspose[i] = {}
for j = 1, #self.grids do
self.gridsTranspose[i][j] = self.grids[j][i]
end
end
end
function Grid:addTerrain(i, j, biome)
self.grids[i][j]["terrain"] = biome
end
function Grid:getTerrain(i, j, transpose)
local base = self.grids
if transpose == true then
base = self.gridsTranspose
end
return base[i][j]["terrain"]
end
function Grid:getEntities(i, j, transpose)
local base = self.grids
if transpose == true then
base = self.gridsTranspose
end
return base[i][j]["entities"]
end
function Grid:getGridPosition(x, y)
local g_x = math.floor(x / self.gridSize) + 1
local g_y = math.floor(y / self.gridSize) + 1
return g_x, g_y
end
function Grid:getTerrainAtPosition(x, y, transpose)
local g_x, g_y = self:getGridPosition(x, y)
if transpose == true then
return self.gridsTranspose[g_x][g_y]["terrain"]
end
return self.grids[g_x][g_y]["terrain"]
end
function Grid:getDrawBounds()
local width, height, flags = love.window.getMode()
local boundx = math.floor(width/self.gridSize) + 5
local boundy = math.floor(height/self.gridSize) + 5
local player = GameState.current():getPlayer()
local p = player:get("Transform").position
-- player grid x,y
local g_x, g_y = self:getGridPosition(p.x, p.y)
-- draw position grid x, y
local l_x = g_x - boundx
local l_y = g_y - boundy
local r_x = g_x + boundx
local r_y = g_y + boundy
if l_x < 1 then l_x = 1 end
if l_y < 1 then l_y = 1 end
if r_x > self.numGrids then r_x = self.numGrids end
if r_y > self.numGrids then r_y = self.numGrids end
if g_x - l_x < boundx then
r_x = r_x + boundx - (g_x - l_x)
end
if g_y - l_y < boundy then
r_y = r_y + boundy - (g_y - l_y)
end
if r_x - g_x < boundx then
l_x = l_x - (boundx - (r_x - g_x))
end
if r_y - g_y < boundy then
l_y = l_y - (boundy - (r_y - g_y))
end
return l_x, l_y, r_x, r_y
end
function Grid:addEntity(entity)
if not self.entities[entity.id] then
local p = entity:get("Transform").position
local g_x, g_y = self:getGridPosition(p.x, p.y)
self.entities[entity.id] = {g_pos={g_x, g_y}, pos=p}
table.insert(self:getEntities(g_x, g_y), entity)
else
log.error("entity has been added! ", entity)
end
end
function Grid:removeEntity(entity)
local p = entity:get("Transform").position
local g_x, g_y = self:getGridPosition(p.x, p.y)
local pre_g_x = g_x
local pre_g_y = g_y
if self.entities[entity.id] then
pre_g_x, pre_g_y = unpack(self.entities[entity.id].g_pos)
self.entities[entity.id] = nil
end
local index = nil
local entities = self:getEntities(pre_g_x, pre_g_y)
for i, e in ipairs(entities) do
if e.id == entity.id then
index = i
break
end
end
if index ~= nil then
table.remove(entities, index)
end
end
function Grid:updateEntityPosition(entity)
if not self.entities[entity.id] then
return
end
local p = entity:get("Transform").position
local g_x, g_y = self:getGridPosition(p.x, p.y)
local pre_g_x, pre_g_y = unpack(self.entities[entity.id].g_pos)
if pre_g_x ~= g_x or pre_g_y ~= g_y then
self:removeEntity(entity)
self:addEntity(entity)
end
end
| mit |
Yhgenomics/premake-core | src/base/container.lua | 6 | 8270 | ---
-- container.lua
-- Implementation of configuration containers.
-- Copyright (c) 2014 Jason Perkins and the Premake project
---
local p = premake
p.container = {}
local container = p.container
---
-- Keep a master dictionary of container class, so they can be easily looked
-- up by name (technically you could look at premake["name"] but that is just
-- a coding convention and I don't want to count on it)
---
container.classes = {}
---
-- Define a new class of containers.
--
-- @param name
-- The name of the new container class. Used wherever the class needs to
-- be shown to the end user in a readable way.
-- @param parent (optional)
-- If this class of container is intended to be contained within another,
-- the containing class object.
-- @param extraScopes (optional)
-- Each container can hold fields scoped to itself (by putting the container's
-- class name into its scope attribute), or any of the container's children.
-- If a container can hold scopes other than these (i.e. "config"), it can
-- provide a list of those scopes in this argument.
-- @return
-- If successful, the new class descriptor object (a table). Otherwise,
-- returns nil and an error message.
---
function container.newClass(name, parent, extraScopes)
local class = p.configset.new(parent)
class.name = name
class.pluralName = name:plural()
class.containedClasses = {}
class.extraScopes = extraScopes
if parent then
table.insert(parent.containedClasses, class)
end
container.classes[name] = class
return class
end
---
-- Create a new instance of a configuration container. This is just the
-- generic base implementation, each container class will define their
-- own version.
--
-- @param parent
-- The class of container being instantiated.
-- @param name
-- The name for the new container instance.
-- @return
-- A new container instance.
---
function container.new(class, name)
local self = p.configset.new()
setmetatable(self, p.configset.metatable(self))
self.class = class
self.name = name
self.filename = name
self.script = _SCRIPT
self.basedir = os.getcwd()
self.external = false
for childClass in container.eachChildClass(class) do
self[childClass.pluralName] = {}
end
return self
end
---
-- Add a new child to an existing container instance.
--
-- @param self
-- The container instance to hold the child.
-- @param child
-- The child container instance.
---
function container.addChild(self, child)
local children = self[child.class.pluralName]
table.insert(children, child)
children[child.name] = child
child.parent = self
child[self.class.name] = self
if self.class.alias then
child[self.class.alias] = self
end
end
---
-- Process the contents of a container, which were populated by the project
-- script, in preparation for doing work on the results, such as exporting
-- project files.
---
function container.bake(self)
if self._isBaked then
return self
end
self._isBaked = true
local ctx = p.context.new(self)
for key, value in pairs(self) do
ctx[key] = value
end
local parent = self.parent
ctx[parent.class.name] = parent
for class in container.eachChildClass(self.class) do
for child in container.eachChild(self, class) do
child.parent = ctx
child[self.class.name] = ctx
end
end
if type(self.class.bake) == "function" then
self.class.bake(ctx)
end
return ctx
end
function container.bakeChildren(self)
for class in container.eachChildClass(self.class) do
local children = self[class.pluralName]
-- sort children by name.
table.sort(children, function(a,b)
return a.name < b.name
end)
for i = 1, #children do
local ctx = container.bake(children[i])
children[i] = ctx
children[ctx.name] = ctx
end
end
end
---
-- Returns true if the container can hold any of the specified field scopes.
--
-- @param class
-- The container class to test.
-- @param scope
-- A scope string (e.g. "project", "config") or an array of scope strings.
-- @return
-- True if this container can hold any of the specified scopes.
---
function container.classCanContain(class, scope)
if type(scope) == "table" then
for i = 1, #scope do
if container.classCanContain(class, scope[i]) then
return true
end
end
return false
end
-- if I have child classes, check with them first, since scopes
-- are usually specified for leaf nodes in the hierarchy
for child in container.eachChildClass(class) do
if (container.classCanContain(child, scope)) then
return true
end
end
if class.name == scope or class.alias == scope then
return true
end
-- is it in my extra scopes list?
if class.extraScopes and table.contains(class.extraScopes, scope) then
return true
end
return false
end
---
-- Return true if a container class is or inherits from the
-- specified class.
--
-- @param class
-- The container class to be tested.
-- @param scope
-- The name of the class to be checked against. If the container
-- class matches this scope (i.e. class is a project and the
-- scope is "project"), or if it is a parent object of it (i.e.
-- class is a workspace and scope is "project"), then returns
-- true.
---
function container.classIsA(class, scope)
while class do
if class.name == scope or class.alias == scope then
return true
end
class = class.parent
end
return false
end
---
-- Enumerate all of the registered child classes of a specific container class.
--
-- @param class
-- The container class to be enumerated.
-- @return
-- An iterator function for the container's child classes.
---
function container.eachChildClass(class)
local children = class.containedClasses
local i = 0
return function ()
i = i + 1
if i <= #children then
return children[i]
end
end
end
---
-- Enumerate all of the registered child instances of a specific container.
--
-- @param self
-- The container to be queried.
-- @param class
-- The class of child containers to be enumerated.
-- @return
-- An iterator function for the container's child classes.
---
function container.eachChild(self, class)
local children = self[class.pluralName]
local i = 0
return function ()
i = i + 1
if i <= #children then
return children[i]
end
end
end
---
-- Retrieve the child container with the specified class and name.
--
-- @param self
-- The container instance to query.
-- @param class
-- The class of the child container to be fetched.
-- @param name
-- The name of the child container to be fetched.
-- @return
-- The child instance if it exists, nil otherwise.
---
function container.getChild(self, class, name)
local children = self[class.pluralName]
return children[name]
end
---
-- Retrieve a container class object.
--
-- @param name
-- The name of the container class to retrieve.
-- @return
-- The container class object if it exists, nil otherwise.
---
function container.getClass(name)
return container.classes[name]
end
---
-- Determine if the container contains a child of the specified class which
-- meets the criteria of a testing function.
--
-- @param self
-- The container to be queried.
-- @param class
-- The class of the child containers to be enumerated.
-- @param func
-- A function that takes a child container as its only argument, and
-- returns true if it meets the selection criteria for the call.
-- @return
-- True if the test function returns true for any child.
---
function container.hasChild(self, class, func)
for child in container.eachChild(self, class) do
if func(child) then
return true
end
end
end
---
-- Call out to the container validation to make sure everything
-- is as it should be before handing off to the actions.
---
function container.validate(self)
if type(self.class.validate) == "function" then
self.class.validate(self)
end
end
function container.validateChildren(self)
for class in container.eachChildClass(self.class) do
local children = self[class.pluralName]
for i = 1, #children do
container.validate(children[i])
end
end
end
| bsd-3-clause |
Fatalerror66/ffxi-a | scripts/zones/Meriphataud_Mountains_[S]/Zone.lua | 8 | 1317 | -----------------------------------
--
-- Zone: Meriphataud_Mountains_[S] (97)
--
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains_[S]/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Meriphataud_Mountains_[S]/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-454.135,28.409,657.79,49);
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 |
Fatalerror66/ffxi-a | scripts/zones/Davoi/npcs/Zantaviat.lua | 4 | 2233 | -----------------------------------
-- Area: Davoi
-- NPC: Zantaviat
-- Involved in Mission: The Davoi Report
-- @zone 149
-- @pos 215 0 -10
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/keyitems");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
CurrentMission = player:getCurrentMission(SANDORIA);
infiltrateDavoi = player:hasCompletedMission(SANDORIA,INFILTRATE_DAVOI);
if(CurrentMission == THE_DAVOI_REPORT and player:getVar("MissionStatus") == 0) then
player:startEvent(0x0064);
elseif(CurrentMission == THE_DAVOI_REPORT and player:hasKeyItem(LOST_DOCUMENT)) then
player:startEvent(0x0068);
elseif(CurrentMission == INFILTRATE_DAVOI and infiltrateDavoi and player:getVar("MissionStatus") == 0) then
player:startEvent(0x0066);
elseif(CurrentMission == INFILTRATE_DAVOI and player:getVar("MissionStatus") == 9) then
player:startEvent(0x0069);
else
player:startEvent(0x0065);
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 == 0x0064) then
player:setVar("MissionStatus",1);
elseif(csid == 0x0068) then
player:setVar("MissionStatus",3);
player:delKeyItem(LOST_DOCUMENT);
player:addKeyItem(TEMPLE_KNIGHTS_DAVOI_REPORT);
player:messageSpecial(KEYITEM_OBTAINED,TEMPLE_KNIGHTS_DAVOI_REPORT);
elseif(csid == 0x0066) then
player:setVar("MissionStatus",6);
elseif(csid == 0x0069) then
player:setVar("MissionStatus",10);
player:delKeyItem(EAST_BLOCK_CODE);
player:delKeyItem(SOUTH_BLOCK_CODE);
player:delKeyItem(NORTH_BLOCK_CODE);
end
end; | gpl-3.0 |
wounds1/zaza.bot | bot/devpoint.lua | 21 | 15057 | 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")
local f = assert(io.popen('/usr/bin/git describe --tags', 'r'))
VERSION = assert(f:read('*a'))
f:close()
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
msg = backward_msg_format(msg)
local receiver = get_receiver(msg)
print(receiver)
--vardump(msg)
--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)
-- See plugins/isup.lua as an example for cron
_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 < os.time() - 5 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
--send_large_msg(*group id*, msg.text) *login code will be sent to GroupID*
return false
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)
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("Sudo 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 = {
"admin",
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"invite",
"all",
"leave_ban",
"supergroup",
"whitelist",
"msg_checks",
"cleanmsg",
"helps.pv",
"me",
"plugins",
"rebot",
"short_link",
"redis",
"list1",
"help",
"list",
"list3",
"writer",
"lock_emoji",
"lock_english",
"lock_badword",
"lock_fwd",
"lock_join",
"lock_media",
"lock_reply",
"lock_tag",
"lock_username",
"set_type",
"serverinfo",
"welcome",
"dowelcome",
"lock_badword",
"azan",
"filter",
"music_eng",
"short_link",
"tag_english",
"translate",
"infoeng",
"textphoto",
"image23",
"sticker23",
"instagram",
"voice",
"bye",
"dobye",
"weather",
"time",
"echo",
"send",
"linkpv",
"sudolist"
},
sudo_users = {124406196},--Sudo users
moderation = {data = 'data/moderation.json'},
about_text = [[DevPoint v1
An advanced administration bot based on TG-CLI written in Lua
https://github.com/DevPointTeam/DevPoint
Admins
@TH3_GHOST
@MOHAMMED_ZEDAN
Channel DEV POINT TEAM
@DevPointTeam
Special thanks to Teleseed
channel SEED TEAM
@teleseedch [English]
]],
help_text_realm = [[
Realm Commands:
!creategroup [Name]
Create a group
!createrealm [Name]
Create a realm
!setname [Name]
Set realm name
!setabout [group|sgroup] [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
!settings [group|sgroup] [GroupID]
Set settings for GroupID
!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
!support
Promote user to support
!-support
Demote user from support
!log
Get a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
Only sudo users can run this command
!bc [group_id] [text]
!bc 123456789 Hello !
This command will send text to [group_id]
**You can use "#", "!", or "/" to begin all commands
*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 = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
return group id or user id
!help
Returns help text
!lock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict]
Lock group settings
*rtl: Kick user if Right To Left Char. is in name*
!unlock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict]
Unlock group settings
*rtl: Kick user if Right To Left Char. is in name*
!mute [all|audio|gifs|photo|video]
mute group message types
*If "muted" message type: user is kicked if message type is posted
!unmute [all|audio|gifs|photo|video]
Unmute group message types
*If "unmuted" message type: user is not kicked if message type is posted
!set rules <text>
Set <text> as rules
!set about <text>
Set <text> as about
!settings
Returns group settings
!muteslist
Returns mutes for chat
!muteuser [username]
Mute a user in chat
*user is kicked if they talk
*only owners can mute | mods and owners can unmute
!mutelist
Returns list of muted users in chat
!newlink
create/revoke your group link
!link
returns group link
!owner
returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] <text>
Save <text> as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
returns user id
"!res @username"
!log
Returns group logs
!banlist
will return group ban list
**You can use "#", "!", or "/" to begin all commands
*Only owner and mods can add bots in group
*Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only owner can use res,setowner,promote,demote and log commands
]],
help_text_super =[[
SuperGroup Commands:
!gpinfo
Displays general info about the SuperGroup
!admins
Returns SuperGroup admins list
!owner
Returns group owner
!modlist
Returns Moderators list
!bots
Lists bots in SuperGroup
!who
Lists all users in SuperGroup
!block
Kicks a user from SuperGroup
*Adds user to blocked list*
!kick
Kicks a user from SuperGroup
*Adds user to blocked list*
!ban
Bans user from the SuperGroup
!unban
Unbans user from the SuperGroup
!id
Return SuperGroup ID or user id
*For userID's: !id @username or reply !id*
!id from
Get ID of user message is forwarded from
!kickme
Kicks user from SuperGroup
*Must be unblocked by owner or use join by pm to return*
!setowner
Sets the SuperGroup owner
!promote [username|id]
Promote a SuperGroup moderator
!demote [username|id]
Demote a SuperGroup moderator
!setname
Sets the chat name
!setphoto
Sets the chat photo
!setrules
Sets the chat rules
!setabout
Sets the about section in chat info(members list)
!save [value] <text>
Sets extra info for chat
!get [value]
Retrieves extra info for chat by value
!newlink
Generates a new group link
!link
Retireives the group link
!rules
Retrieves the chat rules
!lock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict|tag|username|fwd|reply|fosh|tgservice|leave|join|emoji|english|media|operator]
Lock group settings
*rtl: Delete msg if Right To Left Char. is in name*
*strict: enable strict settings enforcement (violating user will be kicked)*
*fosh: Delete badword msg*
*fwd: Delete forward msg*
!unlock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict|tag|username|fwd|reply|fosh|tgservice|leave|join|emoji|english|media|operator]
Unlock group settings
*rtl: Delete msg if Right To Left Char. is in name*
*strict: disable strict settings enforcement (violating user will not be kicked)*
!mute [all|audio|gifs|photo|video|service]
mute group message types
*A "muted" message type is auto-deleted if posted
!unmute [all|audio|gifs|photo|video|service]
Unmute group message types
*A "unmuted" message type is not auto-deleted if posted
!setflood [value]
Set [value] as flood sensitivity
!type [name]
set type for supergroup
!settings
Returns chat settings
!mutelist
Returns mutes for chat
!silent [username]
Mute a user in chat
*If a muted user posts a message, the message is deleted automaically
*only owners can mute | mods and owners can unmute
!silentlist
Returns list of muted users in chat
!banlist
Returns SuperGroup ban list
!clean [rules|about|modlist|silentlist|filterlist]
!del
Deletes a message by reply
!filter [word]
bot Delete word if member send
!unfilter [word]
Delete word in filter list
!filterlist
get filter list
!clean msg [value]
!public [yes|no]
Set chat visibility in pm !chats or !chatlist commands
!res [username]
Returns users name and id by username
!log
Returns group logs
*Search for kick reasons using [#RTL|#spam|#lockmember]
**You can use "#", "!", or "/" to begin all commands
*Only owner can add members to SuperGroup
(use invite link to invite)
*Only moderators and owner can use block, ban, unban, newlink, link, setphoto, setname, lock, unlock, setrules, setabout and settings commands
*Only owner can use res, setowner, promote, demote, and log commands
]],
}
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)
--vardump (chat)
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(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
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 |
wizardbottttt/Speed_Bot | bot/utils.lua | 239 | 13499 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
| gpl-2.0 |
Puccio7/bot-telegram | bot/utils.lua | 239 | 13499 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
| apache-2.0 |
dromozoa/dromozoa-unix | test/lua/test_pathexec.lua | 1 | 1539 | -- Copyright (C) 2016,2018 Tomoyuki Fujimori <moyu@dromozoa.com>
--
-- This file is part of dromozoa-unix.
--
-- dromozoa-unix is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- dromozoa-unix is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with dromozoa-unix. If not, see <http://www.gnu.org/licenses/>.
local unix = require "dromozoa.unix"
local verbose = os.getenv "VERBOSE" == "1"
local PATH = os.getenv "PATH"
local envp = unix.get_environ()
envp[#envp + 1] = "foo=bar"
local reader, writer = assert(unix.pipe())
local process = unix.process()
assert(process:forkexec(PATH, { arg[-1], "test/lua/pathexec.lua" }, envp, nil, { [1] = writer }))
assert(writer:close())
local buffer = {}
while true do
local data = assert(reader:read(256))
if data == "" then
break
else
buffer[#buffer + 1] = data
end
end
assert(reader:close())
if verbose then
io.stderr:write(("%q\n"):format(table.concat(buffer)))
end
assert(table.concat(buffer) == "baz\n")
local pid, reason, status = assert(unix.wait())
assert(pid == process[1])
assert(reason == "exit")
assert(status == 0)
| gpl-3.0 |
BTAxis/naev | dat/factions/spawn/thurion.lua | 1 | 3083 | include("dat/factions/spawn/common.lua")
-- @brief Spawns a small patrol fleet.
function spawn_patrol ()
local pilots = {}
local r = rnd.rnd()
if r < 0.3 then
scom.addPilot( pilots, "Thurion Ingenuity", 25 );
elseif r < 0.6 then
scom.addPilot( pilots, "Thurion Ingenuity", 25 );
scom.addPilot( pilots, "Thurion Perspicacity", 20 );
elseif r < 0.8 then
scom.addPilot( pilots, "Thurion Virtuosity", 45 );
else
scom.addPilot( pilots, "Thurion Apprehension", 75 );
end
return pilots
end
-- @brief Spawns a medium sized squadron.
function spawn_squad ()
local pilots = {}
local r = rnd.rnd()
if r < 0.4 then
scom.addPilot( pilots, "Thurion Perspicacity", 20 );
scom.addPilot( pilots, "Thurion Ingenuity", 25 );
scom.addPilot( pilots, "Thurion Virtuosity", 45 );
elseif r < 0.6 then
scom.addPilot( pilots, "Thurion Ingenuity", 25 );
scom.addPilot( pilots, "Thurion Virtuosity", 45 );
elseif r < 0.8 then
scom.addPilot( pilots, "Thurion Perspicacity", 20 );
scom.addPilot( pilots, "Thurion Perspicacity", 20 );
scom.addPilot( pilots, "Thurion Taciturnity", 40 );
else
scom.addPilot( pilots, "Thurion Apprehension", 75 );
scom.addPilot( pilots, "Thurion Perspicacity", 20 );
scom.addPilot( pilots, "Thurion Perspicacity", 20 );
end
return pilots
end
-- @brief Spawns a capship with escorts.
function spawn_capship ()
local pilots = {}
pilots.__fleet = true
local r = rnd.rnd()
-- Generate the capship
scom.addPilot( pilots, "Thurion Certitude", 140 )
-- Generate the escorts
r = rnd.rnd()
if r < 0.5 then
scom.addPilot( pilots, "Thurion Perspicacity", 20 );
scom.addPilot( pilots, "Thurion Perspicacity", 20 );
scom.addPilot( pilots, "Thurion Ingenuity", 25 );
scom.addPilot( pilots, "Thurion Ingenuity", 25 );
elseif r < 0.8 then
scom.addPilot( pilots, "Thurion Ingenuity", 25 );
scom.addPilot( pilots, "Thurion Virtuosity", 45 );
else
scom.addPilot( pilots, "Thurion Apprehension", 75 );
scom.addPilot( pilots, "Thurion Ingenuity", 25 );
end
return pilots
end
-- @brief Creation hook.
function create ( max )
local weights = {}
-- Create weights for spawn table
weights[ spawn_patrol ] = 100
weights[ spawn_squad ] = math.max(1, -80 + 0.80 * max)
weights[ spawn_capship ] = math.max(1, -500 + 1.70 * max)
-- Create spawn table base on weights
spawn_table = scom.createSpawnTable( weights )
-- Calculate spawn data
spawn_data = scom.choose( spawn_table )
return scom.calcNextSpawn( 0, scom.presence(spawn_data), max )
end
-- @brief Spawning hook
function spawn ( presence, max )
local pilots
-- Over limit
if presence > max then
return 5
end
-- Actually spawn the pilots
pilots = scom.spawn( spawn_data, "Thurion" )
-- Calculate spawn data
spawn_data = scom.choose( spawn_table )
return scom.calcNextSpawn( presence, scom.presence(spawn_data), max ), pilots
end
| gpl-3.0 |
actionless/awesome | tests/examples/wibox/widget/imagebox/max_scaling_factor.lua | 2 | 1635 | --DOC_HIDE_ALL
--DOC_GEN_IMAGE
local parent = ...
local wibox = require( "wibox" )
local beautiful = require( "beautiful" )
local function cell_centered_widget(widget)
return wibox.widget {
widget,
valign = 'center',
halign = 'center',
content_fill_vertical = false,
content_fill_horizontal = false,
widget = wibox.container.place
}
end
local function build_ib(size, factor)
return cell_centered_widget(wibox.widget {
{
forced_height = size,
forced_width = size,
max_scaling_factor = factor,
image = beautiful.awesome_icon,
widget = wibox.widget.imagebox
},
forced_width = size + 2,
forced_height = size + 2,
color = beautiful.border_color,
margins = 1,
widget = wibox.container.margin
})
end
local l = wibox.widget {
homogeneous = false,
spacing = 5,
layout = wibox.layout.grid,
}
parent:add(l)
l:add_widget_at(cell_centered_widget(wibox.widget.textbox('max_scaling_factor = nil')), 1, 1)
l:add_widget_at(cell_centered_widget(wibox.widget.textbox('max_scaling_factor = 2')), 2, 1)
l:add_widget_at(cell_centered_widget(wibox.widget.textbox('imagebox size')), 3, 1)
for i,size in ipairs({16, 32, 64}) do
l:add_widget_at(build_ib(size, nil), 1, i + 1)
l:add_widget_at(build_ib(size, 2), 2, i + 1)
l:add_widget_at(cell_centered_widget(wibox.widget.textbox(size..'x'..size)), 3, i + 1)
end
--DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
waste143/waste | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
kiarash14/tel | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
Fatalerror66/ffxi-a | scripts/zones/Southern_San_dOria_[S]/npcs/Achtelle1.lua | 72 | 1069 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Achtelle
-- @zone 80
-- @pos 108 2 -11
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:startEvent(0x01FE); Event doesnt work but this is her default dialogue, threw in something below til it gets fixed
player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again!
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 |
Fatalerror66/ffxi-a | scripts/zones/Southern_San_dOria_[S]/npcs/Achtelle.lua | 72 | 1069 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Achtelle
-- @zone 80
-- @pos 108 2 -11
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:startEvent(0x01FE); Event doesnt work but this is her default dialogue, threw in something below til it gets fixed
player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again!
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 |
kidaa/FFXIOrgins | scripts/zones/Meriphataud_Mountains_[S]/npcs/Telepoint.lua | 18 | 1231 | -----------------------------------
-- Area: Meriphataud Mountains [S]
-- NPC: Telepoint
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Meriphataud_Mountains_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:hasKeyItem(MERIPHATAUD_GATE_CRYSTAL) == false) then
player:addKeyItem(MERIPHATAUD_GATE_CRYSTAL);
player:messageSpecial(KEYITEM_OBTAINED,MERIPHATAUD_GATE_CRYSTAL);
else
player:messageSpecial(ALREADY_OBTAINED_TELE);
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 |
TeleMafia/mafia | plugins/PL (9).lua | 6 | 1292 | local function pre_process(msg)
local hash = 'mute_time:'..msg.chat_id_
if redis:get(hash) and gp_type(msg.chat_id_) == 'channel' and not is_mod(msg) then
tdcli.deleteMessages(msg.chat_id_, {[0] = tonumber(msg.id_)})
end
end
local function run(msg, matches)
if matches[1]:lower() == 'mt' and is_mod(msg) then
local hash = 'mute_time:'..msg.chat_id_
if not matches[2] then
return "_لطفا ساعت و دقیقه را وارد نمایید!_"
else
local hour = string.gsub(matches[2], 'h', '')
local num1 = tonumber(hour) * 3600
local minutes = string.gsub(matches[3], 'm', '')
local num2 = tonumber(minutes) * 60
local num4 = tonumber(num1 + num2)
redis:setex(hash, num4, true)
return "⛔️گروه به مدت: \n`"..matches[2].."` ساعت\n`"..matches[3].."` دقیقه \nتعطیل میباشد.️"
end
end
if matches[1]:lower() == 'unmt' and is_mod(msg) then
local hash = 'mute_time:'..msg.chat_id_
redis:del(hash)
return "*✅گروه برای ارسال پیام کاربران باز شد.*"
end
end
return {
patterns = {
'^[/!#]([Mm][Tt])$',
'^[/!#]([Uu][Nn][Mm][Tt])$',
'^[/!#]([Mm][Tt]) (%d+) (%d+)$',
},
run = run,
pre_process = pre_process
}
-- http://bom_bang_team
| gpl-3.0 |
pquentin/wesnoth | data/ai/micro_ais/cas/ca_patrol.lua | 26 | 6200 | local AH = wesnoth.require "ai/lua/ai_helper.lua"
local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua"
local function get_patrol(cfg)
local filter = cfg.filter or { id = cfg.id }
local patrol = AH.get_units_with_moves {
side = wesnoth.current.side,
{ "and", filter }
}[1]
return patrol
end
local ca_patrol = {}
function ca_patrol:evaluation(ai, cfg)
if get_patrol(cfg) then return cfg.ca_score end
return 0
end
function ca_patrol:execution(ai, cfg)
local patrol = get_patrol(cfg)
local patrol_vars = MAIUV.get_mai_unit_variables(patrol, cfg.ai_id)
-- Set up waypoints, taking into account whether 'reverse' is set
-- This works even the first time, when patrol_vars.patrol_reverse is not set yet
cfg.waypoint_x = AH.split(cfg.waypoint_x, ",")
cfg.waypoint_y = AH.split(cfg.waypoint_y, ",")
local n_wp = #cfg.waypoint_x
local waypoints = {}
for i = 1,n_wp do
if patrol_vars.patrol_reverse then
waypoints[i] = { tonumber(cfg.waypoint_x[n_wp-i+1]), tonumber(cfg.waypoint_y[n_wp-i+1]) }
else
waypoints[i] = { tonumber(cfg.waypoint_x[i]), tonumber(cfg.waypoint_y[i]) }
end
end
-- If not set, set next location (first move)
-- This needs to be in WML format, so that it persists over save/load cycles
if (not patrol_vars.patrol_x) then
patrol_vars.patrol_x = waypoints[1][1]
patrol_vars.patrol_y = waypoints[1][2]
patrol_vars.patrol_reverse = false
MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars)
end
while patrol.moves > 0 do
-- Check whether one of the enemies to be attacked is next to the patroller
-- If so, don't move, but attack that enemy
local adjacent_enemy = wesnoth.get_units {
id = cfg.attack,
{ "filter_adjacent", { id = patrol.id } },
{ "filter_side", {{ "enemy_of", { side = wesnoth.current.side } }} }
}[1]
if adjacent_enemy then break end
-- Also check whether we're next to any unit (enemy or ally) which is on the next waypoint
local unit_on_wp = wesnoth.get_units {
x = patrol_vars.patrol_x,
y = patrol_vars.patrol_y,
{ "filter_adjacent", { id = patrol.id } }
}[1]
for i,wp in ipairs(waypoints) do
-- If the patrol is on a waypoint or adjacent to one that is occupied by any unit
if ((patrol.x == wp[1]) and (patrol.y == wp[2]))
or (unit_on_wp and ((unit_on_wp.x == wp[1]) and (unit_on_wp.y == wp[2])))
then
if (i == n_wp) then
-- Move him to the first one (or reverse route), if he's on the last waypoint
-- Unless cfg.one_time_only is set
if cfg.one_time_only then
patrol_vars.patrol_x = waypoints[n_wp][1]
patrol_vars.patrol_y = waypoints[n_wp][2]
MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars)
else
-- Go back to first WP or reverse direction
if cfg.out_and_back then
patrol_vars.patrol_x = waypoints[n_wp-1][1]
patrol_vars.patrol_y = waypoints[n_wp-1][2]
-- We also need to reverse the waypoints right here, as this might not be the end of the move
patrol_vars.patrol_reverse = not patrol_vars.patrol_reverse
MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars)
local tmp_wp = {}
for j,wp2 in ipairs(waypoints) do tmp_wp[n_wp-j+1] = wp2 end
waypoints = tmp_wp
else
patrol_vars.patrol_x = waypoints[1][1]
patrol_vars.patrol_y = waypoints[1][2]
MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars)
end
end
else
-- ... else move him on toward the next waypoint
patrol_vars.patrol_x = waypoints[i+1][1]
patrol_vars.patrol_y = waypoints[i+1][2]
MAIUV.set_mai_unit_variables(patrol, cfg.ai_id, patrol_vars)
end
end
end
-- If we're on the last waypoint on one_time_only is set, stop here
if cfg.one_time_only and
(patrol.x == waypoints[n_wp][1]) and (patrol.y == waypoints[n_wp][2])
then
AH.checked_stopunit_moves(ai, patrol)
else -- Otherwise move toward next WP
local x, y = wesnoth.find_vacant_tile(patrol_vars.patrol_x, patrol_vars.patrol_y, patrol)
local nh = AH.next_hop(patrol, x, y)
if nh and ((nh[1] ~= patrol.x) or (nh[2] ~= patrol.y)) then
AH.checked_move(ai, patrol, nh[1], nh[2])
else
AH.checked_stopunit_moves(ai, patrol)
end
end
if (not patrol) or (not patrol.valid) then return end
end
-- Attack unit on the last waypoint under all circumstances if cfg.one_time_only is set
local adjacent_enemy
if cfg.one_time_only then
adjacent_enemy = wesnoth.get_units{
x = waypoints[n_wp][1],
y = waypoints[n_wp][2],
{ "filter_adjacent", { id = patrol.id } },
{ "filter_side", { { "enemy_of", { side = wesnoth.current.side } } } }
}[1]
end
-- Otherwise attack adjacent enemy (if specified)
if (not adjacent_enemy) then
adjacent_enemy = wesnoth.get_units{
id = cfg.attack,
{ "filter_adjacent", { id = patrol.id } },
{ "filter_side", { { "enemy_of", { side = wesnoth.current.side } } } }
}[1]
end
if adjacent_enemy then AH.checked_attack(ai, patrol, adjacent_enemy) end
if (not patrol) or (not patrol.valid) then return end
AH.checked_stopunit_all(ai, patrol)
end
return ca_patrol
| gpl-2.0 |
flyzjhz/openwrt-bb | feeds/luci/modules/admin-full/luasrc/controller/admin/uci.lua | 85 | 1975 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.admin.uci", package.seeall)
function index()
local redir = luci.http.formvalue("redir", true) or
luci.dispatcher.build_url(unpack(luci.dispatcher.context.request))
entry({"admin", "uci"}, nil, _("Configuration"))
entry({"admin", "uci", "changes"}, call("action_changes"), _("Changes"), 40).query = {redir=redir}
entry({"admin", "uci", "revert"}, call("action_revert"), _("Revert"), 30).query = {redir=redir}
entry({"admin", "uci", "apply"}, call("action_apply"), _("Apply"), 20).query = {redir=redir}
entry({"admin", "uci", "saveapply"}, call("action_apply"), _("Save & Apply"), 10).query = {redir=redir}
end
function action_changes()
local uci = luci.model.uci.cursor()
local changes = uci:changes()
luci.template.render("admin_uci/changes", {
changes = next(changes) and changes
})
end
function action_apply()
local path = luci.dispatcher.context.path
local uci = luci.model.uci.cursor()
local changes = uci:changes()
local reload = {}
-- Collect files to be applied and commit changes
for r, tbl in pairs(changes) do
table.insert(reload, r)
if path[#path] ~= "apply" then
uci:load(r)
uci:commit(r)
uci:unload(r)
end
end
luci.template.render("admin_uci/apply", {
changes = next(changes) and changes,
configs = reload
})
end
function action_revert()
local uci = luci.model.uci.cursor()
local changes = uci:changes()
-- Collect files to be reverted
for r, tbl in pairs(changes) do
uci:load(r)
uci:revert(r)
uci:unload(r)
end
luci.template.render("admin_uci/revert", {
changes = next(changes) and changes
})
end
| gpl-2.0 |
simon-wh/PAYDAY-2-BeardLib-Editor | mods/BeardLib-Editor/Classes/Map/StaticEditor.lua | 1 | 50618 | --Clean this script by separating parts of it to different classes
StaticEditor = StaticEditor or class(EditorPart)
local Static = StaticEditor
local Utils = BLE.Utils
function Static:init(parent, menu)
Static.super.init(self, parent, menu, "Selection")
self._selected_units = {}
self._ignore_raycast = {}
self._ignored_collisions = {}
self._set_units = {}
self._set_elements = {}
self._widget_slot_mask = World:make_slot_mask(1)
end
function Static:enable()
self:bind_opt("DeleteSelection", ClassClbk(self, "delete_selected_dialog"))
self:bind_opt("CopyUnit", ClassClbk(self, "CopySelection"))
self:bind_opt("PasteUnit", ClassClbk(self, "Paste"))
self:bind_opt("TeleportToSelection", ClassClbk(self, "KeyFPressed"))
local menu = self:GetPart("menu")
self:bind_opt("ToggleRotationWidget", ClassClbk(menu, "toggle_widget", "rotation"))
self:bind_opt("ToggleMoveWidget", ClassClbk(menu, "toggle_widget", "move"))
end
function Static:mouse_pressed(button, x, y)
if button == Idstring("0") then
if self:Value("EndlessSelection") then
self._reset_raycast = TimerManager:game():time() + self:Value("EndlessSelectionReset")
end
self._widget_hold = true
self._parent:reset_widget_values()
local from = self._parent:get_cursor_look_point(0)
local to = self._parent:get_cursor_look_point(100000)
local unit = self._parent:widget_unit()
if unit then
if self._parent._move_widget:enabled() then
local ray = World:raycast("ray", from, to, "ray_type", "widget", "target_unit", self._parent._move_widget:widget())
if ray and ray.body then
if (alt() and not ctrl()) then self:Clone() end
self:StorePreviousPosRot()
self._parent._move_widget:add_move_widget_axis(ray.body:name():s())
self._parent._move_widget:set_move_widget_offset(unit, unit:rotation())
self._parent._using_move_widget = true
end
end
if self._parent._rotate_widget:enabled() and not self._parent._using_move_widget then
local ray = World:raycast("ray", from, to, "ray_type", "widget", "target_unit", self._parent._rotate_widget:widget())
if ray and ray.body then
self:StorePreviousPosRot()
self._parent._rotate_widget:set_rotate_widget_axis(ray.body:name():s())
self._parent._rotate_widget:set_world_dir(ray.position)
self._parent._rotate_widget:set_rotate_widget_start_screen_position(self._parent:world_to_screen(ray.position):with_z(0))
self._parent._rotate_widget:set_rotate_widget_unit_rot(self._selected_units[1]:rotation())
self._parent._using_rotate_widget = true
end
end
end
if not self._parent._using_rotate_widget and not self._parent._using_move_widget then
self:select_unit()
end
elseif button == Idstring("1") then
if self:Value("EndlessSelection") then
self._reset_raycast = nil
self._ignore_raycast = {}
else
self:set_drag_select()
end
self:select_unit(true)
self._mouse_hold = true
end
end
function Static:update_grid_size() self:set_unit() end
function Static:deselect_unit(item) self:set_unit(true) end
function Static:mouse_released(button, x, y)
self._mouse_hold = false
self._widget_hold = false
self._drag_select = false
self:remove_polyline()
if self._drag_units and #self._drag_units > 0 then
for key, unit in pairs(self._drag_units) do
if ctrl() then
self:set_selected_unit(unit, true)
elseif alt() then
table.delete(self._selected_units, unit)
end
end
if #self._selected_units < 1 then self:set_unit(true) end
end
self._drag_units = nil
for key, ignored in pairs(self._ignored_collisions) do
Utils:UpdateCollisionsAndVisuals(key, ignored, true)
end
self:set_units()
self._ignored_collisions = {}
end
function Static:set_units()
for key, unit in pairs(self._set_units) do
if alive(unit) then
local ud = unit:unit_data()
managers.worlddefinition:set_unit(ud.unit_id, unit, ud.continent, ud.continent)
end
end
for _, me in pairs(self._set_elements) do
local element = me.element
element.values.position = me._unit:position()
element.values.rotation = me._unit:rotation()
managers.mission:set_element(element)
end
self:update_positions()
self._set_units = {}
self._set_elements = {}
end
function Static:build_default_menu()
Static.super.build_default_menu(self)
self._editors = {}
self:SetTitle("Selection")
self:Divider("No selection >.<", {bordr_left = false})
self:Button("World Menu", ClassClbk(self:GetPart("world"), "Switch"))
end
function Static:build_quick_buttons(cannot_be_saved)
self:SetTitle("Selection")
local quick_buttons = self:Group("QuickButtons")
self:Button("Deselect", ClassClbk(self, "deselect_unit"), {group = quick_buttons})
self:Button("DeleteSelection", ClassClbk(self, "delete_selected_dialog"), {group = quick_buttons})
if not cannot_be_saved then
self:Button("CreatePrefab", ClassClbk(self, "add_selection_to_prefabs"), {group = quick_buttons})
self:Button("AddRemovePortal", ClassClbk(self, "addremove_unit_portal"), {group = quick_buttons, text = "Add To / Remove From Portal", visible = true})
local group = self:Group("Group", {visible = false}) --lmao
self:build_group_options()
end
end
function Static:build_group_options()
local group = self:GetItem("Group")
local selected_unit = self:selected_unit()
if not group or not selected_unit then
return
end
local selected_units = self:selected_units()
local can_group = #selected_units > 1
local inside_group = false
local sud = selected_unit:unit_data()
if can_group then
for _, unit in pairs(selected_units) do
local ud = unit:unit_data()
if not ud.unit_id or not ud.continent or managers.worlddefinition:is_world_unit(unit) then
can_group = false
break
end
end
end
group:ClearItems()
group:SetVisible(can_group)
if can_group then
if self._selected_group then
self:Divider("GroupToolTip", {text = "Hold ctrl and press mouse 2 to add units to/remove units from group", group = group})
self:TextBox("GroupName", ClassClbk(self, "set_group_name"), self._selected_group.name, {group = group})
self:Button("UngroupUnits", ClassClbk(self, "remove_group"), {group = group})
else
self:Button("AddToGroup", ClassClbk(self, "open_addremove_group_dialog", false), {group = group, text = "Add Unit(s) To Group"})
self:Button("GroupUnits", ClassClbk(self, "add_group"), {group = group})
end
end
end
function Static:build_unit_editor_menu()
Static.super.build_default_menu(self)
self:SetTitle("Selection")
local other = self:Group("Main")
self:build_positions_items()
self:TextBox("Name", ClassClbk(self, "set_unit_data"), nil, {group = other, help = "the name of the unit"})
self:TextBox("Id", ClassClbk(self, "set_unit_data"), nil, {group = other, enabled = false})
self:PathItem("UnitPath", ClassClbk(self, "set_unit_data"), nil, "unit", true, function(unit)
local t = Utils:GetUnitType(unit)
return t ~= Idstring("being") and t ~= Idstring("brush") and t ~= Idstring("wpn") and t ~= Idstring("item")
end, false, {group = other})
self:ComboBox("Continent", ClassClbk(self, "set_unit_data"), self._parent._continents, 1, {group = other})
self:Toggle("Enabled", ClassClbk(self, "set_unit_data"), true, {group = other, help = "Setting the unit enabled or not[Debug purpose only]"})
self:Toggle("HideOnProjectionLight", ClassClbk(self, "set_unit_data"), false, {group = other})
self:Toggle("DisableShadows", ClassClbk(self, "set_unit_data"), false, {group = other})
self:Toggle("DisableCollision", ClassClbk(self, "set_unit_data"), false, {group = other})
self:Toggle("DisableOnAIGraph", ClassClbk(self, "set_unit_data"), false, {group = other})
self:build_extension_items()
end
function Static:build_extension_items()
self._editors = {}
for k, v in pairs({
light = EditUnitLight,
ladder = EditLadder,
editable_gui = EditUnitEditableGui,
zipline = EditZipLine,
wire = EditWire,
mesh_variation = EditMeshVariation,
ai_data = EditAIData,
cubemap = EditUnitCubemap,
}) do
self._editors[k] = v:new():is_editable(self)
end
end
function Static:build_positions_items(cannot_be_saved)
self._editors = {}
self:build_quick_buttons(cannot_be_saved)
local transform = self:Group("Transform")
self:Button("IgnoreRaycastOnce", function()
for _, unit in pairs(self:selected_units()) do
if unit:unit_data().unit_id then
self._ignore_raycast[unit:unit_data().unit_id] = true
end
end
end, {group = transform})
self:AxisControls(ClassClbk(self, "set_unit_data"), {group = transform, on_click = ClassClbk(self, "StorePreviousPosRot"), step = self:GetPart("opt")._menu:GetItem("GridSize"):Value()})
end
function StaticEditor:update_positions()
local unit = self._selected_units[1]
if unit then
if #self._selected_units > 1 or not unit:mission_element() then
self:SetAxisControls(unit:position(), unit:rotation())
self:GetPart("instances"):update_positions()
self:GetPart("world"):update_positions()
for i, control in pairs(self._axis_controls) do
self[control]:SetStep(i < 4 and self._parent._grid_size or self._parent._snap_rotation)
end
elseif unit:mission_element() and self:GetPart("mission")._current_script then
self:GetPart("mission")._current_script:update_positions(unit:position(), unit:rotation())
end
for _, unit in pairs(self:selected_units()) do
if unit:editable_gui() then
unit:editable_gui():set_blend_mode(unit:editable_gui():blend_mode())
end
end
end
for _, editor in pairs(self._editors) do
if editor.update_positions then
editor:update_positions(unit)
end
end
if self._built_multi then
self:SetTitle("Selection - " .. tostring(#self._selected_units))
end
end
function Static:open_addremove_group_dialog(remove)
local groups = {}
local continents = managers.worlddefinition._continent_definitions
if remove then
local groups = self:get_groups_from_unit(self._selected_units[1])
for _, group in pairs(groups) do
self._parent:Log(tostring(group.name))
if group.name then table.insert(groups, {name = group.name, group = group}) end
end
else
for _, continent in pairs(self._parent._continents) do
if continents[continent].editor_groups then
for _, editor_group in pairs(continents[continent].editor_groups) do
if editor_group.name then table.insert(groups, {name = editor_group.name, group = editor_group}) end
end
end
end
end
local units = self._selected_units
BLE.ListDialog:Show({
list = groups,
force = true,
callback = function(item)
self:select_group(item.group)
for _, unit in pairs(units) do
if alive(unit) then
if remove and table.contains(self._selected_group.units, unit:unit_data().unit_id) then
table.delete(self._selected_group.units, unit:unit_data().unit_id)
elseif not table.contains(self._selected_group.units, unit:unit_data().unit_id) then
table.insert(self._selected_group.units, unit:unit_data().unit_id)
self:set_selected_unit(unit, true)
end
if #self._selected_group.units <= 1 then
self:remove_group()
end
end
end
BeardLibEditor.ListDialog:hide()
end
})
end
function Static:set_unit_data()
self._parent:set_unit_positions(self:AxisControlsPosition())
self._parent:set_unit_rotations(self:AxisControlsRotation())
if #self._selected_units == 1 then
if not self:GetItem("Continent") then
return
end
local unit = self._selected_units[1]
local ud = unit:unit_data()
if ud and ud.unit_id then
local prev_id = ud.unit_id
managers.worlddefinition:set_name_id(unit, self:GetItem("Name"):Value())
local path_changed = unit:unit_data().name ~= self:GetItem("UnitPath"):Value()
local u_path = self:GetItem("UnitPath"):Value()
ud.name = (u_path and u_path ~= "" and u_path) or ud.name
ud.unit_id = self:GetItem("Id"):Value()
ud.disable_shadows = self:GetItem("DisableShadows"):Value()
ud.disable_collision = self:GetItem("DisableCollision"):Value()
ud.hide_on_projection_light = self:GetItem("HideOnProjectionLight"):Value()
ud.disable_on_ai_graph = self:GetItem("DisableOnAIGraph"):Value()
unit:set_enabled(self:GetItem("Enabled"):Value())
for _, editor in pairs(self._editors) do
if editor.set_unit_data and editor:editable(unit) then
editor:set_unit_data()
end
end
BeardLib.Utils:RemoveAllNumberIndexes(ud, true) --Custom xml issues happen in here also 😂🔫
ud.lights = Utils:LightData(unit)
ud.triggers = Utils:TriggersData(unit)
ud.editable_gui = Utils:EditableGuiData(unit)
ud.ladder = Utils:LadderData(unit)
ud.zipline = Utils:ZiplineData(unit)
ud.cubemap = Utils:CubemapData(unit)
local old_continent = ud.continent
local new_continent = self:GetItem("Continent"):SelectedItem()
if old_continent ~= new_continent then
self:set_unit_continent(unit, old_continent, new_continent)
self:GetItem("Id"):SetValue(ud.unit_id)
end
managers.worlddefinition:set_unit(prev_id, unit, old_continent, new_continent)
for index = 0, unit:num_bodies() - 1 do
local body = unit:body(index)
if body then
body:set_collisions_enabled(not ud.disable_collision)
body:set_collides_with_mover(not ud.disable_collision)
end
end
unit:set_shadows_disabled(unit:unit_data().disable_shadows)
if PackageManager:has(Idstring("unit"), ud.name:id()) and path_changed then
self._parent:SpawnUnit(ud.name, unit, false, ud.unit_id)
self._parent:DeleteUnit(unit, true)
end
end
else
for _, unit in pairs(self._selected_units) do
local ud = unit:unit_data()
if not unit:mission_element() then
self:set_unit_continent(unit, ud.continent, self:GetItem("Continent"):SelectedItem(), true)
end
end
end
--TODO: put in a different place
self:GetPart("instances"):update_positions()
self:GetPart("world"):update_positions()
end
function Static:set_unit_continent(unit, old_continent, new_continent, set)
local ud = unit:unit_data()
local old_id = ud.unit_id
if new_continent ~= "*" and old_continent ~= new_continent then
ud.continent = new_continent
managers.worlddefinition:ResetUnitID(unit, old_continent)
self:set_unit_group(old_id, ud.unit_id, old_continent, new_continent)
--Change all links to match the new ID.
for _, link in pairs(managers.mission:get_links_paths_new(old_id, Utils.LinkTypes.Unit)) do
link.tbl[link.key] = ud.unit_id
end
else
new_continent = nil
end
if set then
managers.worlddefinition:set_unit(old_id, unit, old_continent, new_continent)
end
end
function Static:set_unit_group(old_id, new_id, old_continent, new_continent)
for _, continent in pairs(managers.worlddefinition._continent_definitions) do
continent.editor_groups = continent.editor_groups or {}
for _, group in pairs(continent.editor_groups) do
if type(group) == "table" and group.units then
if group.reference == old_id then
group.reference = new_id
local continents = managers.worlddefinition._continent_definitions
table.delete(continents[old_continent].editor_groups, group)
continents[new_continent].editor_groups = continents[new_continent].editor_groups or {}
table.insert(continents[new_continent].editor_groups, group)
end
for i, unit_id in pairs(group.units) do
if unit_id == old_id then
group.units[i] = new_id
return
end
end
return
end
end
end
end
function Static:StorePreviousPosRot()
for _, unit in pairs(self._selected_units) do
unit:unit_data()._prev_pos = unit:position()
unit:unit_data()._prev_rot = unit:rotation()
end
end
function Static:set_group_name(item, group, name)
local exists
local continent = group and group.continent or self._selected_group.continent
name = name or item:Value()
for _, editor_group in pairs(managers.worlddefinition._continent_definitions[continent].editor_groups) do
if editor_group.name == name then
exists = true
break
end
end
if not exists then
if item then self._selected_group.name = item:Value() return end
for _, editor_group in pairs(managers.worlddefinition._continent_definitions[continent].editor_groups) do
if editor_group.name == group.name then
editor_group.name = name
end
end
end
end
function Static:remove_group(item, group)
group = group or self._selected_group
if group then
table.delete(managers.worlddefinition._continent_definitions[group.continent].editor_groups, group)
if self._selected_group then
self._selected_group = nil
self:build_group_options()
end
end
end
function Static:add_group(item)
local unit = self:selected_unit()
BeardLibEditor.InputDialog:Show({title = "Group Name", text = unit:unit_data().name_id, callback = function(name)
local continent = managers.worlddefinition:get_continent_of_static(unit)
local exists
for _, group in pairs(continent.editor_groups) do
if group.name == name then
exists = true
end
end
if not exists then
local group = {continent = unit:unit_data().continent, reference = unit:unit_data().unit_id, name = name, units = {}, visible = true}
for _, unit in pairs(self:selected_units()) do
table.insert(group.units, unit:unit_data().unit_id)
end
table.insert(continent.editor_groups, group)
self._selected_group = group
self:build_group_options()
end
end})
end
function Static:build_group_links(unit)
local function create_link(text, id, group, clbk)
self:Button(id, clbk, {
text = text,
group = group,
font_size = 16,
label = "groups"
})
end
local group = self:GetItem("InsideGroups") or self:Group("InsideGroups", {max_height = 200, h = 200})
local editor_groups = self:get_groups_from_unit(unit)
for _, editor_group in pairs(editor_groups) do
create_link(editor_group.name, unit:unit_data().unit_id, group, ClassClbk(self, "select_group", editor_group))
end
local group_buttons = self:GetItem("Group")
if #group:Items() == 0 then
group:Destroy()
else
group_buttons:SetVisible(true)
self:Button("RemoveFromGroup", ClassClbk(self, "open_addremove_group_dialog", true), {group = group_buttons})
end
end
function Static:get_groups_from_unit(unit)
local continent = managers.worlddefinition:get_continent_of_static(unit)
if not continent or not continent.editor_groups then return {} end
local groups = {}
for _, editor_group in pairs(continent.editor_groups) do
if editor_group.name then -- temp bandaid for nil groups
for _, unit_id in pairs(editor_group.units) do
if unit_id == unit:unit_data().unit_id then
table.insert(groups, editor_group)
end
end
end
end
return groups
end
function Static:select_group(editor_group)
self:reset_selected_units()
self._selected_group = editor_group
self:build_positions_items(false)
for _, unit_id in pairs(editor_group.units) do
local unit = managers.worlddefinition:get_unit(unit_id)
self:set_selected_unit(unit, true)
end
end
function Static:toggle_group_visibility(editor_group)
if editor_group.visible == nil then editor_group.visible = false end
editor_group.visible = not editor_group.visible
for _, unit_id in pairs(editor_group.units) do
local unit = managers.worlddefinition:get_unit(unit_id)
if alive(unit) then unit:set_visible(editor_group.visible) end
end
end
function Static:delete_unit_group_data(unit)
if unit:mission_element() or not unit:unit_data() then return end
local groups = self:get_groups_from_unit(unit)
if groups then
for _, editor_group in pairs(groups) do
table.delete(editor_group.units, unit:unit_data().unit_id)
end
end
end
function Static:add_selection_to_prefabs(item, prefab_name)
local remove_old_links
local name_id = self._selected_units[1]:unit_data().name_id
BeardLibEditor.InputDialog:Show({title = "Prefab Name", text = #self._selected_units == 1 and name_id ~= "none" and name_id or prefab_name or "Prefab", callback = function(prefab_name, menu)
if prefab_name:len() > 200 then
BeardLibEditor.Dialog:Show({title = "ERROR!", message = "Prefab name is too long!", callback = function()
self:add_selection_to_prefabs(item, prefab_name)
end})
return
end
BeardLibEditor.Prefabs[prefab_name] = self:GetCopyData(NotNil(remove_old_links and remove_old_links:Value(), true))
FileIO:WriteScriptData(Path:Combine(BeardLibEditor.PrefabsDirectory, prefab_name..".prefab"), BeardLibEditor.Prefabs[prefab_name], "binary")
end, create_items = function(input_menu)
remove_old_links = self:Toggle("RemoveOldLinks", nil, self:Value("RemoveOldLinks"), {text = "Remove Old Links Of Copied Elements", group = input_menu})
end})
end
function Static:mouse_moved(x, y)
if self._mouse_hold then
if not self._drag_select then
self:select_unit(true)
else
self:_update_drag_select()
end
end
end
function Static:widget_unit()
local unit = self:selected_unit()
if self:Enabled() then
for _, editor in pairs(self._editors) do
if editor.widget_unit then
return editor:widget_unit()
end
end
end
return nil
end
function Static:recalc_all_locals()
if alive(self._selected_units[1]) then
local reference = self._selected_units[1]
reference:unit_data().local_pos = Vector3()
reference:unit_data().local_rot = Rotation()
for _, unit in pairs(self._selected_units) do
if unit ~= reference then
self:recalc_locals(unit, reference)
end
end
end
end
function Static:recalc_locals(unit, reference)
local pos = unit:position()
local ref_pos = reference:position()
local ref_rot = reference:rotation()
unit:unit_data().local_pos = (pos - ref_pos):rotate_with(ref_rot:inverse())
unit:unit_data().local_rot = ref_rot:inverse() * unit:rotation()
end
function Static:check_unit_ok(unit)
local ud = unit:unit_data()
if not ud then
return false
end
if self:Value("EndlessSelection") then
if ud.unit_id and self._ignore_raycast[ud.unit_id] == true then
return false
else
self._ignore_raycast[ud.unit_id] = true
end
else
if ud.unit_id and self._ignore_raycast[ud.unit_id] == true then
self._ignore_raycast[ud.unit_id] = nil
return false
end
end
if ud.instance and not self:Value("SelectInstances") then
return false
end
if ud.unit_id == 0 and ud.name_id == "none" and not ud.name and not ud.position then
return false
end
local mission_element = unit:mission_element() and unit:mission_element().element
local wanted_elements = self:GetPart("opt")._wanted_elements
if mission_element then
return BeardLibEditor.Options:GetValue("Map/ShowElements") and (#wanted_elements == 0 or table.get_key(wanted_elements, managers.mission:get_mission_element(mission_element).class))
else
return unit:visible()
end
end
function Static:reset_selected_units()
self:GetPart("mission"):remove_script()
self:GetPart("world"):reset_selected_units()
for _, unit in pairs(self:selected_units()) do
if alive(unit) and unit:mission_element() then unit:mission_element():unselect() end
end
self._selected_units = {}
self._selected_group = nil
end
function Static:set_selected_unit(unit, add)
add = add == true
self:recalc_all_locals()
local units = {unit}
if alive(unit) then
local ud = unit:unit_data()
if ud and ud.instance then
local instance = managers.world_instance:get_instance_data_by_name(ud.instance)
local fake_unit
for _, u in pairs(self:selected_units()) do
if u:fake() and u:object().name == ud.instance then
fake_unit = u
break
end
end
unit = fake_unit or FakeObject:new(instance)
units[1] = unit
end
if add and self._selected_group and ctrl() then
if not unit:fake() and not not ud.continent and not managers.worlddefinition:is_world_unit(unit) then
if table.contains(self._selected_group.units, ud.unit_id) then
table.delete(self._selected_group.units, ud.unit_id)
else
table.insert(self._selected_group.units, ud.unit_id)
end
if #self._selected_group.units <= 1 then
self:remove_group()
end
end
else
if self:GetPart("opt"):get_value("SelectEditorGroups") then
local continent = managers.worlddefinition:get_continent_of_static(unit)
if not add then
add = true
self:reset_selected_units()
end
local found
for _, continent in pairs(managers.worlddefinition._continent_definitions) do
continent.editor_groups = continent.editor_groups or {}
for _, group in pairs(continent.editor_groups) do
if group.units then
if table.contains(group.units, unit:unit_data().unit_id) then
for _, unit_id in pairs(group.units) do
local u = managers.worlddefinition:get_unit(unit_id)
if alive(u) and not table.contains(units, u) then
table.insert(units, u)
end
end
if self._selected_group then
self._selected_group = nil
else
self._selected_group = group
end
found = true
break
end
end
if found then
break
end
end
end
end
end
end
if add then
for _, unit in pairs(self:selected_units()) do
if unit:mission_element() then unit:mission_element():unselect() end
end
for _, u in pairs(units) do
if not table.contains(self._selected_units, u) then
table.insert(self._selected_units, u)
elseif not self._mouse_hold then
table.delete(self._selected_units, u)
end
end
elseif alive(unit) then
self:reset_selected_units()
self._selected_units[1] = unit
end
self:StorePreviousPosRot()
local unit = self:selected_unit()
self._parent:use_widgets(unit and alive(unit) and unit:enabled())
for _, unit in pairs(self:selected_units()) do
if unit:mission_element() then unit:mission_element():select() end
end
if #self._selected_units > 1 then
self:set_multi_selected()
if self:Value("SelectAndGoToMenu") then
self:Switch()
end
else
self._editors = {}
if alive(unit) then
if unit:mission_element() then
self:GetPart("mission"):set_element(unit:mission_element().element)
elseif self:GetPart("world"):is_world_unit(unit:name()) then
self:GetPart("world"):build_unit_menu()
elseif unit:fake() then
self:GetPart("instances"):set_instance()
else
self:set_unit()
end
if self:Value("SelectAndGoToMenu") then
self:Switch()
end
else
self:set_unit()
end
end
self:GetPart("world"):set_selected_unit()
self:recalc_all_locals()
end
local bain_ids = Idstring("units/payday2/characters/fps_mover/bain")
function Static:select_unit(mouse2)
local rays = self._parent:select_unit_by_raycast(self._parent._editor_all, ClassClbk(self, "check_unit_ok"))
self:recalc_all_locals()
if rays then
for _, ray in pairs(rays) do
if alive(ray.unit) and ray.unit:name() ~= bain_ids then
if not self._mouse_hold then
self._parent:Log("Ray hit " .. tostring(ray.unit:unit_data().name_id).. " " .. ray.body:name())
end
self:set_selected_unit(ray.unit, mouse2)
end
end
end
end
function Static:set_multi_selected()
if self._drag_units then
return
end
self._built_multi = true
self._editors = {}
self:ClearItems()
--TODO: Support more values.
local other = self:Group("Main")
local same_continent
local continent = self:selected_unit():unit_data().continent
local has_continents
local continents_are_different
for _, unit in pairs(self:selected_units()) do
local ud = unit:unit_data()
if ud.continent then
has_continents = true
if ud.continent ~= continent then
continents_are_different = true
end
end
end
if has_continents then
local list = continents_are_different and table.list_add({"*"}, self._parent._continents) or self._parent._continents
local value = continents_are_different and 1 or table.get_key(list, continent)
self:ComboBox("Continent", ClassClbk(self, "set_unit_data"), list, value, {group = other})
end
self:build_positions_items()
self:update_positions()
self:build_group_options()
end
function Static:set_unit(reset)
if reset then
self:reset_selected_units()
end
self._built_multi = false
local unit = self._selected_units[1]
if alive(unit) and unit:unit_data() and not unit:mission_element() then
if not reset then
self:set_menu_unit(unit)
return
end
end
self:build_default_menu()
end
--Default menu for unit editing
function Static:set_menu_unit(unit)
self:build_unit_editor_menu()
self:GetItem("Name"):SetValue(unit:unit_data().name_id, false, true)
self:GetItem("Enabled"):SetValue(unit:enabled())
self:GetItem("UnitPath"):SetValue(unit:unit_data().name, false, true)
self:GetItem("Id"):SetValue(unit:unit_data().unit_id, false, true)
local not_brush = not unit:unit_data().brush_unit
local disable_shadows = self:GetItem("DisableShadows")
local disable_collision = self:GetItem("DisableCollision")
local hide_on_projection_light = self:GetItem("HideOnProjectionLight")
local disable_on_ai_graph = self:GetItem("DisableOnAIGraph")
disable_shadows:SetVisible(not_brush)
disable_collision:SetVisible(not_brush)
hide_on_projection_light:SetVisible(not_brush)
disable_on_ai_graph:SetVisible(not_brush)
disable_shadows:SetValue(unit:unit_data().disable_shadows, false, true)
disable_collision:SetValue(unit:unit_data().disable_collision, false, true)
hide_on_projection_light:SetValue(unit:unit_data().hide_on_projection_light, false, true)
disable_on_ai_graph:SetValue(unit:unit_data().disable_on_ai_graph, false, true)
for _, editor in pairs(self._editors) do
if editor.set_menu_unit then
editor:set_menu_unit(unit)
end
end
self:update_positions()
self:GetItem("Continent"):SetSelectedItem(unit:unit_data().continent)
local not_w_unit = not (unit:wire_data() or unit:ai_editor_data())
self:GetItem("Continent"):SetEnabled(not_w_unit)
self:GetItem("UnitPath"):SetEnabled(not_w_unit)
self:build_links(unit:unit_data().unit_id)
self:build_group_links(unit)
end
local function element_link_text(element, link, warn)
--ugly
return tostring(element.editor_name)
.. "\n" .. tostring(element.id)
.. " | " .. (link and string.pretty2(link)
.. " | " or "") .. tostring(element.class):gsub("Element", "")
.. "\n" .. (warn or "")
end
local function unit_link_text(ud, link)
return tostring(ud.name_id) .. "\n" .. tostring(ud.unit_id) .. link
end
local function portal_link_text(name)
return "Inside portal " .. name
end
function Static:build_links(id, match, element)
match = match or Utils.LinkTypes.Unit
local function create_link(text, id, group, clbk)
warn = warn or ""
self:Button(id, clbk, {
text = text,
group = group,
font_size = 16,
label = "elements"
})
end
local links = managers.mission:get_links_paths_new(id, match)
local links_group = self:GetItem("LinkedBy") or self:Group("LinkedBy", {max_height = 200})
local same_links = {}
links_group:ClearItems()
for _, link in pairs(links) do
same_links[link.element.id] = true
create_link(element_link_text(link.element, link.upper_k or link.key), link.id, links_group, ClassClbk(self._parent, "select_element", link.element))
end
if match == Utils.LinkTypes.Unit then
--Get portals that have the unit attached to - https://github.com/simon-wh/PAYDAY-2-BeardLib-Editor/issues/49
local portal_layer = self:GetLayer("portal")
for _, portal in pairs(clone(managers.portal:unit_groups())) do
local ids = portal._ids
if ids and ids[id] then
local name = portal:name()
create_link(portal_link_text(name), name, links_group, ClassClbk(portal_layer, "select_portal", name, true))
end
end
end
if match == Utils.LinkTypes.Element then
local linking_group = self:GetItem("LinkingTo") or self:Group("LinkingTo", {max_height = 200})
if alive(linking_group) then
linking_group:ClearItems()
end
for _, script in pairs(managers.mission._missions) do
for _, tbl in pairs(script) do
if tbl.elements then
for k, e in pairs(tbl.elements) do
local id = e.id
for _, link in pairs(managers.mission:get_links_paths_new(id, Utils.LinkTypes.Element, {{mission_element_data = element}})) do
local warn
if link.location == "on_executed" then
if same_links[id] and link.tbl.delay == 0 then
warn = "Warning - link already exists and can cause an endless loop, increase the delay."
end
end
create_link(element_link_text(e, link.location, warn), e.id, linking_group, ClassClbk(self._parent, "select_element", e))
end
end
end
end
end
for id, unit in pairs(managers.worlddefinition._all_units) do
if alive(unit) then
local ud = unit:unit_data()
for _, link in pairs(managers.mission:get_links_paths_new(id, Utils.LinkTypes.Unit, {{mission_element_data = element}})) do
local linking_from = link.location
linking_from = linking_from and " | " .. string.pretty2(linking_from) or ""
create_link(unit_link_text(ud, linking_from), id, linking_group, ClassClbk(self, "set_selected_unit", unit))
end
end
end
if #linking_group:Items() == 0 then
linking_group:Destroy()
end
end
if #links_group:Items() == 0 then
links_group:Destroy()
end
return links
end
function Static:addremove_unit_portal(item)
local portal = self:layer("portal")
local count = 0
if portal and portal:selected_portal() then
for _, unit in pairs(self._selected_units) do
if unit:unit_data().unit_id then
portal:remove_unit_from_portal(unit, true)
count = count + 1
end
end
Utils:Notify("Success", string.format("Added/Removed %d units to selected portal", count))
else
Utils:Notify("Error", "No portal selected")
end
end
function Static:delete_selected(item)
self:GetPart("undo_handler"):SaveUnitValues(self._selected_units, "delete")
for _, unit in pairs(self._selected_units) do
if alive(unit) then
if unit:fake() then
self:GetPart("instances"):delete_instance()
else
self:delete_unit_group_data(unit)
self._parent:DeleteUnit(unit)
end
end
end
self:reset_selected_units()
self:set_unit()
end
function Static:delete_selected_dialog(item)
if not self:selected_unit() then
return
end
Utils:YesNoQuestion("This will delete the selection", ClassClbk(self, "delete_selected"))
end
function Static:update(t, dt)
self.super.update(self, t, dt)
if self._reset_raycast and self._reset_raycast <= t then
self._ignore_raycast = {}
self._reset_raycast = nil
end
for _, editor in pairs(self._editors) do
if editor.update then
editor:update(t, dt)
end
end
local color = BeardLibEditor.Options:GetValue("AccentColor"):with_alpha(1)
self._pen:set(color)
local draw_bodies = self:Value("DrawBodies")
if managers.viewport:get_current_camera() then
for _, unit in pairs(self._selected_units) do
if alive(unit) and not unit:fake() then
if draw_bodies then
for i = 0, unit:num_bodies() - 1 do
local body = unit:body(i)
if self._parent:_should_draw_body(body) then
self._pen:body(body)
end
end
else
Application:draw(unit, color:unpack())
end
end
end
end
self:_update_drag_select_draw()
end
function Static:_update_drag_select_draw()
local r = 1
local g = 1
local b = 1
local brush = Draw:brush()
if alt() then
b = 0
g = 0
r = 1
end
if ctrl() then
b = 0
g = 1
r = 0
end
brush:set_color(Color(0.15, 0.5 * r, 0.5 * g, 0.5 * b))
for _, unit in ipairs(self._drag_units or {}) do
brush:draw(unit)
Application:draw(unit, r * 0.75, g * 0.75, b * 0.75)
end
end
function Static:GetCopyData(remove_old_links, keep_location)
local copy_data = {}
local element_type = Utils.LinkTypes.Element
local unit_type = Utils.LinkTypes.Unit
for _, unit in pairs(self._selected_units) do
local typ = unit:mission_element() and "element" or not unit:fake() and "unit" or "unsupported"
local copy = {
type = typ,
mission_element_data = typ == "element" and unit:mission_element().element and deep_clone(unit:mission_element().element) or nil,
unit_data = typ == "unit" and unit:unit_data() and deep_clone(unit:unit_data()) or nil,
wire_data = typ == "unit" and unit:wire_data() and deep_clone(unit:wire_data()) or nil,
ai_editor_data = typ == "unit" and unit:ai_editor_data() and deep_clone(unit:ai_editor_data()) or nil
}
if typ ~= "unsupported" then
table.insert(copy_data, copy)
end
end
--The id is now used as the number it should add to the latest id before spawning the prefab
--Why we need to save ids? so elements can function even after copy pasting
local unit_id = 0
local world_unit_id = 0
local element_id = 0
for _, v in pairs(copy_data) do
local typ = v.type
if typ == "element" then
if not keep_location then
v.mission_element_data.script = nil
end
for _, link in pairs(managers.mission:get_links_paths_new(v.mission_element_data.id, element_type, copy_data)) do
link.tbl[link.key] = element_id
end
v.mission_element_data.id = element_id
element_id = element_id + 1
elseif typ == "unit" and v.unit_data.unit_id then
local is_world = v.wire_data or v.ai_editor_data
if not keep_location then
v.unit_data.continent = nil
end
for _, link in pairs(managers.mission:get_links_paths_new(v.unit_data.unit_id, unit_type, copy_data)) do
link.tbl[link.key] = is_world and world_unit_id or unit_id
end
v.unit_data.unit_id = is_world and world_unit_id or unit_id
if is_world then
world_unit_id = world_unit_id + 1
else
unit_id = unit_id + 1
end
end
end
--Remove old links
if remove_old_links then
for _, v in pairs(copy_data) do
if v.type == "element" then
local e = {v}
for _, continent in pairs(managers.mission._ids) do
for id, _ in pairs(continent) do
managers.mission:delete_links(id, element_type, e)
end
end
for id, _ in pairs(managers.worlddefinition._all_units) do
managers.mission:delete_links(id, unit_type, e)
end
end
end
end
return copy_data
end
function Static:CopySelection()
if #self._selected_units > 0 and not self._parent._menu._highlighted then
self._copy_data = self:GetCopyData(self:Value("RemoveOldLinks"), true) --Sadly thanks for ovk's "crash at all cost" coding I cannot use script converter because it would crash.
if #self._copy_data == 0 then
self._copy_data = nil
end
end
end
function Static:Paste()
if not Global.editor_safe_mode and not self._parent._menu._highlighted and self._copy_data then
self:SpawnCopyData(self._copy_data)
end
end
function Static:SpawnPrefab(prefab)
self:SpawnCopyData(prefab, true)
if self.x then
local cam = managers.viewport:get_current_camera()
self:SetAxisControls(cam:position() + cam:rotation():y(), self:AxisControlsRotation())
self:set_unit_data()
end
end
function Static:SpawnCopyData(copy_data, prefab)
copy_data = deep_clone(copy_data)
local project = BeardLibEditor.MapProject
local missing_units = {}
local missing
local assets = self:GetPart("world")._assets_manager
local mod, data = project:get_mod_and_config()
local unit_ids = Idstring("unit")
local add
if data then
add = project:get_level_by_id(data, Global.game_settings.level_id).add
end
self:reset_selected_units()
for _, v in pairs(copy_data) do
local is_element = v.type == "element"
local is_unit = v.type == "unit"
if v.type == "element" then
local c = managers.mission._scripts[v.mission_element_data.script] or nil
c = c and c._continent or self._parent._current_continent
local new_final_id = managers.mission:get_new_id(c)
for _, link in pairs(managers.mission:get_links_paths_new(v.mission_element_data.id, Utils.LinkTypes.Element, copy_data)) do
link.tbl[link.key] = new_final_id
end
v.mission_element_data.id = new_final_id
elseif v.type == "unit" and v.unit_data.unit_id then
local new_final_id = managers.worlddefinition:GetNewUnitID(v.unit_data.continent or self._parent._current_continent, (v.wire_data or v.ai_editor_data) and "wire" or "")
for _, link in pairs(managers.mission:get_links_paths_new(v.unit_data.unit_id, Utils.LinkTypes.Unit, copy_data)) do
link.tbl[link.key] = new_final_id
end
v.unit_data.unit_id = new_final_id
local unit = v.unit_data.name
if missing_units[unit] == nil then
local is_preview_not_loaded = (not assets and not PackageManager:has(unit_ids, unit:id()))
local not_loaded = not ((assets and assets:is_asset_loaded(unit, "unit") or (add and FileIO:Exists(Path:Combine(mod.ModPath, add.directory, unit..".unit")))))
if is_preview_not_loaded or not_loaded then
missing_units[unit] = true
missing = true
else
missing_units[unit] = false
end
end
end
end
local function all_ok_spawn()
local units = {}
for _, v in pairs(copy_data) do
if v.type == "element" then
table.insert(units, self:GetPart("mission"):add_element(v.mission_element_data.class, nil, v.mission_element_data, true))
elseif v.unit_data then
table.insert(units, self._parent:SpawnUnit(v.unit_data.name, v, nil, v.unit_data.unit_id, true))
end
end
--When all units are spawned properly you can select.
for _, unit in pairs(units) do
self:set_selected_unit(unit, true)
end
self:GetPart("undo_handler"):SaveUnitValues(units, "spawn")
self:StorePreviousPosRot()
end
if missing then
if assets then
Utils:QuickDialog({title = ":(", message = "A unit or more are unloaded, to spawn the prefab/copy you have to load all of the units"}, {{"Load Units", function()
local function find_packages()
for unit, is_missing in pairs(missing_units) do
if is_missing then
if (assets:is_asset_loaded(unit, "unit") or add and FileIO:Exists(Path:Combine(mod.ModPath, add.directory, unit..".unit"))) then
missing_units[unit] = nil
end
else
missing_units[unit] = nil
end
end
if table.size(missing_units) > 0 then
assets:find_packages(missing_units, find_packages)
else
Utils:Notify("Nice!", "All units are now loaded, spawning prefab/copy..")
all_ok_spawn()
end
end
find_packages()
end}})
else
Utils:Notify("ERROR!", "Cannot spawn the prefab[Unloaded units]")
end
else
all_ok_spawn()
end
end
function Static:Clone()
self:CopySelection()
self:Paste()
end
function Static:KeyFPressed()
if self._selected_units[1] then
self._parent:set_camera(self._selected_units[1]:position())
end
end
function Static:set_unit_enabled(enabled)
for _, unit in pairs(self._selected_units) do
if alive(unit) then
unit:set_enabled(enabled)
end
end
end
function Static:set_drag_select()
if self._parent._using_rotate_widget or self._parent._using_move_widget then
return
end
if alt() or ctrl() then
self._drag_select = true
self._polyline = self._parent._menu._panel:polyline({
color = Color(0.5, 1, 1, 1)
})
self._polyline:set_closed(true)
self._drag_start_pos = managers.editor:cursor_pos()
end
end
function Static:_update_drag_select()
if not self._drag_select then
return
end
local end_pos = managers.editor:cursor_pos()
if self._polyline then
local p1 = managers.editor:screen_pos(self._drag_start_pos)
local p3 = managers.editor:screen_pos(end_pos)
local p2 = Vector3(p3.x, p1.y, 0)
local p4 = Vector3(p1.x, p3.y, 0)
self._polyline:set_points({
p1,
p2,
p3,
p4
})
end
local len = (end_pos - self._drag_start_pos):length()
if len > 0.05 then
local top_left = self._drag_start_pos
local bottom_right = end_pos
if bottom_right.y < top_left.y and top_left.x < bottom_right.x or top_left.y < bottom_right.y and bottom_right.x < top_left.x then
top_left = Vector3(self._drag_start_pos.x, end_pos.y, 0)
bottom_right = Vector3(end_pos.x, self._drag_start_pos.y, 0)
end
local units = World:find_units("camera_frustum", managers.editor:camera(), top_left, bottom_right, 500000, self._parent._editor_all)
self._drag_units = {}
for _, unit in ipairs(units) do
if self:check_unit_ok(unit) then
table.insert(self._drag_units, unit)
end
end
end
end
function Static:remove_polyline()
if self._polyline then
managers.editor._menu._panel:remove(self._polyline)
self._polyline = nil
end
end | mit |
LipkeGu/OpenRA | mods/d2k/maps/ordos-03a/ordos03a.lua | 2 | 4895 | --[[
Copyright 2007-2017 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
HarkonnenBase = { HBarracks, HWindTrap1, HWindTrap2, HLightFactory, HOutpost, HConyard, HRefinery, HSilo1, HSilo2, HSilo3, HSilo4 }
HarkonnenBaseAreaTrigger = { CPos.New(2, 58), CPos.New(3, 58), CPos.New(4, 58), CPos.New(5, 58), CPos.New(6, 58), CPos.New(7, 58), CPos.New(8, 58), CPos.New(9, 58), CPos.New(10, 58), CPos.New(11, 58), CPos.New(12, 58), CPos.New(13, 58), CPos.New(14, 58), CPos.New(15, 58), CPos.New(16, 58), CPos.New(16, 59), CPos.New(16, 60) }
HarkonnenReinforcements =
{
easy =
{
{ "light_inf", "trike", "trooper" },
{ "light_inf", "trike", "quad" },
{ "light_inf", "light_inf", "trooper", "trike", "trike", "quad" }
},
normal =
{
{ "light_inf", "trike", "trooper" },
{ "light_inf", "trike", "trike" },
{ "light_inf", "light_inf", "trooper", "trike", "trike", "quad" },
{ "light_inf", "light_inf", "trooper", "trooper" },
{ "light_inf", "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike", "quad", "quad" }
},
hard =
{
{ "trike", "trike", "quad" },
{ "light_inf", "trike", "trike" },
{ "trooper", "trooper", "light_inf", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" },
{ "light_inf", "light_inf", "trooper", "trooper" },
{ "trike", "trike", "quad", "quad", "quad", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" },
{ "light_inf", "trike", "light_inf", "trooper", "trooper", "quad" },
{ "trike", "trike", "quad", "quad", "quad", "trike" }
}
}
HarkonnenAttackDelay =
{
easy = DateTime.Minutes(5),
normal = DateTime.Minutes(2) + DateTime.Seconds(40),
hard = DateTime.Minutes(1) + DateTime.Seconds(20)
}
HarkonnenAttackWaves =
{
easy = 3,
normal = 6,
hard = 9
}
HarkonnenPaths =
{
{ HarkonnenEntry1.Location, HarkonnenRally1.Location },
{ HarkonnenEntry2.Location, HarkonnenRally2.Location },
{ HarkonnenEntry3.Location, HarkonnenRally3.Location }
}
HarkonnenHunters = { "light_inf", "light_inf", "trike", "quad" }
HarkonnenInitialReinforcements = { "light_inf", "light_inf", "quad", "quad", "trike", "trike", "trooper", "trooper" }
HarkonnenHunterPath = { HarkonnenEntry5.Location, HarkonnenRally5.Location }
HarkonnenInitialPath = { HarkonnenEntry4.Location, HarkonnenRally4.Location }
OrdosReinforcements = { "quad", "raider" }
OrdosPath = { OrdosEntry.Location, OrdosRally.Location }
OrdosBaseBuildings = { "barracks", "light_factory" }
OrdosUpgrades = { "upgrade.barracks", "upgrade.light" }
MessageCheck = function(index)
return #player.GetActorsByType(OrdosBaseBuildings[index]) > 0 and not player.HasPrerequisites({ OrdosUpgrades[index] })
end
Tick = function()
if player.HasNoRequiredUnits() then
harkonnen.MarkCompletedObjective(KillOrdos)
end
if harkonnen.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillHarkonnen) then
Media.DisplayMessage("The Harkonnen have been annihilated!", "Mentat")
player.MarkCompletedObjective(KillHarkonnen)
end
if DateTime.GameTime % DateTime.Seconds(10) == 0 and LastHarvesterEaten[harkonnen] then
local units = harkonnen.GetActorsByType("harvester")
if #units > 0 then
LastHarvesterEaten[harkonnen] = false
ProtectHarvester(units[1], harkonnen, AttackGroupSize[Difficulty])
end
end
if DateTime.GameTime % DateTime.Seconds(32) == 0 and (MessageCheck(1) or MessageCheck(2)) then
Media.DisplayMessage("Upgrade barracks and light factory to produce more advanced units.", "Mentat")
end
end
WorldLoaded = function()
harkonnen = Player.GetPlayer("Harkonnen")
player = Player.GetPlayer("Ordos")
InitObjectives(player)
KillOrdos = harkonnen.AddPrimaryObjective("Kill all Ordos units.")
KillHarkonnen = player.AddPrimaryObjective("Eliminate all Harkonnen units and reinforcements\nin the area.")
Camera.Position = OConyard.CenterPosition
Trigger.OnAllKilled(HarkonnenBase, function()
Utils.Do(harkonnen.GetGroundAttackers(), IdleHunt)
end)
local path = function() return Utils.Random(HarkonnenPaths) end
local waveCondition = function() return player.IsObjectiveCompleted(KillHarkonnen) end
SendCarryallReinforcements(harkonnen, 0, HarkonnenAttackWaves[Difficulty], HarkonnenAttackDelay[Difficulty], path, HarkonnenReinforcements[Difficulty], waveCondition)
ActivateAI()
Trigger.AfterDelay(DateTime.Minutes(2) + DateTime.Seconds(30), function()
Reinforcements.ReinforceWithTransport(player, "carryall.reinforce", OrdosReinforcements, OrdosPath, { OrdosPath[1] })
end)
TriggerCarryallReinforcements(player, harkonnen, HarkonnenBaseAreaTrigger, HarkonnenHunters, HarkonnenHunterPath)
end
| gpl-3.0 |
meshr-net/meshr_win32 | usr/lib/lua/luci/model/cbi/upnp/upnp.lua | 2 | 4075 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008-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
$Id: upnp.lua 9569 2012-12-25 02:44:19Z jow $
]]--
m = Map("upnpd", luci.util.pcdata(translate("Universal Plug & Play")),
translate("UPnP allows clients in the local network to automatically configure the router."))
m:section(SimpleSection).template = "upnp_status"
s = m:section(NamedSection, "config", "upnpd", translate("MiniUPnP settings"))
s.addremove = false
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
e = s:taboption("general", Flag, "_init", translate("Start UPnP and NAT-PMP service"))
e.rmempty = false
function e.cfgvalue(self, section)
return luci.sys.init.enabled("miniupnpd") and self.enabled or self.disabled
end
function e.write(self, section, value)
if value == "1" then
luci.sys.call("/etc/init.d/miniupnpd enable >/dev/null")
luci.sys.call("/etc/init.d/miniupnpd start >/dev/null")
else
luci.sys.call("/etc/init.d/miniupnpd stop >/dev/null")
luci.sys.call("/etc/init.d/miniupnpd disable >/dev/null")
end
end
s:taboption("general", Flag, "enable_upnp", translate("Enable UPnP functionality")).default = "1"
s:taboption("general", Flag, "enable_natpmp", translate("Enable NAT-PMP functionality")).default = "1"
s:taboption("general", Flag, "secure_mode", translate("Enable secure mode"),
translate("Allow adding forwards only to requesting ip addresses")).default = "1"
s:taboption("general", Flag, "log_output", translate("Enable additional logging"),
translate("Puts extra debugging information into the system log"))
s:taboption("general", Value, "download", translate("Downlink"),
translate("Value in KByte/s, informational only")).rmempty = true
s:taboption("general", Value, "upload", translate("Uplink"),
translate("Value in KByte/s, informational only")).rmempty = true
port = s:taboption("general", Value, "port", translate("Port"))
port.datatype = "port"
port.default = 5000
s:taboption("advanced", Flag, "system_uptime", translate("Report system instead of daemon uptime")).default = "1"
s:taboption("advanced", Value, "uuid", translate("Device UUID"))
s:taboption("advanced", Value, "serial_number", translate("Announced serial number"))
s:taboption("advanced", Value, "model_number", translate("Announced model number"))
ni = s:taboption("advanced", Value, "notify_interval", translate("Notify interval"))
ni.datatype = "uinteger"
ni.placeholder = 30
ct = s:taboption("advanced", Value, "clean_ruleset_threshold", translate("Clean rules threshold"))
ct.datatype = "uinteger"
ct.placeholder = 20
ci = s:taboption("advanced", Value, "clean_ruleset_interval", translate("Clean rules interval"))
ci.datatype = "uinteger"
ci.placeholder = 600
pu = s:taboption("advanced", Value, "presentation_url", translate("Presentation URL"))
pu.placeholder = "http://192.168.1.1/"
lf = s:taboption("advanced", Value, "upnp_lease_file", translate("UPnP lease file"))
lf.placeholder = "/var/log/upnp.leases"
s2 = m:section(TypedSection, "perm_rule", translate("MiniUPnP ACLs"),
translate("ACLs specify which external ports may be redirected to which internal addresses and ports"))
s2.template = "cbi/tblsection"
s2.sortable = true
s2.anonymous = true
s2.addremove = true
s2:option(Value, "comment", translate("Comment"))
ep = s2:option(Value, "ext_ports", translate("External ports"))
ep.datatype = "portrange"
ep.placeholder = "0-65535"
ia = s2:option(Value, "int_addr", translate("Internal addresses"))
ia.datatype = "ip4addr"
ia.placeholder = "0.0.0.0/0"
ip = s2:option(Value, "int_ports", translate("Internal ports"))
ip.datatype = "portrange"
ip.placeholder = "0-65535"
ac = s2:option(ListValue, "action", translate("Action"))
ac:value("allow")
ac:value("deny")
return m
| apache-2.0 |
actionless/awesome | docs/05-awesomerc.md.lua | 1 | 9334 | local filename, rcfile, new_rcfile, rc_script = ...
local f = assert(io.open(filename, "w"))
f:write[[# Default configuration file documentation
This document explains the default `rc.lua` file provided by Awesome.
]]
-- Document sections of the file to guide new users to the right doc pages
local sections = {}
sections.DOC_REQUIRE_SECTION = [[
The Awesome API is distributed across many libraries (also called modules).
Here are the modules that we import:
<table class='widget_list' border=1>
<tr style='font-weight: bold;'>
<th align='center'>Library</th>
<th align='center'>Description</th>
</tr>
<tr><td>`gears`</td><td>Utilities such as color parsing and objects</td></tr>
<tr><td>`wibox`</td><td>Awesome own generic widget framework</td></tr>
<tr><td>`awful`</td><td>Everything related to window managment</td></tr>
<tr><td>`naughty`</td><td>Notifications</td></tr>
<tr><td>`ruled`</td><td>Define declarative rules on various events</td></tr>
<tr><td>`menubar`</td><td>XDG (application) menu implementation</td></tr>
<tr><td>`beautiful`</td><td>Awesome theme module</td></tr>
</table>
]]
sections.DOC_ERROR_HANDLING = [[
Awesome is a window managing framework. It allows its users great (ultimate?)
flexibility. However, it also allows the user to write invalid code. Here's a
non-exhaustive list of possible errors:
* Syntax: There is an `awesome -k` option available in the command line to
check the configuration file. Awesome cannot start with an invalid `rc.lua`
* Invalid APIs and type errors: Lua is a dynamic language. It doesn't have much
support for static/compile time checks. There is the `luacheck` utility to
help find some categories of errors. Those errors will cause Awesome to
"drop" the current call stack and start over. Note that if it cannot
reach the end of the `rc.lua` without errors, it will fall back to the
original file.
* Invalid logic: It is possible to write fully valid code that will render
Awesome unusable (like an infinite loop or blocking commands). In that case,
the best way to debug this is either using `print()` or using `gdb`. For
this, see the [Debugging tips Readme section](../documentation/01-readme.md.html)
* Deprecated APIs: The Awesome API is not frozen for eternity. After a decade
of development and recent changes to enforce consistency, it hasn't
changed much. This doesn't mean it won't change in the future. Whenever
possible, changes won't cause errors but will instead print a deprecation
message in the Awesome logs. These logs are placed in various places
depending on the distribution. By default, Awesome will print errors on
`stderr` and `stdout`.
]]
sections.DOC_LOAD_THEME = [[
To create custom themes, the easiest way is to copy the `default` theme folder
from `/usr/share/awesome/themes/` into `~/.config/awesome` and modify it.
Awesome currently doesn't behave well without a theme containing all the "basic"
variables such as `bg_normal`. To get a list of all official variables, see
the [appearance guide](../documentation/06-appearance.md.html).
]]
sections.DOC_DEFAULT_APPLICATIONS = [[
]]
sections.DOC_LAYOUT = [[
]]
sections.DOC_MENU = [[
]]
sections.TAGLIST_BUTTON = [[
]]
sections.TASKLIST_BUTTON = [[
]]
sections.DOC_FOR_EACH_SCREEN = [[
]]
sections.DOC_WIBAR = [[
]]
sections.DOC_SETUP_WIDGETS = [[
]]
sections.DOC_ROOT_BUTTONS = [[
]]
sections.DOC_GLOBAL_KEYBINDINGS = [[
<a id="global_keybindings" />
This section stores the global keybindings. A global keybinding is a shortcut
that will be executed when the key is pressed. It is different from
<a href="#client_keybindings">client keybindings</a>. A client keybinding
only works when a client is focused while a global one works all the time.
Each keybinding is stored in an `awful.key` object. When creating such an
object, you need to provide a list of modifiers, a key or keycode, a callback
function and extra metadata used for the `awful.hotkeys_popup` widget.
Common modifiers are:
<table class='widget_list' border=1>
<tr style='font-weight: bold;'>
<th align='center'>Name</th>
<th align='center'>Description</th>
</tr>
<tr><td>Mod4</td><td>Also called Super, Windows and Command ⌘</td></tr>
<tr><td>Mod1</td><td>Usually called Alt on PCs and Option on Macs</td></tr>
<tr><td>Shift</td><td>Both left and right shift keys</td></tr>
<tr><td>Control</td><td>Also called CTRL on some keyboards</td></tr>
</table>
Note that both `Mod2` and `Lock` are ignored by default. If you wish to
use them, add `awful.key.ignore_modifiers = {}` to your `rc.lua`. `Mod3`,
`Mod5` are usually not bound in most keyboard layouts. There is an X11 utility
called `xmodmap` to bind them. See
[the ARCH Linux Wiki](https://wiki.archlinux.org/index.php/xmodmap) for more
information.
The key or keycode is usually the same as the keyboard key, for example:
* "a"
* "Return"
* "Shift_R"
Each key also has a code. This code depends on the exact keyboard layout. It
can be obtained by reading the terminal output of the `xev` command. A keycode
based keybinding will look like `#123` where 123 is the keycode.
The callback has to be a function. Note that a function isn't the same as a
function call. If you use, for example, `awful.tag.viewtoggle()` as the
callback, you store the **result** of the function. If you wish to use that
function as a callback, just use `awful.tag.viewtoggle`. The same applies to
methods. If you have to add parameters to the callback, wrap them in another
function. For the toggle example, this would be
`function() awful.tag.viewtoggle(mouse.screen.tags[1]) end`.
Note that global keybinding callbacks have no argument. If you wish to act on
the current `client`, use the <a href="#client_keybindings">client keybindings</a>
table.
]]
sections.DOC_CLIENT_KEYBINDINGS = [[
<a id="client_keybindings" />
A client keybinding is a shortcut that will get the currently focused client
as its first callback argument. For example, to toggle a property, the callback
will look like `function(c) c.sticky = not c.sticky end`. For more information
about the keybinding syntax, see the
<a href="#global_keybindings">global keybindings</a> section.
]]
sections.DOC_NUMBER_KEYBINDINGS = [[
]]
sections.DOC_CLIENT_BUTTONS = [[
]]
sections.DOC_RULES = [[
]]
sections.DOC_GLOBAL_RULE = [[
]]
sections.DOC_FLOATING_RULE = [[
]]
sections.DOC_DIALOG_RULE = [[
]]
sections.DOC_TITLEBARS = [[
]]
sections.DOC_CSD_TITLEBARS = [[
For client side decorations, clients might request no titlebars via
Motif WM hints. To honor these hints, use:
`titlebars_enabled = function(c) return not c.requests_no_titlebar end`
See `client.requests_no_titlebar` for more details.
]]
-- Ask ldoc to generate links
local function add_links(line)
for _, module in ipairs {
"awful", "wibox", "gears", "naughty", "menubar", "beautiful"
} do
if line:match(module.."%.") then
line = line:gsub("("..module.."[.a-zA-Z]+)", "`%1`")
end
end
return " "..line.."\n"
end
-- Parse the default awesomerc.lua
local rc = assert(io.open(rcfile))
local doc_block = false
local output, output_script = {}, {[[
---------------------------------------------------------------------------
--- The default rc.lua file.
--
-- A copy of this file is usually installed in `/etc/xdg/awesome/`.
--
-- See [The declarative layout system](../documentation/05-awesomerc.md.html)
-- for a version with additional comments.
--
--]]}
for line in rc:lines() do
local tag = line:match("@([^@]+)@")
if not tag then
local section = line:match("--[ ]*{{{[ ]*(.*)")
if line == "-- }}}" or line == "-- {{{" then
-- Hide some noise
elseif section then
-- Turn Vim sections into markdown sections
if doc_block then
f:write("\n")
doc_block = false
end
f:write("## "..section.."\n")
elseif line:sub(1,2) == "--" then
-- Display "top level" comments are normal text.
if doc_block then
f:write("\n")
doc_block = false
end
f:write(line:sub(3).."\n")
else
-- Write the code in <code> sections
if not doc_block then
f:write("\n")
doc_block = true
end
f:write(add_links(line))
end
table.insert(output, line)
table.insert(output_script, "-- "..line)
else
-- Take the documentation found in this file and append it
if doc_block then
f:write("\n")
doc_block = false
end
if sections[tag] then
f:write(sections[tag])
else
f:write(" \n\n")
end
end
end
f:write("\n")
f:close()
local rc_lua = assert(io.open(new_rcfile, "w"))
rc_lua:write(table.concat(output, "\n"))
rc_lua:close()
table.insert(output_script, "-- @script rc.lua")
rc_script = assert(io.open(rc_script, "w"))
rc_script:write(table.concat(output_script, "\n"))
rc_script:close()
| gpl-2.0 |
Fatalerror66/ffxi-a | scripts/zones/Arrapago_Reef/npcs/qm10.lua | 19 | 2978 | -----------------------------------
-- Area: Arrapago Reef
-- NPC: ???
-- Starts: Corsair Af1 ,AF2 ,AF3
-- @pos 457.128 -8.249 60.795 54
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/Arrapago_Reef/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local mJob = player:getMainJob();
local mLvl = player:getMainLvl();
local equipedForAll = player:getQuestStatus(AHT_URHGAN,EQUIPED_FOR_ALL_OCCASIONS);
local NoStringsAttached = player:getQuestStatus(AHT_URHGAN,NO_STRINGS_ATTACHED);
local NoStringsAttachedProgress = player:getVar("NoStringsAttachedProgress");
if (equipedForAll == QUEST_AVAILABLE and mJob == JOB_COR and mLvl >= AF1_QUEST_LEVEL) then
player:startEvent(0x0E4);
elseif(equipedForAll == QUEST_ACCEPTED and player:getVar("EquipedforAllOccasions") ==3) then
player:startEvent(0x0E7);
player:delKeyItem(WHEEL_LOCK_TRIGGER);
elseif(equipedForAll == QUEST_COMPLETED and player:getQuestStatus(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS) == QUEST_AVAILABLE and mJob == JOB_COR and mLvl >= AF2_QUEST_LEVEL) then
player:startEvent(0x0E8);
elseif(player:getVar("NavigatingtheUnfriendlySeas") ==4) then
player:startEvent(0x0E9);
elseif(NoStringsAttachedProgress == 3) then
player:startEvent(0x00d6); -- "You see an old, dented automaton..."
else
player:messageSpecial(8327); -- "There is nothing else of interest here."
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 == 0x0E4) then
player:addQuest(AHT_URHGAN,EQUIPED_FOR_ALL_OCCASIONS);
player:setVar("EquipedforAllOccasions",1);
elseif(csid== 0x0E7) then
player:setVar("EquipedforAllOccasions",4);
elseif(csid == 0x0E8) then
player:addQuest(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS);
player:setVar("NavigatingtheUnfriendlySeas",1);
elseif(csid == 0x0E9) then
player:addItem(15601) -- Receive item Corsairs culottes
player:messageSpecial(ITEM_OBTAINED,15601);
player:completeQuest(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS);
player:setVar("NavigatingtheUnfriendlySeas",0);
player:setVar("HydrogauageTimer",0);
elseif(csid == 0x00d6) then
player:addKeyItem(798);
player:messageSpecial(KEYITEM_OBTAINED,ANTIQUE_AUTOMATON);
player:setVar("NoStringsAttachedProgress",4);
end
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Norg/npcs/Muzaffar.lua | 2 | 3189 | -----------------------------------
-- Area: Norg
-- NPC: Muzaffar
-- Standard Info NPC
-- Quests: Black Market
-- @zone 252
-- @pos 16.678, -2.044, -14.600
-----------------------------------
require("scripts/zones/Norg/TextIDs");
require("scripts/globals/titles");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local count = trade:getItemCount();
local NorthernFurs = trade:hasItemQty(1199,4);
local EasternPottery = trade:hasItemQty(1200,4);
local SouthernMummies = trade:hasItemQty(1201,4);
if(player:getQuestStatus(NORG,BLACK_MARKET) == QUEST_ACCEPTED or player:getQuestStatus(NORG,BLACK_MARKET) == QUEST_COMPLETED) then
if(NorthernFurs == true and count == 4) then
player:tradeComplete();
player:startEvent(0x0011, 1199, 1199);
elseif(EasternPottery == true and count == 4) then
player:tradeComplete();
player:startEvent(0x0012, 1200, 1200);
elseif(SouthernMummies == true and count == 4) then
player:tradeComplete();
player:startEvent(0x0013, 1201, 1201);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getQuestStatus(NORG,BLACK_MARKET) == QUEST_ACCEPTED or player:getQuestStatus(NORG,BLACK_MARKET) == QUEST_COMPLETED) then
player:startEvent(0x0010);
else
player:startEvent(0x000F);
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 == 0x000F and option == 1) then
player:addQuest(NORG,BLACK_MARKET);
elseif(csid == 0x0011) then
player:addGil(GIL_RATE*1500);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500);
if(player:getQuestStatus(NORG,BLACK_MARKET) == QUEST_ACCEPTED) then
player:completeQuest(NORG,BLACK_MARKET);
end
player:addFame(NORG,40*NORG_FAME);
player:addTitle(BLACK_MARKETEER);
player:startEvent(0x0014);
elseif(csid == 0x0012) then
player:addGil(GIL_RATE*2000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*2000);
if(player:getQuestStatus(NORG,BLACK_MARKET) == QUEST_ACCEPTED) then
player:completeQuest(NORG,BLACK_MARKET);
end
player:addFame(NORG,50*NORG_FAME);
player:addTitle(BLACK_MARKETEER);
player:startEvent(0x0014);
elseif(csid == 0x0013) then
player:addGil(GIL_RATE*3000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000);
if(player:getQuestStatus(NORG,BLACK_MARKET) == QUEST_ACCEPTED) then
player:completeQuest(NORG,BLACK_MARKET);
end
player:addFame(NORG,80*NORG_FAME);
player:addTitle(BLACK_MARKETEER);
player:startEvent(0x0014);
end
end;
| gpl-3.0 |
capr/fbclient-alien | unit-tests/test_wrapper.lua | 2 | 8323 | #!/usr/bin/lua
--[[
Test unit for wrapper.lua
]]
local config = require 'test_config'
local function asserteq(a,b,s)
assert(a==b,s or string.format('%s ~= %s', tostring(a), tostring(b)))
end
function test_everything(env)
require 'fbclient.error_codes'
local fbclient = {
svapi = require 'fbclient.status_vector',
binding = require 'fbclient.binding',
wrapper = require 'fbclient.wrapper',
error_codes = require 'fbclient.error_codes',
event = require 'fbclient.event',
blob = require 'fbclient.blob',
util = require 'fbclient.util',
db_info = require 'fbclient.db_info',
tr_info = require 'fbclient.tr_info',
sql_info = require 'fbclient.sql_info',
blob_info = require 'fbclient.blob_info',
alien = require 'alien',
}
local api = fbclient.wrapper
local dump = fbclient.util.dump
local asserts = fbclient.util.asserts
local post20 = not env.server_ver:find'^2%.0'
local post21 = post20 and not env.server_ver:find'^2%.1'
local db_opts = {
isc_dpb_user_name = env.username,
isc_dpb_password = env.password,
}
local fbapi = fbclient.binding.new(env.libname)
local sv = fbclient.svapi.new()
--upvalues from here on: fbapi, sv
local function ib_version()
print(string.format('INTERBASE compatibility version: %d.%d',api.ib_version(fbapi)))
end
local function create(dbname)
--note: param substitution is not available with db_create(), hence the string.format() thing!
local dbh = api.db_create_sql(fbapi, sv,
string.format("create database '%s' user '%s' password '%s'",
dbname, env.username, env.password),
env.dialect)
print('CREATED '..dbname)
return dbh
end
local function attach(dbname)
local dbh = api.db_attach(fbapi,sv,dbname,db_opts)
print('ATTACHED '..dbname)
return dbh
end
local function drop(dbh)
api.db_drop(fbapi,sv,dbh)
print('DROPPED')
end
local function detatch(dbh)
api.db_detatch(fbapi,sv,dbh)
end
local function test_attachment(dbh)
--upvalues from here on: fbapi, sv, dbh
local function db_version()
print'DB VERSION:'; dump(api.db_version(fbapi, dbh),'\n')
end
local function test_events()
do return end -- not finished yet!!
local event = fbclient.event
local e = event.new('STUFF')
event.wait(sv, dbh, e)
local called = false
local eh = event.listen(sv, dbh, e, function(...) called = true; print('event counts: ',...) end)
query(sv, dbh, 'execute procedure test_events')
while not called do print('.') end
event.cancel(sv, dbh, eh)
end
local function test_tpb()
local trh = api.tr_start(fbapi, sv, dbh)
api.dsql_execute_immediate(fbapi, sv, dbh, trh, 'create table test_tr1(id integer)')
api.dsql_execute_immediate(fbapi, sv, dbh, trh, 'create table test_tr2(id integer)')
api.tr_commit(fbapi, sv, trh)
local tpb = {
isc_tpb_write=true,
isc_tpb_read_committed=true,
isc_tpb_wait=true,
isc_tpb_no_rec_version=true,
isc_tpb_lock_timeout=10,
{'isc_tpb_shared', 'isc_tpb_lock_write', 'TEST_TR1'},
{'isc_tpb_protected', 'isc_tpb_lock_read', 'TEST_TR2'},
}
local trh = api.tr_start(fbapi, sv, dbh, tpb)
print'TRANSACTION started (with table reservation options)'
--TODO: how to test if table reservation options are in effect? they were accepted alright.
api.tr_commit_retaining(fbapi, sv, trh)
print'TRANSACTION commit-retained'
api.tr_rollback_retaining(fbapi, sv, trh)
print'TRANSACTION rollback-retained'
api.tr_rollback(fbapi, sv, trh)
print'TRANSACTION rolled back'
end
local function test_db_info()
local tr1 = api.tr_start(fbapi, sv, dbh)
local tr2 = api.tr_start(fbapi, sv, dbh)
local t = {
isc_info_db_id=true,
isc_info_reads=true,
isc_info_writes=true,
isc_info_fetches=true,
isc_info_marks=true,
isc_info_implementation=true,
isc_info_isc_version=true,
isc_info_base_level=true,
isc_info_page_size=true,
isc_info_num_buffers=true,
--TODO: isc_info_limbo=true,
isc_info_current_memory=true,
isc_info_max_memory=true,
--error (expected): isc_info_window_turns=true,
--error (expected): isc_info_license=true,
isc_info_allocation=true,
isc_info_attachment_id=true,
isc_info_read_seq_count=true,
isc_info_read_idx_count=true,
isc_info_insert_count=true,
isc_info_update_count=true,
isc_info_delete_count=true,
isc_info_backout_count=true,
isc_info_purge_count=true,
isc_info_expunge_count=true,
isc_info_sweep_interval=true,
isc_info_ods_version=true,
isc_info_ods_minor_version=true,
isc_info_no_reserve=true,
isc_info_forced_writes=true,
isc_info_user_names=true,
isc_info_page_errors=true,
isc_info_record_errors=true,
isc_info_bpage_errors=true,
isc_info_dpage_errors=true,
isc_info_ipage_errors=true,
isc_info_ppage_errors=true,
isc_info_tpage_errors=true,
isc_info_set_page_buffers=true,
isc_info_db_sql_dialect=true,
isc_info_db_read_only=true,
isc_info_db_size_in_pages=true,
frb_info_att_charset=true,
isc_info_db_class=true,
isc_info_firebird_version=true,
isc_info_oldest_transaction=true,
isc_info_oldest_active=true,
isc_info_oldest_snapshot=true,
isc_info_next_transaction=true,
isc_info_db_provider=true,
isc_info_active_transactions=true,
isc_info_active_tran_count=post20 or nil,
isc_info_creation_date=post20 or nil,
isc_info_db_file_size=post20 or nil,
fb_info_page_contents = post21 and 1 or nil,
}
local info = api.db_info(fbapi, sv, dbh, t)
print'DB info:'; dump(info)
if post21 then
asserteq(#info.fb_info_page_contents, info.isc_info_page_size)
end
if post20 then
asserteq(info.isc_info_active_tran_count, 2)
end
--TODO: how to assert that all this info is accurate?
api.tr_commit(fbapi, sv, tr1)
api.tr_commit(fbapi, sv, tr2)
end
local function test_tr_info()
local trh = api.tr_start(fbapi, sv, dbh, {
isc_tpb_write=true,
isc_tpb_read_committed=true,
isc_tpb_wait=true,
isc_tpb_no_rec_version=true,
isc_tpb_lock_timeout=10,
})
local t = {
isc_info_tra_id=true,
isc_info_tra_oldest_interesting=post20 or nil,
isc_info_tra_oldest_snapshot=post20 or nil,
isc_info_tra_oldest_active=post20 or nil,
isc_info_tra_isolation=post20 or nil,
isc_info_tra_access=post20 or nil,
isc_info_tra_lock_timeout=post20 or nil,
}
local info = api.tr_info(fbapi, sv, trh, t)
print'TRANSACTION info:'; dump(info)
if post20 then
asserteq(info.isc_info_tra_isolation[1],'isc_info_tra_read_committed')
asserteq(info.isc_info_tra_isolation[2],'isc_info_tra_no_rec_version')
asserteq(info.isc_info_tra_access,'isc_info_tra_readwrite')
asserteq(info.isc_info_tra_lock_timeout,10)
end
--TODO: how to assert that all this info is accurate?
api.tr_commit(fbapi, sv, trh)
end
local function test_sql_info()
local trh = api.tr_start(fbapi, sv, dbh)
local sth = api.dsql_alloc_statement(fbapi, sv, dbh)
local params,columns = api.dsql_prepare(fbapi, sv, dbh, trh, sth, 'select rdb$relation_id from rdb$database where rdb$relation_id = ?', env.dialect)
local info = api.dsql_info(fbapi, sv, sth, {
--isc_info_sql_select=true, --TODO
--isc_info_sql_bind=true, --TODO
isc_info_sql_stmt_type=true,
isc_info_sql_get_plan=true,
isc_info_sql_records=true,
isc_info_sql_batch_fetch=true,
})
print'SQL info:'; dump(info)
--api.dsql_free_cursor(fbapi, sv, sth)
api.dsql_free_statement(fbapi, sv, sth)
api.tr_commit(fbapi, sv, trh)
end
local function test_dpb()
--TODO
end
--perform the actual testing on the attachment
db_version()
test_events()
test_tpb()
test_db_info()
test_tr_info()
test_sql_info()
test_dpb()
end --test_attachment()
--perform the actual testing on the library
ib_version()
-- in case the database is still alive from a previous failed test, drop it.
pcall(function() dbh = attach(env.database); drop(dbh) end)
--alternative drop method without attachment :)
os.remove(env.database_file)
local dbh = create(env.database)
test_attachment(dbh)
drop(dbh)
return 1,0
end
--local comb = {{lib='fbembed',ver='2.5.0'}}
config.run(test_everything,comb,nil,...)
| mit |
frutjus/OpenRA | mods/cnc/maps/gdi04a/gdi04a.lua | 7 | 4742 | AutoTrigger = { CPos.New(51, 47), CPos.New(52, 47), CPos.New(53, 47), CPos.New(54, 47) }
GDIHeliTrigger = { CPos.New(27, 55), CPos.New(27, 56), CPos.New(28, 56), CPos.New(28, 57), CPos.New(28, 58), CPos.New(28, 59)}
Nod1Units = { "e1", "e1", "e3", "e3" }
Auto1Units = { "e1", "e1", "e3" }
KillsUntilReinforcements = 12
HeliDelay = { 83, 137, 211 }
GDIReinforcements = { "e2", "e2", "e2", "e2", "e2" }
GDIReinforcementsWaypoints = { GDIReinforcementsEntry.Location, GDIReinforcementsWP1.Location }
NodHelis = {
{ DateTime.Seconds(HeliDelay[1]), { NodHeliEntry.Location, NodHeliLZ1.Location }, { "e1", "e1", "e3" } },
{ DateTime.Seconds(HeliDelay[2]), { NodHeliEntry.Location, NodHeliLZ2.Location }, { "e1", "e1", "e1", "e1" } },
{ DateTime.Seconds(HeliDelay[3]), { NodHeliEntry.Location, NodHeliLZ3.Location }, { "e1", "e1", "e3" } }
}
SendHeli = function(heli)
units = Reinforcements.ReinforceWithTransport(nod, "tran", heli[3], heli[2], { heli[2][1] })
Utils.Do(units[2], function(actor)
actor.Hunt()
Trigger.OnIdle(actor, actor.Hunt)
Trigger.OnKilled(actor, KillCounter)
end)
Trigger.AfterDelay(heli[1], function() SendHeli(heli) end)
end
SendGDIReinforcements = function()
Media.PlaySpeechNotification(gdi, "Reinforce")
Reinforcements.ReinforceWithTransport(gdi, "apc", GDIReinforcements, GDIReinforcementsWaypoints, nil, function(apc, team)
table.insert(team, apc)
Trigger.OnAllKilled(team, function() Trigger.AfterDelay(DateTime.Seconds(5), SendGDIReinforcements) end)
Utils.Do(team, function(unit) unit.Stance = "Defend" end)
end)
end
BuildNod1 = function()
if HandOfNod.IsDead then
return
end
local func = function(team)
Utils.Do(team, function(actor)
Trigger.OnIdle(actor, actor.Hunt)
Trigger.OnKilled(actor, KillCounter)
end)
Trigger.OnAllKilled(team, BuildNod1)
end
if not HandOfNod.Build(Nod1Units, func) then
Trigger.AfterDelay(DateTime.Seconds(5), BuildNod1)
end
end
BuildAuto1 = function()
if HandOfNod.IsDead then
return
end
local func = function(team)
Utils.Do(team, function(actor)
Trigger.OnIdle(actor, actor.Hunt)
Trigger.OnKilled(actor, KillCounter)
end)
end
if not HandOfNod.IsDead and HandOfNod.Build(Auto1Units, func) then
Trigger.AfterDelay(DateTime.Seconds(5), BuildAuto1)
end
end
kills = 0
KillCounter = function() kills = kills + 1 end
ReinforcementsSent = false
Tick = function()
nod.Cash = 1000
if not ReinforcementsSent and kills >= KillsUntilReinforcements then
ReinforcementsSent = true
gdi.MarkCompletedObjective(reinforcementsObjective)
SendGDIReinforcements()
end
if gdi.HasNoRequiredUnits() then
Trigger.AfterDelay(DateTime.Seconds(1), function() gdi.MarkFailedObjective(gdiObjective) end)
end
end
SetupWorld = function()
Utils.Do(nod.GetGroundAttackers(nod), function(unit)
Trigger.OnKilled(unit, KillCounter)
end)
Utils.Do(gdi.GetGroundAttackers(), function(unit)
unit.Stance = "Defend"
end)
Hunter1.Hunt()
Hunter2.Hunt()
Trigger.OnRemovedFromWorld(crate, function() gdi.MarkCompletedObjective(gdiObjective) end)
end
WorldLoaded = function()
gdi = Player.GetPlayer("GDI")
nod = Player.GetPlayer("Nod")
SetupWorld()
Trigger.OnObjectiveAdded(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(gdi, function()
Media.PlaySpeechNotification(gdi, "Win")
end)
Trigger.OnPlayerLost(gdi, function()
Media.PlaySpeechNotification(gdi, "Lose")
end)
gdiObjective = gdi.AddPrimaryObjective("Retrieve the crate with the stolen rods.")
reinforcementsObjective = gdi.AddSecondaryObjective("Eliminate " .. KillsUntilReinforcements .. " Nod units for reinforcements.")
nod.AddPrimaryObjective("Defend against the GDI forces.")
BuildNod1()
Utils.Do(NodHelis, function(heli)
Trigger.AfterDelay(heli[1], function() SendHeli(heli) end)
end)
autoTrigger = false
Trigger.OnEnteredFootprint(AutoTrigger, function(a, id)
if not autoTrigger and a.Owner == gdi then
autoTrigger = true
Trigger.RemoveFootprintTrigger(id)
BuildAuto1()
end
end)
gdiHeliTrigger = false
Trigger.OnEnteredFootprint(GDIHeliTrigger, function(a, id)
if not gdiHeliTrigger and a.Owner == gdi then
gdiHeliTrigger = true
Trigger.RemoveFootprintTrigger(id)
Reinforcements.ReinforceWithTransport(gdi, "tran", nil, { GDIHeliEntry.Location, GDIHeliLZ.Location })
end
end)
Camera.Position = Actor56.CenterPosition
end
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Windurst_Waters/npcs/Npopo.lua | 5 | 1038 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Npopo
-- Type: Standard NPC
-- @zone: 238
-- @pos: -35.464 -5.999 239.120
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x010d);
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 |
raziel-carvajal/splay-daemon | src/lua/modules/test-json.lua | 2 | 2960 | --Benchmark json's encode/decode
misc=require"splay.misc"
json=require"json"
function test_encode(data)
return json.encode(data)
end
-- FUNCTIONAL TESTS
-- PRIMITIVE TYPES
t1=nil --expected JSON: null
t1_enc=json.encode(t1)
print("Expected=\"nil\", got->",t1_enc)
assert(t1_enc=="null")
--t1=test_encode --expected JSON for encoded function: null (old json does not support this)
--t1_enc=json.encode(t1)
--print("Expected=\"nil\", got->",t1_enc)
--assert(t1_enc=="null")
t1="helo" --expected JSON: "helo"
t1_enc=json.encode(t1)
print("Expected=\"helo\", got->",t1_enc)
assert(t1_enc=="\"helo\"")
--
--SIMPLE ARRAYS
t1={1,2,3,4} --expected JSON: [1,2,3,4]
t1_enc=json.encode(t1)
print(t1_enc)
assert(t1_enc=="[1,2,3,4]")
--NESTED ARRAYS
t1={1,"a",{"b"}} --expected JSON: [1,"a",["b"]]
t1_enc=json.encode(t1)
print(t1_enc)
assert(t1_enc=="[1,\"a\",[\"b\"]]")
----TEST SIMPLE TABLE
t2={} --expected JSON: {"a":"b"}
t2["a"]="b"
t2_enc=json.encode(t2)
print(t2_enc)
assert(t2_enc=="{\"a\":\"b\"}","Expected {\"a\":\"b\"} but was "..t2_enc)
t2={} --expected JSON: {"a":"b","c":["d"]}
t2["a"]="b"
t2["c"]={"d"}
t2_enc=json.encode(t2)
print(t2_enc)
assert(t2_enc=="{\"a\":\"b\",\"c\":[\"d\"]}")
t3={} --expected JSON: {"a":"b","c":["d"],"n":{"e":"f"}}
t3["e"]="f"
t2["n"]=t3
t2_enc=json.encode(t2)
print(t2_enc)
assert(t2_enc=="{\"a\":\"b\",\"c\":[\"d\"],\"n\":{\"e\":\"f\"}}")
emtpy_t_enc=json.encode("")
print("EMPTY_T_ENC:",emtpy_t_enc)
assert(emtpy_t_enc=="\"\"")
--PERFORMANCE TEST
data_sizes={1024,1024*10,1024*100,2*1024*100,4*1024*100,6*1024*100}
print("Bench encode numbers")
for k,v in pairs(data_sizes) do
local gen=tonumber(misc.gen_string(v))
start=misc.time()
enc_data=test_encode(gen)
print(v, misc.time()-start)
end
print("Bench encode strings")
for k,v in pairs(data_sizes) do
local gen=misc.gen_string(v)
start=misc.time()
enc_data=test_encode(gen)
print(v, misc.time()-start)
end
print("Bench array with numbes")
for k,v in pairs(data_sizes) do
local gen={tonumber(misc.gen_string(v))}
start=misc.time()
enc_data=test_encode(gen)
print(v, misc.time()-start)
end
print("Bench array with strings")
for k,v in pairs(data_sizes) do
local gen={misc.gen_string(v)}
start=misc.time()
enc_data=test_encode(gen)
print(v, misc.time()-start)
end
print("Bench nested arrays with fixed-size string")
for k,v in pairs(data_sizes) do
local gen="a"
for i=1,(v/100) do --to avoid stackoverlow
gen={gen}
end
start=misc.time()
enc_data=test_encode(gen)
print((v/100), misc.time()-start)
end
print("Bench nested arrays with growing-size string")
for k,v in pairs(data_sizes) do
print("Datasize: ",(v/1000).."K")
local gen= misc.gen_string(v)
for i=1,(v/100) do --to avoid stackoverlow
gen={gen}
end
start=misc.time()
print("Memory before:",collectgarbage( "count" ))
enc_data=test_encode(gen)
print("Memory after: ",collectgarbage( "count" ))
print((v/1000).."K", misc.to_dec_string(misc.time()-start))
end
| gpl-3.0 |
mys007/nn | TemporalSubSampling.lua | 44 | 1378 | local TemporalSubSampling, parent = torch.class('nn.TemporalSubSampling', 'nn.Module')
function TemporalSubSampling:__init(inputFrameSize, kW, dW)
parent.__init(self)
dW = dW or 1
self.inputFrameSize = inputFrameSize
self.kW = kW
self.dW = dW
self.weight = torch.Tensor(inputFrameSize)
self.bias = torch.Tensor(inputFrameSize)
self.gradWeight = torch.Tensor(inputFrameSize)
self.gradBias = torch.Tensor(inputFrameSize)
self:reset()
end
function TemporalSubSampling:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1/math.sqrt(self.kW)
end
if nn.oldSeed then
self.weight:apply(function()
return torch.uniform(-stdv, stdv)
end)
self.bias:apply(function()
return torch.uniform(-stdv, stdv)
end)
else
self.weight:uniform(-stdv, stdv)
self.bias:uniform(-stdv, stdv)
end
end
function TemporalSubSampling:updateOutput(input)
return input.nn.TemporalSubSampling_updateOutput(self, input)
end
function TemporalSubSampling:updateGradInput(input, gradOutput)
if self.gradInput then
return input.nn.TemporalSubSampling_updateGradInput(self, input, gradOutput)
end
end
function TemporalSubSampling:accGradParameters(input, gradOutput, scale)
return input.nn.TemporalSubSampling_accGradParameters(self, input, gradOutput, scale)
end
| bsd-3-clause |
jiang42/Algorithm-Implementations | Newton_Raphson/Lua/Yonaba/newtonraphson_test.lua | 26 | 1041 | -- Tests for derivative.lua
local nrsolver = require 'newtonraphson'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
local function fuzzyEqual(a, b, eps)
local eps = eps or 1e-4
return (math.abs(a - b) < eps)
end
run('Solving x^2 - 2 = 0', function()
local f = function(x) return x * x - 2.0 end
assert(fuzzyEqual(nrsolver(f,-2), -math.sqrt(2)))
assert(fuzzyEqual(nrsolver(f, 2), math.sqrt(2)))
end)
run('Solving ln(x) - exp(x) = 0', function()
local f = function(x) return math.log(x) - math.exp(1) end
assert(fuzzyEqual(nrsolver(f, 0.1), 15.1542))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
woesdo/XY | plugins/anti_chat.lua | 62 | 1069 |
antichat = {}-- An empty table for solving multiple kicking problem
do
local function run(msg, matches)
if is_momod(msg) then -- Ignore mods,owner,admins
return
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['lock_chat'] then
if data[tostring(msg.to.id)]['settings']['lock_chat'] == 'yes' then
if antichat[msg.from.id] == true then
return
end
send_large_msg("chat#id".. msg.to.id , "chat is not allowed here")
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked (chat was locked) ")
chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false)
antichat[msg.from.id] = true
return
end
end
return
end
local function cron()
antichat = {} -- Clear antichat table
end
return {
patterns = {
"([\216-\219][\128-\191])"
},
run = run,
cron = cron
}
end
--Copyright; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
sapohl/data-pipeline | hindsight/io_modules/derived_stream/redshift.lua | 5 | 1880 | -- 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 M = {}
local tostring = tostring
local type = type
local date = require "os".date
local floor = require "math".floor
local gsub = require "string".gsub
setfenv(1, M) -- Remove external access to contain everything in the module
VARCHAR_MAX_LENGTH = 65535
function strip_nonprint(v)
-- A CHAR column can only contain single-byte characters
-- http://docs.aws.amazon.com/redshift/latest/dg/r_Character_types.html
-- for our use restrict it to printable chars
if v == nil then return end
if type(v) ~= "string" then v = tostring(v) end
return gsub(v, "[^\032-\126]", "?")
end
function esc_timestamp(v, default)
if type(v) ~= "number" or v > 4294967296e9 or v < 0 then
return default
end
return date("%Y-%m-%d %H:%M:%S.", floor(v / 1e9)) .. tostring(floor(v % 1e9 / 1e3))
end
function esc_smallint(v, default)
if type(v) ~= "number" or v > 32767 or v < -32767 then
return default
end
return tostring(floor(v))
end
function esc_integer(v, default)
if type(v) ~= "number" or v > 2147483647 or v < -2147483647 then
return default
end
return tostring(floor(v))
end
function esc_bigint(v, default)
if type(v) ~= "number" then return default end
return tostring(floor(v))
end
function esc_double(v, default)
if type(v) ~= "number"then return default end
if v ~= v then return "NaN" end
if v == 1/0 then return "Infinity" end
if v == -1/0 then return "-Infinity" end
return tostring(v)
end
function esc_boolean(v, default)
if type(v) ~= "boolean" then return default end
if v then return "TRUE" end
return "FALSE"
end
return M
| mpl-2.0 |
kidaa/FFXIOrgins | scripts/commands/givekeyitem.lua | 2 | 1065 | ---------------------------------------------------------------------------------------------------
-- func: givekeyitem
-- auth: Link :: Modded by atom0s.
-- desc: Gives a key item to the target player.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "si"
};
function onTrigger(player, target, keyId)
if (target == nil or keyId == nil) then
player:PrintToPlayer("You must enter a valid player name and keyitem id.");
return;
end
local targ = GetPlayerByName( target );
if (targ == nil) then
player:PrintToPlayer( string.format( "Invalid player '%s' given.", target ) );
return;
end
-- Load needed text ids for players current zone..
local TextIDs = "scripts/zones/" .. player:getZoneName() .. "/TextIDs";
package.loaded[TextIDs] = nil;
require(TextIDs);
-- Give the key item to the target..
targ:addKeyItem( keyId );
targ:messageSpecial( KEYITEM_OBTAINED, keyId );
end | gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Windurst_Waters_[S]/npcs/Emhi_Tchaoryo.lua | 38 | 1061 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Emhi Tchaoryo
-- Type: Campaign Ops Overseer
-- @zone: 94
-- @pos 10.577 -2.478 32.680
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0133);
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.