repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
FFXIOrgins/FFXIOrgins | scripts/zones/Port_Bastok/npcs/Kurando.lua | 38 | 2161 | -----------------------------------
-- Area: Port Bastok
-- NPC: Kurando
-- Type: Quest Giver
-- @zone: 236
-- @pos -23.887 3.898 0.870
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Bastok/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/titles");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(BASTOK,FEAR_OF_FLYING) == QUEST_ACCEPTED) then
if (trade:hasItemQty(4526,1) and trade:getItemCount() == 1) then
player:startEvent(0x00AB); -- Quest Completion Dialogue
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local FearofFlying = player:getQuestStatus(BASTOK,FEAR_OF_FLYING);
-- csid 0x00Ad ?
if (FearofFlying == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >=3) then
player:startEvent(0x00AA); -- Quest Start Dialogue
elseif (FearofFlying == QUEST_COMPLETED) then
player:startEvent(0x00AC); -- Dialogue after Completion
else
player:startEvent(0x001c); -- Default 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 == 0x00AA) then
player:addQuest(BASTOK,FEAR_OF_FLYING);
elseif (csid == 0x00AB) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13113);
else
player:tradeComplete();
player:addItem(13113,1);
player:messageSpecial(ITEM_OBTAINED,13113);
player:setTitle(AIRSHIP_DENOUNCER);
player:completeQuest(BASTOK,FEAR_OF_FLYING);
player:addFame(BASTOK,BAS_FAME*30);
end
end
end; | gpl-3.0 |
hb9cwp/snabbswitch | lib/ljsyscall/syscall/netbsd/nr.lua | 24 | 9205 | -- NetBSD syscall numbers
local nr = {
SYS = {
syscall = 0,
exit = 1,
fork = 2,
read = 3,
write = 4,
open = 5,
close = 6,
compat_50_wait4 = 7,
compat_43_ocreat = 8,
link = 9,
unlink = 10,
chdir = 12,
fchdir = 13,
compat_50_mknod = 14,
chmod = 15,
chown = 16,
["break"] = 17,
compat_20_getfsstat = 18,
compat_43_olseek = 19,
getpid = 20,
compat_40_mount = 21,
unmount = 22,
setuid = 23,
getuid = 24,
geteuid = 25,
ptrace = 26,
recvmsg = 27,
sendmsg = 28,
recvfrom = 29,
accept = 30,
getpeername = 31,
getsockname = 32,
access = 33,
chflags = 34,
fchflags = 35,
sync = 36,
kill = 37,
compat_43_stat43 = 38,
getppid = 39,
compat_43_lstat43 = 40,
dup = 41,
pipe = 42,
getegid = 43,
profil = 44,
ktrace = 45,
compat_13_sigaction13 = 46,
getgid = 47,
compat_13_sigprocmask13 = 48,
__getlogin = 49,
__setlogin = 50,
acct = 51,
compat_13_sigpending13 = 52,
compat_13_sigaltstack13 = 53,
ioctl = 54,
compat_12_oreboot = 55,
revoke = 56,
symlink = 57,
readlink = 58,
execve = 59,
umask = 60,
chroot = 61,
compat_43_fstat43 = 62,
compat_43_ogetkerninfo = 63,
compat_43_ogetpagesize = 64,
compat_12_msync = 65,
vfork = 66,
sbrk = 69,
sstk = 70,
compat_43_ommap = 71,
vadvise = 72,
munmap = 73,
mprotect = 74,
madvise = 75,
mincore = 78,
getgroups = 79,
setgroups = 80,
getpgrp = 81,
setpgid = 82,
compat_50_setitimer = 83,
compat_43_owait = 84,
compat_12_oswapon = 85,
compat_50_getitimer = 86,
compat_43_ogethostname = 87,
compat_43_osethostname = 88,
compat_43_ogetdtablesize = 89,
dup2 = 90,
fcntl = 92,
compat_50_select = 93,
fsync = 95,
setpriority = 96,
compat_30_socket = 97,
connect = 98,
compat_43_oaccept = 99,
getpriority = 100,
compat_43_osend = 101,
compat_43_orecv = 102,
compat_13_sigreturn13 = 103,
bind = 104,
setsockopt = 105,
listen = 106,
compat_43_osigvec = 108,
compat_43_osigblock = 109,
compat_43_osigsetmask = 110,
compat_13_sigsuspend13 = 111,
compat_43_osigstack = 112,
compat_43_orecvmsg = 113,
compat_43_osendmsg = 114,
compat_50_gettimeofday = 116,
compat_50_getrusage = 117,
getsockopt = 118,
readv = 120,
writev = 121,
compat_50_settimeofday = 122,
fchown = 123,
fchmod = 124,
compat_43_orecvfrom = 125,
setreuid = 126,
setregid = 127,
rename = 128,
compat_43_otruncate = 129,
compat_43_oftruncate = 130,
flock = 131,
mkfifo = 132,
sendto = 133,
shutdown = 134,
socketpair = 135,
mkdir = 136,
rmdir = 137,
compat_50_utimes = 138,
compat_50_adjtime = 140,
compat_43_ogetpeername = 141,
compat_43_ogethostid = 142,
compat_43_osethostid = 143,
compat_43_ogetrlimit = 144,
compat_43_osetrlimit = 145,
compat_43_okillpg = 146,
setsid = 147,
compat_50_quotactl = 148,
compat_43_oquota = 149,
compat_43_ogetsockname = 150,
nfssvc = 155,
compat_43_ogetdirentries = 156,
compat_20_statfs = 157,
compat_20_fstatfs = 158,
compat_30_getfh = 161,
compat_09_ogetdomainname = 162,
compat_09_osetdomainname = 163,
compat_09_ouname = 164,
sysarch = 165,
compat_10_osemsys = 169,
compat_10_omsgsys = 170,
compat_10_oshmsys = 171,
pread = 173,
pwrite = 174,
compat_30_ntp_gettime = 175,
ntp_adjtime = 176,
setgid = 181,
setegid = 182,
seteuid = 183,
lfs_bmapv = 184,
lfs_markv = 185,
lfs_segclean = 186,
compat_50_lfs_segwait = 187,
compat_12_stat12 = 188,
compat_12_fstat12 = 189,
compat_12_lstat12 = 190,
pathconf = 191,
fpathconf = 192,
getrlimit = 194,
setrlimit = 195,
compat_12_getdirentries = 196,
mmap = 197,
__syscall = 198,
lseek = 199,
truncate = 200,
ftruncate = 201,
__sysctl = 202,
mlock = 203,
munlock = 204,
undelete = 205,
compat_50_futimes = 206,
getpgid = 207,
reboot = 208,
poll= 209,
compat_14___semctl = 220,
semget = 221,
semop = 222,
semconfig = 223,
compat_14_msgctl = 224,
msgget = 225,
msgsnd = 226,
msgrcv = 227,
shmat = 228,
compat_14_shmctl = 229,
shmdt = 230,
shmget = 231,
compat_50_clock_gettime = 232,
compat_50_clock_settime = 233,
compat_50_clock_getres = 234,
timer_create = 235,
timer_delete = 236,
compat_50_timer_settime = 237,
compat_50_timer_gettime = 238,
timer_getoverrun = 239,
compat_50_nanosleep = 240,
fdatasync = 241,
mlockall = 242,
munlockall = 243,
compat_50___sigtimedwait = 244,
sigqueueinfo = 245,
_ksem_init = 247,
_ksem_open = 248,
_ksem_unlink = 249,
_ksem_close = 250,
_ksem_post = 251,
_ksem_wait = 252,
_ksem_trywait = 253,
_ksem_getvalue = 254,
_ksem_destroy = 255,
mq_open = 257,
mq_close = 258,
mq_unlink = 259,
mq_getattr = 260,
mq_setattr = 261,
mq_notify = 262,
mq_send = 263,
mq_receive = 264,
compat_50_mq_timedsend = 265,
compat_50_mq_timedreceive = 266,
__posix_rename = 270,
swapctl = 271,
compat_30_getdents = 272,
minherit = 273,
lchmod = 274,
lchown = 275,
compat_50_lutimes = 276,
__msync13 = 277,
compat_30___stat13 = 278,
compat_30___fstat13 = 279,
compat_30___lstat13 = 280,
__sigaltstack14 = 281,
__vfork14 = 282,
__posix_chown = 283,
__posix_fchown = 284,
__posix_lchown = 285,
getsid = 286,
__clone = 287,
fktrace = 288,
preadv = 289,
pwritev = 290,
compat_16___sigaction14 = 291,
__sigpending14 = 292,
__sigprocmask14 = 293,
__sigsuspend14 = 294,
compat_16___sigreturn14 = 295,
__getcwd = 296,
fchroot = 297,
compat_30_fhopen = 298,
compat_30_fhstat = 299,
compat_20_fhstatfs = 300,
compat_50_____semctl13 = 301,
compat_50___msgctl13 = 302,
compat_50___shmctl13 = 303,
lchflags = 304,
issetugid = 305,
utrace = 306,
getcontext = 307,
setcontext = 308,
_lwp_create = 309,
_lwp_exit = 310,
_lwp_self = 311,
_lwp_wait = 312,
_lwp_suspend = 313,
_lwp_continue = 314,
_lwp_wakeup = 315,
_lwp_getprivate = 316,
_lwp_setprivate = 317,
_lwp_kill = 318,
_lwp_detach = 319,
compat_50__lwp_park = 320,
_lwp_unpark = 321,
_lwp_unpark_all = 322,
_lwp_setname = 323,
_lwp_getname = 324,
_lwp_ctl = 325,
compat_60_sa_register = 330,
compat_60_sa_stacks = 331,
compat_60_sa_enable = 332,
compat_60_sa_setconcurrency = 333,
compat_60_sa_yield = 334,
compat_60_sa_preempt = 335,
__sigaction_sigtramp = 340,
pmc_get_info = 341,
pmc_control = 342,
rasctl = 343,
kqueue = 344,
compat_50_kevent = 345,
_sched_setparam = 346,
_sched_getparam = 347,
_sched_setaffinity = 348,
_sched_getaffinity = 349,
sched_yield = 350,
fsync_range = 354,
uuidgen = 355,
getvfsstat = 356,
statvfs1 = 357,
fstatvfs1 = 358,
compat_30_fhstatvfs1 = 359,
extattrctl = 360,
extattr_set_file = 361,
extattr_get_file = 362,
extattr_delete_file = 363,
extattr_set_fd = 364,
extattr_get_fd = 365,
extattr_delete_fd = 366,
extattr_set_link = 367,
extattr_get_link = 368,
extattr_delete_link = 369,
extattr_list_fd = 370,
extattr_list_file = 371,
extattr_list_link = 372,
compat_50_pselect = 373,
compat_50_pollts = 374,
setxattr = 375,
lsetxattr = 376,
fsetxattr = 377,
getxattr = 378,
lgetxattr = 379,
fgetxattr = 380,
listxattr = 381,
llistxattr = 382,
flistxattr = 383,
removexattr = 384,
lremovexattr = 385,
fremovexattr = 386,
compat_50___stat30 = 387,
compat_50___fstat30 = 388,
compat_50___lstat30 = 389,
__getdents30 = 390,
compat_30___fhstat30 = 392,
compat_50___ntp_gettime30 = 393,
__socket30 = 394,
__getfh30 = 395,
__fhopen40 = 396,
__fhstatvfs140 = 397,
compat_50___fhstat40 = 398,
aio_cancel = 399,
aio_error = 400,
aio_fsync = 401,
aio_read = 402,
aio_return = 403,
compat_50_aio_suspend = 404,
aio_write = 405,
lio_listio = 406,
__mount50 = 410,
mremap = 411,
pset_create = 412,
pset_destroy = 413,
pset_assign = 414,
_pset_bind = 415,
__posix_fadvise50 = 416,
__select50 = 417,
__gettimeofday50 = 418,
__settimeofday50 = 419,
__utimes50 = 420,
__adjtime50 = 421,
__lfs_segwait50 = 422,
__futimes50 = 423,
__lutimes50 = 424,
__setitimer50 = 425,
__getitimer50 = 426,
__clock_gettime50 = 427,
__clock_settime50 = 428,
__clock_getres50 = 429,
__nanosleep50 = 430,
____sigtimedwait50 = 431,
__mq_timedsend50 = 432,
__mq_timedreceive50 = 433,
compat_60__lwp_park = 434,
__kevent50 = 435,
__pselect50 = 436,
__pollts50 = 437,
__aio_suspend50 = 438,
__stat50 = 439,
__fstat50 = 440,
__lstat50 = 441,
____semctl50 = 442,
__shmctl50 = 443,
__msgctl50 = 444,
__getrusage50 = 445,
__timer_gettime50 = 447,
__ntp_gettime50 = 448,
__wait450 = 449,
__mknod50 = 450,
__fhstat50 = 451,
pipe2 = 453,
dup3 = 454,
kqueue1 = 455,
paccept = 456,
linkat = 457,
renameat = 458,
mkfifoat = 459,
mknodat = 460,
mkdirat = 461,
faccessat = 462,
fchmodat = 463,
fchownat = 464,
fexecve = 465,
fstatat = 466,
utimensat = 467,
openat = 468,
readlinkat = 469,
symlinkat = 470,
unlinkat = 471,
futimens = 472,
__quotactl = 473,
posix_spawn = 474,
recvmmsg = 475,
sendmmsg = 476,
clock_nanosleep = 477,
___lwp_park60 = 478,
}
}
return nr
| apache-2.0 |
gustavo-hms/cordel | spec/text.lua | 1 | 3774 | return [=[
# (hrtf) Auralização e o emprego de HRTFs
Além dessas alterações na própria estrutura da onda sonora, o ouvinte capta um
outro tipo de informação decorrente do deslocamento do sinal sonoro através do
espaço de propagação: as diferenças de fase (chamadas ITD, do inglês
*Interaural Time Difference*) e de intensidade (chamadas ILD, do inglês
*Interaural Level Difference*) dos sinais que chegam a seu ouvido
direito e esquerdo. A **inserção artificial** desses efeitos em um sinal sonoro,
com o intuito de reconstruir ou modelar uma cena sonora real, é chamada
**auralização** [@alton2000master @michael2007auralization].
Pensando em termos de **processamento ** de sinais, uma HRTF é, idealmente, um
filtro %--- cuja função de transferência é, digamos, $H(z)$ ---
que modifica um sinal de entrada $x(n)$ incutindo-lhe as mesmas transformações
supracitadas, de modo a tornar a saída $y(n)$ igual ao
sinal sonoro que chega ao ouvido.
Sendo $h(n)$ a resposta impulsiva desse filtro, a saída desejada será, então,
calculada através da convolução do sinal de entrada com $h(n)$, definida por:
$$$ (convolução)
y(n) = (x*h)(n) = \sum_k x(k)h(n-k).
$$$
# (cipic) O banco de dados CIPIC
As HRTFs foram medidas tendo os indivíduos se posicionado no centro de uma
esfera de 1~m de raio com diâmetro alinhado com o eixo interauricular do
indivíduo (cf. figura #esfera-do-cipic). Alto-falantes de 5,8~cm de raio
foram colocados em diversas posições ao longo da esfera (aproximadamente nos
pontos exibidos na figura #esfera-do-cipic). Os canais auditivos dos
indivíduos foram bloqueados e microfones foram utilizados para captar o sinal
emitido pelos alto-falantes.
# (resultados) Resultados
Nenhum dos métodos encontrados na literatura para se obterem filtros IIR a
partir de filtros FIR impõe restrições ao número de pólos e zeros reais que
produz. Assim, não se pode garantir que todos os filtros IIR do banco de
dados terão o mesmo número de pólos reais e de zeros reais, qualquer que seja a
ténica usada para gerar esses filtros IIR. E o que se observou, ao implementar
o método de Kalman, é que, de fato, os números de pólos e de zeros reais
variam filtro a filtro. A tabela #tab:pzreais mostra a distribuição de
cada configuração entre os filtros do banco obtidos pelo método de Kalman, e a
figura #fig:pzreais apresenta graficamente a distribuição espacial dos
filtros com configuração mais comum.
%{
% {
% | polos reais | zeros reais | total de filtros |
% |-------------|-------------|------------------|
% | 0 | 0 | 177 |
% | 0 | 2 | 826 |
%
% (tab:pzreais-6) Filtros com 6 polos e 6 zeros
% },
% {
% | polos reais | zeros reais | total de filtros |
% |-------------|-------------|------------------|
% | 0 | 0 | 49 |
% | 0 | 2 | 306 |
%
% (tab:pzreais-8) Filtros com 8 polos e 8 zeros
% };
% {
% | polos reais | zeros reais | total de filtros |
% |-------------|-------------|------------------|
% | 0 | 0 | 2 |
% | 0 | 4 | 174 |
%
% (tab:pzreais-10) Filtros com 10 polos e 10 zeros
% },
% {
% | polos reais | zeros reais | total de filtros |
% |-------------|-------------|------------------|
% | 0 | 2 | 53 |
% | 0 | 4 | 52 |
%
% (tab:pzreais-12) Filtros com 12 polos e 12 zeros
% }
%
% (tab:pzreais) Distribuição dos filtros segundo número de polos e de zeros reais, para
% filtros de algumas ordens diferentes.
%}
%
%$$$
%{
% | f(x) = { | 1, x < 3; |
% | | 0, c.c. |
%}
%$$$
]=]
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Carpenters_Landing/npcs/qm8.lua | 11 | 2711 | -----------------------------------
-- Area: Carpenters' Landing
-- NPC: ??? (qm2)
-- Involved in Missions: Calm Before the Storm (CoP 7-4)
-- @pos 120.615 -5.457 -390.133 2
-----------------------------------
package.loaded["scripts/zones/Carpenters_Landing/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getCurrentMission(COP) == CALM_BEFORE_THE_STORM )then
local ExecutorID = 16785710;
local Assassin1ID = ExecutorID+1;
local Assassin2ID = ExecutorID+2;
local Assassin3ID = ExecutorID+3;
local ExecutorA = GetMobAction(ExecutorID); --Cryptonberry_Executor
local Assassin1A = GetMobAction(Assassin1ID); --Cryptonberry_Assassins-1
local Assassin2A = GetMobAction(Assassin2ID); --Cryptonberry_Assassins-2
local Assassin3A = GetMobAction(Assassin3ID); --Cryptonberry_Assassins-3
local Assassin1kill= player:getVar("Cryptonberry_Assassins-1_KILL");
local Assassin2kill= player:getVar("Cryptonberry_Assassins-2_KILL");
local Assassin3kill= player:getVar("Cryptonberry_Assassins-3_KILL");
local Executorkill = player:getVar("Cryptonberry_Executor_KILL");
--printf("Assassin1: %u",Assassin1kill);
--printf("Assassin2: %u",Assassin2kill);
--printf("Assassin3: %u",Assassin3kill);
--printf("Executor: %u",Executorkill);
if(Executorkill == 1 and Assassin1kill == 1 and Assassin2kill == 1 and Assassin3kill == 1) then -- If all Mobs have been killed
player:startEvent(0x0025);
elseif(ExecutorA == 0 and Assassin1A == 0 and Assassin2A == 0 and Assassin3A == 0 and Executorkill~=2)then -- If no mobs present
SpawnMob(ExecutorID,180):updateEnmity(player);
SpawnMob(Assassin1ID,420);
SpawnMob(Assassin2ID,420);
SpawnMob(Assassin3ID,420);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x0025) then
player:setVar("Cryptonberry_Executor_KILL",2);
player:setVar("Cryptonberry_Assassins-1_KILL",0);
player:setVar("Cryptonberry_Assassins-2_KILL",0);
player:setVar("Cryptonberry_Assassins-3_KILL",0);
end
end;
| gpl-3.0 |
devilrap978/devil_rap65 | plugins/ar-delete.lua | 1 | 8070 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY MOHAMMED HISHAM ▀▄ ▄▀
▀▄ ▄▀ BY MOHAMMEDHISHAM (@TH3BOSS) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY MOHAMMED HISHAM ▀▄ ▄▀
▀▄ ▄▀ delete : حذف الرسائل ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
local function th3boss(msg, matches)
local reply_id = msg['id']
if not is_momod(msg) then
local th3boss= '❌ لَتلعَب بكَيفك 😜 المشرفيَنَ فقطَ ✔️ 👍'
return
reply_msg(reply_id, th3boss, ok_cb, false)
end
if #matches < 2 then
return "بعد هذا الأمر، من خلال تحديد كلمة المسافة أو العبارة التي تريد إدخال الكتابة الجميلة"
end
if string.len(matches[2]) > 44 then
return "الحد الأقصى المسموح به 40 حرفاالأحرف الإنجليزية والأرقام"
end
local reply_id = msg['id']
local font_base = "ء,ئ,ا,ب,ت,ث,ج,ح,خ,د,ذ,ر,ز,س,ش,ص,ض,ط,ظ,ع,غ,ق,ف,ك,ل,م,ن,ه,و,ي,0,9,8,7,6,5,4,3,2,1,.,_"
local font_hash = "ي,و,ه,ن,م,ل,ك,ف,ق,غ,ع,ظ,ط,ض,ص,ش,س,ز,ر,ذ,د,خ,ح,ج,ث,ت,ب,ا,ئ,ء,0,1,2,3,4,5,6,7,8,9,.,_"
local fonts = {
"ء,ئ,ٳ,ٻً,تہ,ثہ,جہ,حہ,خہ,دٍ,ذً,ر,ڒٍ,سہ,شہ,صً,ض,طہ,ظً,عـ,غہ,قـً,فُہ,كُہ,لہ,مـْ,نٍ,ه,ﯝ,يہ,0ً,1,2ً,3ً,4ً,5ً,6ً,7َ,8ً,9ً,.,_",
"ء,ئ,آ̲,ب̲,ت̲,ث̲,ج̲,ح̲,خ̲,د̲,ذ̲,ر̲,ز̲,س̲,ش̲,ص̲,ض,ط̲,ظً̲,ع̲,غ̲,ق̲,ف̲,ك̲,ل̲,م̲,ن̲,ہ̲,ۆ̲,ي̲,0̲,1̲,2̲,3̲,4̲,5̲,6̲,7̲,8̲,9̲,.,_",
"ء,ئ,آ̯͡,ب̯͡,ت̯͡,ث̯͡,ج̯͡,ح̯͡,خ̯͡,د̯͡,ذ̯͡,ر̯͡,ز̯͡,س̯͡,ش̯͡,ص̯͡,ض,ط̯͡,ظ̯͡,ع̯͡,غ̯͡,ق̯͡,ف̯͡,ك̯͡,ل̯͡,م̯͡,ن̯͡,ہ̯͡,ۆ̯͡,ي̯͡,0̯͡,1̯͡,2̯͡,3̯͡,4̯͡,5̯͡,6̯͡,7̯͡,8̯͡,9̯͡,.,_",
"ء,ئ,آ͠,ب͠,ت͠,ث͠,ج͠,ح͠,خ͠,د͠,ذ͠,ر,ز͠,س͠,ش͠,ص͠,ض,ط͠,ظ͠,ع͠,غ͠,ق͠,ف͠,گ͠,ل͠,م͠,ن͠,ه͠,و͠,ي͠,0͠,1͠,2͠,3͠,4͠,5͠,6͠,7͠,8͠,9͠,.,_",
"ء,ئ,آ,ب,ت,ث,جٍ,حٍ,خـ,دِ,ڌ,رٍ,ز,س,شُ,ص,ض,طُ,ظً,عٍ,غ,ق,فَ,گ,لُ,م,ن,ہ,ۆ,يَ,₀,₁,₂,₃,₄,₅,₆,₇,₈,₉,.,_", "ء,ئ,إآ,̜̌ب,تـ,,ثـ,جٍ,و,خ,ﮃ,ذ,رٍ,زً,سًٌُُ,شُ,ص,ض,طُ,ظً,۶,غ,ق,فَ,گ,لُ,مـ,ن,ه̷̸̐,ۈ,يَ,0,⇂,Շ,Ɛ,h,ʢ,9,L,8,6,.,_",
"ء,ئ,آ,ب,ت,ث,جٍ,حٍ,خـ,دِ,ڌ,رٍ,ز,س,شُ,ص,ض,طُ,ظً,عٍ,غ,ق,فَ,گ,لُ,م,ن,ہ,ۆ,يَ,₀,₁,₂,₃,₄,₅,₆,₇,₈,₉,.,_",
"ء,ئ,ٵ̷ ,ب̷,ت̷,ث̷,ج̷,ح̷,خ̷,د̷ِ,ذ̷,ر̷,ز̷,س̷,ش̷ُ,ص̷,ض,ط̷ُ,ظ̷ً,ع̷ٍ,غ̷,ق̷,ف̷َ,گ̷,ل̷,م̷,ن̷,ہ̷,ۆ̷,ي̷,0̷,1̷,2̷,3̷,4̷,5̷,6̷,7̷,8̷,9̷,.,_",
"ء,ئ,آإ,بـ♥̨̥̬̩,تـ♥̨̥̬̩,ثـ♥̨̥̬̩,جـ♥̨̥̬̩,حـ♥̨̥̬̩,خ,د,ذ,ر,ز,س,ش,ص,ض,ط♥̨̥̬̩,ظ♥̨̥̬̩,ع,غ♥̨̥̬̩,قـ♥̨̥̬̩,ف,گ♥̨̥̬̩,ل,مـ♥̨̥̬̩,ن,هـ♥̨̥̬̩,و,ي,⁰,¹,²,³,⁴,⁵,⁶,⁷,⁸,⁹,.,_",
"ء,ئ,آ,بُ,تْ,ثُ,ج,ح,ځ,ڊ,ڏ,ر,ڒٍ,ڛ,شُ,صً,ض,طُ,ظً,عٌ,غٍ,قٌ,فُ,ڪ,لُ,مْ,نْ,ﮩ,وُ,يُ,0,1,2,3,4,5,6,7,8,9,.,_",
"ء,ئ,آ,بَ,ت,ث,جٍ,حٍ,خـ,دِ,ذَ,رٍ,زْ,س,شُ,ص,ض,طُ,ظً,عٍ,غ,قٌ,فُ,ڪ,لُِ,م,ن,هـ,وُ,ي,0̲̣̣̥,1̣̣̝̇̇,2̲̣̣̣̥,3̍̍̍̊,4̩̥,5̲̣̥,6̥̥̲̣̥,7̣̣̣̝̇̇̇,8̣̝̇,9̲̣̣̥,.,_",
"ء,ئ,آ,ب,ت,ث,جٍ,حٍ,خـ,دِ,ڌ,رٍ,ز,س,شُ,ص,ض,طُ,ظً,عٍ,غ,ق,فَ,گ,لُ,م,ن,ہ,ۆ,يَ,₀,₁,₂,₃,₄,₅,₆,₇,₈,₉,.,_",
"ء,ئ,ٵ̷ ,ب̷,ت̷,ث̷,ج̷,ح̷,خ̷,د̷ِ,ذ̷,ر̷,ز̷,س̷,ش̷ُ,ص̷,ض,ط̷ُ,ظ̷ً,ع̷ٍ,غ̷,ق̷,ف̷َ,گ̷,ل̷,م̷,ن̷,ہ̷,ۆ̷,ي̷,0̷,1̷,2̷,3̷,4̷,5̷,6̷,7̷,8̷,9̷,.,_",
"ء,ئ,آ͠,ب͠,ت͠,ث͠,ج͠,ح͠,خ͠,د͠,ذ͠,ر,ز͠,س͠,ش͠,ص͠,ض,ط͠,ظ͠,ع͠,غ͠,ق͠,ف͠,گ͠,ل͠,م͠,ن͠,ه͠,و͠,ي͠,0͠,1͠,2͠,3͠,4͠,5͠,6͠,7͠,8͠,9͠,.,_",
"ء,ئ,آ̯͡,ب̯͡,ت̯͡,ث̯͡,ج̯͡,ح̯͡,خ̯͡,د̯͡,ذ̯͡,ر̯͡,ز̯͡,س̯͡,ش̯͡,ص̯͡,ض,ط̯͡,ظ̯͡,ع̯͡,غ̯͡,ق̯͡,ف̯͡,ك̯͡,ل̯͡,م̯͡,ن̯͡,ہ̯͡,ۆ̯͡,ي̯͡,0̯͡,1̯͡,2̯͡,3̯͡,4̯͡,5̯͡,6̯͡,7̯͡,8̯͡,9̯͡,.,_",
"ء,ئ,آإ,بـ♥̨̥̬̩,تـ♥̨̥̬̩,ثـ♥̨̥̬̩,جـ♥̨̥̬̩,حـ♥̨̥̬̩,خ,د,ذ,ر,ز,س,ش,ص,ض,ط♥̨̥̬̩,ظ♥̨̥̬̩,ع,غ♥̨̥̬̩,قـ♥̨̥̬̩,ف,گ♥̨̥̬̩,ل,مـ♥̨̥̬̩,ن,هـ♥̨̥̬̩,و,ي,⁰,¹,²,³,⁴,⁵,⁶,⁷,⁸,⁹,̴.̴,̴_̴",
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local result = {}
i=0
for k=1,#fonts do
i=i+1
local tar_font = fonts[i]:split(",")
local text = matches[2]
local text = text:gsub("ء",tar_font[1])
local text = text:gsub("ئ",tar_font[2])
local text = text:gsub("ا",tar_font[3])
local text = text:gsub("ب",tar_font[4])
local text = text:gsub("ت",tar_font[5])
local text = text:gsub("ث",tar_font[6])
local text = text:gsub("ج",tar_font[7])
local text = text:gsub("ح",tar_font[8])
local text = text:gsub("خ",tar_font[9])
local text = text:gsub("د",tar_font[10])
local text = text:gsub("ذ",tar_font[11])
local text = text:gsub("ر",tar_font[12])
local text = text:gsub("ز",tar_font[13])
local text = text:gsub("س",tar_font[14])
local text = text:gsub("ش",tar_font[15])
local text = text:gsub("ص",tar_font[16])
local text = text:gsub("ض",tar_font[17])
local text = text:gsub("ط",tar_font[18])
local text = text:gsub("ظ",tar_font[19])
local text = text:gsub("ع",tar_font[20])
local text = text:gsub("غ",tar_font[21])
local text = text:gsub("ق",tar_font[22])
local text = text:gsub("ف",tar_font[23])
local text = text:gsub("ك",tar_font[24])
local text = text:gsub("ل",tar_font[25])
local text = text:gsub("م",tar_font[26])
local text = text:gsub("ن",tar_font[27])
local text = text:gsub("ه",tar_font[28])
local text = text:gsub("و",tar_font[29])
local text = text:gsub("ي",tar_font[30])
local text = text:gsub("0",tar_font[31])
local text = text:gsub("9",tar_font[32])
local text = text:gsub("8",tar_font[33])
local text = text:gsub("7",tar_font[34])
local text = text:gsub("6",tar_font[35])
local text = text:gsub("5",tar_font[36])
local text = text:gsub("4",tar_font[37])
local text = text:gsub("3",tar_font[38])
local text = text:gsub("2",tar_font[39])
local text = text:gsub("1",tar_font[40])
table.insert(result, text)
end
local result_text = "💯 زخرفة : "..matches[2].."\n💯 تصميم "..tostring(#fonts).." خط :\n🃏〰〰〰〰〰〰〰〰〰🃏\n"
a=0
for v=1,#result do
a=a+1
result_text = result_text..a.."- "..result[a].."\n\n"
end
return result_text.."🃏〰〰〰〰〰〰〰〰〰🃏\n💯-Đєⱴ💀: @TH3BOSS\n💯-Đєⱴ ฿๏ͳ💀: @ll60Kllbot\n💯-Đєⱴ Ϲḫ₳ͷͷєℓ💀: @llDEV1ll"
end
return {
description = "Fantasy Writer",
usagehtm = '<tr><td align="center">decoration متن</td><td align="right">مع هذا البرنامج المساعد يمكن النصوص الخاصة بك مع مجموعة متنوعة من الخطوط والتصميم الجميل. أحرف الحد الأقصى المسموح به هو 20 ويمكن فقط استخدام الأحرف الإنجليزية والأرقام</td></tr>',
usage = {"decoration [text] : زخرفه النص",},
patterns = {
"^(زخرفه) (.*)",
"^(زخرفه)$",
},
run = th3boss
}
| gpl-2.0 |
bluelovers/phprpc | lua/phprpc_client.lua | 1 | 5846 | --[[
/**********************************************************\
| |
| The implementation of PHPRPC Protocol 3.0 |
| |
| phprpc_client.lua |
| |
| Release 3.0 |
| Copyright by Team-PHPRPC |
| |
| WebSite: http://www.phprpc.org/ |
| http://www.phprpc.net/ |
| http://www.phprpc.com/ |
| http://sourceforge.net/projects/php-rpc/ |
| |
| Authors: Chen fei <cf850118@163.com> |
| |
| This file may be distributed and/or modified under the |
| terms of the GNU Lesser General Public License (LGPL) |
| version 3.0 as published by the Free Software Foundation |
| and appearing in the included file LICENSE. |
| |
\**********************************************************/
/* PHPRPC Client library.
*
* Copyright: Chen fei <cf850118@163.com>
* Version: 3.0
* LastModified: Nov 25, 2009
* This library is free. You can redistribute it and/or modify it.
*/
--]]
require('base64')
require('luacurl')
require('php')
phprpc_client_id = 0
phprpc_error = {
number = 0,
message = ''
}
function phprpc_error:new(number, message)
o = {}
setmetatable(o, self)
self.__index = self
o.number = number or 0
o.message = message or ''
return o
end
phprpc_client = {
id = '',
charset = 'utf-8',
key = '',
url = '',
output = '',
version = 3.0,
key_exchanged = false,
key_length = 128,
encrypt_mode = 0,
warning = phprpc_error:new()
}
function phprpc_client:new(url)
o = {}
setmetatable(o, self)
self.__index = self
math.randomseed(os.time())
o.id = 'Lua' .. math.random(2147483647) .. os.date('%Y%m%d%H%M%S') .. phprpc_client_id
phprpc_client_id = phprpc_client_id + 1
o:use_service(url)
return o
end
function phprpc_client:use_service(url)
if string.find(url, '?') == nil then
self.url = url .. '?phprpc_id=' .. self.id
else
self.url = url .. '&phprpc_id=' .. self.id
end
end
function phprpc_client:invoke(func_name, args, by_ref, encrypt_mode)
local fixed_args = {}
local count = 0
for i, v in ipairs(args) do
fixed_args[i - 1] = v
count = count + 1
end
local buffer = 'phprpc_func=' .. func_name
if count > 0 then
buffer = buffer .. '&phprpc_args=' .. string.gsub(base64.encode(serialize(fixed_args)), '+', '%%2B')
end
buffer = buffer .. '&phprpc_encrypt=' .. encrypt_mode
buffer = buffer .. '&phprpc_ref=' .. tostring(by_ref)
local retval = {}
local data = self:post(buffer)
if data.phprpc_errno > 0 then
retval.warning = phprpc_error:new(data.phprpc_errno, data.phprpc_errstr)
end
if data.phprpc_output ~= nil then
retval.output = data.phprpc_output
end
if data.phprpc_result ~= nil then
retval.result = unserialize(data.phprpc_result)
else
retval.result = retval.warning
end
return retval
end
function phprpc_client:post(data)
local function writer(content, buffer)
content.data = content.data .. buffer
return #buffer
end
local header = {data = ''}
local document = {data = ''}
local c = curl.new()
c:setopt(curl.OPT_HTTP_VERSION, 1.1);
c:setopt(curl.OPT_HEADERFUNCTION, writer);
c:setopt(curl.OPT_HEADERDATA, header);
c:setopt(curl.OPT_WRITEFUNCTION, writer);
c:setopt(curl.OPT_WRITEDATA, document);
c:setopt(curl.OPT_HTTPHEADER,
'Cache-Control: no-cache',
'Connection: keep-alive',
'Content-Type: application/x-www-form-urlencoded; charset=' .. self.charset
);
c:setopt(curl.OPT_ENCODING, '');
c:setopt(curl.OPT_USERAGENT, 'phprpc client for lua');
c:setopt(curl.OPT_SSLENGINE_DEFAULT, true);
c:setopt(curl.OPT_SSL_VERIFYPEER, false);
c:setopt(curl.OPT_SSL_VERIFYHOST, 0);
c:setopt(curl.OPT_NOPROGRESS, true);
c:setopt(curl.OPT_NOSIGNAL, true);
c:setopt(curl.OPT_URL, self.url);
c:setopt(curl.OPT_POST, true);
c:setopt(curl.OPT_POSTFIELDS, data);
c:setopt(curl.OPT_POSTFIELDSIZE, #data);
c:perform()
local version = 0
local retval = {}
local response_code = c:getinfo(curl.INFO_RESPONSE_CODE)
local response_desc = string.match(header.data, 'HTTP/%d%.%d%s+' .. response_code .. '%s+([^\r]+)')
if response_code == 200 then
for key, value in string.gmatch(header.data, '([%a%-]+):%s*([^\r]+)') do
if string.lower(key) == 'x-powered-by' then
version = string.match(string.lower(value), 'phprpc server/(%d%.%d)')
break
end
end
if version == 0 then
error('Illegal PHPRPC Server!')
else
self.version = version
end
for key, value in string.gmatch(document.data, '([%a_]+)=\"([^\r]+)\"') do
if key == 'phprpc_errno' or key == 'phprpc_keylen' then
retval[key] = tonumber(value)
else
retval[key] = base64.decode(value)
end
end
else
retval.phprpc_errno = response_code
retval.phprpc_errstr = response_desc
end
return retval
end
function phprpc_client:set_key_length(key_length)
if self.key == '' then
return false
else
self.key_length = key_length;
return true
end
end
function phprpc_client:set_encrypt_mode(encrypt_mode)
if encrypt_mode >= 0 and encrypt_mode <= 3 then
self.encrypt_mode = encrypt_mode
return true
else
self.encrypt_mode = 0
return false
end
end
| gpl-2.0 |
FFXIOrgins/FFXIOrgins | scripts/globals/weaponskills/blade_rin.lua | 6 | 1243 | -----------------------------------
-- Blade Rin
-- Katana weapon skill
-- Skill Level: 5
-- Delivers a single-hit attack. Chance of params.critical varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Light Gorget.
-- Aligned with the Light Belt.
-- Element: None
-- Modifiers: STR:20% ; DEX:20%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.2; params.dex_wsc = 0.2; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.3; params.crit200 = 0.6; params.crit300 = 0.9;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Aht_Urhgan_Whitegate/npcs/Sulbahn.lua | 10 | 2042 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Sulbahn
-- Type: Alchemy Adv. Image Support
-- @pos -10.470 -6.25 -141.700 241
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/status");
require("scripts/globals/crafting");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local guildMember = isGuildMember(player,1);
if (guildMember == 1) then
if (trade:hasItemQty(2184,1) and trade:getItemCount() == 1) then
if (player:hasStatusEffect(EFFECT_ALCHEMY_IMAGERY) == false) then
player:tradeComplete();
player:startEvent(0x027D,17160,1,19405,21215,30030,0,7,0);
else
npc:showText(npc, IMAGE_SUPPORT_ACTIVE);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,1);
local SkillLevel = player:getSkillLevel(2);
if (guildMember == 1) then
player:startEvent(0x027C,2,SkillLevel,0,511,0,0,7,2184);
else
player:startEvent(0x027C,0,0,0,0,0,0,7,0); -- 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 == 0x027D) then
player:messageSpecial(IMAGE_SUPPORT,0,7,0);
player:addStatusEffect(EFFECT_ALCHEMY_IMAGERY,3,0,480);
end
end;
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Aht_Urhgan_Whitegate/npcs/Iruki-Waraki.lua | 38 | 2851 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Iruki-Waraki
-- Type: Standard NPC
-- Involved in quest: No Strings Attached
-- @pos 101.329 -6.999 -29.042 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local NoStringsAttached = player:getQuestStatus(AHT_URHGAN,NO_STRINGS_ATTACHED);
local NoStringsAttachedProgress = player:getVar("NoStringsAttachedProgress");
if (NoStringsAttached == 1 and NoStringsAttachedProgress == 1) then
player:startEvent(0x0104); -- he tells u to get him an automaton
elseif (NoStringsAttached == 1 and NoStringsAttachedProgress == 2) then
player:startEvent(0x0105); -- reminder to get an automaton
elseif (NoStringsAttached == 1 and NoStringsAttachedProgress == 6) then
player:startEvent(0x010a); -- you bring him the automaton
elseif (NoStringsAttached == 2) then
player:startEvent(0x010b); -- asking you how are you doing with your automaton
-- In case a player completed the quest before unlocking attachments was implemented (no harm in doing this repeatedly)
player:unlockAttachment(8224); --Harlequin Frame
player:unlockAttachment(8193); --Harlequin Head
else
player:startEvent(0x0103); -- Leave him alone
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 == 0x0104) then
player:setVar("NoStringsAttachedProgress",2);
elseif (csid == 0x010a) then
if (player:getFreeSlotsCount() ~= 0) then
player:completeQuest(AHT_URHGAN,NO_STRINGS_ATTACHED);
player:addTitle(PROUD_AUTOMATON_OWNER);
player:unlockJob(18);
player:addItem(17859);
player:messageSpecial(ITEM_OBTAINED,17859); -- animator
player:messageSpecial(5699); -- "You can now become a puppetmaster."
player:setVar("NoStringsAttachedProgress",0);
player:setPetName(PETTYPE_AUTOMATON, option+118);
player:unlockAttachment(8224); --Harlequin Frame
player:unlockAttachment(8193); --Harlequin Head
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17859);
end;
end;
end;
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/The_Sanctuary_of_ZiTah/Zone.lua | 2 | 2141 | -----------------------------------
--
-- Zone: The_Sanctuary_of_ZiTah (121)
--
-----------------------------------
package.loaded["scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Sanctuary_of_ZiTah/TextIDs");
require( "scripts/globals/icanheararainbow");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize( zone)
local Noble_Mold = 17273278;
GetMobByID(Noble_Mold):setExtraVar(os.time() + math.random((43200), (57600)));
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn( player, prevZone)
cs = -1;
if( player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( 539.901, 3.379, -580.218, 126);
end
if( triggerLightCutscene( player)) then -- Quest: I Can Hear A Rainbow
cs = 0x0002;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter( player, region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate( player, csid, option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if( csid == 0x0002) then
lightCutsceneUpdate( player); -- Quest: I Can Hear A Rainbow
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish( player, csid, option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if( csid == 0x0002) then
lightCutsceneFinish( player); -- Quest: I Can Hear A Rainbow
end
end;
| gpl-3.0 |
MOSAVI17/Gbot | bot/bot.lua | 2 | 6651 | 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
local receiver = get_receiver(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)
mark_read(receiver, ok_cb, false)
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 < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
print('\27[36mNot valid: Telegram message\27[39m')
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)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"9gag",
"eur",
"echo",
"btc",
"get",
"giphy",
"google",
"gps",
"help",
"id",
"images",
"img_google",
"location",
"media",
"plugins",
"channels",
"set",
"stats",
"time",
"version",
"weather",
"xkcd",
"youtube" },
sudo_users = {157337513},
disabled_channels = {}
}
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('\27[31m'..err..'\27[39m')
end
end
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 5 mins
postpone (cron_plugins, false, 5*60.0)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
suchipi/pac3 | lua/pac3/core/client/parts/fog.lua | 1 | 1185 | local PART = {}
PART.ClassName = "fog"
PART.NonPhysical = true
pac.StartStorableVars()
pac.GetSet(PART, "Color", Vector(255, 255, 255))
pac.GetSet(PART, "Start", 0)
pac.GetSet(PART, "End", 10)
pac.GetSet(PART, "Alpha", 1)
--pac.GetSet(PART, "AffectChildren", false)
pac.GetSet(PART, "Height", 0)
pac.EndStorableVars()
function PART:GetNiceName()
local h,s,v = pac.ColorToNames(self:GetColor())
return h .. " fog"
end
function PART:SetColor(v)
self.Color = v
self.clr = {v.r, v.g, v.b}
end
function PART:OnParent(part)
part:AddModifier(self)
end
function PART:OnUnParent(part)
if not part:IsValid() then return end
part:RemoveModifier(self)
end
function PART:PreOnDraw(owner, pos)
render.FogStart(self.Start*100)
render.FogEnd(self.End*100)
render.FogMaxDensity(self.Alpha)
if self.clr then render.FogColor(unpack(self.clr)) end
if self.Height > 0 then
render.FogMode(MATERIAL_FOG_LINEAR_BELOW_FOG_Z)
render.SetFogZ(self.cached_pos.z + self.Height * 10)
else
render.FogMode(MATERIAL_FOG_LINEAR)
end
end
function PART:PostOnDraw()
render.FogMode(MATERIAL_FOG_NONE)
end
pac.RegisterPart(PART) | gpl-3.0 |
mpeterv/luassert | src/languages/nl.lua | 6 | 1453 | local s = require('say')
s:set_namespace('nl')
s:set("assertion.same.positive", "Verwachtte objecten die vergelijkbaar zijn.\nAangeboden:\n%s\nVerwachtte:\n%s")
s:set("assertion.same.negative", "Verwachtte objecten die niet vergelijkbaar zijn.\nAangeboden:\n%s\nVerwachtte niet:\n%s")
s:set("assertion.equals.positive", "Verwachtte objecten die hetzelfde zijn.\nAangeboden:\n%s\nVerwachtte:\n%s")
s:set("assertion.equals.negative", "Verwachtte objecten die niet hetzelfde zijn.\nAangeboden:\n%s\nVerwachtte niet:\n%s")
s:set("assertion.unique.positive", "Verwachtte objecten die uniek zijn:\n%s")
s:set("assertion.unique.negative", "Verwachtte objecten die niet uniek zijn:\n%s")
s:set("assertion.error.positive", "Verwachtte een foutmelding.")
s:set("assertion.error.negative", "Verwachtte geen foutmelding.\n%s")
s:set("assertion.truthy.positive", "Verwachtte een 'warige' (thruthy) waarde, maar was:\n%s")
s:set("assertion.truthy.negative", "Verwachtte een niet 'warige' (thruthy) waarde, maar was:\n%s")
s:set("assertion.falsy.positive", "Verwachtte een 'onwarige' (falsy) waarde, maar was:\n%s")
s:set("assertion.falsy.negative", "Verwachtte een niet 'onwarige' (falsy) waarde, maar was:\n%s")
-- errors
s:set("assertion.internal.argtolittle", "de '%s' functie verwacht minimaal %s parameters, maar kreeg er: %s")
s:set("assertion.internal.badargtype", "bad argument #%s: de '%s' functie verwacht een %s als parameter, maar kreeg een: %s")
| mit |
FFXIOrgins/FFXIOrgins | scripts/zones/Misareaux_Coast/npcs/_0p3.lua | 34 | 1082 | -----------------------------------
-- Area: Misareaux Coast
-- NPC: Dilapidated Gate
-- Notes: Entrance to Misareaux Coast
-----------------------------------
package.loaded["scripts/zones/Misareaux_Coast/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Misareaux_Coast/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0229);
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 |
FFXIOrgins/FFXIOrgins | scripts/zones/Metalworks/npcs/Romero.lua | 10 | 1805 | -----------------------------------
-- Area: Metalworks
-- NPC: Romero
-- Type: Smithing Synthesis Image Support
-- @pos -106.336 2.000 26.117 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Metalworks/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,8);
local SkillCap = getCraftSkillCap(player,256);
local SkillLevel = player:getSkillLevel(256);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_SMITHING_IMAGERY) == false) then
player:startEvent(0x0069,SkillCap,SkillLevel,2,207,player:getGil(),0,0,0);
else
player:startEvent(0x0069,SkillCap,SkillLevel,2,207,player:getGil(),7127,0,0);
end
else
player:startEvent(0x0069); -- 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 == 0x0069 and option == 1) then
player:messageSpecial(SMITHING_SUPPORT,0,2,2);
player:addStatusEffect(EFFECT_SMITHING_IMAGERY,1,0,120);
end
end;
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Davoi/npcs/_45i.lua | 19 | 2041 | -----------------------------------
-- Area: Davoi
-- NPC: Wailing Pond
-- Used In Quest: Whence Blows the Wind
-- @pos 380 0.1 -181 149
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0034);
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 == 0x0034 and player:getVar("miniQuestForORB_CS") == 1) then
local c = player:getVar("countRedPoolForORB");
if(c == 0) then
player:setVar("countRedPoolForORB", c + 2);
player:delKeyItem(WHITE_ORB);
player:addKeyItem(PINK_ORB);
player:messageSpecial(KEYITEM_OBTAINED, PINK_ORB);
elseif(c == 1 or c == 4 or c == 8) then
player:setVar("countRedPoolForORB", c + 2);
player:delKeyItem(PINK_ORB);
player:addKeyItem(RED_ORB);
player:messageSpecial(KEYITEM_OBTAINED, RED_ORB);
elseif(c == 5 or c == 9 or c == 12) then
player:setVar("countRedPoolForORB", c + 2);
player:delKeyItem(RED_ORB);
player:addKeyItem(BLOOD_ORB);
player:messageSpecial(KEYITEM_OBTAINED, BLOOD_ORB);
elseif(c == 13) then
player:setVar("countRedPoolForORB", c + 2);
player:delKeyItem(BLOOD_ORB);
player:addKeyItem(CURSED_ORB);
player:messageSpecial(KEYITEM_OBTAINED, CURSED_ORB);
player:addStatusEffect(EFFECT_PLAGUE,0,0,900);
end
end
end; | gpl-3.0 |
msburgess3200/PERP | gamemodes/perp/gamemode/vehicles/Old Cars/cop_car.lua | 1 | 2586 | ///////////////////////////////
// © 2011-2012 VoltageGaming //
// All rights reserved //
///////////////////////////////
// This material may not be //
// reproduced, displayed, //
// modified or distributed //
// without the express prior //
// written permission of the //
// the copyright holder. //
///////////////////////////////
VEHICLE = {};
VEHICLE.ID = 'z';
VEHICLE.Name = "Police Car";
VEHICLE.Make = "Ford";
VEHICLE.Model = "Crown Royal";
VEHICLE.Script = "cop";
VEHICLE.Cost = 0;
VEHICLE.PaintJobCost = 0;
VEHICLE.DF = false;
VEHICLE.CustomBodyGroup = nil;
VEHICLE.PaintJobs = {
{model = 'models/perp2.5/police_cruiser.mdl', skin = '1', name = '', color = Color(0, 0, 0, 255)},
};
VEHICLE.PassengerSeats = {
{Vector(19.8167, 0, 10), Angle(0, 0, 0)},
{Vector(19.8167, 40, 14), Angle(0, 0, 0)},
{Vector(-19.8167, 40, 14), Angle(0, 0, 0)},
};
VEHICLE.ExitPoints = {
Vector(-83.1944, 6.2218, 3.3109),
Vector(83.1944, 6.2218, 3.3109),
Vector(83.1944, -31, 3.3109),
Vector(-83.1944, -31, 3.3109),
};
VEHICLE.DefaultIceFriction = 1;
VEHICLE.PlayerReposition_Pos = nil;
VEHICLE.PlayerReposition_Ang = nil;
VEHICLE.ViewAdjustments_FirstPerson = nil;
VEHICLE.ViewAdjustments_ThirdPerson = nil;
VEHICLE.RequiredClass = TEAM_POLICE;
VEHICLE.PaintText = "";
VEHICLE.HornNoise = Sound("PERP2.5/siren_short.mp3");
VEHICLE.HeadlightPositions = {
{Vector(-25.4003, 102.3026, 32.7976), Angle(15, 0, 0)};
{Vector(25.4003, 102.3026, 32.7976), Angle(15, 0, 0)};
};
VEHICLE.TaillightPositions = {
{Vector(-28.1642, -122.3515, 35.9066), Angle(20, -180, 0)};
{Vector(28.1642, -122.3515, 35.9066), Angle(20, -180, 0)};
};
VEHICLE.UnderglowPositions = {
};
VEHICLE.RevvingSound = nil;
VEHICLE.SpinoutSound = nil;
VEHICLE.SirenNoise = Sound("PERP2.5/siren_long.mp3");
VEHICLE.SirenNoise_Alt = Sound("PERP2.5/siren_wail.mp3");
VEHICLE.SirenColors = {
{Color(0, 0, 255, 255), Vector(19.9011, -11.7145, 64.5684)},
{Color(0, 0, 255, 255), Vector(-19.9011, -11.7145, 64.5684)},
{Color(255, 0, 0, 255), Vector(-12.2631, -7.0797, 65.0943)},
{Color(255, 0, 0, 255), Vector(12.2631, -7.0797, 65.0943)},
{Color(0, 0, 255, 255), Vector(-5.4694, -3.4697, 65.1131)},
{Color(0, 0, 255, 255), Vector(5.4694, -3.4697, 65.1131)},
{Color(255, 0, 0, 255), Vector(0, 1.5218, 64.8619)},
};
GM:RegisterVehicle(VEHICLE); | mit |
Gael-de-Sailly/minetest-minetestforfun-server | mods/moretrees/crafts.lua | 7 | 3569 | local S = moretrees.intllib
for i in ipairs(moretrees.treelist) do
local treename = moretrees.treelist[i][1]
-- MODIFICATION MADE FOR MFF //MFF(Mg|08/12/15)
if minetest.registered_items["moretrees:" .. treename .. "_trunk_sideways"] then
minetest.register_craft({
output = "moretrees:"..treename.."_trunk 2",
recipe = {
{"moretrees:"..treename.."_trunk_sideways"},
{"moretrees:"..treename.."_trunk_sideways"}
}
})
minetest.register_craft({
type = "shapeless",
output = "moretrees:"..treename.."_planks 4",
recipe = {
"moretrees:"..treename.."_trunk_sideways"
}
})
end
minetest.register_craft({
type = "shapeless",
output = "moretrees:"..treename.."_planks 4",
recipe = {
"moretrees:"..treename.."_trunk"
}
})
minetest.register_craft({
type = "fuel",
recipe = "moretrees:"..treename.."_sapling",
burntime = 10,
})
end
minetest.register_craft({
type = "shapeless",
output = "moretrees:rubber_tree_planks 4",
recipe = {
"moretrees:rubber_tree_trunk_empty"
}
})
minetest.register_craft({
type = "fuel",
recipe = "group:moretrees_leaves",
burntime = 1,
})
-- Food recipes!
minetest.register_craftitem("moretrees:coconut_milk", {
description = S("Coconut Milk"),
inventory_image = "moretrees_coconut_milk_inv.png",
wield_image = "moretrees_coconut_milk.png",
on_use = minetest.item_eat(2),
})
minetest.register_craftitem("moretrees:raw_coconut", {
description = S("Raw Coconut"),
inventory_image = "moretrees_raw_coconut.png",
on_use = minetest.item_eat(4),
})
minetest.register_craftitem("moretrees:acorn_muffin_batter", {
description = S("Acorn Muffin batter"),
inventory_image = "moretrees_acorn_muffin_batter.png",
})
minetest.register_craftitem("moretrees:acorn_muffin", {
description = S("Acorn Muffin"),
inventory_image = "moretrees_acorn_muffin.png",
on_use = minetest.item_eat(4),
})
minetest.register_craftitem("moretrees:spruce_nuts", {
description = S("Roasted Spruce Cone Nuts"),
inventory_image = "moretrees_spruce_nuts.png",
on_use = minetest.item_eat(1),
})
minetest.register_craftitem("moretrees:cedar_nuts", {
description = S("Roasted Cedar Cone Nuts"),
inventory_image = "moretrees_cedar_nuts.png",
on_use = minetest.item_eat(1),
})
minetest.register_craftitem("moretrees:fir_nuts", {
description = S("Roasted Fir Cone Nuts"),
inventory_image = "moretrees_fir_nuts.png",
on_use = minetest.item_eat(1),
})
for i in ipairs(moretrees.cutting_tools) do
local tool = moretrees.cutting_tools[i]
minetest.register_craft({
type = "shapeless",
output = "moretrees:coconut_milk",
recipe = {
"moretrees:coconut",
"vessels:drinking_glass",
tool
},
replacements = {
{ "moretrees:coconut", "moretrees:raw_coconut" },
{ tool, tool }
}
})
end
minetest.register_craft({
type = "shapeless",
output = "moretrees:acorn_muffin_batter",
recipe = {
"moretrees:acorn",
"moretrees:acorn",
"moretrees:acorn",
"moretrees:acorn",
"moretrees:coconut_milk",
},
replacements = {
{ "moretrees:coconut_milk", "vessels:drinking_glass" }
}
})
minetest.register_craft({
type = "cooking",
output = "moretrees:acorn_muffin 4",
recipe = "moretrees:acorn_muffin_batter",
})
minetest.register_craft({
type = "cooking",
output = "moretrees:spruce_nuts 4",
recipe = "moretrees:spruce_cone",
})
minetest.register_craft({
type = "cooking",
output = "moretrees:cedar_nuts 4",
recipe = "moretrees:cedar_cone",
})
minetest.register_craft({
type = "cooking",
output = "moretrees:fir_nuts 4",
recipe = "moretrees:fir_cone",
})
| unlicense |
daofeng2015/luci | applications/luci-app-vnstat/luasrc/model/cbi/vnstat.lua | 78 | 1816 | -- Copyright 2010-2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache 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
| apache-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Aht_Urhgan_Whitegate/npcs/Mazween.lua | 34 | 1639 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Mazween
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MAZWEEN_SHOP_DIALOG);
stock = {0x1313,11200, -- Scroll of Sleepga
0x12A6,18720, -- Scroll of Sleep II
0x1292,25200, -- Poison II
0x12E7,14000, -- Bio II
0x1296,5160, -- Poisonga
0x1316,19932, -- Stone III
4779,22682, -- Water III
0x12DD,27744, -- Aero III
0x129C,33306, -- Fire III
0x12E1,39368, -- Blizzard III
0x12F6,45930, -- Thunder III
0x1303,27000, -- Absorb-TP
0x1311,44000, -- Absorb-ACC
0x12A1,30780, -- Drain II
0x1315,70560, -- Dread Spikes
4856,79800} -- Aspir II
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 |
FFXIOrgins/FFXIOrgins | scripts/globals/items/roast_pipira.lua | 35 | 1575 | -----------------------------------------
-- ID: 4538
-- Item: roast_pipira
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Dexterity 3
-- Mind -1
-- Attack % 14
-- Attack Cap 85
-- Ranged ATT % 14
-- Ranged ATT Cap 85
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4538);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -1);
target:addMod(MOD_FOOD_ATTP, 14);
target:addMod(MOD_FOOD_ATT_CAP, 85);
target:addMod(MOD_FOOD_RATTP, 14);
target:addMod(MOD_FOOD_RATT_CAP, 85);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -1);
target:delMod(MOD_FOOD_ATTP, 14);
target:delMod(MOD_FOOD_ATT_CAP, 85);
target:delMod(MOD_FOOD_RATTP, 14);
target:delMod(MOD_FOOD_RATT_CAP, 85);
end;
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Dynamis-Xarcabard/mobs/Animated_Great_Axe.lua | 17 | 1489 | -----------------------------------
-- Area: Dynamis Xarcabard
-- NPC: Animated Great Axe
-----------------------------------
require("scripts/globals/status");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if(mob:AnimationSub() == 3) then
SetDropRate(104,1576,1000);
else
SetDropRate(104,1576,0);
end
target:showText(mob,ANIMATED_GREATAXE_DIALOG);
SpawnMob(17330383,120):updateEnmity(target);
SpawnMob(17330384,120):updateEnmity(target);
SpawnMob(17330385,120):updateEnmity(target);
SpawnMob(17330395,120):updateEnmity(target);
SpawnMob(17330396,120):updateEnmity(target);
SpawnMob(17330397,120):updateEnmity(target);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
-- TODO: add battle dialog
end;
-----------------------------------
-- onMobDisengage
-----------------------------------
function onMobDisengage(mob)
mob:showText(mob,ANIMATED_GREATAXE_DIALOG+2);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
killer:showText(mob,ANIMATED_GREATAXE_DIALOG+1);
DespawnMob(17330383);
DespawnMob(17330384);
DespawnMob(17330385);
DespawnMob(17330395);
DespawnMob(17330396);
DespawnMob(17330397);
end; | gpl-3.0 |
marcovr/T-Bot | libs/other.lua | 1 | 2944 | --[[ Docs:
This library is just a random collection of functions which don't fit into another library.
table.deepcopy(variable)
Makes a true copy (not just a reference) of a given variable.
table.show(table)
Returns a readable representation of a table as string.
stringify(...)
Like to tostring() but supports multiple arguments and displays tables.
getArguments(text)
Returns a table of arguments extracted from text.
]]
function table.deepcopy(orig)
if type(orig) == 'table' then
local copy = {}
for orig_key, orig_value in next, orig, nil do
copy[table.deepcopy(orig_key)] = table.deepcopy(orig_value)
end
setmetatable(copy, table.deepcopy(getmetatable(orig)))
return copy
else -- number, string, boolean, etc
return orig
end
end
function table.show(tbl, i, seen)
if not seen then
seen = {}
seen[seen] = true
end
if not i then
i = ""
end
local text = "{\n"
local s={}
local i2 = i.."\t"
seen[tbl]=true
for k in pairs(tbl) do
table.insert(s, k)
end
table.sort(s)
for k,v in ipairs(s) do
text = text..i2..tostring(v)
v = tbl[v]
if type(v) == "function" then
text = text.."()\n"
elseif type(v) == "table" and not seen[v] then
text = text.." = "..table.show(v, i2, seen).."\n"
else
text = text.." = "..tostring(v).."\n"
end
end
return text..i .."}"
end
function stringify(...)
local args = {...}
local n = select("#", ...)
for i = 1, n do
if type(args[i]) == "table" then
args[i] = table.show(args[i])
else
args[i] = tostring(args[i])
end
end
return table.concat(args, " ")
end
function getArguments(text)
local words = {}
for word in string.gmatch(string.sub(text, 2), "%S+") do
table.insert(words, word)
end
local args = {}
local quoteClosed = true
local skip = 2
for k = 2, #words do -- Quotes parsen
if k >= skip then
local word = words[k]
if string.sub(word, -1) == "\"" and string.sub(word, 1, 1) == "\"" then -- Wenn Anfangsquote auch Endquote ist
table.insert(args, string.sub(word, 2, -2))
elseif string.sub(word, 1, 1) == "\"" then -- Wenn Anfangsquote gefunden wurde
quoteClosed = false
for i = k + 1, #words do -- Durch alle restlichen Argumente gehen und Endquote suchen
if string.sub(words[i], -1) == "\"" then -- Wenn Endquote gefunden wurde
quoteClosed = true -- Quote wurde geschlossen
local arg = string.sub(word, 2) -- Argument mit Anfangsquote zu arg hinzufügen
for j = k + 1, i - 1 do -- Von Anfangs+1 bis Endquote-1 durchgehen
arg = arg.." "..words[j] -- Argumente zwischen Anfangs und Endquote zu arg hinzufügen
end
arg = arg.." "..string.sub(words[i], 1, -2) -- Argument mit Endquote zu arg hinzufügen
skip = i + 1 -- Bis nach die Quote skippen
table.insert(args, arg) -- arg in neues Argument-Table hinzufügen
break
end
end
else
table.insert(args, word)
end
end
end
return quoteClosed, args
end | gpl-2.0 |
sjznxd/luci-0.11-aa | applications/luci-openvpn/luasrc/model/cbi/openvpn-advanced.lua | 10 | 20093 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: openvpn-advanced.lua 7774 2011-10-24 18:18:09Z soma $
]]--
require("luci.ip")
require("luci.model.uci")
local knownParams = {
--
-- Widget Name Default(s) Description Option(s)
--
{ "Service", {
-- initialisation and daemon options
{ ListValue, "verb", { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, translate("Set output verbosity") },
{ Flag, "mlock", 0, translate("Disable Paging") },
{ Flag, "disable_occ", 0, translate("Disable options consistency check") },
-- { Value, "user", "root", translate("Set UID to user") },
-- { Value, "group", "root", translate("Set GID to group") },
{ Value, "cd", "/etc/openvpn", translate("Change to directory before initialization") },
{ Value, "chroot", "/var/run", translate("Chroot to directory after initialization") },
-- { Value, "daemon", "Instance-Name", translate("Daemonize after initialization") },
-- { Value, "syslog", "Instance-Name", translate("Output to syslog and do not daemonize") },
{ Flag, "passtos", 0, translate("TOS passthrough (applies to IPv4 only)") },
-- { Value, "inetd", "nowait Instance-Name", translate("Run as an inetd or xinetd server") },
{ Value, "log", "/var/log/openvpn.log", translate("Write log to file") },
{ Value, "log_append", "/var/log/openvpn.log", translate("Append log to file") },
{ Flag, "suppress_timestamps", 0, translate("Don't log timestamps") },
-- { Value, "writepid", "/var/run/openvpn.pid", translate("Write process ID to file") },
{ Value, "nice", 0, translate("Change process priority") },
{ Flag, "fast_io", 0, translate("Optimize TUN/TAP/UDP writes") },
{ Value, "echo", "some params echoed to log", translate("Echo parameters to log") },
{ ListValue, "remap_usr1", { "SIGHUP", "SIGTERM" }, translate("Remap SIGUSR1 signals") },
{ Value, "status", "/var/run/openvpn.status 5", translate("Write status to file every n seconds") },
{ Value, "status_version", { 1, 2 }, translate("Status file format version") }, -- status
{ Value, "mute", 5, translate("Limit repeated log messages") },
{ Value, "up", "/usr/bin/ovpn-up", translate("Shell cmd to execute after tun device open") },
{ Value, "up_delay", 5, translate("Delay tun/tap open and up script execution") },
{ Value, "down", "/usr/bin/ovpn-down", translate("Shell cmd to run after tun device close") },
{ Flag, "down_pre", 0, translate("Call down cmd/script before TUN/TAP close") },
{ Flag, "up_restart", 0, translate("Run up/down scripts for all restarts") },
{ Value, "route_up", "/usr/bin/ovpn-routeup", translate("Execute shell cmd after routes are added") },
{ Value, "ipchange", "/usr/bin/ovpn-ipchange", translate("Execute shell command on remote ip change"), { mode="p2p" } },
{ DynamicList, "setenv", { "VAR1 value1", "VAR2 value2" }, translate("Pass environment variables to script") },
{ Value, "tls_verify", "/usr/bin/ovpn-tlsverify", translate("Shell command to verify X509 name") },
{ Value, "client_connect", "/usr/bin/ovpn-clientconnect", translate("Run script cmd on client connection") },
{ Flag, "client_disconnect", 0, translate("Run script cmd on client disconnection") },
{ Value, "learn_address", "/usr/bin/ovpn-learnaddress", translate("Executed in server mode whenever an IPv4 address/route or MAC address is added to OpenVPN's internal routing table") },
{ Value, "auth_user_pass_verify", "/usr/bin/ovpn-userpass via-env", translate("Executed in server mode on new client connections, when the client is still untrusted") },
{ ListValue, "script_security", { 0, 1, 2, 3 }, translate("Policy level over usage of external programs and scripts"), {mode="server" } },
} },
{ "Networking", {
-- socket config
{ ListValue, "mode", { "p2p", "server" }, translate("Major mode") },
{ Value, "local", "0.0.0.0", translate("Local host name or ip address") },
{ Value, "port", 1194, translate("TCP/UDP port # for both local and remote") },
{ Value, "lport", 1194, translate("TCP/UDP port # for local (default=1194)") },
{ Value, "rport", 1194, translate("TCP/UDP port # for remote (default=1194)") },
{ Flag, "float", 0, translate("Allow remote to change its IP or port") },
{ Flag, "nobind", 0, translate("Do not bind to local address and port") },
{ Value, "dev", "tun0", translate("tun/tap device") },
{ ListValue, "dev_type", { "tun", "tap" }, translate("Type of used device") },
{ Value, "dev_node", "/dev/net/tun", translate("Use tun/tap device node") },
{ Flag, "tun_ipv6", 0, translate("Make tun device IPv6 capable") },
{ Value, "ifconfig", "10.200.200.3 10.200.200.1", translate("Set tun/tap adapter parameters") },
{ Flag, "ifconfig_noexec", 0, translate("Don't actually execute ifconfig") },
{ Flag, "ifconfig_nowarn", 0, translate("Don't warn on ifconfig inconsistencies") },
{ DynamicList, "route", "10.123.0.0 255.255.0.0", translate("Add route after establishing connection") },
{ Value, "route_gateway", "10.234.1.1", translate("Specify a default gateway for routes") },
{ Value, "route_delay", 0, translate("Delay n seconds after connection") },
{ Flag, "route_noexec", 0, translate("Don't add routes automatically") },
{ ListValue, "mtu_disc", { "yes", "maybe", "no" }, translate("Enable Path MTU discovery") },
{ Flag, "mtu_test", 0, translate("Empirically measure MTU") },
{ Flag, "comp_lzo", 0, translate("Use fast LZO compression") },
{ Flag, "comp_noadapt", 0, translate("Don't use adaptive lzo compression"), { comp_lzo=1 } },
{ Value, "link_mtu", 1500, translate("Set TCP/UDP MTU") },
{ Value, "tun_mtu", 1500, translate("Set tun/tap device MTU") },
{ Value, "tun_mtu_extra", 1500, translate("Set tun/tap device overhead") },
{ Value, "fragment", 1500, translate("Enable internal datagram fragmentation"), { proto="udp" } },
{ Value, "mssfix", 1500, translate("Set upper bound on TCP MSS"), { proto="udp" } },
{ Value, "sndbuf", 65536, translate("Set the TCP/UDP send buffer size") },
{ Value, "rcvbuf", 65536, translate("Set the TCP/UDP receive buffer size") },
{ Value, "txqueuelen", 100, translate("Set tun/tap TX queue length") },
{ Value, "shaper", 10240, translate("Shaping for peer bandwidth") },
{ Value, "inactive", 240, translate("tun/tap inactivity timeout") },
{ Value, "keepalive", "10 60", translate("Helper directive to simplify the expression of --ping and --ping-restart in server mode configurations") },
{ Value, "ping", 30, translate("Ping remote every n seconds over TCP/UDP port") },
{ Value, "ping_exit", 120, translate("Remote ping timeout") },
{ Value, "ping_restart", 60, translate("Restart after remote ping timeout") },
{ Flag, "ping_timer_rem", 0, translate("Only process ping timeouts if routes exist") },
{ Flag, "persist_tun", 0, translate("Keep tun/tap device open on restart") },
{ Flag, "persist_key", 0, translate("Don't re-read key on restart") },
{ Flag, "persist_local_ip", 0, translate("Keep local IP address on restart") },
{ Flag, "persist_remote_ip", 0, translate("Keep remote IP address on restart") },
-- management channel
{ Value, "management", "127.0.0.1 31194 /etc/openvpn/mngmt-pwds", translate("Enable management interface on <em>IP</em> <em>port</em>") },
{ Flag, "management_query_passwords", 0, translate("Query management channel for private key") }, -- management
{ Flag, "management_hold", 0, translate("Start OpenVPN in a hibernating state") }, -- management
{ Value, "management_log_cache", 100, translate("Number of lines for log file history") }, -- management
{ ListValue, "topology", { "net30", "p2p", "subnet" }, translate("'net30', 'p2p', or 'subnet'"), {dev_type="tun" } },
} },
{ "VPN", {
{ Value, "server", "10.200.200.0 255.255.255.0", translate("Configure server mode"), { server_mode="1" } },
{ Value, "server_bridge", "10.200.200.1 255.255.255.0 10.200.200.200 10.200.200.250", translate("Configure server bridge"), { server_mode="1" } },
{ DynamicList, "push", { "redirect-gateway", "comp-lzo" }, translate("Push options to peer"), { server_mode="1" } },
{ Flag, "push_reset", 0, translate("Don't inherit global push options"), { server_mode="1" } },
{ Flag, "disable", 0, translate("Client is disabled"), { server_mode="1" } },
{ Value, "ifconfig_pool", "10.200.200.100 10.200.200.150 255.255.255.0", translate("Set aside a pool of subnets"), { server_mode="1" } },
{ Value, "ifconfig_pool_persist", "/etc/openvpn/ipp.txt 600", translate("Persist/unpersist ifconfig-pool"), { server_mode="1" } },
-- { Flag, "ifconfig_pool_linear", 0, translate("Use individual addresses rather than /30 subnets"), { server_mode="1" } }, -- deprecated and replaced by --topology p2p
{ Value, "ifconfig_push", "10.200.200.1 255.255.255.255", translate("Push an ifconfig option to remote"), { server_mode="1" } },
{ Value, "iroute", "10.200.200.0 255.255.255.0", translate("Route subnet to client"), { server_mode="1" } },
{ Flag, "client_to_client", 0, translate("Allow client-to-client traffic"), { server_mode="1" } },
{ Flag, "duplicate_cn", 0, translate("Allow multiple clients with same certificate"), { server_mode="1" } },
{ Value, "client_config_dir", "/etc/openvpn/ccd", translate("Directory for custom client config files"), { server_mode="1" } },
{ Flag, "ccd_exclusive", 0, translate("Refuse connection if no custom client config"), { server_mode="1" } },
{ Value, "tmp_dir", "/var/run/openvpn", translate("Temporary directory for client-connect return file"), { server_mode="1" } },
{ Value, "hash_size", "256 256", translate("Set size of real and virtual address hash tables"), { server_mode="1" } },
{ Value, "bcast_buffers", 256, translate("Number of allocated broadcast buffers"), { server_mode="1" } },
{ Value, "tcp_queue_limit", 64, translate("Maximum number of queued TCP output packets"), { server_mode="1" } },
{ Value, "max_clients", 10, translate("Allowed maximum of connected clients"), { server_mode="1" } },
{ Value, "max_routes_per_client", 256, translate("Allowed maximum of internal"), { server_mode="1" } },
{ Value, "connect_freq", "3 10", translate("Allowed maximum of new connections"), { server_mode="1" } },
{ Flag, "client_cert_not_required", 0, translate("Don't require client certificate"), { server_mode="1" } },
{ Flag, "username_as_common_name", 0, translate("Use username as common name"), { server_mode="1" } },
{ Flag, "client", 0, translate("Configure client mode"), { server_mode="0" }, { server_mode="" } },
{ Flag, "pull", 0, translate("Accept options pushed from server"), { client="1" } },
{ Value, "auth_user_pass", "/etc/openvpn/userpass.txt", translate("Authenticate using username/password"), { client="1" } },
{ ListValue, "auth_retry", { "none", "nointeract", "interact" }, translate("Handling of authentication failures"), { client="1" } },
{ Value, "explicit_exit_notify", 1, translate("Send notification to peer on disconnect"), { client="1" } },
{ DynamicList, "remote", "1.2.3.4", translate("Remote host name or ip address"), { client="1" } },
{ Flag, "remote_random", 1, translate("Randomly choose remote server"), { client="1" } },
{ ListValue, "proto", { "udp", "tcp-client", "tcp-server" }, translate("Use protocol"), { client="1" } },
{ Value, "connect_retry", 5, translate("Connection retry interval"), { proto="tcp-client" }, { client="1" } },
{ Value, "http_proxy", "192.168.1.100 8080", translate("Connect to remote host through an HTTP proxy"), { client="1" } },
{ Flag, "http_proxy_retry", 0, translate("Retry indefinitely on HTTP proxy errors"), { client="1" } },
{ Value, "http_proxy_timeout", 5, translate("Proxy timeout in seconds"), { client="1" } },
{ DynamicList, "http_proxy_option", { "VERSION 1.0", "AGENT OpenVPN/2.0.9" }, translate("Set extended HTTP proxy options"), { client="1" } },
{ Value, "socks_proxy", "192.168.1.200 1080", translate("Connect through Socks5 proxy"), { client="1" } },
{ Value, "socks_proxy_retry", 5, translate("Retry indefinitely on Socks proxy errors"), { client="1" } }, -- client && socks_proxy
{ Value, "resolv_retry", "infinite", translate("If hostname resolve fails, retry"), { client="1" } },
{ ListValue, "redirect_gateway", { "", "local", "def1", "local def1" }, translate("Automatically redirect default route"), { client="1" } },
} },
{ "Cryptography", {
{ Value, "secret", "/etc/openvpn/secret.key 1", translate("Enable Static Key encryption mode (non-TLS)") },
{ Value, "auth", "SHA1", translate("HMAC authentication for packets") }, -- parse
{ Value, "cipher", "BF-CBC", translate("Encryption cipher for packets") }, -- parse
{ Value, "keysize", 1024, translate("Size of cipher key") }, -- parse
{ Value, "engine", "dynamic", translate("Enable OpenSSL hardware crypto engines") }, -- parse
{ Flag, "no_replay", 0, translate("Disable replay protection") },
{ Value, "replay_window", "64 15", translate("Replay protection sliding window size") },
{ Flag, "mute_replay_warnings", 0, translate("Silence the output of replay warnings") },
{ Value, "replay_persist", "/var/run/openvpn-replay-state", translate("Persist replay-protection state") },
{ Flag, "no_iv", 0, translate("Disable cipher initialisation vector") },
{ Flag, "tls_server", 0, translate("Enable TLS and assume server role"), { tls_client="" }, { tls_client="0" } },
{ Flag, "tls_client", 0, translate("Enable TLS and assume client role"), { tls_server="" }, { tls_server="0" } },
{ FileUpload, "ca", "/etc/easy-rsa/keys/ca.crt", translate("Certificate authority") },
{ FileUpload, "dh", "/etc/easy-rsa/keys/dh1024.pem", translate("Diffie Hellman parameters") },
{ FileUpload, "cert", "/etc/easy-rsa/keys/some-client.crt", translate("Local certificate") },
{ FileUpload, "key", "/etc/easy-rsa/keys/some-client.key", translate("Local private key") },
{ FileUpload, "pkcs12", "/etc/easy-rsa/keys/some-client.pk12", translate("PKCS#12 file containing keys") },
{ ListValue, "key_method", { 1, 2 }, translate("Enable TLS and assume client role") },
{ Value, "tls_cipher", "DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-SHA:EDH-RSA-DES-CBC3-SHA:EDH-DSS-DES-CBC3-SHA:DES-CBC3-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:AES128-SHA:RC4-SHA:RC4-MD5:EDH-RSA-DES-CBC-SHA:EDH-DSS-DES-CBC-SHA:DES-CBC-SHA:EXP-EDH-RSA-DES-CBC-SHA:EXP-EDH-DSS-DES-CBC-SHA:EXP-DES-CBC-SHA:EXP-RC2-CBC-MD5:EXP-RC4-MD5",
translate("TLS cipher") },
{ Value, "tls_timeout", 2, translate("Retransmit timeout on TLS control channel") },
{ Value, "reneg_bytes", 1024, translate("Renegotiate data chan. key after bytes") },
{ Value, "reneg_pkts", 100, translate("Renegotiate data chan. key after packets") },
{ Value, "reneg_sec", 3600, translate("Renegotiate data chan. key after seconds") },
{ Value, "hand_window", 60, translate("Timeframe for key exchange") },
{ Value, "tran_window", 3600, translate("Key transition window") },
{ Flag, "single_session", 0, translate("Allow only one session") },
{ Flag, "tls_exit", 0, translate("Exit on TLS negotiation failure") },
{ Value, "tls_auth", "/etc/openvpn/tlsauth.key 1", translate("Additional authentication over TLS") },
--{ Value, "askpass", "[file]", translate("Get PEM password from controlling tty before we daemonize") },
{ Flag, "auth_nocache", 0, translate("Don't cache --askpass or --auth-user-pass passwords") },
{ Value, "tls_remote", "remote_x509_name", translate("Only accept connections from given X509 name") },
{ ListValue, "ns_cert_type", { "client", "server" }, translate("Require explicit designation on certificate") },
{ ListValue, "remote_cert_tls", { "client", "server" }, translate("Require explicit key usage on certificate") },
{ Value, "crl_verify", "/etc/easy-rsa/keys/crl.pem", translate("Check peer certificate against a CRL") },
} }
}
local cts = { }
local params = { }
local m = Map("openvpn")
local p = m:section( SimpleSection )
p.template = "openvpn/pageswitch"
p.mode = "advanced"
p.instance = arg[1]
p.category = arg[2] or "Service"
for _, c in ipairs(knownParams) do
cts[#cts+1] = c[1]
if c[1] == p.category then params = c[2] end
end
p.categories = cts
local s = m:section(
NamedSection, arg[1], "openvpn",
translate("%s" % arg[2])
)
s.title = translate("%s" % arg[2])
s.addremove = false
s.anonymous = true
for _, option in ipairs(params) do
local o = s:option(
option[1], option[2],
option[2], option[4]
)
if option[1] == DummyValue then
o.value = option[3]
else
if option[1] == DynamicList then
o.cast = nil
function o.cfgvalue(...)
local val = AbstractValue.cfgvalue(...)
return ( val and type(val) ~= "table" ) and { val } or val
end
end
o.optional = true
if type(option[3]) == "table" then
if o.optional then o:value("", "-- remove --") end
for _, v in ipairs(option[3]) do
v = tostring(v)
o:value(v)
end
o.default = tostring(option[3][1])
else
o.default = tostring(option[3])
end
end
for i=5,#option do
if type(option[i]) == "table" then
o:depends(option[i])
end
end
end
return m
| apache-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Lower_Jeuno/npcs/_l04.lua | 36 | 1559 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Streetlamp
-- Involved in Quests: Community Service
-- @zone 245
-- @pos -73.039 6 -95.633
-----------------------------------
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") == 7) then
player:setVar("cService",8);
end
elseif (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then
if (player:getVar("cService") == 20) then
player:setVar("cService",21);
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 |
msburgess3200/PERP | gamemodes/perp/gamemode/items/furniture_wood_simple_table.lua | 1 | 1222 |
local ITEM = {};
ITEM.ID = 79;
ITEM.Reference = "furniture_wood_simple_table";
ITEM.Name = "Simplistic Table";
ITEM.Description = "Looks a bit rotten in some parts...\n\nLeft click to spawn as prop.";
ITEM.Weight = 30;
ITEM.Cost = 500;
ITEM.MaxStack = 100;
ITEM.InventoryModel = "models/props/cs_militia/wood_table.mdl";
ITEM.ModelCamPos = Vector(33, 76, 52);
ITEM.ModelLookAt = Vector(0, 0, 0);
ITEM.ModelFOV = 70;
ITEM.WorldModel = "models/props/cs_militia/wood_table.mdl";
ITEM.RestrictedSelling = false; // Used for drugs and the like. So we can't sell it.
ITEM.EquipZone = nil;
ITEM.PredictUseDrop = false; // If this isn't true, the server will tell the client when something happens to us.
if SERVER then
function ITEM.OnUse ( Player )
local prop = Player:SpawnProp(ITEM);
if (!prop || !IsValid(prop)) then return false; end
return true;
end
function ITEM.OnDrop ( Player )
return true;
end
function ITEM.Equip ( Player )
end
function ITEM.Holster ( Player )
end
else
function ITEM.OnUse ( slotID )
return true;
end
function ITEM.OnDrop ( )
return true;
end
end
GM:RegisterItem(ITEM); | mit |
FFXIOrgins/FFXIOrgins | scripts/zones/Northern_San_dOria/npcs/Arachagnon.lua | 36 | 1818 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Arachagnon
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,ARACHAGNON_SHOP_DIALOG);
stock = {0x3159,270, --Elvaan Jerkin
0x315a,270, --Elvaan Bodice
0x31d3,162, --Elvaan Gloves
0x31d7,162, --Elvaan Gauntlets
0x3255,234, --Elvaan M Chausses
0x3259,234, --Elvaan F Chausses
0x32ce,162, --Elvaan M Ledelsens
0x32d3,162} --Elvaan F Ledelsens
showShop(player, SANDORIA, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
realtime-framework/RealtimeMessaging-Lua | OrtcClient/src/ibt/ortc/plugin/OrtcClient.lua | 1 | 22573 | -- Comment these requires when generating unique file with squish
-- http://matthewwild.co.uk/projects/squish
package.path = package.path..";../OrtcClient/src/ibt/ortc/extensibility/?.lua;../OrtcClient/src/ibt/ortc/websocket/?.lua"
require("ProxyProperties")
require("Strings")
require("WebSocketConnection")
require("lfs")
local URI = nil
URI = require ("uri")
OrtcClient = {}
OrtcClient.__index = OrtcClient
local http = require "socket.http"
--local linda = lanes.linda()
local OPERATION_PATTERN = "^a%[\"{\\\"op\\\":\\\"(.-[^\\\"]+)\\\",(.*)}\"%]$"
local CLOSE_PATTERN = "^c%[(.*[^\"]+),\"(.*)\"%]$"
local VALIDATED_PATTERN = "^\\\"up\\\":(.*),\\\"set\\\":(.*)$"
local CHANNEL_PATTERN = "^\\\"ch\\\":\\\"(.*)\\\"$"
local EXCEPTION_PATTERN_1 = "^\\\"ex\\\":{\\\"op\\\":\\\"(.*[^\"]+)\\\",\\\"ex\\\":\\\"(.*)\\\"}$"
local EXCEPTION_PATTERN_2 = "^\\\"ex\\\":{\\\"op\\\":\\\"(.*[^\"]+)\\\",\\\"ch\\\":\\\"(.*)\\\",\\\"ex\\\":\\\"(.*)\\\"}$"
local RECEIVED_PATTERN = "^a%[\"{\\\"ch\\\":\\\"(.*)\\\",\\\"m\\\":\\\"([%s%S]*)\\\"}\"%]$"
local MULTI_PART_MESSAGE_PATTERN = "^(.[^_]*)_(.[^-]*)-(.[^_]*)_([%s%S]*)$"
local PERMISSIONS_PATTERN = "\\\"(.[^\\\"]+)\\\":\\\"(.[^,\\\"]+)\\\",?"
local CLUSTER_RESPONSE_PATTERN = "var SOCKET_SERVER = \"(.*)\";"
local MAX_MESSAGE_SIZE = 800
local MAX_CHANNEL_SIZE = 100
local MAX_CONNECTION_METADATA_SIZE = 256
local SESSION_STORAGE_NAME = "ortcsession-"
local conn = nil
local isCluster = nil
local subscribedChannels = nil
local messagesBuffer = nil
local permissions = nil
local isConnecting = nil
local isReconnecting = nil
local isValid = nil
local stopReconnecting = nil
local sessionExpirationTime = nil
-- private
local attributeSetters = {
url = function(self, url)
isCluster = false
local priv = getmetatable(self).priv
priv.url = Strings:trim(url)
end,
clusterUrl = function(self, clusterUrl)
isCluster = true
local priv = getmetatable(self).priv
priv.clusterUrl = Strings:trim(clusterUrl)
end
}
-- private: Calls the onConnected callback if defined.
local function delegateConnectedCallback (ortc)
if ortc and ortc.onConnected then
ortc.onConnected(ortc)
end
end
-- private: Calls the onDisconnected callback if defined.
local function delegateDisconnectedCallback (ortc)
if ortc and ortc.onDisconnected then
ortc.onDisconnected(ortc)
end
end
-- private: Calls the onSubscribed callback if defined.
local function delegateSubscribedCallback (ortc, channel)
if ortc and ortc.onSubscribed and channel then
ortc.onSubscribed(ortc, channel)
end
end
-- private: Calls the onUnsubscribed callback if defined.
local function delegateUnsubscribedCallback (ortc, channel)
if ortc and ortc.onUnsubscribed and channel then
ortc.onUnsubscribed(ortc, channel)
end
end
-- private: Calls the onMessages callbacks if defined.
local function delegateMessagesCallback (ortc, channel, message)
if ortc and subscribedChannels[channel] and subscribedChannels[channel].isSubscribed and subscribedChannels[channel].onMessageCallback then
subscribedChannels[channel].onMessageCallback(ortc, channel, message)
end
end
-- private: Calls the onException callback if defined.
local function delegateExceptionCallback (ortc, event)
if ortc and ortc.onException then
ortc.onException(ortc, event)
end
end
-- private: Calls the onReconnecting callback if defined.
local function delegateReconnectingCallback (ortc)
if ortc and ortc.onReconnecting then
ortc.onReconnecting(ortc)
end
end
-- private: Calls the onReconnected callback if defined.
local function delegateReconnectedCallback (ortc)
if ortc and ortc.onReconnected then
ortc.onReconnected(ortc)
end
end
-- private
local function getClusterServer (clusterUrl)
local response = http.request(clusterUrl)
local url = nil
if response ~= nil then
_, _, url = string.find(response, CLUSTER_RESPONSE_PATTERN)
end
return url
end
--private
local function doReconnect (self)
self.isConnected = false
if not stopReconnecting then
isReconnecting = true
delegateReconnectingCallback(self)
self:doConnect()
end
end
-- private
local function doStopReconnecting ()
isConnecting = false
-- Stop the connecting/reconnecting process
stopReconnecting = true
end
-- private
local function messageArrived (self, x)
if type(x) == "table" then
for k = 1, table.getn(x) do
local message = x[k]
--print(message)
if message ~= "o" and message ~= "h" then
message = string.gsub(message, "\\\\\\\\", "\\")
local _, _, op, args = string.find(message, "^(.*[^;]+);(.*)$")
--if op == nil then
--print("timed out")
if op ~= nil then
if op == "handshake" then
if args == "1" then
local status, err = pcall(function ()
if unexpected_condition then
error()
end
self.sessionId = Strings:generateId(16)
conn:send("\"validate;"..self.appKey..";"..self.authToken..";"..(self.announcementSubChannel or "")..";"..(self.sessionId or "")..";"..(self.connectionMetadata or "").."\"")
end)
if err ~= nil then
delegateExceptionCallback(self, err)
doStopReconnecting()
conn:disconnect()
end
else
delegateExceptionCallback(self, "Unable to perform handshake")
end
elseif op == "disconnected" then
-- Clear user permissions
permissions = {}
isConnecting = false
isReconnecting = false
if isValid then
delegateDisconnectedCallback(self)
if self.isConnected then
doReconnect(self)
end
end
self.isConnected = false
elseif op == "reconnect" then
isConnecting = false
delegateExceptionCallback(self, "Unable to connect")
socket.sleep(self.connectionTimeout / 1000)
doReconnect(self)
end
else
local _, _, op, args = string.find(message, OPERATION_PATTERN)
if op ~= nil then
if op == "ortc-validated" then
local _, _, perms, set = string.find(args, VALIDATED_PATTERN)
local statusC, errC
if set ~= nil then
sessionExpirationTime = set
end
if perms ~= nil then
for channel, hash in string.gmatch(perms, PERMISSIONS_PATTERN) do
permissions[channel] = hash
end
self.isConnected = true
isConnecting = false
isValid = true
-- Subscribe to the previously subscribed channels
for channel,channelSubscription in pairs(subscribedChannels) do
-- Subscribe again
if channelSubscription.subscribeOnReconnected and (channelSubscription.isSubscribing or channelSubscription.isSubscribed) then
channelSubscription.isSubscribing = true
channelSubscription.isSubscribed = false
local domainChannelCharacterIndex = string.find(channel, ":")
local channelToValidate = channel
if domainChannelCharacterIndex ~= nil and domainChannelCharacterIndex > 0 then
channelToValidate = string.sub(channel, 1, domainChannelCharacterIndex).."*"
end
local hash = (permissions[channel] ~= nil and permissions[channel] or permissions[channelToValidate] ~= nil and permissions[channelToValidate] or "")
conn:send("\"subscribe;"..self.appKey..";"..self.authToken..";"..channel..";"..hash.."\"")
end
end
-- Clean messages buffer (can have lost message parts in memory)
messagesBuffer = {}
if isReconnecting then
isReconnecting = false
delegateReconnectedCallback(self)
else
delegateConnectedCallback(self)
end
end
elseif op == "ortc-subscribed" then
local _, _, channel = string.find(args, CHANNEL_PATTERN)
if subscribedChannels[channel] ~= nil then
subscribedChannels[channel].isSubscribing = false
subscribedChannels[channel].isSubscribed = true
end
delegateSubscribedCallback(self, channel)
elseif op == "ortc-unsubscribed" then
local _, _, channel = string.find(args, CHANNEL_PATTERN)
delegateUnsubscribedCallback(self, channel)
elseif op == "ortc-error" then
local _, _, opException, chnException, msgException = string.find(args, EXCEPTION_PATTERN_2)
if opException == nil then
_, _, opException, msgException = string.find(args, EXCEPTION_PATTERN_1)
end
delegateExceptionCallback(self, msgException)
if opException == "validate" then
isValid = false
doStopReconnecting()
elseif opException == "subscribe" then
if not Strings:isNullOrEmpty(chnException) then
if subscribedChannels[chnException] then
subscribedChannels[chnException].isSubscribing = false
end
end
elseif opException == "subscribe_maxsize" or opException == "unsubscribe_maxsize" or opException == "send_maxsize" then
if not Strings:isNullOrEmpty(chnException) then
if subscribedChannels[chnException] then
subscribedChannels[chnException].isSubscribing = false
end
end
doStopReconnecting()
self:disconnect()
end
end
else
local _, _, closeCode, closeReason = string.find(message, CLOSE_PATTERN)
if closeCode == nil and closeReason == nil then
local _, _, channel, messageReceived = string.find(message, RECEIVED_PATTERN)
if subscribedChannels[channel] then
messageReceived = string.gsub(string.gsub(messageReceived, "\\\\n", "\n"), "\\\\\\\"", "\"")
-- Multi part
local _, _, messageId, messageCurrentPart, messageTotalPart, plainTextMessage = string.find(messageReceived, MULTI_PART_MESSAGE_PATTERN)
local lastPart = false;
-- Is a message part
if not Strings:isNullOrEmpty(messageId) and not Strings:isNullOrEmpty(messageCurrentPart) and not Strings:isNullOrEmpty(messageTotalPart) then
if not messagesBuffer[messageId] then
messagesBuffer[messageId] = {}
end
messagesBuffer[messageId][tonumber(messageCurrentPart)] = plainTextMessage
-- Last message part
if tostring(Strings:tableSize(messagesBuffer[messageId])) == messageTotalPart then
lastPart = true
end
else -- Message does not have multipart, like the messages received at announcement channels
lastPart = true
end
if lastPart then
if not Strings:isNullOrEmpty(messageId) and not Strings:isNullOrEmpty(messageTotalPart) then
messageReceived = "";
for i = 1, messageTotalPart do
messageReceived = messageReceived..messagesBuffer[messageId][i]
-- Delete from messages buffer
messagesBuffer[messageId][i] = nil
end
-- Delete from messages buffer
messagesBuffer[messageId] = nil
end
subscribedChannels[channel].onMessageCallback(self, channel, messageReceived)
end
--else
--print("RECEIVED:")
--print(op)
--print(args)
end
end
end
end
end
end
end
end
-- constructor
function OrtcClient:new ()
local priv = {id, url, clusterUrl, connectionTimeout, isConnected, connectionMetadata, announcementSubChannel, sessionId, onConnected, onDisconnected, onSubscribed, onUnsubscribed, onException} -- private attributes in instance
local self = ProxyProperties:makeProxy(OrtcClient, priv, nil, attributeSetters, true)
-- Initialize random seed
math.randomseed(os.time())
math.random()
self.connectionTimeout = 5000 -- milliseconds
self.isConnected = false
sessionExpirationTime = 30 -- minutes
isConnecting = false
isReconnecting = false
isCluster = false
isValid = false
stopReconnecting = false
subscribedChannels = {}
messagesBuffer = {}
permissions = {}
return self
end
--public
function OrtcClient:doConnect ()
isConnecting = true
if isCluster then
local url = getClusterServer(self.clusterUrl)
if url ~= nil then
self.url = url
else
delegateExceptionCallback(self, "Unable to get URL from cluster")
end
end
if self.url ~= nil then
local uri = URI:new(self.url)
local serverId = Strings:randomNumber(1, 1000)
local connectionId = Strings:randomString(8)
local prefix = (uri:scheme() == "https") and "wss" or "ws"
connectionUrl = prefix.."://"..uri:host()..(uri:port() and ":"..uri:port() or "").."/broadcast/"..serverId.."/"..connectionId.."/websocket"
local connectionUrl = URI:new(connectionUrl)
local host = connectionUrl:host()
local port = connectionUrl:port()
local path = connectionUrl:path()
conn = WebSocketConnection:new{}
conn:connect(self, messageArrived, host, port, path)
end
end
-- private
function OrtcClient:connect (applicationKey, authenticationToken)
-- Sanity Checks
if self.isConnected then
delegateExceptionCallback(self, "Already connected")
elseif Strings:isNullOrEmpty(self.clusterUrl) and Strings:isNullOrEmpty(self.url) then
delegateExceptionCallback(self, "URL and Cluster URL are null or empty")
elseif Strings:isNullOrEmpty(applicationKey) then
delegateExceptionCallback(self, "Application Key is null or empty")
elseif Strings:isNullOrEmpty(authenticationToken) then
delegateExceptionCallback(self, "Authentication ToKen is null or empty")
elseif not isCluster and not Strings:ortcIsValidUrl(self.url) then
delegateExceptionCallback(self, "Invalid URL")
elseif isCluster and not Strings:ortcIsValidUrl(self.clusterUrl) then
delegateExceptionCallback(self, "Invalid Cluster URL")
elseif not Strings:ortcIsValidInput(applicationKey) then
delegateExceptionCallback(self, "Application Key has invalid characters")
elseif not Strings:ortcIsValidInput(authenticationToken) then
delegateExceptionCallback(self, "Authentication Token has invalid characters")
elseif not Strings:ortcIsValidInput(self.announcementSubChannel) then
delegateExceptionCallback(self, "Announcement Subchannel has invalid characters")
elseif not Strings:isNullOrEmpty(self.connectionMetadata) and string.len(self.connectionMetadata) > MAX_CONNECTION_METADATA_SIZE then
delegateExceptionCallback(self, "Connection metadata size exceeds the limit of "..MAX_CONNECTION_METADATA_SIZE.." characters")
elseif isConnecting or isReconnecting then
delegateExceptionCallback(self, "Already trying to connect")
else
if pcall(function ()
if unexpected_condition then
error()
end
if isCluster then
URI:new(self.clusterUrl)
else
URI:new(self.url)
end
end) then
stopReconnecting = false
self.appKey = applicationKey
self.authToken = authenticationToken
self:doConnect()
else
delegateExceptionCallback(self, "Invalid URL")
end
end
end
-- private
function OrtcClient:subscribe (channel, subscribeOnReconnected, onMessageCallback)
--Sanity Checks
if not self.isConnected then
delegateExceptionCallback(self, "Not connected")
elseif Strings:isNullOrEmpty(channel) then
delegateExceptionCallback(self, "Channel is null or empty")
elseif not Strings:ortcIsValidInput(channel) then
delegateExceptionCallback(self, "Channel has invalid characters")
elseif subscribedChannels[channel] and subscribedChannels[channel].isSubscribing then
delegateExceptionCallback(self, "Already subscribing to the channel "..channel)
elseif subscribedChannels[channel] and subscribedChannels[channel].isSubscribed then
delegateExceptionCallback(self, "Already subscribed to the channel "..channel)
elseif string.len(channel) > MAX_CHANNEL_SIZE then
delegateExceptionCallback(self, "Channel size exceeds the limit of "..MAX_CHANNEL_SIZE.." characters")
else
local domainChannelCharacterIndex = string.find(channel, ":")
local channelToValidate = channel
if domainChannelCharacterIndex ~= nil and domainChannelCharacterIndex > 0 then
channelToValidate = string.sub(channel, 1, domainChannelCharacterIndex).."*"
end
local hash = (permissions[channel] ~= nil and permissions[channel] or permissions[channelToValidate] ~= nil and permissions[channelToValidate] or "")
if Strings:tableSize(permissions) > 0 and Strings:isNullOrEmpty(hash) then
delegateExceptionCallback(self, "No permission found to subscribe to the channel '"..channel.."'")
else
if not subscribedChannels[channel] then
subscribedChannels[channel] = {}
end
subscribedChannels[channel].isSubscribing = true
subscribedChannels[channel].isSubscribed = false
subscribedChannels[channel].subscribeOnReconnected = subscribeOnReconnected
subscribedChannels[channel].onMessageCallback = onMessageCallback
conn:send("\"subscribe;"..self.appKey..";"..self.authToken..";"..channel..";"..hash.."\"")
end
end
end
-- private
function OrtcClient:unsubscribe (channel)
--Sanity Checks
if not self.isConnected then
delegateExceptionCallback(self, "Not connected")
elseif Strings:isNullOrEmpty(channel) then
delegateExceptionCallback(self, "Channel is null or empty")
elseif not Strings:ortcIsValidInput(channel) then
delegateExceptionCallback(self, "Channel has invalid characters")
elseif not subscribedChannels[channel] then
delegateExceptionCallback(self, "Not subscribed to the channel "..channel)
elseif string.len(channel) > MAX_CHANNEL_SIZE then
delegateExceptionCallback(self, "Channel size exceeds the limit of "..MAX_CHANNEL_SIZE.." characters")
else
conn:send("\"unsubscribe;"..self.appKey..";"..channel.."\"")
end
end
-- private
function OrtcClient:send (channel, message)
--Sanity Checks
if not self.isConnected then
delegateExceptionCallback(self, "Not connected")
elseif Strings:isNullOrEmpty(channel) then
delegateExceptionCallback(self, "Channel is null or empty")
elseif not Strings:ortcIsValidInput(channel) then
delegateExceptionCallback(self, "Channel has invalid characters")
elseif Strings:isNullOrEmpty(message) then
delegateExceptionCallback(self, "Message is null or empty")
elseif string.len(channel) > MAX_CHANNEL_SIZE then
delegateExceptionCallback(self, "Channel size exceeds the limit of "..MAX_CHANNEL_SIZE.." characters")
else
local domainChannelCharacterIndex = string.find(channel, ":")
local channelToValidate = channel
if domainChannelCharacterIndex ~= nil and domainChannelCharacterIndex > 0 then
channelToValidate = string.sub(channel, 1, domainChannelCharacterIndex).."*"
end
local hash = (permissions[channel] ~= nil and permissions[channel] or permissions[channelToValidate] ~= nil and permissions[channelToValidate] or "")
if Strings:tableSize(permissions) > 0 and Strings:isNullOrEmpty(hash) then
delegateExceptionCallback(self, "No permission found to send to the channel '"..channel.."'")
else
message = string.gsub(string.gsub(message, "\\", "\\\\"), "\\\\n", "\\n")
local messageParts = {}
local messageId = Strings:generateId(8)
-- Multi part
local allowedMaxSize = MAX_MESSAGE_SIZE - string.len(channel);
local i = 1
local index = 1
while i < string.len(message) do
-- Just one part
if string.len(message) <= allowedMaxSize then
messageParts[index] = message
break
end
if string.sub(message, i, i + allowedMaxSize) then
messageParts[index] = string.sub(message, i, i + allowedMaxSize)
end
i = i + allowedMaxSize
index = index + 1
end
for j = 1, Strings:tableSize(messageParts) do
conn:send("\"send;"..self.appKey..";"..self.authToken..";"..channel..";"..hash..";"..messageId.."_"..j.."-"..Strings:tableSize(messageParts).."_"..messageParts[j].."\"")
end
end
end
end
-- private
function OrtcClient:disconnect ()
doStopReconnecting()
-- Clear subscribed channels
subscribedChannels = {}
--Sanity Checks
if not self.isConnected then
delegateExceptionCallback(self, "Not connected")
else
conn:disconnect()
end
end
-- private
function OrtcClient:isSubscribed (channel)
result = nil
--Sanity Checks
if not self.isConnected then
delegateExceptionCallback(self, "Not connected")
elseif Strings:isNullOrEmpty(channel) then
delegateExceptionCallback(self, "Channel is null or empty")
elseif not Strings:ortcIsValidInput(channel) then
delegateExceptionCallback(self, "Channel has invalid characters")
else
result = subscribedChannels[channel] and subscribedChannels[channel].isSubscribed and true or false
end
return result
end
-- private
function OrtcClient:saveAuthentication (url, isCluster, authenticationToken, authenticationTokenIsPrivate, applicationKey, timeToLive, privateKey, permissions, callback)
local result = false
local newUrl = nil
local err = nil
if isCluster then
newUrl = getClusterServer(url)
if newUrl == nil then
delegateExceptionCallback(self, "Unable to get URL from cluster")
end
else
newUrl = url
end
if newUrl ~= nil then
newUrl = (string.sub(newUrl, string.len(url)) == "/" and newUrl or (newUrl.."/")).."authenticate"
local body = "AT="..authenticationToken.."&PVT="..(authenticationTokenIsPrivate and "1" or "0").."&AK="..applicationKey.."&TTL="..timeToLive.."&PK="..privateKey.."&TP="..Strings:tableSize(permissions)
if permissions ~= nil then
for k,v in pairs(permissions) do
body = body.."&"..k.."="..v
end
end
local response, code = http.request(newUrl, body)
if code == 200 or code == 201 then
result = true
else
err = response
end
callback(err, result)
end
end
| mit |
Gael-de-Sailly/minetest-minetestforfun-server | mods/markers/areas.lua | 9 | 31278 |
-- TODO: offer teleport button?
-- Temporary compatibility function - see minetest PR#1180
if not vector.interpolate then
vector.interpolate = function(pos1, pos2, factor)
return {x = pos1.x + (pos2.x - pos1.x) * factor,
y = pos1.y + (pos2.y - pos1.y) * factor,
z = pos1.z + (pos2.z - pos1.z) * factor}
end
end
-- taken from mobf
local COLOR_RED = "#FF0000";
local COLOR_GREEN = "#00FF00";
local COLOR_WHITE = "#FFFFFF";
-- we need to store which list we present to which player
markers.menu_data_by_player = {}
markers.get_area_by_pos = function(pos)
local found_areas = {};
for id, area in pairs(areas.areas) do
if( pos.x >= area.pos1.x and pos.x <= area.pos2.x and
pos.y >= area.pos1.y and pos.y <= area.pos2.y and
pos.z >= area.pos1.z and pos.z <= area.pos2.z )then
area[ 'id' ] = id;
table.insert(found_areas, area );
end
end
return found_areas;
end
-- ppos: current player (or marker stone) position - used for sorting the list
-- mode: can be pos, player, all, subarea, main_areas
-- mode_data: content depends on mode
-- selected: display information about the area the player single-clicked on
markers.get_area_list_formspec = function(ppos, player, mode, pos, mode_data, selected )
local id_list = {};
local title = '???';
local tlabel = '';
-- expects a position in mode_data
if( mode=='pos' ) then
-- title would be too long for a label
title = 'All areas which contain position..';
tlabel = '<'..minetest.pos_to_string( mode_data )..'>:';
for id, area in pairs(areas.areas) do
if( mode_data.x >= area.pos1.x and mode_data.x <= area.pos2.x and
mode_data.y >= area.pos1.y and mode_data.y <= area.pos2.y and
mode_data.z >= area.pos1.z and mode_data.z <= area.pos2.z )then
table.insert( id_list, id );
end
end
-- expects a playername in mode_data
elseif( mode=='player' ) then
title = 'All areas owned by player..';
tlabel = '<'..tostring( mode_data )..'>:';
for id, area in pairs(areas.areas) do
if( area.owner == mode_data ) then
table.insert( id_list, id );
end
end
-- expects an area_id in mode_data
elseif( mode=='subareas' ) then
title = 'All subareas of area..';
tlabel = '<'..tostring( areas.areas[ mode_data ].name )..'> ['..tostring( mode_data )..']:';
for id, area in pairs(areas.areas) do
if( area.parent and area.parent == mode_data ) then
table.insert( id_list, id );
end
end
-- show only areas that do not have parents
elseif( mode=='main_areas' ) then
title = 'All main areas withhin '..tostring( markers.AREA_RANGE )..' m:';
tlabel = '*all main areas*';
for id, area in pairs(areas.areas) do
if( not( area.parent )
-- ppos is always available
and( (area.pos1.x >= ppos.x-markers.AREA_RANGE and area.pos1.x <= ppos.x+markers.AREA_RANGE )
or(area.pos2.x >= ppos.x-markers.AREA_RANGE and area.pos2.x <= ppos.x+markers.AREA_RANGE ))
and( (area.pos1.y >= ppos.y-markers.AREA_RANGE and area.pos1.y <= ppos.y+markers.AREA_RANGE )
or(area.pos2.y >= ppos.y-markers.AREA_RANGE and area.pos2.y <= ppos.y+markers.AREA_RANGE ))
and( (area.pos1.z >= ppos.z-markers.AREA_RANGE and area.pos1.z <= ppos.z+markers.AREA_RANGE )
or(area.pos2.z >= ppos.z-markers.AREA_RANGE and area.pos2.z <= ppos.z+markers.AREA_RANGE ))) then
table.insert( id_list, id );
end
end
elseif( mode=='all' ) then
title = 'All areas withhin '..tostring( markers.AREA_RANGE )..' m:';
tlabel = '*all areas*';
for id, area in pairs(areas.areas) do
if( ( (area.pos1.x >= ppos.x-markers.AREA_RANGE and area.pos1.x <= ppos.x+markers.AREA_RANGE )
or(area.pos2.x >= ppos.x-markers.AREA_RANGE and area.pos2.x <= ppos.x+markers.AREA_RANGE ))
and( (area.pos1.y >= ppos.y-markers.AREA_RANGE and area.pos1.y <= ppos.y+markers.AREA_RANGE )
or(area.pos2.y >= ppos.y-markers.AREA_RANGE and area.pos2.y <= ppos.y+markers.AREA_RANGE ))
and( (area.pos1.z >= ppos.z-markers.AREA_RANGE and area.pos1.z <= ppos.z+markers.AREA_RANGE )
or(area.pos2.z >= ppos.z-markers.AREA_RANGE and area.pos2.z <= ppos.z+markers.AREA_RANGE ))) then
table.insert( id_list, id );
end
end
end
-- Sort the list of areas so the nearest comes first
local nearsorter = function(a, b)
return vector.distance(vector.interpolate(areas.areas[a].pos1, areas.areas[a].pos2, 0.5), ppos) <
vector.distance(vector.interpolate(areas.areas[b].pos1, areas.areas[b].pos2, 0.5), ppos)
end
table.sort(id_list, nearsorter)
local formspec = 'size[10,9]';
title = minetest.formspec_escape( title );
tlabel = minetest.formspec_escape( tlabel );
formspec = formspec..
"label[0.5,0;"..title.."]"..
"label[4.7,0;"..tlabel.."]"..
"label[0.5,8.5;Doubleclick to select area.]"..
"label[4.7,8.5;Areas found: "..tostring( #id_list )..".]"..
"textlist[0.5,0.5;7,8;markers_area_list_selection;";
local liste = '';
for i,v in ipairs( id_list ) do
if( liste ~= '' ) then
liste = liste..',';
end
liste = liste..minetest.formspec_escape( areas:toString( v ) );
end
-- highlight selected entry
if( selected ) then
formspec = formspec..liste..';'..selected..';false]';
else
formspec = formspec..liste..';]';
end
local pname = player:get_player_name();
if( not( markers.menu_data_by_player[ pname ] )) then
markers.menu_data_by_player[ pname ] = {};
end
-- display information about the location of the area the player clicked on
if( selected
and id_list[ selected ]
and areas.areas[ id_list[ selected ]] ) then
local this_area = areas.areas[ id_list[ selected ]];
local subareas = {};
for i,v in pairs( areas.areas ) do
if( v.parent and v.parent == id_list[ selected ]) then
table.insert( subareas, i );
end
end
formspec = formspec..
markers.show_compass_marker( 8.5, 3.0, false, pos, this_area.pos1, this_area.pos2 );
if( this_area.parent) then
formspec = formspec..
'button[8.0,0.5;2,0.5;show_parent;'..
minetest.formspec_escape( areas.areas[ this_area.parent ].name )..']';
end
if( #subareas > 0 ) then
formspec = formspec..
'button[8.0,1.0;2,0.5;list_subareas;'..
minetest.formspec_escape( 'List subareas ('..tostring( #subareas )..')')..']';
end
if( mode=='player' ) then
formspec = formspec..
'label[8.0,1.5;'..
minetest.formspec_escape( this_area.owner..'\'s areas')..']';
else
formspec = formspec..
'button[8.0,1.5;2,0.5;list_player_areas;'..
minetest.formspec_escape( this_area.owner..'\'s areas')..']';
end
end
formspec = formspec..
'button[8.0,8.5;2,0.5;list_main_areas;List all main areas]';
-- we need to remember especially the id_list - else it would be impossible to know what the
-- player selected
markers.menu_data_by_player[ pname ] = {
typ = 'area_list',
mode = mode,
pos = pos,
mode_data = mode_data,
list = id_list,
selected = id_list[ selected ],
};
return formspec;
end
-- shows a formspec with information about a particular area
-- pos is the position of the marker stone or place where the player clicked
-- with the land title register; it is used for relative display of coordinates
markers.get_area_desc_formspec = function( id, player, pos )
if( not( areas.areas ) or not( id ) or not( areas.areas[ id ] )) then
return 'field[info;Error:;Area not found.]';
end
local this_area = areas.areas[ id ];
local pname = player:get_player_name();
-- show some buttons only if area is owned by the player
local is_owner = false;
if( this_area.owner == pname ) then
is_owner = true;
end
local formspec = 'size[10,9]'..
'label[2.5,0.0;Area information and management]'..
'button_exit[4.7,7.0;1,0.5;abort;OK]';
-- general information about the area
formspec = formspec..
'label[0.5,1.0;This is area number ]'..
'label[4.7,1.0;'..tostring( id )..']'..
'label[0.5,1.5;The area is called ]'..
'label[4.7,1.5;'..minetest.formspec_escape( this_area.name or '-not set-')..']'..
'label[0.5,2.0;It is owned by ]'..
'label[4.7,2.0;'..minetest.formspec_escape( this_area.owner)..']';
-- these functions are only available to the owner of the area
if( is_owner ) then
formspec = formspec..
'button_exit[8.0,0.0;2,0.5;change_owner;Change owner]'..
'button_exit[8.0,1.0;2,0.5;delete;Delete]'..
'button_exit[8.0,1.5;2,0.5;rename;Rename]'..
'button_exit[8.0,2.0;2,0.5;list_player_areas;My areas]';
-- subareas of own areas can be deleted (but not renamed)
elseif( not( is_owner )
and this_area.parent
and areas.areas[ this_area.parent ]
and areas.areas[ this_area.parent ].owner == pname ) then
formspec = formspec..
'button_exit[8.0,1.0;2,0.5;delete;Delete subarea]'..
'button_exit[8.0,2.0;2,0.5;list_player_areas;Player\'s areas]';
else
formspec = formspec..
'button_exit[8.0,2.0;2,0.5;list_player_areas;Player\'s areas]';
end
-- players with the areas priv get an extra menu
if( minetest.check_player_privs(pname, {areas=true})) then
formspec = formspec..
'label[8.0,6.0;Admin commands:]'..
'button_exit[8.0,6.5;2,0.5;change_owner;Change owner]'..
'button_exit[8.0,7.0;2,0.5;delete;Delete]'..
'button_exit[8.0,7.5;2,0.5;rename;Rename]';
end
-- show subowners and areas with the same coordinates
formspec = formspec..
'label[0.5,2.5;Further owners of the entire area:]';
local further_owners = {};
for i, area in pairs(areas.areas) do
if( i ~= id and
this_area.pos1.x == area.pos1.x and this_area.pos2.x == area.pos2.x and
this_area.pos1.y == area.pos1.y and this_area.pos2.y == area.pos2.y and
this_area.pos1.z == area.pos1.z and this_area.pos2.z == area.pos2.z )then
table.insert( further_owners, area.owner );
end
end
if( #further_owners > 0 ) then
formspec = formspec..
'label[4.7,2.5;'..minetest.formspec_escape( table.concat( further_owners, ', '))..'.]';
-- deleting subowners is done by deleting their areas
if( is_owner ) then
formspec = formspec..
'button_exit[8.0,2.5;2,0.5;add_owner;Add]';
end
else
formspec = formspec..
'label[4.7,2.5;-none-]';
if( is_owner ) then
formspec = formspec..
'button_exit[8.0,2.5;2,0.5;add_owner;Add]';
end
end
-- is the area a subarea?
if( this_area.parent ) then
formspec = formspec..
'label[0.5,3.0;This area is a sub-area of area]'..
'label[4.7,3.0;'..minetest.formspec_escape( areas.areas[ this_area.parent ].name..' ['..this_area.parent..']' )..']'..
'button_exit[8.0,3.0;2,0.5;show_parent;Show main area]';
end
-- does the area have subareas, i.e. is it a parent area for others?
local sub_areas = {};
for i, area in pairs(areas.areas) do
if( i ~= id and
area.parent == id ) then
table.insert( sub_areas, i );
end
end
if( #sub_areas > 0 ) then
formspec = formspec..
'label[0.5,4.0;Number of defined subareas:]'..
'label[4.7,4.0;'..tostring( #sub_areas )..']'..
'button_exit[8.0,4.0;2,0.5;list_subareas;List subareas]';
else
formspec = formspec..
'label[0.5,4.0;There are no subareas defined.]';
end
-- give information about the size of the area
local length_x = (math.abs( this_area.pos2.x - this_area.pos1.x )+1);
local length_y = (math.abs( this_area.pos2.y - this_area.pos1.y )+1);
local length_z = (math.abs( this_area.pos2.z - this_area.pos1.z )+1);
formspec = formspec..
'label[0.5,4.5;The area extends from]'..
'label[4.7,4.5;'..minetest.pos_to_string( this_area.pos1 )..' to '..minetest.pos_to_string( this_area.pos2 )..'.]'..
'label[4.7,4.75;It spans '..tostring( length_x )..
' x '..tostring( length_z )..
' = '..tostring( length_x * length_z )..
' m^2. Height: '..tostring( length_y )..' m.]';
formspec = formspec..
markers.show_compass_marker( 2.0, 7.0, true, pos, this_area.pos1, this_area.pos2 );
-- TODO: buy / sell button
local pname = player:get_player_name();
if( not( markers.menu_data_by_player[ pname ] )) then
markers.menu_data_by_player[ pname ] = {};
end
-- we need to remember especially the id_list - else it would be impossible to know what the
-- player selected
markers.menu_data_by_player[ pname ] =
{ typ = 'show_area',
mode = nil,
pos = pos,
mode_data = nil,
list = nil,
selected = id,
};
return formspec;
end
-- shows where the area (defined by pos1/pos2) is located relative to the given position pos
-- row_offset/col_offset are offsets for the formspec
markers.show_compass_marker = function( col_offset, row_offset, with_text, pos, pos1, pos2 )
local formspec = '';
-- TODO: show up/down information somehow
-- TODO: what if checked with a land claim register?
-- if possible, show how far the area streches into each direction relative to pos
if( pos.x >= pos1.x and pos.x <= pos2.x
and pos.y >= pos1.y and pos.y <= pos2.y
and pos.z >= pos1.z and pos.z <= pos2.z ) then
if( with_text ) then
formspec = formspec..
'label[0.5,5.5;Dimensions of the area in relation to..]'..
-- TODO: check if there is a marker; else write 'position you clicked on'
'label[4.7,5.5;the marker at '..minetest.pos_to_string( pos )..':]'..
'button_exit[8.0,5.5;2,0.5;list_areas_at;Local areas]';
end
formspec = formspec..
'image['..col_offset..','..row_offset..';1,1;markers_stone.png]'..
'label['..(col_offset-0.8)..','..(row_offset+0.05)..';'..tostring( pos.x - pos1.x )..' m W]'..
'label['..(col_offset+1.0)..','..(row_offset+0.05)..';'..tostring( pos2.x - pos.x )..' m E]'..
'label['..(col_offset+0.1)..','..(row_offset+0.80)..';'..tostring( pos.z - pos1.z )..' m S]'..
'label['..(col_offset+0.1)..','..(row_offset-0.80)..';'..tostring( pos2.z - pos.z )..' m N]';
-- else show how far the area is away
else
local starts_north = '';
local starts_south = '';
local starts_east = '';
local starts_west = '';
if( pos.z > pos2.z ) then
starts_north = '';
starts_south = tostring( pos.z - pos2.z )..' m S';
else
starts_north = tostring( pos1.z - pos.z )..' m N';
starts_south = '';
end
if( pos.x > pos2.x ) then
starts_east = '';
starts_west = tostring( pos.x - pos2.x )..' m W';
else
starts_east = tostring( pos1.x - pos.x )..' m E';
starts_west = '';
end
if( with_text ) then
formspec = formspec..
'label[0.5,5.5;Position of the area in relation to..]'..
-- TODO: check if there is a marker; else write 'position you clicked on'
'label[4.7,5.5;the marker at '..minetest.pos_to_string( pos )..':]'..
'button_exit[8.0,5.5;2,0.5;list_areas_at;Local areas]';
end
formspec = formspec..
'image['..col_offset..','..row_offset..';1,1;compass_side_top.png]'..
'label['..(col_offset-0.8)..','..(row_offset+0.05)..';'..starts_west..']'..
'label['..(col_offset+1.0)..','..(row_offset+0.05)..';'..starts_east..']'..
'label['..(col_offset+0.1)..','..(row_offset-0.80)..';'..starts_north..']'..
'label['..(col_offset+0.1)..','..(row_offset+0.80)..';'..starts_south..']';
end
return formspec;
end
-- formspec input needs to be handled diffrently
markers.form_input_handler_areas = function( player, formname, fields)
local pname = player:get_player_name();
local ppos = player:getpos()
if( formname ~= "markers:info"
or not( player )
or not( markers.menu_data_by_player[ pname ] )) then
return false;
end
local menu_data = markers.menu_data_by_player[ pname ];
local formspec = '';
-- rename an area
if( fields.rename
and menu_data.selected
and areas.areas[ menu_data.selected ]
and areas.areas[ menu_data.selected ].owner == pname ) then
local area = areas.areas[ menu_data.selected ];
if( not( area.name )) then
area.name = '-enter area name-';
end
formspec = 'field[rename_new_name;Enter new name for area:;'..minetest.formspec_escape( area.name )..']';
elseif( fields.rename_new_name
and menu_data.selected
and areas.areas[ menu_data.selected ]
and ((areas.areas[ menu_data.selected ].owner == pname )
or minetest.check_player_privs(pname, {areas=true}))) then
local area = areas.areas[ menu_data.selected ];
-- actually rename the area
areas.areas[ menu_data.selected ].name = fields.rename_new_name;
areas:save();
minetest.chat_send_player( pname, 'Area successfully renamed.');
-- shwo the renamed area
formspec = markers.get_area_desc_formspec( menu_data.selected, player, menu_data.pos );
-- change owner the area
elseif( fields.change_owner
and menu_data.selected
and areas.areas[ menu_data.selected ] ) then
-- there are no checks here - those happen when the area is transferred
local area = areas.areas[ menu_data.selected ];
formspec = 'field[change_owner_name;Give area \"'..minetest.formspec_escape( area.name )..'\" to player:;-enter name of NEW OWNER-]';
elseif( fields.change_owner_name
and menu_data.selected
and areas.areas[ menu_data.selected ] ) then
local area = areas.areas[ menu_data.selected ];
-- only own areas can be transfered to another player (or if the areas priv is there)
if( area.owner ~= pname
and not( minetest.check_player_privs(pname, {areas=true}))) then
minetest.chat_send_player( pname, 'Permission denied. You do not own the area.');
elseif( not( areas:player_exists( fields.change_owner_name ))) then
minetest.chat_send_player( pname, 'That player does not exist.');
else
-- actually change the owner
areas.areas[ menu_data.selected ].owner = fields.change_owner_name;
areas:save()
minetest.chat_send_player( pname, 'Your area '..tostring( area.name )..' has been transfered to '..tostring( fields.change_owner_name )..'.');
minetest.chat_send_player( fields.change_owner_name, pname..'" has given you control over an area.')
end
formspec = markers.get_area_desc_formspec( menu_data.selected, player, menu_data.pos );
-- add an owner to the entire area
elseif( fields.add_owner
and menu_data.selected
and areas.areas[ menu_data.selected ]
and areas.areas[ menu_data.selected ].owner == pname ) then
local area = areas.areas[ menu_data.selected ];
formspec = 'field[add_owner_name;Grant access to area \"'..minetest.formspec_escape( area.name )..'\" to player:;-enter player name-]';
elseif( fields.add_owner_name
-- the player has to own the area already; we need a diffrent name here
and fields.add_owner_name ~= pname
and menu_data.selected
and areas.areas[ menu_data.selected ]
and areas.areas[ menu_data.selected ].owner == pname ) then
local area = areas.areas[ menu_data.selected ];
-- does the player exist?
if( not( areas:player_exists( fields.add_owner_name ))) then
minetest.chat_send_player( pname, 'That player does not exist.');
-- show the formspec
formspec = markers.get_area_desc_formspec( menu_data.selected, player, menu_data.pos );
else
-- log the creation of the new area
minetest.log("action", pname.." runs /add_owner through the markers-mod. Owner = "..fields.add_owner_name..
" AreaName = "..area.name.." ParentID = "..menu_data.selected..
" StartPos = "..area.pos1.x..","..area.pos1.y..","..area.pos1.z..
" EndPos = " ..area.pos2.x..","..area.pos2.y..","..area.pos2.z)
-- take the name from the old/parent area
local new_id = areas:add( fields.add_owner_name, area.name, area.pos1, area.pos2, menu_data.selected );
areas:save()
minetest.chat_send_player( fields.add_owner_name,
"You have been granted control over area #"..
new_id..". Type /list_areas to show your areas.")
minetest.chat_send_player( pname, 'The player may now build and dig in your area.');
-- shwo the new area
markers.menu_data_by_player[ pname ].selected = new_id;
formspec = markers.get_area_desc_formspec( new_id, player, menu_data.pos );
end
-- delete area
elseif( fields.delete
and menu_data.selected
and areas.areas[ menu_data.selected ] ) then
local area = areas.areas[ menu_data.selected ];
-- a player can only delete own areas or subareas of own areas
if( area.owner ~= pname
and not( area.parent
and areas.areas[ area.parent ]
and areas.areas[ area.parent ].owner
and areas.areas[ area.parent ].owner == pname )
and not( minetest.check_player_privs(pname, {areas=true}))) then
minetest.chat_send_player( pname, 'Permission denied. You own neither the area itshelf nor its parent area.');
-- shwo the area where the renaming failed
formspec = markers.get_area_desc_formspec( menu_data.selected, player, menu_data.pos );
else
formspec = 'field[rename_new_name;Enter new name for area:;'..minetest.formspec_escape( area.name )..']';
formspec = 'field[delete_confirm;'..minetest.formspec_escape( 'Really delete area \"'..area.name..
'\" (owned by '..area.owner..')? Confirm with YES:')..';-type yes in capitals to confirm-]';
end
elseif( fields.delete_confirm
and menu_data.selected
and areas.areas[ menu_data.selected ] ) then
local area = areas.areas[ menu_data.selected ];
local old_owner = area.owner;
local subareas = {};
for i,v in pairs( areas.areas ) do
if( v.parent and v.parent == menu_data.selected ) then
table.insert( subareas, i );
end
end
-- a player can only delete own areas or subareas of own areas
if( area.owner ~= pname
and not( area.parent
and areas.areas[ area.parent ]
and areas.areas[ area.parent ].owner
and areas.areas[ area.parent ].owner == pname )
and not( minetest.check_player_privs(pname, {areas=true}))) then
minetest.chat_send_player( pname, 'Permission denied. You own neither the area itshelf nor its parent area.');
-- shwo the renamed area
formspec = markers.get_area_desc_formspec( menu_data.selected, player, menu_data.pos );
-- avoid accidents
elseif( fields.delete_confirm ~= 'YES' ) then
minetest.chat_send_player( pname, 'Delition of area \"'..tostring( area.name )..'\" (owned by '..old_owner..') aborted.');
formspec = markers.get_area_desc_formspec( menu_data.selected, player, menu_data.pos );
-- only areas without subareas can be deleted
elseif( #subareas > 0 ) then
minetest.chat_send_player( pname, 'The area has '..tostring( #subareas )..' subarea(s). Please delete those first!');
formspec = markers.get_area_desc_formspec( menu_data.selected, player, menu_data.pos );
else
minetest.chat_send_player( pname, 'Area \"'..tostring( area.name )..'\" (owned by '..old_owner..') deleted.');
-- really delete
areas:remove( menu_data.selected, false ); -- no recursive delete
areas:save();
-- show the list of areas owned by the previous owner
formspec = markers.get_area_list_formspec(ppos, player, 'player', menu_data.pos, old_owner, nil );
end
elseif( fields.show_parent
and menu_data.selected
and areas.areas[ menu_data.selected ]
and areas.areas[ menu_data.selected ].parent ) then
formspec = markers.get_area_desc_formspec( areas.areas[ menu_data.selected ].parent, player, menu_data.pos );
elseif( fields.list_player_areas
and menu_data.selected
and areas.areas[ menu_data.selected ] ) then
formspec = markers.get_area_list_formspec(ppos, player, 'player', menu_data.pos, areas.areas[ menu_data.selected ].owner, nil );
elseif( fields.list_subareas
and menu_data.selected
and areas.areas[ menu_data.selected ] ) then
formspec = markers.get_area_list_formspec(ppos, player, 'subareas', menu_data.pos, menu_data.selected, nil );
elseif( fields.list_main_areas ) then
formspec = markers.get_area_list_formspec(ppos, player, 'main_areas', menu_data.pos, nil, nil );
elseif( fields.list_areas_at
and menu_data.pos ) then
formspec = markers.get_area_list_formspec(ppos, player, 'pos', menu_data.pos, menu_data.pos, nil );
elseif( fields.markers_area_list_selection
and menu_data.typ
and menu_data.typ == 'area_list'
and menu_data.list
and #menu_data.list > 0 ) then
local field_data = fields.markers_area_list_selection:split( ':' );
if( not( field_data ) or #field_data < 2 ) then
field_data = { '', '' };
end
local selected = tonumber( field_data[ 2 ] );
if( field_data[1]=='DCL' ) then
-- on doubleclick, show detailed area information
formspec = markers.get_area_desc_formspec( tonumber( menu_data.list[ selected ] ), player, menu_data.pos );
else
-- on single click, just show the position of that particular area
formspec = markers.get_area_list_formspec(ppos, player, menu_data.mode, menu_data.pos, menu_data.mode_data, selected );
end
else
return false;
end
minetest.show_formspec( pname, "markers:info", formspec )
return true;
end
-- search the area at the given position pos that might be of most intrest to the player
markers.show_marker_stone_formspec = function( player, pos )
local pname = player:get_player_name();
local ppos = pos
-- this table stores the list the player may have selected from; at the beginning, there is no list
if( not( markers.menu_data_by_player[ pname ] )) then
markers.menu_data_by_player[ pname ] = {
typ = 'area_list',
mode = 'main_areas',
pos = pos,
mode_data = pos,
list = {},
selected = nil,
};
end
local formspec = '';
local found_areas = {};
local min_area_size = 100000000000;
for id, area in pairs(areas.areas) do
if( pos.x >= area.pos1.x and pos.x <= area.pos2.x and
pos.y >= area.pos1.y and pos.y <= area.pos2.y and
pos.z >= area.pos1.z and pos.z <= area.pos2.z )then
-- ignore y (height) value because some areas may go from bottom to top
local area_size = math.abs( area.pos2.x - area.pos1.x )
* math.abs( area.pos2.z - area.pos1.z );
-- collect subareas that have the same size
if( area_size == min_area_size ) then
table.insert(found_areas, id );
-- we have found a smaller area - that is more intresting here
elseif( area_size <= min_area_size ) then
found_areas = {};
min_area_size = area_size;
table.insert(found_areas, id );
end
end
end
-- no areas found; display error message and selection menu
if( #found_areas < 1 ) then
formspec = 'size[4,3]'..
'label[0.5,0.5;This position is not protected.]'..
'button[1.0,1.5;2,0.5;list_main_areas;List all main areas]'..
'button_exit[3.0,1.5;1,0.5;abort;OK]';
-- found exactly one areaa - display it
elseif( #found_areas == 1 ) then
formspec = markers.get_area_desc_formspec( found_areas[ 1 ], player, pos );
-- found more than one area; we have saved only those with the smallest size
else
local own_area = 0;
local parent_area = 0;
local upper_area = 0;
for i,v in ipairs( found_areas ) do
local area = areas.areas[ v ];
-- owned by player?
if( area.owner == pname ) then
own_area = v;
-- parentless area?
elseif( not( area.parent )) then
parent_area = v;
-- the parent has diffrent coordinates?
elseif( areas.areas[ area.parent ].pos1.x ~= area.pos1.x
or areas.areas[ area.parent ].pos1.y ~= area.pos1.y
or areas.areas[ area.parent ].pos1.z ~= area.pos1.z
or areas.areas[ area.parent ].pos2.x ~= area.pos2.x
or areas.areas[ area.parent ].pos2.y ~= area.pos2.y
or areas.areas[ area.parent ].pos2.z ~= area.pos2.z ) then
upper_area = v;
end
end
-- the area owned by the player is most intresting
if( own_area > 0 ) then
formspec = markers.get_area_desc_formspec( own_area, player, pos );
-- if the player owns none of these areas, show the topmost (parentless) area
elseif( parent_area > 0 ) then
formspec = markers.get_area_desc_formspec( parent_area, player, pos );
-- an area which has a parent with diffrent coordinates from its child may (or may not) be the
-- parent of all these subareas we've found here; there is no guarantee, but it's a best guess.
-- If it is not good enough, then the player can still search for himshelf.
elseif( upper_area > 0 ) then
formspec = markers.get_area_desc_formspec( upper_area, player, pos );
-- our superficial analysis of the structure of the areas failed; it is up to the player to
-- find out which of the candidates he is intrested in; we list them all
else
formspec = markers.get_area_list_formspec(ppos, player, 'pos', pos, pos, nil );
end
end
minetest.show_formspec( player:get_player_name(), "markers:info", formspec );
end
| unlicense |
FFXIOrgins/FFXIOrgins | scripts/globals/spells/absorb-tp.lua | 6 | 1344 | --------------------------------------
-- Spell: Absorb-TP
-- Steals an enemy's TP.
--------------------------------------
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)
local dmg = math.random();
dmg = math.random();
dmg = math.random(10, 80);
--get resist multiplier (1x if no resist)
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),DARK_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,spell:getElement());
--add in final adjustments
local cap = 120;
if (dmg > cap) then
dmg = cap;
end
if(resist <= 0.125) then
spell:setMsg(85);
else
spell:setMsg(454);
if(target:getTP() < dmg) then
dmg = target:getTP();
end
-- drain
caster:addTP(dmg);
target:addTP(-dmg);
end
return dmg;
end; | gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/AlTaieu/npcs/_0x2.lua | 6 | 2391 | -----------------------------------
-- Area: Al'Taieu
-- NPC: Rubious Crystal (West Tower)
-- @pos -683.709 -6.250 -222.142 33
-----------------------------------
package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/AlTaieu/TextIDs");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and (player:getVar("PromathiaStatus")==2 or player:getVar("PromathiaStatus")==4 or player:getVar("PromathiaStatus")==6)
and player:getVar("Ru_aern_2-1KILL")==0 and player:getVar("Ru_aern_2-2KILL")==0 and player:getVar("Ru_aern_2-3KILL")==0)then
player:messageSpecial(OMINOUS_SHADOW);
SpawnMob(16912832,180):updateEnmity(player);
SpawnMob(16912833,180):updateEnmity(player);
SpawnMob(16912834,180):updateEnmity(player);
elseif(player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("Ru_aern_2-1KILL")==1 and player:getVar("Ru_aern_2-2KILL")==1 and player:getVar("Ru_aern_2-3KILL")==1) then
if(player:getVar("PromathiaStatus")==3) then
player:startEvent(0x00A1);
elseif(player:getVar("PromathiaStatus")==5) then
player:startEvent(0x00A2);
elseif(player:getVar("PromathiaStatus")==7)then
player:startEvent(0x00A3);
else
player:messageSpecial(NOTHING_OF_INTEREST);
end
else
player:messageSpecial(NOTHING_OF_INTEREST);
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 == 0x00A1)then
player:setVar("PromathiaStatus",4);
elseif(csid == 0x00A2)then
player:setVar("PromathiaStatus",6);
elseif(csid == 0x00A3)then
player:setVar("PromathiaStatus",8);
end
end; | gpl-3.0 |
Nitroteam/s | plugins/inrealm.lua | 850 | 25085 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.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 get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.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 set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
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
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(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, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
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
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_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
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
xToken/CompMod | lua/CompMod/Structures/Alien/Crag/shared.lua | 1 | 2134 | -- Natural Selection 2 Competitive Mod
-- Source located at - https://github.com/xToken/CompMod
-- lua\CompMod\Structures\Alien\Crag\shared.lua
-- - Dragon
Crag.kHealRadius = kCragHealRange
Crag.kHealPercentage = kCragHealPercentage
Crag.kMinHeal = kCragkMinHeal
Crag.kMaxHeal = kCragkMaxHeal
Crag.kHealWaveDuration = kCragHealWaveDuration
Crag.kHealWaveMultiplier = kCragHealWaveMultiplier
Crag.kHealInterval = kCragHealingInterval
-- CRAG
local originalCragOnInitialized
originalCragOnInitialized = Class_ReplaceMethod("Crag", "OnInitialized",
function(self)
InitMixin(self, InfestationMixin)
originalCragOnInitialized(self)
end
)
function Crag:GetInfestationRadius()
return kStructureInfestationRadius
end
function Crag:GetInfestationMaxRadius()
return kStructureInfestationRadius
end
function Crag:TryHeal(target)
local unclampedHeal = target:GetMaxHealth() * Crag.kHealPercentage * self:GetMaturityScaling()
local heal = Clamp(unclampedHeal, Crag.kMinHeal, Crag.kMaxHeal)
if self.healWaveActive then
--heal = heal * Crag.kHealWaveMultiplier
end
if target:GetHealthScalar() ~= 1 and (not target.timeLastCragHeal or target.timeLastCragHeal + Crag.kHealInterval <= Shared.GetTime()) then
local amountHealed = target:AddHealth(heal)
target.timeLastCragHeal = Shared.GetTime()
return amountHealed
else
return 0
end
end
function Crag:UpdateHealing()
local time = Shared.GetTime()
if ( self.timeOfLastHeal == nil or (time > self.timeOfLastHeal + Crag.kHealInterval) ) then
self:PerformHealing()
end
end
function Crag:GetTechAllowed(techId, techNode, player)
if techId == kTechId.HealWave and self:GetMaturityLevel() ~= kMaturityLevel.Flourishing then
return false, false
end
return ScriptActor.GetTechAllowed(self, techId, techNode, player)
end
function Crag:ShouldGenerateInfestation()
return not self.moving
end
local networkVars = { }
AddMixinNetworkVars(InfestationMixin, networkVars)
Shared.LinkClassToMap("Crag", Crag.kMapName, networkVars) | mit |
FFXIOrgins/FFXIOrgins | scripts/zones/Beaucedine_Glacier/mobs/Tundra_Tiger.lua | 10 | 1427 | -----------------------------------
-- Area: Beaucedine Glacier
-- MOB: Tundra Tiger
-- Note: PH for Nue, Kirata
-----------------------------------
require("/scripts/globals/fieldsofvalor");
require("/scripts/zones/Beaucedine_Glacier/MobIDs");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
checkRegime(killer,mob,46,1);
checkRegime(killer,mob,47,1);
-- Kirata
mob = mob:getID();
if (Kirata_PH[mob] ~= nil) then
ToD = GetServerVariable("[POP]Kirata");
if (ToD <= os.time(t) and GetMobAction(Kirata) == 0) then
if (math.random((1),(15)) == 5) then
UpdateNMSpawnPoint(Kirata);
GetMobByID(Kirata):setRespawnTime(GetMobRespawnTime(mob));
SetServerVariable("[PH]Kirata", mob);
DeterMob(mob, true);
end
end
end
-- Nue
if (Nue_PH[mob] ~= nil) then
ToD = GetServerVariable("[POP]Nue");
if (ToD <= os.time(t) and GetMobAction(Nue) == 0) then
if (math.random((1),(15)) == 5) then
UpdateNMSpawnPoint(Nue);
GetMobByID(Nue):setRespawnTime(GetMobRespawnTime(mob));
SetServerVariable("[PH]Nue", mob);
DeterMob(mob, true);
end
end
end
end;
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/globals/mobskills/Hyper_Pulse.lua | 8 | 1330 | ---------------------------------------------------
-- Hyper_Pulse
--
-- Description: 300 magic damage, Gravity and short Bind, wipes Utsusemi
-- Type: Magical
--
---------------------------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/status");
require("/scripts/globals/monstertpmoves");
---------------------------------------------------
function OnMobSkillCheck(target,mob,skill)
local mobID = mob:getID(); --(16908294 ,16908301 ,16908308 =omega ,16933124=proto-omega)
local mobhp = mob:getHPP();
if ((mobID == 16908294 or mobID ==16908301 or mobID ==16908308)and mobhp > 25 ) then --omega
return 0;
elseif (mobID == 16933124 and mobhp > 30 and mobhp < 70)then -- omega bipedform
return 0;
end
return 1;
end;
function OnMobWeaponSkill(target, mob, skill)
local typeEffect1 = EFFECT_BIND;
MobStatusEffectMove(mob, target, typeEffect1, 1, 0, 4);
local typeEffect2 = EFFECT_WEIGHT;
MobStatusEffectMove(mob, target, typeEffect2, 50, 0, 30);
local dmgmod = 1.5;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_DARK,dmgmod,TP_MAB_BONUS,1);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end
| gpl-3.0 |
gitfancode/skynet | service/launcher.lua | 51 | 3199 | local skynet = require "skynet"
local core = require "skynet.core"
require "skynet.manager" -- import manager apis
local string = string
local services = {}
local command = {}
local instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK)
local function handle_to_address(handle)
return tonumber("0x" .. string.sub(handle , 2))
end
local NORET = {}
function command.LIST()
local list = {}
for k,v in pairs(services) do
list[skynet.address(k)] = v
end
return list
end
function command.STAT()
local list = {}
for k,v in pairs(services) do
local stat = skynet.call(k,"debug","STAT")
list[skynet.address(k)] = stat
end
return list
end
function command.KILL(_, handle)
handle = handle_to_address(handle)
skynet.kill(handle)
local ret = { [skynet.address(handle)] = tostring(services[handle]) }
services[handle] = nil
return ret
end
function command.MEM()
local list = {}
for k,v in pairs(services) do
local kb, bytes = skynet.call(k,"debug","MEM")
list[skynet.address(k)] = string.format("%.2f Kb (%s)",kb,v)
end
return list
end
function command.GC()
for k,v in pairs(services) do
skynet.send(k,"debug","GC")
end
return command.MEM()
end
function command.REMOVE(_, handle, kill)
services[handle] = nil
local response = instance[handle]
if response then
-- instance is dead
response(not kill) -- return nil to caller of newservice, when kill == false
instance[handle] = nil
end
-- don't return (skynet.ret) because the handle may exit
return NORET
end
local function launch_service(service, ...)
local param = table.concat({...}, " ")
local inst = skynet.launch(service, param)
local response = skynet.response()
if inst then
services[inst] = service .. " " .. param
instance[inst] = response
else
response(false)
return
end
return inst
end
function command.LAUNCH(_, service, ...)
launch_service(service, ...)
return NORET
end
function command.LOGLAUNCH(_, service, ...)
local inst = launch_service(service, ...)
if inst then
core.command("LOGON", skynet.address(inst))
end
return NORET
end
function command.ERROR(address)
-- see serivce-src/service_lua.c
-- init failed
local response = instance[address]
if response then
response(false)
instance[address] = nil
end
services[address] = nil
return NORET
end
function command.LAUNCHOK(address)
-- init notice
local response = instance[address]
if response then
response(true, address)
instance[address] = nil
end
return NORET
end
-- for historical reasons, launcher support text command (for C service)
skynet.register_protocol {
name = "text",
id = skynet.PTYPE_TEXT,
unpack = skynet.tostring,
dispatch = function(session, address , cmd)
if cmd == "" then
command.LAUNCHOK(address)
elseif cmd == "ERROR" then
command.ERROR(address)
else
error ("Invalid text command " .. cmd)
end
end,
}
skynet.dispatch("lua", function(session, address, cmd , ...)
cmd = string.upper(cmd)
local f = command[cmd]
if f then
local ret = f(address, ...)
if ret ~= NORET then
skynet.ret(skynet.pack(ret))
end
else
skynet.ret(skynet.pack {"Unknown command"} )
end
end)
skynet.start(function() end)
| mit |
TW1STaL1CKY/pac3 | lua/pac3/libraries/webaudio.lua | 1 | 26424 | local webaudio = _G.webaudio or {}
_G.webaudio = webaudio
if me then
webaudio.debug = true
end
webaudio.sample_rate = nil
webaudio.speed_of_sound = 340.29 -- metres per
webaudio.buffer_size = CreateClientConVar("webaudio_buffer_size", "2048", true)
local function logn(str)
MsgC(Color(0, 255, 0), "[pac webaudio] ")
MsgC(Color(255, 255, 255), str)
Msg("\n")
end
local function dprint(str)
if webaudio.debug then
logn(str)
end
end
cvars.AddChangeCallback("webaudio_buffer_size", function(_,_,val)
dprint("buffer size changed to " .. val)
webaudio.Shutdown()
webaudio.Initialize()
end)
if webaudio.browser_panel and webaudio.browser_panel:IsValid() then
webaudio.browser_panel:Remove()
webaudio.browser_panel = nil
end
webaudio.browser_state = "uninitialized"
webaudio.volume = 1
local script_queue
local function run_javascript(code, stream)
if stream and not stream:IsReady() then
stream.js_queue = stream.js_queue or {}
table.insert(stream.js_queue, code)
return
end
if script_queue then
table.insert(script_queue, code)
else
if code ~= "" then
--print("|" .. code .. "|")
webaudio.browser_panel:RunJavascript(code)
end
end
end
local function queue_javascript()
script_queue = script_queue or {}
end
local function execute_javascript()
if script_queue then
local str = table.concat(script_queue, "\n")
script_queue = nil
run_javascript(str)
end
end
do
local last_eye_pos
local last_eye_pos_time
function webaudio.Update()
if webaudio.browser_state ~= "initialized" then
if webaudio.browser_state ~= "initializing" then
webaudio.Initialize()
end
return
end
if not system.HasFocus() and GetConVar("snd_mute_losefocus"):GetBool() then
webaudio.SetVolume(0)
else
webaudio.SetVolume(GetConVar("volume"):GetFloat())
end
local time = RealTime()
last_eye_pos = last_eye_pos or webaudio.eye_pos
last_eye_pos_time = last_eye_pos_time or (time - FrameTime())
webaudio.eye_velocity = (webaudio.eye_pos - last_eye_pos) / (time - last_eye_pos_time)
last_eye_pos = webaudio.eye_pos
last_eye_pos_time = time
for streamId, stream in pairs(webaudio.streams) do
if stream:IsValid() then
stream:Think()
else
webaudio.streams[streamId] = nil
end
end
end
end
function webaudio.Shutdown()
webaudio.browser_state = "uninitialized"
if webaudio.browser_panel then
webaudio.browser_panel:Remove()
end
webaudio.browser_panel = nil
hook.Remove("RenderScene", "pac_webaudio2")
hook.Remove("Think", "pac_webaudio2")
end
function webaudio.Initialize()
if webaudio.browser_state ~= "uninitialized" then return end
webaudio.browser_state = "initializing"
if webaudio.browser_panel then
webaudio.browser_panel:Remove()
end
webaudio.browser_panel = vgui.Create("DHTML")
webaudio.browser_panel:SetVisible(false)
webaudio.browser_panel:SetPos(ScrW(), ScrH())
webaudio.browser_panel:SetSize(1, 1)
local last_message = nil
webaudio.browser_panel.ConsoleMessage = function(self, message)
-- why does awesomium crash in the first place?
if msg == "Uncaught ReferenceError: lua is not defined" then
webaudio.browser_state = "uninitialized"
end
if last_message ~= message then
last_message = message
dprint(message)
end
end
webaudio.browser_panel:AddFunction("lua", "print", dprint)
webaudio.browser_panel:AddFunction("lua", "message", function(typ, ...)
local args = {}
for i = 1, select("#", ...) do
args[i] = tostring(select(i, ...))
end
dprint(typ .. " " .. table.concat(args, ", "))
if typ == "initialized" then
webaudio.browser_state = "initialized"
webaudio.sample_rate = args[1] or -1
elseif typ == "stream" then
local stream = webaudio.GetStream(tonumber(args[2]) or 0)
if stream:IsValid() then
stream:HandleBrowserMessage(args[1], unpack(args, 3, table.maxn(args)))
end
end
end)
local js = ([==[
/*jslint bitwise: true */
window.onerror = function(description, url, line)
{
dprint("Unhandled exception at line " + line + ": " + description);
};
function dprint(str)
{
]==] .. (webaudio.debug and "lua.print(str);" or "") .. [==[
}
var audio;
var gain;
var processor;
var streams = new Object();
var streams_array = [];
function open()
{
if(audio)
{
audio.destination.disconnect();
}
if (typeof AudioContext != "undefined")
{
audio = new AudioContext();
processor = audio.createScriptProcessor(]==] .. webaudio.buffer_size:GetInt() .. [==[, 2, 2);
gain = audio.createGain();
compressor = audio.createDynamicsCompressor()
} else {
audio = new webkitAudioContext();
processor = audio.createJavaScriptNode(]==] .. webaudio.buffer_size:GetInt() .. [==[, 2, 2);
gain = audio.createGainNode();
compressor = audio.createDynamicsCompressor()
}
processor.onaudioprocess = function(event)
{
var output_left = event.outputBuffer.getChannelData(0);
var output_right = event.outputBuffer.getChannelData(1);
for(var i = 0; i < event.outputBuffer.length; ++i)
{
output_left[i] = 0;
output_right[i] = 0;
}
for(var i = 0; i < streams_array.length; ++i)
{
var stream = streams_array[i];
var buffer_length = stream.buffer.length;
var buffer_left = stream.buffer.getChannelData(0);
var buffer_right = stream.buffer.numberOfChannels == 1 ? buffer_left : stream.buffer.getChannelData(1);
if (stream.use_smoothing)
{
stream.speed_smooth = stream.speed_smooth + (stream.speed - stream.speed_smooth) * 1;
stream.vol_left_smooth = stream.vol_left_smooth + (stream.vol_left - stream.vol_left_smooth ) * 1;
stream.vol_right_smooth = stream.vol_right_smooth + (stream.vol_right - stream.vol_right_smooth) * 1;
}
else
{
stream.speed_smooth = stream.speed;
stream.vol_left_smooth = stream.vol_left_smooth;
stream.vol_right_smooth = stream.vol_right_smooth;
}
if(!stream.use_echo && (stream.paused || (stream.vol_left < 0.001 && stream.vol_right < 0.001)))
{
continue;
}
var echol;
var echor;
if (stream.use_echo && stream.echo_buffer)
{
echol = stream.echo_buffer.getChannelData(0);
echor = stream.echo_buffer.getChannelData(1);
}
var sml = 0;
var smr = 0;
for(var j = 0; j < event.outputBuffer.length; ++j)
{
if (stream.paused || stream.max_loop > 0 && stream.position >= (buffer_length * stream.max_loop) - 1)
{
stream.done_playing = true;
if (!stream.paused)
{
stream.paused = true;
}
if (!stream.use_echo)
{
break;
}
}
else
{
stream.done_playing = false;
}
var index = (stream.position >> 0) % buffer_length;
if (stream.reverse)
{
index = -index + buffer_length;
}
var left = 0;
var right = 0;
if (!stream.done_playing)
{
// filters
if (stream.filter_type == 0)
{
// None
left = buffer_left[index] * stream.vol_both;
right = buffer_right[index] * stream.vol_both;
}
else
{
sml = sml + (buffer_left[index] - sml) * stream.filter_fraction;
smr = smr + (buffer_right[index] - smr) * stream.filter_fraction;
if (stream.filter_type == 1)
{
// Low pass
left = sml * stream.vol_both;
right = smr * stream.vol_both;
}
else if (stream.filter_type == 2)
{
// High pass
left = (buffer_left[index] - sml) * stream.vol_both;
right = (buffer_right[index] - smr) * stream.vol_both;
}
}
left = Math.min(Math.max(left, -1), 1) * stream.vol_left_smooth;
right = Math.min(Math.max(right, -1), 1) * stream.vol_right_smooth;
}
if (stream.lfo_volume_time)
{
var res = (Math.sin((stream.position/audio.sampleRate)*10*stream.lfo_volume_time)*stream.lfo_volume_amount);
left *= res;
right *= res;
}
if (stream.use_echo)
{
var echo_index = (stream.position >> 0) % stream.echo_delay;
echol[echo_index] = echol[echo_index] * stream.echo_feedback + left;
echor[echo_index] = echor[echo_index] * stream.echo_feedback + right;
output_left[j] += echol[echo_index];
output_right[j] += echor[echo_index];
}
else
{
output_left[j] += left;
output_right[j] += right;
}
var speed = stream.speed_smooth;
if (stream.lfo_pitch_time)
{
speed -= (Math.sin((stream.position/audio.sampleRate)*10*stream.lfo_pitch_time)*stream.lfo_pitch_amount);
speed += Math.pow(stream.lfo_pitch_amount*0.5,2);
}
stream.position += speed;
var max = 1;
output_left[j] = Math.min(Math.max(output_left[j], -max), max);
output_right[j] = Math.min(Math.max(output_right[j], -max), max);
if (!isFinite(output_left[j])) {
output_left[j] = 0
}
if (!isFinite(output_right[j])) {
output_right[j] = 0
}
}
}
};
processor.connect(compressor);
compressor.connect(gain);
gain.connect(audio.destination);
lua.message("initialized", audio.sampleRate);
}
function close()
{
if(audio)
{
audio.destination.disconnect();
audio = null;
lua.message("uninitialized");
}
}
var buffer_cache = new Object();
function download_buffer(url, callback, skip_cache, id)
{
if (!skip_cache && buffer_cache[url])
{
callback(buffer_cache[url]);
return;
}
var request = new XMLHttpRequest();
request.open("GET", url);
request.responseType = "arraybuffer";
request.send();
request.onload = function()
{
dprint("decoding " + url + " " + request.response.byteLength + " ...");
audio.decodeAudioData(request.response,
function(buffer)
{
dprint("decoded " + url + " successfully");
callback(buffer);
buffer_cache[url] = buffer;
},
function(err)
{
dprint("decoding error " + url + " " + err.message);
lua.message("stream", "call", id, "OnError", "decoding failed", err.message);
}
);
};
request.onprogress = function(event)
{
dprint("downloading " + (event.loaded / event.total) * 100);
};
request.onerror = function()
{
dprint("downloading " + url + " errored");
lua.message("stream", "call", id, "OnError", "download failed: ", request.responseText);
};
}
function CreateStream(url, id, skip_cache)
{
dprint("Loading " + url);
download_buffer(url, function(buffer)
{
var stream = {};
stream.id = id;
stream.position = 0;
stream.buffer = buffer;
stream.url = url;
stream.speed = 1; // 1 = normal pitch
stream.max_loop = 1; // -1 = inf
stream.vol_both = 1;
stream.vol_left = 1;
stream.vol_right = 1;
stream.paused = true;
stream.use_smoothing = true;
stream.echo_volume = 0;
stream.filter_type = 0;
stream.filter_fraction = 1;
stream.done_playing = false;
stream.use_echo = false;
stream.echo_feedback = 0.75;
stream.echo_buffer = false;
stream.vol_left_smooth = 0;
stream.vol_right_smooth = 0;
stream.speed_smooth = stream.speed;
stream.play = function(stop, position)
{
dprint("play " + stop + position)
if(position !== undefined)
{
stream.position = position;
}
stream.paused = !stop;
};
stream.usefft = function(enable)
{
// later
};
stream.useEcho = function(b) {
stream.use_echo = b;
if (b)
{
stream.setEchoDelay(stream.echo_delay);
}
else
{
stream.echo_buffer = undefined;
}
};
stream.setEchoDelay = function(x) {
if(stream.use_echo && (!stream.echo_buffer || (x != stream.echo_buffer.length))) {
var size = 1;
while((size <<= 1) < x);
stream.echo_buffer = audio.createBuffer(2, size, audio.sampleRate);
}
stream.echo_delay = x;
};
streams[id] = stream;
streams_array.push(stream);
dprint("created stream[" + id + "][" + stream.url + "]");
lua.message("stream", "loaded", id, buffer.length);
if (]==] .. (webaudio.debug and "true" or "false") .. [==[)
{
var size = 0, key;
for (key in streams) {
if (streams.hasOwnProperty(key)) size++;
}
dprint("total stream count " + size)
}
}, skip_cache, id);
}
function DestroyStream(id)
{
var stream = streams[id];
if (stream)
{
dprint("destroying stream[" + id + "][" + stream.url + "]");
delete streams[id];
delete buffer_cache[stream.url];
var i = streams_array.indexOf(stream);
streams_array.splice(i, 1);
if (]==] .. (webaudio.debug and "true" or "false") .. [==[)
{
var size = 0, key;
for (key in streams) {
if (streams.hasOwnProperty(key)) size++;
}
dprint("total stream count " + size)
}
}
}
open();
]==])
webaudio.browser_panel.OnFinishLoadingDocument = function(self)
self.OnFinishLoadingDocument = nil
dprint("OnFinishLoadingDocument")
webaudio.browser_panel:RunJavascript(js)
end
file.Write("pac_webaudio2_blankhtml.txt", "<html></html>")
webaudio.browser_panel:OpenURL("asset://garrysmod/data/pac_webaudio2_blankhtml.txt")
hook.Add("RenderScene", "pac_webaudio2", function(pos, ang)
webaudio.eye_pos = pos
webaudio.eye_ang = ang
end)
hook.Add("Think", "pac_webaudio2", webaudio.Update)
end
-- Audio
function webaudio.SetVolume(vol)
if webaudio.volume ~= vol then
webaudio.volume = vol
run_javascript(string.format("gain.gain.value = %f", vol), self)
end
end
webaudio.streams = setmetatable({}, {__mode = "kv"})
do
local META = {}
META.__index = META
local function DECLARE_PROPERTY(name, default, javascriptSetterCode, filterFunction)
META[name] = default
META["Set" .. name] = function(self, value)
if filterFunction then
value = filterFunction(value, self)
end
self[name] = value
if javascriptSetterCode then
self:Call(javascriptSetterCode, value)
end
end
META["Get" .. name] = function(self, ...)
return self[name]
end
end
DECLARE_PROPERTY("Loaded", false)
DECLARE_PROPERTY("Paused", true)
DECLARE_PROPERTY("SampleCount", 0)
DECLARE_PROPERTY("MaxLoopCount", nil)
DECLARE_PROPERTY("Panning", 0)
DECLARE_PROPERTY("Volume", 1)
DECLARE_PROPERTY("AdditiveVolumeFraction", 0)
DECLARE_PROPERTY("3D", false)
DECLARE_PROPERTY("Doppler", true)
DECLARE_PROPERTY("SourceEntity", NULL)
DECLARE_PROPERTY("SourcePosition", nil)
DECLARE_PROPERTY("LastSourcePosition", nil)
DECLARE_PROPERTY("LastSourcePositionTime", nil)
DECLARE_PROPERTY("SourceVelocity", nil)
DECLARE_PROPERTY("SourceRadius", 4300)
DECLARE_PROPERTY("ListenerOutOfRadius", false)
DECLARE_PROPERTY("Id")
DECLARE_PROPERTY("Url", "")
DECLARE_PROPERTY("PlaybackSpeed", 1)
DECLARE_PROPERTY("AdditivePitchModifier", 0)
DECLARE_PROPERTY("SamplePosition", 0, ".position = %f")
DECLARE_PROPERTY("PitchLFOAmount", nil, ".lfo_pitch_amount = %f")
DECLARE_PROPERTY("PitchLFOTime", nil, ".lfo_pitch_time = %f")
DECLARE_PROPERTY("VolumeLFOAmount", nil, ".lfo_volume_amount = %f")
DECLARE_PROPERTY("VolumeLFOTime", nil, ".lfo_volume_time = %f")
DECLARE_PROPERTY("FilterType", nil, ".filter_type = %i")
DECLARE_PROPERTY("FilterFraction", 0, ".filter_fraction = %f", function(num) return math.Clamp(num, 0, 1) end)
DECLARE_PROPERTY("Echo", false, ".useEcho(%s)")
DECLARE_PROPERTY("EchoDelay", 1, ".setEchoDelay(Math.ceil(audio.sampleRate * %f))", function(num) return math.Clamp(num, 0, 5) end)
DECLARE_PROPERTY("EchoFeedback", 0.75, ".echo_feedback = %f")
-- State
function META:IsReady()
return self.Loaded
end
function META:GetLength()
if not self.Loaded then return 0 end
return self.SampleCount / tonumber(webaudio.sample_rate)
end
function META:IsValid()
return self.invalid == nil
end
function META:Remove()
webaudio.streams[self:GetId()] = nil
self:Stop()
run_javascript(string.format("DestroyStream(%i)", self:GetId()))
self.invalid = true
end
-- Browser
function META:Call(fmt, ...)
local code = string.format("var id = %d; try { if (streams[id]) { streams[id]%s } } catch(e) { dprint('streams[' + id + '] ' + e.toString()) }", self:GetId(), string.format(fmt, ...))
run_javascript(code, self)
end
function META:HandleBrowserMessage(t, ...)
if t == "call" then
self:HandleCallBrowserMessage(...)
elseif t == "fft" then
self:HandleFFTBrowserMessage(...)
elseif t == "stop" then
self.Paused = true
elseif t == "return" then
self.ReturnedValues = {...}
elseif t == "loaded" then
self:HandleLoadedBrowserMessage(...)
elseif t == "position" then
self:HandlePositionBrowserMessage(...)
end
end
function META:SetMaxLoopCount(maxLoopCount)
self.MaxLoopCount = maxLoopCount
self:Call(".max_loop = %i", maxLoopCount == true and -1 or maxLoopCount == false and 1 or tonumber(maxLoopCount) or 1)
end
function META:Pause()
self.Paused = true
self:Call(".play(false)")
end
function META:Resume()
self.Paused = false
self:UpdatePlaybackSpeed()
self:UpdateVolume()
self:Call(".play(true)")
end
function META:Play()
self.Paused = false
queue_javascript()
self:UpdatePlaybackSpeed()
self:UpdateVolume()
self:Call(".play(true, 0)")
execute_javascript()
end
function META:Stop()
self.Paused = true
self:Call(".play(false, 0)")
end
function META:Restart()
self:SetSamplePosition(0)
end
function META:SetPosition(pos)
self:SetSamplePosition((pos % 1) * self:GetSampleCount())
end
function META:SetPlaybackRate(mult)
if self.PlaybackSpeed == mult then return self end
self.PlaybackSpeed = mult
self:UpdatePlaybackSpeed()
return self
end
function META:SetAdditivePitchModifier(additivePitchModifier)
if self.AdditivePitchModifier == additivePitchModifier then return self end
self.AdditivePitchModifier = additivePitchModifier
self:UpdatePlaybackSpeed()
return self
end
function META:UpdatePlaybackSpeed(add)
local speed = self.PlaybackSpeed + self.AdditivePitchModifier
if speed < 0 then
self:Call(".reverse = true")
speed = math.abs(speed)
end
if add then
speed = speed + add
end
if speed ~= self.last_speed then
self:Call(".speed = %f", speed)
self.last_speed = speed
end
end
function META:SetPanning(panning)
if self.Panning == panning then return self end
self.Panning = panning
self:UpdateVolume()
return self
end
function META:SetVolume(volumeFraction)
if self.Volume == volumeFraction then return self end
self.Volume = volumeFraction
self:UpdateVolume()
return self
end
function META:SetAdditiveVolumeModifier(additiveVolumeFraction)
if self.AdditiveVolumeFraction == additiveVolumeFraction then return self end
self.AdditiveVolumeFraction = additiveVolumeFraction
self:UpdateVolume()
return self
end
local function FindHeadPos(ent)
if ent.findheadpos_last_mdl ~= ent:GetModel() then
ent.findheadpos_head_bone = nil
ent.findheadpos_head_attachment = nil
ent.findheadpos_last_mdl = ent:GetModel()
end
if not ent.findheadpos_head_bone then
for i = 0, ent:GetBoneCount() or 0 do
local name = ent:GetBoneName(i):lower()
if name:find("head", nil, true) then
ent.findheadpos_head_bone = i
break
end
end
end
if ent.findheadpos_head_bone then
local m = ent:GetBoneMatrix(ent.findheadpos_head_bone)
if m then
local pos = m:GetTranslation()
if pos ~= ent:GetPos() then
return pos, m:GetAngles()
end
end
else
if not ent.findheadpos_attachment_eyes then
ent.findheadpos_head_attachment = ent:GetAttachments().eyes or ent:GetAttachments().forward
end
if ent.findheadpos_head_attachment then
local angpos = ent:GetAttachment(ent.findheadpos_head_attachment)
return angpos.Pos, angpos.Ang
end
end
return ent:EyePos(), ent:EyeAngles()
end
function META:UpdateSourcePosition()
if not self.SourceEntity:IsValid() then
self:OutOfRadius()
return
end
self.SourcePosition = FindHeadPos(self.SourceEntity)
end
function META:UpdateVolume()
queue_javascript()
if self:Get3D() then
self:UpdateVolume3d()
else
self:UpdateVolumeFlat()
end
execute_javascript()
end
function META:UpdateVolumeFlat()
self:SetRightVolume((math.Clamp(1 + self.Panning, 0, 1)) + self.AdditiveVolumeFraction)
self:SetLeftVolume((math.Clamp(1 - self.Panning, 0, 1)) + self.AdditiveVolumeFraction)
end
function META:UpdateVolumeBoth()
if self.last_vol_both ~= self.Volume then
self:Call(".vol_both= %f", self.Volume)
self.last_vol_both = self.Volume
end
end
function META:SetLeftVolume(vol)
if self.last_left_volume ~= vol then
self:Call(".vol_left= %f", vol)
self.last_left_volume = vol
end
self:UpdateVolumeBoth()
end
function META:SetRightVolume(vol)
if self.last_right_volume ~= vol then
self:Call(".vol_right = %f", vol)
self.last_right_volume = vol
end
self:UpdateVolumeBoth()
end
function META:UpdateVolume3d()
if self.SourceEntity == LocalPlayer() and not self.SourceEntity:ShouldDrawLocalPlayer() then
self:UpdateVolumeFlat()
return
end
self:UpdateSourcePosition()
local time = RealTime()
self.SourcePosition = self.SourcePosition or Vector()
self.LastSourcePosition = self.LastSourcePosition or self.SourcePosition
self.LastSourcePositionTime = self.LastSourcePositionTime or (time - FrameTime())
self.SourceVelocity = (self.SourcePosition - self.LastSourcePosition) / (time - self.LastSourcePositionTime)
self.LastSourcePosition = self.SourcePosition
self.LastSourcePositionTime = time + 0.001
local relativeSourcePosition = self.SourcePosition - webaudio.eye_pos
local distanceToSource = relativeSourcePosition:Length()
if distanceToSource < self.SourceRadius then
local pan = relativeSourcePosition:GetNormalized():Dot(webaudio.eye_ang:Right())
local volumeFraction = math.Clamp(1 - distanceToSource / self.SourceRadius, 0, 1) ^ 6
volumeFraction = volumeFraction * 0.5
self:SetRightVolume((math.Clamp(1 + pan, 0, 1) * volumeFraction) + self.AdditiveVolumeFraction)
self:SetLeftVolume((math.Clamp(1 - pan, 0, 1) * volumeFraction) + self.AdditiveVolumeFraction)
if self:GetDoppler() then
local relativeSourceVelocity = self.SourceVelocity - webaudio.eye_velocity
local relativeSourceSpeed = relativeSourcePosition:GetNormalized():Dot(-relativeSourceVelocity) * 0.0254
self:UpdatePlaybackSpeed(relativeSourceSpeed / webaudio.speed_of_sound)
end
self.ListenerOutOfRadius = false
else
self:OutOfRadius()
end
end
function META:OutOfRadius()
if not self.ListenerOutOfRadius then
self:SetRightVolume(0)
self:SetLeftVolume(0)
self.ListenerOutOfRadius = true
end
end
function META:SetSourceEntity(ent, dont_remove)
self.SourceEntity = ent
if not dont_remove and ent:IsValid() then
ent:CallOnRemove("webaudio_remove_stream_" .. tostring(self), function()
if self:IsValid() then
self:Remove()
end
end)
end
end
function META:Think()
if self.Paused then return end
self:UpdateVolume()
end
function META:__newindex(key, val)
if key == "OnFFT" then
if type(val) == "function" then
self:Call(".usefft(true)")
else
self:Call(".usefft(false)")
end
end
rawset(self, key, val)
end
function META:__tostring()
return string.format("stream[%p][%d][%s]", self, self:GetId(), self:GetUrl())
end
-- Internal browser message handlers
function META:HandleCallBrowserMessage(methodName, ...)
if not self[methodName] then return end
self[methodName](self, ...)
end
function META:HandleFFTBrowserMessage(serializeFFTData)
local fftArray = CompileString(serializeFFTData, "stream_fft_data")()
self.OnFFT(fftArray)
end
function META:HandleLoadedBrowserMessage(sampleCount)
self.Loaded = true
self.SampleCount = sampleCount
queue_javascript()
self:SetFilterType(0)
self:SetMaxLoopCount(self:GetMaxLoopCount())
self:SetEcho(self:GetEcho())
self:SetEchoFeedback(self:GetEchoFeedback())
self:SetEchoDelay(self:GetEchoDelay())
execute_javascript()
if self.OnLoad then
self:OnLoad()
end
if self.js_queue then
for _, code in ipairs(self.js_queue) do
run_javascript(code)
end
self.js_queue = nil
end
end
function META:HandlePositionBrowserMessage(samplePosition)
self.SamplePosition = samplePosition
end
webaudio.stream_meta = META
end
webaudio.streams = webaudio.streams or {}
webaudio.last_stream_id = 0
function webaudio.CreateStream(path)
webaudio.Initialize()
path = "../" .. path
local self = setmetatable({}, webaudio.stream_meta)
webaudio.last_stream_id = webaudio.last_stream_id + 1
self:SetId(webaudio.last_stream_id)
self:SetUrl(path)
webaudio.streams[self:GetId()] = self
run_javascript(string.format("CreateStream(%q, %i)", self:GetUrl(), self:GetId()))
return self
end
function webaudio.Panic(strong)
for k,v in pairs(webaudio.streams) do
v:Remove()
end
webaudio.last_stream_id = 0
end
function webaudio.GetStream(streamId)
return webaudio.streams[streamId] or NULL
end
function webaudio.StreamExists(streamId)
return webaudio.streams[streamId] ~= nil
end
return webaudio
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Port_San_dOria/npcs/Parcarin.lua | 17 | 1694 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Parcarin
-- Involved in Quest: Lure of the Wildcat (San d'Oria)
-- @pos -9 -13 -151 232
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if(trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatSandy = player:getVar("WildcatSandy");
if(player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,13) == false) then
player:startEvent(0x02eb);
else
player:startEvent(0x0236);
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 == 0x02eb) then
player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",13,true);
end
end; | gpl-3.0 |
sjznxd/luci-0.11-aa | libs/nixio/docsrc/nixio.File.lua | 173 | 4457 | --- Large File Object.
-- Large file operations are supported up to 52 bits if the Lua number type is
-- double (default).
-- @cstyle instance
module "nixio.File"
--- Write to the file descriptor.
-- @class function
-- @name File.write
-- @usage <strong>Warning:</strong> It is not guaranteed that all data
-- in the buffer is written at once especially when dealing with pipes.
-- You have to check the return value - the number of bytes actually written -
-- or use the safe IO functions in the high-level IO utility module.
-- @usage Unlike standard Lua indexing the lowest offset and default is 0.
-- @param buffer Buffer holding the data to be written.
-- @param offset Offset to start reading the buffer from. (optional)
-- @param length Length of chunk to read from the buffer. (optional)
-- @return number of bytes written
--- Read from a file descriptor.
-- @class function
-- @name File.read
-- @usage <strong>Warning:</strong> It is not guaranteed that all requested data
-- is read at once especially when dealing with pipes.
-- You have to check the return value - the length of the buffer actually read -
-- or use the safe IO functions in the high-level IO utility module.
-- @usage The length of the return buffer is limited by the (compile time)
-- nixio buffersize which is <em>nixio.const.buffersize</em> (8192 by default).
-- Any read request greater than that will be safely truncated to this value.
-- @param length Amount of data to read (in Bytes).
-- @return buffer containing data successfully read
--- Reposition read / write offset of the file descriptor.
-- The seek will be done either from the beginning of the file or relative
-- to the current position or relative to the end.
-- @class function
-- @name File.seek
-- @usage This function calls lseek().
-- @param offset File Offset
-- @param whence Starting point [<strong>"set"</strong>, "cur", "end"]
-- @return new (absolute) offset position
--- Return the current read / write offset of the file descriptor.
-- @class function
-- @name File.tell
-- @usage This function calls lseek() with offset 0 from the current position.
-- @return offset position
--- Synchronizes the file with the storage device.
-- Returns when the file is successfully written to the disk.
-- @class function
-- @name File.sync
-- @usage This function calls fsync() when data_only equals false
-- otherwise fdatasync(), on Windows _commit() is used instead.
-- @usage fdatasync() is only supported by Linux and Solaris. For other systems
-- the <em>data_only</em> parameter is ignored and fsync() is always called.
-- @param data_only Do not synchronize the metadata. (optional, boolean)
-- @return true
--- Apply or test a lock on the file.
-- @class function
-- @name File.lock
-- @usage This function calls lockf() on POSIX and _locking() on Windows.
-- @usage The "lock" command is blocking, "tlock" is non-blocking,
-- "ulock" unlocks and "test" only tests for the lock.
-- @usage The "test" command is not available on Windows.
-- @usage Locks are by default advisory on POSIX, but mandatory on Windows.
-- @param command Locking Command ["lock", "tlock", "ulock", "test"]
-- @param length Amount of Bytes to lock from current offset (optional)
-- @return true
--- Get file status and attributes.
-- @class function
-- @name File.stat
-- @param field Only return a specific field, not the whole table (optional)
-- @usage This function calls fstat().
-- @return Table containing: <ul>
-- <li>atime = Last access timestamp</li>
-- <li>blksize = Blocksize (POSIX only)</li>
-- <li>blocks = Blocks used (POSIX only)</li>
-- <li>ctime = Creation timestamp</li>
-- <li>dev = Device ID</li>
-- <li>gid = Group ID</li>
-- <li>ino = Inode</li>
-- <li>modedec = Mode converted into a decimal number</li>
-- <li>modestr = Mode as string as returned by `ls -l`</li>
-- <li>mtime = Last modification timestamp</li>
-- <li>nlink = Number of links</li>
-- <li>rdev = Device ID (if special file)</li>
-- <li>size = Size in bytes</li>
-- <li>type = ["reg", "dir", "chr", "blk", "fifo", "lnk", "sock"]</li>
-- <li>uid = User ID</li>
-- </ul>
--- Close the file descriptor.
-- @class function
-- @name File.close
-- @return true
--- Get the number of the filedescriptor.
-- @class function
-- @name File.fileno
-- @return file descriptor number
--- (POSIX) Set the blocking mode of the file descriptor.
-- @class function
-- @name File.setblocking
-- @param blocking (boolean)
-- @return true | apache-2.0 |
nbeams/program-visualizer | external/src/glfw/support/lua/examples/gears.lua | 2 | 10185 | --------------------------------------------------------------------------
-- 3-D gear wheels. This program is in the public domain.
--
-- Command line options:
-- -info print GL implementation information
-- -exit automatically exit after 30 seconds
--
--
-- Brian Paul
--
--
-- Marcus Geelnard:
-- - Conversion to GLFW
-- - Time based rendering (frame rate independent)
-- - Slightly modified camera that should work better for stereo viewing
-- - Ported to Lua (thanks to David Medlock for the original Lua port)
--------------------------------------------------------------------------
local t0 = 0.0
local t = 0
local dt = 0
local Frames = 0
local autoexit = 0
--------------------------------------------------------------------------
-- Draw a gear wheel. You'll probably want to call this function when
-- building a display list since we do a lot of trig here.
--
-- Input: inner_radius - radius of hole at center
-- outer_radius - radius at center of teeth
-- width - width of gear
-- teeth - number of teeth
-- tooth_depth - depth of tooth
--------------------------------------------------------------------------
local function gear(inner_radius, outer_radius, width, teeth, tooth_depth)
local PI = 3.141592654
local r0 = inner_radius
local r1 = outer_radius - ( tooth_depth / 2.0 )
local r2 = outer_radius + ( tooth_depth / 2.0 )
local da = 2.0 * PI / teeth / 4.0
gl.ShadeModel("FLAT")
gl.Normal(0.0, 0.0, 1.0)
local cos = math.cos;
local sin = math.sin;
local sqrt = math.sqrt;
-- draw front face
gl.Begin("QUAD_STRIP");
for i = 0, teeth do
angle = i * 2.0 * PI / teeth
gl.Vertex(r0 * cos(angle), r0 * sin(angle), width * 0.5)
gl.Vertex(r1 * cos(angle), r1 * sin(angle), width * 0.5)
if (i < teeth) then
gl.Vertex(r0 * cos(angle), r0 * sin(angle), width * 0.5)
gl.Vertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5)
end
end
gl.End()
-- draw front sides of teeth
gl.Begin("QUADS")
da = 2.0 * PI / teeth / 4.0;
for i = 0,teeth-1 do
angle = i * 2.0 * PI / teeth
gl.Vertex(r1 * cos(angle), r1 * sin(angle), width * 0.5)
gl.Vertex(r2 * cos(angle + da), r2 * sin(angle + da), width * 0.5)
gl.Vertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5)
gl.Vertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5)
end
gl.End()
gl.Normal(0.0, 0.0, -1.0)
-- draw back face
gl.Begin("QUAD_STRIP")
for i = 0,teeth do
angle = i * 2.0 * PI / teeth
gl.Vertex(r1 * cos(angle), r1 * sin(angle), -width * 0.5)
gl.Vertex(r0 * cos(angle), r0 * sin(angle), -width * 0.5)
if (i < teeth) then
gl.Vertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5)
gl.Vertex(r0 * cos(angle), r0 * sin(angle), -width * 0.5)
end
end
gl.End()
-- draw back sides of teeth
gl.Begin("QUADS")
da = 2.0 * PI / teeth / 4.0
for i = 0, teeth-1 do
angle = i * 2.0 * PI / teeth
gl.Vertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5)
gl.Vertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), -width * 0.5)
gl.Vertex(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5)
gl.Vertex(r1 * cos(angle), r1 * sin(angle), -width * 0.5)
end
gl.End()
-- draw outward faces of teeth
gl.Begin("QUAD_STRIP")
for i = 0, teeth-1 do
angle = i * 2.0 * PI / teeth
gl.Vertex(r1 * cos(angle), r1 * sin(angle), width * 0.5)
gl.Vertex(r1 * cos(angle), r1 * sin(angle), -width * 0.5)
u = r2 * cos(angle + da) - r1 * cos(angle)
v = r2 * sin(angle + da) - r1 * sin(angle)
len = sqrt(u * u + v * v)
u = u / len
v = v / len
gl.Normal(v, -u, 0.0)
gl.Vertex(r2 * cos(angle + da), r2 * sin(angle + da), width * 0.5)
gl.Vertex(r2 * cos(angle + da), r2 * sin(angle + da), -width * 0.5)
gl.Normal(cos(angle), sin(angle), 0.0)
gl.Vertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), width * 0.5)
gl.Vertex(r2 * cos(angle + 2 * da), r2 * sin(angle + 2 * da), -width * 0.5)
u = r1 * cos(angle + 3 * da) - r2 * cos(angle + 2 * da)
v = r1 * sin(angle + 3 * da) - r2 * sin(angle + 2 * da)
gl.Normal(v, -u, 0.0)
gl.Vertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), width * 0.5)
gl.Vertex(r1 * cos(angle + 3 * da), r1 * sin(angle + 3 * da), -width * 0.5)
gl.Normal(cos(angle), sin(angle), 0.0)
end
gl.Vertex(r1 * cos(0), r1 * sin(0), width * 0.5)
gl.Vertex(r1 * cos(0), r1 * sin(0), -width * 0.5)
gl.End()
gl.ShadeModel("SMOOTH");
-- draw inside radius cylinder
gl.Begin("QUAD_STRIP")
for i = 0,teeth do
angle = i * 2.0 * PI / teeth
gl.Normal(-cos(angle), -sin(angle), 0.0)
gl.Vertex(r0 * cos(angle), r0 * sin(angle), -width * 0.5)
gl.Vertex(r0 * cos(angle), r0 * sin(angle), width * 0.5)
end
gl.End()
end
local running = true
local view = { rotx = 20.0 ; roty = 30.0 ; rotz = 0.0 }
local gear1, gear2, gear3
local angle = 0.0
--------------------------------------------------------------------------
-- OpenGL draw function & timing
--------------------------------------------------------------------------
local function draw()
gl.Clear("DEPTH_BUFFER_BIT,COLOR_BUFFER_BIT")
gl.MatrixMode( "MODELVIEW" );
gl.PushMatrix()
gl.Rotate(view.rotx, 1.0, 0.0, 0.0)
gl.Rotate(view.roty, 0.0, 1.0, 0.0)
gl.Rotate(view.rotz, 0.0, 0.0, 1.0)
gl.PushMatrix()
gl.Translate(-3.0, -2.0, 0.0)
gl.Rotate(angle, 0.0, 0.0, 1.0)
gl.CallList(gear1)
gl.PopMatrix()
gl.PushMatrix()
gl.Translate(3.1, -2.0, 0.0)
gl.Rotate(-2.0 * angle - 9.0, 0.0, 0.0, 1.0)
gl.CallList(gear2)
gl.PopMatrix()
gl.PushMatrix()
gl.Translate(-3.1, 4.2, 0.0)
gl.Rotate(-2.0 * angle - 25.0, 0.0, 0.0, 1.0)
gl.CallList(gear3)
gl.PopMatrix()
gl.PopMatrix()
Frames = Frames + 1;
do
t_new = glfw.GetTime()
dt = t_new - t;
t = t_new;
if (t - t0 >= 5.0) then
seconds = t - t0;
fps = Frames / seconds;
print(Frames, " frames in ", seconds, " seconds = ", fps, " FPS")
t0 = t;
Frames = 0;
if (t >= 0.999 * autoexit) and autoexit then running = 0 end
end
end
end
--------------------------------------------------------------------------
-- Initialize OpenGL
--------------------------------------------------------------------------
local function init(args)
pos = {5.0, 5.0, 10.0, 0.0}
red = {0.8, 0.1, 0.0, 1.0}
green = {0.0, 0.8, 0.2, 1.0}
blue = {0.2, 0.2, 1.0, 1.0}
gl.Light("LIGHT0", "POSITION", pos)
gl.Enable("CULL_FACE")
gl.Enable("LIGHTING")
gl.Enable("LIGHT0")
gl.Enable("DEPTH_TEST")
gl.DepthFunc("LEQUAL")
-- make the gears
gear1 = gl.GenLists(1)
gl.NewList(gear1, "COMPILE");
gl.Material("FRONT", "AMBIENT_AND_DIFFUSE", red);
gear(1.0, 4.0, 1.0, 20, 0.7);
gl.EndList()
gear2 = gl.GenLists(1)
gl.NewList(gear2, "COMPILE")
gl.Material("FRONT", "AMBIENT_AND_DIFFUSE", green)
gear(0.5, 2.0, 2.0, 10, 0.7)
gl.EndList()
gear3 = gl.GenLists(1);
gl.NewList(gear3, "COMPILE")
gl.Material("FRONT", "AMBIENT_AND_DIFFUSE", blue)
gear(1.3, 2.0, 0.5, 10, 0.7)
gl.EndList()
gl.Enable("NORMALIZE")
if args then
for parm in args do
if parm == "-exit" then
autoexit = 30
print("Auto Exit after ", autoexit ," seconds." );
end
end
end
end
--------------------------------------------------------------------------
-- update animation parameters
--------------------------------------------------------------------------
local function animate()
angle = angle + 100.0*dt
end
--------------------------------------------------------------------------
-- new window size
--------------------------------------------------------------------------
function reshape( width, height )
local h = height / width
local znear = 5.0
local zfar = 30.0
local xmax = znear * 0.5
gl.Viewport( 0, 0, width, height )
gl.MatrixMode( "PROJECTION" );
gl.LoadIdentity()
gl.Frustum( -xmax, xmax, -xmax*h, xmax*h, znear, zfar )
gl.MatrixMode( "MODELVIEW" );
gl.LoadIdentity()
gl.Translate( 0.0, 0.0, -20.0 )
gl.Enable( "DEPTH_TEST" );
end
--------------------------------------------------------------------------
-- change view angle, exit upon ESC
--------------------------------------------------------------------------
function key( k, action )
if action ~= glfw.PRESS then return end
-- 'Z'?
if k == 90 then
if glfw.GetKey( glfw.KEY_LSHIFT ) == glfw.PRESS then
view.rotz = view.rotz - 5.0
else
view.rotz = view.rotz + 5.0
end
return
end
if k == glfw.KEY_ESC then
running = false
return
end
if k == glfw.KEY_UP then
view.rotx = view.rotx + 5.0
return
end
if k == glfw.KEY_DOWN then
view.rotx = view.rotx - 5.0
return
end
if k == glfw.KEY_LEFT then
view.roty = view.roty + 5.0
return
end
if k == glfw.KEY_RIGHT then
view.roty = view.roty - 5.0
return
end
end
--------------------------------------------------------------------------
-- main()
--------------------------------------------------------------------------
local function main()
-- Init GLFW
if glfw.Init() ~= glfw.TRUE then
return
end
-- Open window
if glfw.OpenWindow( 640,480,0,0,0,0,24,0,glfw.WINDOW ) ~= glfw.TRUE then
glfw.Terminate()
return
end
glfw.SetWindowTitle( "Gears" );
glfw.Enable( glfw.KEY_REPEAT );
glfw.SwapInterval( 0 );
-- Special args?
init(args);
-- Set callback functions
glfw.SetWindowSizeCallback( "reshape" );
glfw.SetKeyCallback( "key" );
while running do
-- Draw gears
draw()
-- Update animation
animate()
-- Swap buffers
glfw.SwapBuffers()
-- Was the window closed?
if glfw.GetWindowParam( glfw.OPENED ) ~= glfw.TRUE then
running = false
end
end
-- Terminate GLFW
glfw.Terminate()
-- Exit program
return
end
-- execute!
main()
| gpl-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Southern_San_dOria/npcs/Hanaa_Punaa.lua | 19 | 6196 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Hanaa Punaa
-- Starts and Finishes: A Squire's Test, A Squire's Test II, A Knight's Test
-- @zone 230
-- @pos
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "The Seamstress" , x3 sheepskin trade
if(player:getQuestStatus(SANDORIA,THE_SEAMSTRESS) ~= QUEST_AVAILABLE) then
if(trade:hasItemQty(505,3) and trade:getItemCount() == 3) then
player:startEvent(0x0212);
end
end
-- "Black Tiger Skins", Tiger Hide trade
if(player:getQuestStatus(SANDORIA,BLACK_TIGER_SKINS) == QUEST_ACCEPTED) then
if(trade:hasItemQty(861,3) and trade:getItemCount() == 3) then
player:startEvent(0x0241);
end
end
-- "Lizard Skins", lizard skin trade
if(player:getQuestStatus(SANDORIA,LIZARD_SKINS) ~= QUEST_AVAILABLE) then
if(trade:hasItemQty(852,3) and trade:getItemCount() == 3) then
player:startEvent(0x0231);
end
end
-- "Flyers for Regine"
if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if(MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Checking Fame Level & Quest
sanFame = player:getFameLevel(SANDORIA);
theSteamStress = player:getQuestStatus(SANDORIA,THE_SEAMSTRESS);
lizardSkins = player:getQuestStatus(SANDORIA,LIZARD_SKINS);
blackTigerSkins = player:getQuestStatus(SANDORIA,BLACK_TIGER_SKINS);
-- "The Seamstress" Quest Status
if(theSteamStress == QUEST_AVAILABLE and player:getVar("theSeamStress") == 1) then
player:startEvent(0x0213);
elseif(theSteamStress == QUEST_AVAILABLE) then
player:startEvent(0x0210);
player:setVar("theSeamStress",1);
elseif(theSteamStress == QUEST_ACCEPTED) then
player:startEvent(0x0211);
elseif(theSteamStress == QUEST_COMPLETED and sanFame < 2) then
player:startEvent(0x024e);
-- "Lizard Skins" Quest Dialogs
elseif(lizardSkins == QUEST_AVAILABLE and player:getVar("lzdSkins") == 1 and sanFame >= 2 and theSteamStress == QUEST_COMPLETED) then
player:startEvent(0x0232);
elseif(lizardSkins == QUEST_AVAILABLE and sanFame >= 2 and theSteamStress == QUEST_COMPLETED) then
player:startEvent(0x022f);
player:setVar("lzdSkins",1);
elseif(lizardSkins == QUEST_ACCEPTED) then
player:startEvent(0x0230);
elseif(lizardSkins == QUEST_COMPLETED and sanFame < 3) then
player:startEvent(0x024f);
-- "Black Tiger Skins" Quest Dialogs
elseif(blackTigerSkins == QUEST_AVAILABLE and player:getVar("blkTigerSkin") == 1 and sanFame >= 3 and theSteamStress == QUEST_COMPLETED and lizardSkins == QUEST_COMPLETED) then
player:startEvent(0x0243 );
elseif(blackTigerSkins == QUEST_AVAILABLE and sanFame >= 3 and theSteamStress == QUEST_COMPLETED and lizardSkins == QUEST_COMPLETED) then
player:startEvent(0x0240);
player:setVar("blkTigerSkin",1);
elseif(blackTigerSkins == QUEST_ACCEPTED) then
player:startEvent(0x0242);
elseif(blackTigerSkins == QUEST_COMPLETED) then
player:startEvent(0x0250);
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);
-- "The Seamstress" Quest
if((csid == 0x0210 or csid == 0x0213) and option == 0) then
player:addQuest(SANDORIA,THE_SEAMSTRESS);
player:setVar("theSeamStress",0);
elseif(csid == 0x0212) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12696); -- Leather Gloves
else
player:tradeComplete();
player:addTitle(SILENCER_OF_THE_LAMBS);
player:addItem(12696);
player:messageSpecial(ITEM_OBTAINED, 12696); -- Leather Gloves
if(player:getQuestStatus(SANDORIA,THE_SEAMSTRESS) == QUEST_ACCEPTED) then
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,THE_SEAMSTRESS);
else
player:addFame(SANDORIA,SAN_FAME*5);
end
end
-- "Liard Skins" Quest
elseif((csid == 0x022f or csid == 0x0232) and option == 0) then
player:addQuest(SANDORIA,LIZARD_SKINS);
player:setVar("lzdSkins",0);
elseif(csid == 0x0231) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12697); -- Lizard Gloves
else
player:tradeComplete();
player:addTitle(LIZARD_SKINNER);
player:addItem(12697);
player:messageSpecial(ITEM_OBTAINED, 12697); -- Lizard Gloves
if(player:getQuestStatus(SANDORIA,LIZARD_SKINS) == QUEST_ACCEPTED) then
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,LIZARD_SKINS);
else
player:addFame(SANDORIA,SAN_FAME*5);
end
end
-- "Black Tiger Skins" Quest
elseif((csid == 0x0240 or csid == 0x0243) and option == 0) then
player:addQuest(SANDORIA,BLACK_TIGER_SKINS);
player:setVar("blkTigerSkin",0);
elseif(csid == 0x0241) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13119); -- Tyger Stole
else
player:tradeComplete();
player:addTitle(CAT_SKINNER);
player:addItem(13119);
player:messageSpecial(ITEM_OBTAINED, 13119); -- Tyger Stole
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,BLACK_TIGER_SKINS);
end
end
end; | gpl-3.0 |
msburgess3200/PERP | gamemodes/perp/entities/weapons/weapon_perp_copgun_mp5/shared.lua | 1 | 1293 |
if ( SERVER ) then
AddCSLuaFile( "shared.lua" )
SWEP.BackHolster = false;
end
if ( CLIENT ) then
SWEP.PrintName = "Tactical MP5"
SWEP.Author = "Counter-Strike"
SWEP.Slot = 3
SWEP.SlotPos = 1
SWEP.IconLetter = "x"
end
SWEP.HoldType = "ar2";
SWEP.HoldTypeNorm = "normal";
SWEP.Base = "weapon_perp_base"
SWEP.Category = "Counter-Strike"
SWEP.Spawnable = true
SWEP.AdminSpawnable = true
SWEP.ViewModel = "models/weapons/v_smg_mp5.mdl"
SWEP.WorldModel = "models/weapons/w_smg_mp5.mdl"
SWEP.Weight = 5
SWEP.AutoSwitchTo = false
SWEP.AutoSwitchFrom = false
SWEP.AnimPrefix = "rpg"
SWEP.Primary.Sound = Sound("Weapon_MP5Navy.Single")
SWEP.Primary.Recoil = 0.6
SWEP.Primary.Damage = 17
SWEP.Primary.NumShots = 1
SWEP.Primary.Cone = 0.017
SWEP.Primary.ClipSize = 30
SWEP.Primary.Delay = 0.075
SWEP.Primary.DefaultClip = 30
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "smg1"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.IronSightsPos = Vector (4.7617, -5.1273, 1.9673)
SWEP.IronSightsAng = Vector (0, 0, 0)
SWEP.NormalPos = Vector( 0, 0, 3 )
SWEP.NormalAng = Vector( -20, 0, 0 );
SWEP.MaxPenetration = PENETRATION_SMG; | mit |
joshimoo/Algorithm-Implementations | Euclidean_algorithm/Lua/Yonaba/euclidian_test.lua | 27 | 1896 | -- Tests for euclidian.lua
local gcd = require 'euclidian'
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('Testing gcd.division', function()
assert(gcd.division(10, 15) == 5)
assert(gcd.division(14, 7) == 7)
assert(gcd.division(12, 12) == 12)
assert(gcd.division( 7, 3) == 1)
assert(gcd.division( 5, 0) == 5)
assert(gcd.division( 0, 2) == 2)
assert(not pcall(gcd.division))
assert(not pcall(gcd.division, 0, 0))
assert(not pcall(gcd.division, -1, 5))
assert(not pcall(gcd.division, 10, 2.3))
end)
run('Testing gcd.substraction', function()
assert(gcd.substraction(10, 15) == 5)
assert(gcd.substraction(14, 7) == 7)
assert(gcd.substraction(12, 12) == 12)
assert(gcd.substraction( 7, 3) == 1)
assert(gcd.substraction( 5, 0) == 5)
assert(gcd.substraction( 0, 2) == 2)
assert(not pcall(gcd.substraction))
assert(not pcall(gcd.substraction, 0, 0))
assert(not pcall(gcd.substraction, -1, 5))
assert(not pcall(gcd.substraction, 10, 2.3))
end)
run('Testing gcd.recursive', function()
assert(gcd.recursive(10, 15) == 5)
assert(gcd.recursive(14, 7) == 7)
assert(gcd.recursive(12, 12) == 12)
assert(gcd.recursive( 7, 3) == 1)
assert(gcd.recursive( 5, 0) == 5)
assert(gcd.recursive( 0, 2) == 2)
assert(not pcall(gcd.recursive))
assert(not pcall(gcd.recursive, 0, 0))
assert(not pcall(gcd.recursive, -1, 5))
assert(not pcall(gcd.recursive, 10, 2.3))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
FFXIOrgins/FFXIOrgins | scripts/zones/Port_Bastok/npcs/Zoby_Quhyo.lua | 36 | 1693 | -----------------------------------
-- Area: Port Bastok
-- NPC: Zoby Quhyo
-- Only sells when Bastok controlls Elshimo Lowlands
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(ELSHIMOLOWLANDS);
if (RegionOwner ~= BASTOK) then
player:showText(npc,ZOBYQUHYO_CLOSED_DIALOG);
else
player:showText(npc,ZOBYQUHYO_OPEN_DIALOG);
stock = {
0x0272, 234, --Black Pepper
0x0264, 55, --Kazham Peppers
0x1150, 55, --Kazham Pineapple
0x0278, 110, --Kukuru Bean
0x1126, 36, --Mithran Tomato
0x0276, 88, --Ogre Pumpkin
0x0583, 1656 --Phalaenopsis
}
showShop(player,BASTOK,stock);
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 |
suchipi/pac3 | lua/pac3/editor/client/render_scores.lua | 1 | 1434 | local enable = CreateClientConVar("pac_show_profiling_info", 1, true, true)
local font = "pac_render_score"
surface.CreateFont(font, {font = "Arial", shadow = true, size = 14, antialias = false})
pace.RenderTimes = {} -- render times in seconds
timer.Create("pac_render_times", 0.1, 0, function()
if not pac.IsEnabled() then return end
for key, ply in pairs(player.GetHumans()) do
local data = pac.GetProfilingData(ply)
if data then
local renderTime = 0
-- events are "opaque" and "translucent"
-- WE DO NOT CALCULATE AN AVERAGE
for k,v in pairs(data.events) do
renderTime = renderTime + v.average_ms * 0.001
end
pace.RenderTimes[ply:EntIndex()] = renderTime
end
end
end)
hook.Add("HUDPaint", "pac_show_render_times", function()
if not pace.IsActive() or not pace.IsFocused() or not enable:GetBool() or pace.IsInBasicMode() then return end
for key, ply in pairs(player.GetHumans()) do
if ply == LocalPlayer() then continue end
local pos = ply:EyePos()
if pos:Distance(pac.EyePos) < 100 then
local pos = pos:ToScreen()
if pos.visible then
surface.SetFont(font)
surface.SetTextColor(255, 255, 255, 255)
local renderTime = pace.RenderTimes[ply:EntIndex()]
if renderTime then
surface.SetTextPos(pos.x, pos.y)
surface.DrawText(string.format("average render time : %.3f ms", renderTime * 1000))
end
end
end
end
end) | gpl-3.0 |
nehz/busted | busted/languages/ar.lua | 15 | 1757 | local s = require('say')
s:set_namespace('ar')
-- 'Pending: test.lua @ 12 \n description
s:set('output.pending', 'عالِق')
s:set('output.failure', 'فَشَل')
s:set('output.failure', 'نَجاح')
s:set('output.pending_plural', 'عالِق')
s:set('output.failure_plural', 'إخْفاقات')
s:set('output.success_plural', 'نَجاحات')
s:set('output.pending_zero', 'عالِق')
s:set('output.failure_zero', 'إخْفاقات')
s:set('output.success_zero', 'نَجاحات')
s:set('output.pending_single', 'عالِق')
s:set('output.failure_single', 'فَشَل')
s:set('output.success_single', 'نَجاح')
s:set('output.seconds', 'ثَوانٍ')
-- definitions following are not used within the 'say' namespace
return {
failure_messages = {
'فَشِلَت %d مِنْ الإِختِبارات',
'فَشِلَت إخْتِباراتُك',
'برمجيَّتُكَ ضَعيْفة، أنْصَحُكَ بالتَّقاعُد',
'تقع برمجيَّتُكَ في مَنطِقَةِ الخَطَر',
'أقترِحُ ألّا تَتَقَدَّم بالإختِبار، علَّ يبْقى الطابِقُ مَستوراَ',
'جَدَّتي، فِي أَثْناءِ نَومِها، تَكتبُ بَرمَجياتٍ أفْضلُ مِن هذه',
'يَوَدُّ ليْ مُساعَدَتُكْ، لَكِنّْ...'
},
success_messages = {
'رائِع! تَمَّ إجْتِيازُ جَميعُ الإختِباراتِ بِنَجاحٍ',
'قُل ما شِئت، لا أكتَرِث: busted شَهِدَ لي!',
'حَقَّ عَليْكَ الإفتِخار',
'نَجاحٌ مُبْهِر!',
'عَليكَ بالإحتِفال؛ نَجَحَت جَميعُ التَجارُب'
}
}
| mit |
sjznxd/lc-20130127 | 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
| apache-2.0 |
stackmachine/stackmachine.love | stackmachine/osx.lua | 2 | 2563 | require "love.timer"
local os = require "os"
local glove = require "stackmachine/glove"
local urllib = require "stackmachine/urllib"
local logging = require "stackmachine/logging"
local utils = require "stackmachine/utils"
local osx = {}
local logger = logging.new('update')
local function execute(command, msg)
local code = os.execute(command .. " > /dev/null 2>&1")
logger:info(command)
if code ~= 0 then
error(msg)
end
end
function osx.getApplicationPath(args)
local applicationPath = args[1]
-- Remove /Contents/MacOS/love from the working directory
local path = applicationPath:sub(0, -20)
if path:find(".app") then
return path
end
return ""
end
-- no op
function osx.cleanup()
for _, filename in ipairs(glove.filesystem.enumerate("updates")) do
if filename == "oldgame.app" then
love.timer.sleep(2)
end
end
local destination = love.filesystem.getSaveDirectory() .. "/updates"
execute(string.format("rm -rf \"%s\"", destination),
string.format("Error removing \"%s\"", destination))
end
function osx.getDownload(item)
for i, platform in ipairs(item.platforms) do
if platform.name == "macosx" then
return platform
end
end
return nil
end
function osx.replace(download, oldpath, args, callback)
glove.filesystem.mkdir("updates")
local destination = love.filesystem.getSaveDirectory() .. "/updates"
local zipfile = destination .. "/game_update_osx.zip"
local item = download.files[1]
urllib.retrieve(item.url, zipfile, item.length, callback)
callback(false, "Installing", 25)
execute(string.format("unzip -q -d \"%s\" \"%s\"", destination, zipfile),
string.format("Error unzipping %s", zipfile))
local newpath = nil
for _, filename in ipairs(glove.filesystem.enumerate("updates")) do
if utils.endswith(filename, ".app") then
newpath = destination .. "/" .. filename
end
end
if newpath == nil then
error("Could not find new app to download")
end
callback(false, "Installing", 50)
execute(string.format("mv \"%s\" \"%s\"", oldpath, destination .. "/oldgame.app"),
string.format("Error moving previous install %s", oldpath))
callback(false, "Installing", 75)
execute(string.format("mv \"%s\" \"%s\"", newpath, oldpath),
string.format("Error moving new app %s to %s", newpath, oldpath))
os.remove(zipfile)
callback(false, "Installing", 100)
execute(string.format("(sleep 1; open \"%s\") &", oldpath),
string.format("Can't open %s", oldpath))
end
return osx
| mit |
msburgess3200/PERP | gamemodes/perp/gamemode/cl_modules/calc_view.lua | 1 | 3871 |
function lookForVT ( Vehicle )
if (IsValid(Vehicle)) then
if (!Vehicle.vehicleTable) then
for k, v in pairs(VEHICLE_DATABASE) do
for _, PJ in pairs(v.PaintJobs) do
if (PJ.model == Vehicle:GetModel()) then
Vehicle.vehicleTable = v;
break;
end
end
if (Vehicle.vehicleTable) then break; end
end
end
end
return Vehicle.vehicleTable;
end
/*
hook.Add( "CalcView", "chairs.CalcView", function( pl, origin, angles, fov )
if !pl:InVehicle() then return end
if !
local view = {}
pl:SetNoDraw( true )
origin = pl:GetPos() + pl:GetUp() * 50
angles = (pl.sitview and vgui.CursorVisible()) and (pl.sitview-pl:EyePos()):Angle() or angles
view.angles = angles
view.origin = origin
view.fov = fov
return view
end )
*/
function GM:CalcView( ply, origin, angles, fov )
local Vehicle = ply:GetVehicle()
lookForVT(Vehicle);
local wep = ply:GetActiveWeapon()
if ( ValidEntity( Vehicle ) &&
(GetConVar("gmod_vehicle_viewmode"):GetInt() == 1)
/*&& ( !ValidEntity(wep) || !wep:IsWeaponVisible() )*/
) then
return GAMEMODE:CalcVehicleThirdPersonView( Vehicle, ply, origin*1, angles*1, fov )
end
local view = {}
view.origin = origin
view.angles = angles
if ply:InVehicle() then
if (Vehicle.vehicleTable && Vehicle.vehicleTable.ViewAdjustments_FirstPerson) then
if (Vehicle.vehicleTable.ViewAdjustments_FirstPerson == VIEW_LOCK) then
view.angles = ply:GetAimVector():Angle();
else
view.origin = origin +
(ply:GetVehicle():GetAngles():Up() * Vehicle.vehicleTable.ViewAdjustments_FirstPerson.z) +
(ply:GetVehicle():GetAngles():Forward() * Vehicle.vehicleTable.ViewAdjustments_FirstPerson.x) +
(ply:GetVehicle():GetAngles():Right() * Vehicle.vehicleTable.ViewAdjustments_FirstPerson.y);
end
end
end;
view.fov = fov
view.fov = fov
// Give the active weapon a go at changing the viewmodel position
if ( ValidEntity( wep ) ) then
local func = wep.GetViewModelPosition
if ( func ) then
view.vm_origin, view.vm_angles = func( wep, origin*1, angles*1 ) // Note: *1 to copy the object so the child function can't edit it.
end
local func = wep.CalcView
if ( func ) then
view.origin, view.angles, view.fov = func( wep, ply, origin*1, angles*1, fov ) // Note: *1 to copy the object so the child function can't edit it.
end
end
return view
end
function GM:CalcVehicleThirdPersonView( Vehicle, ply, origin, angles, fov )
local view = {}
if Vehicle.vehicleTable && Vehicle.vehicleTable.ViewAdjustments_FirstPerson && Vehicle.vehicleTable.ViewAdjustments_FirstPerson == VIEW_LOCK then
view.angles = ply:GetAimVector():Angle();
else
view.angles = angles;
end
view.fov = fov
if ( !Vehicle.CalcView ) then
Vehicle.CalcView = {}
// Try to work out the size
local min, max = Vehicle:WorldSpaceAABB()
local size = max - min
Vehicle.CalcView.OffsetUp = size.z
Vehicle.CalcView.OffsetOut = (size.x + size.y + size.z) * 0.33
end
// Offset the origin
local Up = view.angles:Up() * Vehicle.CalcView.OffsetUp * 0.66
local Offset = view.angles:Forward() * -Vehicle.CalcView.OffsetOut
if Vehicle.vehicleTable && Vehicle.vehicleTable.ViewAdjustments_ThirdPerson then
Up = Up + Vehicle.vehicleTable.ViewAdjustments_ThirdPerson;
end
// Trace back from the original eye position, so we don't clip through walls/objects
local TargetOrigin = Vehicle:GetPos() + Up + Offset
local distance = origin - TargetOrigin
local Filter = ents.FindByClass('prop_vehicle_prisoner_pod');
table.insert(Filter, Vehicle);
local trace = {
start = origin,
endpos = TargetOrigin,
filter = Filter
}
local tr = util.TraceLine( trace )
view.origin = origin + tr.Normal * (distance:Length() - 10) * tr.Fraction
return view
end | mit |
sjznxd/lc-20130127 | applications/luci-statistics/luasrc/statistics/datatree.lua | 77 | 4394 | --[[
Luci statistics - rrd data tree builder
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.statistics.datatree", package.seeall)
local util = require("luci.util")
local sys = require("luci.sys")
local fs = require("nixio.fs")
local uci = require("luci.model.uci").cursor()
local sections = uci:get_all("luci_statistics")
Instance = util.class()
function Instance.__init__( self, host )
self._host = host or sections.collectd.Hostname or sys.hostname()
self._libdir = sections.collectd.PluginDir or "/usr/lib/collectd"
self._rrddir = sections.collectd_rrdtool.DataDir or "/tmp/rrd"
self._libdir = self._libdir:gsub("/$","")
self._rrddir = self._rrddir:gsub("/$","")
self._plugins = { }
self:_scan()
end
function Instance._mkpath( self, plugin, pinstance )
local dir = self._rrddir .. "/" .. self._host
if type(plugin) == "string" and plugin:len() > 0 then
dir = dir .. "/" .. plugin
if type(pinstance) == "string" and pinstance:len() > 0 then
dir = dir .. "-" .. pinstance
end
end
return dir
end
function Instance._ls( self, ... )
local ditr = fs.dir(self:_mkpath(...))
if ditr then
local dirs = { }
while true do
local d = ditr()
if not d then break end
dirs[#dirs+1] = d
end
return dirs
end
end
function Instance._notzero( self, table )
for k in pairs(table) do
return true
end
return false
end
function Instance._scan( self )
local dirs = self:_ls()
if not dirs then
return
end
-- for i, plugin in ipairs( dirs ) do
-- if plugin:match("%w+.so") then
-- self._plugins[ plugin:gsub("%.so$", "") ] = { }
-- end
-- end
for _, dir in ipairs(dirs) do
if dir ~= "." and dir ~= ".." and
fs.stat(self:_mkpath(dir)).type == "dir"
then
local plugin = dir:gsub("%-.+$", "")
if not self._plugins[plugin] then
self._plugins[plugin] = { }
end
end
end
for plugin, instances in pairs( self._plugins ) do
local dirs = self:_ls()
if type(dirs) == "table" then
for i, dir in ipairs(dirs) do
if dir:find( plugin .. "%-" ) or dir == plugin then
local instance = ""
if dir ~= plugin then
instance = dir:gsub( plugin .. "%-", "", 1 )
end
instances[instance] = { }
end
end
end
for instance, data_instances in pairs( instances ) do
dirs = self:_ls(plugin, instance)
if type(dirs) == "table" then
for i, file in ipairs(dirs) do
if file:find("%.rrd") then
file = file:gsub("%.rrd","")
local data_type
local data_instance
if file:find("%-") then
data_type = file:gsub( "%-.+","" )
data_instance = file:gsub( "[^%-]-%-", "", 1 )
else
data_type = file
data_instance = ""
end
if not data_instances[data_type] then
data_instances[data_type] = { data_instance }
else
table.insert( data_instances[data_type], data_instance )
end
end
end
end
end
end
end
function Instance.plugins( self )
local rv = { }
for plugin, val in pairs( self._plugins ) do
if self:_notzero( val ) then
table.insert( rv, plugin )
end
end
return rv
end
function Instance.plugin_instances( self, plugin )
local rv = { }
for instance, val in pairs( self._plugins[plugin] ) do
table.insert( rv, instance )
end
return rv
end
function Instance.data_types( self, plugin, instance )
local rv = { }
local p = self._plugins[plugin]
if type(p) == "table" and type(p[instance]) == "table" then
for type, val in pairs(p[instance]) do
table.insert( rv, type )
end
end
return rv
end
function Instance.data_instances( self, plugin, instance, dtype )
local rv = { }
local p = self._plugins[plugin]
if type(p) == "table" and type(p[instance]) == "table" and type(p[instance][dtype]) == "table" then
for i, instance in ipairs(p[instance][dtype]) do
table.insert( rv, instance )
end
end
return rv
end
function Instance.host_instances( self )
local hosts_path = fs.glob(self._rrddir..'/*')
local hosts = { }
if hosts_path then
local path
for path in hosts_path do
hosts[#hosts+1] = fs.basename(path)
end
end
return hosts
end
| apache-2.0 |
zhouxiaoxiaoxujian/skynet | test/testrediscluster.lua | 19 | 3400 | local skynet = require "skynet"
local rediscluster = require "skynet.db.redis.cluster"
local test_more = ...
-- subscribe mode's callback
local function onmessage(data,channel,pchannel)
print("onmessage",data,channel,pchannel)
end
skynet.start(function ()
local db = rediscluster.new({
{host="127.0.0.1",port=7000},
{host="127.0.0.1",port=7001},},
{read_slave=true,auth=nil,db=0,},
onmessage
)
db:del("list")
db:del("map")
db:rpush("list",1,2,3)
local list = db:lrange("list",0,-1)
for i,v in ipairs(list) do
print(v)
end
db:hmset("map","key1",1,"key2",2)
local map = db:hgetall("map")
for i=1,#map,2 do
local key = map[i]
local val = map[i+1]
print(key,val)
end
-- test MOVED
db:flush_slots_cache()
print(db:set("A",1))
print(db:get("A"))
-- reconnect
local cnt = 0
for name,conn in pairs(db.connections) do
print(name,conn)
cnt = cnt + 1
end
print("cnt:",cnt)
db:close_all_connection()
print(db:set("A",1))
print(db:del("A"))
local slot = db:keyslot("{foo}")
local conn = db:get_connection_by_slot(slot)
-- You must ensure keys at one slot: use same key or hash tags
local ret = conn:pipeline({
{"hincrby", "{foo}hello", 1, 1},
{"del", "{foo}hello"},
{"hmset", "{foo}hello", 1, 1, 2, 2, 3, 3},
{"hgetall", "{foo}hello"},
},{})
print(ret[1].ok,ret[1].out)
print(ret[2].ok,ret[2].out)
print(ret[3].ok,ret[3].out)
print(ret[4].ok)
if ret[4].ok then
for i,v in ipairs(ret[4].out) do
print(v)
end
else
print(ret[4].out)
end
-- dbsize/info/keys
local conn = db:get_random_connection()
print("dbsize:",conn:dbsize())
print("info:",conn:info())
local keys = conn:keys("list*")
for i,key in ipairs(keys) do
print(key)
end
print("cluster nodes")
local nodes = db:cluster("nodes")
print(nodes)
print("cluster slots")
local slots = db:cluster("slots")
for i,slot_map in ipairs(slots) do
local start_slot = slot_map[1]
local end_slot = slot_map[2]
local master_node = slot_map[3]
print(start_slot,end_slot)
for i,v in ipairs(master_node) do
print(v)
end
for i=4,#slot_map do
local slave_node = slot_map[i]
for i,v in ipairs(slave_node) do
print(v)
end
end
end
-- test subscribe/publish
db:subscribe("world")
db:subscribe("myteam")
db:publish("world","hello,world")
db:publish("myteam","hello,my team")
-- low-version(such as 3.0.2) redis-server psubscribe is locally
-- if publish and psubscribe not map to same node,
-- we may lost message. so upgrade your redis or use tag to resolved!
db:psubscribe("{tag}*team")
db:publish("{tag}1team","hello,1team")
db:publish("{tag}2team","hello,2team")
-- i test in redis-4.0.9, it's ok
db:psubscribe("*team")
db:publish("1team","hello,1team")
db:publish("2team","hello,2team")
-- test eval
db:set("A",1)
local script = [[
if redis.call("get",KEYS[1]) == ARGV[1] then
return "ok"
else
return "fail"
end]]
print("eval#get",db:eval(script,1,"A",1))
db:del("A")
if not test_more then
skynet.exit()
return
end
local last = false
while not last do
last = db:get("__last__")
if last == nil then
last = 0
end
last = tonumber(last)
end
for val=last,1000000000 do
local ok,errmsg = pcall(function ()
local key = string.format("foo%s",val)
db:set(key,val)
print(key,db:get(key))
db:set("__last__",val)
end)
if not ok then
print("error:",errmsg)
end
end
skynet.exit()
end)
| mit |
ho3einkj/boti | plugins/anti_bot.lua | 65 | 3192 |
local function isBotAllowed (userId, chatId)
local hash = 'anti-bot:allowed:'..chatId..':'..userId
local banned = redis:get(hash)
return banned
end
local function allowBot (userId, chatId)
local hash = 'anti-bot:allowed:'..chatId..':'..userId
redis:set(hash, true)
end
local function disallowBot (userId, chatId)
local hash = 'anti-bot:allowed:'..chatId..':'..userId
redis:del(hash)
end
-- Is anti-bot enabled on chat
local function isAntiBotEnabled (chatId)
local hash = 'anti-bot:enabled:'..chatId
local enabled = redis:get(hash)
return enabled
end
local function enableAntiBot (chatId)
local hash = 'anti-bot:enabled:'..chatId
redis:set(hash, true)
end
local function disableAntiBot (chatId)
local hash = 'anti-bot:enabled:'..chatId
redis:del(hash)
end
local function isABot (user)
-- Flag its a bot 0001000000000000
local binFlagIsBot = 4096
local result = bit32.band(user.flags, binFlagIsBot)
return result == binFlagIsBot
end
local function kickUser(userId, chatId)
local chat = 'chat#id'..chatId
local user = 'user#id'..userId
chat_del_user(chat, user, function (data, success, result)
if success ~= 1 then
print('I can\'t kick '..data.user..' but should be kicked')
end
end, {chat=chat, user=user})
end
local function run (msg, matches)
-- We wont return text if is a service msg
if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then
if msg.to.type ~= 'chat' then
return 'Anti-flood works only on channels'
end
end
local chatId = msg.to.id
if matches[1] == 'enable' then
enableAntiBot(chatId)
return 'bot cant come group is safe'
end
if matches[1] == 'disable' then
disableAntiBot(chatId)
return 'bot can come group is NOT safe'
end
if matches[1] == 'allow' then
local userId = matches[2]
allowBot(userId, chatId)
return 'Bot '..userId..' allowed'
end
if matches[1] == 'disallow' then
local userId = matches[2]
disallowBot(userId, chatId)
return 'Bot '..userId..' disallowed'
end
if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then
local user = msg.action.user or msg.from
if isABot(user) then
print('It\'s a bot!')
if isAntiBotEnabled(chatId) then
print('Anti bot is enabled')
local userId = user.id
if not isBotAllowed(userId, chatId) then
kickUser(userId, chatId)
else
print('This bot is allowed')
end
end
end
end
end
return {
description = 'When bot enters group kick it.',
usage = {
'!antibot enable: Enable Anti-bot on current chat',
'!antibot disable: Disable Anti-bot on current chat',
'!antibot allow <botId>: Allow <botId> on this chat',
'!antibot disallow <botId>: Disallow <botId> on this chat'
},
patterns = {
'^!antibot (allow) (%d+)$',
'^!antibot (disallow) (%d+)$',
'^!antibot (enable)$',
'^!antibot (disable)$',
'^!!tgservice (chat_add_user)$',
'^!!tgservice (chat_add_user_link)$'
},
run = run
}
--Copyright; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
msburgess3200/PERP | gamemodes/perp/gamemode/vehicles/Old Cars/shelby.lua | 1 | 3057 | ///////////////////////////////
// © 2009-2010 Pulsar Effect //
// All rights reserved //
///////////////////////////////
// This material may not be //
// reproduced, displayed, //
// modified or distributed //
// without the express prior //
// written permission of the //
// the copyright holder. //
///////////////////////////////
VEHICLE = {};
VEHICLE.ID = 'm';
VEHICLE.FID = '13';
VEHICLE.Name = "Shelby";
VEHICLE.Make = "Ford";
VEHICLE.Model = "Shelby Mustang";
VEHICLE.Script = "shelby";
VEHICLE.Cost = 105000;
VEHICLE.PaintJobCost = 6500;
VEHICLE.DF = true;
VEHICLE.CustomBodyGroup = 511;
VEHICLE.PaintJobs = {
{model = 'models/shelby/shelby.mdl', skin = '0', name = 'White', color = Color(248, 251, 232, 255)},
{model = 'models/shelby/shelby.mdl', skin = '1', name = 'Red', color = Color(205, 0, 0, 255)},
{model = 'models/shelby/shelby.mdl', skin = '2', name = 'Blue', color = Color(0, 9, 123, 255)},
{model = 'models/shelby/shelby.mdl', skin = '3', name = 'Silver', color = Color(125, 128, 125, 255)},
{model = 'models/shelby/shelby.mdl', skin = '4', name = 'Orange', color = Color(235, 100, 32, 255)},
{model = 'models/shelby/shelby.mdl', skin = '5', name = 'Sky Blue', color = Color(0, 188, 235, 255)},
{model = 'models/shelby/shelby.mdl', skin = '6', name = 'Green', color = Color(0, 88, 36, 255)},
{model = 'models/shelby/shelby.mdl', skin = '7', name = 'Black', color = Color(0, 0, 0, 255)},
{model = 'models/shelby/shelby.mdl', skin = '8', name = 'Brown', color = Color(136, 97, 53, 255)},
{model = 'models/shelby/shelby.mdl', skin = '9', name = 'Purple', color = Color(67, 12, 96, 255)},
{model = 'models/shelby/shelby.mdl', skin = '10', name = 'Pink', color = Color(255, 0, 234, 255)},
};
VEHICLE.PassengerSeats = {
{Vector(16, 4, 13), Angle(0, 0, 10)},
};
VEHICLE.ExitPoints = {
Vector(-72.3996, -6.1857, 1.8621),
Vector(72.3996, -0.1439, 0.3239),
};
VEHICLE.DefaultIceFriction = .5;
VEHICLE.PlayerReposition_Pos = Vector(-16, -15, 18);
VEHICLE.PlayerReposition_Ang = Angle(0, 90, 0);
VEHICLE.ViewAdjustments_FirstPerson = Vector(0, 0, 5);
VEHICLE.ViewAdjustments_ThirdPerson = nil;
VEHICLE.RequiredClass = nil;
VEHICLE.PaintText = "Of course! The great American classic.";
VEHICLE.HornNoise = NORMAL_HORNS;
VEHICLE.HeadlightPositions = {
{Vector(-31.4999, 98.5857, 31.4159), Angle(20, 0, 0)};
{Vector(31.4999, 98.5857, 31.4159), Angle(20, 0, 0)};
};
VEHICLE.TaillightPositions = {
{Vector(18.6511, -92.8365, 31.6970), Angle(20, -180, 0)};
{Vector(-18.6511, -92.8365, 31.6970), Angle(20, -180, 0)};
};
VEHICLE.UnderglowPositions = {
{Vector(0, 35, 5)};
{Vector(0, -35, 5)};
};
VEHICLE.RevvingSound = "vehicles/shelby/shelby_rev_short_loop1.wav";
VEHICLE.SpinoutSound = "vehicles/golf/skid_highfriction.wav";
GM:RegisterVehicle(VEHICLE); | mit |
Mogara/QSanguosha | lang/zh_CN/Audio/StandardWuLines.lua | 6 | 3047 |
return {
-- 孙权
["$zhiheng1"] = "容我三思。",
["$zhiheng2"] = "且慢。",
["$jiuyuan1"] = "有汝辅佐,甚好!",
["$jiuyuan2"] = "好舒服啊。",
["~sunquan"] = "父亲,大哥,仲谋愧矣……",
-- 甘宁
["$qixi1"] = "接招吧!",
["$qixi2"] = "你的牌太多了!",
["~ganning"] = "二十年后,又是一条好汉!",
-- 吕蒙
["$keji1"] = "不是不报,时候未到!",
["$keji2"] = "留得青山在,不怕没柴烧!",
["~lvmeng"] = "被看穿了吗?",
-- 黄盖
["$kurou1"] = "请鞭笞我吧 ,公瑾!",
["$kurou2"] = "赴汤蹈火,在所不辞!",
["~huanggai"] = "失血过多了……",
-- 周瑜
["$yingzi_zhouyu1"] = "哈哈哈哈……",
["$yingzi_zhouyu2"] = "汝等看好了!",
["$fanjian1"] = "挣扎吧,在血和暗的深渊里!",
["$fanjian2"] = "痛苦吧,在仇与恨的地狱中!",
["~zhouyu"] = "既生瑜,何生……",
-- 大乔
["$guose1"] = "请休息吧。",
["$guose2"] = "你累了。",
["$liuli1"] = "交给你了。",
["$liuli2"] = "你来嘛~",
["~daqiao"] = "伯符,我去了……",
-- 陆逊
["$qianxun1"] = "儒生脱尘,不为贪逸淫乐之事。",
["$qianxun2"] = "谦谦君子,不饮盗泉之水。",
["$duoshi2"] = "国之大计审视为先。", -- 仅自己
["$duoshi1"] = "以今日之大势当行此计。",
["~luxun"] = "还以为我已经不再年轻……",
-- 孙尚香
["$jieyin1"] = "夫君,身体要紧。",
["$jieyin2"] = "他好,我也好。",
["$xiaoji1"] = "哼!",
["$xiaoji2"] = "看我的厉害!",
["~sunshangxiang"] = "不!还不可以死!",
-- 小乔
["$tianxiang1"] = "接着哦~",
["$tianxiang2"] = "替我挡着~",
["$hongyan"] = "哼哼~~",
["~xiaoqiao"] = "公瑾…我先走一步……",
-- 周泰
["$buqu1"] = "我绝不会倒下!",
["$buqu2"] = "还不够!",
["~zhoutai"] = "已经尽力了……",
["$tianyi1"] = "我当要替天行道。",
["$tianyi2"] = "请助我一臂之力!",
["~taishici"] = "大丈夫,当带三尺之剑,立不世之功!",
["$yinghun_sunjian1"] = "以吾魂魄,保佑吾儿之基业。",
["$yinghun_sunjian2"] = "不诛此贼三族,则吾死不瞑目!",
["~sunjian"] = "有埋伏!呃……啊!!",
["$haoshi1"] = "拿去拿去,莫跟哥哥客气。",
["$haoshi2"] = "来来来,见面分一半。",
["$dimeng1"] = "以和为贵,以和为贵。",
["$dimeng2"] = "合纵连横,方能以弱胜强。",
["~lusu"] = "此联盟已破,吴蜀休矣。",
["$zhijian1"] = "请恕老臣直言。",
["$zhijian2"] = "为臣者,当冒死以谏!",
["$guzheng1"] = "今当稳固内政,以御外患!",
["$guzheng2"] = "固国安邦,须当如是!",
["~erzhang"] = "竭力尽智,死而无憾。",
-- 丁奉
["$duanbing1"] = "众将官,短刀出鞘。",
["$duanbing2"] = "短兵轻甲也可取汝性命!",
["$fenxun1"] = "取封侯爵赏,正在今日!",
["$fenxun2"] = "给我拉过来!",
["~dingfeng"] = "这风,太冷了……",
} | gpl-3.0 |
psycho-nico/openwrt-packages | net/smartsnmpd/files/mibs/interfaces.lua | 158 | 4833 | --
-- This file is part of SmartSNMP
-- Copyright (C) 2014, Credo Semiconductor Inc.
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License along
-- with this program; if not, write to the Free Software Foundation, Inc.,
-- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
--
local mib = require "smartsnmp"
require "ubus"
require "uloop"
uloop.init()
local conn = ubus.connect()
if not conn then
error("Failed to connect to ubusd")
end
local if_cache = {}
local if_status_cache = {}
local if_index_cache = {}
local last_load_time = os.time()
local function need_to_reload()
if os.time() - last_load_time >= 3 then
last_load_time = os.time()
return true
else
return false
end
end
local function load_config()
if need_to_reload() == true then
if_cache = {}
if_status_cache = {}
if_index_cache = {}
-- if description
for k, v in pairs(conn:call("network.device", "status", {})) do
if_status_cache[k] = {}
end
for name_ in pairs(if_status_cache) do
for k, v in pairs(conn:call("network.device", "status", { name = name_ })) do
if k == 'mtu' then
if_status_cache[name_].mtu = v
elseif k == 'macaddr' then
if_status_cache[name_].macaddr = v
elseif k == 'up' then
if v == true then
if_status_cache[name_].up = 1
else
if_status_cache[name_].up = 2
end
elseif k == 'statistics' then
for item, stat in pairs(v) do
if item == 'rx_bytes' then
if_status_cache[name_].in_octet = stat
elseif item == 'tx_bytes' then
if_status_cache[name_].out_octet = stat
elseif item == 'rx_errors' then
if_status_cache[name_].in_errors = stat
elseif item == 'tx_errors' then
if_status_cache[name_].out_errors = stat
elseif item == 'rx_dropped' then
if_status_cache[name_].in_discards = stat
elseif item == 'tx_dropped' then
if_status_cache[name_].out_discards = stat
end
end
end
end
end
if_cache['desc'] = {}
for name, status in pairs(if_status_cache) do
table.insert(if_cache['desc'], name)
for k, v in pairs(status) do
if if_cache[k] == nil then if_cache[k] = {} end
table.insert(if_cache[k], v)
end
end
-- if index
for i in ipairs(if_cache['desc']) do
table.insert(if_index_cache, i)
end
end
end
mib.module_methods.or_table_reg("1.3.6.1.2.1.2", "The MIB module for managing Interfaces implementations")
local ifGroup = {
[1] = mib.ConstInt(function () load_config() return #if_index_cache end),
[2] = {
[1] = {
[1] = mib.ConstIndex(function () load_config() return if_index_cache end),
[2] = mib.ConstString(function (i) load_config() return if_cache['desc'][i] end),
[4] = mib.ConstInt(function (i) load_config() return if_cache['mtu'][i] end),
[6] = mib.ConstString(function (i) load_config() return if_cache['macaddr'][i] end),
[8] = mib.ConstInt(function (i) load_config() return if_cache['up'][i] end),
[10] = mib.ConstCount(function (i) load_config() return if_cache['in_octet'][i] end),
[13] = mib.ConstCount(function (i) load_config() return if_cache['in_discards'][i] end),
[14] = mib.ConstCount(function (i) load_config() return if_cache['in_errors'][i] end),
[16] = mib.ConstCount(function (i) load_config() return if_cache['out_octet'][i] end),
[19] = mib.ConstCount(function (i) load_config() return if_cache['out_discards'][i] end),
[20] = mib.ConstCount(function (i) load_config() return if_cache['out_errors'][i] end),
}
}
}
return ifGroup
| gpl-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Southern_San_dOria/npcs/Exoroche.lua | 7 | 2503 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Exoroche
-- Involved in Quests: Father and Son, A Boy's Dream
-- @zone 230
-- @pos 72 -1 60
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- player:startEvent(0x004f) -- how the paper works -- under oath
-- player:startEvent(0x0033) -- it says what i dont beleive you -- under oath
-- player:startEvent(0x0013) -- thanks for your help i have to tell trion -- under oath
-- player:startEvent(0x004d) -- a boys dream
-- "Father and Son" Event Dialogs
if(player:getQuestStatus(SANDORIA,FATHER_AND_SON) == QUEST_ACCEPTED) then
player:startEvent(0x021e);
elseif(player:getVar("aBoysDreamCS") == 2) then
player:startEvent(0x0032);
elseif(player:getVar("aBoysDreamCS") >= 7) then
player:startEvent(0x0020);
else
player:startEvent(0x004c);
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 == 0x021e) then
player:setVar("QuestfatherAndSonVar",1);
elseif(csid == 0x0032) then
player:setVar("aBoysDreamCS",3);
elseif(csid == 0x0020 and player:getVar("aBoysDreamCS") == 7) then
player:setVar("aBoysDreamCS",8);
end
end;
------- used in expansions
-- player:startEvent(0x03b2) -- you want to hear of my father go talk to albieche
-- player:startEvent(0x03b3) -- trainees spectacles | gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/globals/weaponskills/weapon_break.lua | 6 | 1674 | -----------------------------------
-- Weapon Break
-- Great Axe weapon skill
-- Skill level: 175
-- Lowers enemy's attack. Duration of effect varies with TP.
-- Lowers attack by as much as 25% if unresisted.
-- Strong against: Manticores, Orcs, Rabbits, Raptors, Sheep.
-- Immune: Crabs, Crawlers, Funguars, Quadavs, Pugils, Sahagin, Scorpion.
-- Will stack with Sneak Attack.
-- Aligned with the Thunder Gorget.
-- Aligned with the Thunder Belt.
-- Element: Water
-- Modifiers: STR:32% ; VIT:32%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.32; params.dex_wsc = 0.0; params.vit_wsc = 0.32; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if damage > 0 then
local tp = player:getTP();
local duration = (tp/100 * 60) + 120;
if(target:hasStatusEffect(EFFECT_ATTACK_DOWN) == false) then
target:addStatusEffect(EFFECT_ATTACK_DOWN, 25, 0, duration);
end
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
KnightTeam/Knight | plugins/supergroup.lua | 3 | 75853 | --Begin supergrpup.lua
--Check members #Add supergroup
local function check_member_super(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
if type(result) == 'boolean' then
print('This is a old message!')
return reply_msg(msg.id, '[Not supported] This is a old message!', ok_cb, false)
end
if success == 0 then
send_large_msg(receiver, "Promote me to admin first!")
end
for k,v in pairs(result) do
local member_id = v.peer_id
if member_id ~= our_id then
-- SuperGroup configuration
data[tostring(msg.to.id)] = {
group_type = 'SuperGroup',
long_id = msg.to.peer_id,
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.title, '_', ' '),
lock_arabic = 'no',
lock_link = "no",
flood = 'yes',
lock_spam = 'yes',
lock_sticker = 'no',
member = 'no',
public = 'no',
lock_rtl = 'no',
lock_tgservice = 'yes',
lock_contacts = 'no',
strict = 'no'
}
}
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)
local text = 'SuperGroup has been added!'
return reply_msg(msg.id, text, ok_cb, false)
end
end
end
--Check Members #rem supergroup
local function check_member_superrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
if type(result) == 'boolean' then
print('This is a old message!')
return reply_msg(msg.id, '[Not supported] This is a old message!', ok_cb, false)
end
for k,v in pairs(result) 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)
local text = 'SuperGroup has been removed'
return reply_msg(msg.id, text, ok_cb, false)
end
end
end
--Function to Add supergroup
local function superadd(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg})
end
--Function to remove supergroup
local function superrem(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg})
end
--Get and output admins and bots in supergroup
local function callback(cb_extra, success, result)
local i = 1
local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ")
local member_type = cb_extra.member_type
local text = member_type.." for "..chat_name..":\n"
for k,v in pairsByKeys(result) do
if not v.first_name then
name = " "
else
vname = v.first_name:gsub("", "")
name = vname:gsub("_", " ")
end
text = text.."\n"..i.." - "..name.."["..v.peer_id.."]"
i = i + 1
end
send_large_msg(cb_extra.receiver, text)
end
local function callback_clean_bots (extra, success, result)
local msg = extra.msg
local receiver = 'channel#id'..msg.to.id
local channel_id = msg.to.id
for k,v in pairs(result) do
local bot_id = v.peer_id
kick_user(bot_id,channel_id)
end
end
--Get and output info about supergroup
local function callback_info(cb_extra, success, result)
local title ="Info for SuperGroup: ["..result.title.."]\n\n"
local admin_num = "Admin count: "..result.admins_count.."\n"
local user_num = "User count: "..result.participants_count.."\n"
local kicked_num = "Kicked user count: "..result.kicked_count.."\n"
local channel_id = "ID: "..result.peer_id.."\n"
if result.username then
channel_username = "Username: @"..result.username
else
channel_username = ""
end
local text = title..admin_num..user_num..kicked_num..channel_id..channel_username
send_large_msg(cb_extra.receiver, text)
end
--Get and output members of supergroup
local function callback_who(cb_extra, success, result)
local text = "Members for "..cb_extra.receiver
local i = 1
for k,v in pairsByKeys(result) do
if not v.print_name then
name = " "
else
vname = v.print_name:gsub("", "")
name = vname:gsub("_", " ")
end
if v.username then
username = " @"..v.username
else
username = ""
end
text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n"
--text = text.."\n"..username
i = i + 1
end
local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w")
file:write(text)
file:flush()
file:close()
send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false)
post_msg(cb_extra.receiver, text, ok_cb, false)
end
--Get and output list of kicked users for supergroup
local function callback_kicked(cb_extra, success, result)
--vardump(result)
local text = "Kicked Members for SuperGroup "..cb_extra.receiver.."\n\n"
local i = 1
for k,v in pairsByKeys(result) do
if not v.print_name then
name = " "
else
vname = v.print_name:gsub("", "")
name = vname:gsub("_", " ")
end
if v.username then
name = name.." @"..v.username
end
text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n"
i = i + 1
end
local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w")
file:write(text)
file:flush()
file:close()
send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false)
--send_large_msg(cb_extra.receiver, text)
end
--Begin supergroup locks
local function lock_group_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'Link posting is already locked'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return 'Link posting has been locked'
end
end
local function unlock_group_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'Link posting is not locked'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'Link posting has been unlocked'
end
end
local function lock_group_spam(msg, data, target)
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Owners only!"
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'yes' then
return 'SuperGroup spam is already locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'yes'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been locked'
end
end
local function unlock_group_spam(msg, data, target)
if not is_momod(msg) then
return
end
local group_spam_lock = data[tostring(target)]['settings']['lock_spam']
if group_spam_lock == 'no' then
return 'SuperGroup spam is not locked'
else
data[tostring(target)]['settings']['lock_spam'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup spam has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_momod(msg) then
return
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Flood is already locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_momod(msg) then
return
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Flood has been unlocked'
end
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return
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
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic/Persian is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic/Persian has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'SuperGroup members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'SuperGroup members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'SuperGroup members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'SuperGroup members has been unlocked'
end
end
local function lock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return 'RTL is already locked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'RTL has been locked'
end
end
local function unlock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return 'RTL is already unlocked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'RTL has been unlocked'
end
end
local function lock_group_tgservice(msg, data, target)
if not is_momod(msg) then
return
end
local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice']
if group_tgservice_lock == 'yes' then
return 'Tgservice is already locked'
else
data[tostring(target)]['settings']['lock_tgservice'] = 'yes'
save_data(_config.moderation.data, data)
return 'Tgservice has been locked'
end
end
local function unlock_group_tgservice(msg, data, target)
if not is_momod(msg) then
return
end
local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice']
if group_tgservice_lock == 'no' then
return 'TgService Is Not Locked!'
else
data[tostring(target)]['settings']['lock_tgservice'] = 'no'
save_data(_config.moderation.data, data)
return 'Tgservice has been unlocked'
end
end
local function lock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'Sticker posting is already locked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'Sticker posting has been locked'
end
end
local function unlock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'Sticker posting is already unlocked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'Sticker posting has been unlocked'
end
end
local function lock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'yes' then
return 'Contact posting is already locked'
else
data[tostring(target)]['settings']['lock_contacts'] = 'yes'
save_data(_config.moderation.data, data)
return 'Contact posting has been locked'
end
end
local function unlock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'no' then
return 'Contact posting is already unlocked'
else
data[tostring(target)]['settings']['lock_contacts'] = 'no'
save_data(_config.moderation.data, data)
return 'Contact posting has been unlocked'
end
end
local function enable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_strict_lock = data[tostring(target)]['settings']['strict']
if group_strict_lock == 'yes' then
return 'Settings are already strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'yes'
save_data(_config.moderation.data, data)
return 'Settings will be strictly enforced'
end
end
local function disable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_strict_lock = data[tostring(target)]['settings']['strict']
if group_strict_lock == 'no' then
return 'Settings are not strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'no'
save_data(_config.moderation.data, data)
return 'Settings will not be strictly enforced'
end
end
--End supergroup locks
--'Set supergroup rules' function
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'SuperGroup rules set'
end
--'Get supergroup rules' function
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 group_name = data[tostring(msg.to.id)]['settings']['set_name']
local rules = group_name..' rules:\n\n'..rules:gsub("/n", " ")
return rules
end
--Set supergroup to public or not public function
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_public_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
if group_public_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'SuperGroup is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return
end
local group_public_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
if group_public_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
data[tostring(target)]['long_id'] = msg.to.long_id
save_data(_config.moderation.data, data)
return 'SuperGroup is now: not public'
end
end
--Show supergroup settings; function
function show_supergroup_settingsmod(msg, target)
if not is_momod(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['public'] then
data[tostring(target)]['settings']['public'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_rtl'] then
data[tostring(target)]['settings']['lock_rtl'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_tgservice'] then
data[tostring(target)]['settings']['lock_tgservice'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_member'] then
data[tostring(target)]['settings']['lock_member'] = 'no'
end
end
local settings = data[tostring(target)]['settings']
local text = "SuperGroup settings:\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nFlood sensitivity : "..NUM_MSG_MAX.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock Tgservice : "..settings.lock_tgservice.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict
return text
end
local function promote_admin(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
local member_tag_username = string.gsub(member_username, '@', '(at)')
if not data[group] then
return
end
if data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(user_id)] = member_tag_username
save_data(_config.moderation.data, data)
end
local function demote_admin(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
if not data[group] then
return
end
if not data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_tag_username..' is not a moderator.')
end
data[group]['moderators'][tostring(user_id)] = nil
save_data(_config.moderation.data, data)
end
local function promote2(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
local member_tag_username = string.gsub(member_username, '@', '(at)')
if not data[group] then
return send_large_msg(receiver, 'SuperGroup is not added.')
end
if data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(user_id)] = member_tag_username
save_data(_config.moderation.data, data)
send_large_msg(receiver, member_username..' has been promoted.')
end
local function demote2(receiver, member_username, user_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'channel#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(user_id)] then
return send_large_msg(receiver, member_tag_username..' is not a moderator.')
end
data[group]['moderators'][tostring(user_id)] = nil
save_data(_config.moderation.data, data)
send_large_msg(receiver, member_username..' has been demoted.')
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 'SuperGroup is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then
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
-- Start by reply actions
function get_message_callback(extra, success, result)
local get_cmd = extra.get_cmd
local msg = extra.msg
local data = load_data(_config.moderation.data)
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
if type(result) == 'boolean' then
print('This is a old message!')
return
end
if get_cmd == "id" and not result.action then
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]")
id1 = send_large_msg(channel, result.from.peer_id)
elseif get_cmd == 'id' and result.action then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
else
user_id = result.peer_id
end
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]")
id1 = send_large_msg(channel, user_id)
end
elseif get_cmd == "idfrom" then
local channel = 'channel#id'..result.to.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]")
id2 = send_large_msg(channel, result.fwd_from.peer_id)
elseif get_cmd == 'channel_block' and not result.action then
local member_id = result.from.peer_id
local channel_id = result.to.peer_id
if member_id == msg.from.id then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
--savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply")
kick_user(member_id, channel_id)
elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then
local user_id = result.action.user.peer_id
local channel_id = result.to.peer_id
if member_id == msg.from.id then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.")
kick_user(user_id, channel_id)
elseif get_cmd == "del" then
delete_msg(result.id, ok_cb, false)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply")
elseif get_cmd == "setadmin" then
local user_id = result.from.peer_id
local channel_id = "channel#id"..result.to.peer_id
channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false)
if result.from.username then
text = "@"..result.from.username.." set as an admin"
else
text = "[ "..user_id.." ]set as an admin"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply")
send_large_msg(channel_id, text)
elseif get_cmd == "demoteadmin" then
local user_id = result.from.peer_id
local channel_id = "channel#id"..result.to.peer_id
if is_admin2(result.from.peer_id) then
return send_large_msg(channel_id, "You can't demote global admins!")
end
channel_demote(channel_id, "user#id"..user_id, ok_cb, false)
if result.from.username then
text = "@"..result.from.username.." has been demoted from admin"
else
text = "[ "..user_id.." ] has been demoted from admin"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply")
send_large_msg(channel_id, text)
elseif get_cmd == "setowner" then
local group_owner = data[tostring(result.to.peer_id)]['set_owner']
if group_owner then
local channel_id = 'channel#id'..result.to.peer_id
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(channel_id, user, ok_cb, false)
end
local user_id = "user#id"..result.from.peer_id
channel_set_admin(channel_id, user_id, ok_cb, false)
data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply")
if result.from.username then
text = "@"..result.from.username.." [ "..result.from.peer_id.." ] added as owner"
else
text = "[ "..result.from.peer_id.." ] added as owner"
end
send_large_msg(channel_id, text)
end
elseif get_cmd == "promote" then
local receiver = result.to.peer_id
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
local member_name = full_name:gsub("", "")
local member_username = member_name:gsub("_", " ")
if result.from.username then
member_username = '@'.. result.from.username
end
local member_id = result.from.peer_id
if result.to.peer_type == 'channel' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply")
promote2("channel#id"..result.to.peer_id, member_username, member_id)
--channel_set_mod(channel_id, user, ok_cb, false)
end
elseif get_cmd == "demote" then
local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '')
local member_name = full_name:gsub("", "")
local member_username = member_name:gsub("_", " ")
if result.from.username then
member_username = '@'.. result.from.username
end
local member_id = result.from.peer_id
--local user = "user#id"..result.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted mod: @"..member_username.."["..user_id.."] by reply")
demote2("channel#id"..result.to.peer_id, member_username, member_id)
--channel_demote(channel_id, user, ok_cb, false)
elseif get_cmd == 'mute_user' then
if result.service then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
end
end
if action == 'chat_add_user_link' then
if result.from then
user_id = result.from.peer_id
end
end
else
user_id = result.from.peer_id
end
local receiver = extra.receiver
local chat_id = msg.to.id
print(user_id)
print(chat_id)
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, "["..user_id.."] removed from the muted user list")
elseif is_admin1(msg) then
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] added to the muted user list")
end
end
end
-- End by reply actions
--By ID actions
local function cb_user_info(extra, success, result)
local receiver = extra.receiver
local user_id = result.peer_id
local get_cmd = extra.get_cmd
local data = load_data(_config.moderation.data)
--[[if get_cmd == "setadmin" then
local user_id = "user#id"..result.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been set as an admin"
else
text = "[ "..result.peer_id.." ] has been set as an admin"
end
send_large_msg(receiver, text)]]
if get_cmd == "demoteadmin" then
if is_admin2(result.peer_id) then
return send_large_msg(receiver, "You can't demote global admins!")
end
local user_id = "user#id"..result.peer_id
channel_demote(receiver, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been demoted from admin"
send_large_msg(receiver, text)
else
text = "[ "..result.peer_id.." ] has been demoted from admin"
send_large_msg(receiver, text)
end
elseif get_cmd == "promote" then
if result.username then
member_username = "@"..result.username
else
member_username = string.gsub(result.print_name, '_', ' ')
end
promote2(receiver, member_username, user_id)
elseif get_cmd == "demote" then
if result.username then
member_username = "@"..result.username
else
member_username = string.gsub(result.print_name, '_', ' ')
end
demote2(receiver, member_username, user_id)
end
end
-- Begin resolve username actions
local function callbackres(extra, success, result)
local member_id = result.peer_id
local member_username = "@"..result.username
local get_cmd = extra.get_cmd
if get_cmd == "res" then
local user = result.peer_id
local name = string.gsub(result.print_name, "_", " ")
local channel = 'channel#id'..extra.channelid
send_large_msg(channel, user..'\n'..name)
return user
elseif get_cmd == "id" then
local user = result.peer_id
local channel = 'channel#id'..extra.channelid
send_large_msg(channel, user)
return user
elseif get_cmd == "invite" then
local receiver = extra.channel
local user_id = "user#id"..result.peer_id
channel_invite(receiver, user_id, ok_cb, false)
--[[elseif get_cmd == "channel_block" then
local user_id = result.peer_id
local channel_id = extra.channelid
local sender = extra.sender
if member_id == sender then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(member_id, channel_id) and not is_admin2(sender) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(member_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
kick_user(user_id, channel_id)
elseif get_cmd == "setadmin" then
local user_id = "user#id"..result.peer_id
local channel_id = extra.channel
channel_set_admin(channel_id, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been set as an admin"
send_large_msg(channel_id, text)
else
text = "@"..result.peer_id.." has been set as an admin"
send_large_msg(channel_id, text)
end
elseif get_cmd == "setowner" then
local receiver = extra.channel
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = extra.from_id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
local user = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_demote(receiver, user, ok_cb, false)
end
local user_id = "user#id"..result.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
data[tostring(channel)]['set_owner'] = tostring(result.peer_id)
save_data(_config.moderation.data, data)
savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username")
if result.username then
text = member_username.." [ "..result.peer_id.." ] added as owner"
else
text = "[ "..result.peer_id.." ] added as owner"
end
send_large_msg(receiver, text)
end]]
elseif get_cmd == "promote" then
local receiver = extra.channel
local user_id = result.peer_id
--local user = "user#id"..result.peer_id
promote2(receiver, member_username, user_id)
--channel_set_mod(receiver, user, ok_cb, false)
elseif get_cmd == "demote" then
local receiver = extra.channel
local user_id = result.peer_id
local user = "user#id"..result.peer_id
demote2(receiver, member_username, user_id)
elseif get_cmd == "demoteadmin" then
local user_id = "user#id"..result.peer_id
local channel_id = extra.channel
if is_admin2(result.peer_id) then
return send_large_msg(channel_id, "You can't demote global admins!")
end
channel_demote(channel_id, user_id, ok_cb, false)
if result.username then
text = "@"..result.username.." has been demoted from admin"
send_large_msg(channel_id, text)
else
text = "@"..result.peer_id.." has been demoted from admin"
send_large_msg(channel_id, text)
end
local receiver = extra.channel
local user_id = result.peer_id
demote_admin(receiver, member_username, user_id)
elseif get_cmd == 'mute_user' then
local user_id = result.peer_id
local receiver = extra.receiver
local chat_id = string.gsub(receiver, 'channel#id', '')
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] removed from muted user list")
elseif is_owner(extra.msg) then
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] added to muted user list")
end
end
end
--End resolve username actions
--Begin non-channel_invite username actions
local function in_channel_cb(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local msg = cb_extra.msg
local data = load_data(_config.moderation.data)
local print_name = user_print_name(cb_extra.msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
local member = cb_extra.username
local memberid = cb_extra.user_id
if member then
text = 'No user @'..member..' in this SuperGroup.'
else
text = 'No user ['..memberid..'] in this SuperGroup.'
end
if get_cmd == "channel_block" then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local user_id = v.peer_id
local channel_id = cb_extra.msg.to.id
local sender = cb_extra.msg.from.id
if user_id == sender then
return send_large_msg("channel#id"..channel_id, "Leave using kickme command")
end
if is_momod2(user_id, channel_id) and not is_admin2(sender) then
return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins")
end
if is_admin2(user_id) then
return send_large_msg("channel#id"..channel_id, "You can't kick other admins")
end
if v.username then
text = ""
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]")
else
text = ""
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]")
end
kick_user(user_id, channel_id)
return
end
end
elseif get_cmd == "setadmin" then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local user_id = "user#id"..v.peer_id
local channel_id = "channel#id"..cb_extra.msg.to.id
channel_set_admin(channel_id, user_id, ok_cb, false)
if v.username then
text = "@"..v.username.." ["..v.peer_id.."] has been set as an admin"
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]")
else
text = "["..v.peer_id.."] has been set as an admin"
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id)
end
if v.username then
member_username = "@"..v.username
else
member_username = string.gsub(v.print_name, '_', ' ')
end
local receiver = channel_id
local user_id = v.peer_id
promote_admin(receiver, member_username, user_id)
end
send_large_msg(channel_id, text)
return
end
elseif get_cmd == 'setowner' then
for k,v in pairs(result) do
vusername = v.username
vpeer_id = tostring(v.peer_id)
if vusername == member or vpeer_id == memberid then
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = cb_extra.msg.from.id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(receiver, user, ok_cb, false)
end
local user_id = "user#id"..v.peer_id
channel_set_admin(receiver, user_id, ok_cb, false)
data[tostring(channel)]['set_owner'] = tostring(v.peer_id)
save_data(_config.moderation.data, data)
savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username")
if result.username then
text = member_username.." ["..v.peer_id.."] added as owner"
else
text = "["..v.peer_id.."] added as owner"
end
end
elseif memberid and vusername ~= member and vpeer_id ~= memberid then
local channel = string.gsub(receiver, 'channel#id', '')
local from_id = cb_extra.msg.from.id
local group_owner = data[tostring(channel)]['set_owner']
if group_owner then
if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then
local user = "user#id"..group_owner
channel_demote(receiver, user, ok_cb, false)
end
data[tostring(channel)]['set_owner'] = tostring(memberid)
save_data(_config.moderation.data, data)
savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username")
text = "["..memberid.."] added as owner"
end
end
end
end
send_large_msg(receiver, text)
end
--End non-channel_invite username actions
--'Set supergroup photo' function
local function set_supergroup_photo(msg, success, result)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return
end
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
channel_set_photo(receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
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
--Run function
local function run(msg, matches)
if msg.to.type == 'chat' then
if matches[1] == 'tosuper' then
if not is_admin1(msg) then
return
end
local receiver = get_receiver(msg)
chat_upgrade(receiver, ok_cb, false)
end
elseif msg.to.type == 'channel'then
if matches[1] == 'tosuper' then
if not is_admin1(msg) then
return
end
return "Already a SuperGroup"
end
end
if msg.to.type == 'channel' then
local support_id = msg.from.id
local receiver = get_receiver(msg)
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
local data = load_data(_config.moderation.data)
if matches[1] == 'add' and not matches[2] then
if not is_admin1(msg) and not is_support(support_id) then
return
end
if is_super_group(msg) then
return reply_msg(msg.id, 'SuperGroup is already added.', ok_cb, false)
end
print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup")
superadd(msg)
set_mutes(msg.to.id)
channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false)
end
if matches[1] == 'rem' and is_admin1(msg) and not matches[2] then
if not is_super_group(msg) then
return reply_msg(msg.id, 'SuperGroup is not added.', ok_cb, false)
end
print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed")
superrem(msg)
rem_mutes(msg.to.id)
end
if not data[tostring(msg.to.id)] then
return
end
if matches[1] == "info" then
if not is_owner(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info")
channel_info(receiver, callback_info, {receiver = receiver, msg = msg})
end
if matches[1] == "admins" then
if not is_owner(msg) and not is_support(msg.from.id) then
return
end
member_type = 'Admins'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list")
admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type})
end
if matches[1] == "owner" then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your SuperGroup"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "SuperGroup owner is ["..group_owner..']'
end
if matches[1] == "modlist" then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
-- channel_get_admins(receiver,callback, {receiver = receiver})
end
if matches[1] == "bots" and is_momod(msg) then
member_type = 'Bots'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list")
channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type})
end
if matches[1] == "who" and not matches[2] and is_momod(msg) then
local user_id = msg.from.peer_id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list")
channel_get_users(receiver, callback_who, {receiver = receiver})
end
if matches[1] == "kicked" and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list")
channel_get_kicked(receiver, callback_kicked, {receiver = receiver})
end
if matches[1] == 'del' and is_momod(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'del',
msg = msg
}
delete_msg(msg.id, ok_cb, false)
get_message(msg.reply_id, get_message_callback, cbreply_extra)
end
end
if matches[1] == 'block' and is_momod(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'channel_block',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'block' and matches[2] and string.match(matches[2], '^%d+$') then
--[[local user_id = matches[2]
local channel_id = msg.to.id
if is_momod2(user_id, channel_id) and not is_admin2(user_id) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]")
kick_user(user_id, channel_id)]]
local get_cmd = 'channel_block'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == "block" and matches[2] and not string.match(matches[2], '^%d+$') then
--[[local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'channel_block',
sender = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username)
resolve_username(username, callbackres, cbres_extra)]]
local get_cmd = 'channel_block'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'id' then
if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then
local cbreply_extra = {
get_cmd = 'id',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then
local cbreply_extra = {
get_cmd = 'idfrom',
msg = msg
}
get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif msg.text:match("@[%a%d]") then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'id'
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username)
resolve_username(username, callbackres, cbres_extra)
else
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID")
return "SuperGroup ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1] == 'kickme' then
if msg.to.type == 'channel' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme")
channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if matches[1] == 'newlink' and is_momod(msg)then
local function callback_link (extra , success, result)
local receiver = get_receiver(msg)
if success == 0 then
send_large_msg(receiver, '*Error: Failed to retrieve link* \nReason: Not creator.\n\nIf you have the link, please use /setlink to set it')
data[tostring(msg.to.id)]['settings']['set_link'] = nil
save_data(_config.moderation.data, data)
else
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link")
export_channel_link(receiver, callback_link, false)
end
if matches[1] == 'setlink' and is_owner(msg) then
data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send the new group link now'
end
if msg.text then
if msg.text:match("^([https?://w]*.?telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then
data[tostring(msg.to.id)]['settings']['set_link'] = msg.text
save_data(_config.moderation.data, data)
return "New link set"
end
end
if matches[1] == 'link' then
if not is_momod(msg) then
return
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first!\n\nOr if I am not creator use /setlink to set your link"
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] == "invite" and is_sudo(msg) then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = "invite"
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username)
resolve_username(username, callbackres, cbres_extra)
end
if matches[1] == 'res' and is_owner(msg) then
local cbres_extra = {
channelid = msg.to.id,
get_cmd = 'res'
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username)
resolve_username(username, callbackres, cbres_extra)
end
--[[if matches[1] == 'kick' and is_momod(msg) then
local receiver = channel..matches[3]
local user = "user#id"..matches[2]
chaannel_kick(receiver, user, ok_cb, false)
end]]
if matches[1] == 'setadmin' then
if not is_support(msg.from.id) and not is_owner(msg) then
return
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'setadmin',
msg = msg
}
setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'setadmin' and matches[2] and string.match(matches[2], '^%d+$') then
--[[] local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'setadmin'
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]]
local get_cmd = 'setadmin'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == 'setadmin' and matches[2] and not string.match(matches[2], '^%d+$') then
--[[local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'setadmin'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username)
resolve_username(username, callbackres, cbres_extra)]]
local get_cmd = 'setadmin'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'demoteadmin' then
if not is_support(msg.from.id) and not is_owner(msg) then
return
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'demoteadmin',
msg = msg
}
demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'demoteadmin' and matches[2] and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'demoteadmin'
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'demoteadmin' and matches[2] and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'demoteadmin'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username)
resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == 'setowner' and is_owner(msg) then
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'setowner',
msg = msg
}
setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'setowner' and matches[2] and string.match(matches[2], '^%d+$') then
--[[ local group_owner = data[tostring(msg.to.id)]['set_owner']
if group_owner then
local receiver = get_receiver(msg)
local user_id = "user#id"..group_owner
if not is_admin2(group_owner) and not is_support(group_owner) then
channel_demote(receiver, user_id, ok_cb, false)
end
local user = "user#id"..matches[2]
channel_set_admin(receiver, user, ok_cb, false)
data[tostring(msg.to.id)]['set_owner'] = tostring(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]]
local get_cmd = 'setowner'
local msg = msg
local user_id = matches[2]
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id})
elseif matches[1] == 'setowner' and matches[2] and not string.match(matches[2], '^%d+$') then
local get_cmd = 'setowner'
local msg = msg
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username})
end
end
if matches[1] == 'promote' then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner/admin can promote"
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'promote',
msg = msg
}
promote = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'promote' and matches[2] and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'promote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2])
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'promote' and matches[2] and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'promote',
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == 'mp' and is_sudo(msg) then
channel = get_receiver(msg)
user_id = 'user#id'..matches[2]
channel_set_mod(channel, user_id, ok_cb, false)
return "ok"
end
if matches[1] == 'md' and is_sudo(msg) then
channel = get_receiver(msg)
user_id = 'user#id'..matches[2]
channel_demote(channel, user_id, ok_cb, false)
return "ok"
end
if matches[1] == 'demote' then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner/support/admin can promote"
end
if type(msg.reply_id) ~= "nil" then
local cbreply_extra = {
get_cmd = 'demote',
msg = msg
}
demote = get_message(msg.reply_id, get_message_callback, cbreply_extra)
elseif matches[1] == 'demote' and matches[2] and string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local user_id = "user#id"..matches[2]
local get_cmd = 'demote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2])
user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == 'demote' and matches[2] and not string.match(matches[2], '^%d+$') then
local cbres_extra = {
channel = get_receiver(msg),
get_cmd = 'demote'
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username)
return resolve_username(username, callbackres, cbres_extra)
end
end
if matches[1] == "setname" and is_momod(msg) then
local receiver = get_receiver(msg)
local set_name = string.gsub(matches[2], '_', '')
savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2])
rename_channel(receiver, set_name, ok_cb, false)
end
if msg.service and msg.action.type == 'chat_rename' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title)
data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title
save_data(_config.moderation.data, data)
end
if matches[1] == "setabout" and is_momod(msg) then
local receiver = get_receiver(msg)
local about_text = matches[2]
local data_cat = 'description'
local target = msg.to.id
data[tostring(target)][data_cat] = about_text
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text)
channel_set_about(receiver, about_text, ok_cb, false)
return "Description has been set.\n\nSelect the chat again to see the changes."
end
if matches[1] == "setusername" and is_admin1(msg) then
local function ok_username_cb (extra, success, result)
local receiver = extra.receiver
if success == 1 then
send_large_msg(receiver, "SuperGroup username Set.\n\nSelect the chat again to see the changes.")
elseif success == 0 then
send_large_msg(receiver, "Failed to set SuperGroup username.\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.")
end
end
local username = string.gsub(matches[2], '@', '')
channel_set_username(receiver, username, ok_username_cb, {receiver=receiver})
end
if matches[1] == 'setrules' and is_momod(msg) then
rules = matches[2]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]")
return set_rulesmod(msg, data, target)
end
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo")
load_photo(msg.id, set_supergroup_photo, msg)
return
end
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)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo")
return 'Please send the new group photo now'
end
if matches[1] == 'clean' then
if not is_momod(msg) then
return
end
if not is_momod(msg) then
return "Only owner can clean"
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then
return 'No moderator(s) in this SuperGroup.'
end
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")
return 'Modlist has been cleaned'
end
if matches[2] == 'rules' then
local data_cat = 'rules'
if data[tostring(msg.to.id)][data_cat] == nil then
return "Rules have not been set"
end
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")
return 'Rules have been cleaned'
end
if matches[2] == 'about' then
local receiver = get_receiver(msg)
local about_text = ' '
local data_cat = 'description'
if data[tostring(msg.to.id)][data_cat] == nil then
return 'About is not set'
end
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")
channel_set_about(receiver, about_text, ok_cb, false)
return "About has been cleaned"
end
if matches[2] == 'mutelist' then
chat_id = msg.to.id
local hash = 'mute_user:'..chat_id
redis:del(hash)
return "Mutelist Cleaned"
end
if matches[2] == 'username' and is_admin1(msg) then
local function ok_username_cb (extra, success, result)
local receiver = extra.receiver
if success == 1 then
send_large_msg(receiver, "SuperGroup username cleaned.")
elseif success == 0 then
send_large_msg(receiver, "Failed to clean SuperGroup username.")
end
end
local username = ""
channel_set_username(receiver, username, ok_username_cb, {receiver=receiver})
end
if matches[2] == "bots" and is_momod(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked all SuperGroup bots")
channel_get_bots(receiver, callback_clean_bots, {msg = msg})
end
end
if matches[1] == 'lock' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'links' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ")
return lock_group_links(msg, data, target)
end
if matches[2] == 'spam' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ")
return lock_group_spam(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_flood(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] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2]:lower() == 'rtl' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names")
return lock_group_rtl(msg, data, target)
end
if matches[2] == 'tgservice' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked Tgservice Actions")
return lock_group_tgservice(msg, data, target)
end
if matches[2] == 'sticker' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting")
return lock_group_sticker(msg, data, target)
end
if matches[2] == 'contacts' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting")
return lock_group_contacts(msg, data, target)
end
if matches[2] == 'strict' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings")
return enable_strict_rules(msg, data, target)
end
end
if matches[1] == 'unlock' and is_momod(msg) then
local target = msg.to.id
if matches[2] == 'links' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting")
return unlock_group_links(msg, data, target)
end
if matches[2] == 'spam' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam")
return unlock_group_spam(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood")
return unlock_group_flood(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] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2]:lower() == 'rtl' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[2] == 'tgservice' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tgservice actions")
return unlock_group_tgservice(msg, data, target)
end
if matches[2] == 'sticker' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting")
return unlock_group_sticker(msg, data, target)
end
if matches[2] == 'contacts' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting")
return unlock_group_contacts(msg, data, target)
end
if matches[2] == 'strict' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings")
return disable_strict_rules(msg, data, target)
end
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return
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 'Flood has been set to: '..matches[2]
end
if matches[1] == 'public' and is_momod(msg) 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 SuperGroup to: not public")
return unset_public_membermod(msg, data, target)
end
end
if matches[1] == 'mute' and is_owner(msg) then
local chat_id = msg.to.id
if matches[2] == 'audio' then
local msg_type = 'Audio'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'photo' then
local msg_type = 'Photo'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'video' then
local msg_type = 'Video'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'gifs' then
local msg_type = 'Gifs'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." have been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'documents' then
local msg_type = 'Documents'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." have been muted"
else
return "SuperGroup mute "..msg_type.." is already on"
end
end
if matches[2] == 'text' then
local msg_type = 'Text'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." has been muted"
else
return "Mute "..msg_type.." is already on"
end
end
if matches[2] == 'all' then
local msg_type = 'All'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type)
mute(chat_id, msg_type)
return "Mute "..msg_type.." has been enabled"
else
return "Mute "..msg_type.." is already on"
end
end
end
if matches[1] == 'unmute' and is_momod(msg) then
local chat_id = msg.to.id
if matches[2] == 'audio' then
local msg_type = 'Audio'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'photo' then
local msg_type = 'Photo'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'video' then
local msg_type = 'Video'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'gifs' then
local msg_type = 'Gifs'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." have been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'documents' then
local msg_type = 'Documents'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." have been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'text' then
local msg_type = 'Text'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message")
unmute(chat_id, msg_type)
return msg_type.." has been unmuted"
else
return "Mute text is already off"
end
end
if matches[2] == 'all' then
local msg_type = 'All'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type)
unmute(chat_id, msg_type)
return "Mute "..msg_type.." has been disabled"
else
return "Mute "..msg_type.." is already disabled"
end
end
end
if matches[1] == "muteuser" and is_momod(msg) then
local chat_id = msg.to.id
local hash = "mute_user"..chat_id
local user_id = ""
if type(msg.reply_id) ~= "nil" then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg})
elseif matches[1] == "muteuser" and matches[2] and string.match(matches[2], '^%d+$') then
local user_id = matches[2]
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list")
return "["..user_id.."] removed from the muted users list"
elseif is_owner(msg) then
mute_user(chat_id, user_id)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list")
return "["..user_id.."] added to the muted user list"
end
elseif matches[1] == "muteuser" and matches[2] and not string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg})
end
end
if matches[1] == "muteslist" and is_momod(msg) then
local chat_id = msg.to.id
if not has_mutes(chat_id) then
set_mutes(chat_id)
return mutes_list(chat_id)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist")
return mutes_list(chat_id)
end
if matches[1] == "mutelist" and is_momod(msg) then
local chat_id = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist")
return muted_user_list(chat_id)
end
if matches[1] == 'settings' and is_momod(msg) then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ")
return show_supergroup_settingsmod(msg, target)
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] == 'help' and not is_owner(msg) then
text = "Message /superhelp to @Teleseed in private for SuperGroup help"
reply_msg(msg.id, text, ok_cb, false)
elseif matches[1] == 'help' and is_owner(msg) then
local name_log = user_print_name(msg.from)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp")
return super_help()
end
if matches[1] == 'peer_id' and is_admin1(msg)then
text = msg.to.peer_id
reply_msg(msg.id, text, ok_cb, false)
post_large_msg(receiver, text)
end
if matches[1] == 'msg.to.id' and is_admin1(msg) then
text = msg.to.id
reply_msg(msg.id, text, ok_cb, false)
post_large_msg(receiver, text)
end
--Admin Join Service Message
if msg.service then
local action = msg.action.type
if action == 'chat_add_user_link' then
if is_owner2(msg.from.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.from.id
savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link")
channel_set_admin(receiver, user, ok_cb, false)
end
if is_support(msg.from.id) and not is_owner2(msg.from.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.from.id
savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup")
channel_set_mod(receiver, user, ok_cb, false)
end
end
if action == 'chat_add_user' then
if is_owner2(msg.action.user.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.action.user.id
savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]")
channel_set_admin(receiver, user, ok_cb, false)
end
if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then
local receiver = get_receiver(msg)
local user = "user#id"..msg.action.user.id
savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]")
channel_set_mod(receiver, user, ok_cb, false)
end
end
end
if matches[1] == 'msg.to.peer_id' then
post_large_msg(receiver, msg.to.peer_id)
end
end
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
return {
patterns = {
"^[#!/]([Aa]dd)$",
"^[#!/]([Rr]em)$",
"^[#!/]([Mm]ove) (.*)$",
"^[#!/]([Ii]nfo)$",
"^[#!/]([Aa]dmins)$",
"^[#!/]([Oo]wner)$",
"^[#!/]([Mm]odlist)$",
"^[#!/]([Bb]ots)$",
"^[#!/]([Ww]ho)$",
"^[#!/]([Kk]icked)$",
"^[#!/]([Bb]lock) (.*)",
"^[#!/]([Bb]lock)",
"^[#!/]([Tt]osuper)$",
"^[#!/]([Ii][Dd])$",
"^[#!/]([Ii][Dd]) (.*)$",
"^[#!/]([Kk]ickme)$",
"^[#!/]([Kk]ick) (.*)$",
"^[#!/]([Nn]ewlink)$",
"^[#!/]([Ss]etlink)$",
"^[#!/]([Ll]ink)$",
"^[#!/]([Rr]es) (.*)$",
"^[#!/]([Ss]etadmin) (.*)$",
"^[#!/]([Ss]etadmin)",
"^[#!/]([Dd]emoteadmin) (.*)$",
"^[#!/]([Dd]emoteadmin)",
"^[#!/]([Ss]etowner) (.*)$",
"^[#!/]([Ss]etowner)$",
"^[#!/]([Pp]romote) (.*)$",
"^[#!/]([Pp]romote)",
"^[#!/]([Dd]emote) (.*)$",
"^[#!/]([Dd]emote)",
"^[#!/]([Ss]etname) (.*)$",
"^[#!/]([Ss]etabout) (.*)$",
"^[#!/]([Ss]etrules) (.*)$",
"^[#!/]([Ss]etphoto)$",
"^[#!/]([Ss]etusername) (.*)$",
"^[#!/]([Dd]el)$",
"^[#!/]([Ll]ock) (.*)$",
"^[#!/]([Uu]nlock) (.*)$",
"^[#!/]([Mm]ute) ([^%s]+)$",
"^[#!/]([Uu]nmute) ([^%s]+)$",
"^[#!/]([Mm]uteuser)$",
"^[#!/]([Mm]uteuser) (.*)$",
"^[#!/]([Pp]ublic) (.*)$",
"^[#!/]([Ss]ettings)$",
"^[#!/]([Rr]ules)$",
"^[#!/]([Ss]etflood) (%d+)$",
"^[#!/]([Cc]lean) (.*)$",
"^[#!/]([Hh]elp)$",
"^[#!/]([Mm]uteslist)$",
"^[#!/]([Mm]utelist)$",
"[#!/](mp) (.*)",
"[#!/](md) (.*)",
"^([https?://w]*.?telegram.me/joinchat/%S+)$",
"msg.to.peer_id",
"%[(document)%]",
"%[(photo)%]",
"%[(video)%]",
"%[(audio)%]",
"%[(contact)%]",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
--End supergrpup.lua
--By @Rondoozle
| agpl-3.0 |
KimNorgaard/dotfiles-1 | hammerspoon/hammerspoon.symlink/init.lua | 1 | 4101 | -- Load Extensions
local application = require "hs.application"
local window = require "hs.window"
local hotkey = require "hs.hotkey"
local keycodes = require "hs.keycodes"
local fnutils = require "hs.fnutils"
local alert = require "hs.alert"
local screen = require "hs.screen"
local grid = require "hs.grid"
local hints = require "hs.hints"
local appfinder = require "hs.appfinder"
local tabs = require "tabs"
local definitions = nil
local hyper = nil
local hyper2 = nil
local gridset = function(frame)
return function()
local win = window.focusedWindow()
if win then
grid.set(win, frame, win:screen())
else
alert.show("No focused window.")
end
end
end
auxWin = nil
function saveFocus()
auxWin = window.focusedWindow()
alert.show("Window '" .. auxWin:title() .. "' saved.")
end
function focusSaved()
if auxWin then
auxWin:focus()
end
end
local hotkeys = {}
function createHotkeys()
for key, fun in pairs(definitions) do
local mod = hyper
if string.len(key) == 2 and string.sub(key,2,2) == "c" then
mod = {"cmd"}
elseif string.len(key) == 2 and string.sub(key,2,2) == "l" then
mod = {"ctrl"}
end
local hk = hotkey.new(mod, string.sub(key,1,1), fun)
table.insert(hotkeys, hk)
hk:enable()
end
end
function rebindHotkeys()
for i, hk in ipairs(hotkeys) do
hk:disable()
end
hotkeys = {}
createHotkeys()
alert.show("Rebound Hotkeys")
end
function applyPlace(win, place)
local scrs = screen:allScreens()
local scr = scrs[place[1]]
grid.set(win, place[2], scr)
end
function applyLayout(layout)
return function()
for appName, place in pairs(layout) do
local app = appfinder.appFromName(appName)
if app then
for i, win in ipairs(app:allWindows()) do
applyPlace(win, place)
end
end
end
end
end
function init()
createHotkeys()
keycodes.inputSourceChanged(rebindHotkeys)
tabs.enableForApp("Emacs")
tabs.enableForApp("Atom")
alert.show("Hammerspoon, at your service.")
end
-- Actual config =================================
hyper = {"cmd", "alt", "ctrl","shift"}
hyper2 = {"ctrl"}
hs.window.animationDuration = 0;
-- hints.style = "vimperator"
-- Set grid size.
grid.GRIDWIDTH = 6
grid.GRIDHEIGHT = 8
grid.MARGINX = 0
grid.MARGINY = 0
local gw = grid.GRIDWIDTH
local gh = grid.GRIDHEIGHT
local gomiddle = {x = 1, y = 1, w = 4, h = 6}
local goleft = {x = 0, y = 0, w = gw/2, h = gh}
local goright = {x = gw/2, y = 0, w = gw/2, h = gh}
local gobig = {x = 0, y = 0, w = gw, h = gh}
local fullApps = {
"Safari","Aurora","Nightly","Xcode","Qt Creator","Google Chrome",
"Google Chrome Canary", "Eclipse", "Coda 2", "iTunes", "Emacs", "Firefox"
}
local layout2 = {
Airmail = {1, gomiddle},
Spotify = {1, gomiddle},
Calendar = {1, gomiddle},
Dash = {1, gomiddle},
iTerm = {2, goright},
MacRanger = {2, goleft},
Mail = {2, goright},
}
fnutils.each(fullApps, function(app) layout2[app] = {1, gobig} end)
definitions = {
[";"] = saveFocus,
a = focusSaved,
h = gridset(gomiddle),
t = gridset(goleft),
n = grid.maximizeWindow,
s = gridset(goright),
g = applyLayout(layout2),
d = grid.pushWindowNextScreen,
r = hs.reload,
q = function() appfinder.appFromName("Hammerspoon"):kill() end,
k = function() hints.windowHints(appfinder.appFromName("Emacs"):allWindows()) end,
j = function() hints.windowHints(window.focusedWindow():application():allWindows()) end,
ll = function() hyper, hyper2 = hyper2,hyper; rebindHotkeys() end,
ec = function() hints.windowHints(nil) end
}
-- launch and focus applications
fnutils.each({
{ key = "o", app = "MacRanger" },
{ key = "e", app = "Google Chrome" },
{ key = "u", app = "Atom" },
{ key = "i", app = "iTerm2" },
{ key = "m", app = "Airmail" }
}, function(object)
definitions[object.key] = function()
local app = appfinder.appFromName(object.app)
if app then app:activate() end
end
end)
for i=1,6 do
definitions[tostring(i)] = function()
local app = application.frontmostApplication()
tabs.focusTab(app,i)
end
end
init()
| mit |
sjznxd/luci-0.11-aa | applications/luci-statistics/luasrc/model/cbi/luci_statistics/email.lua | 7 | 1976 | --[[
Luci configuration model for statistics - collectd email plugin configuration
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: email.lua 7987 2011-11-28 04:19:38Z jow $
]]--
m = Map("luci_statistics",
translate("E-Mail Plugin Configuration"),
translate(
"The email plugin creates a unix socket which can be used " ..
"to transmit email-statistics to a running collectd daemon. " ..
"This plugin is primarily intended to be used in conjunction " ..
"with Mail::SpamAssasin::Plugin::Collectd but can be used in " ..
"other ways as well."
))
-- collectd_email config section
s = m:section( NamedSection, "collectd_email", "luci_statistics" )
-- collectd_email.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_email.socketfile (SocketFile)
socketfile = s:option( Value, "SocketFile", translate("Socket file") )
socketfile.default = "/var/run/collect-email.sock"
socketfile:depends( "enable", 1 )
-- collectd_email.socketgroup (SocketGroup)
socketgroup = s:option( Value, "SocketGroup", translate("Socket group") )
socketgroup.default = "nobody"
socketgroup.rmempty = true
socketgroup.optional = true
socketgroup:depends( "enable", 1 )
-- collectd_email.socketperms (SocketPerms)
socketperms = s:option( Value, "SocketPerms", translate("Socket permissions") )
socketperms.default = "0770"
socketperms.rmempty = true
socketperms.optional = true
socketperms:depends( "enable", 1 )
-- collectd_email.maxconns (MaxConns)
maxconns = s:option( Value, "MaxConns", translate("Maximum allowed connections") )
maxconns.default = 5
maxconns.isinteger = true
maxconns.rmempty = true
maxconns.optional = true
maxconns:depends( "enable", 1 )
return m
| apache-2.0 |
sadegh1996/sword_antispam | plugins/inrealm.lua | 1 | 27232 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created!\nCheck Pm!'
elseif not is_sudo(msg) then
return 'For Creating Group,Send Pm To @sadegha_1996!\n\nIf you are Reported,Send msg To @sadegh_1996_bot!\n\n'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.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 get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.\nAsk Sudo To set it !'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.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 set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
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
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(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, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
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
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_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
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
-- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
--
--
-- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
-- ||\\ //|| //\\ || //|| //\\ // || || //
-- || \\ // || // \\ || // || // \\ // || || //
-- || \\ // || // \\ || // || // \\ || || || //
-- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || //
-- || \\ // || // \\ || // || // \\ || || || || \\
-- || \\ // || // \\ || // || // \\ \\ || || || \\
-- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\
--
--
-- ||-_-_-_- || || || //-_-_-_-_-_-
-- || || || || || //
-- ||_-_-_|| || || || //
-- || || || || \\
-- || || \\ // \\
-- || || \\ // //
-- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-//
--
--By @ali_ghoghnoos
--@telemanager_ch
| gpl-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Kazham/npcs/Gatih_Mijurabi.lua | 21 | 1030 | -----------------------------------
-- Area: Kazham
-- NPC: Gatih Mijurabi
-- Type: Standard NPC
-- @zone: 250
-- @pos 58.249 -13.086 -49.084
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00c4);
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 |
TW1STaL1CKY/pac3 | lua/pac3/libraries/class.lua | 2 | 4120 | local table = {insert = table.insert}
do -- table copy
local lookup_table
local function copy(obj, skip_meta)
local t = type(obj)
if t == "number" or t == "string" or t == "function" or t == "boolean" then
return obj
end
if t == "Vector" or t == "Angle" then
return obj * 1
elseif lookup_table[obj] then
return lookup_table[obj]
elseif t == "table" then
local new_table = {}
lookup_table[obj] = new_table
for key, val in pairs(obj) do
new_table[copy(key, skip_meta)] = copy(val, skip_meta)
end
return skip_meta and new_table or setmetatable(new_table, getmetatable(obj))
end
return obj
end
function table.copy(obj, skip_meta)
lookup_table = {}
return copy(obj, skip_meta)
end
end
local class = {}
class.Registered = {}
local function checkfield(tbl, key, def)
tbl[key] = tbl[key] or def
if not tbl[key] then
error(string.format("The type field %q was not found!", key), 3)
end
return tbl[key]
end
function class.GetSet(tbl, name, def)
if type(def) == "number" then
tbl["Set" .. name] = tbl["Set" .. name] or function(self, var) self[name] = tonumber(var) end
tbl["Get" .. name] = tbl["Get" .. name] or function(self) return tonumber(self[name]) end
elseif type(def) == "string" then
tbl["Set" .. name] = tbl["Set" .. name] or function(self, var) self[name] = tostring(var) end
tbl["Get" .. name] = tbl["Get" .. name] or function(self) return tostring(self[name]) end
else
tbl["Set" .. name] = tbl["Set" .. name] or function(self, var) self[name] = var end
tbl["Get" .. name] = tbl["Get" .. name] or function(self) return self[name] end
end
tbl[name] = def
end
function class.IsSet(tbl, name, def)
if type(def) == "number" then
tbl["Set" .. name] = tbl["Set" .. name] or function(self, var) self[name] = tonumber(var) end
else
tbl["Set" .. name] = tbl["Set" .. name] or function(self, var) self[name] = var end
end
tbl["Is" .. name] = tbl["Is" .. name] or function(self) return self[name] end
tbl[name] = def
end
function class.RemoveField(tbl, name)
tbl["Set" .. name] = nil
tbl["Get" .. name] = nil
tbl["Is" .. name] = nil
tbl[name] = nil
end
function class.Get(type_name, class_name)
return class.Registered[type_name] and class.Registered[type_name][class_name] or nil
end
function class.GetAll(type_name)
return class.Registered[type_name]
end
function class.Register(META, type_name, name)
local type_name = checkfield(META, "Type", type_name)
local name = checkfield(META, "ClassName", name)
class.Registered[type_name] = class.Registered[type_name] or {}
class.Registered[type_name][name] = META
return type_name, name
end
function class.HandleBaseField(META, var)
if not var then return end
local t = type(var)
if t == "string" then
class.HandleBaseField(META, class.Get(META.Type, var))
elseif t == "table" then
-- if it's a table and does not have the Type field we assume it's a table of bases
if not var.Type then
for _, base in pairs(var) do
class.HandleBaseField(META, base)
end
else
-- make a copy of it so we don't alter the meta template
var = table.copy(var)
META.BaseList = META.BaseList or {}
table.insert(META.BaseList, var)
end
end
end
function class.Create(type_name, class_name)
local META = class.Get(type_name, class_name)
if not META then
MsgN(string.format("tried to create unknown %s %q!", type or "no type", class_name or "no class"))
return
end
local obj = table.copy(META)
class.HandleBaseField(obj, obj.Base)
class.HandleBaseField(obj, obj.TypeBase)
if obj.BaseList then
if #obj.BaseList == 1 then
for key, val in pairs(obj.BaseList[1]) do
obj[key] = obj[key] or val
end
obj.BaseClass = obj.BaseList[1]
else
local current = obj
for _, base in pairs(obj.BaseList) do
for key, val in pairs(base) do
obj[key] = obj[key] or val
end
current.BaseClass = base
current = base
end
end
end
obj.MetaTable = META
setmetatable(obj, obj)
return obj
end
class.Copy = table.copy
return class | gpl-3.0 |
FFXIOrgins/FFXIOrgins | 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 |
FFXIOrgins/FFXIOrgins | scripts/globals/items/prime_crab_stewpot.lua | 36 | 1891 | -----------------------------------------
-- ID: 5545
-- Item: Prime Crab Stewpot
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP +10% Cap 75
-- MP +15
-- Vitality +1
-- Agility +1
-- Mind +2
-- HP Recovered while healing +7
-- MP Recovered while healing +2
-- Defense 20% Cap 75
-- Evasion +6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5545);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 10);
target:addMod(MOD_FOOD_HP_CAP, 75);
target:addMod(MOD_MP, 15);
target:addMod(MOD_VIT, 1);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_MND, 2);
target:addMod(MOD_HPHEAL, 7);
target:addMod(MOD_MPHEAL, 2);
target:addMod(MOD_FOOD_DEFP, 20);
target:addMod(MOD_FOOD_DEF_CAP, 75);
target:addMod(MOD_EVA, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 10);
target:delMod(MOD_FOOD_HP_CAP, 75);
target:delMod(MOD_MP, 15);
target:delMod(MOD_VIT, 1);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_MND, 2);
target:delMod(MOD_HPHEAL, 7);
target:delMod(MOD_MPHEAL, 2);
target:delMod(MOD_FOOD_DEFP, 20);
target:delMod(MOD_FOOD_DEF_CAP, 75);
target:delMod(MOD_EVA, 6);
end;
| gpl-3.0 |
mehrpouya81/gamer1 | plugins/all.lua | 264 | 4202 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'chat stats! \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
if not data[tostring(target)] then
return 'Group is not added.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group \n \n"
local settings = show_group_settings(target)
text = text.."Group settings \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\n"..modlist
local link = get_link(target)
text = text.."\n\n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] and msg.to.id ~= our_id then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
return
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end | gpl-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Dynamis-Windurst/Zone.lua | 4 | 2260 | -----------------------------------
--
-- Zone: Dynamis-Windurst
--
-----------------------------------
package.loaded["scripts/zones/Dynamis-Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Dynamis-Windurst/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaWindurst]UniqueID")) then
if(player:isBcnmsFull() == 1) then
if(player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then
inst = player:addPlayerToDynamis(1282);
if(inst == 1)then
player:bcnmEnter(1282);
else
cs = 0;
end
else
player:bcnmEnter(1282);
end
else
inst = player:bcnmRegister(1282);
if(inst == 1)then
player:bcnmEnter(1282);
else
cs = 0;
end
end
else
cs = 0;
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);
if(csid == 0) then
player:setPos(-217.000,1.000,-119.000,94,0xEF);
end
end; | gpl-3.0 |
msburgess3200/PERP | gamemodes/perp/gamemode/vgui/trade_offer.lua | 1 | 1066 |
local PANEL = {};
function PANEL:Init ( )
self.InventoryBlocks = {};
local fakeX, fakeY = 1, 0;
for x = 1, 3 do
for y = 1, 5 do
fakeY = fakeY + 1;
if (fakeY > 5) then
fakeY = 1;
fakeX = fakeX + 1;
end
local newBlock = vgui.Create("perp2_trade_offer_block", self);
newBlock.itemID = y + ((x - 1) * 5);
newBlock.fXPos, newBlock.fYPos = fakeX, fakeY;
self.InventoryBlocks[newBlock.itemID] = newBlock;
end
end
self.Description = true;
//self:SetSkin("ugperp")
end
function PANEL:PerformLayout ( )
local bufferSize = 5;
local curY = bufferSize;
local blocksPerRow = (INVENTORY_HEIGHT * INVENTORY_WIDTH) / 5;
for i, v in pairs(self.InventoryBlocks) do
local x = v.fXPos;
local y = v.fYPos;
v:SetSize(self.SizeOfBlock, self.SizeOfBlock);
v:SetPos((bufferSize * x) + ((x - 1) * self.SizeOfBlock), (bufferSize * y) + ((y - 1) * self.SizeOfBlock));
end
end
function PANEL:Paint ( )
SKIN:PaintFrame(self, true);
end
function PANEL:SetDescription ( ) end
vgui.Register("perp2_trade_offer", PANEL); | mit |
mawri/sswe-team9 | src/SSWE.lua | 1 | 8058 |
-- hardcoded window size as 2
-- require('mobdebug').start();
require("sys")
require("nn")
local SSWE = torch.class ("SSWE")
----------------------------------- constructor ---------------------------
function SSWE:__init()
self.neg_samples = 5;
self.criterion = nn.MarginCriterion()
self.senti_criterion = nn.MarginCriterion()
self.com_criterion = nn.ParallelCriterion();
self.com_criterion : add (self.criterion, 0.6) : add (self.senti_criterion, 0.4);
self.epochs = 5;
self.dim = 50;
self.window_size = 1;
self.contexts = torch.IntTensor(4+self.neg_samples)
self.labels = torch.zeros(4+self.neg_samples);
self.labels[1] = 1; self.labels[2] = 1; self.labels[3] = 1; self.labels[4] = 1 -- first label is always pos sample -- refers to both sides of the target word
self.senti_contexts = torch.IntTensor (4);
self.senti_labels = torch.Tensor (4);
self.lr = .01;
self.vocab = {}
self.index2word = {}
self.word = torch.IntTensor (1)
end
---------------------------------- building vocab --------------------------
function SSWE:build_vocab(corpus_file_name)
local f = io.open (corpus_file_name, "r")
local i = 1
for line in f : lines () do
for _, word in ipairs (self:split (line)) do
if self.vocab[word] == nil then
self.vocab[word] = i
self.index2word[i] = word
i = i + 1
end
end
end
f : close ();
self.vocab_size = #self.index2word
end
------------------------------------ split on separator -------------------------
function SSWE:split(input, sep)
if sep == nil then
sep = "%s"
end
local t = {}; local i = 1
for str in string.gmatch(input, "([^"..sep.."]+)") do
t[i] = str; i = i + 1
end
return t
end
------------------------------------ training -----------------------------------
function SSWE:train_model (corpus_file_name, sentiment_file_name)
-- Describing the model
self.word_vecs = nn.LookupTable(self.vocab_size, self.dim) -- word embeddings
self.context_vecs = nn.LookupTable(self.vocab_size, self.dim) -- context embeddings
self.senti_word_vecs = self.word_vecs : clone ('weight', 'bias', 'gradWeight', 'gradBias')
self.senti_context_vecs = self.context_vecs : clone ('weight', 'bias', 'gradWeight', 'gradBias')
-- semantic model
self.model = nn.Sequential()
self.model:add(nn.ParallelTable())
self.model.modules[1]:add(self.context_vecs)
self.model.modules[1]:add(self.word_vecs)
self.model:add (nn.MM(false, true)); -- dot prod and sigmoid to get probabilities
self.model:add (nn.HardTanh ());
-- self.trainer = nn.StochasticGradient(self.model,self.criterion)
-- self.trainer.learningRate = self.lr
-- self.trainer.maxIteration = self.epochs
-- sentiment model
self.senti_model = nn.Sequential();
self.senti_model : add (nn.ParallelTable())
self.senti_model.modules[1]:add(self.senti_context_vecs)
self.senti_model.modules[1]:add(self.senti_word_vecs)
self.senti_model : add (nn.MM(false, true));
self.senti_model : add (nn.HardTanh ());
-- self.senti_trainer = nn.StochasticGradient(self.senti_model,self.senti_criterion)
-- self.senti_trainer.learningRate = self.lr
-- self.senti_trainer.maxIteration = self.epochs
-- complete model
-- self.com_model = nn.Sequential ();
self.com_model = nn.ParallelTable ();
self.com_model : add (self.model);
self.com_model : add (self.senti_model);
-- complete trainer
self.com_trainer = nn.StochasticGradient (self.com_model, self.com_criterion);
self.com_trainer.verbose = false;
self.com_trainer.learningRate = self.lr;
self.com_trainer.maxIteration = self.epochs;
-- Now beginning the training
print ("training...")
local c = 0;
local start = sys.clock ()
f = io.open (corpus_file_name, "r")
f1 = io.open (sentiment_file_name, "r")
local z = 1;
for line in f : lines () do
if z % 100 == 1 then
print(string.format ("Training line %d...%.2f ?seconds gone", z, sys.clock () - start));
end
z = z + 1;
self.sentiment = tonumber(f1:read ())
sentence = self : split (line)
for i, word in ipairs (sentence) do
self.word[1] = self.vocab[word]
-- find contexts and negative-contexts
if sentence[i - 1] ~= nil and sentence[i + 1] ~= nil
and sentence[i - 2] ~= nil and sentence[i + 2] ~= nil then
self.contexts[1] = self.vocab[sentence[i - 1]];
self.contexts[2] = self.vocab[sentence[i + 1]];
self.contexts[3] = self.vocab[sentence[i - 2]];
self.contexts[4] = self.vocab[sentence[i + 2]];
self.senti_contexts[1] = self.vocab[sentence[i - 1]];
self.senti_contexts[2] = self.vocab[sentence[i + 1]];
self.senti_contexts[3] = self.vocab[sentence[i - 2]];
self.senti_contexts[4] = self.vocab[sentence[i + 2]];
self.senti_labels[1] = self.sentiment;
self.senti_labels[2] = self.sentiment;
self.senti_labels[3] = self.sentiment;
self.senti_labels[4] = self.sentiment;
-- now for the negative contexts
local j = 0;
while j < self.neg_samples do
neg_context = self.index2word[torch.random (self.vocab_size)]
if neg_context ~= sentence[i - 1]
and neg_context ~= sentence[i + 1]
and neg_context ~= sentence[i - 2]
and neg_context ~= sentence[i + 2]
and neg_context ~= word then
self.contexts[j + 5] = self.vocab[neg_context]
j = j + 1
end
end
-- training
data = {}
function data:size () return 1 end
data[1] = {
{{self.contexts, self.word}, {self.senti_contexts, self.word}},
{self.labels, self.senti_labels}
};
self.com_trainer:train(data);
end
end
end
f:close();
end
-------------------------------------------------------------------------------------------------------
---------------------------------Module for testing ---------------------------------------------------
---------------------------------- Row-normalize a matrix ---------------------------------------------
function SSWE:normalize(m)
m_norm = torch.zeros(m:size())
for i = 1, m:size(1) do
m_norm[i] = m[i] / torch.norm(m[i])
end
return m_norm
end
-------------------------------- Get similar words -------------------------------------------------
-- Return the k-nearest words to a word or a vector based on cosine similarity
-- w can be a string such as "king" or a vector for ("king" - "queen" + "man")
function SSWE:get_sim_words(w, k)
if self.word_vecs_norm == nil then
self.word_vecs_norm = self:normalize(self.word_vecs.weight:double())
end
if type(w) == "string" then
if self.vocab[w] == nil then
print("'"..w.."' does not exist in vocabulary.")
return nil
else
w = self.word_vecs_norm[self.vocab[w]]
end
end
local sim = torch.mv(self.word_vecs_norm, w)
sim, idx = torch.sort(-sim)
local r = {}
for i = 1, k do
r[i] = {self.index2word[idx[i]], -sim[i]}
end
return r
end
-- print similar words
function SSWE:print_sim_words(words, k)
for i = 1, #words do
r = self:get_sim_words(words[i], k)
if r ~= nil then
print("-------"..words[i].."-------")
for j = 1, k do
print(string.format("%s, %.4f", r[j][1], r[j][2]))
end
end
end
end | mit |
FFXIOrgins/FFXIOrgins | scripts/zones/Port_San_dOria/npcs/Ilgusin.lua | 38 | 1038 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Ilgusin
-- Type: Standard NPC
-- @zone: 232
-- @pos -68.313 -6.5 -36.985
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x024f);
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 |
elt11bot/seed-sup | plugins/anti-spam.lua | 2 | 3878 |
--An empty table for solving multiple kicking problem(thanks to @topkecleon )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
local data = load_data(_config.moderation.data)
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
return msg
end
if msg.from.id == our_id then
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is one or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
end
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local data = load_data(_config.moderation.data)
local NUM_MSG_MAX = 5
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'])--Obtain group flood sensitivity
end
end
local max_msg = NUM_MSG_MAX * 1
if msgs > max_msg then
local user = msg.from.id
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
local chat = msg.to.id
local user = msg.from.id
-- Return end if user was kicked before
if kicktable[user] == true then
return
end
kick_user(user, chat)
local name = user_print_name(msg.from)
--save it to log file
savelog(msg.to.id, name.." ["..msg.from.id.."] spammed and kicked ! ")
-- incr it on redis
local gbanspam = 'gban:spam'..msg.from.id
redis:incr(gbanspam)
local gbanspam = 'gban:spam'..msg.from.id
local gbanspamonredis = redis:get(gbanspam)
--Check if user has spammed is group more than 4 times
if gbanspamonredis then
if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then
--Global ban that user
banall_user(msg.from.id)
local gbanspam = 'gban:spam'..msg.from.id
--reset the counter
redis:set(gbanspam, 0)
local username = " "
if msg.from.username ~= nil then
username = msg.from.username
end
local name = user_print_name(msg.from)
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." Globally banned (spamming)")
local log_group = 1 --set log group caht id
--send it to log group
send_large_msg("chat#id"..log_group, "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)")
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function cron()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = cron,
pre_process = pre_process
}
end
| gpl-2.0 |
punisherbot/test | 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 |
msburgess3200/PERP | gamemodes/perp/gamemode/items/furniture_bed.lua | 1 | 1236 |
local ITEM = {};
ITEM.ID = 53;
ITEM.Reference = "furniture_bed";
ITEM.Name = "Small Bed";
ITEM.Description = "Needed for a good night's sleep.\n\nLeft click to spawn as prop.";
ITEM.Weight = 10;
ITEM.Cost = 500;
ITEM.MaxStack = 100;
ITEM.InventoryModel = "models/env/furniture/bed_connemara/bed_connemara_3rd.mdl";
ITEM.ModelCamPos = Vector(93, 52, 68);
ITEM.ModelLookAt = Vector(0, 0, 13);
ITEM.ModelFOV = 70;
ITEM.WorldModel = "models/env/furniture/bed_connemara/bed_connemara_3rd.mdl";
ITEM.RestrictedSelling = false; // Used for drugs and the like. So we can't sell it.
ITEM.EquipZone = nil;
ITEM.PredictUseDrop = false; // If this isn't true, the server will tell the client when something happens to us.
if SERVER then
function ITEM.OnUse ( Player )
local prop = Player:SpawnProp(ITEM);
if (!prop || !IsValid(prop)) then return false; end
return true;
end
function ITEM.OnDrop ( Player )
return true;
end
function ITEM.Equip ( Player )
end
function ITEM.Holster ( Player )
end
else
function ITEM.OnUse ( slotID )
return true;
end
function ITEM.OnDrop ( )
return true;
end
end
GM:RegisterItem(ITEM); | mit |
FFXIOrgins/FFXIOrgins | scripts/zones/FeiYin/npcs/Rukususu.lua | 13 | 1766 | -----------------------------------
-- Area: Fei'Yin
-- NPC: Rukususu (talk to Cermet Door _no5 to trigger)
-- Type: Quest NPC
-- @pos -194.133 -0.986 191.077 204
-- Involved in quests: Curses, Foiled A-Golem!?,SMN AF2: Class Reunion, SMN AF3: Carbuncle Debacle
-- Involved in Missions: Windurst 5-1/7-2/8-2
-----------------------------------
package.loaded["scripts/zones/FeiYin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/FeiYin/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Curses, Foiled A_Golem!?
if(player:hasKeyItem(SHANTOTTOS_NEW_SPELL)) then
player:startEvent(0x000E); -- deliver spell
elseif(player:hasKeyItem(SHANTOTTOS_EXSPELL)) then
player:startEvent(0x000D); -- spell erased, try again!
-- standard dialog
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);
-- Curses, Foiled A_Golem!?
if(csid == 0x000E) then
player:setVar("foiledagolemdeliverycomplete",1);
player:delKeyItem(SHANTOTTOS_NEW_SPELL); -- remove key item
end
end;
| gpl-3.0 |
excessive/lua-bgfx | test/camera.lua | 2 | 2923 | local cpml = require "cpml"
local camera = {}
local camera_mt = {
__index = camera
}
local function new(options)
local t = {
fov = options.fov or 45,
near = options.near or 0.1, -- 10cm
far = options.far or 150.0, -- 150m
exposure = options.exposure or 1.0,
position = options.position or cpml.vec3(0, 0, 0),
orientation = options.orientation or cpml.quat(0, 0, 0, 1),
target = options.target or false,
up = cpml.vec3.unit_z,
orbit_offset = options.orbit_offset or cpml.vec3(0, 0, 0),
offset = options.offset or cpml.vec3(0, 0, 0),
view = cpml.mat4(),
projection = cpml.mat4(),
mouse_sensitivity = 0.1,
pitch_limit_up = 0.3,
pitch_limit_down = 0.9
}
t.direction = t.orientation * cpml.vec3.unit_y
return setmetatable(t, camera_mt)
end
function camera:rotate_xy(mx, my)
local sensitivity = self.mouse_sensitivity
local mouse_direction = {
x = math.rad(-mx * sensitivity),
y = math.rad(-my * sensitivity)
}
-- get the axis to rotate around the x-axis.
local axis = cpml.vec3():cross(self.direction, self.up)
axis:normalize(axis)
-- First, we apply a left/right rotation.
self.orientation = cpml.quat.rotate(mouse_direction.x, self.up) * self.orientation
-- Next, we apply up/down rotation.
-- up/down rotation is applied after any other rotation (so that other rotations are not affected by it),
-- hence we post-multiply it.
local new_orientation = self.orientation * cpml.quat.rotate(mouse_direction.y, cpml.vec3.unit_x)
local new_pitch = (new_orientation * cpml.vec3.unit_y):dot(self.up)
-- Don't rotate up/down more than self.pitch_limit.
-- We need to limit pitch, but the only reliable way we're going to get away with this is if we
-- calculate the new orientation twice. If the new rotation is going to be over the threshold and
-- Y will send you out any further, cancel it out. This prevents the camera locking up at +/-PITCH_LIMIT
if new_pitch >= self.pitch_limit_up then
mouse_direction.y = math.min(0, mouse_direction.y)
elseif new_pitch <= -self.pitch_limit_down then
mouse_direction.y = math.max(0, mouse_direction.y)
end
self.orientation = self.orientation * cpml.quat.rotate(mouse_direction.y, cpml.vec3.unit_x)
-- Apply rotation to camera direction
self.direction = self.orientation * cpml.vec3.unit_y
end
function camera:update(w, h)
local aspect = math.max(w / h, h / w)
local target = self.target and self.target or (self.position + self.direction)
local look = cpml.mat4()
look:look_at(look, self.position, target, cpml.vec3.unit_z)
self.view:identity(self.view)
:translate(self.view, self.orbit_offset)
:mul(look, self.view)
:translate(self.view, self.offset)
self.projection = cpml.mat4.from_perspective(self.fov, aspect, self.near, self.far)
end
return setmetatable(
{ new = new },
{ __call = function(_, ...) return new(...) end }
)
| mit |
Vanderlay/tfs-TDEvent | data/actions/scripts/TDEvent/twdHammer.lua | 1 | 2722 | dofile('data/lib/TWD/towerDefenseLib.lua')
function onUse(cid, item, fromPosition, target, toPosition, isHotkey)
local player = Player(cid)
if player:getStorageValue(playingGameStorage) ~= 1 then
return false
end
local tile = toPosition:getTile()
if tile then
if not tile:hasFlag(TILESTATE_PROTECTIONZONE) or tile:hasProperty(CONST_PROP_IMMOVABLEBLOCKSOLID) then
player:sendCancelMessage("You cannot place the turret here.")
return true
end
local npc = Creature(tile:getTopCreature())
if not npc then
local modalWindow = ModalWindow(100, "Build Turret", "Here you can select variations of turrets to build.")
local turret, cfgTable = turrets.allTurretsId
for i = 1, #turret do
turret = turrets.allTurretsId[i]
cfgTable = turrets[turret].cfg
modalWindow:addChoice(turret, string.format("%s [%s coins]", cfgTable.turretName, cfgTable[1].buildPrice))
end
modalWindow:addButton(0, "Build")
modalWindow:setDefaultEnterButton(0)
modalWindow:addButton(1, "Cancel")
modalWindow:setDefaultEscapeButton(1)
modalWindow:sendToPlayer(player)
turretPosition = toPosition
elseif npc:isNpc() and npc:getName() == "Turret" then
local table = turrets[npc:getOutfit().lookType]
local lvl = npc:getTurretLevel()
local cfg, cfgCombat = table.cfg[lvl], table.combat[lvl]
local turrentInfo = string.format("Turret Information\n----------------------------\nTurret Level: %s\nAttack Type: %s\nRange SQM: %sx%s\nTurret Damage: [%s - %s]\nAttack Speed: %s\nSell/Upgrade Price: [%s / %s]", lvl, string.upper(cfgCombat.attackType), cfg.rangeX, cfg.rangeY, cfgCombat.dmgValues[1], cfgCombat.dmgValues[2], cfg.attackSpeed, cfg.sellPrice, cfg.upgradePrice)
local playerInfo = string.format("Player Information\n----------------------------\nWave Level: %s\nYour Coins: %s", getWaveLevel(), player:getCoins())
local modalWindow = ModalWindow(101, "Information", string.format("%s\n\n%s", turrentInfo, playerInfo))
if lvl < 3 then
modalWindow:addChoice(0, "Upgrade")
end
modalWindow:addChoice(1, "Sell")
modalWindow:addButton(0, "Yes")
modalWindow:setDefaultEnterButton(0)
modalWindow:addButton(0x01, "Cancel")
modalWindow:setDefaultEscapeButton(1)
modalWindow:sendToPlayer(player)
targetTurret = npc
end
end
return true
end | gpl-2.0 |
nehz/busted | busted/languages/fr.lua | 12 | 1487 | local s = require('say')
s:set_namespace('fr')
-- 'Pending: test.lua @ 12 \n description
s:set('output.pending', 'En attente')
s:set('output.failure', 'Echec')
s:set('output.success', 'Reussite')
s:set('output.pending_plural', 'en attente')
s:set('output.failure_plural', 'echecs')
s:set('output.success_plural', 'reussites')
s:set('output.pending_zero', 'en attente')
s:set('output.failure_zero', 'echec')
s:set('output.success_zero', 'reussite')
s:set('output.pending_single', 'en attente')
s:set('output.failure_single', 'echec')
s:set('output.success_single', 'reussite')
s:set('output.seconds', 'secondes')
s:set('output.no_test_files_match', 'Aucun test n\'est pourrait trouvé qui corresponde au motif de Lua: %s')
-- definitions following are not used within the 'say' namespace
return {
failure_messages = {
'Vous avez %d test(s) qui a/ont echoue(s)',
'Vos tests ont echoue.',
'Votre code source est mauvais et vous devrez vous sentir mal',
'Vous avez un code source de Destruction Massive',
'Jeu plutot etrange game. Le seul moyen de gagner est de ne pas l\'essayer',
'Meme ma grand-mere ecrivait de meilleurs tests sur un PIII x86',
'A chaque erreur, prenez une biere',
'Ca craint, mon pote'
},
success_messages = {
'Oh yeah, tests reussis',
'Pas grave, y\'a eu du succes',
'C\'est du bon, mon pote. Que du bon!',
'Reussi, haut la main!',
'Test reussi. Un de plus. Offre toi une biere, sur mon compte!',
}
}
| mit |
FFXIOrgins/FFXIOrgins | scripts/globals/items/blackened_frog.lua | 35 | 1741 | -----------------------------------------
-- ID: 4536
-- Item: Blackened Frog
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Dexterity 2
-- Agility 2
-- Mind -2
-- Attack % 14
-- Attack Cap 60
-- Ranged ATT % 14
-- Ranged ATT Cap 60
-- Enmity -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4536);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_AGI, 2);
target:addMod(MOD_MND, -2);
target:addMod(MOD_FOOD_ATTP, 14);
target:addMod(MOD_FOOD_ATT_CAP, 60);
target:addMod(MOD_FOOD_RATTP, 14);
target:addMod(MOD_FOOD_RATT_CAP, 60);
target:addMod(MOD_ENMITY, -5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_AGI, 2);
target:delMod(MOD_MND, -2);
target:delMod(MOD_FOOD_ATTP, 14);
target:delMod(MOD_FOOD_ATT_CAP, 60);
target:delMod(MOD_FOOD_RATTP, 14);
target:delMod(MOD_FOOD_RATT_CAP, 60);
target:delMod(MOD_ENMITY, -5);
end;
| gpl-3.0 |
JulianVolodia/awesome | lib/awful/tag.lua | 3 | 22976 | ---------------------------------------------------------------------------
--- Useful functions for tag manipulation.
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008 Julien Danjou
-- @release @AWESOME_VERSION@
-- @module awful.tag
---------------------------------------------------------------------------
-- Grab environment we need
local util = require("awful.util")
local ascreen = require("awful.screen")
local timer = require("gears.timer")
local beautiful = require("beautiful")
local tostring = tostring
local pairs = pairs
local ipairs = ipairs
local table = table
local setmetatable = setmetatable
local capi =
{
tag = tag,
screen = screen,
mouse = mouse,
client = client,
root = root
}
local tag = { mt = {} }
-- Private data
local data = {}
data.history = {}
data.tags = setmetatable({}, { __mode = 'k' })
-- History functions
tag.history = {}
tag.history.limit = 20
--- Move a tag to an absolute position in the screen[]:tags() table.
-- @param new_index Integer absolute position in the table to insert.
-- @param target_tag The tag that should be moved. If null, the currently
-- selected tag is used.
function tag.move(new_index, target_tag)
local target_tag = target_tag or tag.selected()
local scr = tag.getscreen(target_tag)
local tmp_tags = tag.gettags(scr)
if (not new_index) or (new_index < 1) or (new_index > #tmp_tags) then
return
end
local rm_index = nil
for i, t in ipairs(tmp_tags) do
if t == target_tag then
table.remove(tmp_tags, i)
rm_index = i
break
end
end
table.insert(tmp_tags, new_index, target_tag)
for i=new_index < rm_index and new_index or rm_index, #tmp_tags do
local tmp_tag = tmp_tags[i]
tag.setscreen(tmp_tag, scr)
tag.setproperty(tmp_tag, "index", i)
end
end
--- Swap 2 tags
-- @param tag1 The first tag
-- @param tag2 The second tag
function tag.swap(tag1, tag2)
local idx1, idx2 = tag.getidx(tag1), tag.getidx(tag2)
local src2, src1 = tag.getscreen(tag2), tag.getscreen(tag1)
tag.setscreen(tag2, src1)
tag.move(idx1, tag2)
tag.setscreen(tag1, scr2)
tag.move(idx2, tag1)
end
--- Add a tag.
-- @param name The tag name, a string
-- @param props The tags properties, a table
-- @return The created tag
function tag.add(name, props)
local properties = props or {}
-- Be sure to set the screen before the tag is activated to avoid function
-- connected to property::activated to be called without a valid tag.
-- set properies cannot be used as this has to be set before the first signal
-- is sent
properties.screen = properties.screen or ascreen.focused()
-- Index is also required
properties.index = (#tag.gettags(properties.screen))+1
local newtag = capi.tag{ name = name }
-- Start with a fresh property table to avoid collisions with unsupported data
data.tags[newtag] = {screen=properties.screen, index=properties.index}
newtag.activated = true
for k, v in pairs(properties) do
tag.setproperty(newtag, k, v)
end
return newtag
end
--- Create a set of tags and attach it to a screen.
-- @param names The tag name, in a table
-- @param screen The tag screen, or 1 if not set.
-- @param layout The layout or layout table to set for this tags by default.
-- @return A table with all created tags.
function tag.new(names, screen, layout)
local screen = screen or 1
local tags = {}
for id, name in ipairs(names) do
table.insert(tags, id, tag.add(name, {screen = screen,
layout = (layout and layout[id]) or
layout}))
-- Select the first tag.
if id == 1 then
tags[id].selected = true
end
end
return tags
end
--- Find a suitable fallback tag.
-- @param screen The screen number to look for a tag on. [awful.screen.focused()]
-- @param invalids A table of tags we consider unacceptable. [selectedlist(scr)]
function tag.find_fallback(screen, invalids)
local scr = screen or ascreen.focused()
local t = invalids or tag.selectedlist(scr)
for _, v in pairs(tag.gettags(scr)) do
if not util.table.hasitem(t, v) then return v end
end
end
--- Delete a tag.
-- @param target_tag Optional tag object to delete. [selected()]
-- @param fallback_tag Tag to assign stickied tags to. [~selected()]
-- @return Returns true if the tag is successfully deleted, nil otherwise.
-- If there are no clients exclusively on this tag then delete it. Any
-- stickied clients are assigned to the optional 'fallback_tag'.
-- If after deleting the tag there is no selected tag, try and restore from
-- history or select the first tag on the screen.
function tag.delete(target_tag, fallback_tag)
-- abort if no tag is passed or currently selected
local target_tag = target_tag or tag.selected()
if target_tag == nil or target_tag.activated == false then return end
local target_scr = tag.getscreen(target_tag)
local tags = tag.gettags(target_scr)
local idx = tag.getidx(target_tag)
local ntags = #tags
-- We can't use the target tag as a fallback.
local fallback_tag = fallback_tag
if fallback_tag == target_tag then return end
-- No fallback_tag provided, try and get one.
if fallback_tag == nil then
fallback_tag = tag.find_fallback(target_scr, {target_tag})
end
-- Abort if we would have un-tagged clients.
local clients = target_tag:clients()
if ( #clients > 0 and ntags <= 1 ) or fallback_tag == nil then return end
-- Move the clients we can off of this tag.
for _, c in pairs(clients) do
local nb_tags = #c:tags()
-- If a client has only this tag, or stickied clients with
-- nowhere to go, abort.
if (not c.sticky and nb_tags == 1) or
(c.sticky and fallback_tag == nil) then
return
-- If a client has multiple tags, then do not move it to fallback
elseif nb_tags < 2 then
c:tags({fallback_tag})
end
end
-- delete the tag
data.tags[target_tag].screen = nil
target_tag.activated = false
-- Update all indexes
for i=idx+1, #tags do
tag.setproperty(tags[i], "index", i-1)
end
-- If no tags are visible, try and view one.
if tag.selected(target_scr) == nil and ntags > 0 then
tag.history.restore(nil, 1)
if tag.selected(target_scr) == nil then
tags[tags[1] == target_tag and 2 or 1].selected = true
end
end
return true
end
--- Update the tag history.
-- @param obj Screen object.
function tag.history.update(obj)
local s = obj.index
local curtags = tag.selectedlist(s)
-- create history table
if not data.history[s] then
data.history[s] = {}
else
if data.history[s].current then
-- Check that the list is not identical
local identical = #data.history[s].current == #curtags
if identical then
for idx, _tag in ipairs(data.history[s].current) do
if curtags[idx] ~= _tag then
identical = false
break
end
end
end
-- Do not update history the table are identical
if identical then return end
end
-- Limit history
if #data.history[s] >= tag.history.limit then
for i = tag.history.limit, #data.history[s] do
data.history[s][i] = nil
end
end
end
-- store previously selected tags in the history table
table.insert(data.history[s], 1, data.history[s].current)
data.history[s].previous = data.history[s][1]
-- store currently selected tags
data.history[s].current = setmetatable(curtags, { __mode = 'v' })
end
--- Revert tag history.
-- @param screen The screen number.
-- @param idx Index in history. Defaults to "previous" which is a special index
-- toggling between last two selected sets of tags. Number (eg 1) will go back
-- to the given index in history.
function tag.history.restore(screen, idx)
local s = screen or ascreen.focused()
local i = idx or "previous"
local sel = tag.selectedlist(s)
-- do nothing if history empty
if not data.history[s] or not data.history[s][i] then return end
-- if all tags been deleted, try next entry
if #data.history[s][i] == 0 then
if i == "previous" then i = 0 end
tag.history.restore(s, i + 1)
return
end
-- deselect all tags
tag.viewnone(s)
-- select tags from the history entry
for _, t in ipairs(data.history[s][i]) do
t.selected = true
end
-- update currently selected tags table
data.history[s].current = data.history[s][i]
-- store previously selected tags
data.history[s].previous = setmetatable(sel, { __mode = 'v' })
-- remove the reverted history entry
if i ~= "previous" then table.remove(data.history[s], i) end
capi.screen[s]:emit_signal("tag::history::update")
end
--- Get a list of all tags on a screen
-- @param s Screen number
-- @return A table with all available tags
function tag.gettags(s)
local tags = {}
for i, t in ipairs(root.tags()) do
if tag.getscreen(t) == s then
table.insert(tags, t)
end
end
table.sort(tags, function(a, b)
return (tag.getproperty(a, "index") or 9999) < (tag.getproperty(b, "index") or 9999)
end)
return tags
end
--- Set a tag's screen
-- @param t tag object
-- @param s Screen number
function tag.setscreen(t, s)
local s = s or ascreen.focused()
local sel = tag.selected
local old_screen = tag.getproperty(t, "screen")
if s == old_screen then return end
-- Keeping the old index make very little sense when changing screen
tag.setproperty(t, "index", nil)
-- Change the screen
tag.setproperty(t, "screen", s)
-- Make sure the client's screen matches its tags
for k,c in ipairs(t:clients()) do
c.screen = s --Move all clients
c:tags({t})
end
-- Update all indexes
for _,screen in ipairs {old_screen, s} do
for i,t in ipairs(tag.gettags(screen)) do
tag.setproperty(t, "index", i)
end
end
-- Restore the old screen history if the tag was selected
if sel then
tag.history.restore(old_screen, 1)
end
end
--- Get a tag's screen
-- @param t tag object
-- @return Screen number
function tag.getscreen(t)
return tag.getproperty(t, "screen")
end
--- Return a table with all visible tags
-- @param s Screen number.
-- @return A table with all selected tags.
function tag.selectedlist(s)
local screen = s or ascreen.focused()
local tags = tag.gettags(screen)
local vtags = {}
for i, t in pairs(tags) do
if t.selected then
vtags[#vtags + 1] = t
end
end
return vtags
end
--- Return only the first visible tag.
-- @param s Screen number.
function tag.selected(s)
return tag.selectedlist(s)[1]
end
--- Set master width factor.
-- @param mwfact Master width factor.
-- @param t The tag to modify, if null tag.selected() is used.
function tag.setmwfact(mwfact, t)
local t = t or tag.selected()
if mwfact >= 0 and mwfact <= 1 then
tag.setproperty(t, "mwfact", mwfact)
end
end
--- Increase master width factor.
-- @param add Value to add to master width factor.
-- @param t The tag to modify, if null tag.selected() is used.
function tag.incmwfact(add, t)
tag.setmwfact(tag.getmwfact(t) + add, t)
end
--- Get master width factor.
-- @param[opt] t The tag.
function tag.getmwfact(t)
local t = t or tag.selected()
return tag.getproperty(t, "mwfact") or 0.5
end
--- Set the spacing between clients
-- @param useless_gap The spacing between clients
-- @param t The tag to modify, if null tag.selected() is used.
function tag.setgap(useless_gap, t)
local t = t or tag.selected()
if useless_gap >= 0 then
tag.setproperty(t, "useless_gap", useless_gap)
end
end
--- Increase the spacing between clients
-- @param add Value to add to the spacing between clients
-- @param t The tag to modify, if null tag.selected() is used.
function tag.incgap(add, t)
tag.setgap(tag.getgap(t) + add, t)
end
--- Get the spacing between clients
-- @param t Optional tag.
function tag.getgap(t)
local t = t or tag.selected()
return tag.getproperty(t, "useless_gap") or beautiful.useless_gap or 0
end
--- Set size fill policy for the master client(s)
-- @tparam string policy Can be set to
-- "expand" (fill all the available workarea) or
-- "mwfact" (fill only an area inside the master width factor)
-- @tparam[opt=tag.selected()] tag t The tag to modify
function tag.setmfpol(policy, t)
local t = t or tag.selected()
tag.setproperty(t, "master_fill_policy", policy)
end
--- Toggle size fill policy for the master client(s)
-- between "expand" and "mwfact"
-- @tparam tag t The tag to modify, if null tag.selected() is used.
function tag.togglemfpol(t)
if tag.getmfpol(t) == "expand" then
tag.setmfpol("mwfact", t)
else
tag.setmfpol("expand", t)
end
end
--- Get size fill policy for the master client(s)
-- @tparam[opt=tag.selected()] tag t The tag
-- @treturn string Possible values are
-- "expand" (fill all the available workarea, default one) or
-- "mwfact" (fill only an area inside the master width factor)
function tag.getmfpol(t)
local t = t or tag.selected()
return tag.getproperty(t, "master_fill_policy") or "expand"
end
--- Set the number of master windows.
-- @param nmaster The number of master windows.
-- @param[opt] t The tag.
function tag.setnmaster(nmaster, t)
local t = t or tag.selected()
if nmaster >= 0 then
tag.setproperty(t, "nmaster", nmaster)
end
end
--- Get the number of master windows.
-- @param[opt] t The tag.
function tag.getnmaster(t)
local t = t or tag.selected()
return tag.getproperty(t, "nmaster") or 1
end
--- Increase the number of master windows.
-- @param add Value to add to number of master windows.
-- @param t The tag to modify, if null tag.selected() is used.
function tag.incnmaster(add, t)
tag.setnmaster(tag.getnmaster(t) + add, t)
end
--- Set the tag icon
-- @param icon the icon to set, either path or image object
-- @param _tag the tag
function tag.seticon(icon, _tag)
local _tag = _tag or tag.selected()
tag.setproperty(_tag, "icon", icon)
end
--- Get the tag icon
-- @param _tag the tag
function tag.geticon(_tag)
local _tag = _tag or tag.selected()
return tag.getproperty(_tag, "icon")
end
--- Set number of column windows.
-- @param ncol The number of column.
-- @param t The tag to modify, if null tag.selected() is used.
function tag.setncol(ncol, t)
local t = t or tag.selected()
if ncol >= 1 then
tag.setproperty(t, "ncol", ncol)
end
end
--- Get number of column windows.
-- @param[opt] t The tag.
function tag.getncol(t)
local t = t or tag.selected()
return tag.getproperty(t, "ncol") or 1
end
--- Increase number of column windows.
-- @param add Value to add to number of column windows.
-- @param t The tag to modify, if null tag.selected() is used.
function tag.incncol(add, t)
tag.setncol(tag.getncol(t) + add, t)
end
--- View no tag.
-- @tparam[opt] int screen The screen number.
function tag.viewnone(screen)
local tags = tag.gettags(screen or ascreen.focused())
for i, t in pairs(tags) do
t.selected = false
end
end
--- View a tag by its taglist index.
-- @param i The relative index to see.
-- @param[opt] screen The screen number.
function tag.viewidx(i, screen)
local screen = screen or ascreen.focused()
local tags = tag.gettags(screen)
local showntags = {}
for k, t in ipairs(tags) do
if not tag.getproperty(t, "hide") then
table.insert(showntags, t)
end
end
local sel = tag.selected(screen)
tag.viewnone(screen)
for k, t in ipairs(showntags) do
if t == sel then
showntags[util.cycle(#showntags, k + i)].selected = true
end
end
capi.screen[screen]:emit_signal("tag::history::update")
end
--- Get a tag's index in the gettags() table.
-- @param query_tag The tag object to find. [selected()]
-- @return The index of the tag, nil if the tag is not found.
function tag.getidx(query_tag)
local query_tag = query_tag or tag.selected()
if query_tag == nil then return end
for i, t in ipairs(tag.gettags(tag.getscreen(query_tag))) do
if t == query_tag then
return i
end
end
end
--- View next tag. This is the same as tag.viewidx(1).
-- @param screen The screen number.
function tag.viewnext(screen)
return tag.viewidx(1, screen)
end
--- View previous tag. This is the same a tag.viewidx(-1).
-- @param screen The screen number.
function tag.viewprev(screen)
return tag.viewidx(-1, screen)
end
--- View only a tag.
-- @param t The tag object.
function tag.viewonly(t)
local tags = tag.gettags(tag.getscreen(t))
-- First, untag everyone except the viewed tag.
for _, _tag in pairs(tags) do
if _tag ~= t then
_tag.selected = false
end
end
-- Then, set this one to selected.
-- We need to do that in 2 operations so we avoid flickering and several tag
-- selected at the same time.
t.selected = true
capi.screen[tag.getscreen(t)]:emit_signal("tag::history::update")
end
--- View only a set of tags.
-- @param tags A table with tags to view only.
-- @param[opt] screen The screen number of the tags.
function tag.viewmore(tags, screen)
local screen = screen or ascreen.focused()
local screen_tags = tag.gettags(screen)
for _, _tag in ipairs(screen_tags) do
if not util.table.hasitem(tags, _tag) then
_tag.selected = false
end
end
for _, _tag in ipairs(tags) do
_tag.selected = true
end
capi.screen[screen]:emit_signal("tag::history::update")
end
--- Toggle selection of a tag
-- @tparam tag t Tag to be toggled
function tag.viewtoggle(t)
t.selected = not t.selected
capi.screen[tag.getscreen(t)]:emit_signal("tag::history::update")
end
--- Get tag data table.
-- @tparam tag _tag The tag.
-- @return The data table.
function tag.getdata(_tag)
return data.tags[_tag]
end
--- Get a tag property.
-- @tparam tag _tag The tag.
-- @tparam string prop The property name.
-- @return The property.
function tag.getproperty(_tag, prop)
if data.tags[_tag] then
return data.tags[_tag][prop]
end
end
--- Set a tag property.
-- This properties are internal to awful. Some are used to draw taglist, or to
-- handle layout, etc.
-- @param _tag The tag.
-- @param prop The property name.
-- @param value The value.
function tag.setproperty(_tag, prop, value)
if not data.tags[_tag] then
data.tags[_tag] = {}
end
if data.tags[_tag][prop] ~= value then
data.tags[_tag][prop] = value
_tag:emit_signal("property::" .. prop)
end
end
--- Tag a client with the set of current tags.
-- @param c The client to tag.
function tag.withcurrent(c)
local tags = {}
for k, t in ipairs(c:tags()) do
if tag.getscreen(t) == c.screen then
table.insert(tags, t)
end
end
if #tags == 0 then
tags = tag.selectedlist(c.screen)
end
if #tags == 0 then
tags = tag.gettags(c.screen)
end
if #tags ~= 0 then
c:tags(tags)
end
end
local function attached_connect_signal_screen(screen, sig, func)
capi.tag.connect_signal(sig, function(_tag, ...)
if tag.getscreen(_tag) == screen then
func(_tag)
end
end)
end
--- Add a signal to all attached tag and all tag that will be attached in the
-- future. When a tag is detach from the screen, its signal is removed.
-- @param screen The screen concerned, or all if nil.
function tag.attached_connect_signal(screen, ...)
if screen then
attached_connect_signal_screen(screen, ...)
else
capi.tag.connect_signal(...)
end
end
-- Register standard signals.
capi.client.connect_signal("manage", function(c)
-- If we are not managing this application at startup,
-- move it to the screen where the mouse is.
-- We only do it for "normal" windows (i.e. no dock, etc).
if not awesome.startup and c.type ~= "desktop" and c.type ~= "dock" then
if c.transient_for then
c.screen = c.transient_for.screen
if not c.sticky then
c:tags(c.transient_for:tags())
end
else
c.screen = ascreen.focused()
end
end
c:connect_signal("property::screen", tag.withcurrent)
end)
-- Keep track of the number of urgent clients.
local function update_urgent(c, t, modif)
local count = tag.getproperty(t, "urgent_count") or 0
count = (count + modif) >= 0 and (count + modif) or 0
tag.setproperty(t, "urgent" , count > 0)
tag.setproperty(t, "urgent_count", count )
end
-- Update the urgent counter when a client is tagged.
local function client_tagged(c, t)
if c.urgent then
update_urgent(c, t, 1)
end
end
-- Update the urgent counter when a client is untagged.
local function client_untagged(c, t)
if c.urgent then
update_urgent(c, t, -1)
end
end
-- Count the urgent clients.
local function urgent_callback(c)
for k,t in ipairs(c:tags()) do
update_urgent(c, t, c.urgent and 1 or -1)
end
end
capi.client.connect_signal("property::urgent", urgent_callback)
capi.client.connect_signal("manage", tag.withcurrent)
capi.client.connect_signal("untagged", client_untagged)
capi.client.connect_signal("tagged", client_tagged)
capi.tag.connect_signal("request::select", tag.viewonly)
capi.tag.add_signal("property::hide")
capi.tag.add_signal("property::icon")
capi.tag.add_signal("property::icon_only")
capi.tag.add_signal("property::layout")
capi.tag.add_signal("property::mwfact")
capi.tag.add_signal("property::useless_gap")
capi.tag.add_signal("property::master_fill_policy")
capi.tag.add_signal("property::ncol")
capi.tag.add_signal("property::nmaster")
capi.tag.add_signal("property::windowfact")
capi.tag.add_signal("property::screen")
capi.tag.add_signal("property::index")
capi.tag.add_signal("property::urgent")
capi.tag.add_signal("property::urgent_count")
capi.screen.add_signal("tag::history::update")
for s = 1, capi.screen.count() do
capi.screen[s]:connect_signal("tag::history::update", tag.history.update)
end
function tag.mt:__call(...)
return tag.new(...)
end
return setmetatable(tag, tag.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Halvung/npcs/qm1.lua | 11 | 1200 | -----------------------------------
-- Area: Halvung
-- NPC: ??? (Spawn Big Bomb)
-- @pos -233.830 13.613 286.714 62
-----------------------------------
package.loaded["scripts/zones/Halvung/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Halvung/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Smokey Flask
if(GetMobAction(17031401) == 0 and trade:hasItemQty(2384,1) and trade:getItemCount() == 1) then
player:tradeComplete();
SpawnMob(17031401,900):updateEnmity(player); -- Big Bomb
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(BLUE_FLAMES);
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 |
msburgess3200/PERP | gamemodes/perp/entities/weapons/weapon_perp_fire_extinguisher/shared.lua | 1 | 1975 |
if SERVER then
AddCSLuaFile("shared.lua")
end
if CLIENT then
SWEP.PrintName = "Fire Extinguisher"
SWEP.Slot = 2
SWEP.SlotPos = 1
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = false
end
SWEP.Author = "RedMist"
SWEP.Instructions = "Left Click: Extinguish Fires"
SWEP.Contact = ""
SWEP.Purpose = ""
SWEP.ViewModelFOV = 62
SWEP.ViewModelFlip = false
SWEP.Spawnable = false
SWEP.AdminSpawnable = true
SWEP.Primary.ClipSize = -1
SWEP.Primary.DefaultClip = 0
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = ""
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = 0
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = ""
SWEP.ViewModel = "models/weapons/v_fire_extinguisher.mdl";
SWEP.WorldModel = "models/perp2/w_fists.mdl";
SWEP.ShootSound = Sound("ambient/wind/wind_hit2.wav");
function SWEP:Initialize()
//if SERVER then
self:SetWeaponHoldType("normal")
//end
end
function SWEP:CanPrimaryAttack ( ) return true; end
function SWEP:PrimaryAttack()
if self:GetTable().LastNoise == nil then self:GetTable().LastNoise = true; end
if self:GetTable().LastNoise then
self.Weapon:EmitSound(self.ShootSound)
self:GetTable().LastNoise = false;
else
self:GetTable().LastNoise = true;
end
self.Weapon:SendWeaponAnim(ACT_VM_PRIMARYATTACK)
self.Weapon:SetNextPrimaryFire(CurTime() + .1)
if CLIENT or (SERVER) then
local ED = EffectData();
ED:SetEntity(self.Owner);
util.Effect('fire_extinguish', ED);
end
if SERVER then
local Trace2 = {};
Trace2.start = self.Owner:GetShootPos();
Trace2.endpos = self.Owner:GetShootPos() + self.Owner:GetAimVector() * 150;
Trace2.filter = self.Owner;
local Trace = util.TraceLine(Trace2);
local CloseEnts = ents.FindInSphere(Trace.HitPos, 50)
for k, v in pairs(CloseEnts) do
if v:GetClass() == 'ent_fire' then
v:HitByExtinguisher(self.Owner)
end
if v:IsOnFire() then v:Extinguish() end
end
end
end
function SWEP:SecondaryAttack()
self:PrimaryAttack();
end
| mit |
priderobot/titan | 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 |
MAHDIYAZDI001/mahdi | 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 |
FFXIOrgins/FFXIOrgins | 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 |
sjznxd/luci-0.11-aa | libs/web/luasrc/http/protocol/date.lua | 13 | 2801 | --[[
HTTP protocol implementation for LuCI - date handling
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: date.lua 3860 2008-12-06 03:18:14Z jow $
]]--
--- LuCI http protocol implementation - date helper class.
-- This class contains functions to parse, compare and format http dates.
module("luci.http.protocol.date", package.seeall)
require("luci.sys.zoneinfo")
MONTHS = {
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"
}
--- Return the time offset in seconds between the UTC and given time zone.
-- @param tz Symbolic or numeric timezone specifier
-- @return Time offset to UTC in seconds
function tz_offset(tz)
if type(tz) == "string" then
-- check for a numeric identifier
local s, v = tz:match("([%+%-])([0-9]+)")
if s == '+' then s = 1 else s = -1 end
if v then v = tonumber(v) end
if s and v then
return s * 60 * ( math.floor( v / 100 ) * 60 + ( v % 100 ) )
-- lookup symbolic tz
elseif luci.sys.zoneinfo.OFFSET[tz:lower()] then
return luci.sys.zoneinfo.OFFSET[tz:lower()]
end
end
-- bad luck
return 0
end
--- Parse given HTTP date string and convert it to unix epoch time.
-- @param data String containing the date
-- @return Unix epoch time
function to_unix(date)
local wd, day, mon, yr, hr, min, sec, tz = date:match(
"([A-Z][a-z][a-z]), ([0-9]+) " ..
"([A-Z][a-z][a-z]) ([0-9]+) " ..
"([0-9]+):([0-9]+):([0-9]+) " ..
"([A-Z0-9%+%-]+)"
)
if day and mon and yr and hr and min and sec then
-- find month
local month = 1
for i = 1, 12 do
if MONTHS[i] == mon then
month = i
break
end
end
-- convert to epoch time
return tz_offset(tz) + os.time( {
year = yr,
month = month,
day = day,
hour = hr,
min = min,
sec = sec
} )
end
return 0
end
--- Convert the given unix epoch time to valid HTTP date string.
-- @param time Unix epoch time
-- @return String containing the formatted date
function to_http(time)
return os.date( "%a, %d %b %Y %H:%M:%S GMT", time )
end
--- Compare two dates which can either be unix epoch times or HTTP date strings.
-- @param d1 The first date or epoch time to compare
-- @param d2 The first date or epoch time to compare
-- @return -1 - if d1 is lower then d2
-- @return 0 - if both dates are equal
-- @return 1 - if d1 is higher then d2
function compare(d1, d2)
if d1:match("[^0-9]") then d1 = to_unix(d1) end
if d2:match("[^0-9]") then d2 = to_unix(d2) end
if d1 == d2 then
return 0
elseif d1 < d2 then
return -1
else
return 1
end
end
| apache-2.0 |
FFXIOrgins/FFXIOrgins | scripts/globals/items/boiled_crayfish.lua | 35 | 1248 | -----------------------------------------
-- ID: 4535
-- Item: Boiled Crayfish
-- Food Effect: 30Min, All Races
-----------------------------------------
-- defense % 30
-- defense % 25
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4535);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_DEFP, 30);
target:addMod(MOD_FOOD_DEF_CAP, 25);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_DEFP, 30);
target:delMod(MOD_FOOD_DEF_CAP, 25);
end;
| gpl-3.0 |
m2mselect/owrt | feeds/luci/applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/tcpconns.lua | 68 | 1143 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
m = Map("luci_statistics",
translate("TCPConns Plugin Configuration"),
translate(
"The tcpconns plugin collects informations about open tcp " ..
"connections on selected ports."
))
-- collectd_tcpconns config section
s = m:section( NamedSection, "collectd_tcpconns", "luci_statistics" )
-- collectd_tcpconns.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_tcpconns.listeningports (ListeningPorts)
listeningports = s:option( Flag, "ListeningPorts", translate("Monitor all local listen ports") )
listeningports.default = 1
listeningports:depends( "enable", 1 )
-- collectd_tcpconns.localports (LocalPort)
localports = s:option( Value, "LocalPorts", translate("Monitor local ports") )
localports.optional = true
localports:depends( "enable", 1 )
-- collectd_tcpconns.remoteports (RemotePort)
remoteports = s:option( Value, "RemotePorts", translate("Monitor remote ports") )
remoteports.optional = true
remoteports:depends( "enable", 1 )
return m
| gpl-2.0 |
daofeng2015/luci | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/tcpconns.lua | 68 | 1143 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
m = Map("luci_statistics",
translate("TCPConns Plugin Configuration"),
translate(
"The tcpconns plugin collects informations about open tcp " ..
"connections on selected ports."
))
-- collectd_tcpconns config section
s = m:section( NamedSection, "collectd_tcpconns", "luci_statistics" )
-- collectd_tcpconns.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_tcpconns.listeningports (ListeningPorts)
listeningports = s:option( Flag, "ListeningPorts", translate("Monitor all local listen ports") )
listeningports.default = 1
listeningports:depends( "enable", 1 )
-- collectd_tcpconns.localports (LocalPort)
localports = s:option( Value, "LocalPorts", translate("Monitor local ports") )
localports.optional = true
localports:depends( "enable", 1 )
-- collectd_tcpconns.remoteports (RemotePort)
remoteports = s:option( Value, "RemotePorts", translate("Monitor remote ports") )
remoteports.optional = true
remoteports:depends( "enable", 1 )
return m
| apache-2.0 |
m2mselect/owrt | feeds/luci/modules/luci-mod-admin-mini/luasrc/model/cbi/mini/luci.lua | 76 | 1122 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
require "luci.config"
local fs = require "nixio.fs"
m = Map("luci", translate("Web <abbr title=\"User Interface\">UI</abbr>"), translate("Here you can customize the settings and the functionality of <abbr title=\"Lua Configuration Interface\">LuCI</abbr>."))
-- force reload of global luci config namespace to reflect the changes
function m.commit_handler(self)
package.loaded["luci.config"] = nil
require "luci.config"
end
c = m:section(NamedSection, "main", "core", translate("General"))
l = c:option(ListValue, "lang", translate("Language"))
l:value("auto")
local i18ndir = luci.i18n.i18ndir .. "base."
for k, v in luci.util.kspairs(luci.config.languages) do
local file = i18ndir .. k:gsub("_", "-")
if k:sub(1, 1) ~= "." and fs.access(file .. ".lmo") then
l:value(k, v)
end
end
t = c:option(ListValue, "mediaurlbase", translate("Design"))
for k, v in pairs(luci.config.themes) do
if k:sub(1, 1) ~= "." then
t:value(v, k)
end
end
return m
| gpl-2.0 |
fartoverflow/naev | dat/missions/sirius/heretic/heretic4.lua | 4 | 7247 | --[[misn title - the egress]]
--[[this mission begins with the frenetic nasin wanting to escape
the wringer due to being overwhelmed by house sirius. the player
loads up with as many nasin as their vessel will carry, and takes
them to seek refuge in the ingot system on planet ulios, where they
begin to rebuild and plan.... (ominous music).
this mission is designed to be the end of part 1, and is supposed
to be very hard, and slightly combat oriented, but more supposed to
involve smuggling elements.]]
lang = naev.lang()
--beginning messages
bmsg = {}
bmsg[1] = [[You run up to Draga, who has a look of desperation on his face. He talks to you with more than a hint of urgency.
"We need to go, now. The Sirius are overwhelming us, they're about to finish us off. Will you take me and as many Nasin as you can carry to %s in %s? I swear, if you abort this and jettison those people into space, I will hunt you down and destroy you."]]
bmsg[2] = [[You lead Draga out of the bar and into your landing bay. Refugees are milling about, hoping to get aboard some ship or another. Draga asks you what your tonnage is, and begins directing people on board. Panic erupts when gunfire breaks out on the far end of the bay.]]
bmsg[3] = [[As the gunfire gets nearer, Draga yells at you to get the ship going and take off. As you get in the cabin and begin rising into the air you see Draga running back into the bay to help a woman run with her children to a small inter-planetary skiff. Some Sirius soldiers run and catch up with him, giving him three shots in the chest. The last thing you see as you take off was Draga in a pool of blood, and the woman being dragged off by the soldiers. You rocket out of there, and begin prepping to get those people to safety.]]
--ending messages
emsg = {}
emsg[1] = [[You land on %s, and open the bay doors. You are amazed at how many people Draga had helped get into the cargo hold. You help out the last few people, who are grateful to you, and walk down into the bay. A man walks up to you.]]
emsg[2] = [[The man offers his hand, and begins to speak.
"Hello, my name is Jimmy. Thank you for helping all these people." He gestures to the refugees, who are being helped by some officials. "I am grateful. I've heard about you, from Draga, and I will be forever in your debt. All I can manage right now is this, so consider me in your debt."
He presses a credit chip in your hand, and walks away to help some refugees.]]
--mission osd
osd = {}
osd[1] = "Fly the refugees to %s in the %s system."
--random odds and ends
abort_msg = [[You decide that this mission is just too much. You open up the cargo doors and jettison the %d people out into the cold emptiness of space. The Nasin, and the Sirius, will hate you forever, but you did what you had to do.]]
misn_title = "The Egress"
npc_name = "Draga"
bar_desc = "Draga is running around, helping the few Nasin in the bar to get stuff together and get out."
misn_desc = "Assist the Nasin refugees by flying to %s in %s, and unloading them there."
function create()
--this mission make no system claims.
--initalize your variables
nasin_rep = faction.playerStanding("Nasin")
misn_tracker = var.peek("heretic_misn_tracker")
reward = math.floor((10000+(math.random(5,8)*200)*(nasin_rep^1.315))*.01+.5)/.01
homeasset = planet.cur()
targetasset, targetsys = planet.get("Ulios") --this will be the new HQ for the nasin in the next part.
free_cargo = player.pilot():cargoFree()
people_carried = (16 * free_cargo) + 7 --average weight per person is 62kg. one ton / 62 is 16. added the +7 for ships with 0 cargo.
--set some mission stuff
misn.setNPC(npc_name,"neutral/thief2")
misn.setDesc(bar_desc)
misn.setTitle = misn_title
misn.setReward = reward
osd[1] = osd[1]:format(targetasset:name(),targetsys:name())
end
function accept()
--inital convo. Kept it a yes no to help with the urgent feeling of the situation.
local msg = bmsg[1]:format( targetasset:name(), targetsys:name() )
if not tk.yesno(misn_title, msg) then
misn.finish ()
end
misn.accept()
misn.setDesc(misn_desc:format( targetasset:name(), targetsys:name()))
misn.osdCreate(misn_title,osd)
misn.osdActive(1)
player.allowSave(false) -- so the player won't get stuck with a mission he can't complete.
tk.msg(misn_title,bmsg[2])
tk.msg(misn_title,bmsg[3])
--convo over. time to finish setting the mission stuff.
misn.markerAdd(targetsys,"plot")
refugees = misn.cargoAdd("Refugees",free_cargo)
player.takeoff()
--get the hooks.
hook.takeoff("takeoff")
hook.jumpin("attacked")
hook.jumpout("lastsys")
hook.land("misn_over")
end
function takeoff()
pilot.add("Sirius Assault Force",sirius,vec2.new(rnd.rnd(-450,450),rnd.rnd(-450,450))) --left over fleets from the prior mission.
pilot.add("Sirius Assault Force",sirius,vec2.new(rnd.rnd(-450,450),rnd.rnd(-450,450)))
pilot.add("Sirius Assault Force",sirius,vec2.new(rnd.rnd(-450,450),rnd.rnd(-450,450)))
pilot.add("Nasin Sml Civilian",nil,homeasset) --other escapees.
pilot.add("Nasin Sml Civilian",nil,homeasset)
pilot.add("Nasin Sml Civilian",nil,homeasset)
pilot.add("Nasin Sml Attack Fleet",nil,homeasset) --these are trying to help.
pilot.add("Nasin Sml Attack Fleet",nil,homeasset)
end
function lastsys()
last_sys_in = system.cur()
end
function attacked() --several systems where the sirius have 'strategically placed' an assault fleet to try and kill some nasin.
dangersystems = {
system.get("Neon"),
system.get("Pike"),
system.get("Vanir"),
system.get("Aesir"),
system.get("Herakin"),
system.get("Eiderdown"),
system.get("Eye of Night"),
system.get("Lapis"),
system.get("Ruttwi"),
system.get("Esker"),
system.get("Gutter")
}
for i,sys in ipairs(dangersystems) do
if system.cur() == sys then
pilot.add("Sirius Assault Force",sirius,vec2.new(rnd.rnd(-300,300),rnd.rnd(-300,300)))
end
end
local chance_help,chance_civvie = rnd.rnd(1,3),rnd.rnd(1,3) --attack fleet and civvies are meant as a distraction to help the player.
if chance_help == 1 then
pilot.add("Nasin Sml Attack Fleet",nil,last_sys_in)
end
for i = 1,chance_civvie do
pilot.add("Nasin Sml Civilian",nil,last_sys_in)
end
end
function misn_over() --arent you glad thats over?
if planet.cur() == planet.get("Ulios") then
--introing one of the characters in the next chapter.
tk.msg(misn_title,emsg[1]:format( targetasset:name() ))
tk.msg(misn_title,emsg[2])
player.pay(reward)
misn.cargoRm(refugees)
misn_tracker = misn_tracker + 1
faction.modPlayer("Nasin",8) --big boost to the nasin, for completing the prologue
faction.modPlayer("Sirius",-5) --the sirius shouldn't like you. at all.
var.push("heretic_misn_tracker",misn_tracker)
misn.osdDestroy()
player.allowSave(true)
misn.finish(true)
end
end
function abort()
tk.msg(misn_title,abort_msg)
var.push("heretic_misn_tracker",-1) --if the player jettisons the peeps, the nasin will not let the player join there ranks anymore.
misn.osdDestroy()
player.allowSave(true)
misn.finish(true)
end
| gpl-3.0 |
mohtamohit/CppSharp | build/LLVM.lua | 1 | 4776 | -- Setup the LLVM dependency directories
LLVMRootDir = depsdir .. "/llvm/"
local LLVMDirPerConfiguration = false
local LLVMRootDirDebug = ""
local LLVMRootDirRelease = ""
require "scripts/LLVM"
function SearchLLVM()
LLVMRootDirDebug = basedir .. "/scripts/" .. get_llvm_package_name(nil, "Debug")
LLVMRootDirRelease = basedir .. "/scripts/" .. get_llvm_package_name()
if os.isdir(LLVMRootDirDebug) or os.isdir(LLVMRootDirRelease) then
LLVMDirPerConfiguration = true
print("Using debug LLVM build: " .. LLVMRootDirDebug)
print("Using release LLVM build: " .. LLVMRootDirRelease)
elseif os.isdir(LLVMRootDir) then
print("Using LLVM build: " .. LLVMRootDir)
else
error("Error finding an LLVM build")
end
end
function get_llvm_build_dir()
local packageDir = path.join(LLVMRootDir, get_llvm_package_name())
local buildDir = path.join(LLVMRootDir, "build")
if os.isdir(buildDir) then
return buildDir
else
return packageDir
end
end
function SetupLLVMIncludes()
local c = filter()
if LLVMDirPerConfiguration then
filter { "configurations:Debug" }
includedirs
{
path.join(LLVMRootDirDebug, "include"),
path.join(LLVMRootDirDebug, "tools/clang/include"),
path.join(LLVMRootDirDebug, "tools/clang/lib"),
path.join(LLVMRootDirDebug, "build/include"),
path.join(LLVMRootDirDebug, "build/tools/clang/include"),
}
filter { "configurations:Release" }
includedirs
{
path.join(LLVMRootDirRelease, "include"),
path.join(LLVMRootDirRelease, "tools/clang/include"),
path.join(LLVMRootDirRelease, "tools/clang/lib"),
path.join(LLVMRootDirRelease, "build/include"),
path.join(LLVMRootDirRelease, "build/tools/clang/include"),
}
else
local LLVMBuildDir = get_llvm_build_dir()
includedirs
{
path.join(LLVMRootDir, "include"),
path.join(LLVMRootDir, "tools/clang/include"),
path.join(LLVMRootDir, "tools/clang/lib"),
path.join(LLVMBuildDir, "include"),
path.join(LLVMBuildDir, "tools/clang/include"),
}
end
filter(c)
end
function CopyClangIncludes()
local clangBuiltinIncludeDir = path.join(LLVMRootDir, "lib")
if LLVMDirPerConfiguration then
local clangBuiltinDebug = path.join(LLVMRootDirDebug, "lib")
local clangBuiltinRelease = path.join(LLVMRootDirRelease, "lib")
if os.isdir(path.join(clangBuiltinDebug, "clang")) then
clangBuiltinIncludeDir = clangBuiltinDebug
end
if os.isdir(path.join(clangBuiltinRelease, "clang")) then
clangBuiltinIncludeDir = clangBuiltinRelease
end
end
if os.isdir(clangBuiltinIncludeDir) then
postbuildcommands { string.format("{COPY} %s %%{cfg.buildtarget.directory}", clangBuiltinIncludeDir) }
end
end
function SetupLLVMLibs()
local c = filter()
filter { "action:not vs*" }
defines { "__STDC_CONSTANT_MACROS", "__STDC_LIMIT_MACROS" }
filter { "system:macosx" }
links { "c++", "curses", "pthread", "z" }
filter { "action:vs*" }
links { "version" }
filter {}
if LLVMDirPerConfiguration then
filter { "configurations:Debug" }
libdirs { path.join(LLVMRootDirDebug, "build/lib") }
filter { "configurations:Release" }
libdirs { path.join(LLVMRootDirRelease, "build/lib") }
else
local LLVMBuildDir = get_llvm_build_dir()
libdirs { path.join(LLVMBuildDir, "lib") }
filter { "configurations:Debug", "action:vs*" }
libdirs { path.join(LLVMBuildDir, "Debug/lib") }
filter { "configurations:Release", "action:vs*" }
libdirs { path.join(LLVMBuildDir, "RelWithDebInfo/lib") }
end
filter {}
links
{
"clangFrontend",
"clangDriver",
"clangSerialization",
"clangCodeGen",
"clangParse",
"clangSema",
"clangAnalysis",
"clangEdit",
"clangAST",
"clangLex",
"clangBasic",
"clangIndex",
"LLVMLinker",
"LLVMipo",
"LLVMVectorize",
"LLVMBitWriter",
"LLVMIRReader",
"LLVMAsmParser",
"LLVMOption",
"LLVMInstrumentation",
"LLVMProfileData",
"LLVMX86AsmParser",
"LLVMX86Desc",
"LLVMObject",
"LLVMMCParser",
"LLVMBitReader",
"LLVMX86Info",
"LLVMX86AsmPrinter",
"LLVMX86Utils",
"LLVMX86CodeGen",
"LLVMX86Disassembler",
"LLVMCodeGen",
"LLVMSelectionDAG",
"LLVMGlobalISel",
"LLVMDebugInfoCodeView",
"LLVMScalarOpts",
"LLVMInstCombine",
"LLVMTransformUtils",
"LLVMAnalysis",
"LLVMTarget",
"LLVMMCDisassembler",
"LLVMMC",
"LLVMCoverage",
"LLVMCore",
"LLVMSupport",
"LLVMBinaryFormat",
"LLVMDemangle"
}
filter(c)
end
| mit |
FFXIOrgins/FFXIOrgins | scripts/zones/Mine_Shaft_2716/Zone.lua | 32 | 1656 | -----------------------------------
--
-- Zone: Mine_Shaft_2716 (13)
--
-----------------------------------
package.loaded["scripts/zones/Mine_Shaft_2716/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Mine_Shaft_2716/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-116.599,-122.103,-620.01,253);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
msburgess3200/PERP | gamemodes/perp/gamemode/npcs/car_garage.lua | 1 | 2556 |
local NPC = {};
NPC.Name = "Garage";
NPC.ID = 5;
NPC.Model = Model("models/players/perp2/f_1_02.mdl");
NPC.Invisible = false; // Used for ATM Machines, Casino Tables, etc.
NPC.Location = {Vector(-5317.2427, -10296.3262, 71.0313), Vector(5320.523926, -4728.700195, 128.031250 - 63)};
NPC.Angles = {Angle(0, 0, 0), Angle(0,90,0)};
NPC.ShowChatBubble = "Normal";
NPC.Sequence = 228;
// This is always local player.
function NPC.OnTalk ( )
GAMEMODE.DialogPanel:SetDialog("Can I help you?");
if (LocalPlayer():Team() == TEAM_CITIZEN) then
GAMEMODE.DialogPanel:AddDialog("Yes, I've come to claim my car.", NPC.ClaimCar)
GAMEMODE.DialogPanel:AddDialog("I want to change cars, please.", NPC.NewCar)
GAMEMODE.DialogPanel:AddDialog("I think I'm lost...", LEAVE_DIALOG)
else
GAMEMODE.DialogPanel:AddDialog("No.", LEAVE_DIALOG)
end
GAMEMODE.DialogPanel:Show();
end
function NPC.NewCar ( )
GAMEMODE.ShowGarageView();
LEAVE_DIALOG();
end
function NPC.ClaimCar ( )
local CarID = LocalPlayer():GetLastCar();
//LocalPlayer():Notify(""..CarID.."");
if LocalPlayer():GetLastCar() == 0 or LocalPlayer():GetLastCar() == nil or LocalPlayer():GetLastCar() == "" then
GAMEMODE.DialogPanel:SetDialog("It doesn't seem like you were in a car recently.\n(Use Change cars menu or buy a car.)");
GAMEMODE.DialogPanel:AddDialog("Hmm, ok then.", LEAVE_DIALOG)
else
RunConsoleCommand('perp_v_c', CarID);
LEAVE_DIALOG();
end
end
function NPC.DoFuel ( )
local CarID = tostring(LocalPlayer():GetLastCar());
if LocalPlayer():GetCash() < 50 then
GAMEMODE.DialogPanel:SetDialog("It seems you don't have enough cash on you.");
GAMEMODE.DialogPanel:AddDialog("Damn, I will be back when I get the cash.", LEAVE_DIALOG)
else
LocalPlayer():TakeCash(50);
RunConsoleCommand('perp_c_c', 50);
RunConsoleCommand('perp_v_c', CarID);
GAMEMODE.DialogPanel:AddDialog("", LEAVE_DIALOG)
end
end
function NPC.DoFix ( )
local CarID = tostring(LocalPlayer():GetLastCar());
if LocalPlayer():GetCash() < 2000 then
GAMEMODE.DialogPanel:SetDialog("It seems you don't have enough cash on you.");
GAMEMODE.DialogPanel:AddDialog("Damn, I will be back when I get the cash.", LEAVE_DIALOG);
else
RunConsoleCommand('perp_c_c', 2000);
LocalPlayer():SetCarState(0);
LocalPlayer():TakeCash(2000);
RunConsoleCommand('perp_v_c', CarID);
GAMEMODE.DialogPanel:AddDialog("", LEAVE_DIALOG);
end
end
GAMEMODE:LoadNPC(NPC);
function MiniDebug(Ply, Cmd, Args)
print (LocalPlayer():GetLastCar())
end
concommand.Add("perp_lastcar_debug", MiniDebug) | mit |
sjznxd/luci-0.11-aa | libs/web/luasrc/config.lua | 13 | 1115 | --[[
LuCI - Configuration
Description:
Some LuCI configuration values read from uci file "luci"
FileId:
$Id: config.lua 3856 2008-12-05 15:36:44Z Cyrus $
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local util = require "luci.util"
module("luci.config",
function(m)
if pcall(require, "luci.model.uci") then
local config = util.threadlocal()
setmetatable(m, {
__index = function(tbl, key)
if not config[key] then
config[key] = luci.model.uci.cursor():get_all("luci", key)
end
return config[key]
end
})
end
end)
| apache-2.0 |
SharpWoW/DungeonDan | Main.lua | 1 | 3951 | --[[
* Copyright (c) 2012 by Adam Hellberg <private@f16gaming.com> and Bjørn Tore Håvie <itsbth@itsbth.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR
* A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--]]
local Name, T = ...
T.Name = Name
T.Version = GetAddOnMetadata(Name, "Version")
local Dan = nil
function T:OnLoad()
self:LoadSavedVars()
self.Loaded = true
if self.Settings.Debug then
DungeonDanDebug = self
end
end
function T:LoadSavedVars()
if type(_G.DUNGEONDAN) ~= "table" then
_G.DUNGEONDAN = {}
end
self.Global = _G.DUNGEONDAN
if type(self.Global.Settings) ~= "table" then
self.Global.Settings = {}
end
self.Settings = self.Global.Settings
if type(self.Settings.Debug) ~= "boolean" then
self.Settings.Debug = false
end
end
function T.Events.ADDON_LOADED(self, event, ...)
if (select(1, ...)) == Name then
self:OnLoad()
end
end
function T.Events.PLAYER_ENTERING_WORLD(self, event, ...)
if Dan then return end
self:CreateDan()
Dan = self.Dan
local f = CreateFrame("Frame")
f.t = 0
f:SetScript("OnUpdate", function(s,e)
s.t = s.t + e
if s.t >= 2 then
s:SetScript("OnUpdate", nil)
Dan:ResetModelSettings()
Dan:DoAction(Dan.Actions.Welcome, true)
end
end)
-- Register callbacks on boss mod, if any
local function bossKill()
Dan:DoAction(Dan.Actions.BossKill)
end
local function bossWipe()
Dan:DoAction(Dan.Actions.BossWipe)
end
if DBM then
DBM:RegisterCallback("kill", bossKill)
DBM:RegisterCallback("wipe", bossWipe)
elseif DXE then
DXE.RegisterCallback(T, "DXECallback", bossKill)
elseif BigWigs then
T.Events.CHAT_MSG_ADDON = function(s, e, prefix, message, type, sender)
if prefix ~= "BigWigs" then return end
local sync, rest = select(3, message:find("(%S+)%s*(.*)$"))
if sync ~= "Death" then return end
bossKill()
end
else -- LibBossIDs
local lib = LibStub:GetLibrary("LibBossIDs-1.0", true)
T.Events.COMBAT_LOG_EVENT_UNFILTERED = function(s, e, ...)
local _, event = ...
if event ~= "PARTY_KILL" then return end
local id = tonumber((select(8, ...)):sub(6, 10), 16)
if lib.BossIDs[id] then bossKill() end
end
end
end
function T.Events.LFG_PROPOSAL_SHOW(self, event, ...)
Dan:DoAction(Dan.Actions.DungeonReady, true)
end
function T.Events.LFG_PROPOSAL_FAILED(self, event, ...)
Dan:StopAction()
end
function T.Events.LFG_PROPOSAL_SUCCEEDED(self, event, ...)
Dan:StopAction()
end
local validEvents = {
"SPELL_DAMAGE",
"SPELL_PERIODIC_DAMAGE",
"SPELL_BUILDING_DAMAGE",
"RANGE_DAMAGE"
}
local function IsValidEvent(event)
for _,v in pairs(validEvents) do
if event == v then return true end
end
return false
end
function T.Events.COMBAT_LOG_EVENT_UNFILTERED(self, event, ...)
local _, event, _, _, _, _, _, _, destName = ...
if destName ~= UnitName("player") then return end
if IsValidEvent(event) then
local id = (select(12, ...))
if self.AoeSpells[tostring(id)] then Dan:DoAction(Dan.Actions.AoeDamage) end
end
end
| mit |
sjznxd/luci-0.11-aa | applications/luci-ntpc/luasrc/model/cbi/ntpc/ntpcmini.lua | 6 | 1185 | --[[
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: ntpcmini.lua 9558 2012-12-18 13:58:22Z jow $
]]--
require("luci.tools.webadmin")
m = Map("ntpclient", translate("Time Synchronisation"), translate("Synchronizes the system time"))
s = m:section(TypedSection, "ntpclient", translate("General"))
s.anonymous = true
s.addremove = false
s:option(DummyValue, "_time", translate("Current system time")).value = os.date("%c")
interval = s:option(Value, "interval", translate("Update interval (in seconds)"))
interval.datatype = "and(uinteger,min(1))"
interval.rmempty = true
s3 = m:section(TypedSection, "ntpserver", translate("Time Server"))
s3.anonymous = true
s3.addremove = true
s3.template = "cbi/tblsection"
s3:option(Value, "hostname", translate("Hostname"))
port = s3:option(Value, "port", translate("Port"))
port.datatype = "port"
port.rmempty = true
return m
| apache-2.0 |
POPHUP/maroonhost | bot/TMP_bot.lua | 5 | 9558 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '3'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
------- Don't process outgoing messages
--------------------------- Self Bot By @ali_ghoghnoos
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
-- print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = ''
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"tagall",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"save",
"get",
"broadcast",
"download_media",
"invite",
"all",
"leave_ban",
"admin",
"plugins",
"admin",
"calc",
"dl",
"up",
"echo",
"echoset",
"echoget",
"feedback",
"filtering",
"getplug",
"google",
"help",
"id",
"info",
"lock_ads",
"lock_badword",
"lock_chat",
"lock_eng",
"lock_sticker",
"lock_tag",
"me",
"plugins",
"qrcode",
"share",
"tex",
"version",
"welcome",
"set_type"
},
sudo_users = {100577715},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
text1 = [[
]],
text2 = [[
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(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
-- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
--
--
-- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
-- ||\\ //|| //\\ || //|| //\\ // || || //
-- || \\ // || // \\ || // || // \\ // || || //
-- || \\ // || // \\ || // || // \\ || || || //
-- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || //
-- || \\ // || // \\ || // || // \\ || || || || \\
-- || \\ // || // \\ || // || // \\ \\ || || || \\
-- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\
--
--
-- ||-_-_-_- || || || //-_-_-_-_-_-
-- || || || || || //
-- ||_-_-_|| || || || //
-- || || || || \\
-- || || \\ // \\
-- || || \\ // //
-- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-//
--
--By @ali_ghoghnoos
--@telemanager_ch
| gpl-2.0 |
FFXIOrgins/FFXIOrgins | scripts/zones/Lower_Delkfutts_Tower/npcs/_545.lua | 9 | 1594 | -----------------------------------
-- Area: Lower Delkfutt's Tower
-- NPC: Cermet Door
-- Notes: Involved in Missions: THREE_PATHS
-----------------------------------
package.loaded["scripts/zones/Lower_Delkfutts_Tower/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Lower_Delkfutts_Tower/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 6 and player:hasKeyItem(DELKFUTT_RECOGNITION_DEVICE))then
SpawnMob(17531121,180):updateEnmity(player);
elseif(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 7 and player:hasKeyItem(DELKFUTT_RECOGNITION_DEVICE))then
player:startEvent(0x0019);
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)
--print("CSID:",csid);
--print("RESULT:",option);
if(csid == 0x0019)then
player:setVar("COP_Tenzen_s_Path",8);
end
end; | gpl-3.0 |
fartoverflow/naev | dat/missions/shark/sh07_pirates.lua | 1 | 9225 | --[[
This is the climax mission of the Shark's teeth campaign. The player has to kill 4 pirates.
Stages :
0) There are pirates to kill
1) Way to Alteris
--]]
--Needed scripts
include "pilot/pirate.lua"
include "numstring.lua"
lang = naev.lang()
if lang == "es" then
else -- default english
title = {}
text = {}
osd_msg = {}
npc_desc = {}
bar_desc = {}
title[1] = "The mission"
text[1] = [["Hello again, "says Smith. "As you know, I've agreed with the FLF on a contract that will make it possible for Nexus to sell them hundreds of "Shark" light fighters. This income will easily make up for the losses due to the partial replacement of the "Shark" by drones in the Imperial fleet.
Of course, this transaction must remain a secret. Even the head of the FLF thinks that we are working for an outlaw organization instead of a multi-stellar company. We are going to create a sales subsidiary on a pirate world so nobody will find out who really is behind this deal.
But, as you know, the pirate worlds are the territory of the "Skulls and Bones", the outlaw shipyard that makes copies of legal ships and sells it to pirates. If they discover our project, they will do everything to destroy us. That's why we need to make the first move: the Skulls and Bones use four major hitmen, who are also pirates. I want you to kill these four pirates in order to show the S&B that they can't win against us. I think it's the safest way to do what we have to do. Of course, there is a bounty on each of their heads.
Are you in?"]]
refusetitle = "Sorry, not interested"
refusetext = [["Ok, too bad, you are the only one I can trust for this job. Don't hesitate to come back if you change your mind."]]
title[2] = "Very good"
text[2] = [["So, here are the details: %s is around %s, flying his Gawain: he is taking undercover holidays, spending all the money he has stolen from traders. %s is in %s and %s is around %s with his Kestrel. Be careful, they have escorts. %s is in %s with his fearsome stolen Goddard and his escort.
Come back when you have finished: I will give you your bounties."]]
title[3] = "Well done!"
text[3] = [[This one will never get in our way again.]]
title[4] = "Mission accomplished"
text[4] = "You have killed the four pirates: Adam Smith is probably waiting for you in %s with lots of money."
title[5] = "That was impressive"
text[5] = [[As you land, Smith is already there."Thank your actions, I managed to create the sales subsidiary and I think nobody will prevent us anymore from selling Sharks. It was very nice to work with you. Here is your bounty. Good luck in the future."]]
-- Mission details
misn_title = "The Last Detail"
misn_reward = "%s credits"
misn_desc = "Nexus Shipyard asked you to kill 4 pirates"
-- NPC
npc_desc[1] = "Arnold Smith"
bar_desc[1] = [[Smith has probably a mission for you that implies "fixing a detail" as he says.]]
-- OSD
osd_title = "The Last Detail"
osd_msg[1] = "Kill the four pirates"
osd_msg[2] = "Report back to %s in %s"
end
function create ()
--Change here to change the planets and the systems
--sadly, I didn't manage to figure out how to pick random systems :(
gawsys = system.get("Tau Prime")
kersys1 = system.get("Gamel")
kersys2 = system.get("Khaas")
godsys = system.get("Treacle")
pplname = "Darkshed"
psyname = "Alteris"
paysys = system.get(psyname)
paypla = planet.get(pplname)
if not misn.claim(gawsys) and misn.claim(kersys1) and misn.claim(kersys2) and misn.claim(godsys) then
misn.finish(false)
end
misn.setNPC(npc_desc[1], "neutral/male1")
misn.setDesc(bar_desc[1])
end
function accept()
reward = 4000000
stage = 0
--Initialization of dead pirate memory
gawdead = false
kerdead1 = false
kerdead2 = false
goddead = false
--set the names of the pirates
gawname = pirate_name()
kername1 = pirate_name()
while kername1 == gawname do --That's not beautyfull, but it works...
--I don't want 2 pirates to have the same name
kername1 = pirate_name()
end
kername2 = pirate_name()
while kername2 == gawname or kername2 == kername1 do
kername2 = pirate_name()
end
godname = pirate_name()
while godname == gawname or godname == kername1 or godname == kername2 do
godname = pirate_name()
end
if tk.yesno(title[1], text[1]) then
misn.accept()
tk.msg(title[2], text[2]:format(gawname,gawsys:name(),kername1,kersys1:name(),kername2,kersys2:name(),godname,godsys:name()))
osd_msg[2] = osd_msg[2]:format(pplname,psyname)
misn.setTitle(misn_title)
misn.setReward(misn_reward:format(numstring(reward)))
misn.setDesc(misn_desc)
misn.osdCreate(misn_title, osd_msg)
gawmarker = misn.markerAdd(gawsys, "low")
kermarker1 = misn.markerAdd(kersys1, "high")
kermarker2 = misn.markerAdd(kersys2, "high")
godmarker = misn.markerAdd(godsys, "high")
enterhook = hook.enter("enter")
landhook = hook.land("land")
else
tk.msg(refusetitle, refusetext)
misn.finish(false)
end
end
function land()
--Job is done
if stage == 1 and planet.cur() == planet.get("Darkshed") then
tk.msg(title[5], text[5])
player.pay(reward)
misn.finish(true)
end
end
function enter()
if system.cur() == gawsys and gawdead == false then --The Gawain
baddie = pilot.addRaw( "Gawain","dummy", nil, "Dummy" )[1]
baddie:rename(gawname)
baddie:setHostile()
baddie:setHilight()
baddie:control()
--The pirate becomes nice defensive outfits
baddie:rmOutfit("all")
baddie:rmOutfit("cores")
baddie:addOutfit("S&K Ultralight Stealth Plating")
baddie:addOutfit("Milspec Aegis 2201 Core System")
baddie:addOutfit("Tricon Zephyr Engine")
baddie:addOutfit("Shield Capacitor",2)
baddie:addOutfit("Small Shield Booster")
baddie:addOutfit("Milspec Scrambler")
baddie:addOutfit("Laser Cannon MK3",2)
hook.pilot(baddie, "idle", "idle")
hook.pilot(baddie, "attacked", "attacked")
hook.pilot( baddie, "death", "gawain_dead" )
idle()
elseif system.cur() == kersys1 and kerdead1 == false then --The Kestrel
pilot.clear()
pilot.toggleSpawn(false)
baddie = pilot.add( "Pirate Kestrel", nil, vec2.new(0,0))[1]
ancestor = pilot.add( "Pirate Ancestor", nil, vec2.new(100,0))[1]
hyena = pilot.add( "Pirate Hyena", nil, vec2.new(0,100))[1]
baddie:rename(kername1)
baddie:setHilight()
baddie:setHostile()
hook.pilot( baddie, "death", "kestrel_dead1")
elseif system.cur() == kersys2 and kerdead2 == false then --The Kestrel
pilot.clear()
pilot.toggleSpawn(false)
baddie = pilot.add( "Pirate Kestrel", nil, vec2.new(0,0))[1]
ancestor = pilot.add( "Pirate Ancestor", nil, vec2.new(100,0))[1]
shark = pilot.add( "Pirate Shark", nil, vec2.new(0,100))[1]
hyena = pilot.add( "Pirate Hyena", nil, vec2.new(100,100))[1]
baddie:rename(kername2)
baddie:setHilight()
baddie:setHostile()
hook.pilot( baddie, "death", "kestrel_dead2")
elseif system.cur() == godsys and goddead == false then --The Goddard
pilot.clear()
pilot.toggleSpawn(false)
baddie = pilot.add( "Goddard Goddard", nil, vec2.new(0,0))[1] --Faction's ships come up with upgraded weaponry
baddie:setFaction("Pirate")
baddie:changeAI( "pirate" )
ancestor = pilot.add( "Pirate Ancestor", nil, vec2.new(100,0))[1]
hyena = pilot.add( "Pirate Hyena", nil, vec2.new(0,100))[1]
baddie:rename(godname)
baddie:setHilight()
baddie:setHostile()
hook.pilot( baddie, "death", "goddard_dead")
end
end
function idle() --the Gawain is flying around Anubis
baddie:goto(planet.get("Anubis"):pos() + vec2.new( 800, 800), false)
baddie:goto(planet.get("Anubis"):pos() + vec2.new(-800, 800), false)
baddie:goto(planet.get("Anubis"):pos() + vec2.new(-800, -800), false)
baddie:goto(planet.get("Anubis"):pos() + vec2.new( 800, -800), false)
end
function attacked() --the Gawain is going away
if baddie:exists() then
baddie:runaway(player.pilot(), true)
end
end
function gawain_dead()
misn.markerRm(gawmarker)
gawdead = true
hook.timer(3000,"generic_dead")
end
function kestrel_dead1()
misn.markerRm(kermarker1)
kerdead1 = true
hook.timer(3000,"generic_dead")
end
function kestrel_dead2()
misn.markerRm(kermarker2)
kerdead2 = true
hook.timer(3000,"generic_dead")
end
function goddard_dead()
misn.markerRm(godmarker)
goddead = true
hook.timer(3000,"generic_dead")
end
function generic_dead()
player.msg(text[3])
--Are there still other pirates to kill ?
if gawdead == true and kerdead1 == true and kerdead2 == true and goddead == true then
tk.msg(title[4], text[4]:format(paysys:name()))
stage = 1
misn.osdActive(2)
marker2 = misn.markerAdd(paysys, "low")
end
end
| gpl-3.0 |
FFXIOrgins/FFXIOrgins | scripts/globals/weaponskills/tachi_kasha.lua | 6 | 1642 | -----------------------------------
-- Tachi Kasha
-- Great Katana weapon skill
-- Skill Level: 250
-- Paralyzes target. Damage varies with TP.
-- Paralyze effect duration is 60 seconds when unresisted.
-- In order to obtain Tachi: Kasha, the quest The Potential Within must be completed.
-- Will stack with Sneak Attack.
-- Tachi: Kasha appears to have a moderate attack bonus of +50%. [1]
-- Aligned with the Flame Gorget, Light Gorget & Shadow Gorget.
-- Aligned with the Flame Belt, Light Belt & Shadow Belt.
-- Element: None
-- Modifiers: STR:75%
-- 100%TP 200%TP 300%TP
-- 1.56 1.88 2.50
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1.56; params.ftp200 = 1.88; params.ftp300 = 2.5;
params.str_wsc = 0.75; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1.5;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if damage > 0 and (target:hasStatusEffect(EFFECT_PARALYSIS) == false) then
target:addStatusEffect(EFFECT_PARALYSIS, 25, 0, 60);
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.