repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
qq779089973/ramod
luci/applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-cdr.lua
80
1878
--[[ 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$ ]]-- cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true cdr_csv = module:option(ListValue, "cdr_csv", "Comma Separated Values CDR Backend", "") cdr_csv:value("yes", "Load") cdr_csv:value("no", "Do Not Load") cdr_csv:value("auto", "Load as Required") cdr_csv.rmempty = true cdr_custom = module:option(ListValue, "cdr_custom", "Customizable Comma Separated Values CDR Backend", "") cdr_custom:value("yes", "Load") cdr_custom:value("no", "Do Not Load") cdr_custom:value("auto", "Load as Required") cdr_custom.rmempty = true cdr_manager = module:option(ListValue, "cdr_manager", "Asterisk Call Manager CDR Backend", "") cdr_manager:value("yes", "Load") cdr_manager:value("no", "Do Not Load") cdr_manager:value("auto", "Load as Required") cdr_manager.rmempty = true cdr_mysql = module:option(ListValue, "cdr_mysql", "MySQL CDR Backend", "") cdr_mysql:value("yes", "Load") cdr_mysql:value("no", "Do Not Load") cdr_mysql:value("auto", "Load as Required") cdr_mysql.rmempty = true cdr_pgsql = module:option(ListValue, "cdr_pgsql", "PostgreSQL CDR Backend", "") cdr_pgsql:value("yes", "Load") cdr_pgsql:value("no", "Do Not Load") cdr_pgsql:value("auto", "Load as Required") cdr_pgsql.rmempty = true cdr_sqlite = module:option(ListValue, "cdr_sqlite", "SQLite CDR Backend", "") cdr_sqlite:value("yes", "Load") cdr_sqlite:value("no", "Do Not Load") cdr_sqlite:value("auto", "Load as Required") cdr_sqlite.rmempty = true return cbimap
mit
snabbnfv-goodies/snabbswitch
lib/ljsyscall/syscall/openbsd/ffi.lua
18
6838
-- This are the types for OpenBSD local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local abi = require "syscall.abi" local ffi = require "ffi" require "syscall.ffitypes" local version = require "syscall.openbsd.version".version local defs = {} local function append(str) defs[#defs + 1] = str end append [[ typedef int32_t clockid_t; typedef uint32_t fflags_t; typedef uint64_t fsblkcnt_t; typedef uint64_t fsfilcnt_t; typedef int32_t id_t; typedef long key_t; typedef int32_t lwpid_t; typedef uint32_t mode_t; typedef int accmode_t; typedef int nl_item; typedef uint32_t nlink_t; typedef int64_t rlim_t; typedef uint8_t sa_family_t; typedef long suseconds_t; typedef unsigned int useconds_t; typedef int cpuwhich_t; typedef int cpulevel_t; typedef int cpusetid_t; typedef uint32_t dev_t; typedef uint32_t fixpt_t; typedef unsigned int nfds_t; typedef int64_t daddr_t; typedef int32_t timer_t; ]] if version <= 201311 then append [[ typedef uint32_t ino_t; typedef int32_t time_t; typedef int32_t clock_t; ]] else append [[ typedef uint64_t ino_t; typedef int64_t time_t; typedef int64_t clock_t; ]] end append [[ typedef unsigned int tcflag_t; typedef unsigned int speed_t; typedef char * caddr_t; /* can be changed, TODO also should be long */ typedef uint32_t __fd_mask; typedef struct fd_set { __fd_mask fds_bits[32]; } fd_set; typedef struct __sigset { uint32_t sig[1]; // note renamed to match Linux } sigset_t; // typedef unsigned int sigset_t; /* this is correct TODO fix */ struct cmsghdr { socklen_t cmsg_len; int cmsg_level; int cmsg_type; char cmsg_data[?]; }; struct msghdr { void *msg_name; socklen_t msg_namelen; struct iovec *msg_iov; int msg_iovlen; void *msg_control; socklen_t msg_controllen; int msg_flags; }; struct timespec { time_t tv_sec; long tv_nsec; }; struct timeval { time_t tv_sec; suseconds_t tv_usec; }; struct itimerspec { struct timespec it_interval; struct timespec it_value; }; struct itimerval { struct timeval it_interval; struct timeval it_value; }; struct sockaddr { uint8_t sa_len; sa_family_t sa_family; char sa_data[14]; }; struct sockaddr_storage { uint8_t ss_len; sa_family_t ss_family; unsigned char __ss_pad1[6]; uint64_t __ss_pad2; unsigned char __ss_pad3[240]; }; struct sockaddr_in { uint8_t sin_len; sa_family_t sin_family; in_port_t sin_port; struct in_addr sin_addr; int8_t sin_zero[8]; }; struct sockaddr_in6 { uint8_t sin6_len; sa_family_t sin6_family; in_port_t sin6_port; uint32_t sin6_flowinfo; struct in6_addr sin6_addr; uint32_t sin6_scope_id; }; struct sockaddr_un { uint8_t sun_len; sa_family_t sun_family; char sun_path[104]; }; struct pollfd { int fd; short events; short revents; }; ]] if version <= 201311 then append [[ struct stat { dev_t st_dev; ino_t st_ino; mode_t st_mode; nlink_t st_nlink; uid_t st_uid; gid_t st_gid; dev_t st_rdev; int32_t st_lspare0; struct timespec st_atim; struct timespec st_mtim; struct timespec st_ctim; off_t st_size; int64_t st_blocks; uint32_t st_blksize; uint32_t st_flags; uint32_t st_gen; int32_t st_lspare1; struct timespec __st_birthtim; int64_t st_qspare[2]; }; ]] else append [[ struct stat { mode_t st_mode; dev_t st_dev; ino_t st_ino; nlink_t st_nlink; uid_t st_uid; gid_t st_gid; dev_t st_rdev; struct timespec st_atim; struct timespec st_mtim; struct timespec st_ctim; off_t st_size; int64_t st_blocks; uint32_t st_blksize; uint32_t st_flags; uint32_t st_gen; struct timespec __st_birthtim; }; ]] end append [[ struct rusage { struct timeval ru_utime; struct timeval ru_stime; long ru_maxrss; long ru_ixrss; long ru_idrss; long ru_isrss; long ru_minflt; long ru_majflt; long ru_nswap; long ru_inblock; long ru_oublock; long ru_msgsnd; long ru_msgrcv; long ru_nsignals; long ru_nvcsw; long ru_nivcsw; }; struct flock { off_t l_start; off_t l_len; pid_t l_pid; short l_type; short l_whence; }; struct termios { tcflag_t c_iflag; tcflag_t c_oflag; tcflag_t c_cflag; tcflag_t c_lflag; cc_t c_cc[20]; speed_t c_ispeed; speed_t c_ospeed; }; ]] if version <= 201311 then append [[ struct dirent { uint32_t d_fileno; uint16_t d_reclen; uint8_t d_type; uint8_t d_namlen; char d_name[255 + 1]; }; struct kevent { unsigned int ident; short filter; unsigned short flags; unsigned int fflags; int data; void *udata; }; ]] else append [[ struct dirent { uint64_t d_fileno; int64_t d_off; uint16_t d_reclen; uint8_t d_type; uint8_t d_namlen; char __d_padding[4]; char d_name[255 + 1]; }; struct kevent { intptr_t ident; short filter; unsigned short flags; unsigned int fflags; int64_t data; void *udata; }; ]] end append [[ union sigval { int sival_int; void *sival_ptr; }; static const int SI_MAXSZ = 128; static const int SI_PAD = ((SI_MAXSZ / sizeof (int)) - 3); typedef struct { int si_signo; int si_code; int si_errno; union { int _pad[SI_PAD]; struct { pid_t _pid; union { struct { uid_t _uid; union sigval _value; } _kill; struct { clock_t _utime; int _status; clock_t _stime; } _cld; } _pdata; } _proc; struct { caddr_t _addr; int _trapno; } _fault; } _data; } siginfo_t; struct sigaction { union { void (*__sa_handler)(int); void (*__sa_sigaction)(int, siginfo_t *, void *); } __sigaction_u; sigset_t sa_mask; int sa_flags; }; ]] -- functions append [[ int reboot(int howto); int ioctl(int d, unsigned long request, void *arg); /* not syscalls, but using for now */ int grantpt(int fildes); int unlockpt(int fildes); char *ptsname(int fildes); ]] if version >= 201405 then append [[ int getdents(int fd, void *buf, size_t nbytes); ]] end local s = table.concat(defs, "") ffi.cdef(s) require "syscall.bsd.ffi"
apache-2.0
zhityer/zhityer4
plugins/stats.lua
458
4098
-- Saves the number of messages from a user -- Can check the number of messages with !stats do local NUM_MSG_MAX = 5 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ('..user_id..')' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.msgs..'\n' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') 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) -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
Henkoglobin/luadep
container.lua
1
2858
-- container.lua -- -- Provides a form of dependency injection for Lua projects local container = setmetatable({}, { __call = function(self, ...) return setmetatable(self.new(...), self) end }) container.__index = container function container.new() return { modules = {}, finished = {} } end function container:collect(module) for _, interface in pairs(module.interfaces) do if self.modules[interface] == nil then self.modules[interface] = {} end table.insert(self.modules[interface], module) end end function container:get(interface, multiple) local candidates = self.modules[interface] or {} local ret = {} for _, module in pairs(candidates) do if self.finished[module] then if multiple then table.insert(ret, module.module) else return module.module end end -- Get dependencies of this module local dependencies = module.dependencies for _, dependency in pairs(dependencies) do local resolved = self:get(dependency.interface, dependency.allowMultiple) if resolved then if not next(resolved) then if dependency.allowNone then -- Initialize the property nonetheless by injecting nil module.inject(module.module, dependency.interface, nil, dependency) else error(string.format("Cannot resolve dependency '%s' of module %s %s", dependency.interface, module.name, module.version)) end end if dependency.allowMultiple then for _, resolvedModule in pairs(resolved) do module.inject(module.module, dependency.interface, resolvedModule, dependency) end else module.inject(module.module, dependency.interface, resolved, dependency) end elseif not dependency.allowNone then error(string.format("Cannot resolve dependency '%s' of module %s %s", dependency.interface, module.name, module.version)) end end self.finished[module] = true if multiple then table.insert(ret, module.module) else return module.module end end -- If we reach this point, -- a: multiple was true ==> return table -- b: multiple was false, but no module was found ==> return nil return multiple and ret or nil end function container:validate() local missing = {} for interface, modules in pairs(self.modules) do print("Checking " .. interface) for _, module in pairs(modules) do print("Checking module " .. module.name) -- check every dependency of current module for _, definition in pairs(module.dependencies) do print("Checking definition " .. definition.interface) if not definition.allowNone and not self.modules[definition.interface] then missing[module.name] = definition.interface end end end end return not next(missing), missing end return container
unlicense
qq779089973/ramod
luci/applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_mini.lua
141
1031
--[[ smap_devinfo - SIP Device Information (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.smap_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci-smap-to-devinfo", translate("Phone Information"), translate("Scan for supported SIP devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.smap_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", true, debug) luci.controller.luci_diag.smap_common.action_links(m, true) return m
mit
yanjunh/luasocket-gyp
src/http.lua
121
12193
----------------------------------------------------------------------------- -- HTTP/1.1 client support for the Lua language. -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: http.lua,v 1.71 2007/10/13 23:55:20 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ------------------------------------------------------------------------------- local socket = require("socket") local url = require("socket.url") local ltn12 = require("ltn12") local mime = require("mime") local string = require("string") local base = _G local table = require("table") module("socket.http") ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- -- connection timeout in seconds TIMEOUT = 60 -- default port for document retrieval PORT = 80 -- user agent field sent in request USERAGENT = socket._VERSION ----------------------------------------------------------------------------- -- Reads MIME headers from a connection, unfolding where needed ----------------------------------------------------------------------------- local function receiveheaders(sock, headers) local line, name, value, err headers = headers or {} -- get first line line, err = sock:receive() if err then return nil, err end -- headers go until a blank line is found while line ~= "" do -- get field-name and value name, value = socket.skip(2, string.find(line, "^(.-):%s*(.*)")) if not (name and value) then return nil, "malformed reponse headers" end name = string.lower(name) -- get next line (value might be folded) line, err = sock:receive() if err then return nil, err end -- unfold any folded values while string.find(line, "^%s") do value = value .. line line = sock:receive() if err then return nil, err end end -- save pair in table if headers[name] then headers[name] = headers[name] .. ", " .. value else headers[name] = value end end return headers end ----------------------------------------------------------------------------- -- Extra sources and sinks ----------------------------------------------------------------------------- socket.sourcet["http-chunked"] = function(sock, headers) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function() -- get chunk size, skip extention local line, err = sock:receive() if err then return nil, err end local size = base.tonumber(string.gsub(line, ";.*", ""), 16) if not size then return nil, "invalid chunk size" end -- was it the last chunk? if size > 0 then -- if not, get chunk and skip terminating CRLF local chunk, err, part = sock:receive(size) if chunk then sock:receive() end return chunk, err else -- if it was, read trailers into headers table headers, err = receiveheaders(sock, headers) if not headers then return nil, err end end end }) end socket.sinkt["http-chunked"] = function(sock) return base.setmetatable({ getfd = function() return sock:getfd() end, dirty = function() return sock:dirty() end }, { __call = function(self, chunk, err) if not chunk then return sock:send("0\r\n\r\n") end local size = string.format("%X\r\n", string.len(chunk)) return sock:send(size .. chunk .. "\r\n") end }) end ----------------------------------------------------------------------------- -- Low level HTTP API ----------------------------------------------------------------------------- local metat = { __index = {} } function open(host, port, create) -- create socket with user connect function, or with default local c = socket.try((create or socket.tcp)()) local h = base.setmetatable({ c = c }, metat) -- create finalized try h.try = socket.newtry(function() h:close() end) -- set timeout before connecting h.try(c:settimeout(TIMEOUT)) h.try(c:connect(host, port or PORT)) -- here everything worked return h end function metat.__index:sendrequestline(method, uri) local reqline = string.format("%s %s HTTP/1.1\r\n", method or "GET", uri) return self.try(self.c:send(reqline)) end function metat.__index:sendheaders(headers) local h = "\r\n" for i, v in base.pairs(headers) do h = i .. ": " .. v .. "\r\n" .. h end self.try(self.c:send(h)) return 1 end function metat.__index:sendbody(headers, source, step) source = source or ltn12.source.empty() step = step or ltn12.pump.step -- if we don't know the size in advance, send chunked and hope for the best local mode = "http-chunked" if headers["content-length"] then mode = "keep-open" end return self.try(ltn12.pump.all(source, socket.sink(mode, self.c), step)) end function metat.__index:receivestatusline() local status = self.try(self.c:receive(5)) -- identify HTTP/0.9 responses, which do not contain a status line -- this is just a heuristic, but is what the RFC recommends if status ~= "HTTP/" then return nil, status end -- otherwise proceed reading a status line status = self.try(self.c:receive("*l", status)) local code = socket.skip(2, string.find(status, "HTTP/%d*%.%d* (%d%d%d)")) return self.try(base.tonumber(code), status) end function metat.__index:receiveheaders() return self.try(receiveheaders(self.c)) end function metat.__index:receivebody(headers, sink, step) sink = sink or ltn12.sink.null() step = step or ltn12.pump.step local length = base.tonumber(headers["content-length"]) local t = headers["transfer-encoding"] -- shortcut local mode = "default" -- connection close if t and t ~= "identity" then mode = "http-chunked" elseif base.tonumber(headers["content-length"]) then mode = "by-length" end return self.try(ltn12.pump.all(socket.source(mode, self.c, length), sink, step)) end function metat.__index:receive09body(status, sink, step) local source = ltn12.source.rewind(socket.source("until-closed", self.c)) source(status) return self.try(ltn12.pump.all(source, sink, step)) end function metat.__index:close() return self.c:close() end ----------------------------------------------------------------------------- -- High level HTTP API ----------------------------------------------------------------------------- local function adjusturi(reqt) local u = reqt -- if there is a proxy, we need the full url. otherwise, just a part. if not reqt.proxy and not PROXY then u = { path = socket.try(reqt.path, "invalid path 'nil'"), params = reqt.params, query = reqt.query, fragment = reqt.fragment } end return url.build(u) end local function adjustproxy(reqt) local proxy = reqt.proxy or PROXY if proxy then proxy = url.parse(proxy) return proxy.host, proxy.port or 3128 else return reqt.host, reqt.port end end local function adjustheaders(reqt) -- default headers local lower = { ["user-agent"] = USERAGENT, ["host"] = reqt.host, ["connection"] = "close, TE", ["te"] = "trailers" } -- if we have authentication information, pass it along if reqt.user and reqt.password then lower["authorization"] = "Basic " .. (mime.b64(reqt.user .. ":" .. reqt.password)) end -- override with user headers for i,v in base.pairs(reqt.headers or lower) do lower[string.lower(i)] = v end return lower end -- default url parts local default = { host = "", port = PORT, path ="/", scheme = "http" } local function adjustrequest(reqt) -- parse url if provided local nreqt = reqt.url and url.parse(reqt.url, default) or {} -- explicit components override url for i,v in base.pairs(reqt) do nreqt[i] = v end if nreqt.port == "" then nreqt.port = 80 end socket.try(nreqt.host and nreqt.host ~= "", "invalid host '" .. base.tostring(nreqt.host) .. "'") -- compute uri if user hasn't overriden nreqt.uri = reqt.uri or adjusturi(nreqt) -- ajust host and port if there is a proxy nreqt.host, nreqt.port = adjustproxy(nreqt) -- adjust headers in request nreqt.headers = adjustheaders(nreqt) return nreqt end local function shouldredirect(reqt, code, headers) return headers.location and string.gsub(headers.location, "%s", "") ~= "" and (reqt.redirect ~= false) and (code == 301 or code == 302) and (not reqt.method or reqt.method == "GET" or reqt.method == "HEAD") and (not reqt.nredirects or reqt.nredirects < 5) end local function shouldreceivebody(reqt, code) if reqt.method == "HEAD" then return nil end if code == 204 or code == 304 then return nil end if code >= 100 and code < 200 then return nil end return 1 end -- forward declarations local trequest, tredirect function tredirect(reqt, location) local result, code, headers, status = trequest { -- the RFC says the redirect URL has to be absolute, but some -- servers do not respect that url = url.absolute(reqt.url, location), source = reqt.source, sink = reqt.sink, headers = reqt.headers, proxy = reqt.proxy, nredirects = (reqt.nredirects or 0) + 1, create = reqt.create } -- pass location header back as a hint we redirected headers = headers or {} headers.location = headers.location or location return result, code, headers, status end function trequest(reqt) -- we loop until we get what we want, or -- until we are sure there is no way to get it local nreqt = adjustrequest(reqt) local h = open(nreqt.host, nreqt.port, nreqt.create) -- send request line and headers h:sendrequestline(nreqt.method, nreqt.uri) h:sendheaders(nreqt.headers) -- if there is a body, send it if nreqt.source then h:sendbody(nreqt.headers, nreqt.source, nreqt.step) end local code, status = h:receivestatusline() -- if it is an HTTP/0.9 server, simply get the body and we are done if not code then h:receive09body(status, nreqt.sink, nreqt.step) return 1, 200 end local headers -- ignore any 100-continue messages while code == 100 do headers = h:receiveheaders() code, status = h:receivestatusline() end headers = h:receiveheaders() -- at this point we should have a honest reply from the server -- we can't redirect if we already used the source, so we report the error if shouldredirect(nreqt, code, headers) and not nreqt.source then h:close() return tredirect(reqt, headers.location) end -- here we are finally done if shouldreceivebody(nreqt, code) then h:receivebody(headers, nreqt.sink, nreqt.step) end h:close() return 1, code, headers, status end local function srequest(u, b) local t = {} local reqt = { url = u, sink = ltn12.sink.table(t) } if b then reqt.source = ltn12.source.string(b) reqt.headers = { ["content-length"] = string.len(b), ["content-type"] = "application/x-www-form-urlencoded" } reqt.method = "POST" end local code, headers, status = socket.skip(1, trequest(reqt)) return table.concat(t), code, headers, status end request = socket.protect(function(reqt, body) if base.type(reqt) == "string" then return srequest(reqt, body) else return trequest(reqt) end end)
mit
chelog/brawl
addons/brawl-weapons/lua/weapons/cw_jng90/sh_sounds.lua
1
1315
CustomizableWeaponry:addFireSound("CW_JNG_SUB", "weapons/jng90/sub.wav", 1, 50, CHAN_STATIC) CustomizableWeaponry:addFireSound("CW_JNG_FIRE", "weapons/jng90/fire.wav", 1, 105, CHAN_STATIC) CustomizableWeaponry:addReloadSound("CW_JNG_MAGOUT", "weapons/jng90/magout.wav") CustomizableWeaponry:addReloadSound("CW_JNG_MAGIN", "weapons/jng90/magin.wav") CustomizableWeaponry:addReloadSound("CW_JNG_PULL", "weapons/jng90/pull.wav") CustomizableWeaponry:addReloadSound("CW_JNG_RELEASE", "weapons/jng90/release.wav") /* sound.Add( { name = "J97.down", channel = CHAN_STATIC, volume = 1.0, level = 80, pitch = { 95, 110 }, sound = "weapons/jng90/release.wav" } ) sound.Add( { name = "J97.release", channel = CHAN_STATIC, volume = 1.0, level = 80, pitch = { 95, 110 }, sound = "weapons/jng90/release.wav" } ) sound.Add( { name = "J97.magin", channel = CHAN_STATIC, volume = 1.0, level = 80, pitch = { 95, 110 }, sound = "weapons/jng90/magin.wav" } ) sound.Add( { name = "J97.magout", channel = CHAN_STATIC, volume = 1.0, level = 80, pitch = { 95, 110 }, sound = "weapons/jng90/magout.wav" } ) sound.Add( { name = "J97.pull", channel = CHAN_STATIC, volume = 1.0, level = 80, pitch = { 95, 110 }, sound = "weapons/jng90/pull.wav" } ) */
gpl-3.0
Inorizushi/DDR-X3
BGAnimations/optionicon_P2/default.lua
3
6716
return Def.ActorFrame { -- Speed Def.Sprite { OnCommand=function(self) self:x(-85); if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'1.5x') and SCREENMAN:GetTopScreen():GetScreenType() == "ScreenType_Gameplay" then self:Load(THEME:GetPathB("","optionicon_P2/speed_x1_5_P1")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'2x') then self:Load(THEME:GetPathB("","optionicon_P2/speed_x2_P1")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'3x') then self:Load(THEME:GetPathB("","optionicon_P2/speed_x3_P1")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'5x') then self:Load(THEME:GetPathB("","optionicon_P2/speed_x5_P1")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'8x') then self:Load(THEME:GetPathB("","optionicon_P2/speed_x8_P1")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'0.5x') then self:Load(THEME:GetPathB("","optionicon_P2/speed_x0_5_P1")); end; end; PlayerJoinedMessageCommand=function(self, params) if params.Player == PLAYER_2 then self:playcommand("On"); end; end; CodeMessageCommand=function(self, params) if params.PlayerNumber == PLAYER_2 then self:playcommand("On"); end; end; }; -- Boost Def.Sprite { InitCommand=function(self) self:x(-68); if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'boost') then self:Load(THEME:GetPathB("","optionicon_P2/boost_on_P2")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'brake') then self:Load(THEME:GetPathB("","optionicon_P2/boost_brake_P2")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'wave') then self:Load(THEME:GetPathB("","optionicon_P2/boost_wave_P2")); end; end; PlayerJoinedMessageCommand=function(self, params) if params.Player == PLAYER_2 then self:playcommand("Init"); end; end; }; -- Appearance Def.Sprite { InitCommand=function(self) self:x(-51); if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'hidden') then self:Load(THEME:GetPathB("","optionicon_P2/appearance_hidden_P2")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'sudden') then self:Load(THEME:GetPathB("","optionicon_P2/appearance_sudden_P2")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'stealth') then self:Load(THEME:GetPathB("","optionicon_P2/appearance_stealth_P2")); end; end; PlayerJoinedMessageCommand=function(self, params) if params.Player == PLAYER_2 then self:playcommand("Init"); end; end; }; -- Turn Def.Sprite { InitCommand=function(self) self:x(-34); if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'mirror') then self:Load(THEME:GetPathB("","optionicon_P2/turn_mirror_P2")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'left') then self:Load(THEME:GetPathB("","optionicon_P2/turn_left_P2")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'right') then self:Load(THEME:GetPathB("","optionicon_P2/turn_right_P2")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'shuffle') then self:Load(THEME:GetPathB("","optionicon_P2/turn_shuffle_P2")); end; end; PlayerJoinedMessageCommand=function(self, params) if params.Player == PLAYER_2 then self:playcommand("Init"); end; end; }; -- Dark Def.Sprite { InitCommand=function(self) self:x(-17); if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'dark') then self:Load(THEME:GetPathB("","optionicon_P2/dark_on_P2")); end; end; PlayerJoinedMessageCommand=function(self, params) if params.Player == PLAYER_2 then self:playcommand("Init"); end; end; }; -- Scroll Def.Sprite { InitCommand=function(self) self:x(0); if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'reverse') then self:Load(THEME:GetPathB("","optionicon_P2/scroll_reverse_P2")); end; end; PlayerJoinedMessageCommand=function(self, params) if params.Player == PLAYER_2 then self:playcommand("Init"); end; end; }; -- Arrow Def.Sprite { InitCommand=function(self) self:x(17); if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'NORMAL-FLAT') or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'CLASSIC-FLAT') or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'SOLO-FLAT') or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'PS3-FLAT') then self:Load(THEME:GetPathB("","optionicon_P2/arrow_flat_P2")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'NORMAL-NOTE') or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'CLASSIC-NOTE') or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'SOLO-NOTE') or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'PS3-NOTE') then self:Load(THEME:GetPathB("","optionicon_P2/arrow_note_P2")); elseif GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'NORMAL-RAINBOW') or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'CLASSIC-RAINBOW') or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'SOLO-RAINBOW') or GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'PS3-RAINBOW') then self:Load(THEME:GetPathB("","optionicon_P2/arrow_rainbow_P2")); end; end; PlayerJoinedMessageCommand=function(self, params) if params.Player == PLAYER_2 then self:playcommand("Init"); end; end; }; -- Cut Def.Sprite { InitCommand=function(self) self:x(34); if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'little') then self:Load(THEME:GetPathB("","optionicon_P2/cut_on_P2")); end; end; PlayerJoinedMessageCommand=function(self, params) if params.Player == PLAYER_2 then self:playcommand("Init"); end; end; }; -- Freeze arrow Def.Sprite { InitCommand=function(self) self:x(51); if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'noholds') then self:Load(THEME:GetPathB("","optionicon_P2/freeze_arrow_off_P2")); end; end; PlayerJoinedMessageCommand=function(self, params) if params.Player == PLAYER_2 then self:playcommand("Init"); end; end; }; -- Jump Def.Sprite { InitCommand=function(self) self:x(68); if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'nojumps') then self:Load(THEME:GetPathB("","optionicon_P2/jump_off_P2")); end; end; PlayerJoinedMessageCommand=function(self, params) if params.Player == PLAYER_2 then self:playcommand("Init"); end; end; }; -- Risky Def.Sprite { InitCommand=function(self) self:x(85); if GAMESTATE:PlayerIsUsingModifier(PLAYER_2,'battery') and GAMESTATE:GetPlayMode() ~= 'PlayMode_Oni' then self:Load(THEME:GetPathB("","optionicon_P2/Risky")); end; end; PlayerJoinedMessageCommand=function(self, params) if params.Player == PLAYER_2 then self:playcommand("Init"); end; end; }; };
mit
vladimir-kotikov/clink-completions
modules/matchers.lua
2
4332
local clink_version = require('clink_version') local exports = {} local path = require('path') local w = require('tables').wrap -- A function to generate directory matches. -- -- local matchers = require("matchers") -- clink.argmatcher():addarg(matchers.dirs) exports.dirs = function(word) -- Strip off any path components that may be on text. local prefix = "" local i = word:find("[\\/:][^\\/:]*$") if i then prefix = word:sub(1, i) end local include_dots = word:find("%.+$") ~= nil -- Find matches. local matches = w(clink.find_dirs(word.."*", true)) :filter(function (dir) return clink.is_match(word, prefix..dir) and (include_dots or path.is_real_dir(dir)) end) :map(function(dir) return prefix..dir end) -- If there was no matches but word is a dir then use it as the single match. -- Otherwise tell readline that matches are files and it will do magic. if #matches == 0 and clink.is_dir(rl_state.text) then return {rl_state.text} end clink.matches_are_files() return matches end -- A function to generate file matches. -- -- local matchers = require("matchers") -- clink.argmatcher():addarg(matchers.files) exports.files = function (word) if clink_version.supports_display_filter_description then local matches = w(clink.filematches(word)) return matches end -- Strip off any path components that may be on text. local prefix = "" local i = word:find("[\\/:][^\\/:]*$") if i then prefix = word:sub(1, i) end -- Find matches. local matches = w(clink.find_files(word.."*", true)) :filter(function (file) return clink.is_match(word, prefix..file) end) :map(function(file) return prefix..file end) -- Tell readline that matches are files and it will do magic. if #matches ~= 0 then clink.matches_are_files() end return matches end -- Returns a function that generates matches for the specified wildcards. -- -- local matchers = require("matchers") -- clink.argmatcher():addarg(matchers.ext_files("*.json")) exports.ext_files = function (...) local wildcards = {...} if clink.argmatcher then return function (word) local matches = clink.dirmatches(word.."*") for _, wild in ipairs(wildcards) do for _, m in ipairs(clink.filematches(word..wild)) do table.insert(matches, m) end end return matches end end return function (word) -- Strip off any path components that may be on text. local prefix = "" local i = word:find("[\\/:][^\\/:]*$") if i then prefix = word:sub(1, i) end -- Find directories. local matches = w(clink.find_dirs(word.."*", true)) :filter(function (dir) return clink.is_match(word, prefix..dir) and path.is_real_dir(dir) end) :map(function(dir) return prefix..dir end) -- Find wildcard matches (e.g. *.dll). for _, wild in ipairs(wildcards) do local filematches = w(clink.find_files(word..wild, true)) :filter(function (file) return clink.is_match(word, prefix..file) end) :map(function(file) return prefix..file end) matches = matches:concat(filematches) end -- Tell readline that matches are files and it will do magic. if #matches ~= 0 then clink.matches_are_files() end return matches end end exports.create_dirs_matcher = function (dir_pattern, show_dotfiles) return function (token) return w(clink.find_dirs(dir_pattern)) :filter(function(dir) return clink.is_match(token, dir) and (path.is_real_dir(dir) or show_dotfiles) end ) end end exports.create_files_matcher = function (file_pattern) return function (token) return w(clink.find_files(file_pattern)) :filter(function(file) -- Filter out '.' and '..' entries as well return clink.is_match(token, file) and path.is_real_dir(file) end ) end end return exports
mit
BrasileiroGamer/TrineEE_TranslationTools
translation_tools/base/data/locale/gui/en/menu/mainmenu/howtoplaymenu.lua
1
1630
-- /data/locale/gui/$$/menu/mainmenu/howtoplaymenu.lua headerHowToPlay = "How to Play" buttonTab = "" valuegeneral = "Introduction" valuegettingstarted = "Getting Started" valuetips = "Tips" tipsText1 = "\n <b>•</b> If you find yourself stuck, try solving the puzzle with another character or get another player to join you." tipsText2 = "\n <b>•</b> You can change the game mode from single player to online multiplayer in the Game Settings menu without having to quit first." tipsText3 = "\n <b>•</b> You can access menu options during the game by pressing START." tipsText4 = "\n <b>•</b> Return to any previous levels to collect experience you might have missed, but please remember that your exit point is saved only in the most recently played level." generalText1 = "\n <b>•</b> You can play Trine as a single player game or with one or two co-players." generalText2 = "\n <b>•</b> The available characters are Amadeus the Wizard, Pontius the Knight and Zoya the Thief. All characters have their own set of unique abilities." generalText3 = "\n <b>•</b> You can change the character you are playing at any time during the game." gettingstartedText1 = "\n <b>•</b> Amadeus, Pontius and Zoya are on a journey through the fantastical world of the Trine. Your goal is to help them reach the other side of each level by solving puzzles and defeating enemies." gettingstartedText2 = "\n <b>•</b> The first level, The Story Begins, introduces character controls to you." gettingstartedText3 = "\n <b>•</b> New players are encouraged to start playing the game from the first level."
gpl-3.0
Hzj-jie/koreader-base
ffi/zipwriter.lua
1
7503
-- Zip packing workflow & code from luarocks' zip.lua : -- https://github.com/luarocks/luarocks/blob/master/src/luarocks/tools/zip.lua -- Modified to not require lua-zlib (we can wrap zlib with ffi) -- cf: http://luajit.org/ext_ffi_tutorial.html, which uses zlib as an example ! -- Simplified to take filename and content from strings and not from disk -- We only need a few functions from zlib local ffi = require "ffi" ffi.cdef([[ unsigned long crc32(unsigned long crc, const char *buf, unsigned len); unsigned long compressBound(unsigned long sourceLen); int compress2(uint8_t *dest, unsigned long *destLen, const uint8_t *source, unsigned long sourceLen, int level); ]]) -- We only need to wrap 2 zlib functions to make a zip file local _zlib = ffi.load(ffi.os == "Windows" and "zlib1" or "z") local function zlibCompress(data) local n = _zlib.compressBound(#data) local buf = ffi.new("uint8_t[?]", n) local buflen = ffi.new("unsigned long[1]", n) local res = _zlib.compress2(buf, buflen, data, #data, 9) assert(res == 0) return ffi.string(buf, buflen[0]) end local function zlibCrc32(data, chksum) chksum = chksum or 0 data = data or "" return _zlib.crc32(chksum, data, #data) end local function numberToByteString(number, nbytes) local out = {} for _ = 1, nbytes do local byte = number % 256 table.insert(out, string.char(byte)) number = (number - byte) / 256 end return table.concat(out) end -- Pure lua zip writer local ZipWriter = {} function ZipWriter:new() local o = {} setmetatable(o, self) self.__index = self return o end --- Begin a new file to be stored inside the zipfile. function ZipWriter:_open_new_file_in_zip(filename) if self.in_open_file then self:_close_file_in_zip() return nil end local lfh = {} self.local_file_header = lfh lfh.last_mod_file_time = self.started_time -- 0 = 00:00 lfh.last_mod_file_date = self.started_date -- 0 = 1980-00-00 00:00 lfh.file_name_length = #filename lfh.extra_field_length = 0 lfh.file_name = filename:gsub("\\", "/") lfh.external_attr = 0 self.in_open_file = true return true end --- Write data to the file currently being stored in the zipfile. function ZipWriter:_write_file_in_zip(data) if not self.in_open_file then return nil end local lfh = self.local_file_header local compressed = zlibCompress(data):sub(3, -5) lfh.crc32 = tonumber(zlibCrc32(data)) lfh.compressed_size = #compressed lfh.uncompressed_size = #data self.data = compressed return true end --- Complete the writing of a file stored in the zipfile. function ZipWriter:_close_file_in_zip() local zh = self.ziphandle if not self.in_open_file then return nil end -- Local file header local lfh = self.local_file_header lfh.offset = zh:seek() zh:write(numberToByteString(0x04034b50, 4)) -- signature zh:write(numberToByteString(20, 2)) -- version needed to extract: 2.0 zh:write(numberToByteString(0, 2)) -- general purpose bit flag zh:write(numberToByteString(8, 2)) -- compression method: deflate zh:write(numberToByteString(lfh.last_mod_file_time, 2)) zh:write(numberToByteString(lfh.last_mod_file_date, 2)) zh:write(numberToByteString(lfh.crc32, 4)) zh:write(numberToByteString(lfh.compressed_size, 4)) zh:write(numberToByteString(lfh.uncompressed_size, 4)) zh:write(numberToByteString(lfh.file_name_length, 2)) zh:write(numberToByteString(lfh.extra_field_length, 2)) zh:write(lfh.file_name) -- File data zh:write(self.data) -- Data descriptor zh:write(numberToByteString(lfh.crc32, 4)) zh:write(numberToByteString(lfh.compressed_size, 4)) zh:write(numberToByteString(lfh.uncompressed_size, 4)) -- Done, add it to list of files table.insert(self.files, lfh) self.in_open_file = false return true end --- Complete the writing of the zipfile. function ZipWriter:close() local zh = self.ziphandle local central_directory_offset = zh:seek() local size_of_central_directory = 0 -- Central directory structure for _, lfh in ipairs(self.files) do zh:write(numberToByteString(0x02014b50, 4)) -- signature zh:write(numberToByteString(3, 2)) -- version made by: UNIX zh:write(numberToByteString(20, 2)) -- version needed to extract: 2.0 zh:write(numberToByteString(0, 2)) -- general purpose bit flag zh:write(numberToByteString(8, 2)) -- compression method: deflate zh:write(numberToByteString(lfh.last_mod_file_time, 2)) zh:write(numberToByteString(lfh.last_mod_file_date, 2)) zh:write(numberToByteString(lfh.crc32, 4)) zh:write(numberToByteString(lfh.compressed_size, 4)) zh:write(numberToByteString(lfh.uncompressed_size, 4)) zh:write(numberToByteString(lfh.file_name_length, 2)) zh:write(numberToByteString(lfh.extra_field_length, 2)) zh:write(numberToByteString(0, 2)) -- file comment length zh:write(numberToByteString(0, 2)) -- disk number start zh:write(numberToByteString(0, 2)) -- internal file attributes zh:write(numberToByteString(lfh.external_attr, 4)) -- external file attributes zh:write(numberToByteString(lfh.offset, 4)) -- relative offset of local header zh:write(lfh.file_name) size_of_central_directory = size_of_central_directory + 46 + lfh.file_name_length end -- End of central directory record zh:write(numberToByteString(0x06054b50, 4)) -- signature zh:write(numberToByteString(0, 2)) -- number of this disk zh:write(numberToByteString(0, 2)) -- number of disk with start of central directory zh:write(numberToByteString(#self.files, 2)) -- total number of entries in the central dir on this disk zh:write(numberToByteString(#self.files, 2)) -- total number of entries in the central dir zh:write(numberToByteString(size_of_central_directory, 4)) zh:write(numberToByteString(central_directory_offset, 4)) zh:write(numberToByteString(0, 2)) -- zip file comment length zh:close() return true end -- Open zipfile function ZipWriter:open(zipfilepath) self.files = {} self.in_open_file = false -- set modification date and time of files to now local t = os.date("*t") self.started_date = bit.bor( bit.lshift(t.year-1980, 9), bit.lshift(t.month, 5), bit.lshift(t.day, 0) ) self.started_time = bit.bor( bit.lshift(t.hour, 11), bit.lshift(t.min, 5), bit.rshift(t.sec+2, 1) ) self.ziphandle = io.open(zipfilepath, "wb") if not self.ziphandle then return nil end return true end -- Add to zipfile content with the name in_zip_filepath function ZipWriter:add(in_zip_filepath, content) self:_open_new_file_in_zip(in_zip_filepath) self:_write_file_in_zip(content) self:_close_file_in_zip() end -- Convenience function -- function ZipWriter.createZipWithFiles(zipfilename, files) -- local zw = ZipWriter:new() -- zw:open(zipfilename) -- for _, f in pairs(files) do -- zw:add(f.filename, f.content) -- end -- zw:close() -- end -- files = {} -- files[1] = {filename="tutu.txt", content="this is tutu"} -- files[2] = {filename="subtoto/toto.txt", content="this is toto in subtoto directory"} -- createZipWithFiles("tata.zip", files) return ZipWriter
agpl-3.0
mpeterv/literal
src/literal.lua
1
14728
--- A library for safe evaluation of Lua literal expressions. -- @module literal -- @license Public Domain -- @author Peter Melnichenko local literal = {} local class = require "30log" --- Default grammar to be used by evaluation functions. Set to the version of Lua used to run the module. literal.grammar = _VERSION:find "5.2" and "5.2" or "5.1" --- Maximum nesting level of table literals. Default is 200. literal.max_nesting = 200 --- Maximum length of string representation in error messages. Default is 45. literal.max_repr_length = 45 literal.Cursor = class() function literal.Cursor:__init(str, grammar, filename) self.str = str self.grammar = grammar or literal.grammar self.len = str:len()+1 self.i = 1 self.char = str:sub(1, 1) self.line = 1 if filename then self.repr = filename else self.repr = self:match "([ %p%d%a]*)" if self.repr:len() > literal.max_repr_length or self.repr:len() ~= str:len() then self.repr = self.repr:sub(1, literal.max_repr_length) .. "..." end self.repr = ('[string "%s"]'):format(self.repr) end end function literal.Cursor:errormsg(msg, chunk) local line = self.line if not chunk then self:skip_space_and_comments() chunk = self:match "([^%s%c]+)" if chunk then chunk = "'" .. chunk .. "'" elseif self:match "%c" then chunk = "char(" .. self.char:byte() .. ")" else chunk = "<eof>" end end return ("%s:%d: %s near %s"):format(self.repr, line, msg, chunk) end function literal.Cursor:error(msg, chunk) error(self:errormsg(msg, chunk), 0) end function literal.Cursor:assert(assertion, msg, chunk) return assertion or self:error(msg, chunk) end function literal.Cursor:invalid_escape() self:error("invalid escape sequence", "'\\" .. self:match "(%C?)" .. "'") end function literal.Cursor:step(di) local new_i = self.i + (di or 1) for _ in self.str:sub(self.i, new_i-1):gmatch "\n" do self.line = self.line + 1 end self.i = new_i self.char = self.str:sub(new_i, new_i) return self end function literal.Cursor:match(pattern) return self.str:match("^" .. pattern, self.i) end function literal.Cursor:skip_space() return self:step(#self:match "(%s*)") end function literal.Cursor:skip_space_and_comments() while true do self:skip_space() if self:match "%-%-" then -- Comment self:step(2) if self:match "%[=*%[" then -- Long comment self:eval_long_string() else -- Short comment self:step(#self:match "([^\r\n]*)") end else return self end end end function literal.Cursor:finish() self:skip_space_and_comments() self:assert(self.i == self.len, "<eof> expected") return self end function literal.Cursor:eval_long_string() local brackets, newline, inner_string = self:match "%[(=*)%[(\r?\n?)(.-)%]%1%]" if not brackets then self:error "unfinished long string" end self:step(#brackets*2 + #newline + #inner_string + 4) return inner_string end local escapes = { a = "\a", b = "\b", f = "\f", n = "\n", r = "\r", t = "\t", v = "\v", ["\\"] = "\\", ["'"] = "'", ['"'] = '"' } function literal.Cursor:eval_short_string() self:assert(self:match "['\"]", "short string expected") local specials = "\r\n\\" .. self.char local patt = ("([^%s]*)[%s]"):format(specials, specials) local errmsg = self:errormsg("unfinished string") local buf = {} self:step() while true do local raw_chunk = self:match(patt) if not raw_chunk or self:match "[\r\n]" then error(errmsg, 0) end table.insert(buf, raw_chunk) self:step(#raw_chunk) if self.char == "\\" then -- Escape sequence self:step() if self.char == "" then error(errmsg, 0) end if escapes[self.char] then -- Regular escape table.insert(buf, escapes[self.char]) self:step() elseif self:match "\r?\n" then -- Must replace with \n table.insert(buf, "\n") self:step(#self:match "(\r?\n)") elseif self:match "%d" then -- Decimal escape local code_str = self:match "(%d%d?%d?)" self:step(#code_str) local code = tonumber(code_str) self:assert(code and code < 256, "decimal escape too large", "'\\" .. code_str .. "'") table.insert(buf, string.char(code)) elseif self.grammar == "5.2" then -- Lua 5.2 things if self.char == "z" then self:step() -- Skip z self:skip_space() elseif self.char == "x" then -- Hexadecimal escape self:step() -- Skip x local code_str = self.str:sub(self.i, self.i+1) self:assert(code_str:match "(%x%x)", "hexadecimal digit expected", "'\\x" .. code_str:match "([^%s%c]*)" .. "'") self:step(2) local code = tonumber(code_str, 16) table.insert(buf, string.char(code)) else self:invalid_escape() end else self:invalid_escape() end else -- Ending quote break end end self:step() return table.concat(buf) end function literal.Cursor:eval_sign() if self.char == "-" then self:step() return -1 elseif self.char == "+" then self:step() end return 1 end function literal.Cursor:eval_number() self:assert(self:match "[%+%-%.%x]", "numerical constant expected") local mul = self:eval_sign() local res if self:match "0[xX]" then -- Hexadecimal self:step(2) if self.grammar == "5.1" then -- Should be an integer local integer_str = self:assert(self:match "(%x+)", "malformed number") res = self:assert(tonumber(integer_str, 16), "malformed number") self:step(integer_str:len()) else local integer_str = self:assert(self:match "(%x*)", "malformed number") local integer if integer_str == "" then integer = 0 else integer = self:assert(tonumber(integer_str, 16), "malformed number") end self:step(integer_str:len()) local fract = 0 if self.char == "." then self:step() local fract_str = self:assert(self:match "(%x*)", "malformed number") if fract_str == "" then self:assert(integer_str ~= "", "malformed number") fract = 0 else fract = self:assert(tonumber(fract_str, 16), "malformed number") fract = fract / 16^fract_str:len() end self:step(fract_str:len()) end if self:match "[pP]" then self:step() local pow_mul = self:eval_sign() local pow_str = self:assert(self:match "(%d+)", "malformed number") local pow = self:assert(tonumber(pow_str), "malformed number")*pow_mul mul = mul * 2^pow self:step(pow_str:len()) end res = integer+fract end else -- Decimal local number_str = self:assert(self:match "([%+%-%.%deE]+)", "malformed number") res = self:assert(tonumber(number_str), "malformed number") self:step(number_str:len()) end local number = res*mul if number ~= number then return 0 else return number end end local keywords = { ["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true, ["function"] = true, ["if"] = true, ["in"] = true, ["local"] = true, ["nil"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["true"] = true, ["until"] = true, ["while"] = true } local literals = { ["nil"] = {nil}, ["true"] = {true}, ["false"] = {false} } function literal.Cursor:eval_table(nesting) nesting = (nesting or 0)+1 self:assert(nesting <= literal.max_nesting, "table is too deep") self:assert(self.char == "{", "table literal expected") local t = {} local n = 0 local k, v local key_value local start_line = self.line self:step() while true do self:skip_space_and_comments() key_value = false if self.char == "}" then self:step() return t elseif self.char == "[" then if not self:match "%[=*%[" then self:step() self:skip_space_and_comments() k = self:eval_literal(nesting) self:assert(k ~= nil, "table index is nil") self:skip_space_and_comments() self:assert(self.char == "]", "']' expected") self:step() key_value = true end elseif self:match "[_%a][_%a%d]*" then k = self:match "([_%a][_%a%d]*)" if not literals[k] then if keywords[k] or self.grammar == "5.2" and k == "goto" then self:error("unexpected symbol") end self:step(k:len()) key_value = true end end if key_value then self:skip_space_and_comments() self:assert(self.char == "=", "'=' expected") self:step() self:skip_space_and_comments() v = self:eval_literal(nesting) t[k] = v else v = self:eval_literal(nesting) n = n+1 t[n] = v end self:skip_space_and_comments() if self:match "[,;]" then self:step() else local msg = "'}' expected" if self.line ~= start_line then msg = msg .. " (to close '{' at line " .. start_line .. ")" end self:assert(self.char == "}", msg) end end end function literal.Cursor:eval_literal(nesting) for lit, val in pairs(literals) do if self:match(lit) then self:step(lit:len()) return val[1] end end if self:match "['\"]" then return self:eval_short_string() elseif self:match "%[=*%[" then return self:eval_long_string() elseif self:match "[%.%+%-%d]" then return self:eval_number() elseif self.char == "{" then return self:eval_table(nesting) else self:error("literal expected") end end function literal.Cursor:eval() self:skip_space_and_comments() local res = self:eval_literal() self:finish() return res end function literal.Cursor:eval_config() local t = {} local k, v while self.i < self.len do self:skip_space_and_comments() k = self:assert(self:match "([_%a][_%a%d]*)", "unexpected symbol") self:step(k:len()) self:skip_space_and_comments() self:assert(self.char == "=", "'=' expected") self:step() self:skip_space_and_comments() v = self:eval_literal(1) self:skip_space_and_comments() if self.char == ";" then self:step() end t[k] = v end return t end --- Tries to evaluate a given string as a Lua literal. -- Correct literals are "nil", "true", "false", decimal and hexadecimal numerical constants, short and long strings, and tables of other literals. -- -- Comments are considered whitespace. -- Non-whitespace after a correct literal is an error. -- -- @string str the string. -- @string[opt] grammar the grammar to be used. Must be either "5.1" or "5.2". Default grammar is the grammar of Lua version used to run the module. -- @string[opt] filename the filename to be used in error messages. -- @raise Errors similar to those of Lua compiler. -- @return[type=nil|boolean|number|string|table] Result of evaluation. function literal.eval(str, grammar, filename) assert(type(str) == "string", ("bad argument #1 to 'eval' (string expected, got %s)"):format(type(str))) return literal.Cursor(str, grammar, filename):eval() end --- Protected version of @{eval}. -- Acts as @{eval}, but instead of raising errors returns false and error message. -- -- @string str the string. -- @string[opt] grammar the grammar to be used. Must be either "5.1" or "5.2". Default grammar is the grammar of Lua version used to run the module. -- @string[opt] filename the filename to be used in error messages. -- @return[type=boolean] True if there were no errors, false otherwise. -- @return[type=nil|boolean|number|string|table] Result of evaluation or error message. function literal.peval(str, grammar, filename) assert(type(str) == "string", ("bad argument #1 to 'peval' (string expected, got %s)"):format(type(str))) local cur = literal.Cursor(str, grammar, filename) return pcall(cur.eval, cur) end --- Tries to evaluate a given string as a config file. -- Config is a string consisting of pairs "&lt;string&gt; = &lt;literal&gt;", separated by whitespace and optional semicolons. -- &lt;string&gt; must be a valid Lua name or keyword. -- Config is interpreted as a table with these strings as keys and corresponding literals as values. -- -- @string str the string. -- @string[opt] grammar the grammar to be used. Must be either "5.1" or "5.2". Default grammar is the grammar of Lua version used to run the module. -- @string[opt] filename the filename to be used in error messages. -- @raise Errors similar to those of Lua compiler. -- @return[type=table] Result of evaluation. function literal.eval_config(str, grammar, filename) assert(type(str) == "string", ("bad argument #1 to 'eval_config' (string expected, got %s)"):format(type(str))) return literal.Cursor(str, grammar, filename):eval_config() end --- Protected version of @{eval_config}. -- Acts as @{eval_config}, but instead of raising errors returns false and error message. -- -- @string str the string. -- @string[opt] grammar the grammar to be used. Must be either "5.1" or "5.2". Default grammar is the grammar of Lua version used to run the module. -- @string[opt] filename the filename to be used in error messages. -- @return[type=boolean] True if there were no errors, false otherwise. -- @return[type=string|table] Result of evaluation or error message. function literal.peval_config(str, grammar, filename) assert(type(str) == "string", ("bad argument #1 to 'peval_config' (string expected, got %s)"):format(type(str))) local cur = literal.Cursor(str, grammar, filename) return pcall(cur.eval_config, cur) end return literal
unlicense
hnyman/luci
build/luadoc/luadoc/util.lua
32
5859
------------------------------------------------------------------------------- -- General utilities. -- @release $Id: util.lua,v 1.16 2008/02/17 06:42:51 jasonsantos Exp $ ------------------------------------------------------------------------------- local posix = require "nixio.fs" local type, table, string, io, assert, tostring, setmetatable, pcall = type, table, string, io, assert, tostring, setmetatable, pcall ------------------------------------------------------------------------------- -- Module with several utilities that could not fit in a specific module module "luadoc.util" ------------------------------------------------------------------------------- -- Removes spaces from the beginning and end of a given string -- @param s string to be trimmed -- @return trimmed string function trim (s) return (string.gsub(s, "^%s*(.-)%s*$", "%1")) end ------------------------------------------------------------------------------- -- Removes spaces from the beginning and end of a given string, considering the -- string is inside a lua comment. -- @param s string to be trimmed -- @return trimmed string -- @see trim -- @see string.gsub function trim_comment (s) s = string.gsub(s, "^%s*%-%-+%[%[(.*)$", "%1") s = string.gsub(s, "^%s*%-%-+(.*)$", "%1") return s end ------------------------------------------------------------------------------- -- Checks if a given line is empty -- @param line string with a line -- @return true if line is empty, false otherwise function line_empty (line) return (string.len(trim(line)) == 0) end ------------------------------------------------------------------------------- -- Appends two string, but if the first one is nil, use to second one -- @param str1 first string, can be nil -- @param str2 second string -- @return str1 .. " " .. str2, or str2 if str1 is nil function concat (str1, str2) if str1 == nil or string.len(str1) == 0 then return str2 else return str1 .. " " .. str2 end end ------------------------------------------------------------------------------- -- Split text into a list consisting of the strings in text, -- separated by strings matching delim (which may be a pattern). -- @param delim if delim is "" then action is the same as %s+ except that -- field 1 may be preceded by leading whitespace -- @usage split(",%s*", "Anna, Bob, Charlie,Dolores") -- @usage split(""," x y") gives {"x","y"} -- @usage split("%s+"," x y") gives {"", "x","y"} -- @return array with strings -- @see table.concat function split(delim, text) local list = {} if string.len(text) > 0 then delim = delim or "" local pos = 1 -- if delim matches empty string then it would give an endless loop if string.find("", delim, 1) and delim ~= "" then error("delim matches empty string!") end local first, last while 1 do if delim ~= "" then first, last = string.find(text, delim, pos) else first, last = string.find(text, "%s+", pos) if first == 1 then pos = last+1 first, last = string.find(text, "%s+", pos) end end if first then -- found? table.insert(list, string.sub(text, pos, first-1)) pos = last+1 else table.insert(list, string.sub(text, pos)) break end end end return list end ------------------------------------------------------------------------------- -- Comments a paragraph. -- @param text text to comment with "--", may contain several lines -- @return commented text function comment (text) text = string.gsub(text, "\n", "\n-- ") return "-- " .. text end ------------------------------------------------------------------------------- -- Wrap a string into a paragraph. -- @param s string to wrap -- @param w width to wrap to [80] -- @param i1 indent of first line [0] -- @param i2 indent of subsequent lines [0] -- @return wrapped paragraph function wrap(s, w, i1, i2) w = w or 80 i1 = i1 or 0 i2 = i2 or 0 assert(i1 < w and i2 < w, "the indents must be less than the line width") s = string.rep(" ", i1) .. s local lstart, len = 1, string.len(s) while len - lstart > w do local i = lstart + w while i > lstart and string.sub(s, i, i) ~= " " do i = i - 1 end local j = i while j > lstart and string.sub(s, j, j) == " " do j = j - 1 end s = string.sub(s, 1, j) .. "\n" .. string.rep(" ", i2) .. string.sub(s, i + 1, -1) local change = i2 + 1 - (i - j) lstart = j + change len = len + change end return s end ------------------------------------------------------------------------------- -- Opens a file, creating the directories if necessary -- @param filename full path of the file to open (or create) -- @param mode mode of opening -- @return file handle function posix.open (filename, mode) local f = io.open(filename, mode) if f == nil then filename = string.gsub(filename, "\\", "/") local dir = "" for d in string.gfind(filename, ".-/") do dir = dir .. d posix.mkdir(dir) end f = io.open(filename, mode) end return f end ---------------------------------------------------------------------------------- -- Creates a Logger with LuaLogging, if present. Otherwise, creates a mock logger. -- @param options a table with options for the logging mechanism -- @return logger object that will implement log methods function loadlogengine(options) local logenabled = pcall(function() require "logging" require "logging.console" end) local logging = logenabled and logging if logenabled then if options.filelog then logger = logging.file("luadoc.log") -- use this to get a file log else logger = logging.console("[%level] %message\n") end if options.verbose then logger:setLevel(logging.INFO) else logger:setLevel(logging.WARN) end else noop = {__index=function(...) return function(...) -- noop end end} logger = {} setmetatable(logger, noop) end return logger end
apache-2.0
jjmleiro/hue
tools/wrk-scripts/lib/equal-5bb8dbf.lua
22
1818
-- The MIT License (MIT) -- -- Copyright (c) 2014, Cyril David <cyx@cyx.is> -- -- 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 function equal(x, y) local t1, t2 = type(x), type(y) -- Shortcircuit if types not equal. if t1 ~= t2 then return false end -- For primitive types, direct comparison works. if t1 ~= 'table' and t2 ~= 'table' then return x == y end -- Since we have two tables, make sure both have the same -- length so we can avoid looping over different length arrays. if #x ~= #y then return false end -- Case 1: check over all keys of x for k,v in pairs(x) do if not equal(v, y[k]) then return false end end -- Case 2: check over `y` this time. for k,v in pairs(y) do if not equal(v, x[k]) then return false end end return true end return equal
apache-2.0
chelog/brawl
addons/brawl-weapons/lua/cw/shared/attachments/md_cmore.lua
1
1449
local att = {} att.name = "md_cmore" att.displayName = "C-More Railway Sight" att.displayNameShort = "C-More" att.aimPos = {"CmorePos", "CmoreAng"} att.FOVModifier = 15 att.isSight = true att.colorType = CustomizableWeaponry.colorableParts.COLOR_TYPE_SIGHT att.statModifiers = {OverallMouseSensMult = -0.04} if CLIENT then att.displayIcon = surface.GetTextureID("cw20_extras/icons/upgr_cmore") att.description = {[1] = {t = "Provides a bright reticle to ease aiming.", c = CustomizableWeaponry.textColors.POSITIVE}} att.reticle = "cw2/reticles/kobra_sight" att._reticleSize = 3.4 function att:drawReticle() if not self:isAiming() then return end diff = self:getDifferenceToAimPos(self.CmorePos, self.CmoreAng, att._reticleSize) -- draw the reticle only when it's close to center of the aiming position if diff > 0.9 and diff < 1.1 then cam.IgnoreZ(true) render.SetMaterial(att._reticle) dist = math.Clamp(math.Distance(1, 1, diff, diff), 0, 0.13) local EA = self.Owner:EyeAngles() + self.Owner:GetPunchAngle() local renderColor = self:getSightColor(att.name) renderColor.a = (0.13 - dist) / 0.13 * 255 local pos = EyePos() + EA:Forward() * 100 for i = 1, 2 do render.DrawSprite(pos, att._reticleSize, att._reticleSize, renderColor) end cam.IgnoreZ(false) end end end CustomizableWeaponry:registerAttachment(att)
gpl-3.0
soundsrc/premake-core
modules/vstudio/tests/vc2010/test_rule_vars.lua
9
2233
-- -- tests/actions/vstudio/vc2010/test_rule_vars.lua -- Validate generation of custom rule variables at the project level. -- Author Jason Perkins -- Copyright (c) 2014-2015 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vstudio_vs2010_rule_vars") local vc2010 = p.vstudio.vc2010 -- -- Setup -- local wks, prj function suite.setup() p.action.set("vs2010") rule "MyRule" wks, prj = test.createWorkspace() rules { "MyRule" } end local function createVar(def) rule "MyRule" propertydefinition(def) project "MyProject" end local function prepare() local cfg = test.getconfig(prj, "Debug") vc2010.ruleVars(cfg) end -- -- If the configuration has a rule, but does not set any variables, -- nothing should be written. -- function suite.noOutput_onNoVars() prepare() test.isemptycapture() end -- -- Test setting the various property kinds. -- function suite.onBooleanVar() createVar { name="MyVar", kind="boolean" } myRuleVars { MyVar = false } prepare() test.capture [[ <MyRule> <MyVar>false</MyVar> </MyRule> ]] end function suite.onEnumVar() createVar { name = "MyVar", values = { [0] = "Win32", [1] = "Win64", }, switch = { [0] = "-m32", [1] = "-m64", }, value = 0, } myRuleVars { MyVar = "Win32" } prepare() test.capture [[ <MyRule> <MyVar>0</MyVar> </MyRule> ]] end function suite.onListVar() createVar { name="MyVar", kind="list" } myRuleVars { MyVar = { "a", "b", "c" } } prepare() test.capture [[ <MyRule> <MyVar>a;b;c</MyVar> </MyRule> ]] end function suite.onCustomListSeparator() createVar { name="MyVar", kind="list", separator="," } myRuleVars { MyVar = { "a", "b", "c" } } prepare() test.capture [[ <MyRule> <MyVar>a;b;c</MyVar> </MyRule> ]] end function suite.onPathVar() createVar { name="MyVar", kind="path" } myRuleVars { MyVar = "../path/to/file" } prepare() test.capture [[ <MyRule> <MyVar>..\path\to\file</MyVar> </MyRule> ]] end function suite.onStringVar() createVar { name="MyVar", kind="string" } myRuleVars { MyVar = "hello" } prepare() test.capture [[ <MyRule> <MyVar>hello</MyVar> </MyRule> ]] end
bsd-3-clause
mpeterv/pflua
src/pf/match.lua
15
11796
module(...,package.seeall) --- --- Program := 'match' Cond --- Cond := '{' Clause... '}' --- Clause := Test '=>' Dispatch [ClauseTerminator] -- Test := 'otherwise' | LogicalExpression --- ClauseTerminator := ',' | ';' --- Dispatch := Call | Cond --- Call := Identifier Args? --- Args := '(' [ ArithmeticExpression [ ',' ArithmeticExpression ] ] ')' --- --- LogicalExpression and ArithmeticExpression are embedded productions --- of pflang. 'otherwise' is a Test that always matches. --- --- Comments are prefixed by '--' and continue to the end of the line. --- --- Compiling a Program produces a Matcher. A Matcher is a function of --- three arguments: a handlers table, the packet data as a uint8_t*, --- and the packet length in bytes. --- --- Calling a Matcher will either result in a tail call to a member --- function of the handlers table, or return nil if no dispatch --- matches. --- --- A Call matches if all of the conditions necessary to evaluate the --- arithmetic expressions in its arguments are true. (For example, the --- argument handle(ip[42]) is only valid if the packet is an IPv4 --- packet of a sufficient length.) --- --- A Cond always matches; once you enter a Cond, no clause outside the --- Cond will match. If no clause in the Cond matches, the result is --- nil. --- --- A Clause matches if the Test on the left-hand-side of the arrow is --- true. If the right-hand-side is a call, the conditions from the --- call arguments (if any) are implicitly added to the Test on the --- left. In this way it's possible for the Test to be true but some --- condition from the Call to be false, which causes the match to --- proceed with the next Clause. --- --- Unlike pflang, attempting to access out-of-bounds packet data merely --- causes a clause not to match, instead of immediately aborting the --- match. --- local utils = require('pf.utils') local parse_pflang = require('pf.parse').parse local expand_pflang = require('pf.expand').expand local optimize = require('pf.optimize') local anf = require('pf.anf') local ssa = require('pf.ssa') local backend = require('pf.backend') local function split(str, pat) pat = '()'..pat..'()' local ret, start_pos = {}, 1 local tok_pos, end_pos = str:match(pat) while tok_pos do table.insert(ret, str:sub(start_pos, tok_pos - 1)) start_pos = end_pos tok_pos, end_pos = str:match(pat, start_pos) end table.insert(ret, str:sub(start_pos)) return ret end local function remove_comments(str) local lines = split(str, '\n') for i=1,#lines do local line = lines[i] local comment = line:match('()%-%-') if comment then lines[i] = line:sub(1, comment - 1) end end return table.concat(lines, '\n') end -- Return line, line number, column number. local function error_location(str, pos) local start, count = 1, 1 local stop = str:match('()\n', start) while stop and stop < pos do start, stop = stop + 1, str:match('()\n', stop + 1) count = count + 1 end if stop then stop = stop - 1 end return str:sub(start, stop), count, pos - start + 1 end local function scanner(str) str = remove_comments(str) local pos = 1 local function error_str(message, ...) local line, line_number, column_number = error_location(str, pos) local message = "\npfmatch: syntax error:%d:%d: "..message..'\n' local result = message:format(line_number, column_number, ...) result = result..line.."\n" result = result..string.rep(" ", column_number-1).."^".."\n" return result end local primitive_error = error local function error(message, ...) primitive_error(error_str(message, ...)) end local function skip_whitespace() pos = str:match('^%s*()', pos) end local function peek(pat) skip_whitespace() return str:match('^'..pat, pos) end local function check(pat) skip_whitespace() local start_pos, end_pos = pos, peek(pat.."()") if not end_pos then return nil end pos = end_pos return str:sub(start_pos, end_pos - 1) end local function next_identifier() local id = check('[%a_][%w_]*') if not id then error('expected an identifier') end return id end local function next_balanced(pair) local tok = check('%b'..pair) if not tok then error("expected balanced '%s'", pair) end return tok:sub(2, #tok - 1) end local function consume(pat) if not check(pat) then error("expected pattern '%s'", pat) end end local function consume_until(pat) skip_whitespace() local start_pos, end_pos, next_pos = pos, str:match("()"..pat.."()", pos) if not next_pos then error("expected pattern '%s'") end pos = next_pos return str:sub(start_pos, end_pos - 1) end local function done() skip_whitespace() return pos == #str + 1 end return { error = error, peek = peek, check = check, next_identifier = next_identifier, next_balanced = next_balanced, consume = consume, consume_until = consume_until, done = done } end local parse_dispatch local function parse_call(scanner) local proc = scanner.next_identifier() if not proc then scanner.error('expected a procedure call') end local result = { 'call', proc } if scanner.peek('%(') then local args_str = scanner.next_balanced('()') if not args_str:match('^%s*$') then local args = split(args_str, ',') for i=1,#args do table.insert(result, parse_pflang(args[i], {arithmetic=true})) end end end return result end local function parse_cond(scanner) local res = { 'cond' } while not scanner.check('}') do local test if scanner.check('otherwise') then test = { 'true' } scanner.consume('=>') else test = parse_pflang(scanner.consume_until('=>')) end local consequent = parse_dispatch(scanner) scanner.check('[,;]') table.insert(res, { test, consequent }) end return res end function parse_dispatch(scanner) if scanner.check('{') then return parse_cond(scanner) end return parse_call(scanner) end local function subst(str, values) local out, pos = '', 1 while true do local before, after = str:match('()%$[%w_]+()', pos) if not before then return out..str:sub(pos) end out = out..str:sub(pos, before - 1) local var = str:sub(before + 1, after - 1) local val = values[var] if not val then error('var not found: '..var) end out = out..val pos = after end return out end local function parse(str) local scanner = scanner(str) scanner.consume('match') scanner.consume('{') local cond = parse_cond(scanner) if not scanner.done() then scanner.error("unexpected token") end return cond end local function expand_arg(arg, dlt) -- The argument is an arithmetic expression, but the pflang expander -- expects a logical expression. Wrap in a dummy comparison, then -- tease apart the conditions and the arithmetic expression. local expr = expand_pflang({ '=', arg, 0 }, dlt) local conditions = {} while expr[1] == 'if' do table.insert(conditions, expr[2]) assert(type(expr[4]) == 'table') assert(expr[4][1] == 'fail' or expr[4][1] == 'false') expr = expr[3] end assert(expr[1] == '=' and expr[3] == 0) return conditions, expr[2] end local function expand_call(expr, dlt) local conditions = {} local res = { expr[1], expr[2] } for i=3,#expr do local arg_conditions, arg = expand_arg(expr[i], dlt) conditions = utils.concat(conditions, arg_conditions) table.insert(res, arg) end local test = { 'true' } -- Preserve left-to-right order of conditions. while #conditions ~= 0 do test = { 'if', table.remove(conditions), test, { 'false' } } end return test, res end local expand_cond -- Unlike pflang, out-of-bounds and such just cause the clause to fail, -- not the whole program. local function replace_fail(expr) if type(expr) ~= 'table' then return expr elseif expr[1] == 'fail' then return { 'false' } elseif expr[1] == 'if' then local test = replace_fail(expr[2]) local consequent = replace_fail(expr[3]) local alternate = replace_fail(expr[4]) return { 'if', test, consequent, alternate } else return expr end end local function expand_clause(test, consequent, dlt) test = replace_fail(expand_pflang(test, dlt)) if consequent[1] == 'call' then local conditions, call = expand_call(consequent, dlt) return { 'if', test, conditions, { 'false' } }, call else assert(consequent[1] == 'cond') return test, expand_cond(consequent, dlt) end end function expand_cond(expr, dlt) local res = { 'false' } for i=#expr,2,-1 do local clause = expr[i] local test, consequent = expand_clause(clause[1], clause[2], dlt) res = { 'if', test, consequent, res } end return res end local function expand(expr, dlt) return expand_cond(expr, dlt) end local compile_defaults = { dlt='EN10MB', optimize=true, source=false, subst=false } function compile(str, opts) opts = utils.parse_opts(opts or {}, compile_defaults) if opts.subst then str = subst(str, opts.subst) end local expr = expand(parse(str), opts.dlt) if opts.optimize then expr = optimize.optimize(expr) end expr = anf.convert_anf(expr) expr = ssa.convert_ssa(expr) if opts.source then return backend.emit_match_lua(expr) end return backend.emit_and_load_match(expr, filter_str) end function selftest() print("selftest: pf.match") local function test(str, expr) utils.assert_equals(expr, parse(str)) end test("match {}", { 'cond' }) test("match--comment\n{}", { 'cond' }) test(" match \n { } ", { 'cond' }) test("match{}", { 'cond' }) test("match { otherwise => x() }", { 'cond', { { 'true' }, { 'call', 'x' } } }) test("match { otherwise => x(1) }", { 'cond', { { 'true' }, { 'call', 'x', 1 } } }) test("match { otherwise => x(1&1) }", { 'cond', { { 'true' }, { 'call', 'x', { '&', 1, 1 } } } }) test("match { otherwise => x(ip[42]) }", { 'cond', { { 'true' }, { 'call', 'x', { '[ip]', 42, 1 } } } }) test("match { otherwise => x(ip[42], 10) }", { 'cond', { { 'true' }, { 'call', 'x', { '[ip]', 42, 1 }, 10 } } }) test(subst("match { otherwise => x(ip[$loc], 10) }", {loc=42}), { 'cond', { { 'true' }, { 'call', 'x', { '[ip]', 42, 1 }, 10 } } }) local function test(str, expr) utils.assert_equals(expr, expand(parse(str), 'EN10MB')) end test("match { otherwise => x() }", { 'if', { 'if', { 'true' }, { 'true' }, { 'false' } }, { 'call', 'x' }, { 'false' } }) test("match { otherwise => x(1) }", { 'if', { 'if', { 'true' }, { 'true' }, { 'false' } }, { 'call', 'x', 1 }, { 'false' } }) test("match { otherwise => x(1/0) }", { 'if', { 'if', { 'true' }, { 'if', { '!=', 0, 0 }, { 'true' }, { 'false' } }, { 'false' } }, { 'call', 'x', { 'uint32', { '/', 1, 0 } } }, { 'false' } }) local function test(str, expr) utils.assert_equals(expr, optimize.optimize(expand(parse(str), 'EN10MB'))) end test("match { otherwise => x() }", { 'call', 'x' }) test("match { otherwise => x(1) }", { 'call', 'x', 1 }) test("match { otherwise => x(1/0) }", { 'fail' }) local function test(str, expr) -- Just a test to see if it works without errors. compile(str) end test("match { tcp port 80 => pass }") print("OK") end
apache-2.0
RedSnake64/openwrt-luci-packages
protocols/luci-proto-ipv6/luasrc/model/cbi/admin_network/proto_6rd.lua
72
2039
-- Copyright 2011-2012 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local ipaddr, peeraddr, ip6addr, tunnelid, username, password local defaultroute, metric, ttl, mtu ipaddr = s:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" peeraddr = s:taboption("general", Value, "peeraddr", translate("Remote IPv4 address"), translate("This IPv4 address of the relay")) peeraddr.rmempty = false peeraddr.datatype = "ip4addr" ip6addr = s:taboption("general", Value, "ip6prefix", translate("IPv6 prefix"), translate("The IPv6 prefix assigned to the provider, usually ends with <code>::</code>")) ip6addr.rmempty = false ip6addr.datatype = "ip6addr" ip6prefixlen = s:taboption("general", Value, "ip6prefixlen", translate("IPv6 prefix length"), translate("The length of the IPv6 prefix in bits")) ip6prefixlen.placeholder = "16" ip6prefixlen.datatype = "range(0,128)" ip6prefixlen = s:taboption("general", Value, "ip4prefixlen", translate("IPv4 prefix length"), translate("The length of the IPv4 prefix in bits, the remainder is used in the IPv6 addresses.")) ip6prefixlen.placeholder = "0" ip6prefixlen.datatype = "range(0,32)" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(9200)"
apache-2.0
snabbnfv-goodies/snabbswitch
lib/ljsyscall/syscall/netbsd/fcntl.lua
24
1318
-- NetBSD fcntl local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(types) local c = require "syscall.netbsd.constants" local ffi = require "ffi" local t, pt, s = types.t, types.pt, types.s local h = require "syscall.helpers" local ctobool, booltoc = h.ctobool, h.booltoc local fcntl = { commands = { [c.F.SETFL] = function(arg) return c.O[arg] end, [c.F.SETFD] = function(arg) return c.FD[arg] end, [c.F.GETLK] = t.flock, [c.F.SETLK] = t.flock, [c.F.SETLKW] = t.flock, [c.F.SETNOSIGPIPE] = function(arg) return booltoc(arg) end, }, ret = { [c.F.DUPFD] = function(ret) return t.fd(ret) end, [c.F.DUPFD_CLOEXEC] = function(ret) return t.fd(ret) end, [c.F.GETFD] = function(ret) return tonumber(ret) end, [c.F.GETFL] = function(ret) return tonumber(ret) end, [c.F.GETOWN] = function(ret) return tonumber(ret) end, [c.F.GETLK] = function(ret, arg) return arg end, [c.F.MAXFD] = function(ret) return tonumber(ret) end, [c.F.GETNOSIGPIPE] = function(ret) return ctobool(ret) end, } } return fcntl end return {init = init}
apache-2.0
dismantl/luci-0.12
libs/nixio/docsrc/nixio.bit.lua
171
2044
--- Bitfield operators and mainpulation functions. -- Can be used as a drop-in replacement for bitlib. module "nixio.bit" --- Bitwise OR several numbers. -- @class function -- @name bor -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Invert given number. -- @class function -- @name bnot -- @param oper Operand -- @return number --- Bitwise AND several numbers. -- @class function -- @name band -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Bitwise XOR several numbers. -- @class function -- @name bxor -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Left shift a number. -- @class function -- @name lshift -- @param oper number -- @param shift bits to shift -- @return number --- Right shift a number. -- @class function -- @name rshift -- @param oper number -- @param shift bits to shift -- @return number --- Arithmetically right shift a number. -- @class function -- @name arshift -- @param oper number -- @param shift bits to shift -- @return number --- Integer division of 2 or more numbers. -- @class function -- @name div -- @param oper1 Operand 1 -- @param oper2 Operand 2 -- @param ... More Operands -- @return number --- Cast a number to the bit-operating range. -- @class function -- @name cast -- @param oper number -- @return number --- Sets one or more flags of a bitfield. -- @class function -- @name set -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return altered bitfield --- Unsets one or more flags of a bitfield. -- @class function -- @name unset -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return altered bitfield --- Checks whether given flags are set in a bitfield. -- @class function -- @name check -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return true when all flags are set, otherwise false
apache-2.0
vladimir-kotikov/clink-completions
scoop.lua
2
7981
-- -*- coding: utf-8 -*- -- preamble: common routines local JSON = require("JSON") local matchers = require("matchers") local path = require("path") local w = require("tables").wrap local concat = require("funclib").concat local parser = clink.arg.new_parser local function get_home_dir() return os.getenv("home") or os.getenv("USERPROFILE") end local function scoop_folder() local folder = os.getenv("SCOOP") if not folder then folder = get_home_dir() .. "\\scoop" end return folder end local function scoop_global_folder() local folder = os.getenv("SCOOP_GLOBAL") if not folder then folder = os.getenv("ProgramData") .. "\\scoop" end return folder end local function scoop_load_config() -- luacheck: no unused args local file = io.open(get_home_dir() .. "\\.config\\scoop\\config.json") -- If there is no such file, then close handle and return if file == nil then return w() end -- Read the whole file contents local contents = file:read("*a") file:close() -- strip UTF-8-BOM local utf8_len = contents:len() local pat_start, _ = string.find(contents, "{") contents = contents:sub(pat_start, utf8_len) local data = JSON:decode(contents) if data == nil then return w() end return data end local function scoop_alias_list(token) -- luacheck: no unused args local data = scoop_load_config() return w(data.alias):keys() end local function scoop_config_list(token) -- luacheck: no unused args local data = scoop_load_config() return w(data):keys() end local function scoop_bucket_known_list(token) -- luacheck: no unused args local file = io.open(scoop_folder() .. "\\apps\\scoop\\current\\buckets.json") -- If there is no such file, then close handle and return if file == nil then return w() end -- Read the whole file contents local contents = file:read("*a") file:close() local data = JSON:decode(contents) return w(data):keys() end local function scoop_bucket_list(token) local finder = matchers.create_files_matcher(scoop_folder() .. "\\buckets\\*") local list = finder(token) return list:filter(path.is_real_dir) end local function scoop_apps_list(token) local folders = {scoop_folder(), scoop_global_folder()} local list = w() for _, folder in pairs(folders) do local finder = matchers.create_files_matcher(folder .. "\\apps\\*") local new_list = finder(token) list = w(concat(list, new_list)) end return list:filter(path.is_real_dir) end local function scoop_available_apps_list(token) -- search in default bucket local finder = matchers.create_files_matcher(scoop_folder() .. "\\apps\\scoop\\current\\bucket\\*.json") local list = finder(token) -- search in each installed bucket local buckets = scoop_bucket_list("") for _, bucket in pairs(buckets) do local bucket_folder = scoop_folder() .. "\\buckets\\" .. bucket -- check the bucket folder exists if clink.is_dir(bucket_folder .. "\\bucket") then bucket_folder = bucket_folder .. "\\bucket" end local b_finder = matchers.create_files_matcher(bucket_folder .. "\\*.json") local b_list = b_finder(token) list = w(concat(list, b_list)) end -- remove ".json" of file name for k, v in pairs(list) do list[k] = v:gsub(".json", "") end return list end local function scoop_cache_apps_list(token) local cache_folder = os.getenv("SCOOP_CACHE") if not cache_folder then cache_folder = scoop_folder() .. "\\cache" end local finder = matchers.create_files_matcher(cache_folder .. "\\*") local list = finder(token) list = w(list:filter(path.is_real_dir)) -- get name before "#" from cache list (name#version#url) for k, v in pairs(list) do list[k] = v:gsub("#.*$", "") end return list end local scoop_default_flags = { "--help", "-h" } local scoop_alias_parser = parser( { "add", "list" .. parser("-v", "--verbose"), "rm" .. parser({scoop_alias_list}) } ) local scoop_bucket_parser = parser( { "add" .. parser({scoop_bucket_known_list}), "list", "known", "rm" .. parser({scoop_bucket_list}) } ) local scoop_cache_parser = parser( { "show" .. parser({scoop_cache_apps_list, scoop_apps_list, "*"}), "rm" .. parser({scoop_cache_apps_list, "*"}) } ) local scoop_cleanup_parser = parser( { scoop_apps_list, "*" }, "--global", "-g", "--cache", "-k" ):loop(1) local scoop_config_parser = parser( { "rm" .. parser({scoop_config_list}), scoop_config_list, "aria2-enabled" .. parser({"true", "false"}), "aria2-max-connection-per-server", "aria2-min-split-size", "aria2-options", "aria2-retry-wait", "aria2-split", "debug" .. parser({"true", "false"}), "proxy", "show_update_log" .. parser({"true", "false"}), "virustotal_api_key" } ) local scoop_uninstall_parser = parser( { scoop_apps_list }, "--global", "-g", "--purge", "-p" ):loop(1) local scoop_update_parser = parser( { scoop_apps_list, "*" }, "--force", "-f", "--global", "-g", "--independent", "-i", "--no-cache", "-k", "--skip", "-s", "--quiet", "-q" ):loop(1) local scoop_install_parser = parser( {scoop_available_apps_list}, "--global", "-g", "--independent", "-i", "--no-cache", "-k", "--skip", "-s", "--arch" .. parser({"32bit", "64bit"}), "-a" .. parser({"32bit", "64bit"}) ):loop(1) local scoop_help_parser = parser( { "alias", "bucket", "cache", "checkup", "cleanup", "config", "create", "depends", "export", "help", "home", "hold", "info", "install", "list", "prefix", "reset", "search", "status", "unhold", "uninstall", "update", "virustotal", "which" }, "/?", "--help", "-h", "--version" ) local scoop_parser = parser() scoop_parser:set_flags(scoop_default_flags) scoop_parser:set_arguments( { scoop_alias_list, "alias" .. scoop_alias_parser, "bucket" .. scoop_bucket_parser, "cache" .. scoop_cache_parser, "checkup", "cleanup" .. scoop_cleanup_parser, "config" .. scoop_config_parser, "create", "depends" .. parser( {scoop_available_apps_list, scoop_apps_list}, "--arch" .. parser({"32bit", "64bit"}), "-a" .. parser({"32bit", "64bit"}) ), "export", "help" .. scoop_help_parser, "hold" .. parser({scoop_apps_list}), "home" .. parser({scoop_available_apps_list, scoop_apps_list}), "info" .. parser({scoop_available_apps_list, scoop_apps_list}), "install" .. scoop_install_parser, "list", "prefix" .. parser({scoop_apps_list}), "reset" .. parser({scoop_apps_list}):loop(1), "search", "status", "unhold" .. parser({scoop_apps_list}), "uninstall" .. scoop_uninstall_parser, "update" .. scoop_update_parser, "virustotal" .. parser( {scoop_apps_list, "*"}, "--arch" .. parser({"32bit", "64bit"}), "-a" .. parser({"32bit", "64bit"}), "--scan", "-s", "--no-depends", "-n" ):loop(1), "which" } ) clink.arg.register_parser("scoop", scoop_parser)
mit
chelog/brawl
gamemodes/brawl/gamemode/modules/changelog/client/changelog.lua
1
2822
local f local function refresh( reset ) if reset then f.page = 1 f.prev:SetEnabled( false ) end local t, p = f.type:GetValue(), f.page http.Fetch( "http://www.octothorp.team/changelog/fetch.php?s=brawl&t="..t.."&p="..p, function( body, size, headers, code ) if code ~= 200 then return end local data = util.JSONToTable( body ) f.list:Clear() f.next:SetEnabled( table.Count( data ) == 10 ) for k, v in pairs( data ) do local line = f.list:AddLine( v.id, os.date("%d/%m/%y - %H:%M",v.time), v.title ) end end) end local function newEntry() local d = vgui.Create( "DFrame" ) d:SetSize( 400, 400 ) d:SetTitle( "New entry in '" .. f.type:GetValue() .. "'" ) d:Center() d:MakePopup() d.title = brawl.DTextEntry{ parent = d, pos = { 5, 30 }, size = { 390, 65 }, multiline = true, } d.desc = brawl.DTextEntry{ parent = d, pos = { 5, 100 }, size = { 390, 260 }, multiline = true, } d.add = brawl.DButton{ parent = d, pos = { 320, 370 }, size = { 75, 25 }, txt = "Add", onselect = function() net.Start( "changelog.add" ) net.WriteTable({ type = f.type:GetValue(), time = os.time(), title = d.title:GetValue(), desc = d.desc:GetValue() ~= "" and d.desc:GetValue() or nil, }) net.SendToServer() d:Close() end } end concommand.Add( "changelog", function() if IsValid( f ) then f:SetVisible( not f:IsVisible() ) else f = vgui.Create( "DFrame" ) f:SetSize( 600, 400 ) f:SetTitle( "Changelog editor" ) f:Center() f:MakePopup() f.list = vgui.Create( "DListView", f ) f.list:SetPos( 5, 30 ) f.list:SetSize( 590, 336 ) f.list:SetDataHeight( 32 ) local col = f.list:AddColumn( "id" ) col:SetWidth( 40 ) col = f.list:AddColumn( "Time" ) col:SetWidth( 95 ) col = f.list:AddColumn( "Title" ) col:SetWidth( 470 ) f.type = brawl.DComboBox{ parent = f, pos = { 475, 3 }, size = { 90, 18 }, data = { "dev", "event", "other" }, val = "dev", onselect = refresh, } f.add = brawl.DButton{ parent = f, pos = { 5, 370 }, size = { 75, 25 }, txt = "New", onselect = function() newEntry() end } f.refresh = brawl.DButton{ parent = f, pos = { 85, 370 }, size = { 75, 25 }, txt = "Refresh", onselect = function() refresh() end } f.next = brawl.DButton{ parent = f, pos = { 520, 370 }, size = { 75, 25 }, txt = "Next", onselect = function() f.page = f.page + 1 f.prev:SetEnabled( true ) refresh() end } f.prev = brawl.DButton{ parent = f, pos = { 440, 370 }, size = { 75, 25 }, txt = "Back", onselect = function( self ) f.page = f.page - 1 if f.page == 1 then self:SetEnabled( false ) end f.next:SetEnabled( true ) refresh() end } refresh( true ) end end)
gpl-3.0
RedSnake64/openwrt-luci-packages
applications/luci-app-asterisk/luasrc/model/cbi/asterisk-mod-chan.lua
68
1513
-- 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. cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true chan_agent = module:option(ListValue, "chan_agent", "Agent Proxy Channel", "") chan_agent:value("yes", "Load") chan_agent:value("no", "Do Not Load") chan_agent:value("auto", "Load as Required") chan_agent.rmempty = true chan_alsa = module:option(ListValue, "chan_alsa", "Channel driver for GTalk", "") chan_alsa:value("yes", "Load") chan_alsa:value("no", "Do Not Load") chan_alsa:value("auto", "Load as Required") chan_alsa.rmempty = true chan_gtalk = module:option(ListValue, "chan_gtalk", "Channel driver for GTalk", "") chan_gtalk:value("yes", "Load") chan_gtalk:value("no", "Do Not Load") chan_gtalk:value("auto", "Load as Required") chan_gtalk.rmempty = true chan_iax2 = module:option(Flag, "chan_iax2", "Option chan_iax2", "") chan_iax2.rmempty = true chan_local = module:option(ListValue, "chan_local", "Local Proxy Channel", "") chan_local:value("yes", "Load") chan_local:value("no", "Do Not Load") chan_local:value("auto", "Load as Required") chan_local.rmempty = true chan_sip = module:option(ListValue, "chan_sip", "Session Initiation Protocol (SIP)", "") chan_sip:value("yes", "Load") chan_sip:value("no", "Do Not Load") chan_sip:value("auto", "Load as Required") chan_sip.rmempty = true return cbimap
apache-2.0
jsenellart-systran/OpenNMT
onmt/utils/MemoryOptimizer.lua
8
6733
--[[ MemoryOptimizer is a class used for optimizing memory usage of a replicated network. --]] local MemoryOptimizer = torch.class('MemoryOptimizer') -- We cannot share every internal tensors (that is why we need to replicate in the first place). -- The general rule is to not share tensors whose content is used in the backward pass -- We allow the sharing when only the size is queried as it is constant during the -- forward and backward passes. -- We cannot share the output of these modules as they use it in their backward pass. local protectOutput = { 'nn.Sigmoid', 'nn.SoftMax', 'nn.Tanh' } -- We cannot share the input of these modules as they use it in their backward pass. local protectInput = { 'nn.Linear', 'nn.JoinTable', 'nn.CMulTable', 'nn.MM' } local function useSameStorage(t, l) if torch.isTensor(l) then return torch.pointer(t:storage()) == torch.pointer(l:storage()) elseif torch.type(l) == 'table' then for _, m in ipairs(l) do if useSameStorage(t, m) then return true end end end return false end -- We cannot share a tensor if it is exposed or coming from outside of the net -- otherwise we could generate side-effects. local function canShare(t, net, protected) if torch.isTensor(t) and t:storage() then if not useSameStorage(t, net.gradInput) and not useSameStorage(t, net.output) and not useSameStorage(t, protected) then return true end elseif torch.type(t) == 'table' then for _, m in ipairs(t) do if not canShare(m, net, protected) then return false end end return true end return false end local function getSize(t, mempool) local size = 0 if torch.isTensor(t) then if t:storage() then if not mempool[torch.pointer(t:storage())] then mempool[torch.pointer(t:storage())] = t:storage():size()*t:elementSize() return mempool[torch.pointer(t:storage())] end end elseif torch.type(t) == 'table' then for _, m in ipairs(t) do size = size + getSize(m, mempool) end end return size end -- Convenience function to register a network to optimize. local function registerNet(store, net, base) store.net = net store.base = base store.forward = net.forward net.forward = function(network, input) store.input = input return store.forward(network, input) end store.backward = net.backward net.backward = function(network, input, gradOutput) store.gradOutput = gradOutput return store.backward(network, input, gradOutput) end -- Add a wrapper around updateOutput to catch the module input. net:apply(function (m) local updateOutput = m.updateOutput m.updateOutput = function (mod, input) mod.input = input return updateOutput(mod, input) end end) end --[[ Construct a MemoryOptimizer object. In this function, forward and backward function will -- be overwrited to record input and gradOutput in order to determine which tensors can be shared. Parameters: * `modules` - a list of modules to optimize. Example: local memoryOptimizer = onmt.utils.MemoryOptimizer.new(model) -- prepare memory optimization. model:forward(...) -- initialize output tensors model:backward(...) -- intialize gradInput tensors memoryOptimizer.optimize() -- actual optimization by marking shared tensors ]] function MemoryOptimizer:__init(modules) self.modelDesc = {} for name, mod in pairs(modules) do self.modelDesc[name] = {} if torch.isTypeOf(mod, 'onmt.Sequencer') then -- If the module directly contains a network, take the first clone. self.modelDesc[name][1] = {} registerNet(self.modelDesc[name][1], mod:net(1), mod.network) elseif mod.modules then -- Otherwise, look in submodules instead. local i = 1 mod:apply(function(m) if torch.isTypeOf(m, 'onmt.Sequencer') then self.modelDesc[name][i] = {} registerNet(self.modelDesc[name][i], m:net(1), m.network) i = i + 1 end end) end end if onmt.utils.Table.empty(self.modelDesc) then _G.logger:warning('Only networks inheriting from onmt.Sequencer can be optimized') end end --[[ Enable memory optimization by marking tensors to share. Note that the modules must have been initialized -- by calling forward() and backward() before calling this function and after calling the MemoryOptimizer constructor. Returns: 1. `sharedSize` - shared tensor size 2. `totSize` - total tensor size ]] function MemoryOptimizer:optimize() local totSize = 0 local sharedSize = 0 for _, desc in pairs(self.modelDesc) do for i = 1, #desc do local net = desc[i].net local base = desc[i].base local mempool = {} -- Some modules are using output when performing updateGradInput so we cannot share these. local protectedOutput = { desc[i].input } net:apply(function(m) if onmt.utils.Table.hasValue(protectOutput, torch.typename(m)) then table.insert(protectedOutput, m.output) end if onmt.utils.Table.hasValue(protectInput, torch.typename(m)) then table.insert(protectedOutput, m.input) end end) local globalIdx = 1 local idx = 1 local gradInputMap = {} local outputMap = {} -- Go over the network to determine which tensors can be shared. net:apply(function(m) local giSize = getSize(m.gradInput, mempool) local oSize = getSize(m.output, mempool) totSize = totSize + giSize totSize = totSize + oSize if canShare(m.gradInput, net, desc[i].gradOutput) then sharedSize = sharedSize + giSize m.gradInputSharedIdx = idx gradInputMap[globalIdx] = idx idx = idx + 1 end if canShare(m.output, net, protectedOutput) then sharedSize = sharedSize + oSize m.outputSharedIdx = idx outputMap[globalIdx] = idx idx = idx + 1 end -- Remove the wrapper around updateOutput to catch the module input. m.updateOutput = nil m.input = nil globalIdx = globalIdx + 1 end) globalIdx = 1 -- Mark shareable tensors in the base network. base:apply(function (m) if gradInputMap[globalIdx] then m.gradInputSharedIdx = gradInputMap[globalIdx] end if outputMap[globalIdx] then m.outputSharedIdx = outputMap[globalIdx] end globalIdx = globalIdx + 1 end) -- Restore function on network backward/forward interception input. net.backward = nil net.forward = nil end end return sharedSize, totSize end return MemoryOptimizer
mit
snabbnfv-goodies/snabbswitch
lib/ljsyscall/syscall/linux/nl.lua
18
36273
-- modularize netlink code as it is large and standalone local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(S) local nl = {} -- exports local ffi = require "ffi" local bit = require "syscall.bit" local h = require "syscall.helpers" local util = S.util local types = S.types local c = S.c local htonl = h.htonl local align = h.align local t, pt, s = types.t, types.pt, types.s local adtt = { [c.AF.INET] = t.in_addr, [c.AF.INET6] = t.in6_addr, } local function addrtype(af) local tp = adtt[tonumber(af)] if not tp then error("bad address family") end return tp() end local function mktype(tp, x) if ffi.istype(tp, x) then return x else return tp(x) end end local mt = {} -- metatables local meth = {} -- similar functions for netlink messages local function nlmsg_align(len) return align(len, 4) end local nlmsg_hdrlen = nlmsg_align(s.nlmsghdr) local function nlmsg_length(len) return len + nlmsg_hdrlen end local function nlmsg_ok(msg, len) return len >= nlmsg_hdrlen and msg.nlmsg_len >= nlmsg_hdrlen and msg.nlmsg_len <= len end local function nlmsg_next(msg, buf, len) local inc = nlmsg_align(msg.nlmsg_len) return pt.nlmsghdr(buf + inc), buf + inc, len - inc end local rta_align = nlmsg_align -- also 4 byte align local function rta_length(len) return len + rta_align(s.rtattr) end local function rta_ok(msg, len) return len >= s.rtattr and msg.rta_len >= s.rtattr and msg.rta_len <= len end local function rta_next(msg, buf, len) local inc = rta_align(msg.rta_len) return pt.rtattr(buf + inc), buf + inc, len - inc end local addrlenmap = { -- map interface type to length of hardware address TODO are these always same? [c.ARPHRD.ETHER] = 6, [c.ARPHRD.EETHER] = 6, [c.ARPHRD.LOOPBACK] = 6, } local ifla_decode = { [c.IFLA.IFNAME] = function(ir, buf, len) ir.name = ffi.string(buf) end, [c.IFLA.ADDRESS] = function(ir, buf, len) local addrlen = addrlenmap[ir.type] if (addrlen) then ir.addrlen = addrlen ir.macaddr = t.macaddr() ffi.copy(ir.macaddr, buf, addrlen) end end, [c.IFLA.BROADCAST] = function(ir, buf, len) local addrlen = addrlenmap[ir.type] -- TODO always same if (addrlen) then ir.broadcast = t.macaddr() ffi.copy(ir.broadcast, buf, addrlen) end end, [c.IFLA.MTU] = function(ir, buf, len) local u = pt.uint(buf) ir.mtu = tonumber(u[0]) end, [c.IFLA.LINK] = function(ir, buf, len) local i = pt.int(buf) ir.link = tonumber(i[0]) end, [c.IFLA.QDISC] = function(ir, buf, len) ir.qdisc = ffi.string(buf) end, [c.IFLA.STATS] = function(ir, buf, len) ir.stats = t.rtnl_link_stats() -- despite man page, this is what kernel uses. So only get 32 bit stats here. ffi.copy(ir.stats, buf, s.rtnl_link_stats) end } local ifa_decode = { [c.IFA.ADDRESS] = function(ir, buf, len) ir.addr = addrtype(ir.family) ffi.copy(ir.addr, buf, ffi.sizeof(ir.addr)) end, [c.IFA.LOCAL] = function(ir, buf, len) ir.loc = addrtype(ir.family) ffi.copy(ir.loc, buf, ffi.sizeof(ir.loc)) end, [c.IFA.BROADCAST] = function(ir, buf, len) ir.broadcast = addrtype(ir.family) ffi.copy(ir.broadcast, buf, ffi.sizeof(ir.broadcast)) end, [c.IFA.LABEL] = function(ir, buf, len) ir.label = ffi.string(buf) end, [c.IFA.ANYCAST] = function(ir, buf, len) ir.anycast = addrtype(ir.family) ffi.copy(ir.anycast, buf, ffi.sizeof(ir.anycast)) end, [c.IFA.CACHEINFO] = function(ir, buf, len) ir.cacheinfo = t.ifa_cacheinfo() ffi.copy(ir.cacheinfo, buf, ffi.sizeof(t.ifa_cacheinfo)) end, } local rta_decode = { [c.RTA.DST] = function(ir, buf, len) ir.dst = addrtype(ir.family) ffi.copy(ir.dst, buf, ffi.sizeof(ir.dst)) end, [c.RTA.SRC] = function(ir, buf, len) ir.src = addrtype(ir.family) ffi.copy(ir.src, buf, ffi.sizeof(ir.src)) end, [c.RTA.IIF] = function(ir, buf, len) local i = pt.int(buf) ir.iif = tonumber(i[0]) end, [c.RTA.OIF] = function(ir, buf, len) local i = pt.int(buf) ir.oif = tonumber(i[0]) end, [c.RTA.GATEWAY] = function(ir, buf, len) ir.gateway = addrtype(ir.family) ffi.copy(ir.gateway, buf, ffi.sizeof(ir.gateway)) end, [c.RTA.PRIORITY] = function(ir, buf, len) local i = pt.int(buf) ir.priority = tonumber(i[0]) end, [c.RTA.PREFSRC] = function(ir, buf, len) local i = pt.uint32(buf) ir.prefsrc = tonumber(i[0]) end, [c.RTA.METRICS] = function(ir, buf, len) local i = pt.int(buf) ir.metrics = tonumber(i[0]) end, [c.RTA.TABLE] = function(ir, buf, len) local i = pt.uint32(buf) ir.table = tonumber(i[0]) end, [c.RTA.CACHEINFO] = function(ir, buf, len) ir.cacheinfo = t.rta_cacheinfo() ffi.copy(ir.cacheinfo, buf, s.rta_cacheinfo) end, -- TODO some missing } local nda_decode = { [c.NDA.DST] = function(ir, buf, len) ir.dst = addrtype(ir.family) ffi.copy(ir.dst, buf, ffi.sizeof(ir.dst)) end, [c.NDA.LLADDR] = function(ir, buf, len) ir.lladdr = t.macaddr() ffi.copy(ir.lladdr, buf, s.macaddr) end, [c.NDA.CACHEINFO] = function(ir, buf, len) ir.cacheinfo = t.nda_cacheinfo() ffi.copy(ir.cacheinfo, buf, s.nda_cacheinfo) end, [c.NDA.PROBES] = function(ir, buf, len) -- TODO what is this? 4 bytes end, } local ifflist = {} for k, _ in pairs(c.IFF) do ifflist[#ifflist + 1] = k end mt.iff = { __tostring = function(f) local s = {} for _, k in pairs(ifflist) do if bit.band(f.flags, c.IFF[k]) ~= 0 then s[#s + 1] = k end end return table.concat(s, ' ') end, __index = function(f, k) if c.IFF[k] then return bit.band(f.flags, c.IFF[k]) ~= 0 end end } nl.encapnames = { [c.ARPHRD.ETHER] = "Ethernet", [c.ARPHRD.LOOPBACK] = "Local Loopback", } meth.iflinks = { fn = { refresh = function(i) local j, err = nl.interfaces() if not j then return nil, err end for k, _ in pairs(i) do i[k] = nil end for k, v in pairs(j) do i[k] = v end return i end, }, } mt.iflinks = { __index = function(i, k) if meth.iflinks.fn[k] then return meth.iflinks.fn[k] end end, __tostring = function(is) local s = {} for _, v in ipairs(is) do s[#s + 1] = tostring(v) end return table.concat(s, '\n') end } meth.iflink = { index = { family = function(i) return tonumber(i.ifinfo.ifi_family) end, type = function(i) return tonumber(i.ifinfo.ifi_type) end, typename = function(i) local n = nl.encapnames[i.type] return n or 'unknown ' .. i.type end, index = function(i) return tonumber(i.ifinfo.ifi_index) end, flags = function(i) return setmetatable({flags = tonumber(i.ifinfo.ifi_flags)}, mt.iff) end, change = function(i) return tonumber(i.ifinfo.ifi_change) end, }, fn = { setflags = function(i, flags, change) local ok, err = nl.newlink(i, 0, flags, change or c.IFF.ALL) if not ok then return nil, err end return i:refresh() end, up = function(i) return i:setflags("up", "up") end, down = function(i) return i:setflags("", "up") end, setmtu = function(i, mtu) local ok, err = nl.newlink(i.index, 0, 0, 0, "mtu", mtu) if not ok then return nil, err end return i:refresh() end, setmac = function(i, mac) local ok, err = nl.newlink(i.index, 0, 0, 0, "address", mac) if not ok then return nil, err end return i:refresh() end, address = function(i, address, netmask) -- add address if type(address) == "string" then address, netmask = util.inet_name(address, netmask) end if not address then return nil end local ok, err if ffi.istype(t.in6_addr, address) then ok, err = nl.newaddr(i.index, c.AF.INET6, netmask, "permanent", "local", address) else local broadcast = address:get_mask_bcast(netmask).broadcast ok, err = nl.newaddr(i.index, c.AF.INET, netmask, "permanent", "local", address, "broadcast", broadcast) end if not ok then return nil, err end return i:refresh() end, deladdress = function(i, address, netmask) if type(address) == "string" then address, netmask = util.inet_name(address, netmask) end if not address then return nil end local af if ffi.istype(t.in6_addr, address) then af = c.AF.INET6 else af = c.AF.INET end local ok, err = nl.deladdr(i.index, af, netmask, "local", address) if not ok then return nil, err end return i:refresh() end, delete = function(i) local ok, err = nl.dellink(i.index) if not ok then return nil, err end return true end, move_ns = function(i, ns) -- TODO also support file descriptor form as well as pid local ok, err = nl.newlink(i.index, 0, 0, 0, "net_ns_pid", ns) if not ok then return nil, err end return true -- no longer here so cannot refresh end, rename = function(i, name) local ok, err = nl.newlink(i.index, 0, 0, 0, "ifname", name) if not ok then return nil, err end i.name = name -- refresh not working otherwise as done by name TODO fix so by index return i:refresh() end, refresh = function(i) local j, err = nl.interface(i.name) if not j then return nil, err end for k, _ in pairs(i) do i[k] = nil end for k, v in pairs(j) do i[k] = v end return i end, } } mt.iflink = { __index = function(i, k) if meth.iflink.index[k] then return meth.iflink.index[k](i) end if meth.iflink.fn[k] then return meth.iflink.fn[k] end if k == "inet" or k == "inet6" then return end -- might not be set, as we add it, kernel does not provide if c.ARPHRD[k] then return i.ifinfo.ifi_type == c.ARPHRD[k] end end, __tostring = function(i) local hw = '' if not i.loopback and i.macaddr then hw = ' HWaddr ' .. tostring(i.macaddr) end local s = i.name .. string.rep(' ', 10 - #i.name) .. 'Link encap:' .. i.typename .. hw .. '\n' if i.inet then for a = 1, #i.inet do s = s .. ' ' .. 'inet addr: ' .. tostring(i.inet[a].addr) .. '/' .. i.inet[a].prefixlen .. '\n' end end if i.inet6 then for a = 1, #i.inet6 do s = s .. ' ' .. 'inet6 addr: ' .. tostring(i.inet6[a].addr) .. '/' .. i.inet6[a].prefixlen .. '\n' end end s = s .. ' ' .. tostring(i.flags) .. ' MTU: ' .. i.mtu .. '\n' s = s .. ' ' .. 'RX packets:' .. i.stats.rx_packets .. ' errors:' .. i.stats.rx_errors .. ' dropped:' .. i.stats.rx_dropped .. '\n' s = s .. ' ' .. 'TX packets:' .. i.stats.tx_packets .. ' errors:' .. i.stats.tx_errors .. ' dropped:' .. i.stats.tx_dropped .. '\n' return s end } meth.rtmsg = { index = { family = function(i) return tonumber(i.rtmsg.rtm_family) end, dst_len = function(i) return tonumber(i.rtmsg.rtm_dst_len) end, src_len = function(i) return tonumber(i.rtmsg.rtm_src_len) end, index = function(i) return tonumber(i.oif) end, flags = function(i) return tonumber(i.rtmsg.rtm_flags) end, dest = function(i) return i.dst or addrtype(i.family) end, source = function(i) return i.src or addrtype(i.family) end, gw = function(i) return i.gateway or addrtype(i.family) end, -- might not be set in Lua table, so return nil iif = function() return nil end, oif = function() return nil end, src = function() return nil end, dst = function() return nil end, }, flags = { -- TODO rework so iterates in fixed order. TODO Do not seem to be set, find how to retrieve. [c.RTF.UP] = "U", [c.RTF.GATEWAY] = "G", [c.RTF.HOST] = "H", [c.RTF.REINSTATE] = "R", [c.RTF.DYNAMIC] = "D", [c.RTF.MODIFIED] = "M", [c.RTF.REJECT] = "!", } } mt.rtmsg = { __index = function(i, k) if meth.rtmsg.index[k] then return meth.rtmsg.index[k](i) end -- if S.RTF[k] then return bit.band(i.flags, S.RTF[k]) ~= 0 end -- TODO see above end, __tostring = function(i) -- TODO make more like output of ip route local s = "dst: " .. tostring(i.dest) .. "/" .. i.dst_len .. " gateway: " .. tostring(i.gw) .. " src: " .. tostring(i.source) .. "/" .. i.src_len .. " if: " .. (i.output or i.oif) return s end, } meth.routes = { fn = { match = function(rs, addr, len) -- exact match if type(addr) == "string" then local sl = addr:find("/", 1, true) if sl then len = tonumber(addr:sub(sl + 1)) addr = addr:sub(1, sl - 1) end if rs.family == c.AF.INET6 then addr = t.in6_addr(addr) else addr = t.in_addr(addr) end end local matches = {} for _, v in ipairs(rs) do if len == v.dst_len then if v.family == c.AF.INET then if addr.s_addr == v.dest.s_addr then matches[#matches + 1] = v end else local match = true for i = 0, 15 do if addr.s6_addr[i] ~= v.dest.s6_addr[i] then match = false end end if match then matches[#matches + 1] = v end end end end matches.tp, matches.family = rs.tp, rs.family return setmetatable(matches, mt.routes) end, refresh = function(rs) local nr = nl.routes(rs.family, rs.tp) for k, _ in pairs(rs) do rs[k] = nil end for k, v in pairs(nr) do rs[k] = v end return rs end, } } mt.routes = { __index = function(i, k) if meth.routes.fn[k] then return meth.routes.fn[k] end end, __tostring = function(is) local s = {} for k, v in ipairs(is) do s[#s + 1] = tostring(v) end return table.concat(s, '\n') end, } meth.ifaddr = { index = { family = function(i) return tonumber(i.ifaddr.ifa_family) end, prefixlen = function(i) return tonumber(i.ifaddr.ifa_prefixlen) end, index = function(i) return tonumber(i.ifaddr.ifa_index) end, flags = function(i) return tonumber(i.ifaddr.ifa_flags) end, scope = function(i) return tonumber(i.ifaddr.ifa_scope) end, } } mt.ifaddr = { __index = function(i, k) if meth.ifaddr.index[k] then return meth.ifaddr.index[k](i) end if c.IFA_F[k] then return bit.band(i.ifaddr.ifa_flags, c.IFA_F[k]) ~= 0 end end } -- TODO functions repetitious local function decode_link(buf, len) local iface = pt.ifinfomsg(buf) buf = buf + nlmsg_align(s.ifinfomsg) len = len - nlmsg_align(s.ifinfomsg) local rtattr = pt.rtattr(buf) local ir = setmetatable({ifinfo = t.ifinfomsg()}, mt.iflink) ffi.copy(ir.ifinfo, iface, s.ifinfomsg) while rta_ok(rtattr, len) do if ifla_decode[rtattr.rta_type] then ifla_decode[rtattr.rta_type](ir, buf + rta_length(0), rta_align(rtattr.rta_len) - rta_length(0)) end rtattr, buf, len = rta_next(rtattr, buf, len) end return ir end local function decode_address(buf, len) local addr = pt.ifaddrmsg(buf) buf = buf + nlmsg_align(s.ifaddrmsg) len = len - nlmsg_align(s.ifaddrmsg) local rtattr = pt.rtattr(buf) local ir = setmetatable({ifaddr = t.ifaddrmsg(), addr = {}}, mt.ifaddr) ffi.copy(ir.ifaddr, addr, s.ifaddrmsg) while rta_ok(rtattr, len) do if ifa_decode[rtattr.rta_type] then ifa_decode[rtattr.rta_type](ir, buf + rta_length(0), rta_align(rtattr.rta_len) - rta_length(0)) end rtattr, buf, len = rta_next(rtattr, buf, len) end return ir end local function decode_route(buf, len) local rt = pt.rtmsg(buf) buf = buf + nlmsg_align(s.rtmsg) len = len - nlmsg_align(s.rtmsg) local rtattr = pt.rtattr(buf) local ir = setmetatable({rtmsg = t.rtmsg()}, mt.rtmsg) ffi.copy(ir.rtmsg, rt, s.rtmsg) while rta_ok(rtattr, len) do if rta_decode[rtattr.rta_type] then rta_decode[rtattr.rta_type](ir, buf + rta_length(0), rta_align(rtattr.rta_len) - rta_length(0)) else error("NYI: " .. rtattr.rta_type) end rtattr, buf, len = rta_next(rtattr, buf, len) end return ir end local function decode_neigh(buf, len) local rt = pt.rtmsg(buf) buf = buf + nlmsg_align(s.rtmsg) len = len - nlmsg_align(s.rtmsg) local rtattr = pt.rtattr(buf) local ir = setmetatable({rtmsg = t.rtmsg()}, mt.rtmsg) ffi.copy(ir.rtmsg, rt, s.rtmsg) while rta_ok(rtattr, len) do if nda_decode[rtattr.rta_type] then nda_decode[rtattr.rta_type](ir, buf + rta_length(0), rta_align(rtattr.rta_len) - rta_length(0)) else error("NYI: " .. rtattr.rta_type) end rtattr, buf, len = rta_next(rtattr, buf, len) end return ir end -- TODO other than the first few these could be a table local nlmsg_data_decode = { [c.NLMSG.NOOP] = function(r, buf, len) return r end, [c.NLMSG.ERROR] = function(r, buf, len) local e = pt.nlmsgerr(buf) if e.error ~= 0 then r.error = t.error(-e.error) else r.ack = true end -- error zero is ACK, others negative return r end, [c.NLMSG.DONE] = function(r, buf, len) return r end, [c.NLMSG.OVERRUN] = function(r, buf, len) r.overrun = true return r end, [c.RTM.NEWADDR] = function(r, buf, len) local ir = decode_address(buf, len) ir.op, ir.newaddr, ir.nl = "newaddr", true, c.RTM.NEWADDR r[#r + 1] = ir return r end, [c.RTM.DELADDR] = function(r, buf, len) local ir = decode_address(buf, len) ir.op, ir.deladdr, ir.nl = "delddr", true, c.RTM.DELADDR r[#r + 1] = ir return r end, [c.RTM.GETADDR] = function(r, buf, len) local ir = decode_address(buf, len) ir.op, ir.getaddr, ir.nl = "getaddr", true, c.RTM.GETADDR r[#r + 1] = ir return r end, [c.RTM.NEWLINK] = function(r, buf, len) local ir = decode_link(buf, len) ir.op, ir.newlink, ir.nl = "newlink", true, c.RTM.NEWLINK r[ir.name] = ir r[#r + 1] = ir return r end, [c.RTM.DELLINK] = function(r, buf, len) local ir = decode_link(buf, len) ir.op, ir.dellink, ir.nl = "dellink", true, c.RTM.DELLINK r[ir.name] = ir r[#r + 1] = ir return r end, -- TODO need test that returns these, assume updates do [c.RTM.GETLINK] = function(r, buf, len) local ir = decode_link(buf, len) ir.op, ir.getlink, ir.nl = "getlink", true, c.RTM.GETLINK r[ir.name] = ir r[#r + 1] = ir return r end, [c.RTM.NEWROUTE] = function(r, buf, len) local ir = decode_route(buf, len) ir.op, ir.newroute, ir.nl = "newroute", true, c.RTM.NEWROUTE r[#r + 1] = ir return r end, [c.RTM.DELROUTE] = function(r, buf, len) local ir = decode_route(buf, len) ir.op, ir.delroute, ir.nl = "delroute", true, c.RTM.DELROUTE r[#r + 1] = ir return r end, [c.RTM.GETROUTE] = function(r, buf, len) local ir = decode_route(buf, len) ir.op, ir.getroute, ir.nl = "getroute", true, c.RTM.GETROUTE r[#r + 1] = ir return r end, [c.RTM.NEWNEIGH] = function(r, buf, len) local ir = decode_neigh(buf, len) ir.op, ir.newneigh, ir.nl = "newneigh", true, c.RTM.NEWNEIGH r[#r + 1] = ir return r end, [c.RTM.DELNEIGH] = function(r, buf, len) local ir = decode_neigh(buf, len) ir.op, ir.delneigh, ir.nl = "delneigh", true, c.RTM.DELNEIGH r[#r + 1] = ir return r end, [c.RTM.GETNEIGH] = function(r, buf, len) local ir = decode_neigh(buf, len) ir.op, ir.getneigh, ir.nl = "getneigh", true, c.RTM.GETNEIGH r[#r + 1] = ir return r end, } function nl.read(s, addr, bufsize, untildone) addr = addr or t.sockaddr_nl() -- default to kernel bufsize = bufsize or 8192 local reply = t.buffer(bufsize) local ior = t.iovecs{{reply, bufsize}} local m = t.msghdr{msg_iov = ior.iov, msg_iovlen = #ior, msg_name = addr, msg_namelen = ffi.sizeof(addr)} local done = false -- what should we do if we get a done message but there is some extra buffer? could be next message... local r = {} while not done do local len, err = s:recvmsg(m) if not len then return nil, err end local buffer = reply local msg = pt.nlmsghdr(buffer) while not done and nlmsg_ok(msg, len) do local tp = tonumber(msg.nlmsg_type) if nlmsg_data_decode[tp] then r = nlmsg_data_decode[tp](r, buffer + nlmsg_hdrlen, msg.nlmsg_len - nlmsg_hdrlen) if r.overrun then return S.read(s, addr, bufsize * 2) end -- TODO add test if r.error then return nil, r.error end -- not sure what the errors mean though! if r.ack then done = true end else error("unknown data " .. tp) end if tp == c.NLMSG.DONE then done = true end msg, buffer, len = nlmsg_next(msg, buffer, len) end if not untildone then done = true end end return r end -- TODO share with read side local ifla_msg_types = { ifla = { -- IFLA.UNSPEC [c.IFLA.ADDRESS] = t.macaddr, [c.IFLA.BROADCAST] = t.macaddr, [c.IFLA.IFNAME] = "asciiz", -- TODO IFLA.MAP [c.IFLA.MTU] = t.uint32, [c.IFLA.LINK] = t.uint32, [c.IFLA.MASTER] = t.uint32, [c.IFLA.TXQLEN] = t.uint32, [c.IFLA.WEIGHT] = t.uint32, [c.IFLA.OPERSTATE] = t.uint8, [c.IFLA.LINKMODE] = t.uint8, [c.IFLA.LINKINFO] = {"ifla_info", c.IFLA_INFO}, [c.IFLA.NET_NS_PID] = t.uint32, [c.IFLA.NET_NS_FD] = t.uint32, [c.IFLA.IFALIAS] = "asciiz", --[c.IFLA.VFINFO_LIST] = "nested", --[c.IFLA.VF_PORTS] = "nested", --[c.IFLA.PORT_SELF] = "nested", --[c.IFLA.AF_SPEC] = "nested", }, ifla_info = { [c.IFLA_INFO.KIND] = "ascii", [c.IFLA_INFO.DATA] = "kind", }, ifla_vlan = { [c.IFLA_VLAN.ID] = t.uint16, -- other vlan params }, ifa = { -- IFA.UNSPEC [c.IFA.ADDRESS] = "address", [c.IFA.LOCAL] = "address", [c.IFA.LABEL] = "asciiz", [c.IFA.BROADCAST] = "address", [c.IFA.ANYCAST] = "address", -- IFA.CACHEINFO }, rta = { -- RTA_UNSPEC [c.RTA.DST] = "address", [c.RTA.SRC] = "address", [c.RTA.IIF] = t.uint32, [c.RTA.OIF] = t.uint32, [c.RTA.GATEWAY] = "address", [c.RTA.PRIORITY] = t.uint32, [c.RTA.METRICS] = t.uint32, -- RTA.PREFSRC -- RTA.MULTIPATH -- RTA.PROTOINFO -- RTA.FLOW -- RTA.CACHEINFO }, veth_info = { -- VETH_INFO_UNSPEC [c.VETH_INFO.PEER] = {"ifla", c.IFLA}, }, nda = { [c.NDA.DST] = "address", [c.NDA.LLADDR] = t.macaddr, [c.NDA.CACHEINFO] = t.nda_cacheinfo, -- [c.NDA.PROBES] = , }, } --[[ TODO add static const struct nla_policy ifla_vfinfo_policy[IFLA_VF_INFO_MAX+1] = { [IFLA_VF_INFO] = { .type = NLA_NESTED }, }; static const struct nla_policy ifla_vf_policy[IFLA_VF_MAX+1] = { [IFLA_VF_MAC] = { .type = NLA_BINARY, .len = sizeof(struct ifla_vf_mac) }, [IFLA_VF_VLAN] = { .type = NLA_BINARY, .len = sizeof(struct ifla_vf_vlan) }, [IFLA_VF_TX_RATE] = { .type = NLA_BINARY, .len = sizeof(struct ifla_vf_tx_rate) }, [IFLA_VF_SPOOFCHK] = { .type = NLA_BINARY, .len = sizeof(struct ifla_vf_spoofchk) }, }; static const struct nla_policy ifla_port_policy[IFLA_PORT_MAX+1] = { [IFLA_PORT_VF] = { .type = NLA_U32 }, [IFLA_PORT_PROFILE] = { .type = NLA_STRING, .len = PORT_PROFILE_MAX }, [IFLA_PORT_VSI_TYPE] = { .type = NLA_BINARY, .len = sizeof(struct ifla_port_vsi)}, [IFLA_PORT_INSTANCE_UUID] = { .type = NLA_BINARY, .len = PORT_UUID_MAX }, [IFLA_PORT_HOST_UUID] = { .type = NLA_STRING, .len = PORT_UUID_MAX }, [IFLA_PORT_REQUEST] = { .type = NLA_U8, }, [IFLA_PORT_RESPONSE] = { .type = NLA_U16, }, }; ]] local function ifla_getmsg(args, messages, values, tab, lookup, kind, af) local msg = table.remove(args, 1) local value, len local tp if type(msg) == "table" then -- for nested attributes local nargs = msg len = 0 while #nargs ~= 0 do local nlen nlen, nargs, messages, values, kind = ifla_getmsg(nargs, messages, values, tab, lookup, kind, af) len = len + nlen end return len, args, messages, values, kind end if type(msg) == "cdata" or type(msg) == "userdata" then tp = msg value = table.remove(args, 1) if not value then error("not enough arguments") end value = mktype(tp, value) len = ffi.sizeof(value) messages[#messages + 1] = tp values[#values + 1] = value return len, args, messages, values, kind end local rawmsg = msg msg = lookup[msg] tp = ifla_msg_types[tab][msg] if not tp then error("unknown message type " .. tostring(rawmsg) .. " in " .. tab) end if tp == "kind" then local kinds = { vlan = {"ifla_vlan", c.IFLA_VLAN}, veth = {"veth_info", c.VETH_INFO}, } tp = kinds[kind] end if type(tp) == "table" then value = t.rtattr{rta_type = msg} -- missing rta_len, but have reference and can fix messages[#messages + 1] = t.rtattr values[#values + 1] = value tab, lookup = tp[1], tp[2] len, args, messages, values, kind = ifla_getmsg(args, messages, values, tab, lookup, kind, af) len = nlmsg_align(s.rtattr) + len value.rta_len = len return len, args, messages, values, kind -- recursion base case, just a value, not nested else value = table.remove(args, 1) if not value then error("not enough arguments") end end if tab == "ifla_info" and msg == c.IFLA_INFO.KIND then kind = value end local slen if tp == "asciiz" then -- zero terminated tp = t.buffer(#value + 1) slen = nlmsg_align(s.rtattr) + #value + 1 elseif tp == "ascii" then -- not zero terminated tp = t.buffer(#value) slen = nlmsg_align(s.rtattr) + #value else if tp == "address" then tp = adtt[tonumber(af)] end value = mktype(tp, value) end len = nlmsg_align(s.rtattr) + nlmsg_align(ffi.sizeof(tp)) slen = slen or len messages[#messages + 1] = t.rtattr messages[#messages + 1] = tp values[#values + 1] = t.rtattr{rta_type = msg, rta_len = slen} values[#values + 1] = value return len, args, messages, values, kind end local function ifla_f(tab, lookup, af, ...) local len, kind local messages, values = {t.nlmsghdr}, {false} local args = {...} while #args ~= 0 do len, args, messages, values, kind = ifla_getmsg(args, messages, values, tab, lookup, kind, af) end local len = 0 local offsets = {} local alignment = nlmsg_align(1) for i, tp in ipairs(messages) do local item_alignment = align(ffi.sizeof(tp), alignment) offsets[i] = len len = len + item_alignment end local buf = t.buffer(len) for i = 2, #offsets do -- skip header local value = values[i] if type(value) == "string" then ffi.copy(buf + offsets[i], value) else -- slightly nasty if ffi.istype(t.uint32, value) then value = t.uint32_1(value) end if ffi.istype(t.uint16, value) then value = t.uint16_1(value) end if ffi.istype(t.uint8, value) then value = t.uint8_1(value) end ffi.copy(buf + offsets[i], value, ffi.sizeof(value)) end end return buf, len end local rtpref = { [c.RTM.NEWLINK] = {"ifla", c.IFLA}, [c.RTM.GETLINK] = {"ifla", c.IFLA}, [c.RTM.DELLINK] = {"ifla", c.IFLA}, [c.RTM.NEWADDR] = {"ifa", c.IFA}, [c.RTM.GETADDR] = {"ifa", c.IFA}, [c.RTM.DELADDR] = {"ifa", c.IFA}, [c.RTM.NEWROUTE] = {"rta", c.RTA}, [c.RTM.GETROUTE] = {"rta", c.RTA}, [c.RTM.DELROUTE] = {"rta", c.RTA}, [c.RTM.NEWNEIGH] = {"nda", c.NDA}, [c.RTM.DELNEIGH] = {"nda", c.NDA}, [c.RTM.GETNEIGH] = {"nda", c.NDA}, [c.RTM.NEWNEIGHTBL] = {"ndtpa", c.NDTPA}, [c.RTM.GETNEIGHTBL] = {"ndtpa", c.NDTPA}, [c.RTM.SETNEIGHTBL] = {"ndtpa", c.NDTPA}, } function nl.socket(tp, addr) tp = c.NETLINK[tp] local sock, err = S.socket(c.AF.NETLINK, c.SOCK.RAW, tp) if not sock then return nil, err end if addr then if type(addr) == "table" then addr.type = tp end -- need type to convert group names from string if not ffi.istype(t.sockaddr_nl, addr) then addr = t.sockaddr_nl(addr) end local ok, err = S.bind(sock, addr) if not ok then S.close(sock) return nil, err end end return sock end function nl.write(sock, dest, ntype, flags, af, ...) local a, err = sock:getsockname() -- to get bound address if not a then return nil, err end dest = dest or t.sockaddr_nl() -- kernel destination default local tl = rtpref[ntype] if not tl then error("NYI: ", ntype) end local tab, lookup = tl[1], tl[2] local buf, len = ifla_f(tab, lookup, af, ...) local hdr = pt.nlmsghdr(buf) hdr[0] = {nlmsg_len = len, nlmsg_type = ntype, nlmsg_flags = flags, nlmsg_seq = sock:seq(), nlmsg_pid = a.pid} local ios = t.iovecs{{buf, len}} local m = t.msghdr{msg_iov = ios.iov, msg_iovlen = #ios, msg_name = dest, msg_namelen = s.sockaddr_nl} return sock:sendmsg(m) end -- TODO "route" should be passed in as parameter, test with other netlink types local function nlmsg(ntype, flags, af, ...) ntype = c.RTM[ntype] flags = c.NLM_F[flags] local sock, err = nl.socket("route", {}) -- bind to empty sockaddr_nl, kernel fills address if not sock then return nil, err end local k = t.sockaddr_nl() -- kernel destination local ok, err = nl.write(sock, k, ntype, flags, af, ...) if not ok then sock:close() return nil, err end local r, err = nl.read(sock, k, nil, true) -- true means until get done message if not r then sock:close() return nil, err end local ok, err = sock:close() if not ok then return nil, err end return r end -- TODO do not have all these different arguments for these functions, pass a table for initialization. See also iplink. function nl.newlink(index, flags, iflags, change, ...) if change == 0 then change = c.IFF.NONE end -- 0 should work, but does not flags = c.NLM_F("request", "ack", flags) if type(index) == 'table' then index = index.index end local ifv = {ifi_index = index, ifi_flags = c.IFF[iflags], ifi_change = c.IFF[change]} return nlmsg("newlink", flags, nil, t.ifinfomsg, ifv, ...) end function nl.dellink(index, ...) if type(index) == 'table' then index = index.index end local ifv = {ifi_index = index} return nlmsg("dellink", "request, ack", nil, t.ifinfomsg, ifv, ...) end -- read interfaces and details. function nl.getlink(...) return nlmsg("getlink", "request, dump", nil, t.rtgenmsg, {rtgen_family = c.AF.PACKET}, ...) end -- read routes function nl.getroute(af, tp, tab, prot, scope, ...) local rtm = t.rtmsg{family = af, table = tab, protocol = prot, type = tp, scope = scope} local r, err = nlmsg(c.RTM.GETROUTE, "request, dump", af, t.rtmsg, rtm) if not r then return nil, err end return setmetatable(r, mt.routes) end function nl.routes(af, tp) af = c.AF[af] if not tp then tp = c.RTN.UNICAST end tp = c.RTN[tp] local r, err = nl.getroute(af, tp) if not r then return nil, err end local ifs, err = nl.getlink() if not ifs then return nil, err end local indexmap = {} -- TODO turn into metamethod as used elsewhere for i, v in pairs(ifs) do v.inet, v.inet6 = {}, {} indexmap[v.index] = i end for k, v in ipairs(r) do if ifs[indexmap[v.iif]] then v.input = ifs[indexmap[v.iif]].name end if ifs[indexmap[v.oif]] then v.output = ifs[indexmap[v.oif]].name end if tp > 0 and v.rtmsg.rtm_type ~= tp then r[k] = nil end -- filter unwanted routes end r.family = af r.tp = tp return r end local function preftable(tab, prefix) for k, v in pairs(tab) do if k:sub(1, #prefix) ~= prefix then tab[prefix .. k] = v tab[k] = nil end end return tab end function nl.newroute(flags, rtm, ...) flags = c.NLM_F("request", "ack", flags) rtm = mktype(t.rtmsg, rtm) return nlmsg("newroute", flags, rtm.family, t.rtmsg, rtm, ...) end function nl.delroute(rtm, ...) rtm = mktype(t.rtmsg, rtm) return nlmsg("delroute", "request, ack", rtm.family, t.rtmsg, rtm, ...) end -- read addresses from interface TODO flag cleanup function nl.getaddr(af, ...) local family = c.AF[af] local ifav = {ifa_family = family} return nlmsg("getaddr", "request, root", family, t.ifaddrmsg, ifav, ...) end -- TODO may need ifa_scope function nl.newaddr(index, af, prefixlen, flags, ...) if type(index) == 'table' then index = index.index end local family = c.AF[af] local ifav = {ifa_family = family, ifa_prefixlen = prefixlen or 0, ifa_flags = c.IFA_F[flags], ifa_index = index} --__TODO in __new return nlmsg("newaddr", "request, ack", family, t.ifaddrmsg, ifav, ...) end function nl.deladdr(index, af, prefixlen, ...) if type(index) == 'table' then index = index.index end local family = c.AF[af] local ifav = {ifa_family = family, ifa_prefixlen = prefixlen or 0, ifa_flags = 0, ifa_index = index} return nlmsg("deladdr", "request, ack", family, t.ifaddrmsg, ifav, ...) end function nl.getneigh(index, tab, ...) if type(index) == 'table' then index = index.index end tab.ifindex = index local ndm = t.ndmsg(tab) return nlmsg("getneigh", "request, dump", ndm.family, t.ndmsg, ndm, ...) end function nl.newneigh(index, tab, ...) if type(index) == 'table' then index = index.index end tab.ifindex = index local ndm = t.ndmsg(tab) return nlmsg("newneigh", "request, ack, excl, create", ndm.family, t.ndmsg, ndm, ...) end function nl.delneigh(index, tab, ...) if type(index) == 'table' then index = index.index end tab.ifindex = index local ndm = t.ndmsg(tab) return nlmsg("delneigh", "request, ack", ndm.family, t.ndmsg, ndm, ...) end function nl.interfaces() -- returns with address info too. local ifs, err = nl.getlink() if not ifs then return nil, err end local addr4, err = nl.getaddr(c.AF.INET) if not addr4 then return nil, err end local addr6, err = nl.getaddr(c.AF.INET6) if not addr6 then return nil, err end local indexmap = {} for i, v in pairs(ifs) do v.inet, v.inet6 = {}, {} indexmap[v.index] = i end for i = 1, #addr4 do local v = ifs[indexmap[addr4[i].index]] v.inet[#v.inet + 1] = addr4[i] end for i = 1, #addr6 do local v = ifs[indexmap[addr6[i].index]] v.inet6[#v.inet6 + 1] = addr6[i] end return setmetatable(ifs, mt.iflinks) end function nl.interface(i) -- could optimize just to retrieve info for one local ifs, err = nl.interfaces() if not ifs then return nil, err end return ifs[i] end local link_process_f local link_process = { -- TODO very incomplete. generate? name = function(args, v) return {"ifname", v} end, link = function(args, v) return {"link", v} end, address = function(args, v) return {"address", v} end, type = function(args, v, tab) if v == "vlan" then local id = tab.id if id then tab.id = nil return {"linkinfo", {"kind", "vlan", "data", {"id", id}}} end elseif v == "veth" then local peer = tab.peer tab.peer = nil local peertab = link_process_f(peer) return {"linkinfo", {"kind", "veth", "data", {"peer", {t.ifinfomsg, {}, peertab}}}} end return {"linkinfo", "kind", v} end, } function link_process_f(tab, args) args = args or {} for _, k in ipairs{"link", "name", "type"} do local v = tab[k] if v then if link_process[k] then local a = link_process[k](args, v, tab) for i = 1, #a do args[#args + 1] = a[i] end else error("bad iplink command " .. k) end end end return args end -- TODO better name. even more general, not just newlink. or make this the exposed newlink interface? -- I think this is generally a nicer interface to expose than the ones above, for all functions function nl.iplink(tab) local args = {tab.index or 0, tab.modifier or 0, tab.flags or 0, tab.change or 0} local args = link_process_f(tab, args) return nl.newlink(unpack(args)) end -- TODO iplink may not be appropriate always sort out flags function nl.create_interface(tab) tab.modifier = c.NLM_F.CREATE return nl.iplink(tab) end return nl end return {init = init}
apache-2.0
bsmr-games/lipsofsuna
data/system/color.lua
1
3660
--- Colorspace conversions and helpers. -- -- Lips of Suna is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. -- -- @module system.color -- @alias Color local Class = require("system/class") --- Colorspace conversions and helpers. -- @type Color local Color = Class("Color") --- Converts an HSV color to RGB. -- @param clss Color class. -- @param hsv HSV color. -- @return RGB color. Color.hsv_to_rgb = function(clss, hsv) local h,s,v = hsv[1],hsv[2],hsv[3] local c = v * s local l = v - c local hh = h * 6 local x = c * (1 - math.abs(hh % 2 - 1)) if 0 <= hh and hh < 1 then return {c + l, x + l, l} end if 1 <= hh and hh < 2 then return {x + l, c + l, l} end if 2 <= hh and hh < 3 then return {l, c + l, x + l} end if 3 <= hh and hh < 4 then return {l, x + l, c + l} end if 4 <= hh and hh < 5 then return {x + l, l, c + l} end return {c + l, l, x + l} end --- Converts an RGB color to HSV. -- @param clss Color class. -- @param rgb RGB color. -- @return HSV color. Color.rgb_to_hsv = function(clss, rgb) local eps = 0.00000001 local r,g,b = rgb[1],rgb[2],rgb[3] local v = math.max(math.max(r, g), b) local m = math.min(math.min(r, g), b) local c = v - m if c < eps then h = 0 elseif v == r then h = ((g - b) / c % 6) / 6 elseif v == g then h = ((b - r) / c + 2) / 6 elseif v == b then h = ((r - g) / c + 4) / 6 end if c < eps then s = 0 else s = c / v end return {h, s, v} end --- Converts a [0,1] color to [0,255] -- @param clss Color class. -- @param color color. -- @return Color. Color.float_to_ubyte = function(clss, color) if not color then return end return {color[1] * 255, color[2] * 255, color[3] * 255} end --- Converts a [0,255] color to [0,1] -- @param clss Color class. -- @param color color. -- @return Color. Color.ubyte_to_float = function(clss, color) if not color then return end return {color[1] / 255, color[2] / 255, color[3] / 255} end --- Multiplies the saturation of the RGB color. -- -- rgb' = mult * (rgb - max) + max -- -- @param clss Color class. -- @param rgb RGB color. -- @param mult Number. -- @return RGB color. Color.rgb_multiply_saturation = function(clss, rgb, mult) local v = math.max(math.max(rgb[1], rgb[2]), rgb[3]) return {(rgb[1] - v) * mult + v, (rgb[2] - v) * mult + v, (rgb[3] - v) * mult + v} end --- Multiplies the value of the RGB color. -- @param clss Color class. -- @param rgb RGB color. -- @param mult Number. -- @return RGB color. Color.rgb_multiply_value = function(clss, rgb, mult) return {rgb[1] * mult, rgb[2] * mult, rgb[3] * mult} end --- Sets the saturation of the RGB color. -- -- mult * (min - max) + max = max * (1 - sat') -- -- @param clss Color class. -- @param rgb RGB color. -- @param saturation Saturation. -- @return RGB color. Color.rgb_set_saturation = function(clss, rgb, saturation) local v = math.max(math.max(rgb[1], rgb[2]), rgb[3]) local m = math.min(math.min(rgb[1], rgb[2]), rgb[3]) if m == v then return {rgb[0], rgb[1], rgb[2]} end local mult = saturation * v / (v - m) return {(rgb[1] - v) * mult + v, (rgb[2] - v) * mult + v, (rgb[3] - v) * mult + v} end --- Sets the value of the RGB color. -- @param clss Color class. -- @param rgb RGB color. -- @param value Value. -- @return RGB color. Color.rgb_set_value = function(clss, rgb, value) local v = math.max(math.max(rgb[1], rgb[2]), rgb[3]) if v == 0 then return {value, value, value} end local mult = value / v return {rgb[1] * mult, rgb[2] * mult, rgb[3] * mult} end return Color
gpl-3.0
ashkanpj/seedfire
plugins/banhammer.lua
2
11452
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^(banall) (.*)$", "^(banall)$", "^(banlist) (.*)$", "^(banlist)$", "^(gbanlist)$", "^(ban) (.*)$", "^(kick)$", "^(unban) (.*)$", "^(unbanall) (.*)$", "^(unbanall)$", "^(kick) (.*)$", "^(kickme)$", "^(ban)$", "^(unban)$", "^(id)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
MustaphaTR/OpenRA
mods/ra/maps/sarin-gas-2-down-under/downunder.lua
7
15672
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] TanyaFreed = false TruckStolen = false SovietImportantGuys = { Officer3, Officer2, Officer1, Scientist1, Scientist2 } Camera1Towers = { FlameTower2, FlameTower3 } TruckExit = { TruckDrive1, TruckDrive2 } TruckEntry = { TruckDrive3.Location, TruckDrive4.Location, TruckDrive5.Location } TruckType = { "truk" } DogCrew = { DogCrew1, DogCrew2, DogCrew3 } SarinVictims = { SarinVictim1, SarinVictim2, SarinVictim3, SarinVictim4, SarinVictim5, SarinVictim6, SarinVictim7, SarinVictim8, SarinVictim9, SarinVictim10, SarinVictim11, SarinVictim12, SarinVictim13 } Camera2Team = { Camera2Rifle1, Camera2Rifle2, Camera2Rifle3, Camera2Gren1, Camera2Gren2 } PrisonAlarm = { CPos.New(55,75), CPos.New(55,76), CPos.New(55,77), CPos.New(55,81), CPos.New(55,82), CPos.New(55,83), CPos.New(60,77), CPos.New(60,81), CPos.New(60,82), CPos.New(60,83) } GuardDogs = { PrisonDog1, PrisonDog2, PrisonDog3, PrisonDog4 } TanyaTowers = { FlameTowerTanya1, FlameTowerTanya2 } ExecutionArea = { CPos.New(91, 70), CPos.New(92, 70), CPos.New(93, 70), CPos.New(94, 70) } FiringSquad = { FiringSquad1, FiringSquad2, FiringSquad3, FiringSquad4, FiringSquad5, Officer2 } DemoTeam = { DemoDog, DemoRifle1, DemoRifle2, DemoRifle3, DemoRifle4, DemoFlame } DemoTruckPath = { DemoDrive1, DemoDrive2, DemoDrive3, DemoDrive4 } WinTriggerArea = { CPos.New(111, 59), CPos.New(111, 60), CPos.New(111, 61), CPos.New(111, 62), CPos.New(111, 63), CPos.New(111, 64), CPos.New(111, 65) } ObjectiveTriggers = function() Trigger.OnEnteredFootprint(WinTriggerArea, function(a, id) if not EscapeGoalTrigger and a.Owner == greece then EscapeGoalTrigger = true greece.MarkCompletedObjective(ExitBase) if Difficulty == "hard" then greece.MarkCompletedObjective(NoCasualties) end if not TanyaFreed then greece.MarkFailedObjective(FreeTanya) else greece.MarkCompletedObjective(FreeTanya) end end end) Trigger.OnKilled(Tanya, function() greece.MarkFailedObjective(FreeTanya) end) Trigger.OnAllKilled(TanyaTowers, function() TanyaFreed = true if not Tanya.IsDead then Media.PlaySpeechNotification(greece, "TanyaRescued") Tanya.Owner = greece end end) Trigger.OnAllKilled(SovietImportantGuys, function() greece.MarkCompletedObjective(KillVIPs) end) Trigger.OnInfiltrated(WarFactory2, function() if not StealMammoth.IsDead or StealMammoth.Owner == ussr then greece.MarkCompletedObjective(StealTank) StealMammoth.Owner = greece end end) end ConsoleTriggers = function() Trigger.OnEnteredProximityTrigger(Terminal1.CenterPosition, WDist.FromCells(1), function(actor, id) if actor.Owner == greece then Trigger.RemoveProximityTrigger(id) if not FlameTower1.IsDead then Media.DisplayMessage("Flame Turret deactivated", "Console") FlameTower1.Kill() end end end) Trigger.OnEnteredProximityTrigger(Terminal2.CenterPosition, WDist.FromCells(1), function(actor, id) if actor.Owner == greece then Trigger.RemoveProximityTrigger(id) if not FlameTower2.IsDead then Media.DisplayMessage("Flame Turret deactivated", "Console") FlameTower2.Kill() end end end) Trigger.OnEnteredProximityTrigger(Terminal3.CenterPosition, WDist.FromCells(1), function(actor, id) if actor.Owner == greece then Trigger.RemoveProximityTrigger(id) if not FlameTower3.IsDead then Media.DisplayMessage("Flame Turret deactivated", "Console") FlameTower3.Kill() end end end) local gasActive Trigger.OnEnteredProximityTrigger(Terminal4.CenterPosition, WDist.FromCells(1), function(actor, id) if actor.Owner == greece and not gasActive then Trigger.RemoveProximityTrigger(id) gasActive = true Media.DisplayMessage("Sarin Nerve Gas dispensers activated", "Console") local KillCamera = Actor.Create("camera", true, { Owner = greece, Location = Sarin2.Location }) local flare1 = Actor.Create("flare", true, { Owner = england, Location = Sarin1.Location }) local flare2 = Actor.Create("flare", true, { Owner = england, Location = Sarin2.Location }) local flare3 = Actor.Create("flare", true, { Owner = england, Location = Sarin3.Location }) local flare4 = Actor.Create("flare", true, { Owner = england, Location = Sarin4.Location }) Trigger.AfterDelay(DateTime.Seconds(4), function() Utils.Do(SarinVictims, function(actor) if not actor.IsDead then actor.Kill("ExplosionDeath") end end) end) Trigger.AfterDelay(DateTime.Seconds(20), function() flare1.Destroy() flare2.Destroy() flare3.Destroy() flare4.Destroy() KillCamera.Destroy() end) end end) Trigger.OnEnteredProximityTrigger(Terminal5.CenterPosition, WDist.FromCells(1), function(actor, id) if actor.Owner == greece then Trigger.RemoveProximityTrigger(id) if not BadCoil.IsDead then Media.DisplayMessage("Tesla Coil deactivated", "Console") BadCoil.Kill() end end end) local teslaActive Trigger.OnEnteredProximityTrigger(Terminal6.CenterPosition, WDist.FromCells(1), function(actor, id) if actor.Owner == greece and not teslaActive then Trigger.RemoveProximityTrigger(id) teslaActive = true Media.DisplayMessage("Initialising Tesla Coil defence", "Console") local tesla1 = Actor.Create("tsla", true, { Owner = turkey, Location = TurkeyCoil1.Location }) local tesla2 = Actor.Create("tsla", true, { Owner = turkey, Location = TurkeyCoil2.Location }) Trigger.AfterDelay(DateTime.Seconds(10), function() if not tesla1.IsDead then tesla1.Kill() end if not tesla2.IsDead then tesla2.Kill() end end) end end) Trigger.OnEnteredProximityTrigger(Terminal7.CenterPosition, WDist.FromCells(1), function(actor, id) if actor.Owner == greece then Trigger.RemoveProximityTrigger(id) if not FlameTowerTanya1.IsDead then Media.DisplayMessage("Flame Turret deactivated", "Console") FlameTowerTanya1.Kill() end if not FlameTowerTanya2.IsDead then Media.DisplayMessage("Flame Turret deactivated", "Console") FlameTowerTanya2.Kill() end end end) Trigger.OnEnteredProximityTrigger(Terminal8.CenterPosition, WDist.FromCells(1), function(actor, id) if actor.Owner == greece then Trigger.RemoveProximityTrigger(id) if not FlameTowerExit1.IsDead then Media.DisplayMessage("Flame Turret deactivated", "Console") FlameTowerExit1.Kill() end if not FlameTowerExit3.IsDead then Media.DisplayMessage("Flame Turret deactivated", "Console") FlameTowerExit3.Kill() end end end) end CameraTriggers = function() Trigger.AfterDelay(DateTime.Seconds(1), function() local startCamera = Actor.Create("camera", true, { Owner = greece, Location = start.Location }) Trigger.AfterDelay(DateTime.Seconds(10), function() startCamera.Destroy() end) end) local cam1Triggered Trigger.OnEnteredProximityTrigger(CameraTrigger1.CenterPosition, WDist.FromCells(8), function(actor, id) if actor.Owner == greece and not cam1Triggered then Trigger.RemoveProximityTrigger(id) cam1Triggered = true local camera1 = Actor.Create("camera", true, { Owner = greece, Location = CameraTrigger1.Location }) Trigger.OnAllKilled(Camera1Towers, function() camera1.Destroy() end) end end) local cam2Triggered Trigger.OnEnteredProximityTrigger(CameraTrigger2.CenterPosition, WDist.FromCells(8), function(actor, id) if actor.Owner == greece and not cam2Triggered then Trigger.RemoveProximityTrigger(id) cam2Triggered = true local camera2 = Actor.Create("camera", true, { Owner = greece, Location = CameraTrigger2.Location }) Utils.Do(Camera2Team, function(actor) actor.AttackMove(CameraTrigger1.Location) end) Trigger.AfterDelay(DateTime.Seconds(10), function() camera2.Destroy() end) end end) local cam3Triggered Trigger.OnEnteredProximityTrigger(CameraTrigger3.CenterPosition, WDist.FromCells(8), function(actor, id) if actor.Owner == greece and not cam3Triggered then Trigger.RemoveProximityTrigger(id) cam3Triggered = true local camera3 = Actor.Create("camera", true, { Owner = greece, Location = CameraTrigger3.Location }) Actor.Create("apwr", true, { Owner = france, Location = PowerPlantSpawn1.Location }) Actor.Create("apwr", true, { Owner = germany, Location = PowerPlantSpawn2.Location }) if not Mammoth1.IsDead then Mammoth1.AttackMove(MammothGo.Location) end Trigger.OnKilled(Mammoth1, function() GoodCoil.Kill() camera3.Destroy() end) end end) local cam4Triggered Trigger.OnEnteredProximityTrigger(CameraTrigger4.CenterPosition, WDist.FromCells(9), function(actor, id) if actor.Owner == greece and not cam4Triggered then Trigger.RemoveProximityTrigger(id) cam4Triggered = true local camera4 = Actor.Create("camera", true, { Owner = greece, Location = CameraTrigger4.Location }) Trigger.OnKilled(Mammoth2, function() camera4.Destroy() end) end end) local cam5Triggered Trigger.OnEnteredProximityTrigger(CameraTrigger5.CenterPosition, WDist.FromCells(8), function(actor, id) if actor.Owner == greece and not cam5Triggered then Trigger.RemoveProximityTrigger(id) cam5Triggered = true local camera5 = Actor.Create("camera", true, { Owner = greece, Location = CameraTrigger5.Location }) Trigger.AfterDelay(DateTime.Seconds(10), function() camera5.Destroy() end) end end) local cam6Triggered Trigger.OnEnteredProximityTrigger(CameraTrigger6.CenterPosition, WDist.FromCells(11), function(actor, id) if actor.Owner == greece and not cam6Triggered then Trigger.RemoveProximityTrigger(id) cam6Triggered = true Actor.Create("camera", true, { Owner = greece, Location = CameraTrigger6.Location }) end end) local executionTriggered Trigger.OnEnteredFootprint(ExecutionArea, function(actor, id) if actor.Owner == greece and not executionTriggered then Trigger.RemoveFootprintTrigger(id) executionTriggered = true local camera7 = Actor.Create("camera", true, { Owner = greece, Location = CameraTrigger7.Location }) Trigger.AfterDelay(DateTime.Seconds(25), function() camera7.Destroy() end) ScientistExecution() end end) end TruckSteal = function() Trigger.OnInfiltrated(WarFactory1, function() if not TruckStolen and not StealTruck.IsDead then TruckStolen = true local truckSteal1 = Actor.Create("camera", true, { Owner = greece, Location = TruckDrive1.Location }) Trigger.AfterDelay(DateTime.Seconds(10), function() truckSteal1.Destroy() end) Utils.Do(TruckExit, function(waypoint) StealTruck.Move(waypoint.Location) end) end end) local trukDestroyed Trigger.OnEnteredFootprint({ TruckDrive2.Location }, function(actor, id) if actor.Type == "truk" and not trukDestroyed then Trigger.RemoveFootprintTrigger(id) trukDestroyed = true actor.Destroy() Trigger.AfterDelay(DateTime.Seconds(3), function() SpyTruckDrive() end) end end) end SpyTruckDrive = function() StealTruck = Reinforcements.Reinforce(ussr, TruckType, TruckEntry) local truckSteal2 = Actor.Create("camera", true, { Owner = greece, Location = TruckCamera.Location }) Trigger.AfterDelay(DateTime.Seconds(10), function() truckSteal2.Destroy() end) local spyCreated Trigger.OnEnteredFootprint({ TruckDrive5.Location }, function(actor, id) if actor.Type == "truk" and not spyCreated then Trigger.RemoveFootprintTrigger(id) spyCreated = true Spy = Actor.Create("spy", true, { Owner = greece, Location = TruckDrive5.Location }) Spy.DisguiseAsType("e1", ussr) Spy.Move(SpyMove.Location) local dogCrewCamera = Actor.Create("camera", true, { Owner = greece, Location = DoggyCam.Location }) Trigger.AfterDelay(DateTime.Seconds(10), function() dogCrewCamera.Destroy() end) Utils.Do(DogCrew, function(actor) if not actor.IsDead then actor.AttackMove(DoggyMove.Location) end end) end end) end PrisonEscape = function() local alarmed Trigger.OnEnteredFootprint(PrisonAlarm, function(unit, id) if alarmed then return end alarmed = true Trigger.RemoveFootprintTrigger(id) Media.DisplayMessage("Warning, prisoners are attempting to escape!", "Intercom") Media.PlaySoundNotification(greece, "AlertBuzzer") Utils.Do(GuardDogs, IdleHunt) end) end ScientistExecution = function() Media.PlaySoundNotification(greece, "AlertBleep") Media.DisplayMessage("The base is compromised. We have to hurry the execution!", "Soviet Officer") Utils.Do(DemoTeam, function(actor) actor.AttackMove(DemoDrive2.Location) end) Trigger.OnAllKilled(FiringSquad, function() if not ScientistMan.IsDead then ScientistRescued() end end) Trigger.AfterDelay(DateTime.Seconds(7), function() if not Officer2.IsDead then Media.DisplayMessage("Prepare to Fire!", "Soviet Officer") end end) Trigger.AfterDelay(DateTime.Seconds(15), function() if not Officer2.IsDead then Media.DisplayMessage("Fire!", "Soviet Officer") end Utils.Do(FiringSquad, function(actor) if not actor.IsDead then actor.Attack(ScientistMan, true, true) end end) end) end ScientistRescued = function() Media.DisplayMessage("Thanks for the rescue!", "Scientist") Trigger.AfterDelay(DateTime.Seconds(5), function() if not ScientistMan.IsDead and not DemoTruck.IsDead then Media.DisplayMessage("The Soviets have an unstable nuclear device stored here. \n I need to move it out of the facility!", "Scientist") DemoTruck.GrantCondition("mission") ScientistMan.EnterTransport(DemoTruck) end end) Trigger.OnRemovedFromWorld(ScientistMan, DemoTruckExit) end DemoTruckExit = function() if ScientistMan.IsDead then return end Media.DisplayMessage("I hope the exit is clear!", "Scientist") Utils.Do(DemoTruckPath, function(waypoint) DemoTruck.Move(waypoint.Location) end) local trukEscaped Trigger.OnEnteredFootprint({ DemoDrive4.Location }, function(actor, id) if actor.Type == "dtrk" and not trukEscaped then Trigger.RemoveFootprintTrigger(id) trukEscaped = true actor.Destroy() end end) end AcceptableLosses = 0 Tick = function() if greece.HasNoRequiredUnits() then greece.MarkFailedObjective(ExitBase) end if Difficulty == "hard" and greece.UnitsLost > AcceptableLosses then greece.MarkFailedObjective(NoCasualties) end end WorldLoaded = function() greece = Player.GetPlayer("Greece") england = Player.GetPlayer("England") turkey = Player.GetPlayer("Turkey") ussr = Player.GetPlayer("USSR") france = Player.GetPlayer("France") germany = Player.GetPlayer("Germany") InitObjectives(greece) ussrObj = ussr.AddObjective("Defeat the Allies.") ExitBase = greece.AddObjective("Reach the eastern exit of the facility.") FreeTanya = greece.AddObjective("Free Tanya and keep her alive.") KillVIPs = greece.AddObjective("Kill all Soviet officers and scientists.", "Secondary", false) StealTank = greece.AddObjective("Steal a Soviet mammoth tank.", "Secondary", false) if Difficulty == "hard" then NoCasualties = greece.AddPrimaryObjective("Do not lose a single soldier or civilian\nunder your command.") end StartSpy.DisguiseAsType("e1", ussr) StartAttacker1.AttackMove(start.Location) StartAttacker2.AttackMove(start.Location) Camera.Position = start.CenterPosition ObjectiveTriggers() ConsoleTriggers() CameraTriggers() TruckSteal() PrisonEscape() end
gpl-3.0
prophile/xsera
Resources/Scripts/Modules/TextManip.lua
2
4059
import('GlobalVars') --dofile("PrintRecursive.lua") -- Splits the text into wrappable strings with a maximum length of maxLength. -- Returns a table of strings of maxLength length or shorter. function textWrap(text, font, height, maxLength) local done = false local numWords local words local totalLength = graphics.text_length(text, font, height) if textIsGoodSize(text, font, height, maxLength) then return text end words = textSplit(text) numWords = #words -- try to split the text in half if totalLength / 2 <= maxLength then text = textSplit(text, 2) if graphics.text_length(text[1], font, height) <= maxLength and graphics.text_length(text[2], font, height) <= maxLength then return text end end -- default return textJoinSlow(words, font, height, maxLength) end -- Checks to see if the text is short enough, and is smart enough to check all -- elements of a table, should a table be passed as teh "text" argument function textIsGoodSize(text, font, height, maxLength) if type(text) ~= "table" then return (graphics.text_length(text, font, height) <= maxLength) else local i for i = 1, #text do if not textIsGoodSize(text[i], font, height, maxLength) then return false end end return true end end -- Splits text into totalSeg segments - if totalSeg is not given or greater than -- the number of words, chop all the words individually. Will divide lines -- as evenly as possible. -- Returns a table containing the segments. function textSplit(text, totalSeg) local tempText = {} local wordsLeft = 0 local wordsUsed = 0 local finalText = {} local finalTextCounter = 1 if totalSeg == 1 then return text end for word in text:gmatch("%a+%W*%s*") do wordsLeft = wordsLeft + 1 tempText[wordsLeft] = word end if totalSeg ~= nil then if totalSeg > wordsLeft then return tempText end local wordsPerSeg = math.floor(wordsLeft / totalSeg) while wordsLeft ~= 0 do finalText[finalTextCounter] = "" if wordsLeft % wordsPerSeg ~= 0 then local i = 1 while i <= wordsPerSeg + 1 do finalText[finalTextCounter] = finalText[finalTextCounter] .. tempText[wordsUsed + 1] i = i + 1 wordsUsed = wordsUsed + 1 wordsLeft = wordsLeft - 1 end else local i = 1 while i <= wordsPerSeg do finalText[finalTextCounter] = finalText[finalTextCounter] .. tempText[wordsUsed + 1] i = i + 1 wordsUsed = wordsUsed + 1 wordsLeft = wordsLeft - 1 end end finalTextCounter = finalTextCounter + 1 end else finalText = tempText end return finalText end -- Takes a bunch of words, stored in the table 'words', and concatenates them -- one by one until the line is too long. It repeats this until all the words -- are used. -- Titled "slow" because other faster methods (estimation using the character -- "M" as a ruler (the 'longest' character), and also binary search) function textJoinSlow(words, font, height, maxLength) local returnText = { "" } local index = 1 local wordsLeft = #words returnText[index] = words[#words - wordsLeft + 1] wordsLeft = wordsLeft - 1 while wordsLeft ~= 0 do if graphics.text_length(returnText[index] .. words[#words - wordsLeft + 1], font, height) > maxLength then index = index + 1 returnText[index] = words[#words - wordsLeft + 1] else returnText[index] = returnText[index] .. words[#words - wordsLeft + 1] end wordsLeft = wordsLeft - 1 end return returnText end
mit
spark0511/blueteambot
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
adminomega/exterme-orginal
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
SirSepehr/Sepehr
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
chelog/brawl
addons/brawl-weapons/lua/cw/shared/cw_originalvaluesaving.lua
1
1828
AddCSLuaFile() -- This is a small module-thing that assigns a specified value a value with _Orig at the end of it -- and can also, optionally, assign the value with a 'Mult' ending that's always 1, which can be used for attachments that modify a weapon's stats CustomizableWeaponry.originalValue = {} CustomizableWeaponry.originalValue.registered = {} function CustomizableWeaponry.originalValue:add(varName, makeMultiplier, clientOnly) if clientOnly and SERVER then return end self.registered[varName] = makeMultiplier end local orig = "_Orig" local mult = "Mult" function CustomizableWeaponry.originalValue:assign() for varName, makeMult in pairs(CustomizableWeaponry.originalValue.registered) do self[varName .. orig] = self[varName] if makeMult then self[varName .. mult] = 1 end end end CustomizableWeaponry.originalValue:add("HipSpread", true) CustomizableWeaponry.originalValue:add("AimSpread", true) CustomizableWeaponry.originalValue:add("FireDelay", true) CustomizableWeaponry.originalValue:add("Damage", true) CustomizableWeaponry.originalValue:add("VelocitySensitivity", true) CustomizableWeaponry.originalValue:add("Recoil", true) CustomizableWeaponry.originalValue:add("ReloadSpeed", true) CustomizableWeaponry.originalValue:add("MaxSpreadInc", true) CustomizableWeaponry.originalValue:add("OverallMouseSens", true, true) CustomizableWeaponry.originalValue:add("DrawSpeed", true) CustomizableWeaponry.originalValue:add("SpreadPerShot", true) CustomizableWeaponry.originalValue:add("Shots", false) CustomizableWeaponry.originalValue:add("ClumpSpread", false) CustomizableWeaponry.originalValue:add("DeployTime", false) CustomizableWeaponry.originalValue:add("ReloadHalt", false) CustomizableWeaponry.originalValue:add("ReloadHalt_Empty", false)
gpl-3.0
Shrafe/myo-scripts
browser-control.lua
1
1079
scriptId = 'com.thauser.myo.scripts.browser-control' function webBack() myo.keyboard("left_arrow", "press","alt") myo.debug("webBack() : Navigate to previous webpage") end function nextTab() myo.keyboard("tab", "press", "control") myo.debug("nextTab() : Switch to next tab") end function newTab() myo.keyboard("t", "press", "control") myo.debug("newTab() : Open new tab") end function onPoseEdge(pose, edge) if pose == "waveIn" then if edge == "off" then webBack() end end if pose == "waveOut" then if edge == "off" then nextTab() end end if pose == "fist" then if edge == "off" then newTab() end end end function onForegroundWindowChange(app,title) waitTime = myo.getTimeMilliseconds() local wantActive = false appName = app if string.match(title,".*Google Chrome$") then wantActive = true end -- roooooofl myo.debug("App: " .. app .. " | Title: " .. title .. " | wantActive: " .. string.format("%s", wantActive and "true" or "false")) return wantActive end
apache-2.0
dismantl/luci-0.12
applications/luci-diag-devinfo/luasrc/controller/luci_diag/devinfo_common.lua
76
5638
--[[ Luci diag - Diagnostics controller module (c) 2009 Daniel Dickinson 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.luci_diag.devinfo_common", package.seeall) require("luci.i18n") require("luci.util") require("luci.sys") require("luci.cbi") require("luci.model.uci") local translate = luci.i18n.translate local DummyValue = luci.cbi.DummyValue local SimpleSection = luci.cbi.SimpleSection function index() return -- no-op end function run_processes(outnets, cmdfunc) i = next(outnets, nil) while (i) do outnets[i]["output"] = luci.sys.exec(cmdfunc(outnets, i)) i = next(outnets, i) end end function parse_output(devmap, outnets, haslink, type, mini, debug) local curnet = next(outnets, nil) while (curnet) do local output = outnets[curnet]["output"] local subnet = outnets[curnet]["subnet"] local ports = outnets[curnet]["ports"] local interface = outnets[curnet]["interface"] local netdevs = {} devlines = luci.util.split(output) if not devlines then devlines = {} table.insert(devlines, output) end local j = nil j = next(devlines, j) local found_a_device = false while (j) do if devlines[j] and ( devlines[j] ~= "" ) then found_a_device = true local devtable local row = {} devtable = luci.util.split(devlines[j], ' | ') row["ip"] = devtable[1] if (not mini) then row["mac"] = devtable[2] end if ( devtable[4] == 'unknown' ) then row["vendor"] = devtable[3] else row["vendor"] = devtable[4] end row["type"] = devtable[5] if (not mini) then row["model"] = devtable[6] end if (haslink) then row["config_page"] = devtable[7] end if (debug) then row["raw"] = devlines[j] end table.insert(netdevs, row) end j = next(devlines, j) end if not found_a_device then local row = {} row["ip"] = curnet if (not mini) then row["mac"] = "" end if (type == "smap") then row["vendor"] = luci.i18n.translate("No SIP devices") else row["vendor"] = luci.i18n.translate("No devices detected") end row["type"] = luci.i18n.translate("check other networks") if (not mini) then row["model"] = "" end if (haslink) then row["config_page"] = "" end if (debug) then row["raw"] = output end table.insert(netdevs, row) end local s if (type == "smap") then if (mini) then s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet) else local interfacestring = "" if ( interface ~= "" ) then interfacestring = ", " .. interface end s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet .. " (" .. subnet .. ":" .. ports .. interfacestring .. ")") end s.template = "diag/smapsection" else if (mini) then s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet) else local interfacestring = "" if ( interface ~= "" ) then interfacestring = ", " .. interface end s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet .. " (" .. subnet .. interfacestring .. ")") end end s:option(DummyValue, "ip", translate("IP Address")) if (not mini) then s:option(DummyValue, "mac", translate("MAC Address")) end s:option(DummyValue, "vendor", translate("Vendor")) s:option(DummyValue, "type", translate("Device Type")) if (not mini) then s:option(DummyValue, "model", translate("Model")) end if (haslink) then s:option(DummyValue, "config_page", translate("Link to Device")) end if (debug) then s:option(DummyValue, "raw", translate("Raw")) end curnet = next(outnets, curnet) end end function get_network_device(interface) local state = luci.model.uci.cursor_state() state:load("network") local dev return state:get("network", interface, "ifname") end function cbi_add_networks(field) uci.cursor():foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then field:value(section[".name"]) end end ) field.titleref = luci.dispatcher.build_url("admin", "network", "network") end function config_devinfo_scan(map, scannet) local o o = scannet:option(luci.cbi.Flag, "enable", translate("Enable")) o.optional = false o.rmempty = false o = scannet:option(luci.cbi.Value, "interface", translate("Interface")) o.optional = false luci.controller.luci_diag.devinfo_common.cbi_add_networks(o) local scansubnet scansubnet = scannet:option(luci.cbi.Value, "subnet", translate("Subnet")) scansubnet.optional = false o = scannet:option(luci.cbi.Value, "timeout", translate("Timeout"), translate("Time to wait for responses in seconds (default 10)")) o.optional = true o = scannet:option(luci.cbi.Value, "repeat_count", translate("Repeat Count"), translate("Number of times to send requests (default 1)")) o.optional = true o = scannet:option(luci.cbi.Value, "sleepreq", translate("Sleep Between Requests"), translate("Milliseconds to sleep between requests (default 100)")) o.optional = true end
apache-2.0
Noltari/luci
applications/luci-app-olsr/luasrc/model/cbi/olsr/olsrdplugins6.lua
10
7037
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2009 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local ip = require "luci.ip" local fs = require "nixio.fs" if arg[1] then mp = Map("olsrd6", translate("OLSR - Plugins")) p = mp:section(TypedSection, "LoadPlugin", translate("Plugin configuration")) p:depends("library", arg[1]) p.anonymous = true ign = p:option(Flag, "ignore", translate("Enable")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end lib = p:option(DummyValue, "library", translate("Library")) lib.default = arg[1] local function Range(x,y) local t = {} for i = x, y do t[#t+1] = i end return t end local function Cidr2IpMask(val) if val then for i = 1, #val do local cidr = ip.IPv4(val[i]) or ip.IPv6(val[i]) if cidr then val[i] = cidr:network():string() .. " " .. cidr:mask():string() end end return val end end local function IpMask2Cidr(val) if val then for i = 1, #val do local ip, mask = val[i]:gmatch("([^%s]+)%s+([^%s]+)")() local cidr if ip and mask and ip:match(":") then cidr = ip.IPv6(ip, mask) elseif ip and mask then cidr = ip.IPv4(ip, mask) end if cidr then val[i] = cidr:string() end end return val end end local knownPlParams = { ["olsrd_bmf"] = { { Value, "BmfInterface", "bmf0" }, { Value, "BmfInterfaceIp", "10.10.10.234/24" }, { Flag, "DoLocalBroadcast", "no" }, { Flag, "CapturePacketsOnOlsrInterfaces", "yes" }, { ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } }, { Value, "BroadcastRetransmitCount", "2" }, { Value, "FanOutLimit", "4" }, { DynamicList, "NonOlsrIf", "br-lan" } }, ["olsrd_dyn_gw"] = { { Value, "Interval", "40" }, { DynamicList, "Ping", "141.1.1.1" }, { DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_httpinfo"] = { { Value, "port", "80" }, { DynamicList, "Host", "163.24.87.3" }, { DynamicList, "Net", "0.0.0.0/0", Cidr2IpMask } }, ["olsrd_nameservice"] = { { DynamicList, "name", "my-name.mesh" }, { DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" }, { Value, "suffix", ".olsr" }, { Value, "hosts_file", "/path/to/hosts_file" }, { Value, "add_hosts", "/path/to/file" }, { Value, "dns_server", "141.1.1.1" }, { Value, "resolv_file", "/path/to/resolv.conf" }, { Value, "interval", "120" }, { Value, "timeout", "240" }, { Value, "lat", "12.123" }, { Value, "lon", "12.123" }, { Value, "latlon_file", "/var/run/latlon.js.ipv6" }, { Value, "latlon_infile", "/var/run/gps.txt" }, { Value, "sighup_pid_file", "/var/run/dnsmasq.pid" }, { Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" }, { DynamicList, "service", "http://me.olsr:80|tcp|my little homepage" }, { Value, "services_file", "/var/run/services_olsr" }, { Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" }, { DynamicList, "mac", "xx:xx:xx:xx:xx:xx[,0-255]" }, { Value, "macs_file", "/path/to/macs_file" }, { Value, "macs_change_script", "/path/to/script" } }, ["olsrd_quagga"] = { { StaticList, "redistribute", { "system", "kernel", "connect", "static", "rip", "ripng", "ospf", "ospf6", "isis", "bgp", "hsls" } }, { ListValue, "ExportRoutes", { "only", "both" } }, { Flag, "LocalPref", "true" }, { Value, "Distance", Range(0,255) } }, ["olsrd_secure"] = { { Value, "Keyfile", "/etc/private-olsr.key" } }, ["olsrd_txtinfo"] = { { Value, "accept", "::1/128" } }, ["olsrd_jsoninfo"] = { { Value, "accept", "::1/128" }, { Value, "port", "9090" }, { Value, "UUIDFile", "/etc/olsrd/olsrd.uuid.ipv6" }, }, ["olsrd_watchdog"] = { { Value, "file", "/var/run/olsrd.watchdog.ipv6" }, { Value, "interval", "30" } }, ["olsrd_mdns.so"] = { { DynamicList, "NonOlsrIf", "lan" } }, ["olsrd_p2pd.so"] = { { DynamicList, "NonOlsrIf", "lan" }, { Value, "P2pdTtl", "10" } }, ["olsrd_arprefresh"] = {}, ["olsrd_dot_draw"] = {}, ["olsrd_dyn_gw_plain"] = {}, ["olsrd_pgraph"] = {}, ["olsrd_tas"] = {} } -- build plugin options with dependencies if knownPlParams[arg[1]] then for _, option in ipairs(knownPlParams[arg[1]]) do local otype, name, default, uci2cbi, cbi2uci = unpack(option) local values if type(default) == "table" then values = default default = default[1] end if otype == Flag then local bool = p:option( Flag, name, name ) if default == "yes" or default == "no" then bool.enabled = "yes" bool.disabled = "no" elseif default == "on" or default == "off" then bool.enabled = "on" bool.disabled = "off" elseif default == "1" or default == "0" then bool.enabled = "1" bool.disabled = "0" else bool.enabled = "true" bool.disabled = "false" end bool.optional = true bool.default = default bool:depends({ library = plugin }) else local field = p:option( otype, name, name ) if values then for _, value in ipairs(values) do field:value( value ) end end if type(uci2cbi) == "function" then function field.cfgvalue(self, section) return uci2cbi(otype.cfgvalue(self, section)) end end if type(cbi2uci) == "function" then function field.formvalue(self, section) return cbi2uci(otype.formvalue(self, section)) end end field.optional = true field.default = default --field:depends({ library = arg[1] }) end end end return mp else mpi = Map("olsrd6", translate("OLSR - Plugins")) local plugins = {} mpi.uci:foreach("olsrd6", "LoadPlugin", function(section) if section.library and not plugins[section.library] then plugins[section.library] = true end end ) -- create a loadplugin section for each found plugin for v in fs.dir("/usr/lib") do if v:sub(1, 6) == "olsrd_" then v=string.match(v, "^(olsrd_.*)%.so%..*") if not plugins[v] then mpi.uci:section( "olsrd6", "LoadPlugin", nil, { library = v, ignore = 1 } ) end end end t = mpi:section( TypedSection, "LoadPlugin", translate("Plugins") ) t.anonymous = true t.template = "cbi/tblsection" t.override_scheme = true function t.extedit(self, section) local lib = self.map:get(section, "library") or "" return luci.dispatcher.build_url("admin", "services", "olsrd6", "plugins") .. "/" .. lib end ign = t:option( Flag, "ignore", translate("Enabled") ) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end t:option( DummyValue, "library", translate("Library") ) return mpi end
apache-2.0
bsmr-games/lipsofsuna
data/lipsofsuna/core/ai/combat/melee.lua
1
1227
local AiActionSpec = require("core/specs/aiaction") AiActionSpec{ name = "melee", categories = {["combat"] = true, ["offensive"] = true}, calculate = function(self, args) -- Make sure that the actor can use melee. if not args.attack then return end if not args.spec.can_melee then return end -- Check for good aim. if args.aim < 0.8 then return end -- Check for a melee weapon or bare-handed. if args.weapon and not args.weapon.spec.categories["melee"] then return end -- Check for an applicable feat. args.action_melee = self:find_best_action{category = "melee", target = self.target, weapon = args.weapon} if args.action_melee then return 4 end end, perform = function(self, args) if args.diff.y > 1 and args.spec.allow_jump then self.object:action("jump") end self.object:set_block(false) if args.spec.ai_enable_backstep and args.dist < 0.3 * args.hint then self.object:set_movement(-1) elseif args.spec.ai_enable_walk and args.dist > 0.6 * args.hint then self.object:set_movement(1) else self.object:set_movement(0) end self.object.tilt = self:calculate_melee_tilt() self.object:set_strafing(0) self.object:action(args.action_melee.name) self.action_timer = 0.5 end}
gpl-3.0
Noltari/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
LaFamiglia/Illarion-Content
npc/base/consequence/rune.lua
4
1083
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local class = require("base.class") local consequence = require("npc.base.consequence.consequence") local _rune_helper local rune = class(consequence, function(self, group, id) consequence:init(self) self["id"] = tonumber(id) self["group"] = tonumber(group) self["perform"] = _rune_helper end) function _rune_helper(self, npcChar, player) player:teachMagic(self.group, self.rune) end return rune
agpl-3.0
LaFamiglia/Illarion-Content
monster/base/quests.lua
4
15012
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --Generic 'Kill X monsters' quests by Estralis Seborian local common = require("base.common") local M = {} --TEMPLATE TO ADD A QUEST TO function iniQuests() --local id=NUMBER; --ID of the quest --germanTitle[id]="GERMAN TITLE"; --Title of the quest in german --englishTitle[id]="ENGLISH TITLE"; --Title of the quest in english --NPCName[id]="Miggs"; --This is the name of the NPC who gives out the quest --statusId[id]=NUMBER; --the queststatus as used by the NPC --germanRace[id]="stinkige Gullimumien"; --free description of the foes in german --englishRace[id]="smelly sewer mummies"; --free description of the foes in english --table.insert(questList[MONSTERID],id); --Insert the quest into the quest list of the monster race that has to be slain. You can add multiple monsters this way. --minimumQueststatus[id]=NUMBER1; --quest is only active with this queststatus and above. Each monster slain adds +1. Use a value > 0! --maximumQueststatus[id]=NUMBER2; --quest is finished if this queststatus is reached, no kill are counted anymore. Difference between NUMBER1 and NUMBER2 is the number of monsters that have to be slain --questLocation[id]=position(X,Y,Z); --a position around which the monsters have to be slain, e.g. centre of a dungeon or forest --radius[id]=RADIUS; --in this radius around the questlocation, kills are counted valid --Comment: If you want an NPC to give out multiple quests, you can do it like this: --Quest 1: To accept quest 1, set queststatus to 1 with the NPC. Use queststatus 1->11 to count 10 monsters. If the quest is finished, set queststatus to 12 with the NPC. --Quest 2: To accept quest 2, set queststatus to 13 with the NPC. Use queststatus 13->18 to count 5 monsters. If the quest is finished, set queststatus to 19 with the NPC. --Quest 3: To accept quest 3, set queststatus to 20 with the NPC. Use queststatus 20->21 to count 1 monster. If the quest is finished, set queststatus to 22 with the NPC. local quests = {} local questsByMonsterId = {} local questsByMonsterGroupId = {} local questsByRaceId = {} local function _isNumber(value) return type(value) == "number" end local function _isTable(value) return type(value) == "table" end local function _isFunction(value) return type(value) == "function" end local function _isString(value) return type(value) == "string" end local function registerQuest(quest, monsterIds, groupIds, raceIds) if not _isTable(quest) then error("Tried to insert a illegal structure as quest: Not a table") end if not _isFunction(quest.check) or not _isFunction(quest.execute) then error("Tried to insert a illegal structure as quest: Required check and execute functions not present") end table.insert(quests, quest) local index = #quests if monsterIds ~= nil then if _isTable(monsterIds) then for _, id in pairs(monsterIds) do local numberId = tonumber(id) if questsByMonsterId[numberId] == nil then questsByMonsterId[numberId] = {} end table.insert(questsByMonsterId[numberId], index) end else error("The list of monster IDs is expected to be a table of IDs.") end end if groupIds ~= nil then if _isTable(groupIds) then for _, id in pairs(groupIds) do local numberId = tonumber(id) if questsByMonsterGroupId[numberId] == nil then questsByMonsterGroupId[numberId] = {} end table.insert(questsByMonsterGroupId[numberId], index) end else error("The list of group IDs is expected to be a table of IDs.") end end if raceIds ~= nil then if _isTable(raceIds) then for _, id in pairs(raceIds) do local numberId = tonumber(id) if questsByRaceId[numberId] == nil then questsByRaceId[numberId] = {} end table.insert(questsByRaceId[numberId], index) end else error("The list of race IDs is expected to be a table of IDs.") end end end function M.addQuest(params) if not _isTable(params) then error("Quest data for the quest to add is missing.") end local questId if not _isNumber(params.questId) then error("The quest ID is required to be a number. It is the ID of the quest progress.") else questId = tonumber(params.questId) end local checkQuest if _isFunction(params.check) then checkQuest = params.check else local questLocations if _isTable(params.location) then questLocations = {params.location} elseif _isTable(params.locations) then questLocations = params.locations else error("One or multiple locations for the quests are required.") end for _, location in pairs(questLocations) do if not _isTable(location) then error("Location is not properly stored in a table.") end if location.position == nil or not _isNumber(location.radius) then error("Each location definition requires a position and a radius to be valid.") end end local minimalStatus, maximalStatus if _isTable(params.queststatus) then if _isNumber(params.queststatus.from) and _isNumber(params.queststatus.to) then minimalStatus = tonumber(params.queststatus.from) maximalStatus = tonumber(params.queststatus.to) elseif _isNumber(params.queststatus.min) and _isNumber(params.queststatus.max) then minimalStatus = tonumber(params.queststatus.min) maximalStatus = tonumber(params.queststatus.max) elseif _isNumber(params.queststatus[1]) and _isNumber(params.queststatus[2]) then minimalStatus = tonumber(params.queststatus[1]) maximalStatus = tonumber(params.queststatus[2]) else error("Failed to read the quest status range.") end elseif _isNumber(params.queststatus) then minimalStatus = tonumber(params.queststatus) maximalStatus = tonumber(params.queststatus) else error("Failed to read the required queststatus parameter.") end if minimalStatus > maximalStatus or minimalStatus < 0 then error("Quest status values are out of range.") end checkQuest = function(player, monster) if not player:isInRange(monster, 12) then -- Monster is too far away. Something went wrong return false end for _, location in pairs(questLocations) do if player:isInRangeToPosition(location.position, location.radius) then local currentStatus = player:getQuestProgress(questId); return currentStatus >= minimalStatus and currentStatus < maximalStatus end end return false end end local executeQuest if _isFunction(params.execute) then executeQuest = params.execute else executeQuest = function(player, monster) local currentStatus = player:getQuestProgress(questId); player:setQuestProgress(questId, currentStatus + 1) end end local reportQuest if _isFunction(params.report) then reportQuest = params.report else local minimalStatus, maximalStatus if _isTable(params.queststatus) then if _isNumber(params.queststatus.from) and _isNumber(params.queststatus.to) then minimalStatus = tonumber(params.queststatus.from) maximalStatus = tonumber(params.queststatus.to) elseif _isNumber(params.queststatus.min) and _isNumber(params.queststatus.max) then minimalStatus = tonumber(params.queststatus.min) maximalStatus = tonumber(params.queststatus.max) elseif _isNumber(params.queststatus[1]) and _isNumber(params.queststatus[2]) then minimalStatus = tonumber(params.queststatus[1]) maximalStatus = tonumber(params.queststatus[2]) else error("Failed to read the quest status range.") end elseif _isNumber(params.queststatus) then minimalStatus = tonumber(params.queststatus) maximalStatus = tonumber(params.queststatus) else error("Failed to read the required queststatus parameter.") end if minimalStatus > maximalStatus or minimalStatus < 0 then error("Quest status values are out of range.") end local titleGerman, titleEnglish if _isTable(params.questTitle) then if _isString(params.questTitle.german) and _isString(params.questTitle.english) then titleGerman = params.questTitle.german titleEnglish = params.questTitle.english elseif _isString(params.questTitle[Player.german]) and _isString(params.questTitle[Player.english]) then titleGerman = params.questTitle[Player.german] titleEnglish = params.questTitle[Player.english] end elseif _isString(params.questTitle) then titleGerman = params.questTitle titleEnglish = params.questTitle else error("Failed to read the required title of the quest.") end local monsterNameGerman, monsterNameEnglish if _isTable(params.monsterName) then local germanParams = params.monsterName.german or params.monsterName[Player.german] local englishParams = params.monsterName.english or params.monsterName[Player.english] if _isString(germanParams) then monsterNameGerman = germanParams else error("Failed to read the german part of the monster name.") end if _isString(englishParams) then monsterNameEnglish = englishParams else error("Failed to read the english part of the monster name.") end elseif _isString(params.monsterName) then monsterNameGerman = params.monsterName monsterNameEnglish = params.monsterName else error("Failed to read the required name of the monster.") end local npcName if _isString(params.npcName) then npcName = params.npcName else error("Failed to read the required NPC name.") end local totalCount = maximalStatus - minimalStatus reportQuest = function(player, monster) local currentStatus = player:getQuestProgress(questId); if currentStatus >= maximalStatus then --quest finished local germanFormat, englishFormat if maximalStatus == minimalStatus + 1 then -- only a single monster to beat germanFormat = "[Queststatus] %s: Du hast %s besiegt. Kehre zu %s zurück, um deine Belohnung zu erhalten." englishFormat = "[Quest status] %s: You have slain %s. Return to %s to claim your reward." else germanFormat = "[Queststatus] %s: Du hast genug %s besiegt. Kehre zu %s zurück, um deine Belohnung zu erhalten." englishFormat = "[Quest status] %s: You have slain enough %s. Return to %s to claim your reward." end common.InformNLS(player, germanFormat:format(titleGerman, monsterNameGerman, npcName), englishFormat:format(titleEnglish, monsterNameEnglish, npcName)); else --quest not finished local germanFormat = "[Queststatus] %s: Du hast %d von %d %s besiegt." local englishFormat = "[Quest status] %s: You have slain %d of %d %s." local doneCount = currentStatus - minimalStatus common.InformNLS(player, germanFormat:format(titleGerman, doneCount, totalCount, monsterNameGerman), englishFormat:format(titleEnglish, doneCount, totalCount, monsterNameEnglish)); end end end local quest = {} function quest.check(player, monster) return checkQuest(player, monster) end function quest.execute(player, monster) executeQuest(player, monster) reportQuest(player, monster) end registerQuest(quest, params.monsterIds, params.monsterGroupIds, params.raceIds) end function M.checkQuest(player, monster) local monsterId = monster:getMonsterType() local monsterGroupId = math.floor((monsterId - 1) / 10) local raceId = monster:getRace() local possibleQuests = {} if questsByMonsterId[monsterId] ~= nil then for _, questId in pairs(questsByMonsterId[monsterId]) do possibleQuests[questId] = true end end if questsByMonsterGroupId[monsterGroupId] ~= nil then for _, questId in pairs(questsByMonsterGroupId[monsterGroupId]) do possibleQuests[questId] = true end end if questsByRaceId[raceId] ~= nil then for _, questId in pairs(questsByRaceId[raceId]) do possibleQuests[questId] = true end end -- All candidates are assembled. Now check the ones that execute. local checkedQuests = {} for questId, _ in pairs(possibleQuests) do local quest = quests[questId] if quest.check(player, monster) then table.insert(checkedQuests, quest) end end for _, quest in pairs(checkedQuests) do quest.execute(player, monster) end end return M
agpl-3.0
dariocanoh/numberbook
xlsxwriter/utility.lua
1
9910
---- -- Utility - Utility functions for xlsxwriter.lua. -- -- Copyright 2014-2015, John McNamara, jmcnamara@cpan.org -- require "numberbook.xlsxwriter.strict" local Utility = {} local char_A = string.byte("A") local col_names = {} local named_colors = { ["black"] = "#000000", ["blue"] = "#0000FF", ["brown"] = "#800000", ["cyan"] = "#00FFFF", ["gray"] = "#808080", ["green"] = "#008000", ["lime"] = "#00FF00", ["magenta"] = "#FF00FF", ["navy"] = "#000080", ["orange"] = "#FF6600", ["pink"] = "#FF00FF", ["purple"] = "#800080", ["red"] = "#FF0000", ["silver"] = "#C0C0C0", ["white"] = "#FFFFFF", ["yellow"] = "#FFFF00", } ---- -- Convert a zero indexed column cell reference to an Excel column string. -- function Utility.col_to_name_abs(col_num, col_abs) local col_str = col_names[col_num] local col_num_orig = col_num if not col_str then col_str = "" col_num = col_num + 1 while col_num > 0 do -- Set remainder from 1 .. 26 local remainder = col_num % 26 if remainder == 0 then remainder = 26 end -- Convert the remainder to a character. local col_letter = string.char(char_A + remainder - 1) -- Accumulate the column letters, right to left. col_str = col_letter .. col_str -- Get the next order of magnitude. col_num = math.floor((col_num - 1) / 26) end col_names[col_num_orig] = col_str end if col_abs then col_str = '$' .. col_str end return col_str end ---- -- Convert a zero indexed row and column cell reference to a A1 style string. -- function Utility.rowcol_to_cell(row, col) row = math.modf(row + 1) col = math.modf(col) local col_str = Utility.col_to_name_abs(col, false) return col_str .. row end ---- -- Convert a zero indexed row and column cell reference to a A1 style string -- with Excel absolute indexing. -- function Utility.rowcol_to_cell_abs(row, col, row_abs, col_abs) row = math.modf(row + 1) col = math.modf(col) row_abs = row_abs and "$" or "" local col_str = Utility.col_to_name_abs(col, col_abs) return col_str .. row_abs .. row end ---- -- Convert a cell reference in A1 notation to a zero indexed row, column. -- function Utility.cell_to_rowcol(cell) local col_str, row = cell:match("$?(%u+)$?(%d+)") -- Convert base26 column string to number. local expn = 0 local col = 0 for i = #col_str, 1, -1 do local char = col_str:sub(i, i) col = col + (string.byte(char) - char_A + 1) * (26 ^ expn) expn = expn + 1 end -- Convert 1-index to zero-index row = math.modf(row - 1) col = math.modf(col - 1) return row, col end ---- -- Convert zero indexed row and col cell refs to a A1:B1 style range string. -- function Utility.range(first_row, first_col, last_row, last_col) local range1 = Utility.rowcol_to_cell(first_row, first_col) local range2 = Utility.rowcol_to_cell(last_row, last_col ) return range1 .. ":" .. range2 end ---- -- Convert zero indexed row and col cell refs to absolute A1:B1 range string. -- function Utility.range_abs(first_row, first_col, last_row, last_col) local range1 = Utility.rowcol_to_cell_abs(first_row, first_col, true, true) local range2 = Utility.rowcol_to_cell_abs(last_row, last_col, true, true) return range1 .. ":" .. range2 end ---- -- Generator for returning table items in sorted order. From PIL 3rd Ed. -- function Utility.sorted_pairs(sort_table, sort_function) local array = {} for n in pairs(sort_table) do array[#array + 1] = n end table.sort(array, sort_function) local i = 0 return function () i = i + 1 return array[i], sort_table[array[i]] end end ---- -- Generator for returning table keys in sorted order. -- function Utility.sorted_keys(sort_table, sort_function) local array = {} for n in pairs(sort_table) do array[#array + 1] = n end table.sort(array, sort_function) local i = 0 return function () i = i + 1 return array[i] end end ---- -- Print a non-fatal warning at the highest/calling program stack level. -- function Utility.warn(...) local level = 0 local info -- Find the last highest stack level. for i = 1, math.huge do info = debug.getinfo(i, "Sl") if not info then break end level = level + 1 end -- Print warning to stderr at the calling program stack level. info = debug.getinfo(level -1, "Sl") --< HEAD -- if info then -- io.stderr:write(string.format("Warning:\n\t%s:%d: ", -- info.short_src, -- info.currentline)) -- io.stderr:write(string.format(...)) --end --======= --io.stderr:write(string.format("Warning:\n\t%s:%d: ", -- info.short_src, -- info.currentline)) --io.stderr:write(string.format(...)) --> master end ---- -- Convert a Html #RGB or named colour into an Excel ARGB formatted -- color. Used in conjunction with various xxx_color() methods. -- function Utility.excel_color(color) local rgb = color -- Convert named colours. if named_colors[color] then rgb = named_colors[color] end -- Extract the RBG part of the color. rgb = rgb:match("^#(%x%x%x%x%x%x)$") if rgb then -- Convert the RGB colour to the Excel ARGB format. return "FF" .. rgb:upper() else Utility.warn("Color '%s' is not a valid Excel color.\n", color) return "FF000000" -- Return Black as a default on error. end end ---- -- The function takes an os.time style date table and converts it to a decimal -- number representing a valid Excel date. -- -- Dates and times in Excel are represented by real numbers. The integer part of -- the number stores the number of days since the epoch and the fractional part -- stores the percentage of the day in seconds. The epoch can be either 1900 or -- 1904. -- function Utility.convert_date_time(date_time, date_1904) local year = date_time["year"] local month = date_time["month"] local day = date_time["day"] local hour = date_time["hour"] or 0 local min = date_time["min"] or 0 local sec = date_time["sec"] or 0 -- For times without dates set the default date for the epoch if not year then if not date_1904 then year = 1899; month = 12; day = 31 else year = 1904; month = 1; day = 1 end end -- Converte the Excel seconds to a fraction of the seconds in 24 hours. local seconds = (hour * 60 * 60 + min * 60 + sec) / (24 * 60 * 60) -- Special cases for Excel dates. if not date_1904 then -- Excel 1900 epoch. if year == 1899 and month == 12 and day == 31 then return seconds end if year == 1900 and month == 1 and day == 0 then return seconds end -- Excel false leapday if year == 1900 and month == 2 and day == 29 then return 60 + seconds end end -- We calculate the date by calculating the number of days since the epoch -- and adjust for the number of leap days. We calculate the number of leap -- days by normalising the year in relation to the epoch. Thus the year 2000 -- becomes 100 for 4-year and 100-year leapdays and 400 for 400-year leapdays. -- local epoch = date_1904 and 1904 or 1900 local offset = date_1904 and 4 or 0 local norm = 300 local range = year - epoch -- Set month days and check for leap year. local mdays = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} local leap = 0 if year % 4 == 0 and year % 100 > 0 or year % 400 == 0 then leap = 1 mdays[2] = 29 end -- Some boundary checks if year < epoch or year > 9999 then return nil end if month < 1 or month > 12 then return nil end if day < 1 or day > mdays[month] then return nil end -- Accumulate the number of days since the epoch. local days = day -- Add days for current month for i = 1, month -1 do -- Add days for past months. days = days + mdays[i] end days = days + range * 365 -- Past year days. days = days + math.floor((range ) / 4) -- 4 yr leapdays. days = days - math.floor((range + offset ) / 100) -- 100 yr leapdays. days = days + math.floor((range + offset + norm) / 400) -- 400 yr leapdays. days = days - leap -- Already counted. -- Adjust for Excel erroneously treating 1900 as a leap year. if not date_1904 and days > 59 then days = days + 1 end return days + seconds end ---- -- The function takes a date and time in ISO8601 "yyyy-mm-ddThh:mm:ss.ss" format -- and converts it to a decimal number representing a valid Excel date. -- -- See convert_date_time() funciton above. -- function Utility.convert_date_string(date_str, date_1904) local date_time = {} -- Check for invalid date char. if string.match(date_str, "[^0-9T:%-%.Z]") then return nil end -- Strip trailing Z in ISO8601 date. date_str = date_str:gsub("Z", "") -- Get the date and time parts of the date string. local date = "" local time = "" if string.match(date_str, "T") then date, time = string.match(date_str, "(.*)T(.*)") elseif string.match(date_str, "^%d%d%d%d%-%d%d%-%d%d$") then date = date_str elseif string.match(date_str, "^%d%d:%d%d:%d%d") then time = date_str else return nil end if time ~= '' then -- Match times like hh:mm:ss.sss. local hour, min, sec = string.match(time, "^(%d%d):(%d%d):(.*)$") date_time["hour"] = tonumber(hour) date_time["min"] = tonumber(min) date_time["sec"] = tonumber(sec) end if date ~= '' then -- Match date as yyyy-mm-dd. local year, month, day = string.match(date, "^(%d%d%d%d)-(%d%d)-(%d%d)$") date_time["year"] = tonumber(year) date_time["month"] = tonumber(month) date_time["day"] = tonumber(day) end return Utility.convert_date_time(date_time, date_1904) end return Utility
mit
chelog/brawl
gamemodes/brawl/gamemode/lib/mysqlite.lua
1
12036
--[[ MySQLite - Abstraction mechanism for SQLite and MySQL Why use this? - Easy to use interface for MySQL - No need to modify code when switching between SQLite and MySQL - Queued queries: execute a bunch of queries in order an run the callback when all queries are done License: LGPL V2.1 (read here: https://www.gnu.org/licenses/lgpl-2.1.html) Supported MySQL modules: - MySQLOO - tmysql4 Note: When both MySQLOO and tmysql4 modules are installed, MySQLOO is used by default. /*--------------------------------------------------------------------------- Documentation ---------------------------------------------------------------------------*/ MySQLite.initialize([config :: table]) :: No value Initialize MySQLite. Loads the config from either the config parameter OR the MySQLite_config global. This loads the module (if necessary) and connects to the MySQL database (if set up). The config must have this layout: { EnableMySQL :: Bool - set to true to use MySQL, false for SQLite Host :: String - database hostname Username :: String - database username Password :: String - database password (keep away from clients!) Database_name :: String - name of the database Database_port :: Number - connection port (3306 by default) Preferred_module :: String - Preferred module, case sensitive, must be either "mysqloo" or "tmysql4" } ----------------------------- Utility functions ----------------------------- MySQLite.isMySQL() :: Bool Returns whether MySQLite is set up to use MySQL. True for MySQL, false for SQLite. Use this when the query syntax between SQLite and MySQL differs (example: AUTOINCREMENT vs AUTO_INCREMENT) MySQLite.SQLStr(str :: String) :: String Escapes the string and puts it in quotes. It uses the escaping method of the module that is currently being used. MySQLite.tableExists(tbl :: String, callback :: function, errorCallback :: function) Checks whether table tbl exists. callback format: function(res :: Bool) res is a boolean indicating whether the table exists. The errorCallback format is the same as in MySQLite.query. ----------------------------- Running queries ----------------------------- MySQLite.query(sqlText :: String, callback :: function, errorCallback :: function) :: No value Runs a query. Calls the callback parameter when finished, calls errorCallback when an error occurs. callback format: function(result :: table, lastInsert :: number) Result is the table with results (nil when there are no results or when the result list is empty) lastInsert is the row number of the last inserted value (use with AUTOINCREMENT) Note: lastInsert is NOT supported when using SQLite. errorCallback format: function(error :: String, query :: String) :: Bool error is the error given by the database module. query is the query that triggered the error. Return true to suppress the error! MySQLite.queryValue(sqlText :: String, callback :: function, errorCallback :: function) :: No value Runs a query and returns the first value it comes across. callback format: function(result :: any) where the result is either a string or a number, depending on the requested database field. The errorCallback format is the same as in MySQLite.query. ----------------------------- Transactions ----------------------------- MySQLite.begin() :: No value Starts a transaction. Use in combination with MySQLite.queueQuery and MySQLite.commit. MySQLite.queueQuery(sqlText :: String, callback :: function, errorCallback :: function) :: No value Queues a query in the transaction. Note: a transaction must be started with MySQLite.begin() for this to work. The callback will be called when this specific query has been executed successfully. The errorCallback function will be called when an error occurs in this specific query. See MySQLite.query for the callback and errorCallback format. MySQLite.commit(onFinished) Commits a transaction and calls onFinished when EVERY queued query has finished. onFinished is NOT called when an error occurs in one of the queued queries. onFinished is called without arguments. ----------------------------- Hooks ----------------------------- DatabaseInitialized Called when a successful connection to the database has been made. ]] local bit = bit local debug = debug local error = error local ErrorNoHalt = ErrorNoHalt local hook = hook local include = include local pairs = pairs local require = require local sql = sql local string = string local table = table local timer = timer local tostring = tostring local mysqlOO local TMySQL local _G = _G local MySQLite_config = MySQLite_config or RP_MySQLConfig or FPP_MySQLConfig local moduleLoaded local function loadMySQLModule() if moduleLoaded or not MySQLite_config or not MySQLite_config.EnableMySQL then return end moo, tmsql = file.Exists("bin/gmsv_mysqloo_*.dll", "LUA"), file.Exists("bin/gmsv_tmysql4_*.dll", "LUA") if not moo and not tmsql then error("Could not find a suitable MySQL module. Supported modules are MySQLOO and tmysql4.") end moduleLoaded = true require(moo and tmsql and MySQLite_config.Preferred_module or moo and "mysqloo" or "tmysql4") mysqlOO = mysqloo TMySQL = tmysql end loadMySQLModule() module("MySQLite") function initialize(config) MySQLite_config = config or MySQLite_config if not MySQLite_config then ErrorNoHalt("Warning: No MySQL config!") end loadMySQLModule() if MySQLite_config.EnableMySQL then timer.Simple(1, function() connectToMySQL(MySQLite_config.Host, MySQLite_config.Username, MySQLite_config.Password, MySQLite_config.Database_name, MySQLite_config.Database_port) end) end end local CONNECTED_TO_MYSQL = false local msOOConnect databaseObject = nil local queuedQueries local cachedQueries function isMySQL() return CONNECTED_TO_MYSQL end function begin() if not CONNECTED_TO_MYSQL then sql.Begin() else if queuedQueries then debug.Trace() error("Transaction ongoing!") end queuedQueries = {} end end function commit(onFinished) if not CONNECTED_TO_MYSQL then sql.Commit() if onFinished then onFinished() end return end if not queuedQueries then error("No queued queries! Call begin() first!") end if #queuedQueries == 0 then queuedQueries = nil return end -- Copy the table so other scripts can create their own queue local queue = table.Copy(queuedQueries) queuedQueries = nil -- Handle queued queries in order local queuePos = 0 local call -- Recursion invariant: queuePos > 0 and queue[queuePos] <= #queue call = function(...) queuePos = queuePos + 1 if queue[queuePos].callback then queue[queuePos].callback(...) end -- Base case, end of the queue if queuePos + 1 > #queue then if onFinished then onFinished() end -- All queries have finished return end -- Recursion local nextQuery = queue[queuePos + 1] query(nextQuery.query, call, nextQuery.onError) end query(queue[1].query, call, queue[1].onError) end function queueQuery(sqlText, callback, errorCallback) if CONNECTED_TO_MYSQL then table.insert(queuedQueries, {query = sqlText, callback = callback, onError = errorCallback}) return end -- SQLite is instantaneous, simply running the query is equal to queueing it query(sqlText, callback, errorCallback) end local function msOOQuery(sqlText, callback, errorCallback, queryValue) local query = databaseObject:query(sqlText) local data query.onData = function(Q, D) data = data or {} data[#data + 1] = D end query.onError = function(Q, E) if databaseObject:status() == mysqlOO.DATABASE_NOT_CONNECTED then table.insert(cachedQueries, {sqlText, callback, queryValue}) -- Immediately try reconnecting msOOConnect(MySQLite_config.Host, MySQLite_config.Username, MySQLite_config.Password, MySQLite_config.Database_name, MySQLite_config.Database_port) return end local supp = errorCallback and errorCallback(E, sqlText) if not supp then error(E .. " (" .. sqlText .. ")") end end query.onSuccess = function() local res = queryValue and data and data[1] and table.GetFirstValue(data[1]) or not queryValue and data or nil if callback then callback(res, query:lastInsert()) end end query:start() end local function tmsqlQuery(sqlText, callback, errorCallback, queryValue) local call = function(res) res = res[1] -- For now only support one result set if not res.status then local supp = errorCallback and errorCallback(res.error, sqlText) if not supp then error(res.error .. " (" .. sqlText .. ")") end return end if not res.data or #res.data == 0 then res.data = nil end -- compatibility with other backends if queryValue and callback then return callback(res.data and res.data[1] and table.GetFirstValue(res.data[1]) or nil) end if callback then callback(res.data, res.lastid) end end databaseObject:Query(sqlText, call) end local function SQLiteQuery(sqlText, callback, errorCallback, queryValue) local lastError = sql.LastError() local Result = queryValue and sql.QueryValue(sqlText) or sql.Query(sqlText) if sql.LastError() and sql.LastError() ~= lastError then local err = sql.LastError() local supp = errorCallback and errorCallback(err, sqlText) if not supp then error(err .. " (" .. sqlText .. ")") end return end if callback then callback(Result) end return Result end function query(sqlText, callback, errorCallback) local qFunc = (CONNECTED_TO_MYSQL and mysqlOO and msOOQuery or TMySQL and tmsqlQuery) or SQLiteQuery return qFunc(sqlText, callback, errorCallback, false) end function queryValue(sqlText, callback, errorCallback) local qFunc = (CONNECTED_TO_MYSQL and mysqlOO and msOOQuery or TMySQL and tmsqlQuery) or SQLiteQuery return qFunc(sqlText, callback, errorCallback, true) end local function onConnected() CONNECTED_TO_MYSQL = true -- Run the queries that were called before the connection was made for k, v in pairs(cachedQueries or {}) do cachedQueries[k] = nil if v[3] then queryValue(v[1], v[2]) else query(v[1], v[2]) end end cachedQueries = {} hook.Run("DatabaseInitialized") end msOOConnect = function(host, username, password, database_name, database_port) databaseObject = mysqlOO.connect(host, username, password, database_name, database_port) if timer.Exists("darkrp_check_mysql_status") then timer.Destroy("darkrp_check_mysql_status") end databaseObject.onConnectionFailed = function(_, msg) timer.Simple(5, function() msOOConnect(MySQLite_config.Host, MySQLite_config.Username, MySQLite_config.Password, MySQLite_config.Database_name, MySQLite_config.Database_port) end) error("Connection failed! " .. tostring(msg) .. "\nTrying again in 5 seconds.") end databaseObject.onConnected = onConnected databaseObject:connect() end local function tmsqlConnect(host, username, password, database_name, database_port) local db, err = TMySQL.initialize(host, username, password, database_name, database_port) if err then error("Connection failed! " .. err .. "\n") end databaseObject = db onConnected() end function connectToMySQL(host, username, password, database_name, database_port) database_port = database_port or 3306 local func = mysqlOO and msOOConnect or TMySQL and tmsqlConnect or function() end func(host, username, password, database_name, database_port) end function SQLStr(str) local escape = not CONNECTED_TO_MYSQL and sql.SQLStr or mysqlOO and function(str) return "\"" .. databaseObject:escape(tostring(str)) .. "\"" end or TMySQL and function(str) return "\"" .. databaseObject:Escape(tostring(str)) .. "\"" end return escape(str) end function tableExists(tbl, callback, errorCallback) if not CONNECTED_TO_MYSQL then local exists = sql.TableExists(tbl) callback(exists) return exists end queryValue(string.format("SHOW TABLES LIKE %s", SQLStr(tbl)), function(v) callback(v ~= nil) end, errorCallback) end
gpl-3.0
LaFamiglia/Illarion-Content
monster/race_89_red_imp/id_893_mystic.lua
1
1261
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] --ID 893, Mystic Fireimp, Level: 4, Armourtype: cloth, Weapontype: concussion local mageBehaviour = require("monster.base.behaviour.mage") local monstermagic = require("monster.base.monstermagic") local redImps = require("monster.race_89_red_imp.base") local magic = monstermagic() magic.addWarping{probability = 0.15, usage = magic.ONLY_NEAR_ENEMY} magic.addSummon{probability = 0.03, monsters = {622, 1032}} -- slimes magic.addFireball{probability = 0.05, damage = {from = 250, to = 750}} local M = redImps.generateCallbacks() M = magic.addCallbacks(M) return mageBehaviour.addCallbacks(magic, M)
agpl-3.0
650ia/RaOne
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
PowerFull10/Power_Full
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
Inorizushi/DDR-X3
Graphics/NoteField board.lua
1
1369
--Lifted from default, appears to have been written by Kyzentun local filter_color= color("0,0,0,1") local this_pn local args= { --the danger display Def.Quad{ InitCommand=function(self) self :diffusealpha(0) :diffuseshift() :effectcolor1(color("1,0,0,0.8")) :effectcolor2(color("1,0,0,0")) :effectclock("music") :fadeleft(1/32) :faderight(1/32) :hibernate(math.huge) end, PlayerStateSetCommand= function(self, param) local pn= param.PlayerNumber this_pn= pn local style= GAMESTATE:GetCurrentStyle(pn) local width= style:GetWidth(pn) + 32 self:setsize(width, _screen.h*4096):hibernate(0) end, HealthStateChangedMessageCommand= function(self, param) if this_pn and param.PlayerNumber == this_pn then self:linear(0.1) :diffusealpha((param.HealthState == 'HealthState_Danger') and 1 or 0) end end }, --the screen filter Def.Quad{ InitCommand= function(self) self:hibernate(math.huge):diffuse(filter_color) :fadeleft(1/32) :faderight(1/32) end, PlayerStateSetCommand= function(self, param) local pn= param.PlayerNumber local style= GAMESTATE:GetCurrentStyle(pn) local alf= getenv("ScreenFilter"..ToEnumShortString(pn)) or 0 local width= style:GetWidth(pn) + 32 self:setsize(width, _screen.h*4096):diffusealpha(alf/10):hibernate(0) end, } } return Def.ActorFrame(args)
mit
LaFamiglia/Illarion-Content
content/gatheringcraft/glassingotproducing.lua
1
4375
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- glassmeltoven(313) -- quartz sand (316) + potash (314) --> glass ingot (41) -- additional tool: glass blow pipe (311) local common = require("base.common") local gathering = require("content.gathering") module("content.gatheringcraft.glassingotproducing", package.seeall) function StartGathering(User, SourceItem, ltstate) gathering.InitGathering(); local glassingotproducing = gathering.glassingotproducing; common.ResetInterruption( User, ltstate ); if ( ltstate == Action.abort ) then -- work interrupted User:talk(Character.say, "#me unterbricht "..common.GetGenderText(User, "seine", "ihre").." Arbeit.", "#me interrupts "..common.GetGenderText(User, "his", "her").." work.") return end if not common.CheckItem( User, SourceItem ) then -- security check return end -- additional tool item is needed if (User:countItemAt("all",311)==0) then User:inform("[ERROR] No glass blowing pipe found. Please inform a developer."); return end local toolItem = User:getItemAt(5); if ( toolItem.id ~= 311 ) then toolItem = User:getItemAt(6); if ( toolItem.id ~= 311 ) then common.HighInformNLS( User, "Du musst das Glasblasrohr in der Hand haben!", "You have to hold the glass blow pipe in your hand!" ); return end end if not common.FitForWork( User ) then -- check minimal food points return end common.TurnTo( User, SourceItem.pos ); -- turn if necessary -- any other checks? if (User:countItemAt("all",316)==0 or User:countItemAt("all",314)==0) then -- check for items to work on common.HighInformNLS( User, "Du brauchst Quarzsand und Pottasche um Glasblöcke herzustellen.", "You need quartz sand and potash for producing glass ingots." ); return; end if ( ltstate == Action.none ) then -- currently not working -> let's go glassingotproducing.SavedWorkTime[User.id] = glassingotproducing:GenWorkTime(User,toolItem); User:startAction( glassingotproducing.SavedWorkTime[User.id], 0, 0, 0, 0); User:talk(Character.say, "#me beginnt Glasblöcke herzustellen.", "#me starts to produce glass ingots.") return end -- since we're here, we're working if glassingotproducing:FindRandomItem(User) then return end User:learn( glassingotproducing.LeadSkill, glassingotproducing.SavedWorkTime[User.id], glassingotproducing.LearnLimit); User:eraseItem( 316, 1 ); -- erase the item we're working on User:eraseItem( 314, 1 ); -- erase the item we're working on local amount = 1; -- set the amount of items that are produced local notCreated = User:createItem( 41, amount, 333, nil ); -- create the new produced items if ( notCreated > 0 ) then -- too many items -> character can't carry anymore world:createItemFromId( 41, notCreated, User.pos, true, 333, nil ); common.HighInformNLS(User, "Du kannst nichts mehr halten und der Rest fällt zu Boden.", "You can't carry any more and the rest drops to the ground."); else -- character can still carry something if (User:countItemAt("all",316)>0 and User:countItemAt("all",314)>0) then -- there are still items we can work on glassingotproducing.SavedWorkTime[User.id] = glassingotproducing:GenWorkTime(User,toolItem); User:startAction( glassingotproducing.SavedWorkTime[User.id], 0, 0, 0, 0); else -- no items left common.HighInformNLS(User, "Du brauchst Quarzsand und Pottasche um Glasblöcke herzustellen.", "You need quartz sand and potash for producing glass ingots." ); end end if common.GatheringToolBreaks( User, toolItem, glassingotproducing:GenWorkTime(User,toolItem) ) then -- damage and possibly break the tool common.HighInformNLS(User, "Dein altes Glasblasrohr zerbricht.", "Your old glass blow pipe breaks."); return end end
agpl-3.0
luiseduardohdbackup/WarriorQuest
WarriorQuest/runtime/mac/PrebuiltRuntimeLua.app/Contents/Resources/DeprecatedOpenglEnum.lua
148
11934
-- This is the DeprecatedEnum DeprecatedClass = {} or DeprecatedClass _G.GL_RENDERBUFFER_INTERNAL_FORMAT = gl.RENDERBUFFER_INTERNAL_FORMAT _G.GL_LINE_WIDTH = gl.LINE_WIDTH _G.GL_CONSTANT_ALPHA = gl.CONSTANT_ALPHA _G.GL_BLEND_SRC_ALPHA = gl.BLEND_SRC_ALPHA _G.GL_GREEN_BITS = gl.GREEN_BITS _G.GL_STENCIL_REF = gl.STENCIL_REF _G.GL_ONE_MINUS_SRC_ALPHA = gl.ONE_MINUS_SRC_ALPHA _G.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE _G.GL_CCW = gl.CCW _G.GL_MAX_TEXTURE_IMAGE_UNITS = gl.MAX_TEXTURE_IMAGE_UNITS _G.GL_BACK = gl.BACK _G.GL_ACTIVE_ATTRIBUTES = gl.ACTIVE_ATTRIBUTES _G.GL_TEXTURE_CUBE_MAP_POSITIVE_X = gl.TEXTURE_CUBE_MAP_POSITIVE_X _G.GL_STENCIL_BACK_VALUE_MASK = gl.STENCIL_BACK_VALUE_MASK _G.GL_TEXTURE_CUBE_MAP_POSITIVE_Z = gl.TEXTURE_CUBE_MAP_POSITIVE_Z _G.GL_ONE = gl.ONE _G.GL_TRUE = gl.TRUE _G.GL_TEXTURE12 = gl.TEXTURE12 _G.GL_LINK_STATUS = gl.LINK_STATUS _G.GL_BLEND = gl.BLEND _G.GL_LESS = gl.LESS _G.GL_TEXTURE16 = gl.TEXTURE16 _G.GL_BOOL_VEC2 = gl.BOOL_VEC2 _G.GL_KEEP = gl.KEEP _G.GL_DST_COLOR = gl.DST_COLOR _G.GL_VERTEX_ATTRIB_ARRAY_ENABLED = gl.VERTEX_ATTRIB_ARRAY_ENABLED _G.GL_EXTENSIONS = gl.EXTENSIONS _G.GL_FRONT = gl.FRONT _G.GL_DST_ALPHA = gl.DST_ALPHA _G.GL_ATTACHED_SHADERS = gl.ATTACHED_SHADERS _G.GL_STENCIL_BACK_FUNC = gl.STENCIL_BACK_FUNC _G.GL_ONE_MINUS_DST_COLOR = gl.ONE_MINUS_DST_COLOR _G.GL_BLEND_EQUATION = gl.BLEND_EQUATION _G.GL_RENDERBUFFER_DEPTH_SIZE = gl.RENDERBUFFER_DEPTH_SIZE _G.GL_PACK_ALIGNMENT = gl.PACK_ALIGNMENT _G.GL_VENDOR = gl.VENDOR _G.GL_NEAREST_MIPMAP_LINEAR = gl.NEAREST_MIPMAP_LINEAR _G.GL_TEXTURE_CUBE_MAP_POSITIVE_Y = gl.TEXTURE_CUBE_MAP_POSITIVE_Y _G.GL_NEAREST = gl.NEAREST _G.GL_RENDERBUFFER_WIDTH = gl.RENDERBUFFER_WIDTH _G.GL_ARRAY_BUFFER_BINDING = gl.ARRAY_BUFFER_BINDING _G.GL_ARRAY_BUFFER = gl.ARRAY_BUFFER _G.GL_LEQUAL = gl.LEQUAL _G.GL_VERSION = gl.VERSION _G.GL_COLOR_CLEAR_VALUE = gl.COLOR_CLEAR_VALUE _G.GL_RENDERER = gl.RENDERER _G.GL_STENCIL_BACK_PASS_DEPTH_PASS = gl.STENCIL_BACK_PASS_DEPTH_PASS _G.GL_STENCIL_BACK_PASS_DEPTH_FAIL = gl.STENCIL_BACK_PASS_DEPTH_FAIL _G.GL_STENCIL_BACK_WRITEMASK = gl.STENCIL_BACK_WRITEMASK _G.GL_BOOL = gl.BOOL _G.GL_VIEWPORT = gl.VIEWPORT _G.GL_FRAGMENT_SHADER = gl.FRAGMENT_SHADER _G.GL_LUMINANCE = gl.LUMINANCE _G.GL_DECR_WRAP = gl.DECR_WRAP _G.GL_FUNC_ADD = gl.FUNC_ADD _G.GL_ONE_MINUS_DST_ALPHA = gl.ONE_MINUS_DST_ALPHA _G.GL_OUT_OF_MEMORY = gl.OUT_OF_MEMORY _G.GL_BOOL_VEC4 = gl.BOOL_VEC4 _G.GL_POLYGON_OFFSET_FACTOR = gl.POLYGON_OFFSET_FACTOR _G.GL_STATIC_DRAW = gl.STATIC_DRAW _G.GL_DITHER = gl.DITHER _G.GL_TEXTURE31 = gl.TEXTURE31 _G.GL_TEXTURE30 = gl.TEXTURE30 _G.GL_UNSIGNED_BYTE = gl.UNSIGNED_BYTE _G.GL_DEPTH_COMPONENT16 = gl.DEPTH_COMPONENT16 _G.GL_TEXTURE23 = gl.TEXTURE23 _G.GL_DEPTH_TEST = gl.DEPTH_TEST _G.GL_STENCIL_PASS_DEPTH_FAIL = gl.STENCIL_PASS_DEPTH_FAIL _G.GL_BOOL_VEC3 = gl.BOOL_VEC3 _G.GL_POLYGON_OFFSET_UNITS = gl.POLYGON_OFFSET_UNITS _G.GL_TEXTURE_BINDING_2D = gl.TEXTURE_BINDING_2D _G.GL_TEXTURE21 = gl.TEXTURE21 _G.GL_UNPACK_ALIGNMENT = gl.UNPACK_ALIGNMENT _G.GL_DONT_CARE = gl.DONT_CARE _G.GL_BUFFER_SIZE = gl.BUFFER_SIZE _G.GL_FLOAT_MAT3 = gl.FLOAT_MAT3 _G.GL_UNSIGNED_SHORT_5_6_5 = gl.UNSIGNED_SHORT_5_6_5 _G.GL_INT_VEC2 = gl.INT_VEC2 _G.GL_UNSIGNED_SHORT_4_4_4_4 = gl.UNSIGNED_SHORT_4_4_4_4 _G.GL_NONE = gl.NONE _G.GL_BLEND_DST_ALPHA = gl.BLEND_DST_ALPHA _G.GL_VERTEX_ATTRIB_ARRAY_SIZE = gl.VERTEX_ATTRIB_ARRAY_SIZE _G.GL_SRC_COLOR = gl.SRC_COLOR _G.GL_COMPRESSED_TEXTURE_FORMATS = gl.COMPRESSED_TEXTURE_FORMATS _G.GL_STENCIL_ATTACHMENT = gl.STENCIL_ATTACHMENT _G.GL_MAX_VERTEX_ATTRIBS = gl.MAX_VERTEX_ATTRIBS _G.GL_NUM_COMPRESSED_TEXTURE_FORMATS = gl.NUM_COMPRESSED_TEXTURE_FORMATS _G.GL_BLEND_EQUATION_RGB = gl.BLEND_EQUATION_RGB _G.GL_TEXTURE = gl.TEXTURE _G.GL_LINEAR_MIPMAP_LINEAR = gl.LINEAR_MIPMAP_LINEAR _G.GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING _G.GL_CURRENT_PROGRAM = gl.CURRENT_PROGRAM _G.GL_COLOR_BUFFER_BIT = gl.COLOR_BUFFER_BIT _G.GL_TEXTURE20 = gl.TEXTURE20 _G.GL_ACTIVE_ATTRIBUTE_MAX_LENGTH = gl.ACTIVE_ATTRIBUTE_MAX_LENGTH _G.GL_TEXTURE28 = gl.TEXTURE28 _G.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE _G.GL_TEXTURE22 = gl.TEXTURE22 _G.GL_ELEMENT_ARRAY_BUFFER_BINDING = gl.ELEMENT_ARRAY_BUFFER_BINDING _G.GL_STREAM_DRAW = gl.STREAM_DRAW _G.GL_SCISSOR_BOX = gl.SCISSOR_BOX _G.GL_TEXTURE26 = gl.TEXTURE26 _G.GL_TEXTURE27 = gl.TEXTURE27 _G.GL_TEXTURE24 = gl.TEXTURE24 _G.GL_TEXTURE25 = gl.TEXTURE25 _G.GL_NO_ERROR = gl.NO_ERROR _G.GL_TEXTURE29 = gl.TEXTURE29 _G.GL_FLOAT_MAT4 = gl.FLOAT_MAT4 _G.GL_VERTEX_ATTRIB_ARRAY_NORMALIZED = gl.VERTEX_ATTRIB_ARRAY_NORMALIZED _G.GL_SAMPLE_COVERAGE_INVERT = gl.SAMPLE_COVERAGE_INVERT _G.GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL _G.GL_FLOAT_VEC3 = gl.FLOAT_VEC3 _G.GL_STENCIL_CLEAR_VALUE = gl.STENCIL_CLEAR_VALUE _G.GL_UNSIGNED_SHORT_5_5_5_1 = gl.UNSIGNED_SHORT_5_5_5_1 _G.GL_ACTIVE_UNIFORMS = gl.ACTIVE_UNIFORMS _G.GL_INVALID_OPERATION = gl.INVALID_OPERATION _G.GL_DEPTH_ATTACHMENT = gl.DEPTH_ATTACHMENT _G.GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS _G.GL_FRAMEBUFFER_COMPLETE = gl.FRAMEBUFFER_COMPLETE _G.GL_ONE_MINUS_CONSTANT_COLOR = gl.ONE_MINUS_CONSTANT_COLOR _G.GL_TEXTURE2 = gl.TEXTURE2 _G.GL_TEXTURE1 = gl.TEXTURE1 _G.GL_GEQUAL = gl.GEQUAL _G.GL_TEXTURE7 = gl.TEXTURE7 _G.GL_TEXTURE6 = gl.TEXTURE6 _G.GL_TEXTURE5 = gl.TEXTURE5 _G.GL_TEXTURE4 = gl.TEXTURE4 _G.GL_GENERATE_MIPMAP_HINT = gl.GENERATE_MIPMAP_HINT _G.GL_ONE_MINUS_SRC_COLOR = gl.ONE_MINUS_SRC_COLOR _G.GL_TEXTURE9 = gl.TEXTURE9 _G.GL_STENCIL_TEST = gl.STENCIL_TEST _G.GL_COLOR_WRITEMASK = gl.COLOR_WRITEMASK _G.GL_DEPTH_COMPONENT = gl.DEPTH_COMPONENT _G.GL_STENCIL_INDEX8 = gl.STENCIL_INDEX8 _G.GL_VERTEX_ATTRIB_ARRAY_TYPE = gl.VERTEX_ATTRIB_ARRAY_TYPE _G.GL_FLOAT_VEC2 = gl.FLOAT_VEC2 _G.GL_BLUE_BITS = gl.BLUE_BITS _G.GL_VERTEX_SHADER = gl.VERTEX_SHADER _G.GL_SUBPIXEL_BITS = gl.SUBPIXEL_BITS _G.GL_STENCIL_WRITEMASK = gl.STENCIL_WRITEMASK _G.GL_FLOAT_VEC4 = gl.FLOAT_VEC4 _G.GL_TEXTURE17 = gl.TEXTURE17 _G.GL_ONE_MINUS_CONSTANT_ALPHA = gl.ONE_MINUS_CONSTANT_ALPHA _G.GL_TEXTURE15 = gl.TEXTURE15 _G.GL_TEXTURE14 = gl.TEXTURE14 _G.GL_TEXTURE13 = gl.TEXTURE13 _G.GL_SAMPLES = gl.SAMPLES _G.GL_TEXTURE11 = gl.TEXTURE11 _G.GL_TEXTURE10 = gl.TEXTURE10 _G.GL_FUNC_SUBTRACT = gl.FUNC_SUBTRACT _G.GL_STENCIL_BUFFER_BIT = gl.STENCIL_BUFFER_BIT _G.GL_TEXTURE19 = gl.TEXTURE19 _G.GL_TEXTURE18 = gl.TEXTURE18 _G.GL_NEAREST_MIPMAP_NEAREST = gl.NEAREST_MIPMAP_NEAREST _G.GL_SHORT = gl.SHORT _G.GL_RENDERBUFFER_BINDING = gl.RENDERBUFFER_BINDING _G.GL_REPEAT = gl.REPEAT _G.GL_TEXTURE_MIN_FILTER = gl.TEXTURE_MIN_FILTER _G.GL_RED_BITS = gl.RED_BITS _G.GL_FRONT_FACE = gl.FRONT_FACE _G.GL_BLEND_COLOR = gl.BLEND_COLOR _G.GL_MIRRORED_REPEAT = gl.MIRRORED_REPEAT _G.GL_INT_VEC4 = gl.INT_VEC4 _G.GL_MAX_CUBE_MAP_TEXTURE_SIZE = gl.MAX_CUBE_MAP_TEXTURE_SIZE _G.GL_RENDERBUFFER_BLUE_SIZE = gl.RENDERBUFFER_BLUE_SIZE _G.GL_SAMPLE_COVERAGE = gl.SAMPLE_COVERAGE _G.GL_SRC_ALPHA = gl.SRC_ALPHA _G.GL_FUNC_REVERSE_SUBTRACT = gl.FUNC_REVERSE_SUBTRACT _G.GL_DEPTH_WRITEMASK = gl.DEPTH_WRITEMASK _G.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT _G.GL_POLYGON_OFFSET_FILL = gl.POLYGON_OFFSET_FILL _G.GL_STENCIL_FUNC = gl.STENCIL_FUNC _G.GL_REPLACE = gl.REPLACE _G.GL_LUMINANCE_ALPHA = gl.LUMINANCE_ALPHA _G.GL_DEPTH_RANGE = gl.DEPTH_RANGE _G.GL_FASTEST = gl.FASTEST _G.GL_STENCIL_FAIL = gl.STENCIL_FAIL _G.GL_UNSIGNED_SHORT = gl.UNSIGNED_SHORT _G.GL_RENDERBUFFER_HEIGHT = gl.RENDERBUFFER_HEIGHT _G.GL_STENCIL_BACK_FAIL = gl.STENCIL_BACK_FAIL _G.GL_BLEND_SRC_RGB = gl.BLEND_SRC_RGB _G.GL_TEXTURE3 = gl.TEXTURE3 _G.GL_RENDERBUFFER = gl.RENDERBUFFER _G.GL_RGB5_A1 = gl.RGB5_A1 _G.GL_RENDERBUFFER_ALPHA_SIZE = gl.RENDERBUFFER_ALPHA_SIZE _G.GL_RENDERBUFFER_STENCIL_SIZE = gl.RENDERBUFFER_STENCIL_SIZE _G.GL_NOTEQUAL = gl.NOTEQUAL _G.GL_BLEND_DST_RGB = gl.BLEND_DST_RGB _G.GL_FRONT_AND_BACK = gl.FRONT_AND_BACK _G.GL_TEXTURE_BINDING_CUBE_MAP = gl.TEXTURE_BINDING_CUBE_MAP _G.GL_MAX_RENDERBUFFER_SIZE = gl.MAX_RENDERBUFFER_SIZE _G.GL_ZERO = gl.ZERO _G.GL_TEXTURE0 = gl.TEXTURE0 _G.GL_SAMPLE_ALPHA_TO_COVERAGE = gl.SAMPLE_ALPHA_TO_COVERAGE _G.GL_BUFFER_USAGE = gl.BUFFER_USAGE _G.GL_ACTIVE_TEXTURE = gl.ACTIVE_TEXTURE _G.GL_BYTE = gl.BYTE _G.GL_CW = gl.CW _G.GL_DYNAMIC_DRAW = gl.DYNAMIC_DRAW _G.GL_RENDERBUFFER_RED_SIZE = gl.RENDERBUFFER_RED_SIZE _G.GL_FALSE = gl.FALSE _G.GL_GREATER = gl.GREATER _G.GL_RGBA4 = gl.RGBA4 _G.GL_VALIDATE_STATUS = gl.VALIDATE_STATUS _G.GL_STENCIL_BITS = gl.STENCIL_BITS _G.GL_RGB = gl.RGB _G.GL_INT = gl.INT _G.GL_DEPTH_FUNC = gl.DEPTH_FUNC _G.GL_SAMPLER_2D = gl.SAMPLER_2D _G.GL_NICEST = gl.NICEST _G.GL_MAX_VIEWPORT_DIMS = gl.MAX_VIEWPORT_DIMS _G.GL_CULL_FACE = gl.CULL_FACE _G.GL_INT_VEC3 = gl.INT_VEC3 _G.GL_ALIASED_POINT_SIZE_RANGE = gl.ALIASED_POINT_SIZE_RANGE _G.GL_INVALID_ENUM = gl.INVALID_ENUM _G.GL_INVERT = gl.INVERT _G.GL_CULL_FACE_MODE = gl.CULL_FACE_MODE _G.GL_TEXTURE8 = gl.TEXTURE8 _G.GL_VERTEX_ATTRIB_ARRAY_POINTER = gl.VERTEX_ATTRIB_ARRAY_POINTER _G.GL_TEXTURE_WRAP_S = gl.TEXTURE_WRAP_S _G.GL_VERTEX_ATTRIB_ARRAY_STRIDE = gl.VERTEX_ATTRIB_ARRAY_STRIDE _G.GL_LINES = gl.LINES _G.GL_EQUAL = gl.EQUAL _G.GL_LINE_LOOP = gl.LINE_LOOP _G.GL_TEXTURE_WRAP_T = gl.TEXTURE_WRAP_T _G.GL_DEPTH_BUFFER_BIT = gl.DEPTH_BUFFER_BIT _G.GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS _G.GL_SHADER_TYPE = gl.SHADER_TYPE _G.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME _G.GL_TEXTURE_CUBE_MAP_NEGATIVE_X = gl.TEXTURE_CUBE_MAP_NEGATIVE_X _G.GL_TEXTURE_CUBE_MAP_NEGATIVE_Y = gl.TEXTURE_CUBE_MAP_NEGATIVE_Y _G.GL_TEXTURE_CUBE_MAP_NEGATIVE_Z = gl.TEXTURE_CUBE_MAP_NEGATIVE_Z _G.GL_DECR = gl.DECR _G.GL_DELETE_STATUS = gl.DELETE_STATUS _G.GL_DEPTH_BITS = gl.DEPTH_BITS _G.GL_INCR = gl.INCR _G.GL_SAMPLE_COVERAGE_VALUE = gl.SAMPLE_COVERAGE_VALUE _G.GL_ALPHA_BITS = gl.ALPHA_BITS _G.GL_FLOAT_MAT2 = gl.FLOAT_MAT2 _G.GL_LINE_STRIP = gl.LINE_STRIP _G.GL_SHADER_SOURCE_LENGTH = gl.SHADER_SOURCE_LENGTH _G.GL_INVALID_VALUE = gl.INVALID_VALUE _G.GL_NEVER = gl.NEVER _G.GL_INCR_WRAP = gl.INCR_WRAP _G.GL_BLEND_EQUATION_ALPHA = gl.BLEND_EQUATION_ALPHA _G.GL_TEXTURE_MAG_FILTER = gl.TEXTURE_MAG_FILTER _G.GL_POINTS = gl.POINTS _G.GL_COLOR_ATTACHMENT0 = gl.COLOR_ATTACHMENT0 _G.GL_RGBA = gl.RGBA _G.GL_SRC_ALPHA_SATURATE = gl.SRC_ALPHA_SATURATE _G.GL_SAMPLER_CUBE = gl.SAMPLER_CUBE _G.GL_FRAMEBUFFER = gl.FRAMEBUFFER _G.GL_TEXTURE_CUBE_MAP = gl.TEXTURE_CUBE_MAP _G.GL_SAMPLE_BUFFERS = gl.SAMPLE_BUFFERS _G.GL_LINEAR = gl.LINEAR _G.GL_LINEAR_MIPMAP_NEAREST = gl.LINEAR_MIPMAP_NEAREST _G.GL_ACTIVE_UNIFORM_MAX_LENGTH = gl.ACTIVE_UNIFORM_MAX_LENGTH _G.GL_STENCIL_BACK_REF = gl.STENCIL_BACK_REF _G.GL_ELEMENT_ARRAY_BUFFER = gl.ELEMENT_ARRAY_BUFFER _G.GL_CLAMP_TO_EDGE = gl.CLAMP_TO_EDGE _G.GL_TRIANGLE_STRIP = gl.TRIANGLE_STRIP _G.GL_CONSTANT_COLOR = gl.CONSTANT_COLOR _G.GL_COMPILE_STATUS = gl.COMPILE_STATUS _G.GL_RENDERBUFFER_GREEN_SIZE = gl.RENDERBUFFER_GREEN_SIZE _G.GL_UNSIGNED_INT = gl.UNSIGNED_INT _G.GL_DEPTH_CLEAR_VALUE = gl.DEPTH_CLEAR_VALUE _G.GL_ALIASED_LINE_WIDTH_RANGE = gl.ALIASED_LINE_WIDTH_RANGE _G.GL_SHADING_LANGUAGE_VERSION = gl.SHADING_LANGUAGE_VERSION _G.GL_FRAMEBUFFER_UNSUPPORTED = gl.FRAMEBUFFER_UNSUPPORTED _G.GL_INFO_LOG_LENGTH = gl.INFO_LOG_LENGTH _G.GL_STENCIL_PASS_DEPTH_PASS = gl.STENCIL_PASS_DEPTH_PASS _G.GL_STENCIL_VALUE_MASK = gl.STENCIL_VALUE_MASK _G.GL_ALWAYS = gl.ALWAYS _G.GL_MAX_TEXTURE_SIZE = gl.MAX_TEXTURE_SIZE _G.GL_FLOAT = gl.FLOAT _G.GL_FRAMEBUFFER_BINDING = gl.FRAMEBUFFER_BINDING _G.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT _G.GL_TRIANGLE_FAN = gl.TRIANGLE_FAN _G.GL_INVALID_FRAMEBUFFER_OPERATION = gl.INVALID_FRAMEBUFFER_OPERATION _G.GL_TEXTURE_2D = gl.TEXTURE_2D _G.GL_ALPHA = gl.ALPHA _G.GL_CURRENT_VERTEX_ATTRIB = gl.CURRENT_VERTEX_ATTRIB _G.GL_SCISSOR_TEST = gl.SCISSOR_TEST _G.GL_TRIANGLES = gl.TRIANGLES
mit
hnyman/luci
libs/luci-lib-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
LaFamiglia/Illarion-Content
item/food.lua
1
17537
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.food' WHERE itm_id IN (15,49,73,80,81,142,143,147,151,158,159,160,161,162,163,191,199,200,201,302,303,306,307,353,354,355,388,453,454,455,552,553,554,555,556,557,559,1207,2276,2277,2278,2456,2459,2493,2922,2923,2934,2940,3051); local common = require("base.common") local furtunecookies = require("content.furtunecookies") local alchemy = require("alchemy.base.alchemy") local herbs = require("alchemy.base.herbs") local baking = require("content.craft.baking") local cooking = require("content.craft.cooking") local diet = require("lte.diet") local specialeggs = require("content.specialeggs") local M = {} -- buff types, they have exactly two attributes local BUFFS = { {"constitution", "strength"}, {"agility", "dexterity"}, {"perception", "intelligence"} } -- this is updated while adding food items local MAX_DIFFICULTY = 0 local MIN_CRAFTED_FOODVALUE = 6000 local MAX_CRAFTED_FOODVALUE = 45000 local VALUE_SMALL = 875 local VALUE_MEDIUM = 1687 local VALUE_LARGE = 2500 local VALUE_XLARGE = 4000 --[[ create FoodList FoodList:add() adds an element @param integer - item ID @param integer - food value @param integer - leftover item id @param integer - common diet value @param table{ 10 integer } - racial diet value which is added to the common @param table{ 10 boolean } - if not eatable for each race. Do not set it if eatable for all @param integer - poison value OR nil if no poison at all -- if parameter is nil the default values are chosen. the racial tables have the following struct (in order of the race numbers): { human, dwarf, halfling, elf, orc, lizardman, gnome, fairy, goblin, *all others* } ]] local FoodList FoodList = { add = function (self,id,Value,Leftover,BuffType,RacialFactor,UnEatable,Poison) self[id] = {} self[id].value = Value or VALUE_XLARGE self[id].leftover = Leftover or 0 self[id].buffType = BuffType self[id].difficulty = nil self[id].racialFactor = RacialFactor or {1,1,1,1,1,1,1,1,1,1} self[id].unEatable = UnEatable or {} self[id].poison = Poison end } -- Free Food FoodList:add( 15, VALUE_LARGE, 0); -- apple FoodList:add( 80, VALUE_LARGE, 0); -- banana FoodList:add( 81, VALUE_MEDIUM, 0); -- berries FoodList:add( 142, VALUE_MEDIUM, 0); -- sand berry FoodList:add( 143, VALUE_SMALL, 0); -- red elder FoodList:add( 147, VALUE_MEDIUM, 0); -- black berry FoodList:add( 151, VALUE_MEDIUM, 0); -- strawberries FoodList:add( 160, VALUE_SMALL, 0); -- redhead FoodList:add( 161, VALUE_SMALL, 0); -- herders mushroom FoodList:add( 163, VALUE_SMALL, 0); -- champignon FoodList:add( 199, VALUE_SMALL, 0); -- tangerine FoodList:add( 200, VALUE_MEDIUM, 0); -- tomato FoodList:add( 201, VALUE_SMALL, 0); -- onion FoodList:add( 302, VALUE_SMALL, 0); -- cherry FoodList:add( 388, VALUE_MEDIUM, 0); -- grapes FoodList:add( 759, VALUE_LARGE, 0); -- nuts FoodList:add(2493, VALUE_LARGE, 0); -- carrots FoodList:add(1149, VALUE_SMALL, 0); -- brown egg FoodList:add(1150, VALUE_SMALL, 0); -- white egg FoodList:add(1207, VALUE_LARGE, 0); -- orange FoodList:add(3567, VALUE_MEDIUM, 0); -- potato -- Racial Food FoodList:add( 73, VALUE_LARGE, 0, nil, nil, {true,true,true,true,true,false,true,true,true,true}); -- trout (lizard) FoodList:add( 307, VALUE_LARGE, 0, nil, nil, {true,true,true,true,false,true,true,true,true,true}); -- pork (orc) FoodList:add( 355, VALUE_LARGE, 0, nil, nil, {true,true,true,true,true,false,true,true,true,true}); -- salmon (lizard) FoodList:add( 552, VALUE_LARGE, 0, nil, nil, {true,true,true,true,false,true,true,true,true,true}); -- deer meat (orc) FoodList:add( 553, VALUE_LARGE, 0, nil, nil, {true,true,true,true,false,true,true,true,true,true}); -- rabbit meat (orc) FoodList:add(2934, VALUE_LARGE, 0, nil, nil, {true,true,true,true,false,true,true,true,true,true}); -- lamb meat (orc) FoodList:add(1151, VALUE_LARGE, 0, nil, nil, {true,true,true,true,false,true,true,true,true,true}); -- chicken meat (orc) FoodList:add(2940, VALUE_LARGE, 0, nil, nil, {true,true,true,true,false,true,true,true,true,true}); -- raw steak (orc) FoodList:add(1209, VALUE_LARGE, 0, nil, nil, {true,true,true,true,true,false,true,true,true,true}); -- horse mackerel (lizard) FoodList:add(1210, VALUE_LARGE, 0, nil, nil, {true,true,true,true,true,false,true,true,true,true}); -- rose fish (lizard) -- Simple Food FoodList:add( 306, VALUE_XLARGE, 0); -- ham FoodList:add( 455, VALUE_XLARGE, 0); -- smoked fish -- Crafted Food FoodList:add(3051, nil, 0, 1, {1,1,1,1,2,1,1,0.5,1,1}); -- sausage FoodList:add( 191, nil, 0, 1, {1,1,1,1,1,0.5,1,1,1,1}); -- bread roll FoodList:add(3606, nil, 0, 1, {1,1,1,1,2,1,1,0.5,1,1}); -- cooked steak FoodList:add(2456, nil, 2935, 2, {1,1,1,1,0.5,1,1,1,1,1}); -- mushroom soup FoodList:add( 453, nil, 0, 2, {1,1,2,1,0.5,0.5,1,2,1,1}); -- cookies FoodList:add(2923, nil, 2935, 2, {1,1,1,1,0.5,1,1,1,1,1}); -- onion soup FoodList:add(2459, nil, 2952, 1, {1,1,0.5,1,1,2,1,0.5,1,1}); -- fish filet dish FoodList:add( 49, nil, 0, 1, {1,1,1,1,1,0.5,1,1,1,1}); -- bread FoodList:add(2278, nil, 2935, 2, {1,1,1,1,0.5,1,1,1,1,1}); -- cabbage stew FoodList:add( 556, nil, 2952, 1, {1,1,0.5,1,1,2,1,0.5,1,1}); -- salmon dish FoodList:add(2276, nil, 2935, 2, {1,1,1,1,0.5,1,1,1,1,1}); -- mulligan FoodList:add( 454, nil, 0, 2, {1,1,2,1,0.5,0.5,1,2,1,1}); -- muffin FoodList:add(2277, nil, 2952, 1, {1,1,1,1,2,1,1,0.5,1,1}); -- meat dish FoodList:add( 353, nil, 0, 2, {1,1,2,1,0.5,0.5,1,2,1,1}); -- applecake FoodList:add(2922, nil, 2952, 1, {1,1,1,1,2,1,1,0.5,1,1}); -- sausages dish FoodList:add( 557, nil, 2952, 1, {1,1,1,1,2,1,1,0.5,1,1}); -- steak dish FoodList:add( 303, nil, 0, 2, {1,1,2,1,0.5,0.5,1,2,1,1}); -- cherrycake FoodList:add( 555, nil, 2952, 1, {1,1,1,1,2,1,1,0.5,1,1}); -- rabbit dish FoodList:add( 354, nil, 0, 2, {1,1,2,1,0.5,0.5,1,2,1,1}); -- strawberry cake FoodList:add( 559, nil, 2952, 1, {1,1,1,1,2,1,1,0.5,1,1}); -- lamb dish FoodList:add( 554, nil, 2952, 1, {1,1,1,1,2,1,1,0.5,1,1}); -- venison dish FoodList:add(1152, nil, 2935, 2, {1,1,1,1,0.5,1,1,1,1,1}); -- chicken soup FoodList:add(1153, nil, 0, 3, {1,1,2,1,0.5,0.5,1,2,1,1}); -- custard pie FoodList:add(1154, nil, 2952, 1, {1,1,1,1,2,1,1,0.5,1,1}); -- egg dish FoodList:add(1155, nil, 2952, 1, {1,1,1,1,2,1,1,0.5,1,1}); -- chicken dish FoodList:add( 3568, nil, 0, 1, {1,1,1,1,1,1,1,1,1,1}); -- Baked potato FoodList:add( 3569, nil, 2935, 1, {2,2,2,1,1,1,1,1,1,1}); -- Potato soup FoodList:add( 3570, nil, 2935, 1, {2,2,2,1,1,2,1,1,1,1}); -- Egg Salad FoodList:add( 3571, nil, 0, 1, {2,2,2,1,1,2,1,1,1,1}); -- Egg Salad Sandwich FoodList:add( 3572, nil, 2935, 1, {1,1,1,1,1,2,1,1,1,1}); -- Fish Soup FoodList:add( 3573, nil, 0, 1, {1,1,1,1,1,1,1,1,1,1}); -- cheese FoodList:add( 3609, nil, 0, 1, {1,1,1,1,1,1,1,1,1,1}); -- banana bread FoodList:add( 3610, nil, 0, 1, {1,1,1,1,1,1,1,1,1,1}); -- elderberry pie FoodList:add( 3631, nil, 0, 1, {1,1,1,1,1,1,1,1,1,1}); -- sausage on bread -- Poisoned Food FoodList:add( 162, VALUE_SMALL, 0, nil, nil, nil, 600); -- birth mushroom FoodList:add( 158, VALUE_SMALL, 0, nil, nil, nil, 400); -- bulbsponge mushroom FoodList:add( 159, VALUE_MEDIUM, 0, nil, nil, nil, 1000); -- toadstool local function SetNewFoodLevel(User, NewFoodLevel) NewFoodLevel = common.Limit(NewFoodLevel, 0, 60000); local foodToAdd = NewFoodLevel - User:increaseAttrib("foodlevel",0); while true do User:increaseAttrib("foodlevel",math.min(10000,foodToAdd)); foodToAdd = foodToAdd - math.min(10000,foodToAdd); if (foodToAdd == 0) then break; end end end local Init function M.UseItem(User, SourceItem, ltstate) if (Init == nil) then Init = 1; -- import difficulties from crafts for _,product in pairs(baking.baking.products) do if (FoodList[product.item] ~= nil) then FoodList[product.item].difficulty = product.difficulty; MAX_DIFFICULTY = math.max(MAX_DIFFICULTY, product.difficulty); end end for _,product in pairs(cooking.cooking.products) do if (FoodList[product.item] ~= nil) then FoodList[product.item].difficulty = product.difficulty; MAX_DIFFICULTY = math.max(MAX_DIFFICULTY, product.difficulty); end end -- now we know the max difficulty, so set the food value with linear distribution local diff = MAX_CRAFTED_FOODVALUE - MIN_CRAFTED_FOODVALUE; for _,foodItem in pairs(FoodList) do if (type(foodItem) ~= "function") then if (foodItem.difficulty ~= nil) then foodItem.value = MIN_CRAFTED_FOODVALUE + diff*(foodItem.difficulty/MAX_DIFFICULTY); else -- for non crafted foods, the maximum foodvalue is the MIN_CRAFTED_FOODVALUE foodItem.value = math.min(MIN_CRAFTED_FOODVALUE, foodItem.value); end end end end -- check if used for alchemy purpose local isPlant, ignoreIt = alchemy.getPlantSubstance(SourceItem.id, User) local cauldron = alchemy.GetCauldronInfront(User,SourceItem) if (cauldron ~= nil) and isPlant then herbs.UseItem(User, SourceItem, ltstate) return end --check for special eggs if specialeggs.checkSpecialEgg(SourceItem, User) then return end -- item should not be static if SourceItem.wear == 255 then common.HighInformNLS(User, "Das kannst du nicht essen.", "You can't eat that."); return; end local foodItem = FoodList[ SourceItem.id ]; -- known food item? if (foodItem == nil ) then User:inform("[ERROR] unknown food item. ID: " .. SourceItem.id .. ". Please inform a developer."); return; end -- define user's race (+1 for valid table index), non-playable races are set to 10 local race = math.min(User:getRace()+1, 10); -- not eatable for user's race if foodItem.unEatable[race] then common.HighInformNLS(User, "Das kannst du nicht essen.", "You can't eat that."); return; end -- user should not fight if User.attackmode then common.HighInformNLS( User, "Du kannst nicht während eines Kampfes essen.", "You cannot eat during a fight."); return; end -- fortune cookies if (SourceItem.id == 453) then if (math.random(1,100)==1) then local deText, enText = furtunecookies.cookie(); common.InformNLS( User, "Du findest ein Stück Papier in dem Keks: \""..deText.."\"", "You find a piece of paper inside the cookie: \""..enText.."\""); end end -- consume food world:erase(SourceItem,1); local foodLevel = User:increaseAttrib("foodlevel",0); -- adjust food value for small races local foodVal; if ( User:getRace() == 7 ) then -- fairy (food * 1.8) foodVal = math.ceil( foodItem.value * 1.8 ) elseif ( User:getRace() == 2 ) or ( User:getRace() == 6 ) or ( User:getRace() == 8 ) then -- halfling or gnome and goblin (food * 1.4) foodVal = math.ceil( foodItem.value * 1.4 ) else -- other races foodVal = foodItem.value; end -- create leftovers if( foodItem.leftover > 0 ) then if( math.random( 50 ) <= 1 ) then common.HighInformNLS( User, "Das alte Geschirr ist nicht mehr brauchbar.", "The old dishes are no longer usable."); else local notCreated = User:createItem( foodItem.leftover, 1, 333, nil); if ( notCreated > 0 ) then world:createItemFromId( foodItem.leftover, notCreated, User.pos, true, 333, nil ); common.HighInformNLS(User, "Du kannst nichts mehr halten und lässt das Geschirr zu Boden fallen.", "You can't carry any more and let the dishes drop to the ground."); end end end -- check for poison local poison = foodItem.poison; if (poison ~= nil) then User:setPoisonValue( common.Limit( (User:getPoisonValue() + poison) , 0, 10000) ); common.HighInformNLS(User, "Du fühlst dich krank und etwas benommen.", "You feel sick and a little dizzy."); SetNewFoodLevel(User, foodLevel-foodVal); return; end foodLevel = foodLevel + foodVal; -- check if ate too much. Grant a buffer of half of the actual food value if (60000 + (0.5*foodVal) - foodLevel < 0) then common.HighInformNLS( User, "Du bekommst kaum noch was runter und dir wird schlecht.", "You hardly manage to eat something more and get sick!"); -- check for newbie state if (not common.IsOnNoobia(User.pos) and not (User:increaseAttrib("hitpoints",0) < 2000)) then User:increaseAttrib("hitpoints",-1000); end SetNewFoodLevel(User, 50000); return; end -- everything is okay, so fill the foodlevel SetNewFoodLevel(User, foodLevel); -- inform the player about the food level. Avoid spam. if (foodLevel > 55000) and ((foodLevel-foodVal) <= 55000) then common.InformNLS( User, "Nur mit Mühe kannst du dir noch etwas hinunter zwingen.", "You hardly manage to eat something more."); elseif (foodLevel > 50000) and ((foodLevel-foodVal) <= 50000) then common.InformNLS( User, "Du bist sehr satt.", "You have had enough."); elseif (foodLevel > 40000) and ((foodLevel-foodVal) <= 40000) then common.InformNLS( User, "Du bist satt.", "You are stuffed."); elseif (foodLevel > 30000) and ((foodLevel-foodVal) <= 30000) then common.InformNLS( User, "Du fühlst dich noch etwas hungrig.", "You still feel a little hungry."); elseif (foodLevel > 20000) and ((foodLevel-foodVal) <= 20000) then common.InformNLS( User, "Du hast noch immer Hunger.", "You are still hungry."); elseif (foodLevel > 5000) and ((foodLevel-foodVal) <= 5000) then common.InformNLS( User, "Dein Magen schmerzt noch immer vor Hunger.", "Your stomach still hurts because of your hunger."); end -- check for buffs if (foodItem.buffType ~= nil) then -- calculate how long the buff will last, at least 5min, maximal 30min local newDuration = 300; -- grant even easy craftable items a good chance by adding 5 local raceDifficulty = (foodItem.difficulty+5)*foodItem.racialFactor[race]; -- add 5 more minutes each in 5 more random experiments for i=1,5 do if (math.random(1,105) <= raceDifficulty) then newDuration = newDuration + 300; end end -- determine number of increased attributes local newBuffAmount = 1; if (math.random(1,105) <= raceDifficulty) then newBuffAmount = 2; end -- add buff, if it is better than the previous one local foundEffect,dietEffect=User.effects:find(12); if (foundEffect) then local foundType, buffType = dietEffect:findValue("buffType"); if (foundType) then local foundAmount, buffAmount = dietEffect:findValue("buffAmount"); if (foundAmount) then -- check if old one is better local newIsBetter = false; if (buffAmount < newBuffAmount) then newIsBetter = true; else local foundExpire, buffExpireStamp = dietEffect:findValue("buffExpireStamp"); if (not foundExpire) then User:inform("[ERROR] No expire stamp found. Using new one instead. Please inform a developer."); newIsBetter = true; else if (newDuration > buffExpireStamp - common.GetCurrentTimestamp()) then newIsBetter = true; end end end if (newIsBetter) then dietEffect:addValue("buffExpireStamp", common.GetCurrentTimestamp() + newDuration); if (newBuffAmount > buffAmount or buffType ~= foodItem.buffType) then dietEffect:addValue("buffType", foodItem.buffType); dietEffect:addValue("buffAmount", newBuffAmount); diet.RemoveBuff(dietEffect, User); diet.InformPlayer(dietEffect, User); end end else User:inform("[ERROR] Found diet effect without buffAmount. Adding new buff. Please inform a developer."); end else User:inform("[ERROR] Found diet effect without buffType. Adding new buff. Please inform a developer."); end else local dietEffect=LongTimeEffect(12, newDuration*10); dietEffect:addValue("buffType", foodItem.buffType); dietEffect:addValue("buffAmount", newBuffAmount); dietEffect:addValue("buffExpireStamp", common.GetCurrentTimestamp() + newDuration); User.effects:addEffect(dietEffect); end end end return M
agpl-3.0
mpeterv/pflua
tests/pfquickcheck/pflua_ir.lua
25
1989
#!/usr/bin/env luajit -- -*- lua -*- -- This module generates (a subset of) pflua's IR, -- for property-based tests of pflua internals. module(..., package.seeall) local choose = require("pf.utils").choose local True, False, Fail, ComparisonOp, BinaryOp, Number, Len local Binary, Arithmetic, Comparison, Conditional -- Logical intentionally is not local; it is used elsewhere function True() return { 'true' } end function False() return { 'false' } end function Fail() return { 'fail' } end function ComparisonOp() return choose({ '<', '>' }) end function BinaryOp() return choose({ '+', '-', '/' }) end -- Boundary numbers are often particularly interesting; test them often function Number() if math.random() < 0.2 then return math.random(0, 2^32 - 1) else return choose({ 0, 1, 2^31-1, 2^31, 2^32-1 }) end end function Len() return 'len' end function Binary(db) local op, lhs, rhs = BinaryOp(), Arithmetic(db), Arithmetic(db) if op == '/' then table.insert(db, { '!=', rhs, 0 }) end return { 'uint32', { op, lhs, rhs } } end function PacketAccess(db) local pkt_access_size = choose({1, 2, 4}) local position = Arithmetic(db) table.insert(db, {'>=', 'len', {'+', position, pkt_access_size}}) local access = { '[]', position, pkt_access_size } if pkt_access_size == 1 then return access end if pkt_access_size == 2 then return { 'ntohs', access } end if pkt_access_size == 4 then return { 'uint32', { 'ntohs', access } } end error('unreachable') end function Arithmetic(db) return choose({ Binary, Number, Len, PacketAccess })(db) end function Comparison() local asserts = {} local expr = { ComparisonOp(), Arithmetic(asserts), Arithmetic(asserts) } for i=#asserts,1,-1 do expr = { 'if', asserts[i], expr, { 'fail' } } end return expr end function Conditional() return { 'if', Logical(), Logical(), Logical() } end function Logical() return choose({ Conditional, Comparison, True, False, Fail })() end
apache-2.0
dismantl/luci-0.12
applications/luci-pbx/luasrc/model/cbi/pbx.lua
146
4360
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. luci-pbx 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 luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- modulename = "pbx" if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end -- Returns formatted output of string containing only the words at the indices -- specified in the table "indices". function format_indices(string, indices) if indices == nil then return "Error: No indices to format specified.\n" end -- Split input into separate lines. lines = luci.util.split(luci.util.trim(string), "\n") -- Split lines into separate words. splitlines = {} for lpos,line in ipairs(lines) do splitlines[lpos] = luci.util.split(luci.util.trim(line), "%s+", nil, true) end -- For each split line, if the word at all indices specified -- to be formatted are not null, add the formatted line to the -- gathered output. output = "" for lpos,splitline in ipairs(splitlines) do loutput = "" for ipos,index in ipairs(indices) do if splitline[index] ~= nil then loutput = loutput .. string.format("%-40s", splitline[index]) else loutput = nil break end end if loutput ~= nil then output = output .. loutput .. "\n" end end return output end m = Map (modulename, translate("PBX Main Page"), translate("This configuration page allows you to configure a phone system (PBX) service which \ permits making phone calls through multiple Google and SIP (like Sipgate, \ SipSorcery, and Betamax) accounts and sharing them among many SIP devices. \ Note that Google accounts, SIP accounts, and local user accounts are configured in the \ \"Google Accounts\", \"SIP Accounts\", and \"User Accounts\" sub-sections. \ You must add at least one User Account to this PBX, and then configure a SIP device or \ softphone to use the account, in order to make and receive calls with your Google/SIP \ accounts. Configuring multiple users will allow you to make free calls between all users, \ and share the configured Google and SIP accounts. If you have more than one Google and SIP \ accounts set up, you should probably configure how calls to and from them are routed in \ the \"Call Routing\" page. If you're interested in using your own PBX from anywhere in the \ world, then visit the \"Remote Usage\" section in the \"Advanced Settings\" page.")) ----------------------------------------------------------------------------------------- s = m:section(NamedSection, "connection_status", "main", translate("PBX Service Status")) s.anonymous = true s:option (DummyValue, "status", translate("Service Status")) sts = s:option(DummyValue, "_sts") sts.template = "cbi/tvalue" sts.rows = 20 function sts.cfgvalue(self, section) if server == "asterisk" then regs = luci.sys.exec("asterisk -rx 'sip show registry' | sed 's/peer-//'") jabs = luci.sys.exec("asterisk -rx 'jabber show connections' | grep onnected") usrs = luci.sys.exec("asterisk -rx 'sip show users'") chan = luci.sys.exec("asterisk -rx 'core show channels'") return format_indices(regs, {1, 5}) .. format_indices(jabs, {2, 4}) .. "\n" .. format_indices(usrs, {1} ) .. "\n" .. chan elseif server == "freeswitch" then return "Freeswitch is not supported yet.\n" else return "Neither Asterisk nor FreeSwitch discovered, please install Asterisk, as Freeswitch is not supported yet.\n" end end return m
apache-2.0
shmul/mule
fdi/hourlyAlg.lua
1
5610
------------------------------------- -- Hourly algo, Matlab version 27 --- ------------------------------------- require 'helpers' require 'fdi/statisticsBasic' --require 'statisticsBasic' -- costants local INTERVAL = 3600 local REF_TIME = 1357344000 local DAY = 24 local WEEK = 168 -- parameters local DRIFT = 1.2 local THRESHOLD = 10 local CYCLE_FORGETTING_FACTOR = 0.3 local SD_FORGETTING_FACTOR = 0.005 local TREND_FORGETTING_FACTOR = 0.01 local MAX_TREND = 0.2 local LOGNORMAL_SHIFT = 150 local MIN_SD = 0.15 local MAX_DEV = 3 -- initialization values INIT_SD = 0.2 function calculate_fdi_hours(times_, values_) local step = 0 -- samples model local primaryCycle = {} local secondaryCycle = {} local sd = INIT_SD local trend = 0 -- change model local cycleState = {} local devWindow = {} local alarmPeriod = 0 local upperCusum = 0 local lowerCusum = 0 local upperCusumAno = 0 local lowerCusumAno = 0 local downtime = 0 local function iter(timestamp_, value_) -- lua optimization local insert = table.insert local remove = table.remove local log = math.log local abs = math.abs local max = math.max local min = math.min local sqrt = math.sqrt local exp = math.exp local floor = math.floor step = step + 1 local tval = log(LOGNORMAL_SHIFT + value_) local ii = (timestamp_ - REF_TIME) / INTERVAL local hh = (ii % WEEK) + 1 if(value_ == 0) then downtime = downtime + 1 else downtime = 0 end local err = 0 local est = tval if(step <= WEEK) then primaryCycle[hh] = tval cycleState[hh] = 0 if(step == WEEK) then local cycArray = {} local cycValue = 0 for jj = 1,DAY do for kk = 1,7 do cycArray[kk] = primaryCycle[jj + (kk-1) * DAY] end cycValue = median(cycArray) for kk = 1,7 do primaryCycle[jj + (kk-1) * DAY] = cycValue end end end else est = primaryCycle[hh] + trend if(est < log(LOGNORMAL_SHIFT)) then est = log(LOGNORMAL_SHIFT) end err = tval - est if(cycleState[hh] > 0) then local secondest = secondaryCycle[hh] + trend if(secondest < log(LOGNORMAL_SHIFT)) then secondest = log(LOGNORMAL_SHIFT) end local seconderr = tval - secondest if(abs(seconderr) < abs(err)) then est = secondest err = seconderr local temp = primaryCycle[hh] primaryCycle[hh] = secondaryCycle[hh] secondaryCycle[hh] = temp end end upperCusumAno = max(0, upperCusumAno + (err - DRIFT * sd)) lowerCusumAno = min(0, lowerCusumAno + (err + DRIFT * sd)) local upperCusumTemp = max(0, upperCusum + (err - DRIFT * sd)) local lowerCusumTemp = min(0, lowerCusum + (err + DRIFT * sd)) if((upperCusumTemp > THRESHOLD * sd) or (lowerCusumTemp < -THRESHOLD * sd)) then secondaryCycle[hh] = tval if(cycleState[hh] == 0) then if(downtime == 0 or downtime > 2*DAY) then cycleState[hh] = 1 end alarmPeriod = alarmPeriod + 1 elseif(cycleState[hh] == 1) then cycleState[hh] = 2 alarmPeriod = 0 upperCusum = 0 lowerCusum = 0 else --(cycleState[hh] == 2) cycleState[hh] = 0 alarmPeriod = 0 primaryCycle[hh] = tval end else if(cycleState[hh] == 0) then cycleState[hh] = 0 elseif(cycleState[hh] == 1) then cycleState[hh] = 2 else --(cycleState[hh] == 2) cycleState[hh] = 0 end if(cycleState[hh] == 0 and alarmPeriod == 0) then upperCusum = upperCusumTemp lowerCusum = lowerCusumTemp else upperCusum = 0 lowerCusum = 0 end if(alarmPeriod > 0) then upperCusumAno = upperCusum lowerCusumAno = lowerCusum end -- reset alarm alarmPeriod = 0 -- update cycle primaryCycle[hh] = primaryCycle[hh] + trend + CYCLE_FORGETTING_FACTOR * err -- update trend trend = trend + TREND_FORGETTING_FACTOR * err if(trend > MAX_TREND) then trend = MAX_TREND end if(trend < -MAX_TREND) then trend = -MAX_TREND end end end -- update sd if(alarmPeriod < 3) then local dev = 0 if(err > MAX_DEV * sd) then dev = MAX_DEV * sd elseif(err < -MAX_DEV * sd) then dev = -MAX_DEV * sd else dev = err end sd = sqrt((1-SD_FORGETTING_FACTOR)*sd^2 + SD_FORGETTING_FACTOR*dev^2) if(sd < MIN_SD) then sd = MIN_SD end end local alert = step > 2*WEEK and alarmPeriod > 0 local ano = 0 if(alert) then if(err > 0) then ano = min(1000, floor(upperCusumAno + 0.5)) else ano = max(-1000, floor(lowerCusumAno + 0.5)) end end local iterResult = {timestamp_, alert, exp(est) - LOGNORMAL_SHIFT, ano} return iterResult end -------------------------------------------- --------- Enclosing Function -------------- -------------------------------------------- -- check input local range = #times_ if range ~= #values_ then loge('Size of time ponits and value points must equal') return {} end -- initilialize tables local initEst = math.log(LOGNORMAL_SHIFT) for ii = 1,WEEK do primaryCycle[ii] = initEst secondaryCycle[ii] = initEst cycleState[ii] = 0 end -- detect changes local result = {} local insert = table.insert for ii=1,range do local iterResult = iter(times_[ii], values_[ii]) insert(result, iterResult) end return result end
apache-2.0
chelog/brawl
gamemodes/brawl/gamemode/init.lua
1
2188
brawl = brawl or {} -- include libraries include "lib/mysqlite.lua" AddCSLuaFile "lib/misc.lua" function brawl.msg( text, ... ) local args = {...} local time = os.date( "(%H:%M:%S)", os.time() ) local msg = args and string.format( text, unpack(args) ) or text print( string.format( "[#] %s - %s", time, msg ) ) end function brawl.debugmsg( text, ... ) if brawl.getDebugEnabled() then brawl.msg( text, ... ) end end function brawl.initDB() -- brawl.config.db = { -- -- EnableMySQL = true, -- Host = "127.0.0.1", -- Username = "gmod", -- Password = "ohThatGMod", -- Database_name = "brawl", -- Database_port = 3306, -- Preferred_module = "tmysql4", -- -- } brawl.config.db = { EnableMySQL = false, Host = "", Username = "", Password = "", Database_name = "", Database_port = 3306, Preferred_module = "mysqloo", } MySQLite.initialize( brawl.config.db ) end function brawl.initConCommands() -- basic server confing local data = brawl.config.server RunConsoleCommand( "hostname", data.name ) RunConsoleCommand( "sv_password", data.password ) RunConsoleCommand( "sv_loadingurl", data.loadingURL ) -- workshop for _, id in pairs( brawl.config.server.workshop ) do resource.AddWorkshop( id ) end local map = string.lower( game.GetMap() ) if not brawl.config.maps[ map ] then error( "The map is not in config, please follow instructions here on how to add the map to gamemode: https://github.com/chelog/brawl" ) end local mapID = brawl.config.maps[ map ].workshop if mapID then resource.AddWorkshop( mapID ) brawl.msg( "Added workshop download for %s (%s)", brawl.config.maps[ map ].name, mapID ) end -- startup commands for _, entry in pairs( data.runCommands ) do local args = string.Explode( " ", entry ) local cmd = table.remove( args, 1 ) RunConsoleCommand( cmd, unpack( args ) ) end brawl.setDebugEnabled( brawl.config.debug ) end function brawl.setDebugEnabled( val ) SetGlobalBool( "brawl.debug", val ) end function brawl.init() brawl.loadConfig() brawl.initDB() brawl.loadFiles() brawl.initConCommands() end -- begin loading AddCSLuaFile( "cl_init.lua" ) include( "sh_init.lua" )
gpl-3.0
chelog/brawl
addons/brawl-weapons/lua/weapons/khr_aek971/shared.lua
1
9501
AddCSLuaFile() AddCSLuaFile("sh_sounds.lua") include("sh_sounds.lua") SWEP.magType = "arMag" if CLIENT then SWEP.DrawCrosshair = false SWEP.PrintName = "AEK-971" SWEP.CSMuzzleFlashes = true SWEP.IconLetter = "w" killicon.Add( "", "", Color(255, 80, 0, 150)) SWEP.MuzzleEffect = "muzzleflash_ak47" SWEP.PosBasedMuz = true SWEP.ShellScale = 0.3 SWEP.ShellDelay = .02 SWEP.ShellOffsetMul = 1 SWEP.ShellPosOffset = {x = -0, y = 0, z = 0} SWEP.ForeGripOffsetCycle_Draw = 0 SWEP.ForeGripOffsetCycle_Reload = .85 SWEP.ForeGripOffsetCycle_Reload_Empty = .85 SWEP.SightWithRail = true SWEP.DisableSprintViewSimulation = false SWEP.SnapToIdlePostReload = true SWEP.BoltBone = "slide" SWEP.BoltBonePositionRecoverySpeed = 50 SWEP.BoltShootOffset = Vector(-2, 0, 0) SWEP.IronsightPos = Vector(-2.66, -1.6667, 0.38) SWEP.IronsightAng = Vector(0.1, 0.6, 0) SWEP.CSGOACOGPos = Vector(-2.744, -2.5, -0.96) SWEP.CSGOACOGAng = Vector(0, 0, 0) SWEP.FAS2AimpointPos = Vector(-2.719, -2.5, -0.848) SWEP.FAS2AimpointAng = Vector(0, 0, 0) SWEP.EoTech553Pos = Vector(-2.725, -2.5, -1.056) SWEP.EoTech553Ang = Vector(0, 0, 0) SWEP.MicroT1Pos = Vector(-2.737, -2.5, -0.805) SWEP.MicroT1Ang = Vector(0, 0, 0) SWEP.KR_CMOREPos = Vector(-2.74, -2.5, -0.95) SWEP.KR_CMOREAng = Vector(0, 0, 0) SWEP.PSOPos = Vector(-2.5813, 0.5, -0.114) SWEP.PSOAng = Vector(0, 0, 0) SWEP.ShortDotPos = Vector(-2.7323, -2.5, -0.876) SWEP.ShortDotAng = Vector(0, 0, 0) SWEP.KobraPos = Vector(-2.695, -2.5, -0.15) SWEP.KobraAng = Vector(0, 0, 0) SWEP.AlternativePos = Vector(-0.5556, -0.4, -0.5556) SWEP.AlternativeAng = Vector(0, 0, 0) SWEP.SprintPos = Vector(0.5556, -0.5556, 0.5556) SWEP.SprintAng = Vector(-30, 34, -22) SWEP.BackupSights = {["md_acog"] = {[1] = Vector(-1.12, -1, -.73), [2] = Vector(0, 0, 0)}} SWEP.CustomizationMenuScale = 0.024 SWEP.ViewModelMovementScale = 1 SWEP.AttachmentModelsVM = { ["md_uecw_csgo_acog"] = { type = "Model", model = "models/gmod4phun/csgo/eq_optic_acog.mdl", bone = "Plane02", rel = "", pos = Vector(-5.7, 0.019, -0.47), angle = Angle(0, 0, 0), size = Vector(0.649, 0.649, 0.649), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_fas2_aimpoint"] = { type = "Model", model = "models/c_fas2_aimpoint.mdl", bone = "Plane02", rel = "", pos = Vector(1.557, 0.019, 1.85), angle = Angle(0, 0, 0), size = Vector(0.899, 0.899, 0.899), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["odec3d_cmore_kry"] = { type = "Model", model = "models/weapons/krycek/sights/odec3d_cmore_reddot.mdl", bone = "Plane02", rel = "", pos = Vector(-0.519, 0.109, 2.539), angle = Angle(0, 0, 0), size = Vector(0.209, 0.209, 0.209), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_pso1"] = { type = "Model", model = "models/cw2/attachments/pso.mdl", bone = "Plane02", rel = "", pos = Vector(-4.5, 0, -1), angle = Angle(0, -90, 0), size = Vector(0.649, 0.649, 0.649), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_pbs1"] = { type = "Model", model = "models/cw2/attachments/pbs1.mdl", bone = "Plane02", rel = "", pos = Vector(17, 0.239, -0.65), angle = Angle(0, -90, 0), size = Vector(0.699, 0.699, 0.699), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_microt1kh"] = { type = "Model", model = "models/cw2/attachments/microt1.mdl", bone = "Plane02", rel = "", pos = Vector(-0.801, 0.035, 2.569), angle = Angle(0, -90, 0), size = Vector(0.3, 0.3, 0.3), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_fas2_eotech"] = { type = "Model", model = "models/c_fas2_eotech.mdl", bone = "Plane02", rel = "", pos = Vector(1.957, 0.025, 2.059), angle = Angle(0, 0, 0), size = Vector(0.85, 0.85, 0.85), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_rail"] = { type = "Model", model = "models/wystan/attachments/akrailmount.mdl", bone = "Plane02", rel = "", pos = Vector(-0.601, 0.259, 0.8), angle = Angle(0, 90, 0), size = Vector(0.899, 0.899, 0.899), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_schmidt_shortdot"] = { type = "Model", model = "models/cw2/attachments/schmidt.mdl", bone = "Plane02", rel = "", pos = Vector(-4.676, 0.3, -1.53), angle = Angle(0, 0, 0), size = Vector(0.699, 0.699, 0.699), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_kobra"] = { type = "Model", model = "models/cw2/attachments/kobra.mdl", bone = "Plane02", rel = "", pos = Vector(-0.519, -0.371, -1.3), angle = Angle(0, -90, 0), size = Vector(0.5, 0.5, 0.5), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} }, ["md_foregrip"] = { type = "Model", model = "models/wystan/attachments/foregrip1.mdl", bone = "Plane02", rel = "", pos = Vector(-1.9, 0.5, -2.3), angle = Angle(0, 90, 0), size = Vector(0.6, 0.6, 0.6), color = Color(255, 255, 255, 255), surpresslightning = false, material = "", skin = 0, bodygroup = {} } } SWEP.ForeGripHoldPos = { ["Left_Hand"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-1.111, -18.889, -16.667) }, ["Left_L_Arm"] = { scale = Vector(1, 1, 1), pos = Vector(0, 0, 0), angle = Angle(-16.667, 12.222, 72.222) }, ["Left_U_Arm"] = { scale = Vector(1, 1, 1), pos = Vector(-4.259, 1.296, 2.778), angle = Angle(-16.667, 5.556, 3.332) }} SWEP.ACOGAxisAlign = {right = 0, up = 0, forward = 0} SWEP.SchmidtShortDotAxisAlign = {right = 0, up = 0, forward = 0} SWEP.PSO1AxisAlign = {right = 0, up = 0, forward = 90} end SWEP.MuzzleVelocity = 850 -- in meter/s SWEP.LuaViewmodelRecoil = true SWEP.CanRestOnObjects = true SWEP.Attachments = {[3] = {header = "Sight", offset = {450, -400}, atts = {"md_microt1kh","md_kobra","odec3d_cmore_kry","md_fas2_eotech","md_fas2_aimpoint", "md_schmidt_shortdot", "md_uecw_csgo_acog", "md_pso1"}}, [2] = {header = "Barrel", offset = {-50, -450}, atts = {"md_pbs1"}}, [1] = {header = "Handguard", offset = {-400, -150}, atts = {"md_foregrip"}}, ["+reload"] = {header = "Ammo", offset = {-450, 250}, atts = {"am_magnum", "am_matchgrade"}}} SWEP.Animations = {fire = {"shoot3", "shoot2", "shoot1"}, reload = "reload", idle = "idle", draw = "draw"} SWEP.Sounds = { draw = {{time = .2, sound = "AEK.Draw"}}, reload = {[1] = {time = .6, sound = "AEK.Clipout"}, [2] = {time = 1, sound = "AEK.Clipin"}, [3] = {time = 2, sound = "AEK.Boltpull"}}} SWEP.HoldBoltWhileEmpty = false SWEP.DontHoldWhenReloading = true SWEP.LuaVMRecoilAxisMod = {vert = .75, hor = 1.25, roll = .35, forward = .25, pitch = 1.25} SWEP.SpeedDec = 40 SWEP.Slot = 3 SWEP.SlotPos = 0 SWEP.NormalHoldType = "ar2" SWEP.RunHoldType = "passive" SWEP.FireModes = {"auto", "3burst", "semi"} SWEP.Base = "cw_base" SWEP.Category = "CW 2.0 - Khris" SWEP.Author = "Khris" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "" SWEP.FireMoveMod = 1 SWEP.OverallMouseSens = .8 SWEP.ViewModelFOV = 80 SWEP.AimViewModelFOV = 75 SWEP.ViewModelFlip = false SWEP.ViewModel = "models/khrcw2/v_rif_aek97.mdl" SWEP.WorldModel = "models/khrcw2/w_rif_aek97.mdl" SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.Primary.ClipSize = 30 SWEP.Primary.DefaultClip = 30 SWEP.Primary.Automatic = true SWEP.Primary.Ammo = "5.45x39MM" SWEP.FireDelay = 60/800 SWEP.FireSound = "AEK.FIRE" SWEP.FireSoundSuppressed = "AEK.SUPFIRE" SWEP.Recoil = 1 SWEP.HipSpread = 0.050 SWEP.AimSpread = 0.0013 SWEP.VelocitySensitivity = 1 SWEP.MaxSpreadInc = 0.07 SWEP.SpreadPerShot = 0.005 SWEP.SpreadCooldown = 0.15 SWEP.Shots = 1 SWEP.Damage = 34 SWEP.DeployTime = 1 SWEP.ReloadSpeed = 1 SWEP.ReloadTime = 2.7 SWEP.ReloadTime_Empty = 2.7 SWEP.ReloadHalt = 2.7 SWEP.Offset = { Pos = { Up = 1, Right = 0, Forward = 0, }, Ang = { Up = 0, Right = -10, Forward = 180, } } function SWEP:DrawWorldModel( ) local hand, offset, rotate local pl = self:GetOwner() if IsValid( pl ) then local boneIndex = pl:LookupBone( "ValveBiped.Bip01_R_Hand" ) if boneIndex then local pos, ang = pl:GetBonePosition( boneIndex ) pos = pos + ang:Forward() * self.Offset.Pos.Forward + ang:Right() * self.Offset.Pos.Right + ang:Up() * self.Offset.Pos.Up ang:RotateAroundAxis( ang:Up(), self.Offset.Ang.Up) ang:RotateAroundAxis( ang:Right(), self.Offset.Ang.Right ) ang:RotateAroundAxis( ang:Forward(), self.Offset.Ang.Forward ) self:SetRenderOrigin( pos ) self:SetRenderAngles( ang ) self:DrawModel() end else self:SetRenderOrigin( nil ) self:SetRenderAngles( nil ) self:DrawModel() end end SWEP.ReloadHalt_Empty = 2.7
gpl-3.0
LaFamiglia/Illarion-Content
monster/race_11_skeleton/base.lua
5
2965
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local base = require("monster.base.base") local messages = require("base.messages") --Random Messages local msgs = messages.Messages() msgs:addMessage("#me fehlt bei genauerer Betrachtung wohl der Unterkiefer.", "#me is missing its lower jaw on closer inspection.") msgs:addMessage("#me greift nach oben zu seinem eigenen Schädel und verdreht ihn mit einem lauten, knackenden Geräusch.", "#me reaches up, grabs it's own skull and twists, making a loud cracking noise.") msgs:addMessage("#me grinst wie ein Narr.", "#me grins like a fool.") msgs:addMessage("#me hebt seine Waffe in die Höhe und klappert mit den Zähnen.", "#me raises his weapon and rattles with its tooth.") msgs:addMessage("#me kichert still, die Schultern schwanken und knacken.", "#me cackles silently, shoulders heaving and creaking.") msgs:addMessage("#me klappert, die Knochen rasseln.", "#me clatters, bones rattling.") msgs:addMessage("#me klappt seinen Kiefer zu um bösartig zu grinsen.", "#me snaps its jaw shut, grinning wickedly.") msgs:addMessage("#me kriecht qualvoll über den Boden..", "#me shuffles painfully across the floor.") msgs:addMessage("#me macht langsame und mühsame Schritte... Click...clack...click...clack...", "#me takes slow, tedious steps... Click...clack...click...clack...") msgs:addMessage("#me schlurft vorwärts, Gelenke knarren und knacken.", "#me shambles forward, joints clicking and creaking...") msgs:addMessage("#me schwingt eine uralte Waffe, verrostet und verbeult.", "#me brandishes an ancient weapon, rusted and battered.") msgs:addMessage("#me schwingt gewaltsam seine verfallene Waffe.", "#me swings its decayed weapon violently.") msgs:addMessage("#me streckt eine knochige Hand aus.", "#me reaches out a bony hand.") msgs:addMessage("#me taumelt, beinahe zusammenstürzend.", "#me staggers, nearly toppling over.") msgs:addMessage("#mes Kiefer öffnet sich zu einem lautlosen Schrei.", "#me's jaw swivels in a silent scream...") msgs:addMessage("#mes Knochen schlagen klappernd und rasselnd aneinander.", "#me's bones clinks clacking and rattling together.") msgs:addMessage("#mes Kopf hängt herab, leere Augenhöhlen starren geradeaus.", "#me's head lolls around, empty eye sockets staring.") local M = {} function M.generateCallbacks() return base.generateCallbacks(msgs) end return M
agpl-3.0
dismantl/luci-0.12
modules/admin-full/luasrc/model/cbi/admin_system/fstab/swap.lua
84
1922
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local util = require "nixio.util" local devices = {} util.consume((fs.glob("/dev/sd*")), devices) util.consume((fs.glob("/dev/hd*")), devices) util.consume((fs.glob("/dev/scd*")), devices) util.consume((fs.glob("/dev/mmc*")), devices) local size = {} for i, dev in ipairs(devices) do local s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev:sub(6)))) size[dev] = s and math.floor(s / 2048) end m = Map("fstab", translate("Mount Points - Swap Entry")) m.redirect = luci.dispatcher.build_url("admin/system/fstab") if not arg[1] or m.uci:get("fstab", arg[1]) ~= "swap" then luci.http.redirect(m.redirect) return end mount = m:section(NamedSection, arg[1], "swap", translate("Swap Entry")) mount.anonymous = true mount.addremove = false mount:tab("general", translate("General Settings")) mount:tab("advanced", translate("Advanced Settings")) mount:taboption("general", Flag, "enabled", translate("Enable this swap")).rmempty = false o = mount:taboption("general", Value, "device", translate("Device"), translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)")) for i, d in ipairs(devices) do o:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end o = mount:taboption("advanced", Value, "uuid", translate("UUID"), translate("If specified, mount the device by its UUID instead of a fixed device node")) o = mount:taboption("advanced", Value, "label", translate("Label"), translate("If specified, mount the device by the partition label instead of a fixed device node")) return m
apache-2.0
gwx/tome-grayswandir-weaponry
data/objects/2hspears.lua
1
2561
if config.settings.tome.grayswandir_weaponry_spears ~= false then newEntity{ define_as = 'BASE_GREATSPEAR', slot = 'MAINHAND', slot_forbid = 'OFFHAND', type = 'weapon', subtype='greatspear', add_name = ' (#COMBAT#)', display = '/', color=colors.SLATE, image = 'object/generic_greatspear.png', moddable_tile = 'greatspear', encumber = 5, rarity = 7, metallic = true, twohanded = true, exotic = true, ego_bonus_mult = 0.2, combat = { talented = 'spear', accuracy_effect = 'knife', damrange = 1.6, physspeed = 1.2, thrust_range = 1, sound = {'actions/melee', pitch=0.7, vol=1.2}, sound_miss = {'actions/melee', pitch=0.7, vol=1.2}}, desc = [[A heavy spear.]], randart_able = '/data/general/objects/random-artifacts/melee.lua', egos = '/data-grayswandir-weaponry/egos/2hspears.lua', egos_chance = {prefix = resolvers.mbonus(40, 5), suffix = resolvers.mbonus(40, 5),},} newEntity{ base = 'BASE_GREATSPEAR', name = 'iron greatspear', short_name = 'iron', level_range = {1, 10}, require = { stat = { str=11 }, }, cost = 5, material_level = 1, combat = { dam = resolvers.rngavg(13,19), apr = 4, physcrit = 2.5, dammod = {str=1.2},},} newEntity{ base = 'BASE_GREATSPEAR', name = 'steel greatspear', short_name = 'steel', level_range = {10, 20}, require = { stat = { str=16 }, }, cost = 10, material_level = 2, combat = { dam = resolvers.rngavg(20,28), apr = 5, physcrit = 3, dammod = {str=1.2},},} newEntity{ base = 'BASE_GREATSPEAR', name = 'dwarven-steel greatspear', short_name = 'd.steel', level_range = {20, 30}, require = { stat = { str=24 }, }, cost = 15, material_level = 3, combat = { dam = resolvers.rngavg(32,40), apr = 6, physcrit = 3.5, dammod = {str=1.2},},} newEntity{ base = 'BASE_GREATSPEAR', name = 'stralite greatspear', short_name = 'stralite', level_range = {30, 40}, require = { stat = { str=35 }, }, cost = 25, material_level = 4, combat = { dam = resolvers.rngavg(45,52), apr = 8, physcrit = 4.5, dammod = {str=1.2},},} newEntity{ base = 'BASE_GREATSPEAR', name = 'voratun greatspear', short_name = 'voratun', level_range = {40, 50}, require = { stat = { str=48 }, }, cost = 35, material_level = 5, combat = { dam = resolvers.rngavg(58, 66), apr = 10, physcrit = 5, dammod = {str=1.2},},} end
gpl-3.0
bsmr-games/lipsofsuna
data/lipsofsuna/landscape/camera.lua
1
2571
--- Camera for the landscape subgame. -- -- Lips of Suna is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. -- -- @module landscape.camera -- @alias LandscapeCamera local Camera = require("system/camera") local Class = require("system/class") local MathUtils = require("system/math/utils") local Quaternion = require("system/math/quaternion") local Vector = require("system/math/vector") --- Camera for the landscape subgame. -- @type LandscapeCamera local LandscapeCamera = Class("LandscapeCamera", Camera) --- Creates a new landscape camera. -- @param clss LandscapeCamera class. -- @return LandscapeCamera. LandscapeCamera.new = function(clss) local self = Camera.new(clss) self:set_far(1000) self:set_near(0.3) self:set_mode("first-person") self.position = Vector(5000,5000,5000) self.rotation = Quaternion:new_from_dir(-20,-70,-10, 0,1,0) self.turning = 0 self.tilting = 0 self.turn_speed = 0 self.tilt_speed = 0 return self end --- Flies forward or backward. -- @param self Camera. -- @param value Amount of motion. LandscapeCamera.fly = function(self, value) self.movement = 50 * value end --- Flies sideward. -- @param self Camera. -- @param value Amount of motion. LandscapeCamera.strafe = function(self, value) self.strafing = 50 * value end --- Updates the camera transformation. -- @param self Camera. -- @param secs Seconds since the last update. LandscapeCamera.update = function(self, secs) if not Main.landscape then return end -- Update the position. local vel = Vector() if self.lifting then vel = vel + Vector(0, self.lifting, 0) end if self.movement then vel = vel + self.rotation * Vector(0, 0, self.movement) end if self.strafing then vel = vel + self.rotation * Vector(self.strafing, 0, 0) end self.position = self.position + vel * secs self:set_target_position(self.position) -- Update the rotation. if self.turn_speed then self.turning = MathUtils:radian_wrap(self.turning - 0.1 * self.turn_speed) self.turn_speed = 0 end if self.tilt_speed then self.tilting = MathUtils:radian_wrap(self.tilting - 0.1 * self.tilt_speed) self.tilt_speed = 0 end self.rotation = Quaternion:new_from_euler(self.turning, 0, self.tilting) self:set_target_rotation(self.rotation) -- Warp to the destination. Main.client.camera_manager:set_camera_mode("landscape") Camera.update(self, secs) self:warp() end return LandscapeCamera
gpl-3.0
MustaphaTR/OpenRA
mods/ra/maps/allies-05c/allies05c.lua
7
11123
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] if Difficulty == "easy" then TanyaType = "e7" ReinforceCash = 5000 HoldAITime = DateTime.Minutes(3) SpecialCameras = true elseif Difficulty == "normal" then TanyaType = "e7.noautotarget" ReinforceCash = 3500 HoldAITime = DateTime.Minutes(2) SpecialCameras = true else TanyaType = "e7.noautotarget" ReinforceCash = 2250 HoldAITime = DateTime.Minutes(1) + DateTime.Seconds(30) end SpyType = { "spy" } SpyEntryPath = { SpyEntry.Location, SpyLoadout.Location } InsertionTransport = "lst.in" TrukPath = { TrukWaypoint1, TrukWaypoint2, TrukWaypoint3, TrukWaypoint4, TrukWaypoint5, TrukWaypoint6, TrukWaypoint7, TrukWaypoint8, TrukWaypoint9, TrukWaypoint10 } ExtractionHeliType = "tran" ExtractionPath = { ExtractionEntry.Location, ExtractionLZ.Location } HeliReinforcements = { "medi", "mech", "mech" } GreeceReinforcements1 = { { types = { "2tnk", "2tnk", "2tnk", "2tnk", "2tnk" }, entry = { SpyEntry.Location, LSTLanding1.Location } }, { types = { "e3", "e3", "e3", "e3", "e1" }, entry = { LSTEntry2.Location, LSTLanding2.Location } } } GreeceReinforcements2 = { { types = { "arty", "arty", "jeep", "jeep" }, entry = { SpyEntry.Location, LSTLanding1.Location } }, { types = { "e1", "e1", "e6", "e6", "e6" }, entry = { LSTEntry2.Location, LSTLanding2.Location } } } DogPatrol = { Dog1, Dog2 } RiflePatrol = { RiflePatrol1, RiflePatrol2, RiflePatrol3, RiflePatrol4, RiflePatrol5 } BasePatrol = { BasePatrol1, BasePatrol2, BasePatrol3 } DogPatrolPath = { DogPatrolRally1.Location, SpyCamera2.Location, DogPatrolRally3.Location } RiflePath = { RiflePath1.Location, RiflePath2.Location, RiflePath3.Location } BasePatrolPath = { BasePatrolPath1.Location, BasePatrolPath2.Location, BasePatrolPath3.Location } TanyaVoices = { "tuffguy", "bombit", "laugh", "gotit", "lefty", "keepem" } SpyVoice = "sking" SamSites = { Sam1, Sam2, Sam3, Sam4, Sam5, Sam6 } SendSpy = function() Camera.Position = SpyEntry.CenterPosition Spy = Reinforcements.ReinforceWithTransport(Greece, InsertionTransport, SpyType, SpyEntryPath, { SpyEntryPath[1] })[2][1] Trigger.OnKilled(Spy, function() USSR.MarkCompletedObjective(USSRObj) end) if SpecialCameras then SpyCameraA = Actor.Create("camera", true, { Owner = Greece, Location = SpyCamera1.Location }) SpyCameraB = Actor.Create("camera", true, { Owner = Greece, Location = SpyCamera2.Location }) SpyCameraC = Actor.Create("camera", true, { Owner = Greece, Location = SpyCamera3.Location }) else SpyCameraHard = Actor.Create("camera.small", true, { Owner = Greece, Location = RiflePath1.Location + CVec.New(0, 3) }) end Trigger.AfterDelay(DateTime.Seconds(3), function() Media.DisplayMessage("Commander! You have to disguise me in order to get through the enemy patrols.", "Spy") end) end ActivatePatrols = function() Trigger.AfterDelay(DateTime.Seconds(3), function() GroupPatrol(DogPatrol, DogPatrolPath, DateTime.Seconds(6)) GroupPatrol(RiflePatrol, RiflePath, DateTime.Seconds(7)) GroupPatrol(BasePatrol, BasePatrolPath, DateTime.Seconds(6)) end) end GroupPatrol = function(units, waypoints, delay) local i = 1 local stop = false Utils.Do(units, function(unit) Trigger.OnIdle(unit, function() if stop then return end if unit.Location == waypoints[i] then local bool = Utils.All(units, function(actor) return actor.IsIdle end) if bool then stop = true i = i + 1 if i > #waypoints then i = 1 end Trigger.AfterDelay(delay, function() stop = false end) end else unit.AttackMove(waypoints[i]) end end) end) end SendReinforcements = function() GreeceReinforcementsArrived = true Camera.Position = SpyLoadout.CenterPosition Greece.Cash = Greece.Cash + ReinforceCash Media.PlaySpeechNotification(Greece, "AlliedReinforcementsArrived") Utils.Do(GreeceReinforcements1, function(reinforcements) Reinforcements.ReinforceWithTransport(Greece, InsertionTransport, reinforcements.types, reinforcements.entry, { SpyEntry.Location }) end) Trigger.AfterDelay(DateTime.Seconds(10), function() Media.PlaySpeechNotification(Greece, "AlliedReinforcementsArrived") Utils.Do(GreeceReinforcements2, function(reinforcements) Reinforcements.ReinforceWithTransport(Greece, InsertionTransport, reinforcements.types, reinforcements.entry, { SpyEntry.Location }) end) end) ActivateAI() end ExtractUnits = function(extractionUnit, pos, after) if extractionUnit.IsDead or not extractionUnit.HasPassengers then return end extractionUnit.Move(pos) extractionUnit.Destroy() Trigger.OnRemovedFromWorld(extractionUnit, after) end WarfactoryInfiltrated = function() FollowTruk = true Truk.GrantCondition("hijacked") Truk.Wait(DateTime.Seconds(1)) Utils.Do(TrukPath, function(waypoint) Truk.Move(waypoint.Location) end) if SpecialCameras then Trigger.AfterDelay(DateTime.Seconds(2), function() SpyCameraA.Destroy() SpyCameraB.Destroy() SpyCameraC.Destroy() end) else SpyCameraHard.Destroy() end end MissInfiltrated = function() for i = 0, 5, 1 do local sound = Utils.Random(TanyaVoices) Trigger.AfterDelay(DateTime.Seconds(i), function() Media.PlaySoundNotification(Greece, sound) end) end Prison.Attack(Prison) Trigger.AfterDelay(DateTime.Seconds(6), FreeTanya) end FreeTanya = function() Prison.Stop() Tanya = Actor.Create(TanyaType, true, { Owner = Greece, Location = Prison.Location + CVec.New(1, 1) }) Tanya.Demolish(Prison) Tanya.Move(Tanya.Location + CVec.New(Utils.RandomInteger(-1, 2), 1)) if TanyaType == "e7.noautotarget" then Trigger.AfterDelay(DateTime.Seconds(1), function() Media.DisplayMessage("According to the rules of engagement I need your explicit orders to fire, Commander!", "Tanya") end) end Trigger.OnKilled(Tanya, function() USSR.MarkCompletedObjective(USSRObj) end) if Difficulty == "tough" then KillSams = Greece.AddObjective("Destroy all six SAM Sites that block\nour reinforcements' helicopter.") Greece.MarkCompletedObjective(MainObj) SurviveObj = Greece.AddObjective("Tanya must not die!") Media.PlaySpeechNotification(Greece, "TanyaRescued") else KillSams = Greece.AddObjective("Destroy all six SAM sites that block\nthe extraction helicopter.") Media.PlaySpeechNotification(Greece, "TargetFreed") end if not SpecialCameras and PrisonCamera and PrisonCamera.IsInWorld then PrisonCamera.Destroy() end end InitTriggers = function() Trigger.OnInfiltrated(Warfactory, function() if Greece.IsObjectiveCompleted(InfWarfactory) then return elseif Truk.IsDead then if not Greece.IsObjectiveCompleted(MainObj) then USSR.MarkCompletedObjective(USSRObj) end return end Trigger.ClearAll(Spy) Greece.MarkCompletedObjective(InfWarfactory) WarfactoryInfiltrated() end) Trigger.OnKilled(Truk, function() if not Greece.IsObjectiveCompleted(InfWarfactory) then Greece.MarkFailedObjective(InfWarfactory) elseif FollowTruk then USSR.MarkCompletedObjective(USSRObj) end end) Trigger.OnInfiltrated(Prison, function() if Greece.IsObjectiveCompleted(MainObj) then return end if not Greece.IsObjectiveCompleted(InfWarfactory) then Media.DisplayMessage("Good work! But next time skip the heroics!", "Battlefield Control") Greece.MarkCompletedObjective(InfWarfactory) end if not PrisonCamera then if SpecialCameras then PrisonCamera = Actor.Create("camera", true, { Owner = Greece, Location = SpyJump.Location }) else PrisonCamera = Actor.Create("camera.small", true, { Owner = Greece, Location = Prison.Location + CVec.New(1, 1) }) end end if SpecialCameras and SpyCameraA and not SpyCameraA.IsDead then SpyCameraA.Destroy() SpyCameraB.Destroy() end Trigger.ClearAll(Spy) Trigger.AfterDelay(DateTime.Seconds(2), MissInfiltrated) end) Trigger.OnEnteredFootprint({ SpyJump.Location }, function(a, id) if a == Truk then Trigger.RemoveFootprintTrigger(id) Spy = Actor.Create("spy", true, { Owner = Greece, Location = SpyJump.Location }) Spy.DisguiseAsType("e1", USSR) Spy.Move(SpyWaypoint.Location) Spy.Infiltrate(Prison) Media.PlaySoundNotification(Greece, SpyVoice) FollowTruk = false if SpecialCameras then PrisonCamera = Actor.Create("camera", true, { Owner = Greece, Location = SpyJump.Location }) else PrisonCamera = Actor.Create("camera.small", true, { Owner = Greece, Location = Prison.Location + CVec.New(1, 1) }) end Trigger.OnKilled(Spy, function() USSR.MarkCompletedObjective(USSRObj) end) end end) Trigger.OnEnteredFootprint({ TrukWaypoint10.Location }, function(a, id) if a == Truk then Trigger.RemoveFootprintTrigger(id) Truk.Stop() Truk.Kill() ExplosiveBarrel.Kill() end end) Trigger.OnAllKilled(SamSites, function() Greece.MarkCompletedObjective(KillSams) local flare = Actor.Create("flare", true, { Owner = Greece, Location = ExtractionPath[2] + CVec.New(0, -1) }) Trigger.AfterDelay(DateTime.Seconds(7), flare.Destroy) Media.PlaySpeechNotification(Greece, "SignalFlare") ExtractionHeli = Reinforcements.ReinforceWithTransport(Greece, ExtractionHeliType, nil, ExtractionPath)[1] local exitPos = CPos.New(ExtractionPath[1].X, ExtractionPath[2].Y) Trigger.OnKilled(ExtractionHeli, function() USSR.MarkCompletedObjective(USSRObj) end) Trigger.OnRemovedFromWorld(Tanya, function() ExtractUnits(ExtractionHeli, exitPos, function() Media.PlaySpeechNotification(Greece, "TanyaRescued") Greece.MarkCompletedObjective(MainObj) Trigger.AfterDelay(DateTime.Seconds(2), function() SendReinforcements() end) if PrisonCamera and PrisonCamera.IsInWorld then PrisonCamera.Destroy() end end) end) end) end Tick = function() if FollowTruk and not Truk.IsDead then Camera.Position = Truk.CenterPosition end if USSR.HasNoRequiredUnits() then if not Greece.IsObjectiveCompleted(KillAll) and Difficulty == "tough" then SendWaterExtraction() end Greece.MarkCompletedObjective(KillAll) end if GreeceReinforcementsArrived and Greece.HasNoRequiredUnits() then USSR.MarkCompletedObjective(USSRObj) end if USSR.Resources >= USSR.ResourceCapacity * 0.75 then USSR.Cash = USSR.Cash + USSR.Resources - USSR.ResourceCapacity * 0.25 USSR.Resources = USSR.ResourceCapacity * 0.25 end end WorldLoaded = function() Greece = Player.GetPlayer("Greece") USSR = Player.GetPlayer("USSR") InitObjectives(Greece) USSRObj = USSR.AddObjective("Deny the Allies.") MainObj = Greece.AddObjective("Rescue Tanya.") KillAll = Greece.AddObjective("Eliminate all Soviet units in this area.") InfWarfactory = Greece.AddObjective("Infiltrate the Soviet warfactory.", "Secondary", false) InitTriggers() SendSpy() Trigger.AfterDelay(DateTime.Seconds(3), ActivatePatrols) end
gpl-3.0
dpalacio/awesome-randr-zaphod
luadoc/dbus.lua
3
1563
--- awesome D-Bus API -- @author Julien Danjou &lt;julien@danjou.info&gt; -- @copyright 2008-2009 Julien Danjou module("dbus") --- Register a D-Bus name to receive message from. -- @param bus A string indicating if we are using system or session bus. -- @param name A string with the name of the D-Bus name to register. -- @return True if everything worked fine, false otherwise. -- @name request_name -- @class function --- Release a D-Bus name. -- @param bus A string indicating if we are using system or session bus. -- @param name A string with the name of the D-Bus name to unregister. -- @return True if everything worked fine, false otherwise. -- @name release_name -- @class function --- Add a match rule to match messages going through the message bus. -- @param bus A string indicating if we are using system or session bus. -- @param name A string with the name of the match rule. -- @name add_match -- @class function --- Remove a previously added match rule "by value" -- (the most recently-added identical rule gets removed). -- @param bus A string indicating if we are using system or session bus. -- @param name A string with the name of the match rule. -- @name remove_match -- @class function --- Add a signal receiver on the D-Bus. -- @param interface A string with the interface name. -- @param func The function to call. -- @name add_signal -- @class function --- Remove a signal receiver on the D-Bus. -- @param interface A string with the interface name. -- @param func The function to call. -- @name remove_signal -- @class function
gpl-2.0
koeppea/ettercap
src/lua/share/third-party/stdlib/src/lcs.lua
12
1584
--- Longest Common Subsequence algorithm. -- After pseudo-code in <a -- href="http://www.ics.uci.edu/~eppstein/161/960229.html">lecture -- notes</a> by <a href="mailto:eppstein@ics.uci.edu">David Eppstein</a>. -- Find common subsequences. -- @param a first sequence -- @param b second sequence -- @return list of common subsequences -- @return the length of a -- @return the length of b local function commonSubseqs (a, b) local l, m, n = {}, #a, #b for i = m + 1, 1, -1 do l[i] = {} for j = n + 1, 1, -1 do if i > m or j > n then l[i][j] = 0 elseif a[i] == b[j] then l[i][j] = 1 + l[i + 1][j + 1] else l[i][j] = math.max (l[i + 1][j], l[i][j + 1]) end end end return l, m, n end --- Find the longest common subsequence of two sequences. -- The sequence objects must have an <code>__append</code> metamethod. -- This is provided by <code>string_ext</code> for strings, and by -- <code>list</code> for lists. -- @param a first sequence -- @param b second sequence -- @param s an empty sequence of the same type, to hold the result -- @return the LCS of a and b local function longestCommonSubseq (a, b, s) local l, m, n = commonSubseqs (a, b) local i, j = 1, 1 local f = getmetatable (s).__append while i <= m and j <= n do if a[i] == b[j] then s = f (s, a[i]) i = i + 1 j = j + 1 elseif l[i + 1][j] >= l[i][j + 1] then i = i + 1 else j = j + 1 end end return s end -- Public interface local M = { longestCommonSubseq = longestCommonSubseq, } return M
gpl-2.0
vanzomerenc/misc-lua
functional/bind.lua
1
1224
---@module bind -- @author Christopher VanZomeren -- @copyright (c) 2014 Christopher VanZomeren assert(..., 'Do not use as main file; use require from different file') local _id = select(2, ...) or ... local error = error local select = select local type = type local require = require 'relative_require' (...) local memoize = require('.memoize') local _ENV = {} if setfenv then setfenv(1, _ENV) end local function bind_at_least_one(f, x, ...) local function f_x(...) return f(x, ...) end if select('#', ...) == 0 then return f_x else return bind_at_least_one(f_x, ...) end end bind_at_least_one = memoize(bind_at_least_one, 'allowgc') local function bind_n(n, f, ...) if select('#', ...) < n then return bind_at_least_one(bind_n, n, f, ...) else return bind_at_least_one(f, ...) end end local function bind(fst, ...) if fst == nil then return bind elseif select('#', ...) == 0 then return bind_at_least_one(bind, fst) elseif type(fst) == 'function' then return bind_at_least_one(fst, ...) elseif type(fst) == 'number' then if fst > 0 then return bind_n(fst, ...) else return select(1, ...) end else error('attempt to bind arguments to non-callable object', 2) end end return bind
bsd-2-clause
mohsen9hard/saba
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
snabbnfv-goodies/snabbswitch
lib/ljsyscall/test/bsd.lua
18
16048
-- General BSD tests local function init(S) local helpers = require "syscall.helpers" local types = S.types local c = S.c local abi = S.abi local bit = require "syscall.bit" local ffi = require "ffi" local t, pt, s = types.t, types.pt, types.s local assert = helpers.assert local function fork_assert(cond, err, ...) -- if we have forked we need to fail in main thread not fork if not cond then print(tostring(err)) print(debug.traceback()) S.exit("failure") end if cond == true then return ... end return cond, ... end local function assert_equal(...) collectgarbage("collect") -- force gc, to test for bugs return assert_equals(...) end local teststring = "this is a test string" local size = 512 local buf = t.buffer(size) local tmpfile = "XXXXYYYYZZZ4521" .. S.getpid() local tmpfile2 = "./666666DDDDDFFFF" .. S.getpid() local tmpfile3 = "MMMMMTTTTGGG" .. S.getpid() local longfile = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890" .. S.getpid() local efile = "./tmpexXXYYY" .. S.getpid() .. ".sh" local largeval = math.pow(2, 33) -- larger than 2^32 for testing local mqname = "ljsyscallXXYYZZ" .. S.getpid() local clean = function() S.rmdir(tmpfile) S.unlink(tmpfile) S.unlink(tmpfile2) S.unlink(tmpfile3) S.unlink(longfile) S.unlink(efile) end local test = {} test.bsd_misc = { test_sysctl_all = function() local all, err = S.sysctl() assert(all and type(all) == "table", "expect a table from all sysctls got " .. type(all)) end, } test.bsd_ids = { test_issetugid = function() if not S.issetugid then error "skipped" end local res = assert(S.issetugid()) assert(res == 0 or res == 1) -- some tests call setuid so might be tainted end, } test.filesystem_bsd = { test_revoke = function() local fd = assert(S.posix_openpt("rdwr, noctty")) assert(fd:grantpt()) assert(fd:unlockpt()) local pts_name = assert(fd:ptsname()) local pts = assert(S.open(pts_name, "rdwr, noctty")) assert(S.revoke(pts_name)) local n, err = pts:read() if n then -- correct behaviour according to man page assert_equal(#n, 0) -- read returns EOF after revoke else -- FreeBSD is NXIO Filed http://www.freebsd.org/cgi/query-pr.cgi?pr=188952 -- OSX is EIO assert(not n and (err.IO or err.NXIO)) end local n, err = pts:write("test") -- write fails after revoke assert(not n and (err.IO or err.NXIO), "access should be revoked") assert(pts:close()) -- close succeeds after revoke assert(fd:close()) end, test_chflags = function() local fd = assert(S.creat(tmpfile, "RWXU")) assert(fd:write("append")) assert(S.chflags(tmpfile, "uf_append")) assert(fd:write("append")) assert(fd:seek(0, "set")) local n, err = fd:write("not append") if not (S.__rump or abi.xen) then assert(err and err.PERM, "non append write should fail") end -- TODO I think this is due to tmpfs mount?? assert(S.chflags(tmpfile)) -- clear flags assert(S.unlink(tmpfile)) assert(fd:close()) end, test_lchflags = function() if not S.lchflags then error "skipped" end local fd = assert(S.creat(tmpfile, "RWXU")) assert(fd:write("append")) assert(S.lchflags(tmpfile, "uf_append")) assert(fd:write("append")) assert(fd:seek(0, "set")) local n, err = fd:write("not append") if not (S.__rump or abi.xen) then assert(err and err.PERM, "non append write should fail") end -- TODO I think this is due to tmpfs mount?? assert(S.lchflags(tmpfile)) -- clear flags assert(S.unlink(tmpfile)) assert(fd:close()) end, test_fchflags = function() local fd = assert(S.creat(tmpfile, "RWXU")) assert(fd:write("append")) assert(fd:chflags("uf_append")) assert(fd:write("append")) assert(fd:seek(0, "set")) local n, err = fd:write("not append") if not (S.__rump or abi.xen) then assert(err and err.PERM, "non append write should fail") end -- TODO I think this is due to tmpfs mount?? assert(fd:chflags()) -- clear flags assert(S.unlink(tmpfile)) assert(fd:close()) end, test_chflagsat = function() if not S.chflagsat then error "skipped" end local fd = assert(S.creat(tmpfile, "RWXU")) assert(fd:write("append")) assert(S.chflagsat("fdcwd", tmpfile, "uf_append", "symlink_nofollow")) assert(fd:write("append")) assert(fd:seek(0, "set")) local n, err = fd:write("not append") assert(err and err.PERM, "non append write should fail") assert(S.chflagsat("fdcwd", tmpfile)) -- clear flags assert(S.unlink(tmpfile)) assert(fd:close()) end, test_lchmod = function() if not S.lchmod then error "skipped" end local fd = assert(S.creat(tmpfile, "RWXU")) assert(S.lchmod(tmpfile, "RUSR, WUSR")) assert(S.access(tmpfile, "rw")) assert(S.unlink(tmpfile)) assert(fd:close()) end, test_utimensat = function() -- BSD utimensat as same specification as Linux, but some functionality missing, so test simpler if not S.utimensat then error "skipped" end local fd = assert(S.creat(tmpfile, "RWXU")) local dfd = assert(S.open(".")) assert(S.utimensat(nil, tmpfile)) local st1 = fd:stat() assert(S.utimensat("fdcwd", tmpfile, {"omit", "omit"})) local st2 = fd:stat() assert(st1.mtime == st2.mtime, "mtime unchanged") -- cannot test atime as stat touches it assert(S.unlink(tmpfile)) assert(fd:close()) assert(dfd:close()) end, } test.kqueue = { test_kqueue_vnode = function() local kfd = assert(S.kqueue()) local fd = assert(S.creat(tmpfile, "rwxu")) local kevs = t.kevents{{fd = fd, filter = "vnode", flags = "add, enable, clear", fflags = "delete, write, extend, attrib, link, rename, revoke"}} assert(kfd:kevent(kevs, nil)) local _, _, n = assert(kfd:kevent(nil, kevs, 0)) assert_equal(n, 0) -- no events yet assert(S.unlink(tmpfile)) local count = 0 for k, v in assert(kfd:kevent(nil, kevs, 1)) do assert(v.DELETE, "expect delete event") count = count + 1 end assert_equal(count, 1) assert(fd:write("something")) local count = 0 for k, v in assert(kfd:kevent(nil, kevs, 1)) do assert(v.WRITE, "expect write event") assert(v.EXTEND, "expect extend event") count = count + 1 end assert_equal(count, 1) assert(fd:close()) assert(kfd:close()) end, test_kqueue_read = function() local kfd = assert(S.kqueue()) local p1, p2 = assert(S.pipe()) local kevs = t.kevents{{fd = p1, filter = "read", flags = "add"}} assert(kfd:kevent(kevs, nil)) local a, b, n = assert(kfd:kevent(nil, kevs, 0)) assert_equal(n, 0) -- no events yet local str = "test" p2:write(str) local count = 0 for k, v in assert(kfd:kevent(nil, kevs, 0)) do assert_equal(v.size, #str) -- size will be amount available to read count = count + 1 end assert_equal(count, 1) -- 1 event readable now local r, err = p1:read() local _, _, n = assert(kfd:kevent(nil, kevs, 0)) assert_equal(n, 0) -- no events any more assert(p2:close()) local count = 0 for k, v in assert(kfd:kevent(nil, kevs, 0)) do assert(v.EOF, "expect EOF event") count = count + 1 end assert_equal(count, 1) assert(p1:close()) assert(kfd:close()) end, test_kqueue_write = function() local kfd = assert(S.kqueue()) local p1, p2 = assert(S.pipe()) local kevs = t.kevents{{fd = p2, filter = "write", flags = "add"}} assert(kfd:kevent(kevs, nil)) local count = 0 for k, v in assert(kfd:kevent(nil, kevs, 0)) do assert(v.size > 0) -- size will be amount free in buffer count = count + 1 end assert_equal(count, 1) -- one event assert(p1:close()) -- close read end count = 0 for k, v in assert(kfd:kevent(nil, kevs, 0)) do assert(v.EOF, "expect EOF event") count = count + 1 end assert_equal(count, 1) assert(p2:close()) assert(kfd:close()) end, test_kqueue_timer = function() local kfd = assert(S.kqueue()) local kevs = t.kevents{{ident = 0, filter = "timer", flags = "add, oneshot", data = 10}} assert(kfd:kevent(kevs, nil)) local count = 0 for k, v in assert(kfd:kevent(nil, kevs)) do assert_equal(v.size, 1) -- count of expiries is 1 as oneshot count = count + 1 end assert_equal(count, 1) -- will have expired by now assert(kfd:close()) end, } test.bsd_extattr = { teardown = clean, test_extattr_empty_fd = function() if not S.extattr_get_fd then error "skipped" end local fd = assert(S.creat(tmpfile, "rwxu")) assert(S.unlink(tmpfile)) local n, err = fd:extattr_get("user", "myattr", false) -- false does raw call with no buffer to return length if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr assert(not n and err.NOATTR) assert(fd:close()) end, test_extattr_getsetdel_fd = function() if not S.extattr_get_fd then error "skipped" end local fd = assert(S.creat(tmpfile, "rwxu")) assert(S.unlink(tmpfile)) local n, err = fd:extattr_get("user", "myattr", false) -- false does raw call with no buffer to return length if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr assert(not n and err.NOATTR) local n, err = fd:extattr_set("user", "myattr", "myvalue") if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support setting extattr assert(n, err) assert_equal(n, #"myvalue") local str = assert(fd:extattr_get("user", "myattr")) assert_equal(str, "myvalue") local ok = assert(fd:extattr_delete("user", "myattr")) local str, err = fd:extattr_get("user", "myattr") assert(not str and err.NOATTR) assert(fd:close()) end, test_extattr_getsetdel_file = function() if not S.extattr_get_fd then error "skipped" end local fd = assert(S.creat(tmpfile, "rwxu")) assert(fd:close()) local n, err = S.extattr_get_file(tmpfile, "user", "myattr", false) -- false does raw call with no buffer to return length if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr assert(not n and err.NOATTR) local n, err = S.extattr_set_file(tmpfile, "user", "myattr", "myvalue") if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support setting extattr assert(n, err) assert_equal(n, #"myvalue") local str = assert(S.extattr_get_file(tmpfile, "user", "myattr")) assert_equal(str, "myvalue") local ok = assert(S.extattr_delete_file(tmpfile, "user", "myattr")) local str, err = S.extattr_get_file(tmpfile, "user", "myattr") assert(not str and err.NOATTR) assert(S.unlink(tmpfile)) end, test_extattr_getsetdel_link = function() if not S.extattr_get_fd then error "skipped" end assert(S.symlink(tmpfile2, tmpfile)) local n, err = S.extattr_get_link(tmpfile, "user", "myattr", false) -- false does raw call with no buffer to return length if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr assert(not n and err.NOATTR) local n, err = S.extattr_set_link(tmpfile, "user", "myattr", "myvalue") if not n and err.OPNOTSUPP then error "skipped" end -- fs does not support setting extattr assert(n, err) assert_equal(n, #"myvalue") local str = assert(S.extattr_get_link(tmpfile, "user", "myattr")) assert_equal(str, "myvalue") local ok = assert(S.extattr_delete_link(tmpfile, "user", "myattr")) local str, err = S.extattr_get_link(tmpfile, "user", "myattr") assert(not str and err.NOATTR) assert(S.unlink(tmpfile)) end, test_extattr_list_fd = function() if not S.extattr_list_fd then error "skipped" end local fd = assert(S.creat(tmpfile, "rwxu")) assert(S.unlink(tmpfile)) local attrs, err = fd:extattr_list("user") if not attrs and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr assert(attrs, err) assert_equal(#attrs, 0) assert(fd:extattr_set("user", "myattr", "myvalue")) local attrs = assert(fd:extattr_list("user")) assert_equal(#attrs, 1) assert_equal(attrs[1], "myattr") assert(fd:extattr_set("user", "newattr", "newvalue")) local attrs = assert(fd:extattr_list("user")) assert_equal(#attrs, 2) assert((attrs[1] == "myattr" and attrs[2] == "newattr") or (attrs[2] == "myattr" and attrs[1] == "newattr")) assert(fd:close()) end, test_extattr_list_file = function() if not S.extattr_list_file then error "skipped" end local fd = assert(S.creat(tmpfile, "rwxu")) local attrs, err = S.extattr_list_file(tmpfile, "user") if not attrs and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr assert(attrs, err) assert_equal(#attrs, 0) assert(S.extattr_set_file(tmpfile, "user", "myattr", "myvalue")) local attrs = assert(S.extattr_list_file(tmpfile, "user")) assert_equal(#attrs, 1) assert_equal(attrs[1], "myattr") assert(S.extattr_set_file(tmpfile, "user", "newattr", "newvalue")) local attrs = assert(S.extattr_list_file(tmpfile, "user")) assert_equal(#attrs, 2) assert((attrs[1] == "myattr" and attrs[2] == "newattr") or (attrs[2] == "myattr" and attrs[1] == "newattr")) assert(S.unlink(tmpfile)) end, test_extattr_list_link = function() if not S.extattr_list_file then error "skipped" end assert(S.symlink(tmpfile2, tmpfile)) local attrs, err = S.extattr_list_link(tmpfile, "user") if not attrs and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr assert(attrs, err) assert_equal(#attrs, 0) assert(S.extattr_set_link(tmpfile, "user", "myattr", "myvalue")) local attrs = assert(S.extattr_list_link(tmpfile, "user")) assert_equal(#attrs, 1) assert_equal(attrs[1], "myattr") assert(S.extattr_set_link(tmpfile, "user", "newattr", "newvalue")) local attrs = assert(S.extattr_list_link(tmpfile, "user")) assert_equal(#attrs, 2) assert((attrs[1] == "myattr" and attrs[2] == "newattr") or (attrs[2] == "myattr" and attrs[1] == "newattr")) assert(S.unlink(tmpfile)) end, test_extattr_list_long = function() if not S.extattr_list_fd then error "skipped" end local fd = assert(S.creat(tmpfile, "rwxu")) assert(S.unlink(tmpfile)) local attrs, err = fd:extattr_list("user") if not attrs and err.OPNOTSUPP then error "skipped" end -- fs does not support extattr assert(attrs, err) assert_equal(#attrs, 0) local count = 100 for i = 1, count do assert(fd:extattr_set("user", "myattr" .. i, "myvalue")) end local attrs = assert(fd:extattr_list("user")) assert_equal(#attrs, count) assert(fd:close()) end, } -- skip as no processes in rump if not S.__rump then test.kqueue.test_kqueue_proc = function() local pid = assert(S.fork()) if pid == 0 then -- child S.pause() S.exit() else -- parent local kfd = assert(S.kqueue()) local kevs = t.kevents{{ident = pid, filter = "proc", flags = "add", fflags = "exit, fork, exec"}} assert(kfd:kevent(kevs, nil)) assert(S.kill(pid, "term")) local count = 0 for k, v in assert(kfd:kevent(nil, kevs, 1)) do assert(v.EXIT) count = count + 1 end assert_equal(count, 1) assert(kfd:close()) assert(S.waitpid(pid)) end end test.kqueue.test_kqueue_signal = function() assert(S.signal("alrm", "ign")) local kfd = assert(S.kqueue()) local kevs = t.kevents{{signal = "alrm", filter = "signal", flags = "add"}} assert(kfd:kevent(kevs, nil)) assert(S.kill(0, "alrm")) assert(S.kill(0, "alrm")) local count = 0 for k, v in assert(kfd:kevent(nil, kevs, 1)) do assert_equal(v.data, 2) -- event happened twice count = count + 1 end assert_equal(count, 1) assert(S.signal("alrm", "dfl")) end end return test end return {init = init}
apache-2.0
adminomega/exterme-orginal
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
Ali-2h/wwefucker
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
sobrinho/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
github1380/active-bot
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
alivilteram/seedteam
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
chelog/brawl
gamemodes/brawl/gamemode/modules/base/client/vgui/sidemenuscroller.lua
1
2811
local PANEL = {} function PANEL:Init() self.Panels = {} self.OffsetX = 0 self.FrameTime = 0 self.pnlCanvas = vgui.Create( "DDragBase", self ) self.pnlCanvas:SetDropPos( "6" ) self.pnlCanvas:SetUseLiveDrag( false ) self.pnlCanvas.OnModified = function() self:OnDragModified() end self.pnlCanvas.UpdateDropTarget = function( Canvas, drop, pnl ) if ( !self:GetShowDropTargets() ) then return end DDragBase.UpdateDropTarget( Canvas, drop, pnl ) end self.pnlCanvas.OnChildAdded = function( Canvas, child ) local dn = Canvas:GetDnD() if ( dn ) then child:Droppable( dn ) child.OnDrop = function() local x, y = Canvas:LocalCursorPos() local closest, id = self.pnlCanvas:GetClosestChild( x, Canvas:GetTall() / 2 ), 0 for k, v in pairs( self.Panels ) do if ( v == closest ) then id = k break end end table.RemoveByValue( self.Panels, child ) table.insert( self.Panels, id, child ) self:InvalidateLayout() return child end end end self:SetOverlap( 0 ) end function PANEL:OnMouseWheeled( dlta ) self.OffsetX = self.OffsetX + dlta * -30 self:InvalidateLayout( true ) return true end function PANEL:Think() -- Hmm.. This needs to really just be done in one place -- and made available to everyone. local FrameRate = VGUIFrameTime() - self.FrameTime self.FrameTime = VGUIFrameTime() if ( self.btnRight:IsDown() ) then self.OffsetX = self.OffsetX + (500 * FrameRate) self:InvalidateLayout( true ) end if ( self.btnLeft:IsDown() ) then self.OffsetX = self.OffsetX - (500 * FrameRate) self:InvalidateLayout( true ) end if ( dragndrop.IsDragging() ) then local x, y = self:LocalCursorPos() if ( x < 30 ) then self.OffsetX = self.OffsetX - (350 * FrameRate) elseif ( x > self:GetWide() - 30 ) then self.OffsetX = self.OffsetX + (350 * FrameRate) end self:InvalidateLayout( true ) end end function PANEL:PerformLayout() local w, h = self:GetSize() self.pnlCanvas:SetWide( w ) local y = 0 for k, v in pairs( self.Panels ) do v:SetPos( 0, y ) v:SetWide( w ) v:ApplySchemeSettings() y = y + v:GetTall() - self.m_iOverlap end self.pnlCanvas:SetTall( y + self.m_iOverlap ) if ( w < self.pnlCanvas:GetWide() ) then self.OffsetX = math.Clamp( self.OffsetX, 0, self.pnlCanvas:GetWide() - self:GetWide() ) else self.OffsetX = 0 end self.pnlCanvas.x = self.OffsetX * -1 self.btnLeft:SetSize( 15, 15 ) self.btnLeft:AlignLeft( 4 ) self.btnLeft:AlignBottom( 5 ) self.btnRight:SetSize( 15, 15 ) self.btnRight:AlignRight( 4 ) self.btnRight:AlignBottom( 5 ) self.btnLeft:SetVisible( self.pnlCanvas.x < 0 ) self.btnRight:SetVisible( self.pnlCanvas.x + self.pnlCanvas:GetWide() > self:GetWide() ) end vgui.Register( "SideMenuScroller", PANEL, "DHorizontalScroller" )
gpl-3.0
soundsrc/premake-core
modules/vstudio/vs2010.lua
5
6057
-- -- vs2010.lua -- Add support for the Visual Studio 2010 project formats. -- Copyright (c) Jason Perkins and the Premake project -- local p = premake p.vstudio.vs2010 = {} local vs2010 = p.vstudio.vs2010 local vstudio = p.vstudio local project = p.project local tree = p.tree --- -- Map Premake tokens to the corresponding Visual Studio variables. --- vs2010.pathVars = { ["cfg.objdir"] = { absolute = true, token = "$(IntDir)" }, ["prj.location"] = { absolute = true, token = "$(ProjectDir)" }, ["prj.name"] = { absolute = false, token = "$(ProjectName)" }, ["sln.location"] = { absolute = true, token = "$(SolutionDir)" }, ["sln.name"] = { absolute = false, token = "$(SolutionName)" }, ["wks.location"] = { absolute = true, token = "$(SolutionDir)" }, ["wks.name"] = { absolute = false, token = "$(SolutionName)" }, ["cfg.buildtarget.directory"] = { absolute = false, token = "$(TargetDir)" }, ["cfg.buildtarget.name"] = { absolute = false, token = "$(TargetFileName)" }, ["cfg.buildtarget.basename"] = { absolute = false, token = "$(TargetName)" }, ["file.basename"] = { absolute = false, token = "%(Filename)" }, ["file.abspath"] = { absolute = true, token = "%(FullPath)" }, ["file.relpath"] = { absolute = false, token = "%(Identity)" }, ["file.path"] = { absolute = false, token = "%(Identity)" }, ["file.directory"] = { absolute = true, token = "%(RootDir)%(Directory)" }, ["file.reldirectory"] = { absolute = false, token = "%(RelativeDir)" }, ["file.extension"] = { absolute = false, token = "%(Extension)" }, ["file.name"] = { absolute = false, token = "%(Filename)%(Extension)" }, } --- -- Identify the type of project being exported and hand it off -- the right generator. --- function vs2010.generateProject(prj) p.eol("\r\n") p.indent(" ") p.escaper(vs2010.esc) if p.project.iscsharp(prj) then p.generate(prj, ".csproj", vstudio.cs2005.generate) -- Skip generation of empty user files local user = p.capture(function() vstudio.cs2005.generateUser(prj) end) if #user > 0 then p.generate(prj, ".csproj.user", function() p.outln(user) end) end elseif p.project.isfsharp(prj) then p.generate(prj, ".fsproj", vstudio.fs2005.generate) -- Skip generation of empty user files local user = p.capture(function() vstudio.fs2005.generateUser(prj) end) if #user > 0 then p.generate(prj, ".fsproj.user", function() p.outln(user) end) end elseif p.project.isc(prj) or p.project.iscpp(prj) then local projFileModified = p.generate(prj, ".vcxproj", vstudio.vc2010.generate) -- Skip generation of empty user files local user = p.capture(function() vstudio.vc2010.generateUser(prj) end) if #user > 0 then p.generate(prj, ".vcxproj.user", function() p.outln(user) end) end -- Only generate a filters file if the source tree actually has subfolders if tree.hasbranches(project.getsourcetree(prj)) then if p.generate(prj, ".vcxproj.filters", vstudio.vc2010.generateFilters) == true and projFileModified == false then -- vs workaround for issue where if only the .filters file is modified, VS doesn't automaticly trigger a reload p.touch(prj, ".vcxproj") end end end if not vstudio.nuget2010.supportsPackageReferences(prj) then -- Skip generation of empty packages.config files local packages = p.capture(function() vstudio.nuget2010.generatePackagesConfig(prj) end) if #packages > 0 then p.generate(prj, "packages.config", function() p.outln(packages) end) end -- Skip generation of empty NuGet.Config files local config = p.capture(function() vstudio.nuget2010.generateNuGetConfig(prj) end) if #config > 0 then p.generate(prj, "NuGet.Config", function() p.outln(config) end) end end end --- -- Generate the .props, .targets, and .xml files for custom rules. --- function vs2010.generateRule(rule) p.eol("\r\n") p.indent(" ") p.escaper(vs2010.esc) p.generate(rule, ".props", vs2010.rules.props.generate) p.generate(rule, ".targets", vs2010.rules.targets.generate) p.generate(rule, ".xml", vs2010.rules.xml.generate) end -- -- The VS 2010 standard for XML escaping in generated project files. -- function vs2010.esc(value) value = value:gsub('&', "&amp;") value = value:gsub('<', "&lt;") value = value:gsub('>', "&gt;") return value end --- -- Define the Visual Studio 2010 export action. --- newaction { -- Metadata for the command line and help system trigger = "vs2010", shortname = "Visual Studio 2010", description = "Generate Visual Studio 2010 project files", -- Visual Studio always uses Windows path and naming conventions targetos = "windows", toolset = "msc-v100", -- The capabilities of this action valid_kinds = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", "Makefile", "None", "Utility" }, valid_languages = { "C", "C++", "C#", "F#" }, valid_tools = { cc = { "msc" }, dotnet = { "msnet" }, }, -- Workspace and project generation logic onWorkspace = function(wks) vstudio.vs2005.generateSolution(wks) end, onProject = function(prj) vstudio.vs2010.generateProject(prj) end, onRule = function(rule) vstudio.vs2010.generateRule(rule) end, onCleanWorkspace = function(wks) vstudio.cleanSolution(wks) end, onCleanProject = function(prj) vstudio.cleanProject(prj) end, onCleanTarget = function(prj) vstudio.cleanTarget(prj) end, pathVars = vs2010.pathVars, -- This stuff is specific to the Visual Studio exporters vstudio = { csprojSchemaVersion = "2.0", productVersion = "8.0.30703", solutionVersion = "11", versionName = "2010", targetFramework = "4.0", toolsVersion = "4.0", } }
bsd-3-clause
qq779089973/ramod
luci/modules/admin-full/luasrc/model/cbi/admin_network/iface_add.lua
79
3091
--[[ LuCI - Lua Configuration Interface Copyright 2009-2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local nw = require "luci.model.network".init() local fw = require "luci.model.firewall".init() local utl = require "luci.util" local uci = require "luci.model.uci".cursor() m = SimpleForm("network", translate("Create Interface")) m.redirect = luci.dispatcher.build_url("admin/network/network") m.reset = false newnet = m:field(Value, "_netname", translate("Name of the new interface"), translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " .. "<code>0-9</code> and <code>_</code>" )) newnet:depends("_attach", "") newnet.default = arg[1] and "net_" .. arg[1]:gsub("[^%w_]+", "_") newnet.datatype = "uciname" newproto = m:field(ListValue, "_netproto", translate("Protocol of the new interface")) netbridge = m:field(Flag, "_bridge", translate("Create a bridge over multiple interfaces")) sifname = m:field(Value, "_ifname", translate("Cover the following interface")) sifname.widget = "radio" sifname.template = "cbi/network_ifacelist" sifname.nobridges = true mifname = m:field(Value, "_ifnames", translate("Cover the following interfaces")) mifname.widget = "checkbox" mifname.template = "cbi/network_ifacelist" mifname.nobridges = true local _, p for _, p in ipairs(nw:get_protocols()) do if p:is_installed() then newproto:value(p:proto(), p:get_i18n()) if not p:is_virtual() then netbridge:depends("_netproto", p:proto()) end if not p:is_floating() then sifname:depends({ _bridge = "", _netproto = p:proto()}) mifname:depends({ _bridge = "1", _netproto = p:proto()}) end end end function newproto.validate(self, value, section) local name = newnet:formvalue(section) if not name or #name == 0 then newnet:add_error(section, translate("No network name specified")) elseif m:get(name) then newnet:add_error(section, translate("The given network name is not unique")) end local proto = nw:get_protocol(value) if proto and not proto:is_floating() then local br = (netbridge:formvalue(section) == "1") local ifn = br and mifname:formvalue(section) or sifname:formvalue(section) for ifn in utl.imatch(ifn) do return value end return nil, translate("The selected protocol needs a device assigned") end return value end function newproto.write(self, section, value) local name = newnet:formvalue(section) if name and #name > 0 then local br = (netbridge:formvalue(section) == "1") and "bridge" or nil local net = nw:add_network(name, { proto = value, type = br }) if net then local ifn for ifn in utl.imatch( br and mifname:formvalue(section) or sifname:formvalue(section) ) do net:add_interface(ifn) end nw:save("network") nw:save("wireless") end luci.http.redirect(luci.dispatcher.build_url("admin/network/network", name)) end end return m
mit
Dantevg/RedWeb
src/Server.lua
1
13934
--[[ RedWeb server by DvgCraft Wireless modem required VERSION 1.0 LONG V 0.9.12.2 DATE 29-04-2016 ]]-- -- Variables local arg = {...} local running = true local serverPath = "/server.cfg" local usage = "Usage:\nRedWebServer" local c = { bg = colors.white, txt = colors.black, sBg = term.isColor() and colors.pink or (_CC_VERSION and colors.lightGray or colors.black), sTxt = term.isColor() and colors.lightGray or (_CC_VERSION and colors.lightGray or colors.black), btnBg = term.isColor() and colors.red or colors.black, btnTxt = colors.white, } local headeropt = { bgcolor = term.isColor() and colors.red or colors.black, size = 3, btns = { top = { "Servers", "Log", "Register" }, bgcolor = term.isColor() and colors.red or colors.black, txtcolor = colors.white, } } local domains = {} local tab = 1 local btns = {} local log = {} local inputting = false local input = { "", "", "", "" } local registerSuccess = "" local w, h = term.getSize() -- API Functions local function inAny( checkIn, checkFor ) -- *Modified* from dvg API (github.com/Dantevg/DvgApps) if checkIn == nil or type( checkIn ) ~= "table" or checkFor == nil then error("Expected table, value") end for k, v in pairs( checkIn ) do if k == checkFor then return k end end --End for loop return false end local function header( text, opt ) -- From dvgapps API v0.9.17.20 (github.com/Dantevg/DvgApps) if type( text ) ~= "string" or type( opt ) ~= "table" then error( "Expected string, table" ) end local w = term.getSize() term.setCursorPos( 1,1 ) term.setBackgroundColor( opt.bgcolor and opt.bgcolor or colors.blue ) term.setTextColor( opt.txtcolor and opt.txtcolor or colors.white ) if not opt.size then opt.size = 1 end for i = 1, opt.size do print( string.rep(" ",w) ) end if opt.size == 1 then term.setCursorPos( 1,1 ) else term.setCursorPos( 1,2 ) end if opt.action then write( " "..opt.action.." "..text ) else write( " x "..text ) end if opt.btns then local btnsPos = { top = {}, bottom = {} } term.setBackgroundColor( opt.btns.bgcolor and opt.btns.bgcolor or colors.lightBlue ) term.setTextColor( opt.btns.txtcolor and opt.btns.txtcolor or colors.white ) local function printBtns( place ) local pos = w + 1 if place == "bottom" then pos = 2 end for i = 1, #opt.btns[place] do if type( opt.btns[place][i] ) ~= "number" then if place ~= "bottom" then pos = pos - #opt.btns[place][i] - 3 end if opt.size == 1 then term.setCursorPos( pos, 1 ) elseif place == "top" then term.setCursorPos( pos, 2 ) elseif place == "bottom" then term.setCursorPos( pos, 4 ) end write( " "..opt.btns[place][i].." " ) btnsPos[place][i] = {} btnsPos[place][i].s, btnsPos[place][i].e = pos, pos + #opt.btns[place][i] + 2 if place == "bottom" then pos = pos + #opt.btns[place][i] + 3 end else if place == "bottom" then pos = pos + opt.btns[place][i] - 1 else pos = pos - opt.btns[place][i] + 1 end end -- End if type end -- End for loop end -- End function if opt.btns.top then printBtns( "top" ) end if opt.size == 5 and opt.btns.bottom then printBtns( "bottom" ) end return btnsPos end -- End if opt.btns end local function read( input, exitEvent, exitParam, exitVal ) -- From dvg API (github.com/Dantevg/DvgApps) if ( input and type(input) ~= "string" ) or ( exitEvent and type( exitEvent ) ~= "string" ) or (exitParam and (type(exitParam)~="number" or exitParam>5) ) then error( "Expected [string input [,string exitEvent [,number exitParam, any exitVal]]" ) end -- Input: string, exitEvent: string, exitParam: number < 6, exitVal: any local input = input or "" while true do local p = {os.pullEvent()} local event = p[1] table.remove( p, 1 ) if event == "key" then if exitEvent == "key" and (not exitParam or p[exitParam] == exitVal) then return input, false, false else if p[1] == keys.backspace then return input:sub( 1,-2 ), false, true elseif p[1] == keys.enter then return input, true, false end end -- End if exitEvent elseif event == "char" then if exitEvent == "char" then if not exitParam or p[exitParam] == exitVal then return input, false, false end else return input..p[1], false, true end elseif event == exitEvent then if not exitParam or p[exitParam] == exitVal then return input, false, false end end -- End if event end -- End while true end local function fill( text, to, char ) -- From dvg API (github.com/Dantevg/DvgApps) if type( text ) ~= "string" or type( to ) ~= "number" then error( "Expected string, number [,string]" ) end if char and type( char ) ~= "string" then error( "Expected string, number [,string]" ) end while #text <= to do if char then text = text..char else text = text.." " end end return text end local function center( text, y ) -- From dvg API (github.com/Dantevg/DvgApps) local curX, curY = term.getCursorPos() local w, _ = term.getSize() x = math.ceil( ( w/2 ) - ( string.len(text)/2 ) + 1 ) term.setCursorPos( x, y and y or curY ) write( text ) term.setCursorPos( curX,curY ) end -- UI Functions function drawInterface() term.setBackgroundColor( c.bg ) term.clear() btns = header( "RedWeb Server", headeropt ) term.setBackgroundColor( c.btnBg ) term.setTextColor( c.btnTxt ) for i = 1, 3 do term.setCursorPos( w-6, h-4+i ) if i == 2 then print( " + " ) else print( " " ) end end if tab == 1 then printServers() elseif tab == 2 then printLog() elseif tab == 3 then printRegister() end end function printServers() term.setBackgroundColor( c.bg ) term.setTextColor( c.txt ) term.setCursorPos( btns.top[1].s, 1 ) print( " ") term.setCursorPos( btns.top[1].s, 2 ) print( " Servers " ) term.setCursorPos( btns.top[1].s, 3 ) print( " ") term.setBackgroundColor( c.bg ) term.setCursorPos( 1,5 ) for var, val in pairs( domains ) do term.setTextColor( c.txt ) write( " "..var ) term.setTextColor( c.sTxt ) print( " "..val ) end end function printLog() term.setBackgroundColor( c.bg ) term.setTextColor( c.txt ) term.setCursorPos( btns.top[2].s, 1 ) print( " ") term.setCursorPos( btns.top[2].s, 2 ) print( " Log " ) term.setCursorPos( btns.top[2].s, 3 ) print( " ") term.setCursorPos( 1,5 ) term.setBackgroundColor( c.bg ) term.setTextColor( c.txt ) for i = 1, #log do print( " "..log[i] ) end end function printRegister() term.setBackgroundColor( c.bg ) term.setTextColor( c.txt ) term.setCursorPos( btns.top[3].s, 1 ) print( " ") term.setCursorPos( btns.top[3].s, 2 ) print( " Register " ) term.setCursorPos( btns.top[3].s, 3 ) print( " ") term.setCursorPos( 2,5 ) term.setBackgroundColor( c.bg ) term.setTextColor( c.txt ) term.setCursorPos( 2,5 ) print( "Domain name:" ) term.setBackgroundColor( c.sBg ) term.setCursorPos( 2,6 ) print( " "..fill( input[1], 35 ) ) term.setBackgroundColor( c.bg ) term.setCursorPos( 2,9 ) print( "Base folder path:" ) term.setBackgroundColor( c.sBg ) term.setCursorPos( 2,10 ) print( "/"..fill( input[2], 35 ) ) term.setBackgroundColor( c.bg ) term.setCursorPos( 2,13 ) print( "Company name:" ) term.setBackgroundColor( c.sBg ) term.setCursorPos( 2,14 ) print( " "..fill( input[3], 35 ) ) term.setBackgroundColor( c.bg ) term.setCursorPos( 2,17 ) print( "Additional info file:" ) term.setBackgroundColor( c.sBg ) term.setCursorPos( 2,18 ) print( "/"..fill( input[4], 35 ) ) end function notify( txt ) term.setCursorPos( 1, 8 ) term.setBackgroundColor( c.btnBg ) term.setTextColor( c.btnTxt ) print( string.rep( " ", w ) ) print( string.rep( " ", w ) ) print( string.rep( " ", w ) ) print( string.rep( " ", w ) ) print( string.rep( " ", w ) ) center( txt, 10 ) term.setBackgroundColor( c.bg ) term.setTextColor( c.txt ) end -- Operating Functions function register() term.setCursorBlink( true ) inputting = (y-2) / 4 while true do term.setCursorPos( 2, y ) term.setBackgroundColor( c.sBg ) if inputting == 2 or inputting == 4 then print( "/"..fill( input[inputting], 35 ) ) else print( " "..fill( input[inputting], 35 ) ) end term.setCursorPos( 3+#input[inputting], y ) input[inputting], confirm, continue = read( input[inputting], "mouse_click" ) if not continue then term.setCursorBlink( false ) break end end end function sendRegister() if input[1] == "" or input[2] == "" or input[3] == "" then return end local info = "" if input[4] ~= "" then if not fs.exists( input[4] ) then error( "Additional info file does not exist" ) end local file = fs.open( input[4], "r" ) info = file.readAll() file.close() end rednet.broadcast( {domain=input[1], company=input[3], info = info}, "DVG_REDWEB_IDS_REGISTER_REQUEST" ) local ID, msg = rednet.receive( "DVG_REDWEB_IDS_REGISTER_ANSWER", 1 ) if not msg then error( "Could not connect to IDS" ) elseif type( msg ) == "string" then error( msg ) else domains[input[1]] = input[2] local file = fs.open( serverPath, "w" ) file.write( textutils.serialize( domains ) ) file.close() notify( "Registered "..input[1].." in folder "..input[2] ) os.pullEvent( "key" ) end end function sendRemove( name ) notify( "Delete "..name.."? y/n" ) term.setBackgroundColor( c.bg ) local _, char = os.pullEvent( "char" ) if char:lower() == "y" then rednet.broadcast( name, "DVG_REDWEB_IDS_REMOVE_REQUEST" ) local ID, msg = rednet.receive( "DVG_REDWEB_IDS_REMOVE_ANSWER", 1 ) if not msg then error( "Could not connect to IDS" ) elseif type( msg ) == "string" then error( msg ) else local path = domains[name] domains[name] = nil local file = fs.open( serverPath, "w" ) file.write( textutils.serialize( domains ) ) file.close() notify( "Removed "..name.." from folder "..path ) os.pullEvent( "key" ) end end end function webpage( info ) if not info.path or info.path == "" then info.path = "index" end if not fs.exists( domains[info.domain].."/"..info.path ) then --Does not exist local _,_, ext = string.find( info.path, "%w+(%.+%w+)" ) if ext == nil or ext == "" then if fs.exists( domains[info.domain].."/"..info.path..".lua" ) then info.path = info.path..".lua" local file = fs.open( domains[info.domain].."/"..info.path, "r" ) rednet.send( info.ID, file.readAll(), "DVG_REDWEB_WEBSITE_ANSWER" ) table.insert( log, "LOG Sent "..info.domain.."/"..info.path.." to ID "..info.ID ) file.close() else rednet.send( info.ID, "ERR URL not found", "DVG_REDWEB_WEBSITE_ANSWER" ) table.insert( log, "LOG URL not found" ) end else rednet.send( info.ID, "ERR URL not found", "DVG_REDWEB_WEBSITE_ANSWER" ) table.insert( log, "LOG URL not found" ) end else --Return webpage local file = fs.open( domains[info.domain].."/"..info.path, "r" ) rednet.send( info.ID, file.readAll(), "DVG_REDWEB_WEBSITE_ANSWER" ) table.insert( log, "LOG Sent "..info.domain.."/"..info.path.." to ID "..info.ID ) file.close() end end -- Handling Functions function handleMsg( msg ) _,_, msg.domain, msg.path = msg.url:find( "([^/]+)([^%?]*)" ) -- doma.in / path/to/file table.insert( log, "LOG Got request for ".. msg.domain ..( msg.path and "/".. msg.path or "" ) ) if not inAny( domains, msg.domain ) then rednet.send( msg.ID, "ERR Domain not registered", "DVG_REDWEB_WEBSITE_ANSWER" ) table.insert( log, "ERR Domain not registered" ) elseif not fs.isDir( domains[msg.domain] ) then rednet.send( msg.ID, "ERR Error with server configuration", "DVG_REDWEB_WEBSITE_ANSWER" ) table.insert( log, "ERR Could not find folder for domain: "..msg.domain ) else webpage( msg ) end --End if end function handleClick( x, y ) if y == 2 then -- Header if x >= 1 and x <= 4 then -- "x" pressed running = false return nil else for i = 1, #btns.top do if x >= btns.top[i].s and x <= btns.top[i].e then tab = i break end end end -- End if x elseif y >= h-5 and y <= h-1 and x <= w-2 and x >= w-6 then -- Button pressed if tab == 3 then sendRegister() else tab = 3 end elseif tab == 3 then -- Registering if x >= 2 and x <= 41 and y == 6 or y == 10 or y == 14 or y == 18 then register() else term.setCursorBlink( false ) inputting = false end elseif tab == 1 then -- Server list local i = 1 for k, v in pairs( domains ) do if y == 4 + i then sendRemove( k ) break end i = i + 1 end -- End for end -- End if end -- Run if fs.exists( serverPath ) then local file = fs.open( serverPath, "r" ) domains = assert( textutils.unserialize( assert(file.readAll(),"Could not read server.cfg") ), "Invalid server.cfg" ) file.close() end table.insert( log, "LOG Starting server" ) while running do drawInterface() event, id, x, y = os.pullEvent() if event == "mouse_click" then handleClick( x, y ) elseif event == "rednet_message" and y == "DVG_REDWEB_WEBSITE_REQUEST" then handleMsg( x ) end end --End while term.setBackgroundColor( colors.black ) term.setTextColor( colors.white ) term.clear() term.setCursorPos( 1,1 )
mit
FastTM/Fast-Unique
plugins/links.lua
1
1928
local plugin = {} function plugin.onTextMessage(msg, blocks) if msg.chat.type == 'private' then return end if not roles.is_admin_cached(msg) then return end local hash = 'chat:'..msg.chat.id..':links' local text if blocks[1] == 'link' then local key = 'link' local link = db:hget(hash, key) --check if link is nil or nul if not link then text = _("*No link* for this group. Ask the owner to generate one") else local title = msg.chat.title:escape_hard('link') text = string.format('[%s](%s)', title, link) end api.sendReply(msg, text, true) end if blocks[1] == 'setlink' then local link if msg.chat.username then link = 'https://telegram.me/'..msg.chat.username else if not blocks[2] then local text = _("This is not a *public supergroup*, so you need to write the link near /setlink") api.sendReply(msg, text, true) return end --warn if the link has not the right lenght if string.len(blocks[2]) ~= 22 and blocks[2] ~= '-' then api.sendReply(msg, _("This link is *not valid!*"), true) return end link = 'https://telegram.me/joinchat/'..blocks[2] end local key = 'link' --set to nul the link, or update/set it if blocks[2] and blocks[2] == '-' then db:hdel(hash, key) text = _("Link *unsetted*") else local succ = db:hset(hash, key, link) local title = msg.chat.title:escape_hard('link') local substitution = '['..title..']('..link..')' if succ == false then text = _("The link has been updated.\n*Here's the new link*: %s"):format(substitution) else text = _("The link has been set.\n*Here's the link*: %s"):format(substitution) end end api.sendReply(msg, text, true) end end plugin.triggers = { onTextMessage = { config.cmd..'(link)$', config.cmd..'(setlink)$', config.cmd..'(setlink) https://telegram%.me/joinchat/(.*)', config.cmd..'(setlink) (-)' } } return plugin
gpl-2.0
Noltari/luci
libs/luci-lib-nixio/docsrc/nixio.UnifiedIO.lua
16
5900
--- Unified high-level I/O utility API for Files, Sockets and TLS-Sockets. -- These functions are added to the object function tables by doing <strong> -- require "nixio.util"</strong>, can be used on all nixio IO Descriptors and -- are based on the shared low-level read() and write() functions. -- @cstyle instance module "nixio.UnifiedIO" --- Test whether the I/O-Descriptor is a socket. -- @class function -- @name UnifiedIO.is_socket -- @return boolean --- Test whether the I/O-Descriptor is a TLS socket. -- @class function -- @name UnifiedIO.is_tls_socket -- @return boolean --- Test whether the I/O-Descriptor is a file. -- @class function -- @name UnifiedIO.is_file -- @return boolean --- Read a block of data and wait until all data is available. -- @class function -- @name UnifiedIO.readall -- @usage This function uses the low-level read function of the descriptor. -- @usage If the length parameter is omitted, this function returns all data -- that can be read before an end-of-file, end-of-stream, connection shutdown -- or similar happens. -- @usage If the descriptor is non-blocking this function may fail with EAGAIN. -- @param length Bytes to read (optional) -- @return data that was successfully read if no error occurred -- @return - reserved for error code - -- @return - reserved for error message - -- @return data that was successfully read even if an error occurred --- Write a block of data and wait until all data is written. -- @class function -- @name UnifiedIO.writeall -- @usage This function uses the low-level write function of the descriptor. -- @usage If the descriptor is non-blocking this function may fail with EAGAIN. -- @param block Bytes to write -- @return bytes that were successfully written if no error occurred -- @return - reserved for error code - -- @return - reserved for error message - -- @return bytes that were successfully written even if an error occurred --- Create a line-based iterator. -- Lines may end with either \n or \r\n, these control chars are not included -- in the return value. -- @class function -- @name UnifiedIO.linesource -- @usage This function uses the low-level read function of the descriptor. -- @usage <strong>Note:</strong> This function uses an internal buffer to read -- ahead. Do NOT mix calls to read(all) and the returned iterator. If you want -- to stop reading line-based and want to use the read(all) functions instead -- you can pass "true" to the iterator which will flush the buffer -- and return the bufferd data. -- @usage If the limit parameter is omitted, this function uses the nixio -- buffersize (8192B by default). -- @usage If the descriptor is non-blocking the iterator may fail with EAGAIN. -- @usage The iterator can be used as an LTN12 source. -- @param limit Line limit -- @return Line-based Iterator --- Create a block-based iterator. -- @class function -- @name UnifiedIO.blocksource -- @usage This function uses the low-level read function of the descriptor. -- @usage The blocksize given is only advisory and to be seen as an upper limit, -- if an underlying read returns less bytes the chunk is nevertheless returned. -- @usage If the limit parameter is omitted, the iterator returns data -- until an end-of-file, end-of-stream, connection shutdown or similar happens. -- @usage The iterator will not buffer so it is safe to mix with calls to read. -- @usage If the descriptor is non-blocking the iterator may fail with EAGAIN. -- @usage The iterator can be used as an LTN12 source. -- @param blocksize Advisory blocksize (optional) -- @param limit Amount of data to consume (optional) -- @return Block-based Iterator --- Create a sink. -- This sink will simply write all data that it receives and optionally -- close the descriptor afterwards. -- @class function -- @name UnifiedIO.sink -- @usage This function uses the writeall function of the descriptor. -- @usage If the descriptor is non-blocking the sink may fail with EAGAIN. -- @usage The iterator can be used as an LTN12 sink. -- @param close_when_done (optional, boolean) -- @return Sink --- Copy data from the current descriptor to another one. -- @class function -- @name UnifiedIO.copy -- @usage This function uses the blocksource function of the source descriptor -- and the sink function of the target descriptor. -- @usage If the limit parameter is omitted, data is copied -- until an end-of-file, end-of-stream, connection shutdown or similar happens. -- @usage If the descriptor is non-blocking the function may fail with EAGAIN. -- @param fdout Target Descriptor -- @param size Bytes to copy (optional) -- @return bytes that were successfully written if no error occurred -- @return - reserved for error code - -- @return - reserved for error message - -- @return bytes that were successfully written even if an error occurred --- Copy data from the current descriptor to another one using kernel-space -- copying if possible. -- @class function -- @name UnifiedIO.copyz -- @usage This function uses the sendfile() syscall to copy the data or the -- blocksource function of the source descriptor and the sink function -- of the target descriptor as a fallback mechanism. -- @usage If the limit parameter is omitted, data is copied -- until an end-of-file, end-of-stream, connection shutdown or similar happens. -- @usage If the descriptor is non-blocking the function may fail with EAGAIN. -- @param fdout Target Descriptor -- @param size Bytes to copy (optional) -- @return bytes that were successfully written if no error occurred -- @return - reserved for error code - -- @return - reserved for error message - -- @return bytes that were successfully written even if an error occurred --- Close the descriptor. -- @class function -- @name UnifiedIO.close -- @usage If the descriptor is a TLS-socket the underlying descriptor is -- closed without touching the TLS connection. -- @return true
apache-2.0
chelog/brawl
gamemodes/brawl/gamemode/modules/base/modes/squad_dm/sv_mode.lua
1
3144
function MODE:Think() if GetGlobalInt( "brawl.RoundState" ) == 0 then SetGlobalInt( "brawl.Rounds", 0 ) brawl.NewRound() end if GetGlobalInt( "brawl.RoundState" ) < 3 then for _, k in pairs( self.teams ) do if team.GetScore( k ) >= self.maxKills then brawl.EndRound({ winner = k }) end end end end local intermissionTime = 10 function MODE:EndRound( data ) if data.winner then local t = data.winner if not t then return end timer.Simple( intermissionTime, brawl.NewRound ) SetGlobalFloat( "RoundStart", CurTime() + intermissionTime ) SetGlobalInt( "brawl.RoundState", 3 ) brawl.NotifyAll({ team.GetColor( data.winner ), team.GetName( data.winner ) .. " squad", color_white, " won the round!" }) for k, ply in pairs( team.GetPlayers(t) ) do ply:AddXP( 750, "Round winner" ) end end end function MODE:NewRound( type ) local delay = 6.1 game.CleanUpMap() brawl.CleanUpMap() for k, ply in RandomPairs( player.GetAll() ) do if not ply:GetNWBool( "SpectateOnly" ) then ply:SetFrags( 0 ) ply:SetDeaths( 0 ) ply:KillSilent() ply:UnSpectate() ply:SetNWBool( "Spectating", false ) ply:Spawn() ply:Freeze( true ) net.Start( "brawl.round.start" ) net.WriteFloat( delay ) net.WriteString( self.name ) net.WriteString( self.agenda ) net.Send( ply ) end end SetGlobalInt( "brawl.RoundState", 1 ) timer.Simple( delay, function() for k, ply in pairs( player.GetAll() ) do ply:Freeze( false ) end SetGlobalInt( "brawl.RoundState", 2 ) brawl.NotifyAll( "A new round has started!" ) end) end function MODE:PlayerSpawn( ply ) local spawn = brawl.points.findNearestTeamSpawn( ply ) if spawn.pos then ply:SetPos( spawn.pos + Vector(0,0,5) ) end if spawn.ang then ply:SetEyeAngles( spawn.ang ) end ply:LoadModel() ply:LoadWeapons() ply:LoadSkills() end function MODE:DeathThink( ply ) local spawnTime = ply:GetNWFloat( "RespawnTime" ) if CurTime() > spawnTime then if ply:GetNWBool( "SpectateOnly" ) then ply:StartSpectating() else ply:Spawn() end end return false end function MODE:PlayerCanTalkTo( listener, talker, t, text ) return true, listener:Team() ~= talker:Team() end function MODE:PlayerCanSpectate( ply, ent ) return true end function MODE:PlayerInitialSpawn( ply ) timer.Simple(0, function() local delay = 6.1 ply:KillSilent() ply:SetNWFloat( "RespawnTime", CurTime() + delay ) net.Start( "brawl.round.start" ) net.WriteFloat( delay ) net.WriteString( self.name ) net.WriteString( self.agenda ) net.Send( ply ) local t = team.BestAutoJoinTeam( ply ) ply:SetTeam( t ) brawl.NotifyAll({ team.GetColor( t ), ply:Name(), color_white, " joined ", team.GetColor( t ), team.GetName(t) .. " squad" }) end) end function MODE:PlayerDeath( ply ) ply:SetNWFloat( "RespawnTime", CurTime() + 8 ) end function MODE:DoPlayerDeath( victim, attacker, dmg ) if not attacker:IsPlayer() then return end local victimTeam = victim:Team() local killerTeam = attacker:Team() team.AddScore( killerTeam, victimTeam ~= killerTeam and 1 or -1 ) end
gpl-3.0
qq779089973/ramod
luci/applications/luci-statistics/luasrc/statistics/rrdtool/definitions/interface.lua
69
2769
--[[ Luci statistics - interface plugin diagram definition (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.rrdtool.definitions.interface", package.seeall) function rrdargs( graph, plugin, plugin_instance ) -- -- traffic diagram -- local traffic = { -- draw this diagram for each data instance per_instance = true, title = "%H: Transfer on %di", vlabel = "Bytes/s", -- diagram data description data = { -- defined sources for data types, if ommitted assume a single DS named "value" (optional) sources = { if_octets = { "tx", "rx" } }, -- special options for single data lines options = { if_octets__tx = { total = true, -- report total amount of bytes color = "00ff00", -- tx is green title = "Bytes (TX)" }, if_octets__rx = { flip = true, -- flip rx line total = true, -- report total amount of bytes color = "0000ff", -- rx is blue title = "Bytes (RX)" } } } } -- -- packet diagram -- local packets = { -- draw this diagram for each data instance per_instance = true, title = "%H: Packets on %di", vlabel = "Packets/s", -- diagram data description data = { -- data type order types = { "if_packets", "if_errors" }, -- defined sources for data types sources = { if_packets = { "tx", "rx" }, if_errors = { "tx", "rx" } }, -- special options for single data lines options = { -- processed packets (tx DS) if_packets__tx = { overlay = true, -- don't summarize total = true, -- report total amount of bytes color = "00ff00", -- processed tx is green title = "Processed (tx)" }, -- processed packets (rx DS) if_packets__rx = { overlay = true, -- don't summarize flip = true, -- flip rx line total = true, -- report total amount of bytes color = "0000ff", -- processed rx is blue title = "Processed (rx)" }, -- packet errors (tx DS) if_errors__tx = { overlay = true, -- don't summarize total = true, -- report total amount of packets color = "ff5500", -- tx errors are orange title = "Errors (tx)" }, -- packet errors (rx DS) if_errors__rx = { overlay = true, -- don't summarize flip = true, -- flip rx line total = true, -- report total amount of packets color = "ff0000", -- rx errors are red title = "Errors (rx)" } } } } return { traffic, packets } end
mit
mamadtnt/ya
plugins/google.lua
722
1037
local function googlethat(query) local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&" local parameters = "q=".. (URL.escape(query) or "") -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults="" for key,val in ipairs(results) do stringresults=stringresults..val[1].." - "..val[2].."\n" end return stringresults end local function run(msg, matches) local results = googlethat(matches[1]) return stringlinks(results) end return { description = "Searches Google and send results", usage = "!google [terms]: Searches Google and send results", patterns = { "^!google (.*)$", "^%.[g|G]oogle (.*)$" }, run = run }
gpl-2.0
LaFamiglia/Illarion-Content
item/id_3076_coppercoins.lua
1
1846
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] -- UPDATE items SET itm_script='item.id_3076_coppercoins' WHERE itm_id=3076; local common = require("base.common") local lookat = require("base.lookat") local M = {} local TimeList = {} function M.LookAtItem(User, Item) if Item.number == 1 then lookat.SetSpecialDescription(Item, "Eine einzelne Münze", "A single coin") else lookat.SetSpecialDescription(Item, "Eine Sammlung aus " .. Item.number .. " Münzen", "A collection of " .. Item.number .. " coins") end return lookat.GenerateLookAt(User, Item, lookat.NONE) end function M.UseItem(User, SourceItem) if TimeList[User.id] ~= nil then if (math.abs(world:getTime("second") - TimeList[User.id])) <= 3 then -- 1 Rl. second delay return end end local face if math.random(2) == 1 then face = common.GetNLS(User, "Kopf", "head") else face = common.GetNLS(User, "Zahl","tail") end User:talk(Character.say, "#me wirft eine Münze in die Luft und fängt sie wieder auf. Sie zeigt "..face..".", "#me throws a coin in the air and catches it again. It shows "..face..".") TimeList[User.id] = world:getTime("second") end return M
agpl-3.0
23maverick23/hammerspoon-config
modules/layouts.lua
1
2220
-- Main grid methods local layouts = {} -- Define monitor names for layout purposes local display_home = "f.lux profile" local display_laptop = "Color LCD" local display_monitor = "Thunderbolt Display" -- Define window layouts -- Format reminder: -- {"App name", "Window name", "Display Name", "unitrect", "framerect", "fullframerect"}, layouts.layouts = { { name="Home Laptop", description='15" MacBook Pro personal laptop screen' }, { name="Work Laptop", description='13" MacBook Air work laptop screen' }, { name="Office Setup", description="Dual monitor setup at the office", small={ {"Spark", nil, display_laptop, {hs.layout.maximized}, nil, nil}, {"Fantastical 2", nil, display_laptop, {hs.layout.maximized}, nil, nil}, }, large={ {"Google Chrome", nil, display_monitor, {0, 0, 2/3, 1}, nil, nil}, {"Sublime Text", nil, display_monitor, {1/3, 1/3, 1/3, 2/3}, nil, nil} } }, } function layouts.applyLayout(layout) print('Layout ' .. layout.name .. ' selected') if lastNumberOfScreens > 1 then -- Multiple monitors print('We have multiple monitors') hs.layout.apply(layout.large, function(windowTitle, layoutWindowTitle) return string.sub(windowTitle, 1, string.len(layoutWindowTitle)) == layoutWindowTitle end) end -- Multiple monitors print('We have a single screen') hs.layout.apply(layout.small, function(windowTitle, layoutWindowTitle) return string.sub(windowTitle, 1, string.len(layoutWindowTitle)) == layoutWindowTitle end) end layouts.chooser = hs.chooser.new(function(selection) if not selection then return end layouts.applyLayout(layouts.layouts[selection.uuid]) end) -- chooser:choices(choices) local i = 0 local choices = hs.fnutils.imap(layouts.layouts, function(layout) i = i + 1 return { uuid=i, text=layout.name, subText=layout.description } end) layouts.chooser:choices(choices) layouts.chooser:searchSubText(true) layouts.chooser:rows(#choices) layouts.chooser:width(20) return layouts
mit
AIUbi/2D-vector-for-Lua
vector2.lua
1
3032
local META = {} META = { __index = function(tbl, key) return META[key] end, __unm = function(lhs) return vec2(-lhs.x, lhs.y) end, __add = function(lhs, rhs) return vec2(lhs.x + (rhs.x or rhs), lhs.y + (rhs.y or rhs)) end, __sub = function(lhs, rhs) return vec2(lhs.x - (rhs.x or rhs), lhs.y - (rhs.y or rhs)) end, __mul = function(lhs, rhs) return vec2(lhs.x * (rhs.x or rhs), lhs.y * (rhs.y or rhs)) end, __div = function(lhs, rhs) return vec2(lhs.x / (rhs.x or rhs), lhs.y / (rhs.y or rhs)) end, __mod = function(lhs, rhs) return vec2(lhs.x % (rhs.x or rhs), lhs.y % (rhs.y or rhs)) end, __pow = function(lhs, rhs) return vec2(lhs.x ^ (rhs.x or rhs), lhs.y ^ (rhs.y or rhs)) end, __tostring = function(lhs) return string.format("vec2(%s,%s)",lhs.x,lhs.y) end, __le = function(lhs, rhs) return lhs.x <= rhs.x and lhs.y <= rhs.y end, __lt = function(lhs, rhs) return lhs.x < rhs.x and lhs.y < rhs.y end, __eq = function(lhs, rhs) return lhs.x == rhs.x and lhs.y == rhs.y end, clamp = function(lhs, min, max) return vec2(math.min(math.max(lhs.x, min.x), max.x), math.min(math.max(lhs.y, min.y), max.y)) end, length = function(lhs) return math.sqrt(lhs.x*lhs.x+lhs.y*lhs.y) end, distance = function(lhs, vec) return math.abs(math.sqrt((lhs.x-vec.x)^2+(lhs.y-vec.y)^2)) end, dot_product = function(lhs, vec) return lhs.x*vec.x+lhs.y*vec.y end, angle_atan = function(lhs, vec) return math.deg(math.atan2( vec:length(), lhs:length())) end, angle_cos = function(lhs, vec) return math.deg(math.acos(lhs:dot_product(vec)/(lhs:length()*vec:length()))) end, normalize = function(lhs) return vec2(lhs.x/lhs:length(),lhs.y/lhs:length()) end, perpendecular = function(lhs, rhs, sign) return ((lhs+rhs)/2):rotate_around_axis(lhs, 90*math.min(math.max(sign, -1), 1)) end, rotate = function(lhs, ang) ang = math.rad(ang) local c = math.cos(ang) local s = math.sin(ang) return vec2(lhs.x*c-lhs.y*s, lhs.x*s+lhs.y*c) end, rotate_around_axis = function(lhs, ang, pos) ang = math.rad(ang) local c = math.cos(ang) local s = math.sin(ang) return vec2((pos.x+lhs.x)*c-(pos.y+lhs.y)*s, (pos.x+lhs.x)*s+(pos.y+lhs.y)*c) end, } vec2 = function(x, y) return setmetatable({x = math.floor(x or 0, 4), y = math.floor(y or x or 0, 4)}, META) end --[[ Uncomment for see results print("Clamp vectors:", vec2(1, 0):clamp(vec2(0, 0), vec2(0.5, 0))) print("Length vector:", vec2(1, 0):length()) print("Distance between two vectors:", vec2(0, 0):distance(vec2(1000, 0))) print("Scalar product (Dot product):", vec2(15,25):dot_product()) print("Angle btween two vectors from ATAN (90):", vec2(1, 0):angle_atan(vec2(0, 1))) print("Angle btween two vectors from COS (180):", vec2(1, 0):angle_cos(vec2(0, 1))) print("Vector normalization:", vec2(0.99, 561):normalize()) print("Perpendecular from two points:", vec2(0, 1):perpendecular(vec2(1, 0))) print("Rotate on 35 degrees:", vec2(1, 0):rotate(35)) print("Rotate on 90 degrees around axis:", vec2(1, 0):rotate_around_axis(90, vec(0, 1))) ]]--
gpl-2.0
skatsuta/aerospike-training
book/answers/Aggregations/Java/udf/aggregationByRegion.lua
16
1246
local function aggregate_stats(map,rec) -- Examine value of 'region' bin in record rec and increment respective counter in the map if rec.region == 'n' then map['n'] = map['n'] + 1 elseif rec.region == 's' then map['s'] = map['s'] + 1 elseif rec.region == 'e' then map['e'] = map['e'] + 1 elseif rec.region == 'w' then map['w'] = map['w'] + 1 end -- return updated map return map end local function reduce_stats(a,b) -- Merge values from map b into a a.n = a.n + b.n a.s = a.s + b.s a.e = a.e + b.e a.w = a.w + b.w -- Return updated map a return a end function sum(stream) -- Process incoming record stream and pass it to aggregate function, then to reduce function -- NOTE: aggregate function aggregate_stats accepts two parameters: -- 1) A map that contains four variables to store number-of-users counter for north, south, east and west regions with initial value set to 0 -- 2) function name aggregate_stats -- which will be called for each record as it flows in -- Return reduced value of the map generated by reduce function reduce_stats return stream : aggregate(map{n=0,s=0,e=0,w=0},aggregate_stats) : reduce(reduce_stats) end
mit
skatsuta/aerospike-training
book/answers/Queries/Go/udf/aggregationByRegion.lua
16
1246
local function aggregate_stats(map,rec) -- Examine value of 'region' bin in record rec and increment respective counter in the map if rec.region == 'n' then map['n'] = map['n'] + 1 elseif rec.region == 's' then map['s'] = map['s'] + 1 elseif rec.region == 'e' then map['e'] = map['e'] + 1 elseif rec.region == 'w' then map['w'] = map['w'] + 1 end -- return updated map return map end local function reduce_stats(a,b) -- Merge values from map b into a a.n = a.n + b.n a.s = a.s + b.s a.e = a.e + b.e a.w = a.w + b.w -- Return updated map a return a end function sum(stream) -- Process incoming record stream and pass it to aggregate function, then to reduce function -- NOTE: aggregate function aggregate_stats accepts two parameters: -- 1) A map that contains four variables to store number-of-users counter for north, south, east and west regions with initial value set to 0 -- 2) function name aggregate_stats -- which will be called for each record as it flows in -- Return reduced value of the map generated by reduce function reduce_stats return stream : aggregate(map{n=0,s=0,e=0,w=0},aggregate_stats) : reduce(reduce_stats) end
mit
skatsuta/aerospike-training
book/answers/Aggregations/C#/AerospikeTraining/udf/aggregationByRegion.lua
16
1246
local function aggregate_stats(map,rec) -- Examine value of 'region' bin in record rec and increment respective counter in the map if rec.region == 'n' then map['n'] = map['n'] + 1 elseif rec.region == 's' then map['s'] = map['s'] + 1 elseif rec.region == 'e' then map['e'] = map['e'] + 1 elseif rec.region == 'w' then map['w'] = map['w'] + 1 end -- return updated map return map end local function reduce_stats(a,b) -- Merge values from map b into a a.n = a.n + b.n a.s = a.s + b.s a.e = a.e + b.e a.w = a.w + b.w -- Return updated map a return a end function sum(stream) -- Process incoming record stream and pass it to aggregate function, then to reduce function -- NOTE: aggregate function aggregate_stats accepts two parameters: -- 1) A map that contains four variables to store number-of-users counter for north, south, east and west regions with initial value set to 0 -- 2) function name aggregate_stats -- which will be called for each record as it flows in -- Return reduced value of the map generated by reduce function reduce_stats return stream : aggregate(map{n=0,s=0,e=0,w=0},aggregate_stats) : reduce(reduce_stats) end
mit
skatsuta/aerospike-training
book/exercise/Queries/Go/udf/aggregationByRegion.lua
16
1246
local function aggregate_stats(map,rec) -- Examine value of 'region' bin in record rec and increment respective counter in the map if rec.region == 'n' then map['n'] = map['n'] + 1 elseif rec.region == 's' then map['s'] = map['s'] + 1 elseif rec.region == 'e' then map['e'] = map['e'] + 1 elseif rec.region == 'w' then map['w'] = map['w'] + 1 end -- return updated map return map end local function reduce_stats(a,b) -- Merge values from map b into a a.n = a.n + b.n a.s = a.s + b.s a.e = a.e + b.e a.w = a.w + b.w -- Return updated map a return a end function sum(stream) -- Process incoming record stream and pass it to aggregate function, then to reduce function -- NOTE: aggregate function aggregate_stats accepts two parameters: -- 1) A map that contains four variables to store number-of-users counter for north, south, east and west regions with initial value set to 0 -- 2) function name aggregate_stats -- which will be called for each record as it flows in -- Return reduced value of the map generated by reduce function reduce_stats return stream : aggregate(map{n=0,s=0,e=0,w=0},aggregate_stats) : reduce(reduce_stats) end
mit
enulex/skynet
examples/agent.lua
65
2082
local skynet = require "skynet" local netpack = require "netpack" local socket = require "socket" local sproto = require "sproto" local sprotoloader = require "sprotoloader" local WATCHDOG local host local send_request local CMD = {} local REQUEST = {} local client_fd function REQUEST:get() print("get", self.what) local r = skynet.call("SIMPLEDB", "lua", "get", self.what) return { result = r } end function REQUEST:set() print("set", self.what, self.value) local r = skynet.call("SIMPLEDB", "lua", "set", self.what, self.value) end function REQUEST:handshake() return { msg = "Welcome to skynet, I will send heartbeat every 5 sec." } end function REQUEST:quit() skynet.call(WATCHDOG, "lua", "close", client_fd) end local function request(name, args, response) local f = assert(REQUEST[name]) local r = f(args) if response then return response(r) end end local function send_package(pack) local package = string.pack(">s2", pack) socket.write(client_fd, package) end skynet.register_protocol { name = "client", id = skynet.PTYPE_CLIENT, unpack = function (msg, sz) return host:dispatch(msg, sz) end, dispatch = function (_, _, type, ...) if type == "REQUEST" then local ok, result = pcall(request, ...) if ok then if result then send_package(result) end else skynet.error(result) end else assert(type == "RESPONSE") error "This example doesn't support request client" end end } function CMD.start(conf) local fd = conf.client local gate = conf.gate WATCHDOG = conf.watchdog -- slot 1,2 set at main.lua host = sprotoloader.load(1):host "package" send_request = host:attach(sprotoloader.load(2)) skynet.fork(function() while true do send_package(send_request "heartbeat") skynet.sleep(500) end end) client_fd = fd skynet.call(gate, "lua", "forward", fd) end function CMD.disconnect() -- todo: do something before exit skynet.exit() end skynet.start(function() skynet.dispatch("lua", function(_,_, command, ...) local f = CMD[command] skynet.ret(skynet.pack(f(...))) end) end)
mit
Godfather021/yag
plugins/btc.lua
289
1375
-- See https://bitcoinaverage.com/api local function getBTCX(amount,currency) local base_url = 'https://api.bitcoinaverage.com/ticker/global/' -- Do request on bitcoinaverage, the final / is critical! local res,code = https.request(base_url..currency.."/") if code ~= 200 then return nil end local data = json:decode(res) -- Easy, it's right there text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid -- If we have a number as second parameter, calculate the bitcoin amount if amount~=nil then btc = tonumber(amount) / tonumber(data.ask) text = text.."\n "..currency .." "..amount.." = BTC "..btc end return text end local function run(msg, matches) local cur = 'EUR' local amt = nil -- Get the global match out of the way if matches[1] == "!btc" then return getBTCX(amt,cur) end if matches[2] ~= nil then -- There is a second match amt = matches[2] cur = string.upper(matches[1]) else -- Just a EUR or USD param cur = string.upper(matches[1]) end return getBTCX(amt,cur) end return { description = "Bitcoin global average market value (in EUR or USD)", usage = "!btc [EUR|USD] [amount]", patterns = { "^!btc$", "^!btc ([Ee][Uu][Rr])$", "^!btc ([Uu][Ss][Dd])$", "^!btc (EUR) (%d+[%d%.]*)$", "^!btc (USD) (%d+[%d%.]*)$" }, run = run }
gpl-2.0
Noltari/luci
applications/luci-app-nut/luasrc/model/cbi/nut_monitor.lua
9
7370
-- Copyright 2015 Daniel Dickinson <openwrt@daniel.thecshore.com> -- Licensed to the public under the Apache License 2.0. local m, s, o require "luci.util" m = Map("nut_monitor", translate("Network UPS Tools (Monitor)"), translate("Network UPS Tools Monitoring Configuration")) s = m:section(NamedSection, "upsmon", "upsmon", translate("Global Settings")) s.addremove = true s.optional = true o = s:option(Value, "runas", translate("RunAs User"), translate("upsmon drops privileges to this user")) o.placeholder = "nutmon" o = s:option(Value, "minsupplies", translate("Minimum required number or power supplies")) o.datatype = "uinteger" o.placeholder = 1 o.optional = true o = s:option(Value, "shutdowncmd", translate("Shutdown command")) o.optional = true o.placeholder = "/sbin/halt" o = s:option(Value, "notifycmd", translate("Notify command")) o.optional = true o = s:option(Value, "pollfreq", translate("Poll frequency")) o.datatype = "uinteger" o.placeholder = 5 o.optional = true o = s:option(Value, "pollfreqalert", translate("Poll frequency alert")) o.datatype = "uinteger" o.optional = true o.placeholder = 5 o = s:option(Value, "hotsync", translate("Hot Sync")) o.optional = true o.placeholder = 15 o = s:option(Value, "deadtime", translate("Deadtime")) o.datatype = "uinteger" o.optional = true o.placeholder = 15 o = s:option(Value, "onlinemsg", translate("Online message")) o.optional = true o = s:option(Value, "onbattmsg", translate("On battery message")) o.optional = true o = s:option(Value, "lowbattmsg", translate("Low battery message")) o.optional = true o = s:option(Value, "fsdmsg", translate("Forced shutdown message")) o.optional = true o = s:option(Value, "comokmsg", translate("Communications restored message")) o.optional = true o = s:option(Value, "combadmsg", translate("Communications lost message")) o.optional = true o = s:option(Value, "shutdownmsg", translate("Shutdown message")) o.optional = true o = s:option(Value, "replbattmsg", translate("Replace battery message")) o.optional = true o = s:option(Value, "nocommsg", translate("No communications message")) o.optional = true o = s:option(Value, "noparentmsg", translate("No parent message")) o.optional = true validatenotify = function(self, value) val = StaticList.validate(self, value) if val then for k, v in pairs(val) do if (v == 'IGNORE') then return nil, "Ignore must the only option selected, when selected" end end end return val end o = s:option(StaticList, "defaultnotify", translate("Notification defaults")) o.optional = true o.widget = "select" o:value("EXEC", translate("Execute notify command")) o:value("SYSLOG", translate("Write to syslog")) o:value("IGNORE", translate("Ignore")) o.default = "SYSLOG" o.validate = validatenotify o = s:option(StaticList, "onlinenotify", translate("Notify when back online")) o.optional = true o.widget = "select" o:value("EXEC", translate("Execute notify command")) o:value("SYSLOG", translate("Write to syslog")) o:value("IGNORE", translate("Ignore")) o.validate = validatenotify o = s:option(StaticList, "onbattnotify", translate("Notify when on battery")) o.optional = true o.widget = "select" o:value("EXEC", translate("Execute notify command")) o:value("SYSLOG", translate("Write to syslog")) o:value("IGNORE", translate("Ignore")) o.validate = validatenotify o = s:option(StaticList, "nowbattnotify", translate("Notify when low battery")) o.optional = true o.widget = "select" o:value("EXEC", translate("Execute notify command")) o:value("SYSLOG", translate("Write to syslog")) o:value("IGNORE", translate("Ignore")) o.validate = validatenotify o = s:option(StaticList, "nowbattnotify", translate("Notify when low battery")) o.optional = true o.widget = "select" o:value("EXEC", translate("Execute notify command")) o:value("SYSLOG", translate("Write to syslog")) o:value("IGNORE", translate("Ignore")) o.validate = validatenotify o = s:option(StaticList, "fsdnotify", translate("Notify when force shutdown")) o.optional = true o.widget = "select" o:value("EXEC", translate("Execute notify command")) o:value("SYSLOG", translate("Write to syslog")) o:value("IGNORE", translate("Ignore")) o.validate = validatenotify o = s:option(StaticList, "comoknotify", translate("Notify when communications restored")) o.optional = true o.widget = "select" o:value("EXEC", translate("Execute notify command")) o:value("SYSLOG", translate("Write to syslog")) o:value("IGNORE", translate("Ignore")) o.validate = validatenotify o = s:option(StaticList, "combadnotify", translate("Notify when communications lost")) o.optional = true o.widget = "select" o:value("EXEC", translate("Execute notify command")) o:value("SYSLOG", translate("Write to syslog")) o:value("IGNORE", translate("Ignore")) o.validate = validatenotify o = s:option(StaticList, "shutdownotify", translate("Notify when shutting down")) o.optional = true o.widget = "select" o:value("EXEC", translate("Execute notify command")) o:value("SYSLOG", translate("Write to syslog")) o:value("IGNORE", translate("Ignore")) o.validate = validatenotify o = s:option(StaticList, "replbattnotify", translate("Notify when battery needs replacing")) o.optional = true o.widget = "select" o:value("EXEC", translate("Execute notify command")) o:value("SYSLOG", translate("Write to syslog")) o:value("IGNORE", translate("Ignore")) o.validate = validatenotify local have_ssl_support = luci.util.checklib("/usr/sbin/upsmon", "libssl.so") if have_ssl_support then o = s:option(Value, "certpath", translate("CA Certificate path"), translate("Path containing ca certificates to match against host certificate")) o.optional = true o.placeholder = "/etc/ssl/certs" o = s:option(Flag, "certverify", translate("Verify all connection with SSL"), translate("Require SSL and make sure server CN matches hostname")) o.optional = true o.default = false end s = m:section(TypedSection, "master", translate("UPS Master")) s.optional = true s.addremove = true s.anonymous = true o = s:option(Value, "upsname", translate("Name of UPS"), translate("As configured by NUT")) o.optional = false o = s:option(Value, "hostname", translate("Hostname or address of UPS")) o.optional = false s.datatype = "host" o = s:option(Value, "port", translate("Port")) o.optional = true o.placeholder = 3493 o.datatype = "port" o = s:option(Value, "powervalue", translate("Power value")) o.optional = false o.datatype = "uinteger" o.default = 1 o = s:option(Value, "username", translate("Username")) o.optional = false o = s:option(Value, "password", translate("Password")) o.optional = false o.password = true s = m:section(TypedSection, "slave", translate("UPS Slave")) s.optional = true s.addremove = true s.anonymous = true o = s:option(Value, "upsname", translate("Name of UPS"), translate("As configured by NUT")) o.optional = false o = s:option(Value, "hostname", translate("Hostname or address of UPS")) o.optional = false s.datatype = "host" o = s:option(Value, "port", translate("Port")) o.optional = true o.placeholder = 3493 o.datatype = "port" o = s:option(Value, "powervalue", translate("Power value")) o.optional = false o.datatype = "uinteger" o.default = 1 o = s:option(Value, "username", translate("Username")) o.optional = false o = s:option(Value, "password", translate("Password")) o.optional = false o.password = true return m
apache-2.0
MustaphaTR/OpenRA
mods/ra/maps/evacuation/evacuation.lua
7
11136
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] DeathThreshold = { easy = 200, normal = 100, } TanyaType = "e7" if Difficulty ~= "easy" then TanyaType = "e7.noautotarget" end RepairTriggerThreshold = { easy = 50, normal = 75, } Sams = { Sam1, Sam2, Sam3, Sam4 } TownUnits = { Einstein, Engineer, TownUnit01, TownUnit02, TownUnit03, TownUnit04, TownUnit05, TownUnit06, TownUnit07, TownUnit08, TownUnit09, TownUnit10, TownUnit11, TownUnit12, TownUnit13, TownUnit14, } ParabombDelay = DateTime.Seconds(30) ParatroopersDelay = DateTime.Minutes(5) Paratroopers = { { proxy = "powerproxy.paras1", entry = BadgerEntryPoint1.Location, drop = BadgerDropPoint1.Location, }, { proxy = "powerproxy.paras2", entry = BadgerEntryPoint1.Location + CVec.New(3, 0), drop = BadgerDropPoint2.Location, }, { proxy = "powerproxy.paras2", entry = BadgerEntryPoint1.Location + CVec.New(6, 0), drop = BadgerDropPoint3.Location, }, } AttackGroup = { } AttackGroupSize = 5 SovietInfantry = { "e1", "e2", "e3" } SovietVehiclesUpgradeDelay = DateTime.Minutes(4) SovietVehicleType = "Normal" SovietVehicles = { Normal = { "3tnk" }, Upgraded = { "3tnk", "v2rl" }, } ProductionInterval = { easy = DateTime.Seconds(10), normal = DateTime.Seconds(2), } ReinforcementsDelay = DateTime.Minutes(16) ReinforcementsUnits = { "2tnk", "2tnk", "2tnk", "2tnk", "2tnk", "2tnk", "1tnk", "1tnk", "jeep", "e1", "e1", "e1", "e1", "e3", "e3", "mcv", "truk", "truk", "truk", "truk", "truk", "truk" } SpawnAlliedReinforcements = function() if allies2.IsLocalPlayer then UserInterface.SetMissionText("") Media.PlaySpeechNotification(allies2, "AlliedReinforcementsArrived") end Reinforcements.Reinforce(allies2, ReinforcementsUnits, { ReinforcementsEntryPoint.Location, Allies2BasePoint.Location }) end Yak = nil YakAttack = function() local targets = Map.ActorsInCircle(YakAttackPoint.CenterPosition, WDist.FromCells(10), function(a) return a.Owner == allies1 and not a.IsDead and a ~= Einstein and a ~= Tanya and a ~= Engineer and Yak.CanTarget(a) end) if (#targets > 0) then Yak.Attack(Utils.Random(targets)) end Yak.Move(Map.ClosestEdgeCell(Yak.Location)) Yak.Destroy() Trigger.OnRemovedFromWorld(Yak, function() Yak = nil end) end SovietTownAttack = function() local units = Utils.Shuffle(Utils.Where(Map.ActorsWithTag("TownAttacker"), function(a) return not a.IsDead end)) Utils.Do(Utils.Take(5, units), function(unit) unit.AttackMove(TownPoint.Location) Trigger.OnIdle(unit, unit.Hunt) end) end SendParabombs = function() local proxy = Actor.Create("powerproxy.parabombs", false, { Owner = soviets }) proxy.TargetAirstrike(ParabombPoint1.CenterPosition, (BadgerEntryPoint2.CenterPosition - ParabombPoint1.CenterPosition).Facing) proxy.TargetAirstrike(ParabombPoint2.CenterPosition, (Map.CenterOfCell(BadgerEntryPoint2.Location + CVec.New(0, 3)) - ParabombPoint2.CenterPosition).Facing) proxy.Destroy() end SendParatroopers = function() Utils.Do(Paratroopers, function(para) local proxy = Actor.Create(para.proxy, false, { Owner = soviets }) local target = Map.CenterOfCell(para.drop) local dir = target - Map.CenterOfCell(para.entry) local aircraft = proxy.TargetParatroopers(target, dir.Facing) Utils.Do(aircraft, function(a) Trigger.OnPassengerExited(a, function(t, p) IdleHunt(p) end) end) proxy.Destroy() end) end SendAttackGroup = function() if #AttackGroup < AttackGroupSize then return end Utils.Do(AttackGroup, function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end) AttackGroup = { } end ProduceInfantry = function() if SovietBarracks.IsDead or SovietBarracks.Owner ~= soviets then return end soviets.Build({ Utils.Random(SovietInfantry) }, function(units) table.insert(AttackGroup, units[1]) SendAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceInfantry) end) end ProduceVehicles = function() if SovietWarFactory.IsDead or SovietWarFactory.Owner ~= soviets then return end soviets.Build({ Utils.Random(SovietVehicles[SovietVehicleType]) }, function(units) table.insert(AttackGroup, units[1]) SendAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceVehicles) end) end NumBaseBuildings = function() local buildings = Map.ActorsInBox(AlliedBaseTopLeft.CenterPosition, AlliedBaseBottomRight.CenterPosition, function(a) return not a.IsDead and a.Owner == allies2 and a.HasProperty("StartBuildingRepairs") end) return #buildings end Tick = function() if DateTime.GameTime > 1 and DateTime.GameTime % 25 == 0 and NumBaseBuildings() == 0 then allies2.MarkFailedObjective(objHoldPosition) end if not allies2.IsObjectiveCompleted(objCutSovietPower) and soviets.PowerState ~= "Normal" then allies2.MarkCompletedObjective(objCutSovietPower) end if not allies2.IsObjectiveCompleted(objLimitLosses) and allies2.UnitsLost > DeathThreshold[Difficulty] then allies2.MarkFailedObjective(objLimitLosses) end if allies2.IsLocalPlayer and DateTime.GameTime <= ReinforcementsDelay then UserInterface.SetMissionText("Allied reinforcements arrive in " .. Utils.FormatTime(ReinforcementsDelay - DateTime.GameTime)) else UserInterface.SetMissionText("") end end SetupSoviets = function() soviets.Cash = 1000 if Difficulty == "easy" then Utils.Do(Sams, function(sam) local camera = Actor.Create("Camera.SAM", true, { Owner = allies1, Location = sam.Location }) Trigger.OnKilledOrCaptured(sam, function() camera.Destroy() end) end) end local buildings = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == soviets and self.HasProperty("StartBuildingRepairs") end) Utils.Do(buildings, function(actor) Trigger.OnDamaged(actor, function(building) if building.Owner == soviets and building.Health < (building.MaxHealth * RepairTriggerThreshold[Difficulty] / 100) then building.StartBuildingRepairs() end end) end) SovietBarracks.IsPrimaryBuilding = true SovietBarracks.RallyPoint = SovietRallyPoint.Location SovietWarFactory.IsPrimaryBuilding = true SovietWarFactory.RallyPoint = SovietRallyPoint.Location Trigger.AfterDelay(SovietVehiclesUpgradeDelay, function() SovietVehicleType = "Upgraded" end) Trigger.AfterDelay(0, function() ProduceInfantry() ProduceVehicles() end) end SetupTriggers = function() Trigger.OnKilled(Tanya, function() allies1.MarkFailedObjective(objTanyaMustSurvive) end) Trigger.OnAllKilledOrCaptured(Sams, function() allies1.MarkCompletedObjective(objDestroySamSites) objExtractEinstein = allies1.AddObjective("Wait for a helicopter at the LZ and extract Einstein.") Actor.Create("flare", true, { Owner = allies1, Location = ExtractionLZ.Location + CVec.New(1, -1) }) Beacon.New(allies1, ExtractionLZ.CenterPosition) Media.PlaySpeechNotification(allies1, "SignalFlareNorth") ExtractionHeli = Reinforcements.ReinforceWithTransport(allies1, "tran", nil, { ExtractionLZEntryPoint.Location, ExtractionLZ.Location })[1] Trigger.OnKilled(ExtractionHeli, function() allies1.MarkFailedObjective(objExtractEinstein) end) Trigger.OnPassengerEntered(ExtractionHeli, function(heli, passenger) if passenger == Einstein then heli.Move(ExtractionLZEntryPoint.Location) heli.Destroy() Trigger.OnRemovedFromWorld(heli, function() allies2.MarkCompletedObjective(objLimitLosses) allies2.MarkCompletedObjective(objHoldPosition) allies1.MarkCompletedObjective(objTanyaMustSurvive) allies1.MarkCompletedObjective(objEinsteinSurvival) allies1.MarkCompletedObjective(objExtractEinstein) end) end end) end) Trigger.OnEnteredProximityTrigger(TownPoint.CenterPosition, WDist.FromCells(15), function(actor, trigger) if actor.Owner == allies1 then ReassignActors(TownUnits, neutral, allies1) Utils.Do(TownUnits, function(a) a.Stance = "Defend" end) allies1.MarkCompletedObjective(objFindEinstein) objEinsteinSurvival = allies1.AddObjective("Keep Einstein alive at all costs.") Trigger.OnKilled(Einstein, function() allies1.MarkFailedObjective(objEinsteinSurvival) end) Trigger.RemoveProximityTrigger(trigger) SovietTownAttack() end end) Trigger.OnEnteredProximityTrigger(YakAttackPoint.CenterPosition, WDist.FromCells(5), function(actor, trigger) if not (Yak == nil or Yak.IsDead) or actor.Owner ~= allies1 then return end Yak = Actor.Create("yak", true, { Owner = soviets, Location = YakEntryPoint.Location, CenterPosition = YakEntryPoint.CenterPosition + WVec.New(0, 0, Actor.CruiseAltitude("yak")) }) Yak.Move(YakAttackPoint.Location + CVec.New(0, -10)) Yak.CallFunc(YakAttack) end) Trigger.AfterDelay(ParabombDelay, SendParabombs) Trigger.AfterDelay(ParatroopersDelay, SendParatroopers) Trigger.AfterDelay(ReinforcementsDelay, SpawnAlliedReinforcements) end SpawnTanya = function() Tanya = Actor.Create(TanyaType, true, { Owner = allies1, Location = TanyaLocation.Location }) if Difficulty ~= "easy" and allies1.IsLocalPlayer then Trigger.AfterDelay(DateTime.Seconds(2), function() Media.DisplayMessage("According to the rules of engagement I need your explicit orders to fire, Commander!", "Tanya") end) end end ReassignActors = function(actors, from, to) Utils.Do(actors, function(a) if a.Owner == from then a.Owner = to a.Stance = "Defend" end end) end WorldLoaded = function() neutral = Player.GetPlayer("Neutral") -- Allies is the pre-set owner of units that get assigned to either the second player, if any, or the first player otherwise. allies = Player.GetPlayer("Allies") -- Allies1 is the player starting on the right, controlling Tanya allies1 = Player.GetPlayer("Allies1") -- Allies2 is the player starting on the left, defending the base allies2 = Player.GetPlayer("Allies2") soviets = Player.GetPlayer("Soviets") Utils.Do({ allies1, allies2 }, function(player) if player and player.IsLocalPlayer then InitObjectives(player) end end) if not allies2 or allies2.IsLocalPlayer then Camera.Position = Allies2BasePoint.CenterPosition else Camera.Position = ChinookHusk.CenterPosition end if not allies2 then allies2 = allies1 end ReassignActors(Map.ActorsInWorld, allies, allies2) SpawnTanya() objTanyaMustSurvive = allies1.AddObjective("Tanya must survive.") objFindEinstein = allies1.AddObjective("Find Einstein's crashed helicopter.") objDestroySamSites = allies1.AddObjective("Destroy the SAM sites.") objHoldPosition = allies2.AddObjective("Hold your position and protect the base.") objLimitLosses = allies2.AddObjective("Do not lose more than " .. DeathThreshold[Difficulty] .. " units.", "Secondary", false) objCutSovietPower = allies2.AddObjective("Take out the Soviet power grid.", "Secondary", false) SetupTriggers() SetupSoviets() end
gpl-3.0
cvondrick/soundnet
main_train.lua
1
8577
require 'torch' require 'nn' require 'optim' -- to specify these at runtime, you can do, e.g.: -- $ lr=0.001 th main.lua opt = { dataset = 'audio', -- indicates what dataset load to use (in data.lua) nThreads = 40, -- how many threads to pre-fetch data batchSize = 64, -- self-explanatory loadSize = 22050*20, -- when loading images, resize first to this size fineSize = 22050*20, -- crop this size from the loaded image lr = 0.001, -- learning rate lambda = 250, beta1 = 0.9, -- momentum term for adam meanIter = 0, -- how many iterations to retrieve for mean estimation saveIter = 5000, -- write check point on this interval niter = 10000, -- number of iterations through dataset ntrain = math.huge, -- how big one epoch should be gpu = 1, -- which GPU to use; consider using CUDA_VISIBLE_DEVICES instead cudnn = 1, -- whether to use cudnn or not finetune = '', -- if set, will load this network instead of starting from scratch name = 'soundnet', -- the name of the experiment randomize = 1, -- whether to shuffle the data file or not display_port = 8001, -- port to push graphs display_id = 1, -- window ID when pushing graphs data_root = '/data/vision/torralba/crossmodal/flickr_videos/soundnet/mp3', label_binary_file = '/data/vision/torralba/crossmodal/soundnet/features/VGG16_IMNET_TRAIN_B%04d/prob', label2_binary_file = '/data/vision/torralba/crossmodal/soundnet/features/VGG16_PLACES2_TRAIN_B%04d/prob', label_text_file = '/data/vision/torralba/crossmodal/soundnet/lmdbs/train_frames4_%04d.txt', label_dim = 1000, label2_dim = 401, label_time_steps = 4, video_frame_time = 5, -- 5 seconds sample_rate = 22050, mean = 0, } -- one-line argument parser. parses enviroment variables to override the defaults for k,v in pairs(opt) do opt[k] = tonumber(os.getenv(k)) or os.getenv(k) or opt[k] end print(opt) torch.manualSeed(0) torch.setnumthreads(1) torch.setdefaulttensortype('torch.FloatTensor') -- if using GPU, select indicated one if opt.gpu > 0 then require 'cunn' cutorch.setDevice(opt.gpu) end -- create data loader local DataLoader = paths.dofile('data/data.lua') local data = DataLoader.new(opt.nThreads, opt.dataset, opt) print("Dataset: " .. opt.dataset, " Size: ", data:size()) -- define the model local net if opt.finetune == '' then -- build network from scratch -- SpatialConvolution is (nInputChannels, nOutputChannels, 1, kernelWidth, 1, stride, 0, padding) -- the constants are for the other dimension (which is unused) net = nn.Sequential() net:add(nn.SpatialConvolution(1, 16, 1,64, 1,2, 0,32)) net:add(nn.SpatialBatchNormalization(16)) net:add(nn.ReLU(true)) net:add(nn.SpatialMaxPooling(1,8, 1,8)) net:add(nn.SpatialConvolution(16, 32, 1,32, 1,2, 0,16)) net:add(nn.SpatialBatchNormalization(32)) net:add(nn.ReLU(true)) net:add(nn.SpatialMaxPooling(1,8, 1,8)) net:add(nn.SpatialConvolution(32, 64, 1,16, 1,2, 0,8)) net:add(nn.SpatialBatchNormalization(64)) net:add(nn.ReLU(true)) net:add(nn.SpatialConvolution(64, 128, 1,8, 1,2, 0,4)) net:add(nn.SpatialBatchNormalization(128)) net:add(nn.ReLU(true)) net:add(nn.SpatialConvolution(128, 256, 1,4, 1,2, 0,2)) net:add(nn.SpatialBatchNormalization(256)) net:add(nn.ReLU(true)) net:add(nn.SpatialMaxPooling(1,4, 1,4)) net:add(nn.SpatialConvolution(256, 512, 1,4, 1,2, 0,2)) net:add(nn.SpatialBatchNormalization(512)) net:add(nn.ReLU(true)) net:add(nn.SpatialConvolution(512, 1024, 1,4, 1,2, 0,2)) net:add(nn.SpatialBatchNormalization(1024)) net:add(nn.ReLU(true)) net:add(nn.ConcatTable():add(nn.SpatialConvolution(1024, 1000, 1,8, 1,2, 0,0)) :add(nn.SpatialConvolution(1024, 401, 1,8, 1,2, 0,0))) net:add(nn.ParallelTable():add(nn.SplitTable(3)):add(nn.SplitTable(3))) net:add(nn.FlattenTable()) local output_net = nn.ParallelTable() -- There is a loop over 8 because SoundNet predicts 2 distributions (objects, scenes) for every 5 seconds. -- The input is 20 seconds. So, this means there are 2 * 20 / 5 = 8 output distributions. for i=1,8 do output_net:add(nn.Sequential():add(nn.Contiguous()):add(nn.LogSoftMax()):add(nn.Squeeze())) end net:add(output_net) -- initialize the model local function weights_init(m) local name = torch.type(m) if name:find('Convolution') then m.weight:normal(0.0, 0.01) m.bias:fill(0) elseif name:find('BatchNormalization') then if m.weight then m.weight:normal(1.0, 0.02) end if m.bias then m.bias:fill(0) end end end net:apply(weights_init) -- loop over all layers, applying weights_init else -- load in existing network print('loading ' .. opt.finetune) net = torch.load(opt.finetune) end print(net) -- define the loss local criterion = nn.ParallelCriterion(false) for i=1,8 do criterion:add(nn.DistKLDivCriterion()) end -- create the data placeholders local input = torch.Tensor(opt.batchSize, 1, opt.fineSize, 1) local labels = {} for i=1,opt.label_time_steps do labels[i] = torch.Tensor(opt.batchSize, 1000) end for i=1,opt.label_time_steps do labels[opt.label_time_steps+i] = torch.Tensor(opt.batchSize, 401) end local err -- timers to roughly profile performance local tm = torch.Timer() local data_tm = torch.Timer() -- ship everything to GPU if needed if opt.gpu > 0 then input = input:cuda() for i=1,#labels do labels[i] = labels[i]:cuda() end net:cuda() criterion:cuda() end -- conver to cudnn if needed if opt.gpu > 0 and opt.cudnn > 0 then require 'cudnn' net = cudnn.convert(net, cudnn) end -- get a vector of parameters local parameters, gradParameters = net:getParameters() -- show graphics disp = require 'display' disp.url = 'http://localhost:' .. opt.display_port .. '/events' -- optimization closure -- the optimizer will call this function to get the gradients local data_im,data_label,data_extra local fx = function(x) gradParameters:zero() -- fetch data data_tm:reset(); data_tm:resume() data_im,data_label,data_label2,data_extra = data:getBatch() data_tm:stop() -- ship data to GPU input:copy(data_im:view(opt.batchSize, 1, opt.fineSize, 1)) for i=1,opt.label_time_steps do labels[i]:copy(data_label:select(3,i)) end for i=1,opt.label_time_steps do labels[opt.label_time_steps+i]:copy(data_label2:select(3,i)) end -- forward, backwards local output = net:forward(input) err = criterion:forward(output, labels) / #labels * opt.lambda local df_do = criterion:backward(output, labels) for i=1,#labels do df_do[i]:mul(opt.lambda / #labels) end net:backward(input, df_do) -- return gradients return err, gradParameters end local counter = 0 local history = {} -- parameters for the optimization -- very important: you must only create this table once! -- the optimizer will add fields to this table (such as momentum) local optimState = { learningRate = opt.lr, beta1 = opt.beta1, } -- train main loop for epoch = 1,opt.niter do -- for each epoch for i = 1, math.min(data:size(), opt.ntrain), opt.batchSize do -- for each mini-batch collectgarbage() -- necessary sometimes tm:reset() -- do one iteration optim.adam(fx, parameters, optimState) -- logging if counter % 10 == 0 then table.insert(history, {counter, err}) disp.plot(history, {win=opt.display_id+1, title=opt.name, labels = {"iteration", "err"}}) local w = net.modules[1].weight:clone():float():squeeze() disp.image(w, {win=opt.display_id+30, title=("conv1 min: %.4f, max: %.4f"):format(w:min(), w:max())}) end counter = counter + 1 print(('%s: Iteration: [%d]\t Time: %.3f DataTime: %.3f ' .. ' Err: %.4f'):format( opt.name, counter, tm:time().real, data_tm:time().real, err and err or -1)) -- save checkpoint -- :clearState() compacts the model so it takes less space on disk if counter % opt.saveIter == 0 then print('Saving ' .. opt.name .. '/iter' .. counter .. '_net.t7') paths.mkdir('checkpoints') paths.mkdir('checkpoints/' .. opt.name) torch.save('checkpoints/' .. opt.name .. '/iter' .. counter .. '_net.t7', net:clearState()) --torch.save('checkpoints/' .. opt.name .. '/iter' .. counter .. '_optim.t7', optimState) torch.save('checkpoints/' .. opt.name .. '/iter' .. counter .. '_history.t7', history) end end end
mit
bsmr-games/lipsofsuna
data/lipsofsuna/main/messaging.lua
1
6978
--- Implements communications between the server and the client. -- -- Lips of Suna is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. -- -- @module main.messaging -- @alias Messaging local Class = require("system/class") local Message = require("main/message") local Network = require("system/network") local Packet = require("system/packet") --- Implements communications between the server and the client. -- @type Messaging local Messaging = Class("Messaging") --- Creates a new messaging system. -- @param clss Messaging class. -- @return Messaging. Messaging.new = function(clss) local self = Class.new(clss) self.next_id = 1 self.dict_id = {} self.dict_name = {} self.local_server = false self.local_client = false self.networking = false return self end --- Client sends a message to the server. -- -- If the server is run in the same process, the message is passed to it -- directly. Otherwise, it is encoded and sent over the network. -- -- @param self Messaging. -- @param type Message name. -- @param ... Message arguments. Messaging.client_event = function(self, type, ...) -- Get the message handler. local handler = self.dict_name[type] if not handler then return end assert(handler.client_to_server_encode) assert(handler.client_to_server_decode) assert(handler.client_to_server_handle) -- Handle the message. if self.local_server then handler.client_to_server_handle(self, -1, ...) else if not self.networking then error("tried to send remote event without connection to a remote server") end local args = handler.client_to_server_encode(self, ...) if not args then return end if handler.client_to_server_predict and not Server.initialized then handler.client_to_server_predict(self, ...) end if args.class == Packet then Network:send{packet = args} else Network:send{packet = Packet(handler.id, unpack(args))} end end end --- Registers a new message type. -- @param self Messaging. -- @param args Message arguments. Messaging.register_message = function(self, args) -- Argument validation. assert(type(args.name) == "string") assert(args.name ~= "") assert(self.dict_name[args.name] == nil) assert(args.client_to_server_handle or args.server_to_client_handle) if args.client_to_server_handle ~= nil then assert(type(args.client_to_server_handle) == "function") assert(type(args.client_to_server_encode) == "function") assert(type(args.client_to_server_decode) == "function") else assert(type(args.client_to_server_handle) == "nil") assert(type(args.client_to_server_encode) == "nil") assert(type(args.client_to_server_decode) == "nil") assert(type(args.client_to_server_predict) == "nil") end if args.server_to_client_handle ~= nil then assert(type(args.server_to_client_handle) == "function") assert(type(args.server_to_client_encode) == "function") assert(type(args.server_to_client_decode) == "function") else assert(type(args.server_to_client_handle) == "nil") assert(type(args.server_to_client_encode) == "nil") assert(type(args.server_to_client_decode) == "nil") assert(type(args.server_to_client_predict) == "nil") end -- Create the message. local msg = Message(self.next_id, args) self.next_id = self.next_id + 1 self.dict_id[msg.id] = msg self.dict_name[msg.name] = msg end --- Server sends a message to an individual client. -- -- If the client is run in the same process, the message is passed to it -- directly. Otherwise, it is encoded and sent over the network. -- -- @param self Messaging. -- @param type Message name. -- @param client Client ID. -- @param ... Message arguments. Messaging.server_event = function(self, type, client, ...) if not client then return end -- Get the message handler. local handler = self.dict_name[type] if not handler then return end assert(handler.server_to_client_encode) assert(handler.server_to_client_decode) assert(handler.server_to_client_handle) -- Handle the message. if client == -1 then if not self.local_client then error("tried to send local event without local client") end handler.server_to_client_handle(self, ...) else if not self.networking then error("tried to send remote event without hosting a networked server") end local args = handler.server_to_client_encode(self, ...) if not args then return end if args.class == Packet then Network:send{client = client, packet = args} else Network:send{client = client, packet = Packet(handler.id, unpack(args))} end end end --- Server sends a message to all clients. -- @param self Messaging. -- @param type Message name. -- @param ... Message arguments. Messaging.server_event_broadcast = function(self, type, ...) if self.local_client then self:server_event(type, -1, ...) end if self.networking then for k,v in pairs(Network:get_clients()) do self:server_event(type, v, ...) end end end --- Handles a received message. -- @param self Messaging. -- @param client Client ID. Nil if received by the client. -- @param package Message packet. Messaging.handle_packet = function(self, client, packet) -- Get the message handler. local handler = self.dict_id[packet:get_type()] if not handler then return end -- Handle the message. if client then if not self.local_server then error("received unexpected server packet") end local args = handler.client_to_server_decode(self, packet) if not args then print(string.format("WARNING: Failed to decode message %s from client", handler.name)) return end handler.client_to_server_handle(self, client, unpack(args)) else if not self.local_client then --error("received unexpected client packet") return end local args = handler.server_to_client_decode(self, packet) if not args then print(string.format("WARNING: Failed to decode message %s from server", handler.name)) return end handler.server_to_client_handle(self, unpack(args)) end end --- Gets the ID of the message of the given type. -- @param self Messaging. -- @param type Message name. -- @return Message ID if found. Nil otherwise. Messaging.get_event_id = function(self, type) local handler = self.dict_name[type] if not handler then return end return handler.id end --- Sets the transmission mode. -- @param self Messaging. -- @param local_server True if a local server is running. False otherwise. -- @param local_client True if a local client is connected. False otherwise. -- @param port Port number if remote clients may connect. Nil otherwise. Messaging.set_transmit_mode = function(self, local_server, local_client, port) self.local_server = local_server self.local_client = local_client if port then self.networking = true Network:host{port = port} else self.networking = false Network:shutdown() end end return Messaging
gpl-3.0
Hzj-jie/koreader-base
spec/unit/md5_spec.lua
4
1050
describe("MD5 module", function() local md5 setup(function() md5 = require("ffi/MD5") end) it("should calculate correct MD5 hashes", function() assert.is_equal(md5.sum(""), "d41d8cd98f00b204e9800998ecf8427e") assert.is_equal(md5.new():sum("\0"), "93b885adfe0da089cdf634904fd59f71") assert.is_equal(md5.new():sum("0123456789abcdefX"), "1b05aba914a8b12315c7ee52b42f3d35") end) it("should calculate MD5 sum by updating", function() local m = md5.new() m:update("0123456789") m:update("abcdefghij") assert.is_equal(m:sum(), md5.sum("0123456789abcdefghij")) end) it("should calculate MD5 sum of a file", function() assert.is_equal( md5.sumFile("spec/base/unit/data/2col.jbig2.pdf"), "ee53c8f032c3d047cb3d1999c8ff5e09") end) it("should error out on non-exist file", function() local ok, err = md5.sumFile("foo/bar/abc/123/baz.pdf") assert.is.falsy(ok) assert.is_not_nil(err) end) end)
agpl-3.0
dismantl/luci-0.12
applications/luci-statistics/luasrc/model/cbi/luci_statistics/ping.lua
80
1397
--[[ Luci configuration model for statistics - collectd ping plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("Ping Plugin Configuration"), translate( "The ping plugin will send icmp echo replies to selected " .. "hosts and measure the roundtrip time for each host." )) -- collectd_ping config section s = m:section( NamedSection, "collectd_ping", "luci_statistics" ) -- collectd_ping.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_ping.hosts (Host) hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space.")) hosts.default = "127.0.0.1" hosts:depends( "enable", 1 ) -- collectd_ping.ttl (TTL) ttl = s:option( Value, "TTL", translate("TTL for ping packets") ) ttl.isinteger = true ttl.default = 128 ttl:depends( "enable", 1 ) -- collectd_ping.interval (Interval) interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") ) interval.isinteger = true interval.default = 30 interval:depends( "enable", 1 ) return m
apache-2.0
qq779089973/ramod
luci/applications/luci-statistics/luasrc/model/cbi/luci_statistics/ping.lua
80
1397
--[[ Luci configuration model for statistics - collectd ping plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("Ping Plugin Configuration"), translate( "The ping plugin will send icmp echo replies to selected " .. "hosts and measure the roundtrip time for each host." )) -- collectd_ping config section s = m:section( NamedSection, "collectd_ping", "luci_statistics" ) -- collectd_ping.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_ping.hosts (Host) hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space.")) hosts.default = "127.0.0.1" hosts:depends( "enable", 1 ) -- collectd_ping.ttl (TTL) ttl = s:option( Value, "TTL", translate("TTL for ping packets") ) ttl.isinteger = true ttl.default = 128 ttl:depends( "enable", 1 ) -- collectd_ping.interval (Interval) interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") ) interval.isinteger = true interval.default = 30 interval:depends( "enable", 1 ) return m
mit
bsmr-games/lipsofsuna
data/lipsofsuna/core/messaging/messages/walk.lua
1
1130
-- Lips of Suna is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. Main.messaging:register_message{ name = "walk", client_to_server_predict = function(self, value) local o = Client.player_object if not o then return end if not o.prediction then return end local vel = o:get_rotation() * Vector(0,0,-1) * (value * o.spec.speed_walk) o.prediction:set_target_velocity(vel) end, client_to_server_encode = function(self, value) return {"int8", value * 127} end, client_to_server_decode = function(self, packet) local ok,value = packet:read("int8") if not ok then return end return {value / 127} end, client_to_server_handle = function(self, client, value) local player = Server:get_player_by_client(client) if not player then return end if player.dead then return end if value > 0 then player:set_movement(1) elseif value < 0 then player:set_movement(-1) else player:set_movement(0) end end}
gpl-3.0
ramindel0761/setdelete
libs/fakeredis.lua
650
40405
local unpack = table.unpack or unpack --- Bit operations local ok,bit if _VERSION == "Lua 5.3" then bit = (load [[ return { band = function(x, y) return x & y end, bor = function(x, y) return x | y end, bxor = function(x, y) return x ~ y end, bnot = function(x) return ~x end, rshift = function(x, n) return x >> n end, lshift = function(x, n) return x << n end, } ]])() else ok,bit = pcall(require,"bit") if not ok then bit = bit32 end end assert(type(bit) == "table", "module for bitops not found") --- default sleep local default_sleep do local ok, mod = pcall(require, "socket") if ok and type(mod) == "table" then default_sleep = mod.sleep else default_sleep = function(n) local t0 = os.clock() while true do local delta = os.clock() - t0 if (delta < 0) or (delta > n) then break end end end end end --- Helpers local xdefv = function(ktype) if ktype == "list" then return {head = 0, tail = 0} elseif ktype == "zset" then return { list = {}, set = {}, } else return {} end end local xgetr = function(self, k, ktype) if self.data[k] then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) assert(self.data[k].value) return self.data[k].value else return xdefv(ktype) end end local xgetw = function(self, k, ktype) if self.data[k] and self.data[k].value then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) else self.data[k] = {ktype = ktype, value = xdefv(ktype)} end return self.data[k].value end local empty = function(self, k) local v, t = self.data[k].value, self.data[k].ktype if t == nil then return true elseif t == "string" then return not v[1] elseif (t == "hash") or (t == "set") then for _,_ in pairs(v) do return false end return true elseif t == "list" then return v.head == v.tail elseif t == "zset" then if #v.list == 0 then for _,_ in pairs(v.set) do error("incoherent") end return true else for _,_ in pairs(v.set) do return(false) end error("incoherent") end else error("unsupported") end end local cleanup = function(self, k) if empty(self, k) then self.data[k] = nil end end local is_integer = function(x) return (type(x) == "number") and (math.floor(x) == x) end local overflows = function(n) return (n > 2^53-1) or (n < -2^53+1) end local is_bounded_integer = function(x) return (is_integer(x) and (not overflows(x))) end local is_finite_number = function(x) return (type(x) == "number") and (x > -math.huge) and (x < math.huge) end local toint = function(x) if type(x) == "string" then x = tonumber(x) end return is_bounded_integer(x) and x or nil end local tofloat = function(x) if type(x) == "number" then return x end if type(x) ~= "string" then return nil end local r = tonumber(x) if r then return r end if x == "inf" or x == "+inf" then return math.huge elseif x == "-inf" then return -math.huge else return nil end end local tostr = function(x) if is_bounded_integer(x) then return string.format("%d", x) else return tostring(x) end end local char_bitcount = function(x) assert( (type(x) == "number") and (math.floor(x) == x) and (x >= 0) and (x < 256) ) local n = 0 while x ~= 0 do x = bit.band(x, x-1) n = n+1 end return n end local chkarg = function(x) if type(x) == "number" then x = tostr(x) end assert(type(x) == "string") return x end local chkargs = function(n, ...) local arg = {...} assert(#arg == n) for i=1,n do arg[i] = chkarg(arg[i]) end return unpack(arg) end local getargs = function(...) local arg = {...} local n = #arg; assert(n > 0) for i=1,n do arg[i] = chkarg(arg[i]) end return arg end local getargs_as_map = function(...) local arg, r = getargs(...), {} assert(#arg%2 == 0) for i=1,#arg,2 do r[arg[i]] = arg[i+1] end return r end local chkargs_wrap = function(f, n) assert( (type(f) == "function") and (type(n) == "number") ) return function(self, ...) return f(self, chkargs(n, ...)) end end local lset_to_list = function(s) local r = {} for v,_ in pairs(s) do r[#r+1] = v end return r end local nkeys = function(x) local r = 0 for _,_ in pairs(x) do r = r + 1 end return r end --- Commands -- keys local del = function(self, ...) local arg = getargs(...) local r = 0 for i=1,#arg do if self.data[arg[i]] then r = r + 1 end self.data[arg[i]] = nil end return r end local exists = function(self, k) return not not self.data[k] end local keys = function(self, pattern) assert(type(pattern) == "string") -- We want to convert the Redis pattern to a Lua pattern. -- Start by escaping dashes *outside* character classes. -- We also need to escape percents here. local t, p, n = {}, 1, #pattern local p1, p2 while true do p1, p2 = pattern:find("%[.+%]", p) if p1 then if p1 > p then t[#t+1] = {true, pattern:sub(p, p1-1)} end t[#t+1] = {false, pattern:sub(p1, p2)} p = p2+1 if p > n then break end else t[#t+1] = {true, pattern:sub(p, n)} break end end for i=1,#t do if t[i][1] then t[i] = t[i][2]:gsub("[%%%-]", "%%%0") else t[i] = t[i][2]:gsub("%%", "%%%%") end end -- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]' -- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is. -- Wrap in '^$' to enforce bounds. local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0") :gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$" local r = {} for k,_ in pairs(self.data) do if k:match(lp) then r[#r+1] = k end end return r end local _type = function(self, k) return self.data[k] and self.data[k].ktype or "none" end local randomkey = function(self) local ks = lset_to_list(self.data) local n = #ks if n > 0 then return ks[math.random(1, n)] else return nil end end local rename = function(self, k, k2) assert((k ~= k2) and self.data[k]) self.data[k2] = self.data[k] self.data[k] = nil return true end local renamenx = function(self, k, k2) if self.data[k2] then return false else return rename(self, k, k2) end end -- strings local getrange, incrby, set local append = function(self, k, v) local x = xgetw(self, k, "string") x[1] = (x[1] or "") .. v return #x[1] end local bitcount = function(self, k, i1, i2) k = chkarg(k) local s if i1 or i2 then assert(i1 and i2, "ERR syntax error") s = getrange(self, k, i1, i2) else s = xgetr(self, k, "string")[1] or "" end local r, bytes = 0,{s:byte(1, -1)} for i=1,#bytes do r = r + char_bitcount(bytes[i]) end return r end local bitop = function(self, op, k, ...) assert(type(op) == "string") op = op:lower() assert( (op == "and") or (op == "or") or (op == "xor") or (op == "not"), "ERR syntax error" ) k = chkarg(k) local arg = {...} local good_arity = (op == "not") and (#arg == 1) or (#arg > 0) assert(good_arity, "ERR wrong number of arguments for 'bitop' command") local l, vals = 0, {} local s for i=1,#arg do s = xgetr(self, arg[i], "string")[1] or "" if #s > l then l = #s end vals[i] = s end if l == 0 then del(self, k) return 0 end local vector_mt = {__index=function() return 0 end} for i=1,#vals do vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt) end local r = {} if op == "not" then assert(#vals[1] == l) for i=1,l do r[i] = bit.band(bit.bnot(vals[1][i]), 0xff) end else local _op = bit["b" .. op] for i=1,l do local t = {} for j=1,#vals do t[j] = vals[j][i] end r[i] = _op(unpack(t)) end end set(self, k, string.char(unpack(r))) return l end local decr = function(self, k) return incrby(self, k, -1) end local decrby = function(self, k, n) n = toint(n) assert(n, "ERR value is not an integer or out of range") return incrby(self, k, -n) end local get = function(self, k) local x = xgetr(self, k, "string") return x[1] end local getbit = function(self, k, offset) k = chkarg(k) offset = toint(offset) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" if bytepos >= #s then return 0 end local char = s:sub(bytepos+1, bytepos+1):byte() return bit.band(bit.rshift(char, 7-bitpos), 1) end getrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetr(self, k, "string") x = x[1] or "" if i1 >= 0 then i1 = i1 + 1 end if i2 >= 0 then i2 = i2 + 1 end return x:sub(i1, i2) end local getset = function(self, k, v) local r = get(self, k) set(self, k, v) return r end local incr = function(self, k) return incrby(self, k, 1) end incrby = function(self, k, n) k, n = chkarg(k), toint(n) assert(n, "ERR value is not an integer or out of range") local x = xgetw(self, k, "string") local i = toint(x[1] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[1] = tostr(i) return i end local incrbyfloat = function(self, k, n) k, n = chkarg(k), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "string") local i = tofloat(x[1] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[1] = tostr(i) return i end local mget = function(self, ...) local arg, r = getargs(...), {} for i=1,#arg do r[i] = get(self, arg[i]) end return r end local mset = function(self, ...) local argmap = getargs_as_map(...) for k,v in pairs(argmap) do set(self, k, v) end return true end local msetnx = function(self, ...) local argmap = getargs_as_map(...) for k,_ in pairs(argmap) do if self.data[k] then return false end end for k,v in pairs(argmap) do set(self, k, v) end return true end set = function(self, k, v) self.data[k] = {ktype = "string", value = {v}} return true end local setbit = function(self, k, offset, b) k = chkarg(k) offset, b = toint(offset), toint(b) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) assert( (b == 0) or (b == 1), "ERR bit is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" local pad = {s} for i=2,bytepos+2-#s do pad[i] = "\0" end s = table.concat(pad) assert(#s >= bytepos+1) local before = s:sub(1, bytepos) local char = s:sub(bytepos+1, bytepos+1):byte() local after = s:sub(bytepos+2, -1) local old = bit.band(bit.rshift(char, 7-bitpos), 1) if b == 1 then char = bit.bor(bit.lshift(1, 7-bitpos), char) else char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char) end local r = before .. string.char(char) .. after set(self, k, r) return old end local setnx = function(self, k, v) if self.data[k] then return false else return set(self, k, v) end end local setrange = function(self, k, i, s) local k, s = chkargs(2, k, s) i = toint(i) assert(i and (i >= 0)) local x = xgetw(self, k, "string") local y = x[1] or "" local ly, ls = #y, #s if i > ly then -- zero padding local t = {} for i=1, i-ly do t[i] = "\0" end y = y .. table.concat(t) .. s else y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly) end x[1] = y return #y end local strlen = function(self, k) local x = xgetr(self, k, "string") return x[1] and #x[1] or 0 end -- hashes local hdel = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local r = 0 local x = xgetw(self, k, "hash") for i=1,#arg do if x[arg[i]] then r = r + 1 end x[arg[i]] = nil end cleanup(self, k) return r end local hget local hexists = function(self, k, k2) return not not hget(self, k, k2) end hget = function(self, k, k2) local x = xgetr(self, k, "hash") return x[k2] end local hgetall = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,v in pairs(x) do r[_k] = v end return r end local hincrby = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), toint(n) assert(n, "ERR value is not an integer or out of range") assert(type(n) == "number") local x = xgetw(self, k, "hash") local i = toint(x[k2] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[k2] = tostr(i) return i end local hincrbyfloat = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "hash") local i = tofloat(x[k2] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[k2] = tostr(i) return i end local hkeys = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,_ in pairs(x) do r[#r+1] = _k end return r end local hlen = function(self, k) local x = xgetr(self, k, "hash") return nkeys(x) end local hmget = function(self, k, k2s) k = chkarg(k) assert((type(k2s) == "table")) local r = {} local x = xgetr(self, k, "hash") for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end return r end local hmset = function(self, k, ...) k = chkarg(k) local arg = {...} if type(arg[1]) == "table" then assert(#arg == 1) local x = xgetw(self, k, "hash") for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end else assert(#arg % 2 == 0) local x = xgetw(self, k, "hash") local t = getargs(...) for i=1,#t,2 do x[t[i]] = t[i+1] end end return true end local hset = function(self, k, k2, v) local x = xgetw(self, k, "hash") local r = not x[k2] x[k2] = v return r end local hsetnx = function(self, k, k2, v) local x = xgetw(self, k, "hash") if x[k2] == nil then x[k2] = v return true else return false end end local hvals = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _,v in pairs(x) do r[#r+1] = v end return r end -- lists (head = left, tail = right) local _l_real_i = function(x, i) if i < 0 then return x.tail+i+1 else return x.head+i+1 end end local _l_len = function(x) return x.tail - x.head end local _block_for = function(self, timeout) if timeout > 0 then local sleep = self.sleep or default_sleep if type(sleep) == "function" then sleep(timeout) else error("sleep function unavailable", 0) end else error("operation would block", 0) end end local rpoplpush local blpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpoplpush = function(self, k1, k2, timeout) k1, k2 = chkargs(2, k1, k2) timeout = toint(timeout) if not self.data[k1] then _block_for(self, timeout) end return rpoplpush(self, k1, k2) end local lindex = function(self, k, i) k = chkarg(k) i = assert(toint(i)) local x = xgetr(self, k, "list") return x[_l_real_i(x, i)] end local linsert = function(self, k, mode, pivot, v) mode = mode:lower() assert((mode == "before") or (mode == "after")) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local p = nil for i=x.head+1, x.tail do if x[i] == pivot then p = i break end end if not p then return -1 end if mode == "after" then for i=x.head+1, p do x[i-1] = x[i] end x.head = x.head - 1 else for i=x.tail, p, -1 do x[i+1] = x[i] end x.tail = x.tail + 1 end x[p] = v return _l_len(x) end local llen = function(self, k) local x = xgetr(self, k, "list") return _l_len(x) end local lpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return r end local lpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x[x.head] = vs[i] x.head = x.head - 1 end return _l_len(x) end local lpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x[x.head] = v x.head = x.head - 1 return _l_len(x) end local lrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x, r = xgetr(self, k, "list"), {} i1 = math.max(_l_real_i(x, i1), x.head+1) i2 = math.min(_l_real_i(x, i2), x.tail) for i=i1,i2 do r[#r+1] = x[i] end return r end local _lrem_i = function(x, p) for i=p,x.tail do x[i] = x[i+1] end x.tail = x.tail - 1 end local _lrem_l = function(x, v, s) assert(v) if not s then s = x.head+1 end for i=s,x.tail do if x[i] == v then _lrem_i(x, i) return i end end return false end local _lrem_r = function(x, v, s) assert(v) if not s then s = x.tail end for i=s,x.head+1,-1 do if x[i] == v then _lrem_i(x, i) return i end end return false end local lrem = function(self, k, count, v) k, v = chkarg(k), chkarg(v) count = assert(toint(count)) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local n, last = 0, nil local op = (count < 0) and _lrem_r or _lrem_l local limited = (count ~= 0) count = math.abs(count) while true do last = op(x, v, last) if last then n = n+1 if limited then count = count - 1 if count == 0 then break end end else break end end return n end local lset = function(self, k, i, v) k, v = chkarg(k), chkarg(v) i = assert(toint(i)) if not self.data[k] then error("ERR no such key") end local x = xgetw(self, k, "list") local l = _l_len(x) if i >= l or i < -l then error("ERR index out of range") end x[_l_real_i(x, i)] = v return true end local ltrim = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetw(self, k, "list") i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2) for i=x.head+1,i1-1 do x[i] = nil end for i=i2+1,x.tail do x[i] = nil end x.head = math.max(i1-1, x.head) x.tail = math.min(i2, x.tail) assert( (x[x.head] == nil) and (x[x.tail+1] == nil) ) cleanup(self, k) return true end local rpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return r end rpoplpush = function(self, k1, k2) local v = rpop(self, k1) if not v then return nil end lpush(self, k2, v) return v end local rpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x.tail = x.tail + 1 x[x.tail] = vs[i] end return _l_len(x) end local rpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x.tail = x.tail + 1 x[x.tail] = v return _l_len(x) end -- sets local sadd = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if not x[arg[i]] then x[arg[i]] = true r = r + 1 end end return r end local scard = function(self, k) local x = xgetr(self, k, "set") return nkeys(x) end local _sdiff = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} for v,_ in pairs(x) do r[v] = true end for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = nil end end return r end local sdiff = function(self, k, ...) return lset_to_list(_sdiff(self, k, ...)) end local sdiffstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sdiff(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local _sinter = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} local y for v,_ in pairs(x) do r[v] = true for i=1,#arg do y = xgetr(self, arg[i], "set") if not y[v] then r[v] = nil; break end end end return r end local sinter = function(self, k, ...) return lset_to_list(_sinter(self, k, ...)) end local sinterstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sinter(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local sismember = function(self, k, v) local x = xgetr(self, k, "set") return not not x[v] end local smembers = function(self, k) local x = xgetr(self, k, "set") return lset_to_list(x) end local smove = function(self, k, k2, v) local x = xgetr(self, k, "set") if x[v] then local y = xgetw(self, k2, "set") x[v] = nil y[v] = true return true else return false end end local spop = function(self, k) local x, r = xgetw(self, k, "set"), nil local l = lset_to_list(x) local n = #l if n > 0 then r = l[math.random(1, n)] x[r] = nil end cleanup(self, k) return r end local srandmember = function(self, k, count) k = chkarg(k) local x = xgetr(self, k, "set") local l = lset_to_list(x) local n = #l if not count then if n > 0 then return l[math.random(1, n)] else return nil end end count = toint(count) if (count == 0) or (n == 0) then return {} end if count >= n then return l end local r = {} if count > 0 then -- distinct elements for i=0,count-1 do r[#r+1] = table.remove(l, math.random(1, n-i)) end else -- allow repetition for i=1,-count do r[#r+1] = l[math.random(1, n)] end end return r end local srem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if x[arg[i]] then x[arg[i]] = nil r = r + 1 end end cleanup(self, k) return r end local _sunion = function(self, ...) local arg = getargs(...) local r = {} local x for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = true end end return r end local sunion = function(self, k, ...) return lset_to_list(_sunion(self, k, ...)) end local sunionstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sunion(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end -- zsets local _z_p_mt = { __eq = function(a, b) if a.v == b.v then assert(a.s == b.s) return true else return false end end, __lt = function(a, b) if a.s == b.s then return (a.v < b.v) else return (a.s < b.s) end end, } local _z_pair = function(s, v) assert( (type(s) == "number") and (type(v) == "string") ) local r = {s = s, v = v} return setmetatable(r, _z_p_mt) end local _z_pairs = function(...) local arg = {...} assert((#arg > 0) and (#arg % 2 == 0)) local ps = {} for i=1,#arg,2 do ps[#ps+1] = _z_pair( assert(tofloat(arg[i])), chkarg(arg[i+1]) ) end return ps end local _z_insert = function(x, ix, p) assert( (type(x) == "table") and (type(ix) == "number") and (type(p) == "table") ) local l = x.list table.insert(l, ix, p) for i=ix+1,#l do x.set[l[i].v] = x.set[l[i].v] + 1 end x.set[p.v] = ix end local _z_remove = function(x, v) if not x.set[v] then return false end local l, ix = x.list, x.set[v] assert(l[ix].v == v) table.remove(l, ix) for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - 1 end x.set[v] = nil return true end local _z_remove_range = function(x, i1, i2) local l = x.list i2 = i2 or i1 assert( (i1 > 0) and (i2 >= i1) and (i2 <= #l) ) local ix, n = i1, i2-i1+1 for i=1,n do x.set[l[ix].v] = nil table.remove(l, ix) end for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - n end return n end local _z_update = function(x, p) local l = x.list local found = _z_remove(x, p.v) local ix = nil for i=1,#l do if l[i] > p then ix = i; break end end if not ix then ix = #l+1 end _z_insert(x, ix, p) return found end local _z_coherence = function(x) local l, s = x.list, x.set local found, n = {}, 0 for val,pos in pairs(s) do if found[pos] then return false end found[pos] = true n = n + 1 if not (l[pos] and (l[pos].v == val)) then return false end end if #l ~= n then return false end for i=1, n-1 do if l[i].s > l[i+1].s then return false end end return true end local _z_normrange = function(l, i1, i2) i1, i2 = assert(toint(i1)), assert(toint(i2)) if i1 < 0 then i1 = #l+i1 end if i2 < 0 then i2 = #l+i2 end i1, i2 = math.max(i1+1, 1), i2+1 if (i2 < i1) or (i1 > #l) then return nil end i2 = math.min(i2, #l) return i1, i2 end local _zrbs_opts = function(...) local arg = {...} if #arg == 0 then return {} end local ix, opts = 1, {} while type(arg[ix]) == "string" do if arg[ix] == "withscores" then opts.withscores = true ix = ix + 1 elseif arg[ix] == "limit" then opts.limit = { offset = assert(toint(arg[ix+1])), count = assert(toint(arg[ix+2])), } ix = ix + 3 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.withscores = opts.withscores or _o.withscores if _o.limit then opts.limit = { offset = assert(toint(_o.limit.offset or _o.limit[1])), count = assert(toint(_o.limit.count or _o.limit[2])), } end ix = ix + 1 end assert(arg[ix] == nil) if opts.limit then assert( (opts.limit.count >= 0) and (opts.limit.offset >= 0) ) end return opts end local _z_store_params = function(dest, numkeys, ...) dest = chkarg(dest) numkeys = assert(toint(numkeys)) assert(numkeys > 0) local arg = {...} assert(#arg >= numkeys) local ks = {} for i=1, numkeys do ks[i] = chkarg(arg[i]) end local ix, opts = numkeys+1,{} while type(arg[ix]) == "string" do if arg[ix] == "weights" then opts.weights = {} ix = ix + 1 for i=1, numkeys do opts.weights[i] = assert(toint(arg[ix])) ix = ix + 1 end elseif arg[ix] == "aggregate" then opts.aggregate = assert(chkarg(arg[ix+1])) ix = ix + 2 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.weights = opts.weights or _o.weights opts.aggregate = opts.aggregate or _o.aggregate ix = ix + 1 end assert(arg[ix] == nil) if opts.aggregate then assert( (opts.aggregate == "sum") or (opts.aggregate == "min") or (opts.aggregate == "max") ) else opts.aggregate = "sum" end if opts.weights then assert(#opts.weights == numkeys) for i=1,#opts.weights do assert(type(opts.weights[i]) == "number") end else opts.weights = {} for i=1, numkeys do opts.weights[i] = 1 end end opts.keys = ks opts.dest = dest return opts end local _zrbs_limits = function(x, s1, s2, descending) local s1_incl, s2_incl = true, true if s1:sub(1, 1) == "(" then s1, s1_incl = s1:sub(2, -1), false end s1 = assert(tofloat(s1)) if s2:sub(1, 1) == "(" then s2, s2_incl = s2:sub(2, -1), false end s2 = assert(tofloat(s2)) if descending then s1, s2 = s2, s1 s1_incl, s2_incl = s2_incl, s1_incl end if s2 < s1 then return nil end local l = x.list local i1, i2 local fst, lst = l[1].s, l[#l].s if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end for i=1,#l do if (i1 and i2) then break end if (not i1) then if l[i].s > s1 then i1 = i end if s1_incl and l[i].s == s1 then i1 = i end end if (not i2) then if l[i].s > s2 then i2 = i-1 end if (not s2_incl) and l[i].s == s2 then i2 = i-1 end end end assert(i1 and i2) if descending then return #l-i2, #l-i1 else return i1-1, i2-1 end end local dbg_zcoherence = function(self, k) local x = xgetr(self, k, "zset") return _z_coherence(x) end local zadd = function(self, k, ...) k = chkarg(k) local ps = _z_pairs(...) local x = xgetw(self, k, "zset") local n = 0 for i=1,#ps do if not _z_update(x, ps[i]) then n = n+1 end end return n end local zcard = function(self, k) local x = xgetr(self, k, "zset") return #x.list end local zcount = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return i2 - i1 + 1 end local zincrby = function(self, k, n, v) k,v = chkargs(2, k, v) n = assert(tofloat(n)) local x = xgetw(self, k, "zset") local p = x.list[x.set[v]] local s = p and (p.s + n) or n _z_update(x, _z_pair(s, v)) return s end local zinterstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local aggregate if params.aggregate == "sum" then aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then aggregate = math.min elseif params.aggregate == "max" then aggregate = math.max else error() end local y = xgetr(self, params.keys[1], "zset") local p1, p2 for j=1,#y.list do p1 = _z_pair(y.list[j].s, y.list[j].v) _z_update(x, p1) end for i=2,#params.keys do y = xgetr(self, params.keys[i], "zset") local to_remove, to_update = {}, {} for j=1,#x.list do p1 = x.list[j] if y.set[p1.v] then p2 = _z_pair( aggregate( p1.s, params.weights[i] * y.list[y.set[p1.v]].s ), p1.v ) to_update[#to_update+1] = p2 else to_remove[#to_remove+1] = p1.v end end for j=1,#to_remove do _z_remove(x, to_remove[j]) end for j=1,#to_update do _z_update(x, to_update[j]) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end local _zranger = function(descending) return function(self, k, i1, i2, opts) k = chkarg(k) local withscores = false if type(opts) == "table" then withscores = opts.withscores elseif type(opts) == "string" then assert(opts:lower() == "withscores") withscores = true else assert(opts == nil) end local x = xgetr(self, k, "zset") local l = x.list i1, i2 = _z_normrange(l, i1, i2) if not i1 then return {} end local inc = 1 if descending then i1 = #l - i1 + 1 i2 = #l - i2 + 1 inc = -1 end local r = {} if withscores then for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end else for i=i1, i2, inc do r[#r+1] = l[i].v end end return r end end local zrange = _zranger(false) local zrevrange = _zranger(true) local _zrangerbyscore = function(descending) return function(self, k, s1, s2, ...) k, s1, s2 = chkargs(3, k, s1, s2) local opts = _zrbs_opts(...) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, descending) if not (i1 and i2) then return {} end if opts.limit then if opts.limit.count == 0 then return {} end i1 = i1 + opts.limit.offset if i1 > i2 then return {} end i2 = math.min(i2, i1+opts.limit.count-1) end if descending then return zrevrange(self, k, i1, i2, opts) else return zrange(self, k, i1, i2, opts) end end end local zrangebyscore = _zrangerbyscore(false) local zrevrangebyscore = _zrangerbyscore(true) local zrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return r-1 else return nil end end local zrem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "zset"), 0 for i=1,#arg do if _z_remove(x, arg[i]) then r = r + 1 end end cleanup(self, k) return r end local zremrangebyrank = function(self, k, i1, i2) k = chkarg(k) local x = xgetw(self, k, "zset") i1, i2 = _z_normrange(x.list, i1, i2) if not i1 then cleanup(self, k) return 0 end local n = _z_remove_range(x, i1, i2) cleanup(self, k) return n end local zremrangebyscore = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return zremrangebyrank(self, k, i1, i2) end local zrevrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return #x.list-r else return nil end end local zscore = function(self, k, v) local x = xgetr(self, k, "zset") local p = x.list[x.set[v]] if p then return p.s else return nil end end local zunionstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local default_score, aggregate if params.aggregate == "sum" then default_score = 0 aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then default_score = math.huge aggregate = math.min elseif params.aggregate == "max" then default_score = -math.huge aggregate = math.max else error() end local y, p1, p2 for i=1,#params.keys do y = xgetr(self, params.keys[i], "zset") for j=1,#y.list do p1 = y.list[j] p2 = _z_pair( aggregate( params.weights[i] * p1.s, x.set[p1.v] and x.list[x.set[p1.v]].s or default_score ), p1.v ) _z_update(x, p2) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end -- connection local echo = function(self, v) return v end local ping = function(self) return true end -- server local flushdb = function(self) self.data = {} return true end --- Class local methods = { -- keys del = del, -- (...) -> #removed exists = chkargs_wrap(exists, 1), -- (k) -> exists? keys = keys, -- (pattern) -> list of keys ["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none] randomkey = randomkey, -- () -> [k|nil] rename = chkargs_wrap(rename, 2), -- (k,k2) -> true renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2 -- strings append = chkargs_wrap(append, 2), -- (k,v) -> #new bitcount = bitcount, -- (k,[start,end]) -> n bitop = bitop, -- ([and|or|xor|not],k,...) decr = chkargs_wrap(decr, 1), -- (k) -> new decrby = decrby, -- (k,n) -> new get = chkargs_wrap(get, 1), -- (k) -> [v|nil] getbit = getbit, -- (k,offset) -> b getrange = getrange, -- (k,start,end) -> string getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil] incr = chkargs_wrap(incr, 1), -- (k) -> new incrby = incrby, -- (k,n) -> new incrbyfloat = incrbyfloat, -- (k,n) -> new mget = mget, -- (k1,...) -> {v1,...} mset = mset, -- (k1,v1,...) -> true msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k) set = chkargs_wrap(set, 2), -- (k,v) -> true setbit = setbit, -- (k,offset,b) -> old setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?) setrange = setrange, -- (k,offset,val) -> #new strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0] -- hashes hdel = hdel, -- (k,sk1,...) -> #removed hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists? hget = chkargs_wrap(hget,2), -- (k,sk) -> v hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map hincrby = hincrby, -- (k,sk,n) -> new hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0] hmget = hmget, -- (k,{sk1,...}) -> {v1,...} hmset = hmset, -- (k,{sk1=v1,...}) -> true hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed? hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?) hvals = chkargs_wrap(hvals, 1), -- (k) -> values -- lists blpop = blpop, -- (k1,...) -> k,v brpop = brpop, -- (k1,...) -> k,v brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v lindex = lindex, -- (k,i) -> v linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after) llen = chkargs_wrap(llen, 1), -- (k) -> #list lpop = chkargs_wrap(lpop, 1), -- (k) -> v lpush = lpush, -- (k,v1,...) -> #list (after) lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after) lrange = lrange, -- (k,start,stop) -> list lrem = lrem, -- (k,count,v) -> #removed lset = lset, -- (k,i,v) -> true ltrim = ltrim, -- (k,start,stop) -> true rpop = chkargs_wrap(rpop, 1), -- (k) -> v rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v rpush = rpush, -- (k,v1,...) -> #list (after) rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after) -- sets sadd = sadd, -- (k,v1,...) -> #added scard = chkargs_wrap(scard, 1), -- (k) -> [n|0] sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...) sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0 sinter = sinter, -- (k1,...) -> set sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0 sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member? smembers = chkargs_wrap(smembers, 1), -- (k) -> set smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1) spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil] srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...] srem = srem, -- (k,v1,...) -> #removed sunion = sunion, -- (k1,...) -> set sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0 -- zsets zadd = zadd, -- (k,score,member,[score,member,...]) zcard = chkargs_wrap(zcard, 1), -- (k) -> n zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count zincrby = zincrby, -- (k,score,v) -> score zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank zrem = zrem, -- (k,v1,...) -> #removed zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card -- connection echo = chkargs_wrap(echo, 1), -- (v) -> v ping = ping, -- () -> true -- server flushall = flushdb, -- () -> true flushdb = flushdb, -- () -> true -- debug dbg_zcoherence = dbg_zcoherence, } local new = function() local r = {data = {}} return setmetatable(r,{__index = methods}) end return { new = new, }
gpl-3.0
tsharly/TSHARLY
libs/fakeredis.lua
650
40405
local unpack = table.unpack or unpack --- Bit operations local ok,bit if _VERSION == "Lua 5.3" then bit = (load [[ return { band = function(x, y) return x & y end, bor = function(x, y) return x | y end, bxor = function(x, y) return x ~ y end, bnot = function(x) return ~x end, rshift = function(x, n) return x >> n end, lshift = function(x, n) return x << n end, } ]])() else ok,bit = pcall(require,"bit") if not ok then bit = bit32 end end assert(type(bit) == "table", "module for bitops not found") --- default sleep local default_sleep do local ok, mod = pcall(require, "socket") if ok and type(mod) == "table" then default_sleep = mod.sleep else default_sleep = function(n) local t0 = os.clock() while true do local delta = os.clock() - t0 if (delta < 0) or (delta > n) then break end end end end end --- Helpers local xdefv = function(ktype) if ktype == "list" then return {head = 0, tail = 0} elseif ktype == "zset" then return { list = {}, set = {}, } else return {} end end local xgetr = function(self, k, ktype) if self.data[k] then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) assert(self.data[k].value) return self.data[k].value else return xdefv(ktype) end end local xgetw = function(self, k, ktype) if self.data[k] and self.data[k].value then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) else self.data[k] = {ktype = ktype, value = xdefv(ktype)} end return self.data[k].value end local empty = function(self, k) local v, t = self.data[k].value, self.data[k].ktype if t == nil then return true elseif t == "string" then return not v[1] elseif (t == "hash") or (t == "set") then for _,_ in pairs(v) do return false end return true elseif t == "list" then return v.head == v.tail elseif t == "zset" then if #v.list == 0 then for _,_ in pairs(v.set) do error("incoherent") end return true else for _,_ in pairs(v.set) do return(false) end error("incoherent") end else error("unsupported") end end local cleanup = function(self, k) if empty(self, k) then self.data[k] = nil end end local is_integer = function(x) return (type(x) == "number") and (math.floor(x) == x) end local overflows = function(n) return (n > 2^53-1) or (n < -2^53+1) end local is_bounded_integer = function(x) return (is_integer(x) and (not overflows(x))) end local is_finite_number = function(x) return (type(x) == "number") and (x > -math.huge) and (x < math.huge) end local toint = function(x) if type(x) == "string" then x = tonumber(x) end return is_bounded_integer(x) and x or nil end local tofloat = function(x) if type(x) == "number" then return x end if type(x) ~= "string" then return nil end local r = tonumber(x) if r then return r end if x == "inf" or x == "+inf" then return math.huge elseif x == "-inf" then return -math.huge else return nil end end local tostr = function(x) if is_bounded_integer(x) then return string.format("%d", x) else return tostring(x) end end local char_bitcount = function(x) assert( (type(x) == "number") and (math.floor(x) == x) and (x >= 0) and (x < 256) ) local n = 0 while x ~= 0 do x = bit.band(x, x-1) n = n+1 end return n end local chkarg = function(x) if type(x) == "number" then x = tostr(x) end assert(type(x) == "string") return x end local chkargs = function(n, ...) local arg = {...} assert(#arg == n) for i=1,n do arg[i] = chkarg(arg[i]) end return unpack(arg) end local getargs = function(...) local arg = {...} local n = #arg; assert(n > 0) for i=1,n do arg[i] = chkarg(arg[i]) end return arg end local getargs_as_map = function(...) local arg, r = getargs(...), {} assert(#arg%2 == 0) for i=1,#arg,2 do r[arg[i]] = arg[i+1] end return r end local chkargs_wrap = function(f, n) assert( (type(f) == "function") and (type(n) == "number") ) return function(self, ...) return f(self, chkargs(n, ...)) end end local lset_to_list = function(s) local r = {} for v,_ in pairs(s) do r[#r+1] = v end return r end local nkeys = function(x) local r = 0 for _,_ in pairs(x) do r = r + 1 end return r end --- Commands -- keys local del = function(self, ...) local arg = getargs(...) local r = 0 for i=1,#arg do if self.data[arg[i]] then r = r + 1 end self.data[arg[i]] = nil end return r end local exists = function(self, k) return not not self.data[k] end local keys = function(self, pattern) assert(type(pattern) == "string") -- We want to convert the Redis pattern to a Lua pattern. -- Start by escaping dashes *outside* character classes. -- We also need to escape percents here. local t, p, n = {}, 1, #pattern local p1, p2 while true do p1, p2 = pattern:find("%[.+%]", p) if p1 then if p1 > p then t[#t+1] = {true, pattern:sub(p, p1-1)} end t[#t+1] = {false, pattern:sub(p1, p2)} p = p2+1 if p > n then break end else t[#t+1] = {true, pattern:sub(p, n)} break end end for i=1,#t do if t[i][1] then t[i] = t[i][2]:gsub("[%%%-]", "%%%0") else t[i] = t[i][2]:gsub("%%", "%%%%") end end -- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]' -- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is. -- Wrap in '^$' to enforce bounds. local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0") :gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$" local r = {} for k,_ in pairs(self.data) do if k:match(lp) then r[#r+1] = k end end return r end local _type = function(self, k) return self.data[k] and self.data[k].ktype or "none" end local randomkey = function(self) local ks = lset_to_list(self.data) local n = #ks if n > 0 then return ks[math.random(1, n)] else return nil end end local rename = function(self, k, k2) assert((k ~= k2) and self.data[k]) self.data[k2] = self.data[k] self.data[k] = nil return true end local renamenx = function(self, k, k2) if self.data[k2] then return false else return rename(self, k, k2) end end -- strings local getrange, incrby, set local append = function(self, k, v) local x = xgetw(self, k, "string") x[1] = (x[1] or "") .. v return #x[1] end local bitcount = function(self, k, i1, i2) k = chkarg(k) local s if i1 or i2 then assert(i1 and i2, "ERR syntax error") s = getrange(self, k, i1, i2) else s = xgetr(self, k, "string")[1] or "" end local r, bytes = 0,{s:byte(1, -1)} for i=1,#bytes do r = r + char_bitcount(bytes[i]) end return r end local bitop = function(self, op, k, ...) assert(type(op) == "string") op = op:lower() assert( (op == "and") or (op == "or") or (op == "xor") or (op == "not"), "ERR syntax error" ) k = chkarg(k) local arg = {...} local good_arity = (op == "not") and (#arg == 1) or (#arg > 0) assert(good_arity, "ERR wrong number of arguments for 'bitop' command") local l, vals = 0, {} local s for i=1,#arg do s = xgetr(self, arg[i], "string")[1] or "" if #s > l then l = #s end vals[i] = s end if l == 0 then del(self, k) return 0 end local vector_mt = {__index=function() return 0 end} for i=1,#vals do vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt) end local r = {} if op == "not" then assert(#vals[1] == l) for i=1,l do r[i] = bit.band(bit.bnot(vals[1][i]), 0xff) end else local _op = bit["b" .. op] for i=1,l do local t = {} for j=1,#vals do t[j] = vals[j][i] end r[i] = _op(unpack(t)) end end set(self, k, string.char(unpack(r))) return l end local decr = function(self, k) return incrby(self, k, -1) end local decrby = function(self, k, n) n = toint(n) assert(n, "ERR value is not an integer or out of range") return incrby(self, k, -n) end local get = function(self, k) local x = xgetr(self, k, "string") return x[1] end local getbit = function(self, k, offset) k = chkarg(k) offset = toint(offset) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" if bytepos >= #s then return 0 end local char = s:sub(bytepos+1, bytepos+1):byte() return bit.band(bit.rshift(char, 7-bitpos), 1) end getrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetr(self, k, "string") x = x[1] or "" if i1 >= 0 then i1 = i1 + 1 end if i2 >= 0 then i2 = i2 + 1 end return x:sub(i1, i2) end local getset = function(self, k, v) local r = get(self, k) set(self, k, v) return r end local incr = function(self, k) return incrby(self, k, 1) end incrby = function(self, k, n) k, n = chkarg(k), toint(n) assert(n, "ERR value is not an integer or out of range") local x = xgetw(self, k, "string") local i = toint(x[1] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[1] = tostr(i) return i end local incrbyfloat = function(self, k, n) k, n = chkarg(k), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "string") local i = tofloat(x[1] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[1] = tostr(i) return i end local mget = function(self, ...) local arg, r = getargs(...), {} for i=1,#arg do r[i] = get(self, arg[i]) end return r end local mset = function(self, ...) local argmap = getargs_as_map(...) for k,v in pairs(argmap) do set(self, k, v) end return true end local msetnx = function(self, ...) local argmap = getargs_as_map(...) for k,_ in pairs(argmap) do if self.data[k] then return false end end for k,v in pairs(argmap) do set(self, k, v) end return true end set = function(self, k, v) self.data[k] = {ktype = "string", value = {v}} return true end local setbit = function(self, k, offset, b) k = chkarg(k) offset, b = toint(offset), toint(b) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) assert( (b == 0) or (b == 1), "ERR bit is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" local pad = {s} for i=2,bytepos+2-#s do pad[i] = "\0" end s = table.concat(pad) assert(#s >= bytepos+1) local before = s:sub(1, bytepos) local char = s:sub(bytepos+1, bytepos+1):byte() local after = s:sub(bytepos+2, -1) local old = bit.band(bit.rshift(char, 7-bitpos), 1) if b == 1 then char = bit.bor(bit.lshift(1, 7-bitpos), char) else char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char) end local r = before .. string.char(char) .. after set(self, k, r) return old end local setnx = function(self, k, v) if self.data[k] then return false else return set(self, k, v) end end local setrange = function(self, k, i, s) local k, s = chkargs(2, k, s) i = toint(i) assert(i and (i >= 0)) local x = xgetw(self, k, "string") local y = x[1] or "" local ly, ls = #y, #s if i > ly then -- zero padding local t = {} for i=1, i-ly do t[i] = "\0" end y = y .. table.concat(t) .. s else y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly) end x[1] = y return #y end local strlen = function(self, k) local x = xgetr(self, k, "string") return x[1] and #x[1] or 0 end -- hashes local hdel = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local r = 0 local x = xgetw(self, k, "hash") for i=1,#arg do if x[arg[i]] then r = r + 1 end x[arg[i]] = nil end cleanup(self, k) return r end local hget local hexists = function(self, k, k2) return not not hget(self, k, k2) end hget = function(self, k, k2) local x = xgetr(self, k, "hash") return x[k2] end local hgetall = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,v in pairs(x) do r[_k] = v end return r end local hincrby = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), toint(n) assert(n, "ERR value is not an integer or out of range") assert(type(n) == "number") local x = xgetw(self, k, "hash") local i = toint(x[k2] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[k2] = tostr(i) return i end local hincrbyfloat = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "hash") local i = tofloat(x[k2] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[k2] = tostr(i) return i end local hkeys = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,_ in pairs(x) do r[#r+1] = _k end return r end local hlen = function(self, k) local x = xgetr(self, k, "hash") return nkeys(x) end local hmget = function(self, k, k2s) k = chkarg(k) assert((type(k2s) == "table")) local r = {} local x = xgetr(self, k, "hash") for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end return r end local hmset = function(self, k, ...) k = chkarg(k) local arg = {...} if type(arg[1]) == "table" then assert(#arg == 1) local x = xgetw(self, k, "hash") for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end else assert(#arg % 2 == 0) local x = xgetw(self, k, "hash") local t = getargs(...) for i=1,#t,2 do x[t[i]] = t[i+1] end end return true end local hset = function(self, k, k2, v) local x = xgetw(self, k, "hash") local r = not x[k2] x[k2] = v return r end local hsetnx = function(self, k, k2, v) local x = xgetw(self, k, "hash") if x[k2] == nil then x[k2] = v return true else return false end end local hvals = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _,v in pairs(x) do r[#r+1] = v end return r end -- lists (head = left, tail = right) local _l_real_i = function(x, i) if i < 0 then return x.tail+i+1 else return x.head+i+1 end end local _l_len = function(x) return x.tail - x.head end local _block_for = function(self, timeout) if timeout > 0 then local sleep = self.sleep or default_sleep if type(sleep) == "function" then sleep(timeout) else error("sleep function unavailable", 0) end else error("operation would block", 0) end end local rpoplpush local blpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpoplpush = function(self, k1, k2, timeout) k1, k2 = chkargs(2, k1, k2) timeout = toint(timeout) if not self.data[k1] then _block_for(self, timeout) end return rpoplpush(self, k1, k2) end local lindex = function(self, k, i) k = chkarg(k) i = assert(toint(i)) local x = xgetr(self, k, "list") return x[_l_real_i(x, i)] end local linsert = function(self, k, mode, pivot, v) mode = mode:lower() assert((mode == "before") or (mode == "after")) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local p = nil for i=x.head+1, x.tail do if x[i] == pivot then p = i break end end if not p then return -1 end if mode == "after" then for i=x.head+1, p do x[i-1] = x[i] end x.head = x.head - 1 else for i=x.tail, p, -1 do x[i+1] = x[i] end x.tail = x.tail + 1 end x[p] = v return _l_len(x) end local llen = function(self, k) local x = xgetr(self, k, "list") return _l_len(x) end local lpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return r end local lpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x[x.head] = vs[i] x.head = x.head - 1 end return _l_len(x) end local lpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x[x.head] = v x.head = x.head - 1 return _l_len(x) end local lrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x, r = xgetr(self, k, "list"), {} i1 = math.max(_l_real_i(x, i1), x.head+1) i2 = math.min(_l_real_i(x, i2), x.tail) for i=i1,i2 do r[#r+1] = x[i] end return r end local _lrem_i = function(x, p) for i=p,x.tail do x[i] = x[i+1] end x.tail = x.tail - 1 end local _lrem_l = function(x, v, s) assert(v) if not s then s = x.head+1 end for i=s,x.tail do if x[i] == v then _lrem_i(x, i) return i end end return false end local _lrem_r = function(x, v, s) assert(v) if not s then s = x.tail end for i=s,x.head+1,-1 do if x[i] == v then _lrem_i(x, i) return i end end return false end local lrem = function(self, k, count, v) k, v = chkarg(k), chkarg(v) count = assert(toint(count)) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local n, last = 0, nil local op = (count < 0) and _lrem_r or _lrem_l local limited = (count ~= 0) count = math.abs(count) while true do last = op(x, v, last) if last then n = n+1 if limited then count = count - 1 if count == 0 then break end end else break end end return n end local lset = function(self, k, i, v) k, v = chkarg(k), chkarg(v) i = assert(toint(i)) if not self.data[k] then error("ERR no such key") end local x = xgetw(self, k, "list") local l = _l_len(x) if i >= l or i < -l then error("ERR index out of range") end x[_l_real_i(x, i)] = v return true end local ltrim = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetw(self, k, "list") i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2) for i=x.head+1,i1-1 do x[i] = nil end for i=i2+1,x.tail do x[i] = nil end x.head = math.max(i1-1, x.head) x.tail = math.min(i2, x.tail) assert( (x[x.head] == nil) and (x[x.tail+1] == nil) ) cleanup(self, k) return true end local rpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return r end rpoplpush = function(self, k1, k2) local v = rpop(self, k1) if not v then return nil end lpush(self, k2, v) return v end local rpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x.tail = x.tail + 1 x[x.tail] = vs[i] end return _l_len(x) end local rpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x.tail = x.tail + 1 x[x.tail] = v return _l_len(x) end -- sets local sadd = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if not x[arg[i]] then x[arg[i]] = true r = r + 1 end end return r end local scard = function(self, k) local x = xgetr(self, k, "set") return nkeys(x) end local _sdiff = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} for v,_ in pairs(x) do r[v] = true end for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = nil end end return r end local sdiff = function(self, k, ...) return lset_to_list(_sdiff(self, k, ...)) end local sdiffstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sdiff(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local _sinter = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} local y for v,_ in pairs(x) do r[v] = true for i=1,#arg do y = xgetr(self, arg[i], "set") if not y[v] then r[v] = nil; break end end end return r end local sinter = function(self, k, ...) return lset_to_list(_sinter(self, k, ...)) end local sinterstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sinter(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local sismember = function(self, k, v) local x = xgetr(self, k, "set") return not not x[v] end local smembers = function(self, k) local x = xgetr(self, k, "set") return lset_to_list(x) end local smove = function(self, k, k2, v) local x = xgetr(self, k, "set") if x[v] then local y = xgetw(self, k2, "set") x[v] = nil y[v] = true return true else return false end end local spop = function(self, k) local x, r = xgetw(self, k, "set"), nil local l = lset_to_list(x) local n = #l if n > 0 then r = l[math.random(1, n)] x[r] = nil end cleanup(self, k) return r end local srandmember = function(self, k, count) k = chkarg(k) local x = xgetr(self, k, "set") local l = lset_to_list(x) local n = #l if not count then if n > 0 then return l[math.random(1, n)] else return nil end end count = toint(count) if (count == 0) or (n == 0) then return {} end if count >= n then return l end local r = {} if count > 0 then -- distinct elements for i=0,count-1 do r[#r+1] = table.remove(l, math.random(1, n-i)) end else -- allow repetition for i=1,-count do r[#r+1] = l[math.random(1, n)] end end return r end local srem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if x[arg[i]] then x[arg[i]] = nil r = r + 1 end end cleanup(self, k) return r end local _sunion = function(self, ...) local arg = getargs(...) local r = {} local x for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = true end end return r end local sunion = function(self, k, ...) return lset_to_list(_sunion(self, k, ...)) end local sunionstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sunion(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end -- zsets local _z_p_mt = { __eq = function(a, b) if a.v == b.v then assert(a.s == b.s) return true else return false end end, __lt = function(a, b) if a.s == b.s then return (a.v < b.v) else return (a.s < b.s) end end, } local _z_pair = function(s, v) assert( (type(s) == "number") and (type(v) == "string") ) local r = {s = s, v = v} return setmetatable(r, _z_p_mt) end local _z_pairs = function(...) local arg = {...} assert((#arg > 0) and (#arg % 2 == 0)) local ps = {} for i=1,#arg,2 do ps[#ps+1] = _z_pair( assert(tofloat(arg[i])), chkarg(arg[i+1]) ) end return ps end local _z_insert = function(x, ix, p) assert( (type(x) == "table") and (type(ix) == "number") and (type(p) == "table") ) local l = x.list table.insert(l, ix, p) for i=ix+1,#l do x.set[l[i].v] = x.set[l[i].v] + 1 end x.set[p.v] = ix end local _z_remove = function(x, v) if not x.set[v] then return false end local l, ix = x.list, x.set[v] assert(l[ix].v == v) table.remove(l, ix) for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - 1 end x.set[v] = nil return true end local _z_remove_range = function(x, i1, i2) local l = x.list i2 = i2 or i1 assert( (i1 > 0) and (i2 >= i1) and (i2 <= #l) ) local ix, n = i1, i2-i1+1 for i=1,n do x.set[l[ix].v] = nil table.remove(l, ix) end for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - n end return n end local _z_update = function(x, p) local l = x.list local found = _z_remove(x, p.v) local ix = nil for i=1,#l do if l[i] > p then ix = i; break end end if not ix then ix = #l+1 end _z_insert(x, ix, p) return found end local _z_coherence = function(x) local l, s = x.list, x.set local found, n = {}, 0 for val,pos in pairs(s) do if found[pos] then return false end found[pos] = true n = n + 1 if not (l[pos] and (l[pos].v == val)) then return false end end if #l ~= n then return false end for i=1, n-1 do if l[i].s > l[i+1].s then return false end end return true end local _z_normrange = function(l, i1, i2) i1, i2 = assert(toint(i1)), assert(toint(i2)) if i1 < 0 then i1 = #l+i1 end if i2 < 0 then i2 = #l+i2 end i1, i2 = math.max(i1+1, 1), i2+1 if (i2 < i1) or (i1 > #l) then return nil end i2 = math.min(i2, #l) return i1, i2 end local _zrbs_opts = function(...) local arg = {...} if #arg == 0 then return {} end local ix, opts = 1, {} while type(arg[ix]) == "string" do if arg[ix] == "withscores" then opts.withscores = true ix = ix + 1 elseif arg[ix] == "limit" then opts.limit = { offset = assert(toint(arg[ix+1])), count = assert(toint(arg[ix+2])), } ix = ix + 3 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.withscores = opts.withscores or _o.withscores if _o.limit then opts.limit = { offset = assert(toint(_o.limit.offset or _o.limit[1])), count = assert(toint(_o.limit.count or _o.limit[2])), } end ix = ix + 1 end assert(arg[ix] == nil) if opts.limit then assert( (opts.limit.count >= 0) and (opts.limit.offset >= 0) ) end return opts end local _z_store_params = function(dest, numkeys, ...) dest = chkarg(dest) numkeys = assert(toint(numkeys)) assert(numkeys > 0) local arg = {...} assert(#arg >= numkeys) local ks = {} for i=1, numkeys do ks[i] = chkarg(arg[i]) end local ix, opts = numkeys+1,{} while type(arg[ix]) == "string" do if arg[ix] == "weights" then opts.weights = {} ix = ix + 1 for i=1, numkeys do opts.weights[i] = assert(toint(arg[ix])) ix = ix + 1 end elseif arg[ix] == "aggregate" then opts.aggregate = assert(chkarg(arg[ix+1])) ix = ix + 2 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.weights = opts.weights or _o.weights opts.aggregate = opts.aggregate or _o.aggregate ix = ix + 1 end assert(arg[ix] == nil) if opts.aggregate then assert( (opts.aggregate == "sum") or (opts.aggregate == "min") or (opts.aggregate == "max") ) else opts.aggregate = "sum" end if opts.weights then assert(#opts.weights == numkeys) for i=1,#opts.weights do assert(type(opts.weights[i]) == "number") end else opts.weights = {} for i=1, numkeys do opts.weights[i] = 1 end end opts.keys = ks opts.dest = dest return opts end local _zrbs_limits = function(x, s1, s2, descending) local s1_incl, s2_incl = true, true if s1:sub(1, 1) == "(" then s1, s1_incl = s1:sub(2, -1), false end s1 = assert(tofloat(s1)) if s2:sub(1, 1) == "(" then s2, s2_incl = s2:sub(2, -1), false end s2 = assert(tofloat(s2)) if descending then s1, s2 = s2, s1 s1_incl, s2_incl = s2_incl, s1_incl end if s2 < s1 then return nil end local l = x.list local i1, i2 local fst, lst = l[1].s, l[#l].s if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end for i=1,#l do if (i1 and i2) then break end if (not i1) then if l[i].s > s1 then i1 = i end if s1_incl and l[i].s == s1 then i1 = i end end if (not i2) then if l[i].s > s2 then i2 = i-1 end if (not s2_incl) and l[i].s == s2 then i2 = i-1 end end end assert(i1 and i2) if descending then return #l-i2, #l-i1 else return i1-1, i2-1 end end local dbg_zcoherence = function(self, k) local x = xgetr(self, k, "zset") return _z_coherence(x) end local zadd = function(self, k, ...) k = chkarg(k) local ps = _z_pairs(...) local x = xgetw(self, k, "zset") local n = 0 for i=1,#ps do if not _z_update(x, ps[i]) then n = n+1 end end return n end local zcard = function(self, k) local x = xgetr(self, k, "zset") return #x.list end local zcount = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return i2 - i1 + 1 end local zincrby = function(self, k, n, v) k,v = chkargs(2, k, v) n = assert(tofloat(n)) local x = xgetw(self, k, "zset") local p = x.list[x.set[v]] local s = p and (p.s + n) or n _z_update(x, _z_pair(s, v)) return s end local zinterstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local aggregate if params.aggregate == "sum" then aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then aggregate = math.min elseif params.aggregate == "max" then aggregate = math.max else error() end local y = xgetr(self, params.keys[1], "zset") local p1, p2 for j=1,#y.list do p1 = _z_pair(y.list[j].s, y.list[j].v) _z_update(x, p1) end for i=2,#params.keys do y = xgetr(self, params.keys[i], "zset") local to_remove, to_update = {}, {} for j=1,#x.list do p1 = x.list[j] if y.set[p1.v] then p2 = _z_pair( aggregate( p1.s, params.weights[i] * y.list[y.set[p1.v]].s ), p1.v ) to_update[#to_update+1] = p2 else to_remove[#to_remove+1] = p1.v end end for j=1,#to_remove do _z_remove(x, to_remove[j]) end for j=1,#to_update do _z_update(x, to_update[j]) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end local _zranger = function(descending) return function(self, k, i1, i2, opts) k = chkarg(k) local withscores = false if type(opts) == "table" then withscores = opts.withscores elseif type(opts) == "string" then assert(opts:lower() == "withscores") withscores = true else assert(opts == nil) end local x = xgetr(self, k, "zset") local l = x.list i1, i2 = _z_normrange(l, i1, i2) if not i1 then return {} end local inc = 1 if descending then i1 = #l - i1 + 1 i2 = #l - i2 + 1 inc = -1 end local r = {} if withscores then for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end else for i=i1, i2, inc do r[#r+1] = l[i].v end end return r end end local zrange = _zranger(false) local zrevrange = _zranger(true) local _zrangerbyscore = function(descending) return function(self, k, s1, s2, ...) k, s1, s2 = chkargs(3, k, s1, s2) local opts = _zrbs_opts(...) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, descending) if not (i1 and i2) then return {} end if opts.limit then if opts.limit.count == 0 then return {} end i1 = i1 + opts.limit.offset if i1 > i2 then return {} end i2 = math.min(i2, i1+opts.limit.count-1) end if descending then return zrevrange(self, k, i1, i2, opts) else return zrange(self, k, i1, i2, opts) end end end local zrangebyscore = _zrangerbyscore(false) local zrevrangebyscore = _zrangerbyscore(true) local zrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return r-1 else return nil end end local zrem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "zset"), 0 for i=1,#arg do if _z_remove(x, arg[i]) then r = r + 1 end end cleanup(self, k) return r end local zremrangebyrank = function(self, k, i1, i2) k = chkarg(k) local x = xgetw(self, k, "zset") i1, i2 = _z_normrange(x.list, i1, i2) if not i1 then cleanup(self, k) return 0 end local n = _z_remove_range(x, i1, i2) cleanup(self, k) return n end local zremrangebyscore = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return zremrangebyrank(self, k, i1, i2) end local zrevrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return #x.list-r else return nil end end local zscore = function(self, k, v) local x = xgetr(self, k, "zset") local p = x.list[x.set[v]] if p then return p.s else return nil end end local zunionstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local default_score, aggregate if params.aggregate == "sum" then default_score = 0 aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then default_score = math.huge aggregate = math.min elseif params.aggregate == "max" then default_score = -math.huge aggregate = math.max else error() end local y, p1, p2 for i=1,#params.keys do y = xgetr(self, params.keys[i], "zset") for j=1,#y.list do p1 = y.list[j] p2 = _z_pair( aggregate( params.weights[i] * p1.s, x.set[p1.v] and x.list[x.set[p1.v]].s or default_score ), p1.v ) _z_update(x, p2) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end -- connection local echo = function(self, v) return v end local ping = function(self) return true end -- server local flushdb = function(self) self.data = {} return true end --- Class local methods = { -- keys del = del, -- (...) -> #removed exists = chkargs_wrap(exists, 1), -- (k) -> exists? keys = keys, -- (pattern) -> list of keys ["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none] randomkey = randomkey, -- () -> [k|nil] rename = chkargs_wrap(rename, 2), -- (k,k2) -> true renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2 -- strings append = chkargs_wrap(append, 2), -- (k,v) -> #new bitcount = bitcount, -- (k,[start,end]) -> n bitop = bitop, -- ([and|or|xor|not],k,...) decr = chkargs_wrap(decr, 1), -- (k) -> new decrby = decrby, -- (k,n) -> new get = chkargs_wrap(get, 1), -- (k) -> [v|nil] getbit = getbit, -- (k,offset) -> b getrange = getrange, -- (k,start,end) -> string getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil] incr = chkargs_wrap(incr, 1), -- (k) -> new incrby = incrby, -- (k,n) -> new incrbyfloat = incrbyfloat, -- (k,n) -> new mget = mget, -- (k1,...) -> {v1,...} mset = mset, -- (k1,v1,...) -> true msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k) set = chkargs_wrap(set, 2), -- (k,v) -> true setbit = setbit, -- (k,offset,b) -> old setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?) setrange = setrange, -- (k,offset,val) -> #new strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0] -- hashes hdel = hdel, -- (k,sk1,...) -> #removed hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists? hget = chkargs_wrap(hget,2), -- (k,sk) -> v hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map hincrby = hincrby, -- (k,sk,n) -> new hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0] hmget = hmget, -- (k,{sk1,...}) -> {v1,...} hmset = hmset, -- (k,{sk1=v1,...}) -> true hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed? hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?) hvals = chkargs_wrap(hvals, 1), -- (k) -> values -- lists blpop = blpop, -- (k1,...) -> k,v brpop = brpop, -- (k1,...) -> k,v brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v lindex = lindex, -- (k,i) -> v linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after) llen = chkargs_wrap(llen, 1), -- (k) -> #list lpop = chkargs_wrap(lpop, 1), -- (k) -> v lpush = lpush, -- (k,v1,...) -> #list (after) lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after) lrange = lrange, -- (k,start,stop) -> list lrem = lrem, -- (k,count,v) -> #removed lset = lset, -- (k,i,v) -> true ltrim = ltrim, -- (k,start,stop) -> true rpop = chkargs_wrap(rpop, 1), -- (k) -> v rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v rpush = rpush, -- (k,v1,...) -> #list (after) rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after) -- sets sadd = sadd, -- (k,v1,...) -> #added scard = chkargs_wrap(scard, 1), -- (k) -> [n|0] sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...) sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0 sinter = sinter, -- (k1,...) -> set sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0 sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member? smembers = chkargs_wrap(smembers, 1), -- (k) -> set smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1) spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil] srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...] srem = srem, -- (k,v1,...) -> #removed sunion = sunion, -- (k1,...) -> set sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0 -- zsets zadd = zadd, -- (k,score,member,[score,member,...]) zcard = chkargs_wrap(zcard, 1), -- (k) -> n zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count zincrby = zincrby, -- (k,score,v) -> score zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank zrem = zrem, -- (k,v1,...) -> #removed zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card -- connection echo = chkargs_wrap(echo, 1), -- (v) -> v ping = ping, -- () -> true -- server flushall = flushdb, -- () -> true flushdb = flushdb, -- () -> true -- debug dbg_zcoherence = dbg_zcoherence, } local new = function() local r = {data = {}} return setmetatable(r,{__index = methods}) end return { new = new, }
gpl-2.0
chelog/brawl
addons/brawl-weapons/lua/cw/client/cw_hud.lua
1
1033
CustomizableWeaponry.ITEM_PACKS_TOP_COLOR = Color(0, 200, 255, 255) local noDraw = {CHudAmmo = true, CHudSecondaryAmmo = true, CHudHealth = true, CHudBattery = true} local noDrawAmmo = {CHudAmmo = true, CHudSecondaryAmmo = true} local wep, ply local function CW_HUDShouldDraw(n) local customHud = GetConVarNumber("cw_customhud") >= 1 local customAmmo = GetConVarNumber("cw_customhud_ammo") >= 1 if customAmmo or customHud then ply = LocalPlayer() if IsValid(ply) and ply:Alive() then wep = ply:GetActiveWeapon() end else ply, wep = nil, nil end if customAmmo then if IsValid(ply) and ply:Alive() then if IsValid(wep) and wep.CW20Weapon then if noDrawAmmo[n] then return false end end end end if customHud then if IsValid(ply) and ply:Alive() then if IsValid(wep) and wep.CW20Weapon then if noDraw[n] then return false end end end end end hook.Add("HUDShouldDraw", "CW_HUDShouldDraw", CW_HUDShouldDraw)
gpl-3.0
LaFamiglia/Illarion-Content
monster/base/spells/heal.lua
1
5407
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local function _isNumber(value) return type(value) == "number" end local function _isTable(value) return type(value) == "table" end return function(params) local self = {} local healAtOnce = 1 local healRange = {1000, 2000} local probability = 0.03 local gfxId = 16 local sfxId = 0 local usedMovepoints = 20 if _isTable(params) then if params.probability ~= nil then if _isNumber(params.probability) then probability = tonumber(params.probability) if (probability <= 0) or (probability > 1) then error("The probability for the spell is set to a illegal value.") end else error("The probability for the spell was set to something, but not to a number.") end end if params.hp ~= nil then if _isNumber(params.hp) then local hp = tonumber(params.hp) healRange = {hp, hp } elseif _isTable(params.hp) then local fromValue = params.hp.from or params.hp[1] local toValue = params.hp.to or params.hp[2] if _isNumber(fromValue) and _isNumber(toValue) then healRange = {tonumber(fromValue), tonumber(toValue) } if healRange[1] > healRange[2] then error("Range for healed hitpoint was set but the from value is greater than the to value.") end else error("The healed hitpoints value was detected as table. How ever the from and to value for the " + "range is missing.") end else error("The healed hitpoints was set to something. How ever it was not possible to detect what the input means.") end end if params.targetCount ~= nil then if _isNumber(params.targetCount) then healAtOnce = tonumber(params.targetCount) if healAtOnce < 1 then error("The amount of targets for the healing spell was set to less then 1") end else error("The amount of targets for the spell was set to something, but not to a number.") end end if params.gfxId ~= nil then if _isNumber(params.gfxId) then gfxId = tonumber(params.gfxId) else error("The gfx id for the spell was set to something, but not to a number.") end end if params.sfxId ~= nil then if _isNumber(params.sfxId) then sfxId = tonumber(params.sfxId) else error("The sound effect id for the spell was set to something, but not to a number.") end end if params.movepoints ~= nil then if _isNumber(params.movepoints) then usedMovepoints = tonumber(params.movepoints) else error("The required move points for the spell was set to something, but not to a number.") end end end function self.getAttackRange() return 0 end function self.cast(monster, enemy) if Random.uniform() <= probability then -- Look for my friends local otherMonsters = world:getMonstersInRangeOf(monster.pos, 8) if #otherMonsters == 0 then return false end -- Scan Monsters and select wounded local woundedMonsters = {} for _, checkMonster in pairs(otherMonsters) do if (checkMonster:increaseAttrib("hitpoints", 0) < 10000) then table.insert(woundedMonsters, checkMonster) end end local performedSpell = false for _ = 1, healAtOnce do if #woundedMonsters == 0 then return performedSpell end -- Select monster to help local selectedMonsterIndex = Random.uniform(1, #woundedMonsters) local selectedMonster = woundedMonsters[selectedMonsterIndex] table.remove(woundedMonsters, selectedMonsterIndex) selectedMonster:increaseAttrib("hitpoints", Random.uniform(healRange[1], healRange[2])) if gfxId > 0 then world:gfx(gfxId, selectedMonster.pos) end if sfxId > 0 then world:makeSound(sfxId, selectedMonster.pos) end monster.movepoints = monster.movepoints - usedMovepoints; performedSpell = true end return performedSpell end return false end return self end
agpl-3.0